repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
edx/i18n-tools
i18n/transifex.py
pull_all_rtl
def pull_all_rtl(configuration): """ Pulls all translations - reviewed or not - for RTL languages """ print("Pulling all translated RTL languages from transifex...") for lang in configuration.rtl_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) execute('tx pull -l ' + lang) clean_translated_locales(configuration, langs=configuration.rtl_langs)
python
def pull_all_rtl(configuration): print("Pulling all translated RTL languages from transifex...") for lang in configuration.rtl_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) execute('tx pull -l ' + lang) clean_translated_locales(configuration, langs=configuration.rtl_langs)
[ "def", "pull_all_rtl", "(", "configuration", ")", ":", "print", "(", "\"Pulling all translated RTL languages from transifex...\"", ")", "for", "lang", "in", "configuration", ".", "rtl_langs", ":", "print", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "(", "'tx pull -l '", "+", "lang", ")", "clean_translated_locales", "(", "configuration", ",", "langs", "=", "configuration", ".", "rtl_langs", ")" ]
Pulls all translations - reviewed or not - for RTL languages
[ "Pulls", "all", "translations", "-", "reviewed", "or", "not", "-", "for", "RTL", "languages" ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L91-L100
edx/i18n-tools
i18n/transifex.py
clean_translated_locales
def clean_translated_locales(configuration, langs=None): """ Strips out the warning from all translated po files about being an English source file. """ if not langs: langs = configuration.translated_locales for locale in langs: clean_locale(configuration, locale)
python
def clean_translated_locales(configuration, langs=None): if not langs: langs = configuration.translated_locales for locale in langs: clean_locale(configuration, locale)
[ "def", "clean_translated_locales", "(", "configuration", ",", "langs", "=", "None", ")", ":", "if", "not", "langs", ":", "langs", "=", "configuration", ".", "translated_locales", "for", "locale", "in", "langs", ":", "clean_locale", "(", "configuration", ",", "locale", ")" ]
Strips out the warning from all translated po files about being an English source file.
[ "Strips", "out", "the", "warning", "from", "all", "translated", "po", "files", "about", "being", "an", "English", "source", "file", "." ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L103-L111
edx/i18n-tools
i18n/transifex.py
clean_locale
def clean_locale(configuration, locale): """ Strips out the warning from all of a locale's translated po files about being an English source file. Iterates over machine-generated files. """ dirname = configuration.get_messages_dir(locale) if not dirname.exists(): # Happens when we have a supported locale that doesn't exist in Transifex return for filename in dirname.files('*.po'): clean_file(configuration, dirname.joinpath(filename))
python
def clean_locale(configuration, locale): dirname = configuration.get_messages_dir(locale) if not dirname.exists(): return for filename in dirname.files('*.po'): clean_file(configuration, dirname.joinpath(filename))
[ "def", "clean_locale", "(", "configuration", ",", "locale", ")", ":", "dirname", "=", "configuration", ".", "get_messages_dir", "(", "locale", ")", "if", "not", "dirname", ".", "exists", "(", ")", ":", "# Happens when we have a supported locale that doesn't exist in Transifex", "return", "for", "filename", "in", "dirname", ".", "files", "(", "'*.po'", ")", ":", "clean_file", "(", "configuration", ",", "dirname", ".", "joinpath", "(", "filename", ")", ")" ]
Strips out the warning from all of a locale's translated po files about being an English source file. Iterates over machine-generated files.
[ "Strips", "out", "the", "warning", "from", "all", "of", "a", "locale", "s", "translated", "po", "files", "about", "being", "an", "English", "source", "file", ".", "Iterates", "over", "machine", "-", "generated", "files", "." ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L114-L125
edx/i18n-tools
i18n/transifex.py
clean_file
def clean_file(configuration, filename): """ Strips out the warning from a translated po file about being an English source file. Replaces warning with a note about coming from Transifex. """ pofile = polib.pofile(filename) if pofile.header.find(EDX_MARKER) != -1: new_header = get_new_header(configuration, pofile) new = pofile.header.replace(EDX_MARKER, new_header) pofile.header = new pofile.save()
python
def clean_file(configuration, filename): pofile = polib.pofile(filename) if pofile.header.find(EDX_MARKER) != -1: new_header = get_new_header(configuration, pofile) new = pofile.header.replace(EDX_MARKER, new_header) pofile.header = new pofile.save()
[ "def", "clean_file", "(", "configuration", ",", "filename", ")", ":", "pofile", "=", "polib", ".", "pofile", "(", "filename", ")", "if", "pofile", ".", "header", ".", "find", "(", "EDX_MARKER", ")", "!=", "-", "1", ":", "new_header", "=", "get_new_header", "(", "configuration", ",", "pofile", ")", "new", "=", "pofile", ".", "header", ".", "replace", "(", "EDX_MARKER", ",", "new_header", ")", "pofile", ".", "header", "=", "new", "pofile", ".", "save", "(", ")" ]
Strips out the warning from a translated po file about being an English source file. Replaces warning with a note about coming from Transifex.
[ "Strips", "out", "the", "warning", "from", "a", "translated", "po", "file", "about", "being", "an", "English", "source", "file", ".", "Replaces", "warning", "with", "a", "note", "about", "coming", "from", "Transifex", "." ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L128-L139
edx/i18n-tools
i18n/transifex.py
get_new_header
def get_new_header(configuration, pofile): """ Insert info about edX into the po file headers """ team = pofile.metadata.get('Language-Team', None) if not team: return TRANSIFEX_HEADER.format(configuration.TRANSIFEX_URL) return TRANSIFEX_HEADER.format(team)
python
def get_new_header(configuration, pofile): team = pofile.metadata.get('Language-Team', None) if not team: return TRANSIFEX_HEADER.format(configuration.TRANSIFEX_URL) return TRANSIFEX_HEADER.format(team)
[ "def", "get_new_header", "(", "configuration", ",", "pofile", ")", ":", "team", "=", "pofile", ".", "metadata", ".", "get", "(", "'Language-Team'", ",", "None", ")", "if", "not", "team", ":", "return", "TRANSIFEX_HEADER", ".", "format", "(", "configuration", ".", "TRANSIFEX_URL", ")", "return", "TRANSIFEX_HEADER", ".", "format", "(", "team", ")" ]
Insert info about edX into the po file headers
[ "Insert", "info", "about", "edX", "into", "the", "po", "file", "headers" ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L142-L149
edx/i18n-tools
i18n/converter.py
Converter.convert
def convert(self, string): """Returns: a converted tagged string param: string (contains html tags) Don't replace characters inside tags """ (string, tags) = self.detag_string(string) string = self.inner_convert_string(string) string = self.retag_string(string, tags) return string
python
def convert(self, string): (string, tags) = self.detag_string(string) string = self.inner_convert_string(string) string = self.retag_string(string, tags) return string
[ "def", "convert", "(", "self", ",", "string", ")", ":", "(", "string", ",", "tags", ")", "=", "self", ".", "detag_string", "(", "string", ")", "string", "=", "self", ".", "inner_convert_string", "(", "string", ")", "string", "=", "self", ".", "retag_string", "(", "string", ",", "tags", ")", "return", "string" ]
Returns: a converted tagged string param: string (contains html tags) Don't replace characters inside tags
[ "Returns", ":", "a", "converted", "tagged", "string", "param", ":", "string", "(", "contains", "html", "tags", ")" ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/converter.py#L40-L49
edx/i18n-tools
i18n/converter.py
Converter.detag_string
def detag_string(self, string): """Extracts tags from string. returns (string, list) where string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.) list: list of the removed tags ('<BR>', '<I>', '</I>') """ counter = itertools.count(0) count = lambda m: '<%s>' % next(counter) tags = self.tag_pattern.findall(string) tags = [''.join(tag) for tag in tags] (new, nfound) = self.tag_pattern.subn(count, string) if len(tags) != nfound: raise Exception('tags dont match:' + string) return (new, tags)
python
def detag_string(self, string): counter = itertools.count(0) count = lambda m: '<%s>' % next(counter) tags = self.tag_pattern.findall(string) tags = [''.join(tag) for tag in tags] (new, nfound) = self.tag_pattern.subn(count, string) if len(tags) != nfound: raise Exception('tags dont match:' + string) return (new, tags)
[ "def", "detag_string", "(", "self", ",", "string", ")", ":", "counter", "=", "itertools", ".", "count", "(", "0", ")", "count", "=", "lambda", "m", ":", "'<%s>'", "%", "next", "(", "counter", ")", "tags", "=", "self", ".", "tag_pattern", ".", "findall", "(", "string", ")", "tags", "=", "[", "''", ".", "join", "(", "tag", ")", "for", "tag", "in", "tags", "]", "(", "new", ",", "nfound", ")", "=", "self", ".", "tag_pattern", ".", "subn", "(", "count", ",", "string", ")", "if", "len", "(", "tags", ")", "!=", "nfound", ":", "raise", "Exception", "(", "'tags dont match:'", "+", "string", ")", "return", "(", "new", ",", "tags", ")" ]
Extracts tags from string. returns (string, list) where string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.) list: list of the removed tags ('<BR>', '<I>', '</I>')
[ "Extracts", "tags", "from", "string", "." ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/converter.py#L51-L65
edx/i18n-tools
i18n/converter.py
Converter.retag_string
def retag_string(self, string, tags): """substitutes each tag back into string, into occurrences of <0>, <1> etc""" for i, tag in enumerate(tags): bracketed = '<%s>' % i string = re.sub(bracketed, tag, string, 1) return string
python
def retag_string(self, string, tags): for i, tag in enumerate(tags): bracketed = '<%s>' % i string = re.sub(bracketed, tag, string, 1) return string
[ "def", "retag_string", "(", "self", ",", "string", ",", "tags", ")", ":", "for", "i", ",", "tag", "in", "enumerate", "(", "tags", ")", ":", "bracketed", "=", "'<%s>'", "%", "i", "string", "=", "re", ".", "sub", "(", "bracketed", ",", "tag", ",", "string", ",", "1", ")", "return", "string" ]
substitutes each tag back into string, into occurrences of <0>, <1> etc
[ "substitutes", "each", "tag", "back", "into", "string", "into", "occurrences", "of", "<0", ">", "<1", ">", "etc" ]
train
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/converter.py#L67-L72
protream/iquery
iquery/utils.py
Args.options
def options(self): """Train tickets query options.""" arg = self.get(0) if arg.startswith('-') and not self.is_asking_for_help: return arg[1:] return ''.join(x for x in arg if x in 'dgktz')
python
def options(self): arg = self.get(0) if arg.startswith('-') and not self.is_asking_for_help: return arg[1:] return ''.join(x for x in arg if x in 'dgktz')
[ "def", "options", "(", "self", ")", ":", "arg", "=", "self", ".", "get", "(", "0", ")", "if", "arg", ".", "startswith", "(", "'-'", ")", "and", "not", "self", ".", "is_asking_for_help", ":", "return", "arg", "[", "1", ":", "]", "return", "''", ".", "join", "(", "x", "for", "x", "in", "arg", "if", "x", "in", "'dgktz'", ")" ]
Train tickets query options.
[ "Train", "tickets", "query", "options", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/utils.py#L79-L84
protream/iquery
iquery/trains.py
TrainsCollection.trains
def trains(self): """Filter rows according to `headers`""" for row in self._rows: train_no = row.get('station_train_code') initial = train_no[0].lower() if not self._opts or initial in self._opts: train = [ # Column: '车次' train_no, # Column: '车站' '\n'.join([ colored.green(row.get('from_station_name')), colored.red(row.get('to_station_name')), ]), # Column: '时间' '\n'.join([ colored.green(row.get('start_time')), colored.red(row.get('arrive_time')), ]), # Column: '历时' self._get_duration(row), # Column: '商务' row.get('swz_num'), # Column: '一等' row.get('zy_num'), # Column: '二等' row.get('ze_num'), # Column: '软卧' row.get('rw_num'), # Column: '硬卧' row.get('yw_num'), # Column: '软座' row.get('rz_num'), # Column: '硬座' row.get('yz_num'), # Column: '无座' row.get('wz_num') ] yield train
python
def trains(self): for row in self._rows: train_no = row.get('station_train_code') initial = train_no[0].lower() if not self._opts or initial in self._opts: train = [ train_no, '\n'.join([ colored.green(row.get('from_station_name')), colored.red(row.get('to_station_name')), ]), '\n'.join([ colored.green(row.get('start_time')), colored.red(row.get('arrive_time')), ]), self._get_duration(row), row.get('swz_num'), row.get('zy_num'), row.get('ze_num'), row.get('rw_num'), row.get('yw_num'), row.get('rz_num'), row.get('yz_num'), row.get('wz_num') ] yield train
[ "def", "trains", "(", "self", ")", ":", "for", "row", "in", "self", ".", "_rows", ":", "train_no", "=", "row", ".", "get", "(", "'station_train_code'", ")", "initial", "=", "train_no", "[", "0", "]", ".", "lower", "(", ")", "if", "not", "self", ".", "_opts", "or", "initial", "in", "self", ".", "_opts", ":", "train", "=", "[", "# Column: '车次'", "train_no", ",", "# Column: '车站'", "'\\n'", ".", "join", "(", "[", "colored", ".", "green", "(", "row", ".", "get", "(", "'from_station_name'", ")", ")", ",", "colored", ".", "red", "(", "row", ".", "get", "(", "'to_station_name'", ")", ")", ",", "]", ")", ",", "# Column: '时间'", "'\\n'", ".", "join", "(", "[", "colored", ".", "green", "(", "row", ".", "get", "(", "'start_time'", ")", ")", ",", "colored", ".", "red", "(", "row", ".", "get", "(", "'arrive_time'", ")", ")", ",", "]", ")", ",", "# Column: '历时'", "self", ".", "_get_duration", "(", "row", ")", ",", "# Column: '商务'", "row", ".", "get", "(", "'swz_num'", ")", ",", "# Column: '一等'", "row", ".", "get", "(", "'zy_num'", ")", ",", "# Column: '二等'", "row", ".", "get", "(", "'ze_num'", ")", ",", "# Column: '软卧'", "row", ".", "get", "(", "'rw_num'", ")", ",", "# Column: '硬卧'", "row", ".", "get", "(", "'yw_num'", ")", ",", "# Column: '软座'", "row", ".", "get", "(", "'rz_num'", ")", ",", "# Column: '硬座'", "row", ".", "get", "(", "'yz_num'", ")", ",", "# Column: '无座'", "row", ".", "get", "(", "'wz_num'", ")", "]", "yield", "train" ]
Filter rows according to `headers`
[ "Filter", "rows", "according", "to", "headers" ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L63-L101
protream/iquery
iquery/trains.py
TrainsCollection.pretty_print
def pretty_print(self): """Use `PrettyTable` to perform formatted outprint.""" pt = PrettyTable() if len(self) == 0: pt._set_field_names(['Sorry,']) pt.add_row([TRAIN_NOT_FOUND]) else: pt._set_field_names(self.headers) for train in self.trains: pt.add_row(train) print(pt)
python
def pretty_print(self): pt = PrettyTable() if len(self) == 0: pt._set_field_names(['Sorry,']) pt.add_row([TRAIN_NOT_FOUND]) else: pt._set_field_names(self.headers) for train in self.trains: pt.add_row(train) print(pt)
[ "def", "pretty_print", "(", "self", ")", ":", "pt", "=", "PrettyTable", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "pt", ".", "_set_field_names", "(", "[", "'Sorry,'", "]", ")", "pt", ".", "add_row", "(", "[", "TRAIN_NOT_FOUND", "]", ")", "else", ":", "pt", ".", "_set_field_names", "(", "self", ".", "headers", ")", "for", "train", "in", "self", ".", "trains", ":", "pt", ".", "add_row", "(", "train", ")", "print", "(", "pt", ")" ]
Use `PrettyTable` to perform formatted outprint.
[ "Use", "PrettyTable", "to", "perform", "formatted", "outprint", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L103-L113
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): 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) 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L177-L194
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): result = ''.join(re.findall('\d', date)) l = len(result) if l in (2, 3, 4): year = str(datetime.today().year) return year + result 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L197-L218
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): 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L220-L229
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): 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/showes.py#L121-L135
protream/iquery
iquery/showes.py
ShowTicketsQuery.parse
def parse(self, items): """Parse `主题`, `时间`, `场馆`, 票价` in every item.""" rows = [] for i, item in enumerate(items): theme = colored.green(item.find(class_='ico').a.text.strip()) text = item.find(class_='mt10').text.strip() mix = re.sub('\s+', ' ', text).split(':') time = mix[1][:-3] place = mix[2][:-7] # display time below theme theme_time = '\n'.join([theme, colored.red(time)]) price = item.find(class_='price-sort').text.strip() rows.append([theme_time, price, place]) return rows
python
def parse(self, items): rows = [] for i, item in enumerate(items): theme = colored.green(item.find(class_='ico').a.text.strip()) text = item.find(class_='mt10').text.strip() mix = re.sub('\s+', ' ', text).split(':') time = mix[1][:-3] place = mix[2][:-7] theme_time = '\n'.join([theme, colored.red(time)]) price = item.find(class_='price-sort').text.strip() rows.append([theme_time, price, place]) return rows
[ "def", "parse", "(", "self", ",", "items", ")", ":", "rows", "=", "[", "]", "for", "i", ",", "item", "in", "enumerate", "(", "items", ")", ":", "theme", "=", "colored", ".", "green", "(", "item", ".", "find", "(", "class_", "=", "'ico'", ")", ".", "a", ".", "text", ".", "strip", "(", ")", ")", "text", "=", "item", ".", "find", "(", "class_", "=", "'mt10'", ")", ".", "text", ".", "strip", "(", ")", "mix", "=", "re", ".", "sub", "(", "'\\s+'", ",", "' '", ",", "text", ")", ".", "split", "(", "':')", "", "time", "=", "mix", "[", "1", "]", "[", ":", "-", "3", "]", "place", "=", "mix", "[", "2", "]", "[", ":", "-", "7", "]", "# display time below theme", "theme_time", "=", "'\\n'", ".", "join", "(", "[", "theme", ",", "colored", ".", "red", "(", "time", ")", "]", ")", "price", "=", "item", ".", "find", "(", "class_", "=", "'price-sort'", ")", ".", "text", ".", "strip", "(", ")", "rows", ".", "append", "(", "[", "theme_time", ",", "price", ",", "place", "]", ")", "return", "rows" ]
Parse `主题`, `时间`, `场馆`, 票价` in every item.
[ "Parse", "主题", "时间", "场馆", "票价", "in", "every", "item", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/showes.py#L146-L159
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): 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/hospitals.py#L67-L99
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(): 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/core.py#L44-L117
protream/iquery
iquery/lyrics.py
query
def query(song_name): """CLI: $ iquery -l song_name """ r = requests_get(SONG_SEARCH_URL.format(song_name)) try: # Get the first result. song_url = re.search(r'(http://www.xiami.com/song/\d+)', r.text).group(0) except AttributeError: exit_after_echo(SONG_NOT_FOUND) return SongPage(song_url)
python
def query(song_name): r = requests_get(SONG_SEARCH_URL.format(song_name)) try: song_url = re.search(r'(http://www.xiami.com/song/\d+)', r.text).group(0) except AttributeError: exit_after_echo(SONG_NOT_FOUND) return SongPage(song_url)
[ "def", "query", "(", "song_name", ")", ":", "r", "=", "requests_get", "(", "SONG_SEARCH_URL", ".", "format", "(", "song_name", ")", ")", "try", ":", "# Get the first result.", "song_url", "=", "re", ".", "search", "(", "r'(http://www.xiami.com/song/\\d+)'", ",", "r", ".", "text", ")", ".", "group", "(", "0", ")", "except", "AttributeError", ":", "exit_after_echo", "(", "SONG_NOT_FOUND", ")", "return", "SongPage", "(", "song_url", ")" ]
CLI: $ iquery -l song_name
[ "CLI", ":" ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/lyrics.py#L58-L71
protream/iquery
iquery/lottery.py
LotteryPage.lotteries
def lotteries(self): """用于生成所有彩种最近开奖信息""" for idx, row in enumerate(self._rows): i = pq(row) cz = i('td:eq(0)').text().strip() if cz in self.need_to_show: qh = i('td:eq(1)').text().strip() kjsj = i('td:eq(2)').text().strip() hm_r = colored.red(i('td:eq(3) span.ball_1').text().strip()) hm_g = colored.green(i('td:eq(3) span.ball_2').text().strip()) kjhm = ' '.join([hm_r, hm_g]) jcgc = i('td:eq(4)').text().strip() lottery = [idx, cz, qh, kjsj, kjhm, jcgc] yield lottery
python
def lotteries(self): for idx, row in enumerate(self._rows): i = pq(row) cz = i('td:eq(0)').text().strip() if cz in self.need_to_show: qh = i('td:eq(1)').text().strip() kjsj = i('td:eq(2)').text().strip() hm_r = colored.red(i('td:eq(3) span.ball_1').text().strip()) hm_g = colored.green(i('td:eq(3) span.ball_2').text().strip()) kjhm = ' '.join([hm_r, hm_g]) jcgc = i('td:eq(4)').text().strip() lottery = [idx, cz, qh, kjsj, kjhm, jcgc] yield lottery
[ "def", "lotteries", "(", "self", ")", ":", "for", "idx", ",", "row", "in", "enumerate", "(", "self", ".", "_rows", ")", ":", "i", "=", "pq", "(", "row", ")", "cz", "=", "i", "(", "'td:eq(0)'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "if", "cz", "in", "self", ".", "need_to_show", ":", "qh", "=", "i", "(", "'td:eq(1)'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "kjsj", "=", "i", "(", "'td:eq(2)'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "hm_r", "=", "colored", ".", "red", "(", "i", "(", "'td:eq(3) span.ball_1'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", ")", "hm_g", "=", "colored", ".", "green", "(", "i", "(", "'td:eq(3) span.ball_2'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", ")", "kjhm", "=", "' '", ".", "join", "(", "[", "hm_r", ",", "hm_g", "]", ")", "jcgc", "=", "i", "(", "'td:eq(4)'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "lottery", "=", "[", "idx", ",", "cz", ",", "qh", ",", "kjsj", ",", "kjhm", ",", "jcgc", "]", "yield", "lottery" ]
用于生成所有彩种最近开奖信息
[ "用于生成所有彩种最近开奖信息" ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/lottery.py#L43-L57
protream/iquery
iquery/lottery.py
LotteryPage._get_lottery_detail_by_id
def _get_lottery_detail_by_id(self, id): """ 相应彩种历史信息生成 百度详细信息页有两种结构,需要分开处理 """ header = '编号 期号 开奖日期 开奖号码'.split() pt = PrettyTable() pt._set_field_names(header) url = QUERY_DETAIL_URL.format(id=id) import requests content = requests.get(url).text d = pq(content) if d('table.historylist'): # 输出彩种 info = d('div.historyHd1 h2').text() print(info) # 输出table rows = d('table.historylist>tbody>tr') for idx, row in enumerate(rows): i = pq(row) qh = i('td:eq(0)').text().strip() kjrq = i('td:eq(1)').text().strip() hm_r = colored.red(i('td:eq(2) td.redBalls').text().strip()) hm_g = colored.green(i('td:eq(2) td.blueBalls').text().strip()) kjhm = ' '.join([hm_r, hm_g]) item = [idx + 1, qh, kjrq, kjhm] pt.add_row(item) print(pt) elif d('table#draw_list'): # 输出彩种 info = d('div.cpinfo>div.title').text() print(info) # 输出table rows = d('table#draw_list>tbody>tr') for idx, row in enumerate(rows): i = pq(row) qh = i('td.td2').text().strip() kjrq = i('td.td1').text().strip() hm_r = colored.red(i('td.td3 span.ball_1').text().strip()) hm_g = colored.green(i('td.td3 span.ball_2').text().strip()) kjhm = ' '.join([hm_r, hm_g]) item = [idx + 1, qh, kjrq, kjhm] pt.add_row(item) print(pt) else: print('请联系作者')
python
def _get_lottery_detail_by_id(self, id): header = '编号 期号 开奖日期 开奖号码'.split() pt = PrettyTable() pt._set_field_names(header) url = QUERY_DETAIL_URL.format(id=id) import requests content = requests.get(url).text d = pq(content) if d('table.historylist'): info = d('div.historyHd1 h2').text() print(info) rows = d('table.historylist>tbody>tr') for idx, row in enumerate(rows): i = pq(row) qh = i('td:eq(0)').text().strip() kjrq = i('td:eq(1)').text().strip() hm_r = colored.red(i('td:eq(2) td.redBalls').text().strip()) hm_g = colored.green(i('td:eq(2) td.blueBalls').text().strip()) kjhm = ' '.join([hm_r, hm_g]) item = [idx + 1, qh, kjrq, kjhm] pt.add_row(item) print(pt) elif d('table info = d('div.cpinfo>div.title').text() print(info) rows = d('table for idx, row in enumerate(rows): i = pq(row) qh = i('td.td2').text().strip() kjrq = i('td.td1').text().strip() hm_r = colored.red(i('td.td3 span.ball_1').text().strip()) hm_g = colored.green(i('td.td3 span.ball_2').text().strip()) kjhm = ' '.join([hm_r, hm_g]) item = [idx + 1, qh, kjrq, kjhm] pt.add_row(item) print(pt) else: print('请联系作者')
[ "def", "_get_lottery_detail_by_id", "(", "self", ",", "id", ")", ":", "header", "=", "'编号 期号 开奖日期 开奖号码'.split()", "", "", "", "", "pt", "=", "PrettyTable", "(", ")", "pt", ".", "_set_field_names", "(", "header", ")", "url", "=", "QUERY_DETAIL_URL", ".", "format", "(", "id", "=", "id", ")", "import", "requests", "content", "=", "requests", ".", "get", "(", "url", ")", ".", "text", "d", "=", "pq", "(", "content", ")", "if", "d", "(", "'table.historylist'", ")", ":", "# 输出彩种", "info", "=", "d", "(", "'div.historyHd1 h2'", ")", ".", "text", "(", ")", "print", "(", "info", ")", "# 输出table", "rows", "=", "d", "(", "'table.historylist>tbody>tr'", ")", "for", "idx", ",", "row", "in", "enumerate", "(", "rows", ")", ":", "i", "=", "pq", "(", "row", ")", "qh", "=", "i", "(", "'td:eq(0)'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "kjrq", "=", "i", "(", "'td:eq(1)'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "hm_r", "=", "colored", ".", "red", "(", "i", "(", "'td:eq(2) td.redBalls'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", ")", "hm_g", "=", "colored", ".", "green", "(", "i", "(", "'td:eq(2) td.blueBalls'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", ")", "kjhm", "=", "' '", ".", "join", "(", "[", "hm_r", ",", "hm_g", "]", ")", "item", "=", "[", "idx", "+", "1", ",", "qh", ",", "kjrq", ",", "kjhm", "]", "pt", ".", "add_row", "(", "item", ")", "print", "(", "pt", ")", "elif", "d", "(", "'table#draw_list'", ")", ":", "# 输出彩种", "info", "=", "d", "(", "'div.cpinfo>div.title'", ")", ".", "text", "(", ")", "print", "(", "info", ")", "# 输出table", "rows", "=", "d", "(", "'table#draw_list>tbody>tr'", ")", "for", "idx", ",", "row", "in", "enumerate", "(", "rows", ")", ":", "i", "=", "pq", "(", "row", ")", "qh", "=", "i", "(", "'td.td2'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "kjrq", "=", "i", "(", "'td.td1'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", "hm_r", "=", "colored", ".", "red", "(", "i", "(", "'td.td3 span.ball_1'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", ")", "hm_g", "=", "colored", ".", "green", "(", "i", "(", "'td.td3 span.ball_2'", ")", ".", "text", "(", ")", ".", "strip", "(", ")", ")", "kjhm", "=", "' '", ".", "join", "(", "[", "hm_r", ",", "hm_g", "]", ")", "item", "=", "[", "idx", "+", "1", ",", "qh", ",", "kjrq", ",", "kjhm", "]", "pt", ".", "add_row", "(", "item", ")", "print", "(", "pt", ")", "else", ":", "print", "(", "'请联系作者')", "" ]
相应彩种历史信息生成 百度详细信息页有两种结构,需要分开处理
[ "相应彩种历史信息生成", "百度详细信息页有两种结构,需要分开处理" ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/lottery.py#L59-L105
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(): 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", "." ]
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/movies.py#L93-L103
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): 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" ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L54-L64
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): 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.')) 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: 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" ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L67-L92
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): 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])) rec.write({ 'state': 'approved', 'approved_date': fields.datetime.now(), 'approved_uid': self.env.uid, }) rec.page_id._compute_history_head() rec.message_post( subtype='mt_comment', body=_( 'Change request has been approved by %s.' ) % (self.env.user.name) ) 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L95-L129
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): 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L132-L141
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): 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" ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L150-L153
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): 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 '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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L156-L170
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): 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" ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L173-L186
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): 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_url/wizard/document_url.py#L14-L32
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): 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L76-L82
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): 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L86-L92
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): 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L96-L99
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): self.ensure_one() if not self.is_approval_required: return True if user.has_group('document_page.group_document_manager'): return True if not user.has_group( 'document_page_approval.group_document_approver_user'): return False if not self.approver_group_ids: return True 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", "." ]
train
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L102-L119
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): response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self.locationId, headers=self.client._headers() ) response.raise_for_status() data = response.json() 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/location.py#L26-L55
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L34-L45
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L47-L58
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): response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), headers=self.client._headers() ) 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) 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" ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L16-L42
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): try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) headers = dict(self.client._headers()) 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" ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L44-L63
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L115-L133
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L135-L139
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L266-L275
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L288-L311
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L313-L324
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L84-L93
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): _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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L95-L130
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L192-L202
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L204-L223
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L225-L234
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): 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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L236-L243
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): self.location.status() if self.hotwater: yield { 'thermostat': 'DOMESTIC_HOT_WATER', 'id': self.hotwater.dhwId, 'name': '', 'temp': self.hotwater.temperatureStatus['temperature'], '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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L92-L116
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): _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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L118-L149
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): _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", "." ]
train
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L151-L174
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/item_list.py#L18-L53
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): 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/item_list.py#L56-L66
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vlan/list.py#L34-L58
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/nas/list.py#L13-L36
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): 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: 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L15-L37
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): 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.') 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L42-L86
softlayer/softlayer-python
SoftLayer/CLI/config/setup.py
get_user_input
def get_user_input(env): """Ask for username, secret (api_key or password) and endpoint_url.""" defaults = config.get_settings_from_client(env.client) # Ask for username username = env.input('Username', default=defaults['username']) # Ask for 'secret' which can be api_key or their password secret = env.getpass('API Key or Password', default=defaults['api_key']) # Ask for which endpoint they want to use endpoint = defaults.get('endpoint_url', 'public') endpoint_type = env.input( 'Endpoint (public|private|custom)', default=endpoint) endpoint_type = endpoint_type.lower() if endpoint_type == 'public': endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT elif endpoint_type == 'private': endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT else: if endpoint_type == 'custom': endpoint_url = env.input('Endpoint URL', default=endpoint) else: endpoint_url = endpoint_type # Ask for timeout timeout = env.input('Timeout', default=defaults['timeout'] or 0) return username, secret, endpoint_url, timeout
python
def get_user_input(env): defaults = config.get_settings_from_client(env.client) username = env.input('Username', default=defaults['username']) secret = env.getpass('API Key or Password', default=defaults['api_key']) endpoint = defaults.get('endpoint_url', 'public') endpoint_type = env.input( 'Endpoint (public|private|custom)', default=endpoint) endpoint_type = endpoint_type.lower() if endpoint_type == 'public': endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT elif endpoint_type == 'private': endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT else: if endpoint_type == 'custom': endpoint_url = env.input('Endpoint URL', default=endpoint) else: endpoint_url = endpoint_type timeout = env.input('Timeout', default=defaults['timeout'] or 0) return username, secret, endpoint_url, timeout
[ "def", "get_user_input", "(", "env", ")", ":", "defaults", "=", "config", ".", "get_settings_from_client", "(", "env", ".", "client", ")", "# Ask for username", "username", "=", "env", ".", "input", "(", "'Username'", ",", "default", "=", "defaults", "[", "'username'", "]", ")", "# Ask for 'secret' which can be api_key or their password", "secret", "=", "env", ".", "getpass", "(", "'API Key or Password'", ",", "default", "=", "defaults", "[", "'api_key'", "]", ")", "# Ask for which endpoint they want to use", "endpoint", "=", "defaults", ".", "get", "(", "'endpoint_url'", ",", "'public'", ")", "endpoint_type", "=", "env", ".", "input", "(", "'Endpoint (public|private|custom)'", ",", "default", "=", "endpoint", ")", "endpoint_type", "=", "endpoint_type", ".", "lower", "(", ")", "if", "endpoint_type", "==", "'public'", ":", "endpoint_url", "=", "SoftLayer", ".", "API_PUBLIC_ENDPOINT", "elif", "endpoint_type", "==", "'private'", ":", "endpoint_url", "=", "SoftLayer", ".", "API_PRIVATE_ENDPOINT", "else", ":", "if", "endpoint_type", "==", "'custom'", ":", "endpoint_url", "=", "env", ".", "input", "(", "'Endpoint URL'", ",", "default", "=", "endpoint", ")", "else", ":", "endpoint_url", "=", "endpoint_type", "# Ask for timeout", "timeout", "=", "env", ".", "input", "(", "'Timeout'", ",", "default", "=", "defaults", "[", "'timeout'", "]", "or", "0", ")", "return", "username", ",", "secret", ",", "endpoint_url", ",", "timeout" ]
Ask for username, secret (api_key or password) and endpoint_url.
[ "Ask", "for", "username", "secret", "(", "api_key", "or", "password", ")", "and", "endpoint_url", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L89-L119
softlayer/softlayer-python
SoftLayer/CLI/loadbal/__init__.py
parse_id
def parse_id(input_id): """Parse the load balancer kind and actual id from the "kind:id" form.""" parts = input_id.split(':') if len(parts) != 2: raise exceptions.CLIAbort( 'Invalid ID %s: ID should be of the form "kind:id"' % input_id) return parts[0], int(parts[1])
python
def parse_id(input_id): parts = input_id.split(':') if len(parts) != 2: raise exceptions.CLIAbort( 'Invalid ID %s: ID should be of the form "kind:id"' % input_id) return parts[0], int(parts[1])
[ "def", "parse_id", "(", "input_id", ")", ":", "parts", "=", "input_id", ".", "split", "(", "':'", ")", "if", "len", "(", "parts", ")", "!=", "2", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Invalid ID %s: ID should be of the form \"kind:id\"'", "%", "input_id", ")", "return", "parts", "[", "0", "]", ",", "int", "(", "parts", "[", "1", "]", ")" ]
Parse the load balancer kind and actual id from the "kind:id" form.
[ "Parse", "the", "load", "balancer", "kind", "and", "actual", "id", "from", "the", "kind", ":", "id", "form", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/__init__.py#L6-L12
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): mgr = SoftLayer.DedicatedHostManager(env.client) tables = [] if not kwargs['flavor'] and not kwargs['datacenter']: options = mgr.get_create_options() 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/create_options.py#L22-L61
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/cancel_reasons.py#L13-L25
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): 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/list.py#L13-L31
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/locations.py#L32-L49
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/list_guests.py#L57-L76
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/detail.py#L20-L26
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): 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L45-L56
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L544-L558
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): 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L158-L163
softlayer/softlayer-python
SoftLayer/transports.py
XmlRpcTransport.print_reproduceable
def print_reproduceable(self, request): """Prints out the minimal python code to reproduce a specific request The will also automatically replace the API key so its not accidently exposed. :param request request: Request object """ from string import Template output = Template('''============= testing.py ============= import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from xml.etree import ElementTree client = requests.Session() client.headers.update({'Content-Type': 'application/json', 'User-Agent': 'softlayer-python/testing',}) retry = Retry(connect=3, backoff_factor=3) adapter = HTTPAdapter(max_retries=retry) client.mount('https://', adapter) url = '$url' payload = """$payload""" transport_headers = $transport_headers timeout = $timeout verify = $verify cert = $cert proxy = $proxy response = client.request('POST', url, data=payload, headers=transport_headers, timeout=timeout, verify=verify, cert=cert, proxies=proxy) xml = ElementTree.fromstring(response.content) ElementTree.dump(xml) ==========================''') safe_payload = re.sub(r'<string>[a-z0-9]{64}</string>', r'<string>API_KEY_GOES_HERE</string>', request.payload) safe_payload = re.sub(r'(\s+)', r' ', safe_payload) substitutions = dict(url=request.url, payload=safe_payload, transport_headers=request.transport_headers, timeout=self.timeout, verify=request.verify, cert=request.cert, proxy=_proxies_dict(self.proxy)) return output.substitute(substitutions)
python
def print_reproduceable(self, request): from string import Template output = Template() safe_payload = re.sub(r'<string>[a-z0-9]{64}</string>', r'<string>API_KEY_GOES_HERE</string>', request.payload) safe_payload = re.sub(r'(\s+)', r' ', safe_payload) substitutions = dict(url=request.url, payload=safe_payload, transport_headers=request.transport_headers, timeout=self.timeout, verify=request.verify, cert=request.cert, proxy=_proxies_dict(self.proxy)) return output.substitute(substitutions)
[ "def", "print_reproduceable", "(", "self", ",", "request", ")", ":", "from", "string", "import", "Template", "output", "=", "Template", "(", "'''============= testing.py =============\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nfrom xml.etree import ElementTree\nclient = requests.Session()\nclient.headers.update({'Content-Type': 'application/json', 'User-Agent': 'softlayer-python/testing',})\nretry = Retry(connect=3, backoff_factor=3)\nadapter = HTTPAdapter(max_retries=retry)\nclient.mount('https://', adapter)\nurl = '$url'\npayload = \"\"\"$payload\"\"\"\ntransport_headers = $transport_headers\ntimeout = $timeout\nverify = $verify\ncert = $cert\nproxy = $proxy\nresponse = client.request('POST', url, data=payload, headers=transport_headers, timeout=timeout,\n verify=verify, cert=cert, proxies=proxy)\nxml = ElementTree.fromstring(response.content)\nElementTree.dump(xml)\n=========================='''", ")", "safe_payload", "=", "re", ".", "sub", "(", "r'<string>[a-z0-9]{64}</string>'", ",", "r'<string>API_KEY_GOES_HERE</string>'", ",", "request", ".", "payload", ")", "safe_payload", "=", "re", ".", "sub", "(", "r'(\\s+)'", ",", "r' '", ",", "safe_payload", ")", "substitutions", "=", "dict", "(", "url", "=", "request", ".", "url", ",", "payload", "=", "safe_payload", ",", "transport_headers", "=", "request", ".", "transport_headers", ",", "timeout", "=", "self", ".", "timeout", ",", "verify", "=", "request", ".", "verify", ",", "cert", "=", "request", ".", "cert", ",", "proxy", "=", "_proxies_dict", "(", "self", ".", "proxy", ")", ")", "return", "output", ".", "substitute", "(", "substitutions", ")" ]
Prints out the minimal python code to reproduce a specific request The will also automatically replace the API key so its not accidently exposed. :param request request: Request object
[ "Prints", "out", "the", "minimal", "python", "code", "to", "reproduce", "a", "specific", "request" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L246-L282
softlayer/softlayer-python
SoftLayer/transports.py
RestTransport.print_reproduceable
def print_reproduceable(self, request): """Prints out the minimal python code to reproduce a specific request The will also automatically replace the API key so its not accidently exposed. :param request request: Request object """ command = "curl -u $SL_USER:$SL_APIKEY -X {method} -H {headers} {data} '{uri}'" method = REST_SPECIAL_METHODS.get(request.method) if method is None: method = 'GET' if request.args: method = 'POST' data = '' if request.payload is not None: data = "-d '{}'".format(request.payload) headers = ['"{0}: {1}"'.format(k, v) for k, v in request.transport_headers.items()] headers = " -H ".join(headers) return command.format(method=method, headers=headers, data=data, uri=request.url)
python
def print_reproduceable(self, request): command = "curl -u $SL_USER:$SL_APIKEY -X {method} -H {headers} {data} '{uri}'" method = REST_SPECIAL_METHODS.get(request.method) if method is None: method = 'GET' if request.args: method = 'POST' data = '' if request.payload is not None: data = "-d '{}'".format(request.payload) headers = ['"{0}: {1}"'.format(k, v) for k, v in request.transport_headers.items()] headers = " -H ".join(headers) return command.format(method=method, headers=headers, data=data, uri=request.url)
[ "def", "print_reproduceable", "(", "self", ",", "request", ")", ":", "command", "=", "\"curl -u $SL_USER:$SL_APIKEY -X {method} -H {headers} {data} '{uri}'\"", "method", "=", "REST_SPECIAL_METHODS", ".", "get", "(", "request", ".", "method", ")", "if", "method", "is", "None", ":", "method", "=", "'GET'", "if", "request", ".", "args", ":", "method", "=", "'POST'", "data", "=", "''", "if", "request", ".", "payload", "is", "not", "None", ":", "data", "=", "\"-d '{}'\"", ".", "format", "(", "request", ".", "payload", ")", "headers", "=", "[", "'\"{0}: {1}\"'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "request", ".", "transport_headers", ".", "items", "(", ")", "]", "headers", "=", "\" -H \"", ".", "join", "(", "headers", ")", "return", "command", ".", "format", "(", "method", "=", "method", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "uri", "=", "request", ".", "url", ")" ]
Prints out the minimal python code to reproduce a specific request The will also automatically replace the API key so its not accidently exposed. :param request request: Request object
[ "Prints", "out", "the", "minimal", "python", "code", "to", "reproduce", "a", "specific", "request" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L412-L434
softlayer/softlayer-python
SoftLayer/transports.py
DebugTransport.post_transport_log
def post_transport_log(self, call): """Prints the result "Returned Data: \n%s" % (call.result)of an API call""" output = "Returned Data: \n{}".format(call.result) LOGGER.debug(output)
python
def post_transport_log(self, call): output = "Returned Data: \n{}".format(call.result) LOGGER.debug(output)
[ "def", "post_transport_log", "(", "self", ",", "call", ")", ":", "output", "=", "\"Returned Data: \\n{}\"", ".", "format", "(", "call", ".", "result", ")", "LOGGER", ".", "debug", "(", "output", ")" ]
Prints the result "Returned Data: \n%s" % (call.result)of an API call
[ "Prints", "the", "result", "Returned", "Data", ":", "\\", "n%s", "%", "(", "call", ".", "result", ")", "of", "an", "API", "call" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L471-L474
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): 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/toggle_ipmi.py#L16-L22
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_remove.py#L15-L23
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): 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) 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/count.py#L19-L42
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/load.py#L14-L18
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vlan/detail.py#L21-L83
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/lun.py#L14-L36
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/detail.py#L15-L81
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): 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: 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L108-L135
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L140-L174
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L177-L208
softlayer/softlayer-python
SoftLayer/CLI/core.py
CommandLoader.list_commands
def list_commands(self, ctx): """List all sub-commands.""" env = ctx.ensure_object(environment.Environment) env.load() return sorted(env.list_commands(*self.path))
python
def list_commands(self, ctx): env = ctx.ensure_object(environment.Environment) env.load() return sorted(env.list_commands(*self.path))
[ "def", "list_commands", "(", "self", ",", "ctx", ")", ":", "env", "=", "ctx", ".", "ensure_object", "(", "environment", ".", "Environment", ")", "env", ".", "load", "(", ")", "return", "sorted", "(", "env", ".", "list_commands", "(", "*", "self", ".", "path", ")", ")" ]
List all sub-commands.
[ "List", "all", "sub", "-", "commands", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L47-L52
softlayer/softlayer-python
SoftLayer/CLI/core.py
CommandLoader.get_command
def get_command(self, ctx, name): """Get command for click.""" env = ctx.ensure_object(environment.Environment) env.load() # Do alias lookup (only available for root commands) if len(self.path) == 0: name = env.resolve_alias(name) new_path = list(self.path) new_path.append(name) module = env.get_command(*new_path) if isinstance(module, types.ModuleType): return CommandLoader(*new_path, help=module.__doc__ or '') else: return module
python
def get_command(self, ctx, name): env = ctx.ensure_object(environment.Environment) env.load() if len(self.path) == 0: name = env.resolve_alias(name) new_path = list(self.path) new_path.append(name) module = env.get_command(*new_path) if isinstance(module, types.ModuleType): return CommandLoader(*new_path, help=module.__doc__ or '') else: return module
[ "def", "get_command", "(", "self", ",", "ctx", ",", "name", ")", ":", "env", "=", "ctx", ".", "ensure_object", "(", "environment", ".", "Environment", ")", "env", ".", "load", "(", ")", "# Do alias lookup (only available for root commands)", "if", "len", "(", "self", ".", "path", ")", "==", "0", ":", "name", "=", "env", ".", "resolve_alias", "(", "name", ")", "new_path", "=", "list", "(", "self", ".", "path", ")", "new_path", ".", "append", "(", "name", ")", "module", "=", "env", ".", "get_command", "(", "*", "new_path", ")", "if", "isinstance", "(", "module", ",", "types", ".", "ModuleType", ")", ":", "return", "CommandLoader", "(", "*", "new_path", ",", "help", "=", "module", ".", "__doc__", "or", "''", ")", "else", ":", "return", "module" ]
Get command for click.
[ "Get", "command", "for", "click", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L54-L69
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): block_manager = SoftLayer.BlockStorageManager(env.client) ip_address_id_list = list(ip_address_id) 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) 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/access/revoke.py#L23-L41
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/create.py
cli
def cli(env, **kwargs): """Order/create a dedicated host.""" mgr = SoftLayer.DedicatedHostManager(env.client) order = { 'hostname': kwargs['hostname'], 'domain': kwargs['domain'], 'flavor': kwargs['flavor'], 'location': kwargs['datacenter'], 'hourly': kwargs.get('billing') == 'hourly', } if kwargs['router']: order['router'] = kwargs['router'] do_create = not (kwargs['export'] or kwargs['verify']) output = None result = mgr.verify_order(**order) table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' if len(result['prices']) != 1: raise exceptions.ArgumentError("More than 1 price was found or no " "prices found") price = result['prices'] if order['hourly']: total = float(price[0].get('hourlyRecurringFee', 0.0)) else: total = float(price[0].get('recurringFee', 0.0)) if order['hourly']: table.add_row(['Total hourly cost', "%.2f" % total]) else: table.add_row(['Total monthly cost', "%.2f" % total]) output = [] output.append(table) output.append(formatting.FormattedItem( '', ' -- ! Prices reflected here are retail and do not ' 'take account level discounts and are not guaranteed.')) if kwargs['export']: export_file = kwargs.pop('export') template.export_to_template(export_file, kwargs, exclude=['wait', 'verify']) env.fout('Successfully exported options to a template file.') if do_create: if not env.skip_confirmations and not formatting.confirm( "This action will incur charges on your account. " "Continue?"): raise exceptions.CLIAbort('Aborting dedicated host order.') result = mgr.place_order(**order) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) output.append(table) env.fout(output)
python
def cli(env, **kwargs): mgr = SoftLayer.DedicatedHostManager(env.client) order = { 'hostname': kwargs['hostname'], 'domain': kwargs['domain'], 'flavor': kwargs['flavor'], 'location': kwargs['datacenter'], 'hourly': kwargs.get('billing') == 'hourly', } if kwargs['router']: order['router'] = kwargs['router'] do_create = not (kwargs['export'] or kwargs['verify']) output = None result = mgr.verify_order(**order) table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' if len(result['prices']) != 1: raise exceptions.ArgumentError("More than 1 price was found or no " "prices found") price = result['prices'] if order['hourly']: total = float(price[0].get('hourlyRecurringFee', 0.0)) else: total = float(price[0].get('recurringFee', 0.0)) if order['hourly']: table.add_row(['Total hourly cost', "%.2f" % total]) else: table.add_row(['Total monthly cost', "%.2f" % total]) output = [] output.append(table) output.append(formatting.FormattedItem( '', ' -- ! Prices reflected here are retail and do not ' 'take account level discounts and are not guaranteed.')) if kwargs['export']: export_file = kwargs.pop('export') template.export_to_template(export_file, kwargs, exclude=['wait', 'verify']) env.fout('Successfully exported options to a template file.') if do_create: if not env.skip_confirmations and not formatting.confirm( "This action will incur charges on your account. " "Continue?"): raise exceptions.CLIAbort('Aborting dedicated host order.') result = mgr.place_order(**order) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) output.append(table) env.fout(output)
[ "def", "cli", "(", "env", ",", "*", "*", "kwargs", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "order", "=", "{", "'hostname'", ":", "kwargs", "[", "'hostname'", "]", ",", "'domain'", ":", "kwargs", "[", "'domain'", "]", ",", "'flavor'", ":", "kwargs", "[", "'flavor'", "]", ",", "'location'", ":", "kwargs", "[", "'datacenter'", "]", ",", "'hourly'", ":", "kwargs", ".", "get", "(", "'billing'", ")", "==", "'hourly'", ",", "}", "if", "kwargs", "[", "'router'", "]", ":", "order", "[", "'router'", "]", "=", "kwargs", "[", "'router'", "]", "do_create", "=", "not", "(", "kwargs", "[", "'export'", "]", "or", "kwargs", "[", "'verify'", "]", ")", "output", "=", "None", "result", "=", "mgr", ".", "verify_order", "(", "*", "*", "order", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'Item'", ",", "'cost'", "]", ")", "table", ".", "align", "[", "'Item'", "]", "=", "'r'", "table", ".", "align", "[", "'cost'", "]", "=", "'r'", "if", "len", "(", "result", "[", "'prices'", "]", ")", "!=", "1", ":", "raise", "exceptions", ".", "ArgumentError", "(", "\"More than 1 price was found or no \"", "\"prices found\"", ")", "price", "=", "result", "[", "'prices'", "]", "if", "order", "[", "'hourly'", "]", ":", "total", "=", "float", "(", "price", "[", "0", "]", ".", "get", "(", "'hourlyRecurringFee'", ",", "0.0", ")", ")", "else", ":", "total", "=", "float", "(", "price", "[", "0", "]", ".", "get", "(", "'recurringFee'", ",", "0.0", ")", ")", "if", "order", "[", "'hourly'", "]", ":", "table", ".", "add_row", "(", "[", "'Total hourly cost'", ",", "\"%.2f\"", "%", "total", "]", ")", "else", ":", "table", ".", "add_row", "(", "[", "'Total monthly cost'", ",", "\"%.2f\"", "%", "total", "]", ")", "output", "=", "[", "]", "output", ".", "append", "(", "table", ")", "output", ".", "append", "(", "formatting", ".", "FormattedItem", "(", "''", ",", "' -- ! Prices reflected here are retail and do not '", "'take account level discounts and are not guaranteed.'", ")", ")", "if", "kwargs", "[", "'export'", "]", ":", "export_file", "=", "kwargs", ".", "pop", "(", "'export'", ")", "template", ".", "export_to_template", "(", "export_file", ",", "kwargs", ",", "exclude", "=", "[", "'wait'", ",", "'verify'", "]", ")", "env", ".", "fout", "(", "'Successfully exported options to a template file.'", ")", "if", "do_create", ":", "if", "not", "env", ".", "skip_confirmations", "and", "not", "formatting", ".", "confirm", "(", "\"This action will incur charges on your account. \"", "\"Continue?\"", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborting dedicated host order.'", ")", "result", "=", "mgr", ".", "place_order", "(", "*", "*", "order", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "result", "[", "'orderId'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'created'", ",", "result", "[", "'orderDate'", "]", "]", ")", "output", ".", "append", "(", "table", ")", "env", ".", "fout", "(", "output", ")" ]
Order/create a dedicated host.
[ "Order", "/", "create", "a", "dedicated", "host", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/create.py#L49-L114
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/group_add.py#L28-L41
softlayer/softlayer-python
SoftLayer/CLI/loadbal/routing_methods.py
cli
def cli(env): """List routing types.""" mgr = SoftLayer.LoadBalancerManager(env.client) routing_methods = mgr.get_routing_methods() table = formatting.KeyValueTable(['ID', 'Name']) table.align['ID'] = 'l' table.align['Name'] = 'l' table.sortby = 'ID' for routing_method in routing_methods: table.add_row([routing_method['id'], routing_method['name']]) env.fout(table)
python
def cli(env): mgr = SoftLayer.LoadBalancerManager(env.client) routing_methods = mgr.get_routing_methods() table = formatting.KeyValueTable(['ID', 'Name']) table.align['ID'] = 'l' table.align['Name'] = 'l' table.sortby = 'ID' for routing_method in routing_methods: table.add_row([routing_method['id'], routing_method['name']]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "routing_methods", "=", "mgr", ".", "get_routing_methods", "(", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'ID'", ",", "'Name'", "]", ")", "table", ".", "align", "[", "'ID'", "]", "=", "'l'", "table", ".", "align", "[", "'Name'", "]", "=", "'l'", "table", ".", "sortby", "=", "'ID'", "for", "routing_method", "in", "routing_methods", ":", "table", ".", "add_row", "(", "[", "routing_method", "[", "'id'", "]", ",", "routing_method", "[", "'name'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List routing types.
[ "List", "routing", "types", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/routing_methods.py#L13-L25
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/cancel_guests.py#L16-L43
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/list.py#L66-L81
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): 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 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/duplicate.py#L56-L88
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): manager = SoftLayer.IPSECManager(env.client) 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 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/subnet/remove.py#L25-L51
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/list.py#L15-L38
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/detail.py#L14-L73
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_add.py#L43-L90
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/cancel.py#L16-L29
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): 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", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/preset_list.py#L20-L50
softlayer/softlayer-python
SoftLayer/CLI/user/permissions.py
cli
def cli(env, identifier): """User Permissions. TODO change to list all permissions, and which users have them""" mgr = SoftLayer.UserManager(env.client) user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username') object_mask = "mask[id, permissions, isMasterUserFlag, roles]" user = mgr.get_user(user_id, object_mask) all_permissions = mgr.get_all_permissions() user_permissions = perms_to_dict(user['permissions']) if user['isMasterUserFlag']: click.secho('This account is the Master User and has all permissions enabled', fg='green') env.fout(roles_table(user)) env.fout(permission_table(user_permissions, all_permissions))
python
def cli(env, identifier): mgr = SoftLayer.UserManager(env.client) user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username') object_mask = "mask[id, permissions, isMasterUserFlag, roles]" user = mgr.get_user(user_id, object_mask) all_permissions = mgr.get_all_permissions() user_permissions = perms_to_dict(user['permissions']) if user['isMasterUserFlag']: click.secho('This account is the Master User and has all permissions enabled', fg='green') env.fout(roles_table(user)) env.fout(permission_table(user_permissions, all_permissions))
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "UserManager", "(", "env", ".", "client", ")", "user_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'username'", ")", "object_mask", "=", "\"mask[id, permissions, isMasterUserFlag, roles]\"", "user", "=", "mgr", ".", "get_user", "(", "user_id", ",", "object_mask", ")", "all_permissions", "=", "mgr", ".", "get_all_permissions", "(", ")", "user_permissions", "=", "perms_to_dict", "(", "user", "[", "'permissions'", "]", ")", "if", "user", "[", "'isMasterUserFlag'", "]", ":", "click", ".", "secho", "(", "'This account is the Master User and has all permissions enabled'", ",", "fg", "=", "'green'", ")", "env", ".", "fout", "(", "roles_table", "(", "user", ")", ")", "env", ".", "fout", "(", "permission_table", "(", "user_permissions", ",", "all_permissions", ")", ")" ]
User Permissions. TODO change to list all permissions, and which users have them
[ "User", "Permissions", ".", "TODO", "change", "to", "list", "all", "permissions", "and", "which", "users", "have", "them" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/permissions.py#L13-L28
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): 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" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/permissions.py#L39-L49