repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
AoiKuiyuyou/AoikLiveReload
src/aoiklivereload/demo/flask_demo.py
main
def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `demo` directory's absolute path os.path.dirname( # This file's absolute path os.path.abspath(__file__) ) ) ) # If the `src` directory path is not in `sys.path` if src_path not in sys.path: # Add to `sys.path`. # # This aims to save user setting PYTHONPATH when running this demo. # sys.path.append(src_path) # Import reloader class from aoiklivereload import LiveReloader # Create reloader reloader = LiveReloader() # Start watcher thread reloader.start_watcher_thread() # Server host server_host = '0.0.0.0' # Server port server_port = 8000 # Get message msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format( server_host, server_port ) # Print message print(msg) # Create Flask app flask_app = flask.Flask(__name__) # Create request handler @flask_app.route('/') def hello_handler(): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return 'hello' # Run server flask_app.run( host=server_host, port=server_port, # Disable Flask's reloader debug=False, ) # If have `KeyboardInterrupt` except KeyboardInterrupt: # Not treat as error pass
python
def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `demo` directory's absolute path os.path.dirname( # This file's absolute path os.path.abspath(__file__) ) ) ) # If the `src` directory path is not in `sys.path` if src_path not in sys.path: # Add to `sys.path`. # # This aims to save user setting PYTHONPATH when running this demo. # sys.path.append(src_path) # Import reloader class from aoiklivereload import LiveReloader # Create reloader reloader = LiveReloader() # Start watcher thread reloader.start_watcher_thread() # Server host server_host = '0.0.0.0' # Server port server_port = 8000 # Get message msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format( server_host, server_port ) # Print message print(msg) # Create Flask app flask_app = flask.Flask(__name__) # Create request handler @flask_app.route('/') def hello_handler(): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return 'hello' # Run server flask_app.run( host=server_host, port=server_port, # Disable Flask's reloader debug=False, ) # If have `KeyboardInterrupt` except KeyboardInterrupt: # Not treat as error pass
[ "def", "main", "(", ")", ":", "try", ":", "# Get the `src` directory's absolute path", "src_path", "=", "os", ".", "path", ".", "dirname", "(", "# `aoiklivereload` directory's absolute path", "os", ".", "path", ".", "dirname", "(", "# `demo` directory's absolute path", "os", ".", "path", ".", "dirname", "(", "# This file's absolute path", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ")", ")", "# If the `src` directory path is not in `sys.path`", "if", "src_path", "not", "in", "sys", ".", "path", ":", "# Add to `sys.path`.", "#", "# This aims to save user setting PYTHONPATH when running this demo.", "#", "sys", ".", "path", ".", "append", "(", "src_path", ")", "# Import reloader class", "from", "aoiklivereload", "import", "LiveReloader", "# Create reloader", "reloader", "=", "LiveReloader", "(", ")", "# Start watcher thread", "reloader", ".", "start_watcher_thread", "(", ")", "# Server host", "server_host", "=", "'0.0.0.0'", "# Server port", "server_port", "=", "8000", "# Get message", "msg", "=", "'# ----- Run server -----\\nHost: {}\\nPort: {}'", ".", "format", "(", "server_host", ",", "server_port", ")", "# Print message", "print", "(", "msg", ")", "# Create Flask app", "flask_app", "=", "flask", ".", "Flask", "(", "__name__", ")", "# Create request handler", "@", "flask_app", ".", "route", "(", "'/'", ")", "def", "hello_handler", "(", ")", ":", "# pylint: disable=unused-variable", "\"\"\"\n Request handler.\n\n :return:\n Response body.\n \"\"\"", "# Return response body", "return", "'hello'", "# Run server", "flask_app", ".", "run", "(", "host", "=", "server_host", ",", "port", "=", "server_port", ",", "# Disable Flask's reloader", "debug", "=", "False", ",", ")", "# If have `KeyboardInterrupt`", "except", "KeyboardInterrupt", ":", "# Not treat as error", "pass" ]
Main function. :return: None.
[ "Main", "function", "." ]
0d5adb12118a33749e6690a8165fdb769cff7d5c
https://github.com/AoiKuiyuyou/AoikLiveReload/blob/0d5adb12118a33749e6690a8165fdb769cff7d5c/src/aoiklivereload/demo/flask_demo.py#L15-L92
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
get_excel_workbook
def get_excel_workbook(api_data, result_info_key, identifier_keys): """Generates an Excel workbook object given api_data returned by the Analytics API Args: api_data: Analytics API data as a list of dicts (one per identifier) result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: raw excel file data """ cleaned_data = [] for item_data in api_data: result_info = item_data.pop(result_info_key, {}) cleaned_item_data = {} if 'meta' in item_data: meta = item_data.pop('meta') cleaned_item_data['meta'] = meta for key in item_data: cleaned_item_data[key] = item_data[key]['result'] cleaned_item_data[result_info_key] = result_info cleaned_data.append(cleaned_item_data) data_list = copy.deepcopy(cleaned_data) workbook = openpyxl.Workbook() write_worksheets(workbook, data_list, result_info_key, identifier_keys) return workbook
python
def get_excel_workbook(api_data, result_info_key, identifier_keys): """Generates an Excel workbook object given api_data returned by the Analytics API Args: api_data: Analytics API data as a list of dicts (one per identifier) result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: raw excel file data """ cleaned_data = [] for item_data in api_data: result_info = item_data.pop(result_info_key, {}) cleaned_item_data = {} if 'meta' in item_data: meta = item_data.pop('meta') cleaned_item_data['meta'] = meta for key in item_data: cleaned_item_data[key] = item_data[key]['result'] cleaned_item_data[result_info_key] = result_info cleaned_data.append(cleaned_item_data) data_list = copy.deepcopy(cleaned_data) workbook = openpyxl.Workbook() write_worksheets(workbook, data_list, result_info_key, identifier_keys) return workbook
[ "def", "get_excel_workbook", "(", "api_data", ",", "result_info_key", ",", "identifier_keys", ")", ":", "cleaned_data", "=", "[", "]", "for", "item_data", "in", "api_data", ":", "result_info", "=", "item_data", ".", "pop", "(", "result_info_key", ",", "{", "}", ")", "cleaned_item_data", "=", "{", "}", "if", "'meta'", "in", "item_data", ":", "meta", "=", "item_data", ".", "pop", "(", "'meta'", ")", "cleaned_item_data", "[", "'meta'", "]", "=", "meta", "for", "key", "in", "item_data", ":", "cleaned_item_data", "[", "key", "]", "=", "item_data", "[", "key", "]", "[", "'result'", "]", "cleaned_item_data", "[", "result_info_key", "]", "=", "result_info", "cleaned_data", ".", "append", "(", "cleaned_item_data", ")", "data_list", "=", "copy", ".", "deepcopy", "(", "cleaned_data", ")", "workbook", "=", "openpyxl", ".", "Workbook", "(", ")", "write_worksheets", "(", "workbook", ",", "data_list", ",", "result_info_key", ",", "identifier_keys", ")", "return", "workbook" ]
Generates an Excel workbook object given api_data returned by the Analytics API Args: api_data: Analytics API data as a list of dicts (one per identifier) result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: raw excel file data
[ "Generates", "an", "Excel", "workbook", "object", "given", "api_data", "returned", "by", "the", "Analytics", "API" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L30-L67
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
write_worksheets
def write_worksheets(workbook, data_list, result_info_key, identifier_keys): """Writes rest of the worksheets to workbook. Args: workbook: workbook to write into data_list: Analytics API data as a list of dicts result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) """ # we can use the first item to figure out the worksheet keys worksheet_keys = get_worksheet_keys(data_list[0], result_info_key) for key in worksheet_keys: title = key.split('/')[1] title = utilities.convert_snake_to_title_case(title) title = KEY_TO_WORKSHEET_MAP.get(title, title) if key == 'property/nod': # the property/nod endpoint needs to be split into two worksheets create_property_nod_worksheets(workbook, data_list, result_info_key, identifier_keys) else: # all other endpoints are written to a single worksheet # Maximum 31 characters allowed in sheet title worksheet = workbook.create_sheet(title=title[:31]) processed_data = process_data(key, data_list, result_info_key, identifier_keys) write_data(worksheet, processed_data) # remove the first, unused empty sheet workbook.remove_sheet(workbook.active)
python
def write_worksheets(workbook, data_list, result_info_key, identifier_keys): """Writes rest of the worksheets to workbook. Args: workbook: workbook to write into data_list: Analytics API data as a list of dicts result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) """ # we can use the first item to figure out the worksheet keys worksheet_keys = get_worksheet_keys(data_list[0], result_info_key) for key in worksheet_keys: title = key.split('/')[1] title = utilities.convert_snake_to_title_case(title) title = KEY_TO_WORKSHEET_MAP.get(title, title) if key == 'property/nod': # the property/nod endpoint needs to be split into two worksheets create_property_nod_worksheets(workbook, data_list, result_info_key, identifier_keys) else: # all other endpoints are written to a single worksheet # Maximum 31 characters allowed in sheet title worksheet = workbook.create_sheet(title=title[:31]) processed_data = process_data(key, data_list, result_info_key, identifier_keys) write_data(worksheet, processed_data) # remove the first, unused empty sheet workbook.remove_sheet(workbook.active)
[ "def", "write_worksheets", "(", "workbook", ",", "data_list", ",", "result_info_key", ",", "identifier_keys", ")", ":", "# we can use the first item to figure out the worksheet keys", "worksheet_keys", "=", "get_worksheet_keys", "(", "data_list", "[", "0", "]", ",", "result_info_key", ")", "for", "key", "in", "worksheet_keys", ":", "title", "=", "key", ".", "split", "(", "'/'", ")", "[", "1", "]", "title", "=", "utilities", ".", "convert_snake_to_title_case", "(", "title", ")", "title", "=", "KEY_TO_WORKSHEET_MAP", ".", "get", "(", "title", ",", "title", ")", "if", "key", "==", "'property/nod'", ":", "# the property/nod endpoint needs to be split into two worksheets", "create_property_nod_worksheets", "(", "workbook", ",", "data_list", ",", "result_info_key", ",", "identifier_keys", ")", "else", ":", "# all other endpoints are written to a single worksheet", "# Maximum 31 characters allowed in sheet title", "worksheet", "=", "workbook", ".", "create_sheet", "(", "title", "=", "title", "[", ":", "31", "]", ")", "processed_data", "=", "process_data", "(", "key", ",", "data_list", ",", "result_info_key", ",", "identifier_keys", ")", "write_data", "(", "worksheet", ",", "processed_data", ")", "# remove the first, unused empty sheet", "workbook", ".", "remove_sheet", "(", "workbook", ".", "active", ")" ]
Writes rest of the worksheets to workbook. Args: workbook: workbook to write into data_list: Analytics API data as a list of dicts result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc)
[ "Writes", "rest", "of", "the", "worksheets", "to", "workbook", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L70-L106
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
create_property_nod_worksheets
def create_property_nod_worksheets(workbook, data_list, result_info_key, identifier_keys): """Creates two worksheets out of the property/nod data because the data doesn't come flat enough to make sense on one sheet. Args: workbook: the main workbook to add the sheets to data_list: the main list of data result_info_key: the key in api_data dicts that contains the data results Should always be 'address_info' for property/nod identifier_keys: the list of keys used as requested identifiers (address, zipcode, city, state, etc) """ nod_details_list = [] nod_default_history_list = [] for prop_data in data_list: nod_data = prop_data['property/nod'] if nod_data is None: nod_data = {} default_history_data = nod_data.pop('default_history', []) _set_identifier_fields(nod_data, prop_data, result_info_key, identifier_keys) nod_details_list.append(nod_data) for item in default_history_data: _set_identifier_fields(item, prop_data, result_info_key, identifier_keys) nod_default_history_list.append(item) worksheet = workbook.create_sheet(title='NOD Details') write_data(worksheet, nod_details_list) worksheet = workbook.create_sheet(title='NOD Default History') write_data(worksheet, nod_default_history_list)
python
def create_property_nod_worksheets(workbook, data_list, result_info_key, identifier_keys): """Creates two worksheets out of the property/nod data because the data doesn't come flat enough to make sense on one sheet. Args: workbook: the main workbook to add the sheets to data_list: the main list of data result_info_key: the key in api_data dicts that contains the data results Should always be 'address_info' for property/nod identifier_keys: the list of keys used as requested identifiers (address, zipcode, city, state, etc) """ nod_details_list = [] nod_default_history_list = [] for prop_data in data_list: nod_data = prop_data['property/nod'] if nod_data is None: nod_data = {} default_history_data = nod_data.pop('default_history', []) _set_identifier_fields(nod_data, prop_data, result_info_key, identifier_keys) nod_details_list.append(nod_data) for item in default_history_data: _set_identifier_fields(item, prop_data, result_info_key, identifier_keys) nod_default_history_list.append(item) worksheet = workbook.create_sheet(title='NOD Details') write_data(worksheet, nod_details_list) worksheet = workbook.create_sheet(title='NOD Default History') write_data(worksheet, nod_default_history_list)
[ "def", "create_property_nod_worksheets", "(", "workbook", ",", "data_list", ",", "result_info_key", ",", "identifier_keys", ")", ":", "nod_details_list", "=", "[", "]", "nod_default_history_list", "=", "[", "]", "for", "prop_data", "in", "data_list", ":", "nod_data", "=", "prop_data", "[", "'property/nod'", "]", "if", "nod_data", "is", "None", ":", "nod_data", "=", "{", "}", "default_history_data", "=", "nod_data", ".", "pop", "(", "'default_history'", ",", "[", "]", ")", "_set_identifier_fields", "(", "nod_data", ",", "prop_data", ",", "result_info_key", ",", "identifier_keys", ")", "nod_details_list", ".", "append", "(", "nod_data", ")", "for", "item", "in", "default_history_data", ":", "_set_identifier_fields", "(", "item", ",", "prop_data", ",", "result_info_key", ",", "identifier_keys", ")", "nod_default_history_list", ".", "append", "(", "item", ")", "worksheet", "=", "workbook", ".", "create_sheet", "(", "title", "=", "'NOD Details'", ")", "write_data", "(", "worksheet", ",", "nod_details_list", ")", "worksheet", "=", "workbook", ".", "create_sheet", "(", "title", "=", "'NOD Default History'", ")", "write_data", "(", "worksheet", ",", "nod_default_history_list", ")" ]
Creates two worksheets out of the property/nod data because the data doesn't come flat enough to make sense on one sheet. Args: workbook: the main workbook to add the sheets to data_list: the main list of data result_info_key: the key in api_data dicts that contains the data results Should always be 'address_info' for property/nod identifier_keys: the list of keys used as requested identifiers (address, zipcode, city, state, etc)
[ "Creates", "two", "worksheets", "out", "of", "the", "property", "/", "nod", "data", "because", "the", "data", "doesn", "t", "come", "flat", "enough", "to", "make", "sense", "on", "one", "sheet", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L109-L144
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
get_worksheet_keys
def get_worksheet_keys(data_dict, result_info_key): """Gets sorted keys from the dict, ignoring result_info_key and 'meta' key Args: data_dict: dict to pull keys from Returns: list of keys in the dict other than the result_info_key """ keys = set(data_dict.keys()) keys.remove(result_info_key) if 'meta' in keys: keys.remove('meta') return sorted(keys)
python
def get_worksheet_keys(data_dict, result_info_key): """Gets sorted keys from the dict, ignoring result_info_key and 'meta' key Args: data_dict: dict to pull keys from Returns: list of keys in the dict other than the result_info_key """ keys = set(data_dict.keys()) keys.remove(result_info_key) if 'meta' in keys: keys.remove('meta') return sorted(keys)
[ "def", "get_worksheet_keys", "(", "data_dict", ",", "result_info_key", ")", ":", "keys", "=", "set", "(", "data_dict", ".", "keys", "(", ")", ")", "keys", ".", "remove", "(", "result_info_key", ")", "if", "'meta'", "in", "keys", ":", "keys", ".", "remove", "(", "'meta'", ")", "return", "sorted", "(", "keys", ")" ]
Gets sorted keys from the dict, ignoring result_info_key and 'meta' key Args: data_dict: dict to pull keys from Returns: list of keys in the dict other than the result_info_key
[ "Gets", "sorted", "keys", "from", "the", "dict", "ignoring", "result_info_key", "and", "meta", "key", "Args", ":", "data_dict", ":", "dict", "to", "pull", "keys", "from" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L147-L159
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
get_keys
def get_keys(data_list, leading_columns=LEADING_COLUMNS): """Gets all possible keys from a list of dicts, sorting by leading_columns first Args: data_list: list of dicts to pull keys from leading_columns: list of keys to put first in the result Returns: list of keys to be included as columns in excel worksheet """ all_keys = set().union(*(list(d.keys()) for d in data_list)) leading_keys = [] for key in leading_columns: if key not in all_keys: continue leading_keys.append(key) all_keys.remove(key) return leading_keys + sorted(all_keys)
python
def get_keys(data_list, leading_columns=LEADING_COLUMNS): """Gets all possible keys from a list of dicts, sorting by leading_columns first Args: data_list: list of dicts to pull keys from leading_columns: list of keys to put first in the result Returns: list of keys to be included as columns in excel worksheet """ all_keys = set().union(*(list(d.keys()) for d in data_list)) leading_keys = [] for key in leading_columns: if key not in all_keys: continue leading_keys.append(key) all_keys.remove(key) return leading_keys + sorted(all_keys)
[ "def", "get_keys", "(", "data_list", ",", "leading_columns", "=", "LEADING_COLUMNS", ")", ":", "all_keys", "=", "set", "(", ")", ".", "union", "(", "*", "(", "list", "(", "d", ".", "keys", "(", ")", ")", "for", "d", "in", "data_list", ")", ")", "leading_keys", "=", "[", "]", "for", "key", "in", "leading_columns", ":", "if", "key", "not", "in", "all_keys", ":", "continue", "leading_keys", ".", "append", "(", "key", ")", "all_keys", ".", "remove", "(", "key", ")", "return", "leading_keys", "+", "sorted", "(", "all_keys", ")" ]
Gets all possible keys from a list of dicts, sorting by leading_columns first Args: data_list: list of dicts to pull keys from leading_columns: list of keys to put first in the result Returns: list of keys to be included as columns in excel worksheet
[ "Gets", "all", "possible", "keys", "from", "a", "list", "of", "dicts", "sorting", "by", "leading_columns", "first" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L162-L182
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
write_data
def write_data(worksheet, data): """Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written """ if not data: return if isinstance(data, list): rows = data else: rows = [data] if isinstance(rows[0], dict): keys = get_keys(rows) worksheet.append([utilities.convert_snake_to_title_case(key) for key in keys]) for row in rows: values = [get_value_from_row(row, key) for key in keys] worksheet.append(values) elif isinstance(rows[0], list): for row in rows: values = [utilities.normalize_cell_value(value) for value in row] worksheet.append(values) else: for row in rows: worksheet.append([utilities.normalize_cell_value(row)])
python
def write_data(worksheet, data): """Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written """ if not data: return if isinstance(data, list): rows = data else: rows = [data] if isinstance(rows[0], dict): keys = get_keys(rows) worksheet.append([utilities.convert_snake_to_title_case(key) for key in keys]) for row in rows: values = [get_value_from_row(row, key) for key in keys] worksheet.append(values) elif isinstance(rows[0], list): for row in rows: values = [utilities.normalize_cell_value(value) for value in row] worksheet.append(values) else: for row in rows: worksheet.append([utilities.normalize_cell_value(row)])
[ "def", "write_data", "(", "worksheet", ",", "data", ")", ":", "if", "not", "data", ":", "return", "if", "isinstance", "(", "data", ",", "list", ")", ":", "rows", "=", "data", "else", ":", "rows", "=", "[", "data", "]", "if", "isinstance", "(", "rows", "[", "0", "]", ",", "dict", ")", ":", "keys", "=", "get_keys", "(", "rows", ")", "worksheet", ".", "append", "(", "[", "utilities", ".", "convert_snake_to_title_case", "(", "key", ")", "for", "key", "in", "keys", "]", ")", "for", "row", "in", "rows", ":", "values", "=", "[", "get_value_from_row", "(", "row", ",", "key", ")", "for", "key", "in", "keys", "]", "worksheet", ".", "append", "(", "values", ")", "elif", "isinstance", "(", "rows", "[", "0", "]", ",", "list", ")", ":", "for", "row", "in", "rows", ":", "values", "=", "[", "utilities", ".", "normalize_cell_value", "(", "value", ")", "for", "value", "in", "row", "]", "worksheet", ".", "append", "(", "values", ")", "else", ":", "for", "row", "in", "rows", ":", "worksheet", ".", "append", "(", "[", "utilities", ".", "normalize_cell_value", "(", "row", ")", "]", ")" ]
Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written
[ "Writes", "data", "into", "worksheet", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L185-L212
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
process_data
def process_data(key, data_list, result_info_key, identifier_keys): """ Given a key as the endpoint name, pulls the data for that endpoint out of the data_list for each address, processes the data into a more excel-friendly format and returns that data. Args: key: the endpoint name of the data to process data_list: the main data list to take the data from result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: A list of dicts (rows) to be written to a worksheet """ master_data = [] for item_data in data_list: data = item_data[key] if data is None: current_item_data = {} else: if key == 'property/value': current_item_data = data['value'] elif key == 'property/details': top_level_keys = ['property', 'assessment'] current_item_data = flatten_top_level_keys(data, top_level_keys) elif key == 'property/school': current_item_data = data['school'] school_list = [] for school_type_key in current_item_data: schools = current_item_data[school_type_key] for school in schools: school['school_type'] = school_type_key school['school_address'] = school['address'] school['school_zipcode'] = school['zipcode'] school_list.append(school) current_item_data = school_list elif key == 'property/value_forecast': current_item_data = {} for month_key in data: current_item_data[month_key] = data[month_key]['value'] elif key in ['property/value_within_block', 'property/rental_value_within_block']: current_item_data = flatten_top_level_keys(data, [ 'housecanary_value_percentile_range', 'housecanary_value_sqft_percentile_range', 'client_value_percentile_range', 'client_value_sqft_percentile_range' ]) elif key in ['property/zip_details', 'zip/details']: top_level_keys = ['multi_family', 'single_family'] current_item_data = flatten_top_level_keys(data, top_level_keys) else: current_item_data = data if isinstance(current_item_data, dict): _set_identifier_fields(current_item_data, item_data, result_info_key, identifier_keys) master_data.append(current_item_data) else: # it's a list for item in current_item_data: _set_identifier_fields(item, item_data, result_info_key, identifier_keys) master_data.extend(current_item_data) return master_data
python
def process_data(key, data_list, result_info_key, identifier_keys): """ Given a key as the endpoint name, pulls the data for that endpoint out of the data_list for each address, processes the data into a more excel-friendly format and returns that data. Args: key: the endpoint name of the data to process data_list: the main data list to take the data from result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: A list of dicts (rows) to be written to a worksheet """ master_data = [] for item_data in data_list: data = item_data[key] if data is None: current_item_data = {} else: if key == 'property/value': current_item_data = data['value'] elif key == 'property/details': top_level_keys = ['property', 'assessment'] current_item_data = flatten_top_level_keys(data, top_level_keys) elif key == 'property/school': current_item_data = data['school'] school_list = [] for school_type_key in current_item_data: schools = current_item_data[school_type_key] for school in schools: school['school_type'] = school_type_key school['school_address'] = school['address'] school['school_zipcode'] = school['zipcode'] school_list.append(school) current_item_data = school_list elif key == 'property/value_forecast': current_item_data = {} for month_key in data: current_item_data[month_key] = data[month_key]['value'] elif key in ['property/value_within_block', 'property/rental_value_within_block']: current_item_data = flatten_top_level_keys(data, [ 'housecanary_value_percentile_range', 'housecanary_value_sqft_percentile_range', 'client_value_percentile_range', 'client_value_sqft_percentile_range' ]) elif key in ['property/zip_details', 'zip/details']: top_level_keys = ['multi_family', 'single_family'] current_item_data = flatten_top_level_keys(data, top_level_keys) else: current_item_data = data if isinstance(current_item_data, dict): _set_identifier_fields(current_item_data, item_data, result_info_key, identifier_keys) master_data.append(current_item_data) else: # it's a list for item in current_item_data: _set_identifier_fields(item, item_data, result_info_key, identifier_keys) master_data.extend(current_item_data) return master_data
[ "def", "process_data", "(", "key", ",", "data_list", ",", "result_info_key", ",", "identifier_keys", ")", ":", "master_data", "=", "[", "]", "for", "item_data", "in", "data_list", ":", "data", "=", "item_data", "[", "key", "]", "if", "data", "is", "None", ":", "current_item_data", "=", "{", "}", "else", ":", "if", "key", "==", "'property/value'", ":", "current_item_data", "=", "data", "[", "'value'", "]", "elif", "key", "==", "'property/details'", ":", "top_level_keys", "=", "[", "'property'", ",", "'assessment'", "]", "current_item_data", "=", "flatten_top_level_keys", "(", "data", ",", "top_level_keys", ")", "elif", "key", "==", "'property/school'", ":", "current_item_data", "=", "data", "[", "'school'", "]", "school_list", "=", "[", "]", "for", "school_type_key", "in", "current_item_data", ":", "schools", "=", "current_item_data", "[", "school_type_key", "]", "for", "school", "in", "schools", ":", "school", "[", "'school_type'", "]", "=", "school_type_key", "school", "[", "'school_address'", "]", "=", "school", "[", "'address'", "]", "school", "[", "'school_zipcode'", "]", "=", "school", "[", "'zipcode'", "]", "school_list", ".", "append", "(", "school", ")", "current_item_data", "=", "school_list", "elif", "key", "==", "'property/value_forecast'", ":", "current_item_data", "=", "{", "}", "for", "month_key", "in", "data", ":", "current_item_data", "[", "month_key", "]", "=", "data", "[", "month_key", "]", "[", "'value'", "]", "elif", "key", "in", "[", "'property/value_within_block'", ",", "'property/rental_value_within_block'", "]", ":", "current_item_data", "=", "flatten_top_level_keys", "(", "data", ",", "[", "'housecanary_value_percentile_range'", ",", "'housecanary_value_sqft_percentile_range'", ",", "'client_value_percentile_range'", ",", "'client_value_sqft_percentile_range'", "]", ")", "elif", "key", "in", "[", "'property/zip_details'", ",", "'zip/details'", "]", ":", "top_level_keys", "=", "[", "'multi_family'", ",", "'single_family'", "]", "current_item_data", "=", "flatten_top_level_keys", "(", "data", ",", "top_level_keys", ")", "else", ":", "current_item_data", "=", "data", "if", "isinstance", "(", "current_item_data", ",", "dict", ")", ":", "_set_identifier_fields", "(", "current_item_data", ",", "item_data", ",", "result_info_key", ",", "identifier_keys", ")", "master_data", ".", "append", "(", "current_item_data", ")", "else", ":", "# it's a list", "for", "item", "in", "current_item_data", ":", "_set_identifier_fields", "(", "item", ",", "item_data", ",", "result_info_key", ",", "identifier_keys", ")", "master_data", ".", "extend", "(", "current_item_data", ")", "return", "master_data" ]
Given a key as the endpoint name, pulls the data for that endpoint out of the data_list for each address, processes the data into a more excel-friendly format and returns that data. Args: key: the endpoint name of the data to process data_list: the main data list to take the data from result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: A list of dicts (rows) to be written to a worksheet
[ "Given", "a", "key", "as", "the", "endpoint", "name", "pulls", "the", "data", "for", "that", "endpoint", "out", "of", "the", "data_list", "for", "each", "address", "processes", "the", "data", "into", "a", "more", "excel", "-", "friendly", "format", "and", "returns", "that", "data", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L222-L297
train
housecanary/hc-api-python
housecanary/excel/analytics_data_excel.py
flatten_top_level_keys
def flatten_top_level_keys(data, top_level_keys): """ Helper method to flatten a nested dict of dicts (one level) Example: {'a': {'b': 'bbb'}} becomes {'a_-_b': 'bbb'} The separator '_-_' gets formatted later for the column headers Args: data: the dict to flatten top_level_keys: a list of the top level keys to flatten ('a' in the example above) """ flattened_data = {} for top_level_key in top_level_keys: if data[top_level_key] is None: flattened_data[top_level_key] = None else: for key in data[top_level_key]: flattened_data['{}_-_{}'.format(top_level_key, key)] = data[top_level_key][key] return flattened_data
python
def flatten_top_level_keys(data, top_level_keys): """ Helper method to flatten a nested dict of dicts (one level) Example: {'a': {'b': 'bbb'}} becomes {'a_-_b': 'bbb'} The separator '_-_' gets formatted later for the column headers Args: data: the dict to flatten top_level_keys: a list of the top level keys to flatten ('a' in the example above) """ flattened_data = {} for top_level_key in top_level_keys: if data[top_level_key] is None: flattened_data[top_level_key] = None else: for key in data[top_level_key]: flattened_data['{}_-_{}'.format(top_level_key, key)] = data[top_level_key][key] return flattened_data
[ "def", "flatten_top_level_keys", "(", "data", ",", "top_level_keys", ")", ":", "flattened_data", "=", "{", "}", "for", "top_level_key", "in", "top_level_keys", ":", "if", "data", "[", "top_level_key", "]", "is", "None", ":", "flattened_data", "[", "top_level_key", "]", "=", "None", "else", ":", "for", "key", "in", "data", "[", "top_level_key", "]", ":", "flattened_data", "[", "'{}_-_{}'", ".", "format", "(", "top_level_key", ",", "key", ")", "]", "=", "data", "[", "top_level_key", "]", "[", "key", "]", "return", "flattened_data" ]
Helper method to flatten a nested dict of dicts (one level) Example: {'a': {'b': 'bbb'}} becomes {'a_-_b': 'bbb'} The separator '_-_' gets formatted later for the column headers Args: data: the dict to flatten top_level_keys: a list of the top level keys to flatten ('a' in the example above)
[ "Helper", "method", "to", "flatten", "a", "nested", "dict", "of", "dicts", "(", "one", "level", ")" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L311-L332
train
mozilla-services/python-dockerflow
src/dockerflow/django/checks.py
check_database_connected
def check_database_connected(app_configs, **kwargs): """ A Django check to see if connecting to the configured default database backend succeeds. """ errors = [] try: connection.ensure_connection() except OperationalError as e: msg = 'Could not connect to database: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_DATABASE)) except ImproperlyConfigured as e: msg = 'Datbase misconfigured: "{!s}"'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_DATABASE)) else: if not connection.is_usable(): errors.append(checks.Error('Database connection is not usable', id=health.ERROR_UNUSABLE_DATABASE)) return errors
python
def check_database_connected(app_configs, **kwargs): """ A Django check to see if connecting to the configured default database backend succeeds. """ errors = [] try: connection.ensure_connection() except OperationalError as e: msg = 'Could not connect to database: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_DATABASE)) except ImproperlyConfigured as e: msg = 'Datbase misconfigured: "{!s}"'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_DATABASE)) else: if not connection.is_usable(): errors.append(checks.Error('Database connection is not usable', id=health.ERROR_UNUSABLE_DATABASE)) return errors
[ "def", "check_database_connected", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "try", ":", "connection", ".", "ensure_connection", "(", ")", "except", "OperationalError", "as", "e", ":", "msg", "=", "'Could not connect to database: {!s}'", ".", "format", "(", "e", ")", "errors", ".", "append", "(", "checks", ".", "Error", "(", "msg", ",", "id", "=", "health", ".", "ERROR_CANNOT_CONNECT_DATABASE", ")", ")", "except", "ImproperlyConfigured", "as", "e", ":", "msg", "=", "'Datbase misconfigured: \"{!s}\"'", ".", "format", "(", "e", ")", "errors", ".", "append", "(", "checks", ".", "Error", "(", "msg", ",", "id", "=", "health", ".", "ERROR_MISCONFIGURED_DATABASE", ")", ")", "else", ":", "if", "not", "connection", ".", "is_usable", "(", ")", ":", "errors", ".", "append", "(", "checks", ".", "Error", "(", "'Database connection is not usable'", ",", "id", "=", "health", ".", "ERROR_UNUSABLE_DATABASE", ")", ")", "return", "errors" ]
A Django check to see if connecting to the configured default database backend succeeds.
[ "A", "Django", "check", "to", "see", "if", "connecting", "to", "the", "configured", "default", "database", "backend", "succeeds", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L26-L48
train
mozilla-services/python-dockerflow
src/dockerflow/django/checks.py
check_migrations_applied
def check_migrations_applied(app_configs, **kwargs): """ A Django check to see if all migrations have been applied correctly. """ from django.db.migrations.loader import MigrationLoader errors = [] # Load migrations from disk/DB try: loader = MigrationLoader(connection, ignore_no_migrations=True) except (ImproperlyConfigured, ProgrammingError, OperationalError): msg = "Can't connect to database to check migrations" return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)] if app_configs: app_labels = [app.label for app in app_configs] else: app_labels = loader.migrated_apps for node, migration in loader.graph.nodes.items(): if migration.app_label not in app_labels: continue if node not in loader.applied_migrations: msg = 'Unapplied migration {}'.format(migration) # NB: This *must* be a Warning, not an Error, because Errors # prevent migrations from being run. errors.append(checks.Warning(msg, id=health.WARNING_UNAPPLIED_MIGRATION)) return errors
python
def check_migrations_applied(app_configs, **kwargs): """ A Django check to see if all migrations have been applied correctly. """ from django.db.migrations.loader import MigrationLoader errors = [] # Load migrations from disk/DB try: loader = MigrationLoader(connection, ignore_no_migrations=True) except (ImproperlyConfigured, ProgrammingError, OperationalError): msg = "Can't connect to database to check migrations" return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)] if app_configs: app_labels = [app.label for app in app_configs] else: app_labels = loader.migrated_apps for node, migration in loader.graph.nodes.items(): if migration.app_label not in app_labels: continue if node not in loader.applied_migrations: msg = 'Unapplied migration {}'.format(migration) # NB: This *must* be a Warning, not an Error, because Errors # prevent migrations from being run. errors.append(checks.Warning(msg, id=health.WARNING_UNAPPLIED_MIGRATION)) return errors
[ "def", "check_migrations_applied", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "from", "django", ".", "db", ".", "migrations", ".", "loader", "import", "MigrationLoader", "errors", "=", "[", "]", "# Load migrations from disk/DB", "try", ":", "loader", "=", "MigrationLoader", "(", "connection", ",", "ignore_no_migrations", "=", "True", ")", "except", "(", "ImproperlyConfigured", ",", "ProgrammingError", ",", "OperationalError", ")", ":", "msg", "=", "\"Can't connect to database to check migrations\"", "return", "[", "checks", ".", "Info", "(", "msg", ",", "id", "=", "health", ".", "INFO_CANT_CHECK_MIGRATIONS", ")", "]", "if", "app_configs", ":", "app_labels", "=", "[", "app", ".", "label", "for", "app", "in", "app_configs", "]", "else", ":", "app_labels", "=", "loader", ".", "migrated_apps", "for", "node", ",", "migration", "in", "loader", ".", "graph", ".", "nodes", ".", "items", "(", ")", ":", "if", "migration", ".", "app_label", "not", "in", "app_labels", ":", "continue", "if", "node", "not", "in", "loader", ".", "applied_migrations", ":", "msg", "=", "'Unapplied migration {}'", ".", "format", "(", "migration", ")", "# NB: This *must* be a Warning, not an Error, because Errors", "# prevent migrations from being run.", "errors", ".", "append", "(", "checks", ".", "Warning", "(", "msg", ",", "id", "=", "health", ".", "WARNING_UNAPPLIED_MIGRATION", ")", ")", "return", "errors" ]
A Django check to see if all migrations have been applied correctly.
[ "A", "Django", "check", "to", "see", "if", "all", "migrations", "have", "been", "applied", "correctly", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L51-L80
train
mozilla-services/python-dockerflow
src/dockerflow/django/checks.py
check_redis_connected
def check_redis_connected(app_configs, **kwargs): """ A Django check to connect to the default redis connection using ``django_redis.get_redis_connection`` and see if Redis responds to a ``PING`` command. """ import redis from django_redis import get_redis_connection errors = [] try: connection = get_redis_connection('default') except redis.ConnectionError as e: msg = 'Could not connect to redis: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS)) except NotImplementedError as e: msg = 'Redis client not available: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT)) except ImproperlyConfigured as e: msg = 'Redis misconfigured: "{!s}"'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS)) else: result = connection.ping() if not result: msg = 'Redis ping failed' errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED)) return errors
python
def check_redis_connected(app_configs, **kwargs): """ A Django check to connect to the default redis connection using ``django_redis.get_redis_connection`` and see if Redis responds to a ``PING`` command. """ import redis from django_redis import get_redis_connection errors = [] try: connection = get_redis_connection('default') except redis.ConnectionError as e: msg = 'Could not connect to redis: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS)) except NotImplementedError as e: msg = 'Redis client not available: {!s}'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT)) except ImproperlyConfigured as e: msg = 'Redis misconfigured: "{!s}"'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS)) else: result = connection.ping() if not result: msg = 'Redis ping failed' errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED)) return errors
[ "def", "check_redis_connected", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "import", "redis", "from", "django_redis", "import", "get_redis_connection", "errors", "=", "[", "]", "try", ":", "connection", "=", "get_redis_connection", "(", "'default'", ")", "except", "redis", ".", "ConnectionError", "as", "e", ":", "msg", "=", "'Could not connect to redis: {!s}'", ".", "format", "(", "e", ")", "errors", ".", "append", "(", "checks", ".", "Error", "(", "msg", ",", "id", "=", "health", ".", "ERROR_CANNOT_CONNECT_REDIS", ")", ")", "except", "NotImplementedError", "as", "e", ":", "msg", "=", "'Redis client not available: {!s}'", ".", "format", "(", "e", ")", "errors", ".", "append", "(", "checks", ".", "Error", "(", "msg", ",", "id", "=", "health", ".", "ERROR_MISSING_REDIS_CLIENT", ")", ")", "except", "ImproperlyConfigured", "as", "e", ":", "msg", "=", "'Redis misconfigured: \"{!s}\"'", ".", "format", "(", "e", ")", "errors", ".", "append", "(", "checks", ".", "Error", "(", "msg", ",", "id", "=", "health", ".", "ERROR_MISCONFIGURED_REDIS", ")", ")", "else", ":", "result", "=", "connection", ".", "ping", "(", ")", "if", "not", "result", ":", "msg", "=", "'Redis ping failed'", "errors", ".", "append", "(", "checks", ".", "Error", "(", "msg", ",", "id", "=", "health", ".", "ERROR_REDIS_PING_FAILED", ")", ")", "return", "errors" ]
A Django check to connect to the default redis connection using ``django_redis.get_redis_connection`` and see if Redis responds to a ``PING`` command.
[ "A", "Django", "check", "to", "connect", "to", "the", "default", "redis", "connection", "using", "django_redis", ".", "get_redis_connection", "and", "see", "if", "Redis", "responds", "to", "a", "PING", "command", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L83-L109
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/alarms.py
get_realtime_alarm
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_realtime_alarm('admin', auth.creds, auth.url) >>> type(real_time_alarm) <class 'list'> >>> assert 'faultDesc' in real_time_alarm[0] """ get_realtime_alarm_url = "/imcrs/fault/faultRealTime?operatorName=" + username f_url = url + get_realtime_alarm_url r = requests.get(f_url, auth=auth, headers=headers) try: realtime_alarm_list = (json.loads(r.text)) return realtime_alarm_list['faultRealTime']['faultRealTimeList'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_realtime_alarm: An Error has occured'
python
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_realtime_alarm('admin', auth.creds, auth.url) >>> type(real_time_alarm) <class 'list'> >>> assert 'faultDesc' in real_time_alarm[0] """ get_realtime_alarm_url = "/imcrs/fault/faultRealTime?operatorName=" + username f_url = url + get_realtime_alarm_url r = requests.get(f_url, auth=auth, headers=headers) try: realtime_alarm_list = (json.loads(r.text)) return realtime_alarm_list['faultRealTime']['faultRealTimeList'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_realtime_alarm: An Error has occured'
[ "def", "get_realtime_alarm", "(", "username", ",", "auth", ",", "url", ")", ":", "get_realtime_alarm_url", "=", "\"/imcrs/fault/faultRealTime?operatorName=\"", "+", "username", "f_url", "=", "url", "+", "get_realtime_alarm_url", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "try", ":", "realtime_alarm_list", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "return", "realtime_alarm_list", "[", "'faultRealTime'", "]", "[", "'faultRealTimeList'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' get_realtime_alarm: An Error has occured'" ]
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_realtime_alarm('admin', auth.creds, auth.url) >>> type(real_time_alarm) <class 'list'> >>> assert 'faultDesc' in real_time_alarm[0]
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "RealTime", "Alarms", "from", "HP", "IMC", "RESTFUL", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/alarms.py#L63-L100
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/alarms.py
get_alarms
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> type(all_alarms) <class 'list'> >>> assert 'ackStatus' in all_alarms[0] [{'OID': '1.3.6.1.4.1.11.2.14.11.15.2.75.5.3.1.6.7', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '1001', 'alarmCategoryDesc': 'Wireless Device Alarm', 'alarmDesc': 'The device(MAC Address: F4 B7 E2 95 A0 CD) is detected to be flooding the network. Attack Frame Type: Probe Request.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187616', 'alarmLevel': '3', 'alarmLevelDesc': 'Minor', 'deviceId': '31', 'deviceIp': '10.10.10.5', 'deviceName': 'HP830_WSC', 'faultTime': '1469471298', 'faultTimeDesc': '2016-07-25 14:28:18', 'holdInfo': '', 'id': '187616', 'originalType': '1', 'originalTypeDesc': 'Trap', 'paras': '*Attack MAC= F4 B7 E2 95 A0 CD;Attack Frame Type=Probe Request', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (hh3cPeriodicalTrap) of device ADP_Initial_Config(10.20.10.10) from 2016-07-25 12:56:01 to 2016-07-25 14:36:01.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187625', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469471761', 'faultTimeDesc': '2016-07-25 14:36:01', 'id': '187625', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 12:56:01;Stop Time=2016-07-25 14:36:01;Times=100;*Repeat Event Name=hh3cPeriodicalTrap;*Device IP=10.20.10.10;Device Name=ADP_Initial_Config', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:07:06 to 2016-07-25 14:40:21.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187626', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469472021', 'faultTimeDesc': '2016-07-25 14:40:21', 'id': '187626', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:07:06;Stop Time=2016-07-25 14:40:21;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The in direction of interface GigabitEthernet1/0/23 on device 192.168.1.221 at 2016-07-25 14:32:00 is greater than the baseline(2.87 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187631', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187631', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The in direction of interface GigabitEthernet1/0/23 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.38 Mbps;Alarm Severity=2;Threshold Speed=2.87 Mbps;Device IP=192.168.1.221;Interface Index=23;Interface Name=GigabitEthernet1/0/23;Flow Direction=1', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221 at 2016-07-25 14:32:00 is greater than the baseline(1.78 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187632', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187632', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.79 Mbps;Alarm Severity=2;Threshold Speed=1.78 Mbps;Device IP=192.168.1.221;Interface Index=2;Interface Name=GigabitEthernet1/0/2;Flow Direction=0', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient AP interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:14:00 to 2016-07-25 14:47:55.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187637', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469472475', 'faultTimeDesc': '2016-07-25 14:47:55', 'id': '187637', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:14:00;Stop Time=2016-07-25 14:47:55;Times=100;*Repeat Event Name=Some ambient AP interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:40:21 to 2016-07-25 15:15:50.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187654', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469474150', 'faultTimeDesc': '2016-07-25 15:15:50', 'id': '187654', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:40:21;Stop Time=2016-07-25 15:15:50;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}] """ get_alarms_url = "/imcrs/fault/alarm?operatorName=" + username + "&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true" f_url = url + get_alarms_url r = requests.get(f_url, auth=auth, headers=headers) # r.status_code try: if r.status_code == 200: alarm_list = (json.loads(r.text)) return alarm_list['alarm'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_alarms: An Error has occured'
python
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> type(all_alarms) <class 'list'> >>> assert 'ackStatus' in all_alarms[0] [{'OID': '1.3.6.1.4.1.11.2.14.11.15.2.75.5.3.1.6.7', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '1001', 'alarmCategoryDesc': 'Wireless Device Alarm', 'alarmDesc': 'The device(MAC Address: F4 B7 E2 95 A0 CD) is detected to be flooding the network. Attack Frame Type: Probe Request.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187616', 'alarmLevel': '3', 'alarmLevelDesc': 'Minor', 'deviceId': '31', 'deviceIp': '10.10.10.5', 'deviceName': 'HP830_WSC', 'faultTime': '1469471298', 'faultTimeDesc': '2016-07-25 14:28:18', 'holdInfo': '', 'id': '187616', 'originalType': '1', 'originalTypeDesc': 'Trap', 'paras': '*Attack MAC= F4 B7 E2 95 A0 CD;Attack Frame Type=Probe Request', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (hh3cPeriodicalTrap) of device ADP_Initial_Config(10.20.10.10) from 2016-07-25 12:56:01 to 2016-07-25 14:36:01.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187625', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469471761', 'faultTimeDesc': '2016-07-25 14:36:01', 'id': '187625', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 12:56:01;Stop Time=2016-07-25 14:36:01;Times=100;*Repeat Event Name=hh3cPeriodicalTrap;*Device IP=10.20.10.10;Device Name=ADP_Initial_Config', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:07:06 to 2016-07-25 14:40:21.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187626', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469472021', 'faultTimeDesc': '2016-07-25 14:40:21', 'id': '187626', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:07:06;Stop Time=2016-07-25 14:40:21;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The in direction of interface GigabitEthernet1/0/23 on device 192.168.1.221 at 2016-07-25 14:32:00 is greater than the baseline(2.87 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187631', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187631', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The in direction of interface GigabitEthernet1/0/23 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.38 Mbps;Alarm Severity=2;Threshold Speed=2.87 Mbps;Device IP=192.168.1.221;Interface Index=23;Interface Name=GigabitEthernet1/0/23;Flow Direction=1', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221 at 2016-07-25 14:32:00 is greater than the baseline(1.78 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187632', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187632', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.79 Mbps;Alarm Severity=2;Threshold Speed=1.78 Mbps;Device IP=192.168.1.221;Interface Index=2;Interface Name=GigabitEthernet1/0/2;Flow Direction=0', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient AP interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:14:00 to 2016-07-25 14:47:55.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187637', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469472475', 'faultTimeDesc': '2016-07-25 14:47:55', 'id': '187637', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:14:00;Stop Time=2016-07-25 14:47:55;Times=100;*Repeat Event Name=Some ambient AP interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:40:21 to 2016-07-25 15:15:50.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187654', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469474150', 'faultTimeDesc': '2016-07-25 15:15:50', 'id': '187654', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:40:21;Stop Time=2016-07-25 15:15:50;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}] """ get_alarms_url = "/imcrs/fault/alarm?operatorName=" + username + "&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true" f_url = url + get_alarms_url r = requests.get(f_url, auth=auth, headers=headers) # r.status_code try: if r.status_code == 200: alarm_list = (json.loads(r.text)) return alarm_list['alarm'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_alarms: An Error has occured'
[ "def", "get_alarms", "(", "username", ",", "auth", ",", "url", ")", ":", "get_alarms_url", "=", "\"/imcrs/fault/alarm?operatorName=\"", "+", "username", "+", "\"&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true\"", "f_url", "=", "url", "+", "get_alarms_url", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "try", ":", "if", "r", ".", "status_code", "==", "200", ":", "alarm_list", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "return", "alarm_list", "[", "'alarm'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' get_alarms: An Error has occured'" ]
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> type(all_alarms) <class 'list'> >>> assert 'ackStatus' in all_alarms[0] [{'OID': '1.3.6.1.4.1.11.2.14.11.15.2.75.5.3.1.6.7', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '1001', 'alarmCategoryDesc': 'Wireless Device Alarm', 'alarmDesc': 'The device(MAC Address: F4 B7 E2 95 A0 CD) is detected to be flooding the network. Attack Frame Type: Probe Request.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187616', 'alarmLevel': '3', 'alarmLevelDesc': 'Minor', 'deviceId': '31', 'deviceIp': '10.10.10.5', 'deviceName': 'HP830_WSC', 'faultTime': '1469471298', 'faultTimeDesc': '2016-07-25 14:28:18', 'holdInfo': '', 'id': '187616', 'originalType': '1', 'originalTypeDesc': 'Trap', 'paras': '*Attack MAC= F4 B7 E2 95 A0 CD;Attack Frame Type=Probe Request', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (hh3cPeriodicalTrap) of device ADP_Initial_Config(10.20.10.10) from 2016-07-25 12:56:01 to 2016-07-25 14:36:01.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187625', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469471761', 'faultTimeDesc': '2016-07-25 14:36:01', 'id': '187625', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 12:56:01;Stop Time=2016-07-25 14:36:01;Times=100;*Repeat Event Name=hh3cPeriodicalTrap;*Device IP=10.20.10.10;Device Name=ADP_Initial_Config', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:07:06 to 2016-07-25 14:40:21.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187626', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469472021', 'faultTimeDesc': '2016-07-25 14:40:21', 'id': '187626', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:07:06;Stop Time=2016-07-25 14:40:21;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The in direction of interface GigabitEthernet1/0/23 on device 192.168.1.221 at 2016-07-25 14:32:00 is greater than the baseline(2.87 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187631', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187631', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The in direction of interface GigabitEthernet1/0/23 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.38 Mbps;Alarm Severity=2;Threshold Speed=2.87 Mbps;Device IP=192.168.1.221;Interface Index=23;Interface Name=GigabitEthernet1/0/23;Flow Direction=1', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221 at 2016-07-25 14:32:00 is greater than the baseline(1.78 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187632', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187632', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.79 Mbps;Alarm Severity=2;Threshold Speed=1.78 Mbps;Device IP=192.168.1.221;Interface Index=2;Interface Name=GigabitEthernet1/0/2;Flow Direction=0', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient AP interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:14:00 to 2016-07-25 14:47:55.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187637', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469472475', 'faultTimeDesc': '2016-07-25 14:47:55', 'id': '187637', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:14:00;Stop Time=2016-07-25 14:47:55;Times=100;*Repeat Event Name=Some ambient AP interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:40:21 to 2016-07-25 15:15:50.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187654', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469474150', 'faultTimeDesc': '2016-07-25 15:15:50', 'id': '187654', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016-07-25 14:40:21;Stop Time=2016-07-25 15:15:50;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}]
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "RealTime", "Alarms", "from", "HP", "IMC", "RESTFUL", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/alarms.py#L103-L349
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
get_dev_alarms
def get_dev_alarms(auth, url, devid=None, devip=None): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devid: int or str value of the target device :param devip: str of ipv4 address of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries containing the alarms for this device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_alarms = get_dev_alarms(auth.creds, auth.url, devip='10.101.0.221') >>> assert 'ackStatus' in dev_alarms[0] """ # checks to see if the imc credentials are already available if devip is not None: devid = get_dev_details(devip, auth, url)['id'] f_url = url + "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devid) + "&desc=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_alarm = (json.loads(response.text)) if 'alarm' in dev_alarm: return dev_alarm['alarm'] else: return "Device has no alarms" except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_alarms: An Error has occured'
python
def get_dev_alarms(auth, url, devid=None, devip=None): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devid: int or str value of the target device :param devip: str of ipv4 address of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries containing the alarms for this device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_alarms = get_dev_alarms(auth.creds, auth.url, devip='10.101.0.221') >>> assert 'ackStatus' in dev_alarms[0] """ # checks to see if the imc credentials are already available if devip is not None: devid = get_dev_details(devip, auth, url)['id'] f_url = url + "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devid) + "&desc=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_alarm = (json.loads(response.text)) if 'alarm' in dev_alarm: return dev_alarm['alarm'] else: return "Device has no alarms" except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_alarms: An Error has occured'
[ "def", "get_dev_alarms", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "# checks to see if the imc credentials are already available", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "f_url", "=", "url", "+", "\"/imcrs/fault/alarm?operatorName=admin&deviceId=\"", "+", "str", "(", "devid", ")", "+", "\"&desc=false\"", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_alarm", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "'alarm'", "in", "dev_alarm", ":", "return", "dev_alarm", "[", "'alarm'", "]", "else", ":", "return", "\"Device has no alarms\"", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_dev_alarms: An Error has occured'" ]
function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devid: int or str value of the target device :param devip: str of ipv4 address of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries containing the alarms for this device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_alarms = get_dev_alarms(auth.creds, auth.url, devip='10.101.0.221') >>> assert 'ackStatus' in dev_alarms[0]
[ "function", "takes", "the", "devId", "of", "a", "specific", "device", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "current", "alarms", "for", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L20-L62
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
get_realtime_alarm
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_realtime_alarm('admin', auth.creds, auth.url) >>> assert type(real_time_alarm) is list >>> assert 'faultDesc' in real_time_alarm[0] """ f_url = url + "/imcrs/fault/faultRealTime?operatorName=" + username response = requests.get(f_url, auth=auth, headers=HEADERS) try: realtime_alarm_list = (json.loads(response.text)) return realtime_alarm_list['faultRealTime']['faultRealTimeList'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_realtime_alarm: An Error has occured'
python
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_realtime_alarm('admin', auth.creds, auth.url) >>> assert type(real_time_alarm) is list >>> assert 'faultDesc' in real_time_alarm[0] """ f_url = url + "/imcrs/fault/faultRealTime?operatorName=" + username response = requests.get(f_url, auth=auth, headers=HEADERS) try: realtime_alarm_list = (json.loads(response.text)) return realtime_alarm_list['faultRealTime']['faultRealTimeList'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_realtime_alarm: An Error has occured'
[ "def", "get_realtime_alarm", "(", "username", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/fault/faultRealTime?operatorName=\"", "+", "username", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "realtime_alarm_list", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "return", "realtime_alarm_list", "[", "'faultRealTime'", "]", "[", "'faultRealTimeList'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_realtime_alarm: An Error has occured'" ]
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_realtime_alarm('admin', auth.creds, auth.url) >>> assert type(real_time_alarm) is list >>> assert 'faultDesc' in real_time_alarm[0]
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "RealTime", "Alarms", "from", "HP", "IMC", "RESTFUL", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L65-L99
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
get_alarms
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> assert (type(all_alarms)) is list >>> assert 'ackStatus' in all_alarms[0] """ f_url = url + "/imcrs/fault/alarm?operatorName=" + username + \ "&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: alarm_list = (json.loads(response.text)) return alarm_list['alarm'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarms: An Error has occured'
python
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> assert (type(all_alarms)) is list >>> assert 'ackStatus' in all_alarms[0] """ f_url = url + "/imcrs/fault/alarm?operatorName=" + username + \ "&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: alarm_list = (json.loads(response.text)) return alarm_list['alarm'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarms: An Error has occured'
[ "def", "get_alarms", "(", "username", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/fault/alarm?operatorName=\"", "+", "username", "+", "\"&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true\"", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "alarm_list", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "return", "alarm_list", "[", "'alarm'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_alarms: An Error has occured'" ]
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('admin', auth.creds, auth.url) >>> assert (type(all_alarms)) is list >>> assert 'ackStatus' in all_alarms[0]
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "RealTime", "Alarms", "from", "HP", "IMC", "RESTFUL", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L102-L138
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
get_alarm_details
def get_alarm_details(alarm_id, auth, url): """ function to take str input of alarm_id, issues a REST call to the IMC REST interface and returns a dictionary object which contains the details of a specific alarm. :param alarm_id: str number which represents the internal ID of a specific alarm :param auth: :param url: :return: """ f_url = url + "/imcrs/fault/alarm/" + str(alarm_id) response = requests.get(f_url, auth=auth, headers=HEADERS) try: alarm_details = json.loads(response.text) return alarm_details except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarm_details: An Error has occured'
python
def get_alarm_details(alarm_id, auth, url): """ function to take str input of alarm_id, issues a REST call to the IMC REST interface and returns a dictionary object which contains the details of a specific alarm. :param alarm_id: str number which represents the internal ID of a specific alarm :param auth: :param url: :return: """ f_url = url + "/imcrs/fault/alarm/" + str(alarm_id) response = requests.get(f_url, auth=auth, headers=HEADERS) try: alarm_details = json.loads(response.text) return alarm_details except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarm_details: An Error has occured'
[ "def", "get_alarm_details", "(", "alarm_id", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/fault/alarm/\"", "+", "str", "(", "alarm_id", ")", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "alarm_details", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "return", "alarm_details", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_alarm_details: An Error has occured'" ]
function to take str input of alarm_id, issues a REST call to the IMC REST interface and returns a dictionary object which contains the details of a specific alarm. :param alarm_id: str number which represents the internal ID of a specific alarm :param auth: :param url: :return:
[ "function", "to", "take", "str", "input", "of", "alarm_id", "issues", "a", "REST", "call", "to", "the", "IMC", "REST", "interface", "and", "returns", "a", "dictionary", "object", "which", "contains", "the", "details", "of", "a", "specific", "alarm", ".", ":", "param", "alarm_id", ":", "str", "number", "which", "represents", "the", "internal", "ID", "of", "a", "specific", "alarm", ":", "param", "auth", ":", ":", "param", "url", ":", ":", "return", ":" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L140-L155
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
acknowledge_alarm
def acknowledge_alarm(alarm_id, auth, url): """ Function tasks input of str of alarm ID and sends to REST API. Function will acknowledge designated alarm in the IMC alarm database. :param alarm_id: str of alarm ID param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: integer HTTP response code :rtype int """ f_url = url + "/imcrs/fault/alarm/acknowledge/"+str(alarm_id) response = requests.put(f_url, auth=auth, headers=HEADERS) try: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarms: An Error has occured'
python
def acknowledge_alarm(alarm_id, auth, url): """ Function tasks input of str of alarm ID and sends to REST API. Function will acknowledge designated alarm in the IMC alarm database. :param alarm_id: str of alarm ID param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: integer HTTP response code :rtype int """ f_url = url + "/imcrs/fault/alarm/acknowledge/"+str(alarm_id) response = requests.put(f_url, auth=auth, headers=HEADERS) try: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarms: An Error has occured'
[ "def", "acknowledge_alarm", "(", "alarm_id", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/fault/alarm/acknowledge/\"", "+", "str", "(", "alarm_id", ")", "response", "=", "requests", ".", "put", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_alarms: An Error has occured'" ]
Function tasks input of str of alarm ID and sends to REST API. Function will acknowledge designated alarm in the IMC alarm database. :param alarm_id: str of alarm ID param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: integer HTTP response code :rtype int
[ "Function", "tasks", "input", "of", "str", "of", "alarm", "ID", "and", "sends", "to", "REST", "API", ".", "Function", "will", "acknowledge", "designated", "alarm", "in", "the", "IMC", "alarm", "database", ".", ":", "param", "alarm_id", ":", "str", "of", "alarm", "ID", "param", "auth", ":", "requests", "auth", "object", "#usually", "auth", ".", "creds", "from", "auth", "pyhpeimc", ".", "auth", ".", "class" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L158-L175
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/operator.py
create_operator
def create_operator(operator, auth, url,headers=HEADERS): """ Function takes input of dictionary operator with the following keys operator = { "fullName" : "" , "sessionTimeout" : "", "password" : "", "operatorGroupId" : "", "name" : "", "desc" : "", "defaultAcl" : "", "authType" : ""} converts to json and issues a HTTP POST request to the HPE IMC Restful API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param operator: dictionary with the required operator key-value pairs as defined above. :param headers: json formated string. default values set in module :return: :rtype: >>> import json >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = '''{ "fullName" : "test administrator", "sessionTimeout" : "30","password" : "password","operatorGroupId" : "1","name" : "testadmin","desc" : "test admin account","defaultAcl" : "","authType" : "0"}''' >>> operator = json.loads(operator) >>> delete_if_exists = delete_plat_operator('testadmin', auth.creds, auth.url) >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> assert type(new_operator) is int >>> assert new_operator == 201 >>> fail_operator_create = create_operator(operator, auth.creds, auth.url) >>> assert type(fail_operator_create) is int >>> assert fail_operator_create == 409 """ create_operator_url = '/imcrs/plat/operator' f_url = url + create_operator_url payload = json.dumps(operator, indent=4) # creates the URL using the payload variable as the contents r = requests.post(f_url, data=payload, auth=auth, headers=headers) try: if r.status_code == 409: #print("Operator Already Exists") return r.status_code elif r.status_code == 201: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' create_operator: An Error has occured'
python
def create_operator(operator, auth, url,headers=HEADERS): """ Function takes input of dictionary operator with the following keys operator = { "fullName" : "" , "sessionTimeout" : "", "password" : "", "operatorGroupId" : "", "name" : "", "desc" : "", "defaultAcl" : "", "authType" : ""} converts to json and issues a HTTP POST request to the HPE IMC Restful API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param operator: dictionary with the required operator key-value pairs as defined above. :param headers: json formated string. default values set in module :return: :rtype: >>> import json >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = '''{ "fullName" : "test administrator", "sessionTimeout" : "30","password" : "password","operatorGroupId" : "1","name" : "testadmin","desc" : "test admin account","defaultAcl" : "","authType" : "0"}''' >>> operator = json.loads(operator) >>> delete_if_exists = delete_plat_operator('testadmin', auth.creds, auth.url) >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> assert type(new_operator) is int >>> assert new_operator == 201 >>> fail_operator_create = create_operator(operator, auth.creds, auth.url) >>> assert type(fail_operator_create) is int >>> assert fail_operator_create == 409 """ create_operator_url = '/imcrs/plat/operator' f_url = url + create_operator_url payload = json.dumps(operator, indent=4) # creates the URL using the payload variable as the contents r = requests.post(f_url, data=payload, auth=auth, headers=headers) try: if r.status_code == 409: #print("Operator Already Exists") return r.status_code elif r.status_code == 201: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' create_operator: An Error has occured'
[ "def", "create_operator", "(", "operator", ",", "auth", ",", "url", ",", "headers", "=", "HEADERS", ")", ":", "create_operator_url", "=", "'/imcrs/plat/operator'", "f_url", "=", "url", "+", "create_operator_url", "payload", "=", "json", ".", "dumps", "(", "operator", ",", "indent", "=", "4", ")", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "try", ":", "if", "r", ".", "status_code", "==", "409", ":", "#print(\"Operator Already Exists\")", "return", "r", ".", "status_code", "elif", "r", ".", "status_code", "==", "201", ":", "return", "r", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' create_operator: An Error has occured'" ]
Function takes input of dictionary operator with the following keys operator = { "fullName" : "" , "sessionTimeout" : "", "password" : "", "operatorGroupId" : "", "name" : "", "desc" : "", "defaultAcl" : "", "authType" : ""} converts to json and issues a HTTP POST request to the HPE IMC Restful API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param operator: dictionary with the required operator key-value pairs as defined above. :param headers: json formated string. default values set in module :return: :rtype: >>> import json >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = '''{ "fullName" : "test administrator", "sessionTimeout" : "30","password" : "password","operatorGroupId" : "1","name" : "testadmin","desc" : "test admin account","defaultAcl" : "","authType" : "0"}''' >>> operator = json.loads(operator) >>> delete_if_exists = delete_plat_operator('testadmin', auth.creds, auth.url) >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> assert type(new_operator) is int >>> assert new_operator == 201 >>> fail_operator_create = create_operator(operator, auth.creds, auth.url) >>> assert type(fail_operator_create) is int >>> assert fail_operator_create == 409
[ "Function", "takes", "input", "of", "dictionary", "operator", "with", "the", "following", "keys", "operator", "=", "{", "fullName", ":", "sessionTimeout", ":", "password", ":", "operatorGroupId", ":", "name", ":", "desc", ":", "defaultAcl", ":", "authType", ":", "}", "converts", "to", "json", "and", "issues", "a", "HTTP", "POST", "request", "to", "the", "HPE", "IMC", "Restful", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/operator.py#L18-L83
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
list
def list(): '''List virtual folders that belongs to the current user.''' fields = [ ('Name', 'name'), ('ID', 'id'), ('Owner', 'is_owner'), ('Permission', 'permission'), ] with Session() as session: try: resp = session.VFolder.list() if not resp: print('There is no virtual folders created yet.') return rows = (tuple(vf[key] for _, key in fields) for vf in resp) hdrs = (display_name for display_name, _ in fields) print(tabulate(rows, hdrs)) except Exception as e: print_error(e) sys.exit(1)
python
def list(): '''List virtual folders that belongs to the current user.''' fields = [ ('Name', 'name'), ('ID', 'id'), ('Owner', 'is_owner'), ('Permission', 'permission'), ] with Session() as session: try: resp = session.VFolder.list() if not resp: print('There is no virtual folders created yet.') return rows = (tuple(vf[key] for _, key in fields) for vf in resp) hdrs = (display_name for display_name, _ in fields) print(tabulate(rows, hdrs)) except Exception as e: print_error(e) sys.exit(1)
[ "def", "list", "(", ")", ":", "fields", "=", "[", "(", "'Name'", ",", "'name'", ")", ",", "(", "'ID'", ",", "'id'", ")", ",", "(", "'Owner'", ",", "'is_owner'", ")", ",", "(", "'Permission'", ",", "'permission'", ")", ",", "]", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "resp", "=", "session", ".", "VFolder", ".", "list", "(", ")", "if", "not", "resp", ":", "print", "(", "'There is no virtual folders created yet.'", ")", "return", "rows", "=", "(", "tuple", "(", "vf", "[", "key", "]", "for", "_", ",", "key", "in", "fields", ")", "for", "vf", "in", "resp", ")", "hdrs", "=", "(", "display_name", "for", "display_name", ",", "_", "in", "fields", ")", "print", "(", "tabulate", "(", "rows", ",", "hdrs", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
List virtual folders that belongs to the current user.
[ "List", "virtual", "folders", "that", "belongs", "to", "the", "current", "user", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L21-L40
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
list_hosts
def list_hosts(): '''List the hosts of virtual folders that is accessible to the current user.''' with Session() as session: try: resp = session.VFolder.list_hosts() print(f"Default vfolder host: {resp['default']}") print(f"Usable hosts: {', '.join(resp['allowed'])}") except Exception as e: print_error(e) sys.exit(1)
python
def list_hosts(): '''List the hosts of virtual folders that is accessible to the current user.''' with Session() as session: try: resp = session.VFolder.list_hosts() print(f"Default vfolder host: {resp['default']}") print(f"Usable hosts: {', '.join(resp['allowed'])}") except Exception as e: print_error(e) sys.exit(1)
[ "def", "list_hosts", "(", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "resp", "=", "session", ".", "VFolder", ".", "list_hosts", "(", ")", "print", "(", "f\"Default vfolder host: {resp['default']}\"", ")", "print", "(", "f\"Usable hosts: {', '.join(resp['allowed'])}\"", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
List the hosts of virtual folders that is accessible to the current user.
[ "List", "the", "hosts", "of", "virtual", "folders", "that", "is", "accessible", "to", "the", "current", "user", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L44-L53
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
create
def create(name, host): '''Create a new virtual folder. \b NAME: Name of a virtual folder. HOST: Name of a virtual folder host in which the virtual folder will be created. ''' with Session() as session: try: result = session.VFolder.create(name, host) print('Virtual folder "{0}" is created.'.format(result['name'])) except Exception as e: print_error(e) sys.exit(1)
python
def create(name, host): '''Create a new virtual folder. \b NAME: Name of a virtual folder. HOST: Name of a virtual folder host in which the virtual folder will be created. ''' with Session() as session: try: result = session.VFolder.create(name, host) print('Virtual folder "{0}" is created.'.format(result['name'])) except Exception as e: print_error(e) sys.exit(1)
[ "def", "create", "(", "name", ",", "host", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "VFolder", ".", "create", "(", "name", ",", "host", ")", "print", "(", "'Virtual folder \"{0}\" is created.'", ".", "format", "(", "result", "[", "'name'", "]", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Create a new virtual folder. \b NAME: Name of a virtual folder. HOST: Name of a virtual folder host in which the virtual folder will be created.
[ "Create", "a", "new", "virtual", "folder", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L59-L72
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
delete
def delete(name): '''Delete the given virtual folder. This operation is irreversible! NAME: Name of a virtual folder. ''' with Session() as session: try: session.VFolder(name).delete() print_done('Deleted.') except Exception as e: print_error(e) sys.exit(1)
python
def delete(name): '''Delete the given virtual folder. This operation is irreversible! NAME: Name of a virtual folder. ''' with Session() as session: try: session.VFolder(name).delete() print_done('Deleted.') except Exception as e: print_error(e) sys.exit(1)
[ "def", "delete", "(", "name", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "session", ".", "VFolder", "(", "name", ")", ".", "delete", "(", ")", "print_done", "(", "'Deleted.'", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Delete the given virtual folder. This operation is irreversible! NAME: Name of a virtual folder.
[ "Delete", "the", "given", "virtual", "folder", ".", "This", "operation", "is", "irreversible!" ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L77-L88
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
rename
def rename(old_name, new_name): '''Rename the given virtual folder. This operation is irreversible! You cannot change the vfolders that are shared by other users, and the new name must be unique among all your accessible vfolders including the shared ones. OLD_NAME: The current name of a virtual folder. NEW_NAME: The new name of a virtual folder. ''' with Session() as session: try: session.VFolder(old_name).rename(new_name) print_done('Renamed.') except Exception as e: print_error(e) sys.exit(1)
python
def rename(old_name, new_name): '''Rename the given virtual folder. This operation is irreversible! You cannot change the vfolders that are shared by other users, and the new name must be unique among all your accessible vfolders including the shared ones. OLD_NAME: The current name of a virtual folder. NEW_NAME: The new name of a virtual folder. ''' with Session() as session: try: session.VFolder(old_name).rename(new_name) print_done('Renamed.') except Exception as e: print_error(e) sys.exit(1)
[ "def", "rename", "(", "old_name", ",", "new_name", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "session", ".", "VFolder", "(", "old_name", ")", ".", "rename", "(", "new_name", ")", "print_done", "(", "'Renamed.'", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Rename the given virtual folder. This operation is irreversible! You cannot change the vfolders that are shared by other users, and the new name must be unique among all your accessible vfolders including the shared ones. OLD_NAME: The current name of a virtual folder. NEW_NAME: The new name of a virtual folder.
[ "Rename", "the", "given", "virtual", "folder", ".", "This", "operation", "is", "irreversible!", "You", "cannot", "change", "the", "vfolders", "that", "are", "shared", "by", "other", "users", "and", "the", "new", "name", "must", "be", "unique", "among", "all", "your", "accessible", "vfolders", "including", "the", "shared", "ones", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L94-L109
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
info
def info(name): '''Show the information of the given virtual folder. NAME: Name of a virtual folder. ''' with Session() as session: try: result = session.VFolder(name).info() print('Virtual folder "{0}" (ID: {1})' .format(result['name'], result['id'])) print('- Owner:', result['is_owner']) print('- Permission:', result['permission']) print('- Number of files: {0}'.format(result['numFiles'])) except Exception as e: print_error(e) sys.exit(1)
python
def info(name): '''Show the information of the given virtual folder. NAME: Name of a virtual folder. ''' with Session() as session: try: result = session.VFolder(name).info() print('Virtual folder "{0}" (ID: {1})' .format(result['name'], result['id'])) print('- Owner:', result['is_owner']) print('- Permission:', result['permission']) print('- Number of files: {0}'.format(result['numFiles'])) except Exception as e: print_error(e) sys.exit(1)
[ "def", "info", "(", "name", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "VFolder", "(", "name", ")", ".", "info", "(", ")", "print", "(", "'Virtual folder \"{0}\" (ID: {1})'", ".", "format", "(", "result", "[", "'name'", "]", ",", "result", "[", "'id'", "]", ")", ")", "print", "(", "'- Owner:'", ",", "result", "[", "'is_owner'", "]", ")", "print", "(", "'- Permission:'", ",", "result", "[", "'permission'", "]", ")", "print", "(", "'- Number of files: {0}'", ".", "format", "(", "result", "[", "'numFiles'", "]", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Show the information of the given virtual folder. NAME: Name of a virtual folder.
[ "Show", "the", "information", "of", "the", "given", "virtual", "folder", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L114-L129
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
download
def download(name, filenames): ''' Download a file from the virtual folder to the current working directory. The files with the same names will be overwirtten. \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to be uploaded. ''' with Session() as session: try: session.VFolder(name).download(filenames, show_progress=True) print_done('Done.') except Exception as e: print_error(e) sys.exit(1)
python
def download(name, filenames): ''' Download a file from the virtual folder to the current working directory. The files with the same names will be overwirtten. \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to be uploaded. ''' with Session() as session: try: session.VFolder(name).download(filenames, show_progress=True) print_done('Done.') except Exception as e: print_error(e) sys.exit(1)
[ "def", "download", "(", "name", ",", "filenames", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "session", ".", "VFolder", "(", "name", ")", ".", "download", "(", "filenames", ",", "show_progress", "=", "True", ")", "print_done", "(", "'Done.'", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Download a file from the virtual folder to the current working directory. The files with the same names will be overwirtten. \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to be uploaded.
[ "Download", "a", "file", "from", "the", "virtual", "folder", "to", "the", "current", "working", "directory", ".", "The", "files", "with", "the", "same", "names", "will", "be", "overwirtten", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L156-L171
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
mkdir
def mkdir(name, path): '''Create an empty directory in the virtual folder. \b NAME: Name of a virtual folder. PATH: The name or path of directory. Parent directories are created automatically if they do not exist. ''' with Session() as session: try: session.VFolder(name).mkdir(path) print_done('Done.') except Exception as e: print_error(e) sys.exit(1)
python
def mkdir(name, path): '''Create an empty directory in the virtual folder. \b NAME: Name of a virtual folder. PATH: The name or path of directory. Parent directories are created automatically if they do not exist. ''' with Session() as session: try: session.VFolder(name).mkdir(path) print_done('Done.') except Exception as e: print_error(e) sys.exit(1)
[ "def", "mkdir", "(", "name", ",", "path", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "session", ".", "VFolder", "(", "name", ")", ".", "mkdir", "(", "path", ")", "print_done", "(", "'Done.'", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Create an empty directory in the virtual folder. \b NAME: Name of a virtual folder. PATH: The name or path of directory. Parent directories are created automatically if they do not exist.
[ "Create", "an", "empty", "directory", "in", "the", "virtual", "folder", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L190-L204
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
rm
def rm(name, filenames, recursive): ''' Delete files in a virtual folder. If one of the given paths is a directory and the recursive option is enabled, all its content and the directory itself are recursively deleted. This operation is irreversible! \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to delete. ''' with Session() as session: try: if input("> Are you sure? (y/n): ").lower().strip()[:1] == 'y': session.VFolder(name).delete_files( filenames, recursive=recursive) print_done('Done.') except Exception as e: print_error(e) sys.exit(1)
python
def rm(name, filenames, recursive): ''' Delete files in a virtual folder. If one of the given paths is a directory and the recursive option is enabled, all its content and the directory itself are recursively deleted. This operation is irreversible! \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to delete. ''' with Session() as session: try: if input("> Are you sure? (y/n): ").lower().strip()[:1] == 'y': session.VFolder(name).delete_files( filenames, recursive=recursive) print_done('Done.') except Exception as e: print_error(e) sys.exit(1)
[ "def", "rm", "(", "name", ",", "filenames", ",", "recursive", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "if", "input", "(", "\"> Are you sure? (y/n): \"", ")", ".", "lower", "(", ")", ".", "strip", "(", ")", "[", ":", "1", "]", "==", "'y'", ":", "session", ".", "VFolder", "(", "name", ")", ".", "delete_files", "(", "filenames", ",", "recursive", "=", "recursive", ")", "print_done", "(", "'Done.'", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Delete files in a virtual folder. If one of the given paths is a directory and the recursive option is enabled, all its content and the directory itself are recursively deleted. This operation is irreversible! \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to delete.
[ "Delete", "files", "in", "a", "virtual", "folder", ".", "If", "one", "of", "the", "given", "paths", "is", "a", "directory", "and", "the", "recursive", "option", "is", "enabled", "all", "its", "content", "and", "the", "directory", "itself", "are", "recursively", "deleted", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L212-L233
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
ls
def ls(name, path): """ List files in a path of a virtual folder. \b NAME: Name of a virtual folder. PATH: Path inside vfolder. """ with Session() as session: try: print_wait('Retrieving list of files in "{}"...'.format(path)) result = session.VFolder(name).list_files(path) if 'error_msg' in result and result['error_msg']: print_fail(result['error_msg']) return files = json.loads(result['files']) table = [] headers = ['file name', 'size', 'modified', 'mode'] for file in files: mdt = datetime.fromtimestamp(file['mtime']) mtime = mdt.strftime('%b %d %Y %H:%M:%S') row = [file['filename'], file['size'], mtime, file['mode']] table.append(row) print_done('Retrived.') print(tabulate(table, headers=headers)) except Exception as e: print_error(e)
python
def ls(name, path): """ List files in a path of a virtual folder. \b NAME: Name of a virtual folder. PATH: Path inside vfolder. """ with Session() as session: try: print_wait('Retrieving list of files in "{}"...'.format(path)) result = session.VFolder(name).list_files(path) if 'error_msg' in result and result['error_msg']: print_fail(result['error_msg']) return files = json.loads(result['files']) table = [] headers = ['file name', 'size', 'modified', 'mode'] for file in files: mdt = datetime.fromtimestamp(file['mtime']) mtime = mdt.strftime('%b %d %Y %H:%M:%S') row = [file['filename'], file['size'], mtime, file['mode']] table.append(row) print_done('Retrived.') print(tabulate(table, headers=headers)) except Exception as e: print_error(e)
[ "def", "ls", "(", "name", ",", "path", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "print_wait", "(", "'Retrieving list of files in \"{}\"...'", ".", "format", "(", "path", ")", ")", "result", "=", "session", ".", "VFolder", "(", "name", ")", ".", "list_files", "(", "path", ")", "if", "'error_msg'", "in", "result", "and", "result", "[", "'error_msg'", "]", ":", "print_fail", "(", "result", "[", "'error_msg'", "]", ")", "return", "files", "=", "json", ".", "loads", "(", "result", "[", "'files'", "]", ")", "table", "=", "[", "]", "headers", "=", "[", "'file name'", ",", "'size'", ",", "'modified'", ",", "'mode'", "]", "for", "file", "in", "files", ":", "mdt", "=", "datetime", ".", "fromtimestamp", "(", "file", "[", "'mtime'", "]", ")", "mtime", "=", "mdt", ".", "strftime", "(", "'%b %d %Y %H:%M:%S'", ")", "row", "=", "[", "file", "[", "'filename'", "]", ",", "file", "[", "'size'", "]", ",", "mtime", ",", "file", "[", "'mode'", "]", "]", "table", ".", "append", "(", "row", ")", "print_done", "(", "'Retrived.'", ")", "print", "(", "tabulate", "(", "table", ",", "headers", "=", "headers", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")" ]
List files in a path of a virtual folder. \b NAME: Name of a virtual folder. PATH: Path inside vfolder.
[ "List", "files", "in", "a", "path", "of", "a", "virtual", "folder", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L239-L265
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
invite
def invite(name, emails, perm): """Invite other users to access the virtual folder. \b NAME: Name of a virtual folder. EMAIL: Emails to invite. """ with Session() as session: try: assert perm in ['rw', 'ro'], \ 'Invalid permission: {}'.format(perm) result = session.VFolder(name).invite(perm, emails) invited_ids = result.get('invited_ids', []) if len(invited_ids) > 0: print('Invitation sent to:') for invitee in invited_ids: print('\t- ' + invitee) else: print('No users found. Invitation was not sent.') except Exception as e: print_error(e) sys.exit(1)
python
def invite(name, emails, perm): """Invite other users to access the virtual folder. \b NAME: Name of a virtual folder. EMAIL: Emails to invite. """ with Session() as session: try: assert perm in ['rw', 'ro'], \ 'Invalid permission: {}'.format(perm) result = session.VFolder(name).invite(perm, emails) invited_ids = result.get('invited_ids', []) if len(invited_ids) > 0: print('Invitation sent to:') for invitee in invited_ids: print('\t- ' + invitee) else: print('No users found. Invitation was not sent.') except Exception as e: print_error(e) sys.exit(1)
[ "def", "invite", "(", "name", ",", "emails", ",", "perm", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "assert", "perm", "in", "[", "'rw'", ",", "'ro'", "]", ",", "'Invalid permission: {}'", ".", "format", "(", "perm", ")", "result", "=", "session", ".", "VFolder", "(", "name", ")", ".", "invite", "(", "perm", ",", "emails", ")", "invited_ids", "=", "result", ".", "get", "(", "'invited_ids'", ",", "[", "]", ")", "if", "len", "(", "invited_ids", ")", ">", "0", ":", "print", "(", "'Invitation sent to:'", ")", "for", "invitee", "in", "invited_ids", ":", "print", "(", "'\\t- '", "+", "invitee", ")", "else", ":", "print", "(", "'No users found. Invitation was not sent.'", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Invite other users to access the virtual folder. \b NAME: Name of a virtual folder. EMAIL: Emails to invite.
[ "Invite", "other", "users", "to", "access", "the", "virtual", "folder", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L273-L294
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/vfolder.py
invitations
def invitations(): """List and manage received invitations. """ with Session() as session: try: result = session.VFolder.invitations() invitations = result.get('invitations', []) if len(invitations) < 1: print('No invitations.') return print('List of invitations (inviter, vfolder id, permission):') for cnt, inv in enumerate(invitations): if inv['perm'] == 'rw': perm = 'read-write' elif inv['perm'] == 'ro': perm = 'read-only' else: perm = inv['perm'] print('[{}] {}, {}, {}'.format(cnt + 1, inv['inviter'], inv['vfolder_id'], perm)) selection = input('Choose invitation number to manage: ') if selection.isdigit(): selection = int(selection) - 1 else: return if 0 <= selection < len(invitations): while True: action = input('Choose action. (a)ccept, (r)eject, (c)ancel: ') if action.lower() == 'a': # TODO: Let user can select access_key among many. # Currently, the config objects holds only one key. config = get_config() result = session.VFolder.accept_invitation( invitations[selection]['id'], config.access_key) print(result['msg']) break elif action.lower() == 'r': result = session.VFolder.delete_invitation( invitations[selection]['id']) print(result['msg']) break elif action.lower() == 'c': break except Exception as e: print_error(e) sys.exit(1)
python
def invitations(): """List and manage received invitations. """ with Session() as session: try: result = session.VFolder.invitations() invitations = result.get('invitations', []) if len(invitations) < 1: print('No invitations.') return print('List of invitations (inviter, vfolder id, permission):') for cnt, inv in enumerate(invitations): if inv['perm'] == 'rw': perm = 'read-write' elif inv['perm'] == 'ro': perm = 'read-only' else: perm = inv['perm'] print('[{}] {}, {}, {}'.format(cnt + 1, inv['inviter'], inv['vfolder_id'], perm)) selection = input('Choose invitation number to manage: ') if selection.isdigit(): selection = int(selection) - 1 else: return if 0 <= selection < len(invitations): while True: action = input('Choose action. (a)ccept, (r)eject, (c)ancel: ') if action.lower() == 'a': # TODO: Let user can select access_key among many. # Currently, the config objects holds only one key. config = get_config() result = session.VFolder.accept_invitation( invitations[selection]['id'], config.access_key) print(result['msg']) break elif action.lower() == 'r': result = session.VFolder.delete_invitation( invitations[selection]['id']) print(result['msg']) break elif action.lower() == 'c': break except Exception as e: print_error(e) sys.exit(1)
[ "def", "invitations", "(", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "VFolder", ".", "invitations", "(", ")", "invitations", "=", "result", ".", "get", "(", "'invitations'", ",", "[", "]", ")", "if", "len", "(", "invitations", ")", "<", "1", ":", "print", "(", "'No invitations.'", ")", "return", "print", "(", "'List of invitations (inviter, vfolder id, permission):'", ")", "for", "cnt", ",", "inv", "in", "enumerate", "(", "invitations", ")", ":", "if", "inv", "[", "'perm'", "]", "==", "'rw'", ":", "perm", "=", "'read-write'", "elif", "inv", "[", "'perm'", "]", "==", "'ro'", ":", "perm", "=", "'read-only'", "else", ":", "perm", "=", "inv", "[", "'perm'", "]", "print", "(", "'[{}] {}, {}, {}'", ".", "format", "(", "cnt", "+", "1", ",", "inv", "[", "'inviter'", "]", ",", "inv", "[", "'vfolder_id'", "]", ",", "perm", ")", ")", "selection", "=", "input", "(", "'Choose invitation number to manage: '", ")", "if", "selection", ".", "isdigit", "(", ")", ":", "selection", "=", "int", "(", "selection", ")", "-", "1", "else", ":", "return", "if", "0", "<=", "selection", "<", "len", "(", "invitations", ")", ":", "while", "True", ":", "action", "=", "input", "(", "'Choose action. (a)ccept, (r)eject, (c)ancel: '", ")", "if", "action", ".", "lower", "(", ")", "==", "'a'", ":", "# TODO: Let user can select access_key among many.", "# Currently, the config objects holds only one key.", "config", "=", "get_config", "(", ")", "result", "=", "session", ".", "VFolder", ".", "accept_invitation", "(", "invitations", "[", "selection", "]", "[", "'id'", "]", ",", "config", ".", "access_key", ")", "print", "(", "result", "[", "'msg'", "]", ")", "break", "elif", "action", ".", "lower", "(", ")", "==", "'r'", ":", "result", "=", "session", ".", "VFolder", ".", "delete_invitation", "(", "invitations", "[", "selection", "]", "[", "'id'", "]", ")", "print", "(", "result", "[", "'msg'", "]", ")", "break", "elif", "action", ".", "lower", "(", ")", "==", "'c'", ":", "break", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
List and manage received invitations.
[ "List", "and", "manage", "received", "invitations", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L298-L344
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.init_check
def init_check(self, check, obj): """ Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom checks. """ self.logger.info('Adding extension check %s' % check.__name__) check = functools.wraps(check)(functools.partial(check, obj)) self.check(func=check)
python
def init_check(self, check, obj): """ Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom checks. """ self.logger.info('Adding extension check %s' % check.__name__) check = functools.wraps(check)(functools.partial(check, obj)) self.check(func=check)
[ "def", "init_check", "(", "self", ",", "check", ",", "obj", ")", ":", "self", ".", "logger", ".", "info", "(", "'Adding extension check %s'", "%", "check", ".", "__name__", ")", "check", "=", "functools", ".", "wraps", "(", "check", ")", "(", "functools", ".", "partial", "(", "check", ",", "obj", ")", ")", "self", ".", "check", "(", "func", "=", "check", ")" ]
Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom checks.
[ "Adds", "a", "given", "check", "callback", "with", "the", "provided", "object", "to", "the", "list", "of", "checks", ".", "Useful", "for", "built", "-", "ins", "but", "also", "advanced", "custom", "checks", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L135-L142
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.init_app
def init_app(self, app): """ Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks. """ # If no version path was provided in the init of the Dockerflow # class we'll use the parent directory of the app root path. if self.version_path is None: self.version_path = os.path.dirname(app.root_path) for view in ( ('/__version__', 'version', self._version_view), ('/__heartbeat__', 'heartbeat', self._heartbeat_view), ('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view), ): self._blueprint.add_url_rule(*view) self._blueprint.before_app_request(self._before_request) self._blueprint.after_app_request(self._after_request) self._blueprint.app_errorhandler(HeartbeatFailure)(self._heartbeat_exception_handler) app.register_blueprint(self._blueprint) got_request_exception.connect(self._got_request_exception, sender=app) if not hasattr(app, 'extensions'): # pragma: nocover app.extensions = {} app.extensions['dockerflow'] = self
python
def init_app(self, app): """ Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks. """ # If no version path was provided in the init of the Dockerflow # class we'll use the parent directory of the app root path. if self.version_path is None: self.version_path = os.path.dirname(app.root_path) for view in ( ('/__version__', 'version', self._version_view), ('/__heartbeat__', 'heartbeat', self._heartbeat_view), ('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view), ): self._blueprint.add_url_rule(*view) self._blueprint.before_app_request(self._before_request) self._blueprint.after_app_request(self._after_request) self._blueprint.app_errorhandler(HeartbeatFailure)(self._heartbeat_exception_handler) app.register_blueprint(self._blueprint) got_request_exception.connect(self._got_request_exception, sender=app) if not hasattr(app, 'extensions'): # pragma: nocover app.extensions = {} app.extensions['dockerflow'] = self
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# If no version path was provided in the init of the Dockerflow", "# class we'll use the parent directory of the app root path.", "if", "self", ".", "version_path", "is", "None", ":", "self", ".", "version_path", "=", "os", ".", "path", ".", "dirname", "(", "app", ".", "root_path", ")", "for", "view", "in", "(", "(", "'/__version__'", ",", "'version'", ",", "self", ".", "_version_view", ")", ",", "(", "'/__heartbeat__'", ",", "'heartbeat'", ",", "self", ".", "_heartbeat_view", ")", ",", "(", "'/__lbheartbeat__'", ",", "'lbheartbeat'", ",", "self", ".", "_lbheartbeat_view", ")", ",", ")", ":", "self", ".", "_blueprint", ".", "add_url_rule", "(", "*", "view", ")", "self", ".", "_blueprint", ".", "before_app_request", "(", "self", ".", "_before_request", ")", "self", ".", "_blueprint", ".", "after_app_request", "(", "self", ".", "_after_request", ")", "self", ".", "_blueprint", ".", "app_errorhandler", "(", "HeartbeatFailure", ")", "(", "self", ".", "_heartbeat_exception_handler", ")", "app", ".", "register_blueprint", "(", "self", ".", "_blueprint", ")", "got_request_exception", ".", "connect", "(", "self", ".", "_got_request_exception", ",", "sender", "=", "app", ")", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "# pragma: nocover", "app", ".", "extensions", "=", "{", "}", "app", ".", "extensions", "[", "'dockerflow'", "]", "=", "self" ]
Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks.
[ "Initializes", "the", "extension", "with", "the", "given", "app", "registers", "the", "built", "-", "in", "views", "with", "an", "own", "blueprint", "and", "hooks", "up", "our", "signal", "callbacks", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L144-L169
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._before_request
def _before_request(self): """ The before_request callback. """ g._request_id = str(uuid.uuid4()) g._start_timestamp = time.time()
python
def _before_request(self): """ The before_request callback. """ g._request_id = str(uuid.uuid4()) g._start_timestamp = time.time()
[ "def", "_before_request", "(", "self", ")", ":", "g", ".", "_request_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "g", ".", "_start_timestamp", "=", "time", ".", "time", "(", ")" ]
The before_request callback.
[ "The", "before_request", "callback", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L178-L183
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._after_request
def _after_request(self, response): """ The signal handler for the request_finished signal. """ if not getattr(g, '_has_exception', False): extra = self.summary_extra() self.summary_logger.info('', extra=extra) return response
python
def _after_request(self, response): """ The signal handler for the request_finished signal. """ if not getattr(g, '_has_exception', False): extra = self.summary_extra() self.summary_logger.info('', extra=extra) return response
[ "def", "_after_request", "(", "self", ",", "response", ")", ":", "if", "not", "getattr", "(", "g", ",", "'_has_exception'", ",", "False", ")", ":", "extra", "=", "self", ".", "summary_extra", "(", ")", "self", ".", "summary_logger", ".", "info", "(", "''", ",", "extra", "=", "extra", ")", "return", "response" ]
The signal handler for the request_finished signal.
[ "The", "signal", "handler", "for", "the", "request_finished", "signal", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L185-L192
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._got_request_exception
def _got_request_exception(self, sender, exception, **extra): """ The signal handler for the got_request_exception signal. """ extra = self.summary_extra() extra['errno'] = 500 self.summary_logger.error(str(exception), extra=extra) g._has_exception = True
python
def _got_request_exception(self, sender, exception, **extra): """ The signal handler for the got_request_exception signal. """ extra = self.summary_extra() extra['errno'] = 500 self.summary_logger.error(str(exception), extra=extra) g._has_exception = True
[ "def", "_got_request_exception", "(", "self", ",", "sender", ",", "exception", ",", "*", "*", "extra", ")", ":", "extra", "=", "self", ".", "summary_extra", "(", ")", "extra", "[", "'errno'", "]", "=", "500", "self", ".", "summary_logger", ".", "error", "(", "str", "(", "exception", ")", ",", "extra", "=", "extra", ")", "g", ".", "_has_exception", "=", "True" ]
The signal handler for the got_request_exception signal.
[ "The", "signal", "handler", "for", "the", "got_request_exception", "signal", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L194-L201
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.user_id
def user_id(self): """ Return the ID of the current request's user """ # This needs flask-login to be installed if not has_flask_login: return # and the actual login manager installed if not hasattr(current_app, 'login_manager'): return # fail if no current_user was attached to the request context try: is_authenticated = current_user.is_authenticated except AttributeError: return # because is_authenticated could be a callable, call it if callable(is_authenticated): is_authenticated = is_authenticated() # and fail if the user isn't authenticated if not is_authenticated: return # finally return the user id return current_user.get_id()
python
def user_id(self): """ Return the ID of the current request's user """ # This needs flask-login to be installed if not has_flask_login: return # and the actual login manager installed if not hasattr(current_app, 'login_manager'): return # fail if no current_user was attached to the request context try: is_authenticated = current_user.is_authenticated except AttributeError: return # because is_authenticated could be a callable, call it if callable(is_authenticated): is_authenticated = is_authenticated() # and fail if the user isn't authenticated if not is_authenticated: return # finally return the user id return current_user.get_id()
[ "def", "user_id", "(", "self", ")", ":", "# This needs flask-login to be installed", "if", "not", "has_flask_login", ":", "return", "# and the actual login manager installed", "if", "not", "hasattr", "(", "current_app", ",", "'login_manager'", ")", ":", "return", "# fail if no current_user was attached to the request context", "try", ":", "is_authenticated", "=", "current_user", ".", "is_authenticated", "except", "AttributeError", ":", "return", "# because is_authenticated could be a callable, call it", "if", "callable", "(", "is_authenticated", ")", ":", "is_authenticated", "=", "is_authenticated", "(", ")", "# and fail if the user isn't authenticated", "if", "not", "is_authenticated", ":", "return", "# finally return the user id", "return", "current_user", ".", "get_id", "(", ")" ]
Return the ID of the current request's user
[ "Return", "the", "ID", "of", "the", "current", "request", "s", "user" ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L203-L230
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.summary_extra
def summary_extra(self): """ Build the extra data for the summary logger. """ out = { 'errno': 0, 'agent': request.headers.get('User-Agent', ''), 'lang': request.headers.get('Accept-Language', ''), 'method': request.method, 'path': request.path, } # set the uid value to the current user ID user_id = self.user_id() if user_id is None: user_id = '' out['uid'] = user_id # the rid value to the current request ID request_id = g.get('_request_id', None) if request_id is not None: out['rid'] = request_id # and the t value to the time it took to render start_timestamp = g.get('_start_timestamp', None) if start_timestamp is not None: # Duration of request, in milliseconds. out['t'] = int(1000 * (time.time() - start_timestamp)) return out
python
def summary_extra(self): """ Build the extra data for the summary logger. """ out = { 'errno': 0, 'agent': request.headers.get('User-Agent', ''), 'lang': request.headers.get('Accept-Language', ''), 'method': request.method, 'path': request.path, } # set the uid value to the current user ID user_id = self.user_id() if user_id is None: user_id = '' out['uid'] = user_id # the rid value to the current request ID request_id = g.get('_request_id', None) if request_id is not None: out['rid'] = request_id # and the t value to the time it took to render start_timestamp = g.get('_start_timestamp', None) if start_timestamp is not None: # Duration of request, in milliseconds. out['t'] = int(1000 * (time.time() - start_timestamp)) return out
[ "def", "summary_extra", "(", "self", ")", ":", "out", "=", "{", "'errno'", ":", "0", ",", "'agent'", ":", "request", ".", "headers", ".", "get", "(", "'User-Agent'", ",", "''", ")", ",", "'lang'", ":", "request", ".", "headers", ".", "get", "(", "'Accept-Language'", ",", "''", ")", ",", "'method'", ":", "request", ".", "method", ",", "'path'", ":", "request", ".", "path", ",", "}", "# set the uid value to the current user ID", "user_id", "=", "self", ".", "user_id", "(", ")", "if", "user_id", "is", "None", ":", "user_id", "=", "''", "out", "[", "'uid'", "]", "=", "user_id", "# the rid value to the current request ID", "request_id", "=", "g", ".", "get", "(", "'_request_id'", ",", "None", ")", "if", "request_id", "is", "not", "None", ":", "out", "[", "'rid'", "]", "=", "request_id", "# and the t value to the time it took to render", "start_timestamp", "=", "g", ".", "get", "(", "'_start_timestamp'", ",", "None", ")", "if", "start_timestamp", "is", "not", "None", ":", "# Duration of request, in milliseconds.", "out", "[", "'t'", "]", "=", "int", "(", "1000", "*", "(", "time", ".", "time", "(", ")", "-", "start_timestamp", ")", ")", "return", "out" ]
Build the extra data for the summary logger.
[ "Build", "the", "extra", "data", "for", "the", "summary", "logger", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L232-L261
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._version_view
def _version_view(self): """ View that returns the contents of version.json or a 404. """ version_json = self._version_callback(self.version_path) if version_json is None: return 'version.json not found', 404 else: return jsonify(version_json)
python
def _version_view(self): """ View that returns the contents of version.json or a 404. """ version_json = self._version_callback(self.version_path) if version_json is None: return 'version.json not found', 404 else: return jsonify(version_json)
[ "def", "_version_view", "(", "self", ")", ":", "version_json", "=", "self", ".", "_version_callback", "(", "self", ".", "version_path", ")", "if", "version_json", "is", "None", ":", "return", "'version.json not found'", ",", "404", "else", ":", "return", "jsonify", "(", "version_json", ")" ]
View that returns the contents of version.json or a 404.
[ "View", "that", "returns", "the", "contents", "of", "version", ".", "json", "or", "a", "404", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L263-L271
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow._heartbeat_view
def _heartbeat_view(self): """ Runs all the registered checks and returns a JSON response with either a status code of 200 or 500 depending on the results of the checks. Any check that returns a warning or worse (error, critical) will return a 500 response. """ details = {} statuses = {} level = 0 for name, check in self.checks.items(): detail = self._heartbeat_check_detail(check) statuses[name] = detail['status'] level = max(level, detail['level']) if detail['level'] > 0: details[name] = detail payload = { 'status': checks.level_to_text(level), 'checks': statuses, 'details': details, } def render(status_code): return make_response(jsonify(payload), status_code) if level < checks.WARNING: status_code = 200 heartbeat_passed.send(self, level=level) return render(status_code) else: status_code = 500 heartbeat_failed.send(self, level=level) raise HeartbeatFailure(response=render(status_code))
python
def _heartbeat_view(self): """ Runs all the registered checks and returns a JSON response with either a status code of 200 or 500 depending on the results of the checks. Any check that returns a warning or worse (error, critical) will return a 500 response. """ details = {} statuses = {} level = 0 for name, check in self.checks.items(): detail = self._heartbeat_check_detail(check) statuses[name] = detail['status'] level = max(level, detail['level']) if detail['level'] > 0: details[name] = detail payload = { 'status': checks.level_to_text(level), 'checks': statuses, 'details': details, } def render(status_code): return make_response(jsonify(payload), status_code) if level < checks.WARNING: status_code = 200 heartbeat_passed.send(self, level=level) return render(status_code) else: status_code = 500 heartbeat_failed.send(self, level=level) raise HeartbeatFailure(response=render(status_code))
[ "def", "_heartbeat_view", "(", "self", ")", ":", "details", "=", "{", "}", "statuses", "=", "{", "}", "level", "=", "0", "for", "name", ",", "check", "in", "self", ".", "checks", ".", "items", "(", ")", ":", "detail", "=", "self", ".", "_heartbeat_check_detail", "(", "check", ")", "statuses", "[", "name", "]", "=", "detail", "[", "'status'", "]", "level", "=", "max", "(", "level", ",", "detail", "[", "'level'", "]", ")", "if", "detail", "[", "'level'", "]", ">", "0", ":", "details", "[", "name", "]", "=", "detail", "payload", "=", "{", "'status'", ":", "checks", ".", "level_to_text", "(", "level", ")", ",", "'checks'", ":", "statuses", ",", "'details'", ":", "details", ",", "}", "def", "render", "(", "status_code", ")", ":", "return", "make_response", "(", "jsonify", "(", "payload", ")", ",", "status_code", ")", "if", "level", "<", "checks", ".", "WARNING", ":", "status_code", "=", "200", "heartbeat_passed", ".", "send", "(", "self", ",", "level", "=", "level", ")", "return", "render", "(", "status_code", ")", "else", ":", "status_code", "=", "500", "heartbeat_failed", ".", "send", "(", "self", ",", "level", "=", "level", ")", "raise", "HeartbeatFailure", "(", "response", "=", "render", "(", "status_code", ")", ")" ]
Runs all the registered checks and returns a JSON response with either a status code of 200 or 500 depending on the results of the checks. Any check that returns a warning or worse (error, critical) will return a 500 response.
[ "Runs", "all", "the", "registered", "checks", "and", "returns", "a", "JSON", "response", "with", "either", "a", "status", "code", "of", "200", "or", "500", "depending", "on", "the", "results", "of", "the", "checks", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L291-L326
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
Dockerflow.check
def check(self, func=None, name=None): """ A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: acme.storage.ping() except SlowConnectionException as exc: return [checks.Warning(exc.msg, id='acme.health.0002')] except StorageException as exc: return [checks.Error(exc.msg, id='acme.health.0001')] or using a custom name:: @dockerflow.check(name='acme-storage-check) def storage_reachable(): # ... """ if func is None: return functools.partial(self.check, name=name) if name is None: name = func.__name__ self.logger.info('Registered Dockerflow check %s', name) @functools.wraps(func) def decorated_function(*args, **kwargs): self.logger.info('Called Dockerflow check %s', name) return func(*args, **kwargs) self.checks[name] = decorated_function return decorated_function
python
def check(self, func=None, name=None): """ A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: acme.storage.ping() except SlowConnectionException as exc: return [checks.Warning(exc.msg, id='acme.health.0002')] except StorageException as exc: return [checks.Error(exc.msg, id='acme.health.0001')] or using a custom name:: @dockerflow.check(name='acme-storage-check) def storage_reachable(): # ... """ if func is None: return functools.partial(self.check, name=name) if name is None: name = func.__name__ self.logger.info('Registered Dockerflow check %s', name) @functools.wraps(func) def decorated_function(*args, **kwargs): self.logger.info('Called Dockerflow check %s', name) return func(*args, **kwargs) self.checks[name] = decorated_function return decorated_function
[ "def", "check", "(", "self", ",", "func", "=", "None", ",", "name", "=", "None", ")", ":", "if", "func", "is", "None", ":", "return", "functools", ".", "partial", "(", "self", ".", "check", ",", "name", "=", "name", ")", "if", "name", "is", "None", ":", "name", "=", "func", ".", "__name__", "self", ".", "logger", ".", "info", "(", "'Registered Dockerflow check %s'", ",", "name", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorated_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "logger", ".", "info", "(", "'Called Dockerflow check %s'", ",", "name", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "checks", "[", "name", "]", "=", "decorated_function", "return", "decorated_function" ]
A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: acme.storage.ping() except SlowConnectionException as exc: return [checks.Warning(exc.msg, id='acme.health.0002')] except StorageException as exc: return [checks.Error(exc.msg, id='acme.health.0001')] or using a custom name:: @dockerflow.check(name='acme-storage-check) def storage_reachable(): # ...
[ "A", "decorator", "to", "register", "a", "new", "Dockerflow", "check", "to", "be", "run", "when", "the", "/", "__heartbeat__", "endpoint", "is", "called", ".", "e", ".", "g", ".", "::" ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L354-L391
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
drange
def drange(start: Decimal, stop: Decimal, num: int): ''' A simplified version of numpy.linspace with default options ''' delta = stop - start step = delta / (num - 1) yield from (start + step * Decimal(tick) for tick in range(0, num))
python
def drange(start: Decimal, stop: Decimal, num: int): ''' A simplified version of numpy.linspace with default options ''' delta = stop - start step = delta / (num - 1) yield from (start + step * Decimal(tick) for tick in range(0, num))
[ "def", "drange", "(", "start", ":", "Decimal", ",", "stop", ":", "Decimal", ",", "num", ":", "int", ")", ":", "delta", "=", "stop", "-", "start", "step", "=", "delta", "/", "(", "num", "-", "1", ")", "yield", "from", "(", "start", "+", "step", "*", "Decimal", "(", "tick", ")", "for", "tick", "in", "range", "(", "0", ",", "num", ")", ")" ]
A simplified version of numpy.linspace with default options
[ "A", "simplified", "version", "of", "numpy", ".", "linspace", "with", "default", "options" ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L32-L38
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
range_expr
def range_expr(arg): ''' Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case range: "case:a,b,c" (comma-separated strings) ''' key, value = arg.split('=', maxsplit=1) assert _rx_range_key.match(key), 'The key must be a valid slug string.' try: if value.startswith('case:'): return key, value[5:].split(',') elif value.startswith('linspace:'): start, stop, num = value[9:].split(',') return key, tuple(drange(Decimal(start), Decimal(stop), int(num))) elif value.startswith('range:'): range_args = map(int, value[6:].split(',')) return key, tuple(range(*range_args)) else: raise ArgumentTypeError('Unrecognized range expression type') except ValueError as e: raise ArgumentTypeError(str(e))
python
def range_expr(arg): ''' Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case range: "case:a,b,c" (comma-separated strings) ''' key, value = arg.split('=', maxsplit=1) assert _rx_range_key.match(key), 'The key must be a valid slug string.' try: if value.startswith('case:'): return key, value[5:].split(',') elif value.startswith('linspace:'): start, stop, num = value[9:].split(',') return key, tuple(drange(Decimal(start), Decimal(stop), int(num))) elif value.startswith('range:'): range_args = map(int, value[6:].split(',')) return key, tuple(range(*range_args)) else: raise ArgumentTypeError('Unrecognized range expression type') except ValueError as e: raise ArgumentTypeError(str(e))
[ "def", "range_expr", "(", "arg", ")", ":", "key", ",", "value", "=", "arg", ".", "split", "(", "'='", ",", "maxsplit", "=", "1", ")", "assert", "_rx_range_key", ".", "match", "(", "key", ")", ",", "'The key must be a valid slug string.'", "try", ":", "if", "value", ".", "startswith", "(", "'case:'", ")", ":", "return", "key", ",", "value", "[", "5", ":", "]", ".", "split", "(", "','", ")", "elif", "value", ".", "startswith", "(", "'linspace:'", ")", ":", "start", ",", "stop", ",", "num", "=", "value", "[", "9", ":", "]", ".", "split", "(", "','", ")", "return", "key", ",", "tuple", "(", "drange", "(", "Decimal", "(", "start", ")", ",", "Decimal", "(", "stop", ")", ",", "int", "(", "num", ")", ")", ")", "elif", "value", ".", "startswith", "(", "'range:'", ")", ":", "range_args", "=", "map", "(", "int", ",", "value", "[", "6", ":", "]", ".", "split", "(", "','", ")", ")", "return", "key", ",", "tuple", "(", "range", "(", "*", "range_args", ")", ")", "else", ":", "raise", "ArgumentTypeError", "(", "'Unrecognized range expression type'", ")", "except", "ValueError", "as", "e", ":", "raise", "ArgumentTypeError", "(", "str", "(", "e", ")", ")" ]
Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case range: "case:a,b,c" (comma-separated strings)
[ "Accepts", "a", "range", "expression", "which", "generates", "a", "range", "of", "values", "for", "a", "variable", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L41-L63
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
exec_loop
async def exec_loop(stdout, stderr, kernel, mode, code, *, opts=None, vprint_done=print_done, is_multi=False): ''' Fully streamed asynchronous version of the execute loop. ''' async with kernel.stream_execute(code, mode=mode, opts=opts) as stream: async for result in stream: if result.type == aiohttp.WSMsgType.TEXT: result = json.loads(result.data) else: # future extension continue for rec in result.get('console', []): if rec[0] == 'stdout': print(rec[1], end='', file=stdout) elif rec[0] == 'stderr': print(rec[1], end='', file=stderr) else: print('----- output record (type: {0}) -----'.format(rec[0]), file=stdout) print(rec[1], file=stdout) print('----- end of record -----', file=stdout) stdout.flush() files = result.get('files', []) if files: print('--- generated files ---', file=stdout) for item in files: print('{0}: {1}'.format(item['name'], item['url']), file=stdout) print('--- end of generated files ---', file=stdout) if result['status'] == 'clean-finished': exitCode = result.get('exitCode') msg = 'Clean finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) elif result['status'] == 'build-finished': exitCode = result.get('exitCode') msg = 'Build finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) elif result['status'] == 'finished': exitCode = result.get('exitCode') msg = 'Execution finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) break elif result['status'] == 'waiting-input': if result['options'].get('is_password', False): code = getpass.getpass() else: code = input() await stream.send_str(code) elif result['status'] == 'continued': pass
python
async def exec_loop(stdout, stderr, kernel, mode, code, *, opts=None, vprint_done=print_done, is_multi=False): ''' Fully streamed asynchronous version of the execute loop. ''' async with kernel.stream_execute(code, mode=mode, opts=opts) as stream: async for result in stream: if result.type == aiohttp.WSMsgType.TEXT: result = json.loads(result.data) else: # future extension continue for rec in result.get('console', []): if rec[0] == 'stdout': print(rec[1], end='', file=stdout) elif rec[0] == 'stderr': print(rec[1], end='', file=stderr) else: print('----- output record (type: {0}) -----'.format(rec[0]), file=stdout) print(rec[1], file=stdout) print('----- end of record -----', file=stdout) stdout.flush() files = result.get('files', []) if files: print('--- generated files ---', file=stdout) for item in files: print('{0}: {1}'.format(item['name'], item['url']), file=stdout) print('--- end of generated files ---', file=stdout) if result['status'] == 'clean-finished': exitCode = result.get('exitCode') msg = 'Clean finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) elif result['status'] == 'build-finished': exitCode = result.get('exitCode') msg = 'Build finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) elif result['status'] == 'finished': exitCode = result.get('exitCode') msg = 'Execution finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) break elif result['status'] == 'waiting-input': if result['options'].get('is_password', False): code = getpass.getpass() else: code = input() await stream.send_str(code) elif result['status'] == 'continued': pass
[ "async", "def", "exec_loop", "(", "stdout", ",", "stderr", ",", "kernel", ",", "mode", ",", "code", ",", "*", ",", "opts", "=", "None", ",", "vprint_done", "=", "print_done", ",", "is_multi", "=", "False", ")", ":", "async", "with", "kernel", ".", "stream_execute", "(", "code", ",", "mode", "=", "mode", ",", "opts", "=", "opts", ")", "as", "stream", ":", "async", "for", "result", "in", "stream", ":", "if", "result", ".", "type", "==", "aiohttp", ".", "WSMsgType", ".", "TEXT", ":", "result", "=", "json", ".", "loads", "(", "result", ".", "data", ")", "else", ":", "# future extension", "continue", "for", "rec", "in", "result", ".", "get", "(", "'console'", ",", "[", "]", ")", ":", "if", "rec", "[", "0", "]", "==", "'stdout'", ":", "print", "(", "rec", "[", "1", "]", ",", "end", "=", "''", ",", "file", "=", "stdout", ")", "elif", "rec", "[", "0", "]", "==", "'stderr'", ":", "print", "(", "rec", "[", "1", "]", ",", "end", "=", "''", ",", "file", "=", "stderr", ")", "else", ":", "print", "(", "'----- output record (type: {0}) -----'", ".", "format", "(", "rec", "[", "0", "]", ")", ",", "file", "=", "stdout", ")", "print", "(", "rec", "[", "1", "]", ",", "file", "=", "stdout", ")", "print", "(", "'----- end of record -----'", ",", "file", "=", "stdout", ")", "stdout", ".", "flush", "(", ")", "files", "=", "result", ".", "get", "(", "'files'", ",", "[", "]", ")", "if", "files", ":", "print", "(", "'--- generated files ---'", ",", "file", "=", "stdout", ")", "for", "item", "in", "files", ":", "print", "(", "'{0}: {1}'", ".", "format", "(", "item", "[", "'name'", "]", ",", "item", "[", "'url'", "]", ")", ",", "file", "=", "stdout", ")", "print", "(", "'--- end of generated files ---'", ",", "file", "=", "stdout", ")", "if", "result", "[", "'status'", "]", "==", "'clean-finished'", ":", "exitCode", "=", "result", ".", "get", "(", "'exitCode'", ")", "msg", "=", "'Clean finished. (exit code = {0})'", ".", "format", "(", "exitCode", ")", "if", "is_multi", ":", "print", "(", "msg", ",", "file", "=", "stderr", ")", "vprint_done", "(", "msg", ")", "elif", "result", "[", "'status'", "]", "==", "'build-finished'", ":", "exitCode", "=", "result", ".", "get", "(", "'exitCode'", ")", "msg", "=", "'Build finished. (exit code = {0})'", ".", "format", "(", "exitCode", ")", "if", "is_multi", ":", "print", "(", "msg", ",", "file", "=", "stderr", ")", "vprint_done", "(", "msg", ")", "elif", "result", "[", "'status'", "]", "==", "'finished'", ":", "exitCode", "=", "result", ".", "get", "(", "'exitCode'", ")", "msg", "=", "'Execution finished. (exit code = {0})'", ".", "format", "(", "exitCode", ")", "if", "is_multi", ":", "print", "(", "msg", ",", "file", "=", "stderr", ")", "vprint_done", "(", "msg", ")", "break", "elif", "result", "[", "'status'", "]", "==", "'waiting-input'", ":", "if", "result", "[", "'options'", "]", ".", "get", "(", "'is_password'", ",", "False", ")", ":", "code", "=", "getpass", ".", "getpass", "(", ")", "else", ":", "code", "=", "input", "(", ")", "await", "stream", ".", "send_str", "(", "code", ")", "elif", "result", "[", "'status'", "]", "==", "'continued'", ":", "pass" ]
Fully streamed asynchronous version of the execute loop.
[ "Fully", "streamed", "asynchronous", "version", "of", "the", "execute", "loop", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L66-L121
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
exec_loop_sync
def exec_loop_sync(stdout, stderr, kernel, mode, code, *, opts=None, vprint_done=print_done): ''' Old synchronous polling version of the execute loop. ''' opts = opts if opts else {} run_id = None # use server-assigned run ID while True: result = kernel.execute(run_id, code, mode=mode, opts=opts) run_id = result['runId'] opts.clear() # used only once for rec in result['console']: if rec[0] == 'stdout': print(rec[1], end='', file=stdout) elif rec[0] == 'stderr': print(rec[1], end='', file=stderr) else: print('----- output record (type: {0}) -----'.format(rec[0]), file=stdout) print(rec[1], file=stdout) print('----- end of record -----', file=stdout) stdout.flush() files = result.get('files', []) if files: print('--- generated files ---', file=stdout) for item in files: print('{0}: {1}'.format(item['name'], item['url']), file=stdout) print('--- end of generated files ---', file=stdout) if result['status'] == 'clean-finished': exitCode = result.get('exitCode') vprint_done('Clean finished. (exit code = {0}'.format(exitCode), file=stdout) mode = 'continue' code = '' elif result['status'] == 'build-finished': exitCode = result.get('exitCode') vprint_done('Build finished. (exit code = {0})'.format(exitCode), file=stdout) mode = 'continue' code = '' elif result['status'] == 'finished': exitCode = result.get('exitCode') vprint_done('Execution finished. (exit code = {0})'.format(exitCode), file=stdout) break elif result['status'] == 'waiting-input': mode = 'input' if result['options'].get('is_password', False): code = getpass.getpass() else: code = input() elif result['status'] == 'continued': mode = 'continue' code = ''
python
def exec_loop_sync(stdout, stderr, kernel, mode, code, *, opts=None, vprint_done=print_done): ''' Old synchronous polling version of the execute loop. ''' opts = opts if opts else {} run_id = None # use server-assigned run ID while True: result = kernel.execute(run_id, code, mode=mode, opts=opts) run_id = result['runId'] opts.clear() # used only once for rec in result['console']: if rec[0] == 'stdout': print(rec[1], end='', file=stdout) elif rec[0] == 'stderr': print(rec[1], end='', file=stderr) else: print('----- output record (type: {0}) -----'.format(rec[0]), file=stdout) print(rec[1], file=stdout) print('----- end of record -----', file=stdout) stdout.flush() files = result.get('files', []) if files: print('--- generated files ---', file=stdout) for item in files: print('{0}: {1}'.format(item['name'], item['url']), file=stdout) print('--- end of generated files ---', file=stdout) if result['status'] == 'clean-finished': exitCode = result.get('exitCode') vprint_done('Clean finished. (exit code = {0}'.format(exitCode), file=stdout) mode = 'continue' code = '' elif result['status'] == 'build-finished': exitCode = result.get('exitCode') vprint_done('Build finished. (exit code = {0})'.format(exitCode), file=stdout) mode = 'continue' code = '' elif result['status'] == 'finished': exitCode = result.get('exitCode') vprint_done('Execution finished. (exit code = {0})'.format(exitCode), file=stdout) break elif result['status'] == 'waiting-input': mode = 'input' if result['options'].get('is_password', False): code = getpass.getpass() else: code = input() elif result['status'] == 'continued': mode = 'continue' code = ''
[ "def", "exec_loop_sync", "(", "stdout", ",", "stderr", ",", "kernel", ",", "mode", ",", "code", ",", "*", ",", "opts", "=", "None", ",", "vprint_done", "=", "print_done", ")", ":", "opts", "=", "opts", "if", "opts", "else", "{", "}", "run_id", "=", "None", "# use server-assigned run ID", "while", "True", ":", "result", "=", "kernel", ".", "execute", "(", "run_id", ",", "code", ",", "mode", "=", "mode", ",", "opts", "=", "opts", ")", "run_id", "=", "result", "[", "'runId'", "]", "opts", ".", "clear", "(", ")", "# used only once", "for", "rec", "in", "result", "[", "'console'", "]", ":", "if", "rec", "[", "0", "]", "==", "'stdout'", ":", "print", "(", "rec", "[", "1", "]", ",", "end", "=", "''", ",", "file", "=", "stdout", ")", "elif", "rec", "[", "0", "]", "==", "'stderr'", ":", "print", "(", "rec", "[", "1", "]", ",", "end", "=", "''", ",", "file", "=", "stderr", ")", "else", ":", "print", "(", "'----- output record (type: {0}) -----'", ".", "format", "(", "rec", "[", "0", "]", ")", ",", "file", "=", "stdout", ")", "print", "(", "rec", "[", "1", "]", ",", "file", "=", "stdout", ")", "print", "(", "'----- end of record -----'", ",", "file", "=", "stdout", ")", "stdout", ".", "flush", "(", ")", "files", "=", "result", ".", "get", "(", "'files'", ",", "[", "]", ")", "if", "files", ":", "print", "(", "'--- generated files ---'", ",", "file", "=", "stdout", ")", "for", "item", "in", "files", ":", "print", "(", "'{0}: {1}'", ".", "format", "(", "item", "[", "'name'", "]", ",", "item", "[", "'url'", "]", ")", ",", "file", "=", "stdout", ")", "print", "(", "'--- end of generated files ---'", ",", "file", "=", "stdout", ")", "if", "result", "[", "'status'", "]", "==", "'clean-finished'", ":", "exitCode", "=", "result", ".", "get", "(", "'exitCode'", ")", "vprint_done", "(", "'Clean finished. (exit code = {0}'", ".", "format", "(", "exitCode", ")", ",", "file", "=", "stdout", ")", "mode", "=", "'continue'", "code", "=", "''", "elif", "result", "[", "'status'", "]", "==", "'build-finished'", ":", "exitCode", "=", "result", ".", "get", "(", "'exitCode'", ")", "vprint_done", "(", "'Build finished. (exit code = {0})'", ".", "format", "(", "exitCode", ")", ",", "file", "=", "stdout", ")", "mode", "=", "'continue'", "code", "=", "''", "elif", "result", "[", "'status'", "]", "==", "'finished'", ":", "exitCode", "=", "result", ".", "get", "(", "'exitCode'", ")", "vprint_done", "(", "'Execution finished. (exit code = {0})'", ".", "format", "(", "exitCode", ")", ",", "file", "=", "stdout", ")", "break", "elif", "result", "[", "'status'", "]", "==", "'waiting-input'", ":", "mode", "=", "'input'", "if", "result", "[", "'options'", "]", ".", "get", "(", "'is_password'", ",", "False", ")", ":", "code", "=", "getpass", ".", "getpass", "(", ")", "else", ":", "code", "=", "input", "(", ")", "elif", "result", "[", "'status'", "]", "==", "'continued'", ":", "mode", "=", "'continue'", "code", "=", "''" ]
Old synchronous polling version of the execute loop.
[ "Old", "synchronous", "polling", "version", "of", "the", "execute", "loop", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L124-L177
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
run
def run(lang, files, session_id, cluster_size, code, clean, build, exec, terminal, basedir, rm, env, env_range, build_range, exec_range, max_parallel, mount, stats, tag, resources, quiet): ''' Run the given code snippet or files in a session. Depending on the session ID you give (default is random), it may reuse an existing session or create a new one. \b LANG: The name (and version/platform tags appended after a colon) of session runtime or programming language.') FILES: The code file(s). Can be added multiple times. ''' if quiet: vprint_info = vprint_wait = vprint_done = _noop else: vprint_info = print_info vprint_wait = print_wait vprint_done = print_done if files and code: print('You can run only either source files or command-line ' 'code snippet.', file=sys.stderr) sys.exit(1) if not files and not code: print('You should provide the command-line code snippet using ' '"-c" option if run without files.', file=sys.stderr) sys.exit(1) envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) if not (1 <= cluster_size < 4): print('Invalid cluster size.', file=sys.stderr) sys.exit(1) if env_range is None: env_range = [] # noqa if build_range is None: build_range = [] # noqa if exec_range is None: exec_range = [] # noqa env_ranges = {v: r for v, r in env_range} build_ranges = {v: r for v, r in build_range} exec_ranges = {v: r for v, r in exec_range} env_var_maps = [dict(zip(env_ranges.keys(), values)) for values in itertools.product(*env_ranges.values())] build_var_maps = [dict(zip(build_ranges.keys(), values)) for values in itertools.product(*build_ranges.values())] exec_var_maps = [dict(zip(exec_ranges.keys(), values)) for values in itertools.product(*exec_ranges.values())] case_set = collections.OrderedDict() vmaps_product = itertools.product(env_var_maps, build_var_maps, exec_var_maps) build_template = string.Template(build) exec_template = string.Template(exec) env_templates = {k: string.Template(v) for k, v in envs.items()} for env_vmap, build_vmap, exec_vmap in vmaps_product: interpolated_envs = tuple((k, vt.substitute(env_vmap)) for k, vt in env_templates.items()) if build: interpolated_build = build_template.substitute(build_vmap) else: interpolated_build = '*' if exec: interpolated_exec = exec_template.substitute(exec_vmap) else: interpolated_exec = '*' case_set[(interpolated_envs, interpolated_build, interpolated_exec)] = 1 is_multi = (len(case_set) > 1) if is_multi: if max_parallel <= 0: print('The number maximum parallel sessions must be ' 'a positive integer.', file=sys.stderr) sys.exit(1) if terminal: print('You cannot run multiple cases with terminal.', file=sys.stderr) sys.exit(1) if not quiet: vprint_info('Running multiple sessions for the following combinations:') for case in case_set.keys(): pretty_env = ' '.join('{}={}'.format(item[0], item[1]) for item in case[0]) print('env = {!r}, build = {!r}, exec = {!r}' .format(pretty_env, case[1], case[2])) def _run_legacy(session, idx, session_id, envs, clean_cmd, build_cmd, exec_cmd): try: kernel = session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, tag=tag) except Exception as e: print_error(e) sys.exit(1) if kernel.created: vprint_done('[{0}] Session {0} is ready.'.format(idx, kernel.kernel_id)) else: vprint_done('[{0}] Reusing session {0}...'.format(idx, kernel.kernel_id)) if kernel.service_ports: print_info('This session provides the following app services: ' ', '.join(sport['name'] for sport in kernel.service_ports)) try: if files: vprint_wait('[{0}] Uploading source files...'.format(idx)) ret = kernel.upload(files, basedir=basedir, show_progress=True) if ret.status // 100 != 2: print_fail('[{0}] Uploading source files failed!'.format(idx)) print('{0}: {1}\n{2}'.format( ret.status, ret.reason, ret.text())) return vprint_done('[{0}] Uploading done.'.format(idx)) opts = { 'clean': clean_cmd, 'build': build_cmd, 'exec': exec_cmd, } if not terminal: exec_loop_sync(sys.stdout, sys.stderr, kernel, 'batch', '', opts=opts, vprint_done=vprint_done) if terminal: raise NotImplementedError('Terminal access is not supported in ' 'the legacy synchronous mode.') if code: exec_loop_sync(sys.stdout, sys.stderr, kernel, 'query', code, vprint_done=vprint_done) vprint_done('[{0}] Execution finished.'.format(idx)) except Exception as e: print_error(e) sys.exit(1) finally: if rm: vprint_wait('[{0}] Cleaning up the session...'.format(idx)) ret = kernel.destroy() vprint_done('[{0}] Cleaned up the session.'.format(idx)) if stats: _stats = ret.get('stats', None) if ret else None if _stats: _stats.pop('precpu_used', None) _stats.pop('precpu_system_used', None) _stats.pop('cpu_system_used', None) print('[{0}] Statistics:\n{1}' .format(idx, _format_stats(_stats))) else: print('[{0}] Statistics is not available.'.format(idx)) async def _run(session, idx, session_id, envs, clean_cmd, build_cmd, exec_cmd, is_multi=False): try: kernel = await session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, tag=tag) except BackendError as e: print_fail('[{0}] {1}'.format(idx, e)) return if kernel.created: vprint_done('[{0}] Session {1} is ready.'.format(idx, kernel.kernel_id)) else: vprint_done('[{0}] Reusing session {1}...'.format(idx, kernel.kernel_id)) if not is_multi: stdout = sys.stdout stderr = sys.stderr else: log_dir = Path.home() / '.cache' / 'backend.ai' / 'client-logs' log_dir.mkdir(parents=True, exist_ok=True) stdout = open(log_dir / '{0}.stdout.log'.format(session_id), 'w', encoding='utf-8') stderr = open(log_dir / '{0}.stderr.log'.format(session_id), 'w', encoding='utf-8') try: def indexed_vprint_done(msg): vprint_done('[{0}] '.format(idx) + msg) if files: if not is_multi: vprint_wait('[{0}] Uploading source files...'.format(idx)) ret = await kernel.upload(files, basedir=basedir, show_progress=not is_multi) if ret.status // 100 != 2: print_fail('[{0}] Uploading source files failed!'.format(idx)) print('{0}: {1}\n{2}'.format( ret.status, ret.reason, ret.text()), file=stderr) raise RuntimeError('Uploading source files has failed!') if not is_multi: vprint_done('[{0}] Uploading done.'.format(idx)) opts = { 'clean': clean_cmd, 'build': build_cmd, 'exec': exec_cmd, } if not terminal: await exec_loop(stdout, stderr, kernel, 'batch', '', opts=opts, vprint_done=indexed_vprint_done, is_multi=is_multi) if terminal: await exec_terminal(kernel) return if code: await exec_loop(stdout, stderr, kernel, 'query', code, vprint_done=indexed_vprint_done, is_multi=is_multi) except BackendError as e: print_fail('[{0}] {1}'.format(idx, e)) raise RuntimeError(e) except Exception as e: print_fail('[{0}] Execution failed!'.format(idx)) traceback.print_exc() raise RuntimeError(e) finally: try: if rm: if not is_multi: vprint_wait('[{0}] Cleaning up the session...'.format(idx)) ret = await kernel.destroy() vprint_done('[{0}] Cleaned up the session.'.format(idx)) if stats: _stats = ret.get('stats', None) if ret else None if _stats: _stats.pop('precpu_used', None) _stats.pop('precpu_system_used', None) _stats.pop('cpu_system_used', None) stats_str = _format_stats(_stats) print(format_info('[{0}] Statistics:'.format(idx)) + '\n{0}'.format(stats_str)) if is_multi: print('Statistics:\n{0}'.format(stats_str), file=stderr) else: print_warn('[{0}] Statistics: unavailable.'.format(idx)) if is_multi: print('Statistics: unavailable.', file=stderr) finally: if is_multi: stdout.close() stderr.close() def _run_cases_legacy(): if session_id is None: session_id_prefix = token_hex(5) else: session_id_prefix = session_id vprint_info('Session token prefix: {0}'.format(session_id_prefix)) vprint_info('In the legacy mode, all cases will run serially!') with Session() as session: for idx, case in enumerate(case_set.keys()): if is_multi: _session_id = '{0}-{1}'.format(session_id_prefix, idx) else: _session_id = session_id_prefix envs = dict(case[0]) clean_cmd = clean if clean else '*' build_cmd = case[1] exec_cmd = case[2] _run_legacy(session, idx, _session_id, envs, clean_cmd, build_cmd, exec_cmd) async def _run_cases(): loop = current_loop() if session_id is None: session_id_prefix = token_hex(5) else: session_id_prefix = session_id vprint_info('Session token prefix: {0}'.format(session_id_prefix)) if is_multi: print_info('Check out the stdout/stderr logs stored in ' '~/.cache/backend.ai/client-logs directory.') async with AsyncSession() as session: tasks = [] # TODO: limit max-parallelism using aiojobs for idx, case in enumerate(case_set.keys()): if is_multi: _session_id = '{0}-{1}'.format(session_id_prefix, idx) else: _session_id = session_id_prefix envs = dict(case[0]) clean_cmd = clean if clean else '*' build_cmd = case[1] exec_cmd = case[2] t = loop.create_task( _run(session, idx, _session_id, envs, clean_cmd, build_cmd, exec_cmd, is_multi=is_multi)) tasks.append(t) results = await asyncio.gather(*tasks, return_exceptions=True) if any(map(lambda r: isinstance(r, Exception), results)): if is_multi: print_fail('There were failed cases!') sys.exit(1) if is_legacy_server(): _run_cases_legacy() else: loop = asyncio.get_event_loop() try: loop.run_until_complete(_run_cases()) finally: loop.close()
python
def run(lang, files, session_id, cluster_size, code, clean, build, exec, terminal, basedir, rm, env, env_range, build_range, exec_range, max_parallel, mount, stats, tag, resources, quiet): ''' Run the given code snippet or files in a session. Depending on the session ID you give (default is random), it may reuse an existing session or create a new one. \b LANG: The name (and version/platform tags appended after a colon) of session runtime or programming language.') FILES: The code file(s). Can be added multiple times. ''' if quiet: vprint_info = vprint_wait = vprint_done = _noop else: vprint_info = print_info vprint_wait = print_wait vprint_done = print_done if files and code: print('You can run only either source files or command-line ' 'code snippet.', file=sys.stderr) sys.exit(1) if not files and not code: print('You should provide the command-line code snippet using ' '"-c" option if run without files.', file=sys.stderr) sys.exit(1) envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) if not (1 <= cluster_size < 4): print('Invalid cluster size.', file=sys.stderr) sys.exit(1) if env_range is None: env_range = [] # noqa if build_range is None: build_range = [] # noqa if exec_range is None: exec_range = [] # noqa env_ranges = {v: r for v, r in env_range} build_ranges = {v: r for v, r in build_range} exec_ranges = {v: r for v, r in exec_range} env_var_maps = [dict(zip(env_ranges.keys(), values)) for values in itertools.product(*env_ranges.values())] build_var_maps = [dict(zip(build_ranges.keys(), values)) for values in itertools.product(*build_ranges.values())] exec_var_maps = [dict(zip(exec_ranges.keys(), values)) for values in itertools.product(*exec_ranges.values())] case_set = collections.OrderedDict() vmaps_product = itertools.product(env_var_maps, build_var_maps, exec_var_maps) build_template = string.Template(build) exec_template = string.Template(exec) env_templates = {k: string.Template(v) for k, v in envs.items()} for env_vmap, build_vmap, exec_vmap in vmaps_product: interpolated_envs = tuple((k, vt.substitute(env_vmap)) for k, vt in env_templates.items()) if build: interpolated_build = build_template.substitute(build_vmap) else: interpolated_build = '*' if exec: interpolated_exec = exec_template.substitute(exec_vmap) else: interpolated_exec = '*' case_set[(interpolated_envs, interpolated_build, interpolated_exec)] = 1 is_multi = (len(case_set) > 1) if is_multi: if max_parallel <= 0: print('The number maximum parallel sessions must be ' 'a positive integer.', file=sys.stderr) sys.exit(1) if terminal: print('You cannot run multiple cases with terminal.', file=sys.stderr) sys.exit(1) if not quiet: vprint_info('Running multiple sessions for the following combinations:') for case in case_set.keys(): pretty_env = ' '.join('{}={}'.format(item[0], item[1]) for item in case[0]) print('env = {!r}, build = {!r}, exec = {!r}' .format(pretty_env, case[1], case[2])) def _run_legacy(session, idx, session_id, envs, clean_cmd, build_cmd, exec_cmd): try: kernel = session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, tag=tag) except Exception as e: print_error(e) sys.exit(1) if kernel.created: vprint_done('[{0}] Session {0} is ready.'.format(idx, kernel.kernel_id)) else: vprint_done('[{0}] Reusing session {0}...'.format(idx, kernel.kernel_id)) if kernel.service_ports: print_info('This session provides the following app services: ' ', '.join(sport['name'] for sport in kernel.service_ports)) try: if files: vprint_wait('[{0}] Uploading source files...'.format(idx)) ret = kernel.upload(files, basedir=basedir, show_progress=True) if ret.status // 100 != 2: print_fail('[{0}] Uploading source files failed!'.format(idx)) print('{0}: {1}\n{2}'.format( ret.status, ret.reason, ret.text())) return vprint_done('[{0}] Uploading done.'.format(idx)) opts = { 'clean': clean_cmd, 'build': build_cmd, 'exec': exec_cmd, } if not terminal: exec_loop_sync(sys.stdout, sys.stderr, kernel, 'batch', '', opts=opts, vprint_done=vprint_done) if terminal: raise NotImplementedError('Terminal access is not supported in ' 'the legacy synchronous mode.') if code: exec_loop_sync(sys.stdout, sys.stderr, kernel, 'query', code, vprint_done=vprint_done) vprint_done('[{0}] Execution finished.'.format(idx)) except Exception as e: print_error(e) sys.exit(1) finally: if rm: vprint_wait('[{0}] Cleaning up the session...'.format(idx)) ret = kernel.destroy() vprint_done('[{0}] Cleaned up the session.'.format(idx)) if stats: _stats = ret.get('stats', None) if ret else None if _stats: _stats.pop('precpu_used', None) _stats.pop('precpu_system_used', None) _stats.pop('cpu_system_used', None) print('[{0}] Statistics:\n{1}' .format(idx, _format_stats(_stats))) else: print('[{0}] Statistics is not available.'.format(idx)) async def _run(session, idx, session_id, envs, clean_cmd, build_cmd, exec_cmd, is_multi=False): try: kernel = await session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, tag=tag) except BackendError as e: print_fail('[{0}] {1}'.format(idx, e)) return if kernel.created: vprint_done('[{0}] Session {1} is ready.'.format(idx, kernel.kernel_id)) else: vprint_done('[{0}] Reusing session {1}...'.format(idx, kernel.kernel_id)) if not is_multi: stdout = sys.stdout stderr = sys.stderr else: log_dir = Path.home() / '.cache' / 'backend.ai' / 'client-logs' log_dir.mkdir(parents=True, exist_ok=True) stdout = open(log_dir / '{0}.stdout.log'.format(session_id), 'w', encoding='utf-8') stderr = open(log_dir / '{0}.stderr.log'.format(session_id), 'w', encoding='utf-8') try: def indexed_vprint_done(msg): vprint_done('[{0}] '.format(idx) + msg) if files: if not is_multi: vprint_wait('[{0}] Uploading source files...'.format(idx)) ret = await kernel.upload(files, basedir=basedir, show_progress=not is_multi) if ret.status // 100 != 2: print_fail('[{0}] Uploading source files failed!'.format(idx)) print('{0}: {1}\n{2}'.format( ret.status, ret.reason, ret.text()), file=stderr) raise RuntimeError('Uploading source files has failed!') if not is_multi: vprint_done('[{0}] Uploading done.'.format(idx)) opts = { 'clean': clean_cmd, 'build': build_cmd, 'exec': exec_cmd, } if not terminal: await exec_loop(stdout, stderr, kernel, 'batch', '', opts=opts, vprint_done=indexed_vprint_done, is_multi=is_multi) if terminal: await exec_terminal(kernel) return if code: await exec_loop(stdout, stderr, kernel, 'query', code, vprint_done=indexed_vprint_done, is_multi=is_multi) except BackendError as e: print_fail('[{0}] {1}'.format(idx, e)) raise RuntimeError(e) except Exception as e: print_fail('[{0}] Execution failed!'.format(idx)) traceback.print_exc() raise RuntimeError(e) finally: try: if rm: if not is_multi: vprint_wait('[{0}] Cleaning up the session...'.format(idx)) ret = await kernel.destroy() vprint_done('[{0}] Cleaned up the session.'.format(idx)) if stats: _stats = ret.get('stats', None) if ret else None if _stats: _stats.pop('precpu_used', None) _stats.pop('precpu_system_used', None) _stats.pop('cpu_system_used', None) stats_str = _format_stats(_stats) print(format_info('[{0}] Statistics:'.format(idx)) + '\n{0}'.format(stats_str)) if is_multi: print('Statistics:\n{0}'.format(stats_str), file=stderr) else: print_warn('[{0}] Statistics: unavailable.'.format(idx)) if is_multi: print('Statistics: unavailable.', file=stderr) finally: if is_multi: stdout.close() stderr.close() def _run_cases_legacy(): if session_id is None: session_id_prefix = token_hex(5) else: session_id_prefix = session_id vprint_info('Session token prefix: {0}'.format(session_id_prefix)) vprint_info('In the legacy mode, all cases will run serially!') with Session() as session: for idx, case in enumerate(case_set.keys()): if is_multi: _session_id = '{0}-{1}'.format(session_id_prefix, idx) else: _session_id = session_id_prefix envs = dict(case[0]) clean_cmd = clean if clean else '*' build_cmd = case[1] exec_cmd = case[2] _run_legacy(session, idx, _session_id, envs, clean_cmd, build_cmd, exec_cmd) async def _run_cases(): loop = current_loop() if session_id is None: session_id_prefix = token_hex(5) else: session_id_prefix = session_id vprint_info('Session token prefix: {0}'.format(session_id_prefix)) if is_multi: print_info('Check out the stdout/stderr logs stored in ' '~/.cache/backend.ai/client-logs directory.') async with AsyncSession() as session: tasks = [] # TODO: limit max-parallelism using aiojobs for idx, case in enumerate(case_set.keys()): if is_multi: _session_id = '{0}-{1}'.format(session_id_prefix, idx) else: _session_id = session_id_prefix envs = dict(case[0]) clean_cmd = clean if clean else '*' build_cmd = case[1] exec_cmd = case[2] t = loop.create_task( _run(session, idx, _session_id, envs, clean_cmd, build_cmd, exec_cmd, is_multi=is_multi)) tasks.append(t) results = await asyncio.gather(*tasks, return_exceptions=True) if any(map(lambda r: isinstance(r, Exception), results)): if is_multi: print_fail('There were failed cases!') sys.exit(1) if is_legacy_server(): _run_cases_legacy() else: loop = asyncio.get_event_loop() try: loop.run_until_complete(_run_cases()) finally: loop.close()
[ "def", "run", "(", "lang", ",", "files", ",", "session_id", ",", "cluster_size", ",", "code", ",", "clean", ",", "build", ",", "exec", ",", "terminal", ",", "basedir", ",", "rm", ",", "env", ",", "env_range", ",", "build_range", ",", "exec_range", ",", "max_parallel", ",", "mount", ",", "stats", ",", "tag", ",", "resources", ",", "quiet", ")", ":", "if", "quiet", ":", "vprint_info", "=", "vprint_wait", "=", "vprint_done", "=", "_noop", "else", ":", "vprint_info", "=", "print_info", "vprint_wait", "=", "print_wait", "vprint_done", "=", "print_done", "if", "files", "and", "code", ":", "print", "(", "'You can run only either source files or command-line '", "'code snippet.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "files", "and", "not", "code", ":", "print", "(", "'You should provide the command-line code snippet using '", "'\"-c\" option if run without files.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "envs", "=", "_prepare_env_arg", "(", "env", ")", "resources", "=", "_prepare_resource_arg", "(", "resources", ")", "mount", "=", "_prepare_mount_arg", "(", "mount", ")", "if", "not", "(", "1", "<=", "cluster_size", "<", "4", ")", ":", "print", "(", "'Invalid cluster size.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "if", "env_range", "is", "None", ":", "env_range", "=", "[", "]", "# noqa", "if", "build_range", "is", "None", ":", "build_range", "=", "[", "]", "# noqa", "if", "exec_range", "is", "None", ":", "exec_range", "=", "[", "]", "# noqa", "env_ranges", "=", "{", "v", ":", "r", "for", "v", ",", "r", "in", "env_range", "}", "build_ranges", "=", "{", "v", ":", "r", "for", "v", ",", "r", "in", "build_range", "}", "exec_ranges", "=", "{", "v", ":", "r", "for", "v", ",", "r", "in", "exec_range", "}", "env_var_maps", "=", "[", "dict", "(", "zip", "(", "env_ranges", ".", "keys", "(", ")", ",", "values", ")", ")", "for", "values", "in", "itertools", ".", "product", "(", "*", "env_ranges", ".", "values", "(", ")", ")", "]", "build_var_maps", "=", "[", "dict", "(", "zip", "(", "build_ranges", ".", "keys", "(", ")", ",", "values", ")", ")", "for", "values", "in", "itertools", ".", "product", "(", "*", "build_ranges", ".", "values", "(", ")", ")", "]", "exec_var_maps", "=", "[", "dict", "(", "zip", "(", "exec_ranges", ".", "keys", "(", ")", ",", "values", ")", ")", "for", "values", "in", "itertools", ".", "product", "(", "*", "exec_ranges", ".", "values", "(", ")", ")", "]", "case_set", "=", "collections", ".", "OrderedDict", "(", ")", "vmaps_product", "=", "itertools", ".", "product", "(", "env_var_maps", ",", "build_var_maps", ",", "exec_var_maps", ")", "build_template", "=", "string", ".", "Template", "(", "build", ")", "exec_template", "=", "string", ".", "Template", "(", "exec", ")", "env_templates", "=", "{", "k", ":", "string", ".", "Template", "(", "v", ")", "for", "k", ",", "v", "in", "envs", ".", "items", "(", ")", "}", "for", "env_vmap", ",", "build_vmap", ",", "exec_vmap", "in", "vmaps_product", ":", "interpolated_envs", "=", "tuple", "(", "(", "k", ",", "vt", ".", "substitute", "(", "env_vmap", ")", ")", "for", "k", ",", "vt", "in", "env_templates", ".", "items", "(", ")", ")", "if", "build", ":", "interpolated_build", "=", "build_template", ".", "substitute", "(", "build_vmap", ")", "else", ":", "interpolated_build", "=", "'*'", "if", "exec", ":", "interpolated_exec", "=", "exec_template", ".", "substitute", "(", "exec_vmap", ")", "else", ":", "interpolated_exec", "=", "'*'", "case_set", "[", "(", "interpolated_envs", ",", "interpolated_build", ",", "interpolated_exec", ")", "]", "=", "1", "is_multi", "=", "(", "len", "(", "case_set", ")", ">", "1", ")", "if", "is_multi", ":", "if", "max_parallel", "<=", "0", ":", "print", "(", "'The number maximum parallel sessions must be '", "'a positive integer.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "if", "terminal", ":", "print", "(", "'You cannot run multiple cases with terminal.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "quiet", ":", "vprint_info", "(", "'Running multiple sessions for the following combinations:'", ")", "for", "case", "in", "case_set", ".", "keys", "(", ")", ":", "pretty_env", "=", "' '", ".", "join", "(", "'{}={}'", ".", "format", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ")", "for", "item", "in", "case", "[", "0", "]", ")", "print", "(", "'env = {!r}, build = {!r}, exec = {!r}'", ".", "format", "(", "pretty_env", ",", "case", "[", "1", "]", ",", "case", "[", "2", "]", ")", ")", "def", "_run_legacy", "(", "session", ",", "idx", ",", "session_id", ",", "envs", ",", "clean_cmd", ",", "build_cmd", ",", "exec_cmd", ")", ":", "try", ":", "kernel", "=", "session", ".", "Kernel", ".", "get_or_create", "(", "lang", ",", "client_token", "=", "session_id", ",", "cluster_size", "=", "cluster_size", ",", "mounts", "=", "mount", ",", "envs", "=", "envs", ",", "resources", "=", "resources", ",", "tag", "=", "tag", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "if", "kernel", ".", "created", ":", "vprint_done", "(", "'[{0}] Session {0} is ready.'", ".", "format", "(", "idx", ",", "kernel", ".", "kernel_id", ")", ")", "else", ":", "vprint_done", "(", "'[{0}] Reusing session {0}...'", ".", "format", "(", "idx", ",", "kernel", ".", "kernel_id", ")", ")", "if", "kernel", ".", "service_ports", ":", "print_info", "(", "'This session provides the following app services: '", "', '", ".", "join", "(", "sport", "[", "'name'", "]", "for", "sport", "in", "kernel", ".", "service_ports", ")", ")", "try", ":", "if", "files", ":", "vprint_wait", "(", "'[{0}] Uploading source files...'", ".", "format", "(", "idx", ")", ")", "ret", "=", "kernel", ".", "upload", "(", "files", ",", "basedir", "=", "basedir", ",", "show_progress", "=", "True", ")", "if", "ret", ".", "status", "//", "100", "!=", "2", ":", "print_fail", "(", "'[{0}] Uploading source files failed!'", ".", "format", "(", "idx", ")", ")", "print", "(", "'{0}: {1}\\n{2}'", ".", "format", "(", "ret", ".", "status", ",", "ret", ".", "reason", ",", "ret", ".", "text", "(", ")", ")", ")", "return", "vprint_done", "(", "'[{0}] Uploading done.'", ".", "format", "(", "idx", ")", ")", "opts", "=", "{", "'clean'", ":", "clean_cmd", ",", "'build'", ":", "build_cmd", ",", "'exec'", ":", "exec_cmd", ",", "}", "if", "not", "terminal", ":", "exec_loop_sync", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ",", "kernel", ",", "'batch'", ",", "''", ",", "opts", "=", "opts", ",", "vprint_done", "=", "vprint_done", ")", "if", "terminal", ":", "raise", "NotImplementedError", "(", "'Terminal access is not supported in '", "'the legacy synchronous mode.'", ")", "if", "code", ":", "exec_loop_sync", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ",", "kernel", ",", "'query'", ",", "code", ",", "vprint_done", "=", "vprint_done", ")", "vprint_done", "(", "'[{0}] Execution finished.'", ".", "format", "(", "idx", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "finally", ":", "if", "rm", ":", "vprint_wait", "(", "'[{0}] Cleaning up the session...'", ".", "format", "(", "idx", ")", ")", "ret", "=", "kernel", ".", "destroy", "(", ")", "vprint_done", "(", "'[{0}] Cleaned up the session.'", ".", "format", "(", "idx", ")", ")", "if", "stats", ":", "_stats", "=", "ret", ".", "get", "(", "'stats'", ",", "None", ")", "if", "ret", "else", "None", "if", "_stats", ":", "_stats", ".", "pop", "(", "'precpu_used'", ",", "None", ")", "_stats", ".", "pop", "(", "'precpu_system_used'", ",", "None", ")", "_stats", ".", "pop", "(", "'cpu_system_used'", ",", "None", ")", "print", "(", "'[{0}] Statistics:\\n{1}'", ".", "format", "(", "idx", ",", "_format_stats", "(", "_stats", ")", ")", ")", "else", ":", "print", "(", "'[{0}] Statistics is not available.'", ".", "format", "(", "idx", ")", ")", "async", "def", "_run", "(", "session", ",", "idx", ",", "session_id", ",", "envs", ",", "clean_cmd", ",", "build_cmd", ",", "exec_cmd", ",", "is_multi", "=", "False", ")", ":", "try", ":", "kernel", "=", "await", "session", ".", "Kernel", ".", "get_or_create", "(", "lang", ",", "client_token", "=", "session_id", ",", "cluster_size", "=", "cluster_size", ",", "mounts", "=", "mount", ",", "envs", "=", "envs", ",", "resources", "=", "resources", ",", "tag", "=", "tag", ")", "except", "BackendError", "as", "e", ":", "print_fail", "(", "'[{0}] {1}'", ".", "format", "(", "idx", ",", "e", ")", ")", "return", "if", "kernel", ".", "created", ":", "vprint_done", "(", "'[{0}] Session {1} is ready.'", ".", "format", "(", "idx", ",", "kernel", ".", "kernel_id", ")", ")", "else", ":", "vprint_done", "(", "'[{0}] Reusing session {1}...'", ".", "format", "(", "idx", ",", "kernel", ".", "kernel_id", ")", ")", "if", "not", "is_multi", ":", "stdout", "=", "sys", ".", "stdout", "stderr", "=", "sys", ".", "stderr", "else", ":", "log_dir", "=", "Path", ".", "home", "(", ")", "/", "'.cache'", "/", "'backend.ai'", "/", "'client-logs'", "log_dir", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "stdout", "=", "open", "(", "log_dir", "/", "'{0}.stdout.log'", ".", "format", "(", "session_id", ")", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "stderr", "=", "open", "(", "log_dir", "/", "'{0}.stderr.log'", ".", "format", "(", "session_id", ")", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "def", "indexed_vprint_done", "(", "msg", ")", ":", "vprint_done", "(", "'[{0}] '", ".", "format", "(", "idx", ")", "+", "msg", ")", "if", "files", ":", "if", "not", "is_multi", ":", "vprint_wait", "(", "'[{0}] Uploading source files...'", ".", "format", "(", "idx", ")", ")", "ret", "=", "await", "kernel", ".", "upload", "(", "files", ",", "basedir", "=", "basedir", ",", "show_progress", "=", "not", "is_multi", ")", "if", "ret", ".", "status", "//", "100", "!=", "2", ":", "print_fail", "(", "'[{0}] Uploading source files failed!'", ".", "format", "(", "idx", ")", ")", "print", "(", "'{0}: {1}\\n{2}'", ".", "format", "(", "ret", ".", "status", ",", "ret", ".", "reason", ",", "ret", ".", "text", "(", ")", ")", ",", "file", "=", "stderr", ")", "raise", "RuntimeError", "(", "'Uploading source files has failed!'", ")", "if", "not", "is_multi", ":", "vprint_done", "(", "'[{0}] Uploading done.'", ".", "format", "(", "idx", ")", ")", "opts", "=", "{", "'clean'", ":", "clean_cmd", ",", "'build'", ":", "build_cmd", ",", "'exec'", ":", "exec_cmd", ",", "}", "if", "not", "terminal", ":", "await", "exec_loop", "(", "stdout", ",", "stderr", ",", "kernel", ",", "'batch'", ",", "''", ",", "opts", "=", "opts", ",", "vprint_done", "=", "indexed_vprint_done", ",", "is_multi", "=", "is_multi", ")", "if", "terminal", ":", "await", "exec_terminal", "(", "kernel", ")", "return", "if", "code", ":", "await", "exec_loop", "(", "stdout", ",", "stderr", ",", "kernel", ",", "'query'", ",", "code", ",", "vprint_done", "=", "indexed_vprint_done", ",", "is_multi", "=", "is_multi", ")", "except", "BackendError", "as", "e", ":", "print_fail", "(", "'[{0}] {1}'", ".", "format", "(", "idx", ",", "e", ")", ")", "raise", "RuntimeError", "(", "e", ")", "except", "Exception", "as", "e", ":", "print_fail", "(", "'[{0}] Execution failed!'", ".", "format", "(", "idx", ")", ")", "traceback", ".", "print_exc", "(", ")", "raise", "RuntimeError", "(", "e", ")", "finally", ":", "try", ":", "if", "rm", ":", "if", "not", "is_multi", ":", "vprint_wait", "(", "'[{0}] Cleaning up the session...'", ".", "format", "(", "idx", ")", ")", "ret", "=", "await", "kernel", ".", "destroy", "(", ")", "vprint_done", "(", "'[{0}] Cleaned up the session.'", ".", "format", "(", "idx", ")", ")", "if", "stats", ":", "_stats", "=", "ret", ".", "get", "(", "'stats'", ",", "None", ")", "if", "ret", "else", "None", "if", "_stats", ":", "_stats", ".", "pop", "(", "'precpu_used'", ",", "None", ")", "_stats", ".", "pop", "(", "'precpu_system_used'", ",", "None", ")", "_stats", ".", "pop", "(", "'cpu_system_used'", ",", "None", ")", "stats_str", "=", "_format_stats", "(", "_stats", ")", "print", "(", "format_info", "(", "'[{0}] Statistics:'", ".", "format", "(", "idx", ")", ")", "+", "'\\n{0}'", ".", "format", "(", "stats_str", ")", ")", "if", "is_multi", ":", "print", "(", "'Statistics:\\n{0}'", ".", "format", "(", "stats_str", ")", ",", "file", "=", "stderr", ")", "else", ":", "print_warn", "(", "'[{0}] Statistics: unavailable.'", ".", "format", "(", "idx", ")", ")", "if", "is_multi", ":", "print", "(", "'Statistics: unavailable.'", ",", "file", "=", "stderr", ")", "finally", ":", "if", "is_multi", ":", "stdout", ".", "close", "(", ")", "stderr", ".", "close", "(", ")", "def", "_run_cases_legacy", "(", ")", ":", "if", "session_id", "is", "None", ":", "session_id_prefix", "=", "token_hex", "(", "5", ")", "else", ":", "session_id_prefix", "=", "session_id", "vprint_info", "(", "'Session token prefix: {0}'", ".", "format", "(", "session_id_prefix", ")", ")", "vprint_info", "(", "'In the legacy mode, all cases will run serially!'", ")", "with", "Session", "(", ")", "as", "session", ":", "for", "idx", ",", "case", "in", "enumerate", "(", "case_set", ".", "keys", "(", ")", ")", ":", "if", "is_multi", ":", "_session_id", "=", "'{0}-{1}'", ".", "format", "(", "session_id_prefix", ",", "idx", ")", "else", ":", "_session_id", "=", "session_id_prefix", "envs", "=", "dict", "(", "case", "[", "0", "]", ")", "clean_cmd", "=", "clean", "if", "clean", "else", "'*'", "build_cmd", "=", "case", "[", "1", "]", "exec_cmd", "=", "case", "[", "2", "]", "_run_legacy", "(", "session", ",", "idx", ",", "_session_id", ",", "envs", ",", "clean_cmd", ",", "build_cmd", ",", "exec_cmd", ")", "async", "def", "_run_cases", "(", ")", ":", "loop", "=", "current_loop", "(", ")", "if", "session_id", "is", "None", ":", "session_id_prefix", "=", "token_hex", "(", "5", ")", "else", ":", "session_id_prefix", "=", "session_id", "vprint_info", "(", "'Session token prefix: {0}'", ".", "format", "(", "session_id_prefix", ")", ")", "if", "is_multi", ":", "print_info", "(", "'Check out the stdout/stderr logs stored in '", "'~/.cache/backend.ai/client-logs directory.'", ")", "async", "with", "AsyncSession", "(", ")", "as", "session", ":", "tasks", "=", "[", "]", "# TODO: limit max-parallelism using aiojobs", "for", "idx", ",", "case", "in", "enumerate", "(", "case_set", ".", "keys", "(", ")", ")", ":", "if", "is_multi", ":", "_session_id", "=", "'{0}-{1}'", ".", "format", "(", "session_id_prefix", ",", "idx", ")", "else", ":", "_session_id", "=", "session_id_prefix", "envs", "=", "dict", "(", "case", "[", "0", "]", ")", "clean_cmd", "=", "clean", "if", "clean", "else", "'*'", "build_cmd", "=", "case", "[", "1", "]", "exec_cmd", "=", "case", "[", "2", "]", "t", "=", "loop", ".", "create_task", "(", "_run", "(", "session", ",", "idx", ",", "_session_id", ",", "envs", ",", "clean_cmd", ",", "build_cmd", ",", "exec_cmd", ",", "is_multi", "=", "is_multi", ")", ")", "tasks", ".", "append", "(", "t", ")", "results", "=", "await", "asyncio", ".", "gather", "(", "*", "tasks", ",", "return_exceptions", "=", "True", ")", "if", "any", "(", "map", "(", "lambda", "r", ":", "isinstance", "(", "r", ",", "Exception", ")", ",", "results", ")", ")", ":", "if", "is_multi", ":", "print_fail", "(", "'There were failed cases!'", ")", "sys", ".", "exit", "(", "1", ")", "if", "is_legacy_server", "(", ")", ":", "_run_cases_legacy", "(", ")", "else", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "try", ":", "loop", ".", "run_until_complete", "(", "_run_cases", "(", ")", ")", "finally", ":", "loop", ".", "close", "(", ")" ]
Run the given code snippet or files in a session. Depending on the session ID you give (default is random), it may reuse an existing session or create a new one. \b LANG: The name (and version/platform tags appended after a colon) of session runtime or programming language.') FILES: The code file(s). Can be added multiple times.
[ "Run", "the", "given", "code", "snippet", "or", "files", "in", "a", "session", ".", "Depending", "on", "the", "session", "ID", "you", "give", "(", "default", "is", "random", ")", "it", "may", "reuse", "an", "existing", "session", "or", "create", "a", "new", "one", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L273-L584
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
start
def start(lang, session_id, owner, env, mount, tag, resources, cluster_size): ''' Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" command. \b LANG: The name (and version/platform tags appended after a colon) of session runtime or programming language. ''' if session_id is None: session_id = token_hex(5) else: session_id = session_id ###### envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) with Session() as session: try: kernel = session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, owner_access_key=owner, tag=tag) except Exception as e: print_error(e) sys.exit(1) else: if kernel.created: print_info('Session ID {0} is created and ready.' .format(session_id)) else: print_info('Session ID {0} is already running and ready.' .format(session_id)) if kernel.service_ports: print_info('This session provides the following app services: ' + ', '.join(sport['name'] for sport in kernel.service_ports))
python
def start(lang, session_id, owner, env, mount, tag, resources, cluster_size): ''' Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" command. \b LANG: The name (and version/platform tags appended after a colon) of session runtime or programming language. ''' if session_id is None: session_id = token_hex(5) else: session_id = session_id ###### envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) with Session() as session: try: kernel = session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, owner_access_key=owner, tag=tag) except Exception as e: print_error(e) sys.exit(1) else: if kernel.created: print_info('Session ID {0} is created and ready.' .format(session_id)) else: print_info('Session ID {0} is already running and ready.' .format(session_id)) if kernel.service_ports: print_info('This session provides the following app services: ' + ', '.join(sport['name'] for sport in kernel.service_ports))
[ "def", "start", "(", "lang", ",", "session_id", ",", "owner", ",", "env", ",", "mount", ",", "tag", ",", "resources", ",", "cluster_size", ")", ":", "if", "session_id", "is", "None", ":", "session_id", "=", "token_hex", "(", "5", ")", "else", ":", "session_id", "=", "session_id", "######", "envs", "=", "_prepare_env_arg", "(", "env", ")", "resources", "=", "_prepare_resource_arg", "(", "resources", ")", "mount", "=", "_prepare_mount_arg", "(", "mount", ")", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "kernel", "=", "session", ".", "Kernel", ".", "get_or_create", "(", "lang", ",", "client_token", "=", "session_id", ",", "cluster_size", "=", "cluster_size", ",", "mounts", "=", "mount", ",", "envs", "=", "envs", ",", "resources", "=", "resources", ",", "owner_access_key", "=", "owner", ",", "tag", "=", "tag", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "if", "kernel", ".", "created", ":", "print_info", "(", "'Session ID {0} is created and ready.'", ".", "format", "(", "session_id", ")", ")", "else", ":", "print_info", "(", "'Session ID {0} is already running and ready.'", ".", "format", "(", "session_id", ")", ")", "if", "kernel", ".", "service_ports", ":", "print_info", "(", "'This session provides the following app services: '", "+", "', '", ".", "join", "(", "sport", "[", "'name'", "]", "for", "sport", "in", "kernel", ".", "service_ports", ")", ")" ]
Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" command. \b LANG: The name (and version/platform tags appended after a colon) of session runtime or programming language.
[ "Prepare", "and", "start", "a", "single", "compute", "session", "without", "executing", "codes", ".", "You", "may", "use", "the", "created", "session", "to", "execute", "codes", "using", "the", "run", "command", "or", "connect", "to", "an", "application", "service", "provided", "by", "the", "session", "using", "the", "app", "command", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L607-L652
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/run.py
terminate
def terminate(sess_id_or_alias, owner, stats): ''' Terminate the given session. SESSID: session ID or its alias given when creating the session. ''' print_wait('Terminating the session(s)...') with Session() as session: has_failure = False for sess in sess_id_or_alias: try: kernel = session.Kernel(sess, owner) ret = kernel.destroy() except BackendAPIError as e: print_error(e) if e.status == 404: print_info( 'If you are an admin, use "-o" / "--owner" option ' 'to terminate other user\'s session.') has_failure = True except Exception as e: print_error(e) has_failure = True if has_failure: sys.exit(1) else: print_done('Done.') if stats: stats = ret.get('stats', None) if ret else None if stats: print(_format_stats(stats)) else: print('Statistics is not available.')
python
def terminate(sess_id_or_alias, owner, stats): ''' Terminate the given session. SESSID: session ID or its alias given when creating the session. ''' print_wait('Terminating the session(s)...') with Session() as session: has_failure = False for sess in sess_id_or_alias: try: kernel = session.Kernel(sess, owner) ret = kernel.destroy() except BackendAPIError as e: print_error(e) if e.status == 404: print_info( 'If you are an admin, use "-o" / "--owner" option ' 'to terminate other user\'s session.') has_failure = True except Exception as e: print_error(e) has_failure = True if has_failure: sys.exit(1) else: print_done('Done.') if stats: stats = ret.get('stats', None) if ret else None if stats: print(_format_stats(stats)) else: print('Statistics is not available.')
[ "def", "terminate", "(", "sess_id_or_alias", ",", "owner", ",", "stats", ")", ":", "print_wait", "(", "'Terminating the session(s)...'", ")", "with", "Session", "(", ")", "as", "session", ":", "has_failure", "=", "False", "for", "sess", "in", "sess_id_or_alias", ":", "try", ":", "kernel", "=", "session", ".", "Kernel", "(", "sess", ",", "owner", ")", "ret", "=", "kernel", ".", "destroy", "(", ")", "except", "BackendAPIError", "as", "e", ":", "print_error", "(", "e", ")", "if", "e", ".", "status", "==", "404", ":", "print_info", "(", "'If you are an admin, use \"-o\" / \"--owner\" option '", "'to terminate other user\\'s session.'", ")", "has_failure", "=", "True", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "has_failure", "=", "True", "if", "has_failure", ":", "sys", ".", "exit", "(", "1", ")", "else", ":", "print_done", "(", "'Done.'", ")", "if", "stats", ":", "stats", "=", "ret", ".", "get", "(", "'stats'", ",", "None", ")", "if", "ret", "else", "None", "if", "stats", ":", "print", "(", "_format_stats", "(", "stats", ")", ")", "else", ":", "print", "(", "'Statistics is not available.'", ")" ]
Terminate the given session. SESSID: session ID or its alias given when creating the session.
[ "Terminate", "the", "given", "session", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/run.py#L661-L693
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/groups.py
get_custom_view_details
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0] """ view_id = get_custom_views(auth, url, name=name)[0]['symbolId'] get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + get_custom_view_details_url r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 200: current_devices = (json.loads(r.text)) if 'device' in current_devices: return current_devices['device'] else: return [] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_custom_views: An Error has occured'
python
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0] """ view_id = get_custom_views(auth, url, name=name)[0]['symbolId'] get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + get_custom_view_details_url r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 200: current_devices = (json.loads(r.text)) if 'device' in current_devices: return current_devices['device'] else: return [] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_custom_views: An Error has occured'
[ "def", "get_custom_view_details", "(", "name", ",", "auth", ",", "url", ")", ":", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "name", ")", "[", "0", "]", "[", "'symbolId'", "]", "get_custom_view_details_url", "=", "'/imcrs/plat/res/view/custom/'", "+", "str", "(", "view_id", ")", "f_url", "=", "url", "+", "get_custom_view_details_url", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "# creates the URL using the payload variable as the contents", "try", ":", "if", "r", ".", "status_code", "==", "200", ":", "current_devices", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "'device'", "in", "current_devices", ":", "return", "current_devices", "[", "'device'", "]", "else", ":", "return", "[", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' get_custom_views: An Error has occured'" ]
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0]
[ "function", "requires", "no", "input", "and", "returns", "a", "list", "of", "dictionaries", "of", "custom", "views", "from", "an", "HPE", "IMC", ".", "Optional", "name", "argument", "will", "return", "only", "the", "specified", "view", ".", ":", "param", "name", ":", "str", "containing", "the", "name", "of", "the", "desired", "custom", "view" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/groups.py#L72-L114
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/groups.py
add_devs_custom_views
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") """ view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId'] add_devs_custom_views_url = '/imcrs/plat/res/view/custom/'+str(view_id) payload = '''{"device" : '''+ json.dumps(dev_list) + '''}''' f_url = url + add_devs_custom_views_url r = requests.put(f_url, data = payload, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 204: print ('View ' + custom_view_name +' : Devices Successfully Added') return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_custom_views: An Error has occured'
python
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") """ view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId'] add_devs_custom_views_url = '/imcrs/plat/res/view/custom/'+str(view_id) payload = '''{"device" : '''+ json.dumps(dev_list) + '''}''' f_url = url + add_devs_custom_views_url r = requests.put(f_url, data = payload, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 204: print ('View ' + custom_view_name +' : Devices Successfully Added') return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_custom_views: An Error has occured'
[ "def", "add_devs_custom_views", "(", "custom_view_name", ",", "dev_list", ",", "auth", ",", "url", ")", ":", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "custom_view_name", ")", "[", "0", "]", "[", "'symbolId'", "]", "add_devs_custom_views_url", "=", "'/imcrs/plat/res/view/custom/'", "+", "str", "(", "view_id", ")", "payload", "=", "'''{\"device\" : '''", "+", "json", ".", "dumps", "(", "dev_list", ")", "+", "'''}'''", "f_url", "=", "url", "+", "add_devs_custom_views_url", "r", "=", "requests", ".", "put", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "# creates the URL using the payload variable as the contents", "try", ":", "if", "r", ".", "status_code", "==", "204", ":", "print", "(", "'View '", "+", "custom_view_name", "+", "' : Devices Successfully Added'", ")", "return", "r", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' get_custom_views: An Error has occured'" ]
function takes a list of devIDs from devices discovered in the HPE IMC platform and and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
[ "function", "takes", "a", "list", "of", "devIDs", "from", "devices", "discovered", "in", "the", "HPE", "IMC", "platform", "and", "and", "issues", "a", "RESTFUL", "call", "to", "add", "the", "list", "of", "devices", "to", "a", "specific", "custom", "views", "from", "HPE", "IMC", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/groups.py#L181-L213
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/groups.py
delete_custom_view
def delete_custom_view(auth, url, name): """ function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 == None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 == None """ view_id = get_custom_views(auth, url,name )[0]['symbolId'] delete_custom_view_url = '/imcrs/plat/res/view/custom/'+str(view_id) f_url = url + delete_custom_view_url r = requests.delete(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 204: return 'View ' + name +' deleted successfully' except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' delete_custom_view: An Error has occured'
python
def delete_custom_view(auth, url, name): """ function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 == None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 == None """ view_id = get_custom_views(auth, url,name )[0]['symbolId'] delete_custom_view_url = '/imcrs/plat/res/view/custom/'+str(view_id) f_url = url + delete_custom_view_url r = requests.delete(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 204: return 'View ' + name +' deleted successfully' except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' delete_custom_view: An Error has occured'
[ "def", "delete_custom_view", "(", "auth", ",", "url", ",", "name", ")", ":", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", ")", "[", "0", "]", "[", "'symbolId'", "]", "delete_custom_view_url", "=", "'/imcrs/plat/res/view/custom/'", "+", "str", "(", "view_id", ")", "f_url", "=", "url", "+", "delete_custom_view_url", "r", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "# creates the URL using the payload variable as the contents", "try", ":", "if", "r", ".", "status_code", "==", "204", ":", "return", "'View '", "+", "name", "+", "' deleted successfully'", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' delete_custom_view: An Error has occured'" ]
function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 == None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 == None
[ "function", "takes", "input", "of", "auth", "url", "and", "name", "and", "issues", "a", "RESTFUL", "call", "to", "delete", "a", "specific", "of", "custom", "views", "from", "HPE", "IMC", ".", ":", "param", "name", ":", "string", "containg", "the", "name", "of", "the", "desired", "custom", "view" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/groups.py#L217-L260
train
Tygs/ww
src/ww/tools/strings.py
multisplit
def multisplit(string, # type: unicode *separators, # type: unicode **kwargs # type: Union[unicode, C[..., I[unicode]]] ): # type: (...) -> I """ Like unicode.split, but accept several separators and regexes Args: string: the string to split. separators: strings you can split on. Each string can be a regex. maxsplit: max number of time you wish to split. default is 0, which means no limit. flags: flags you wish to pass if you use regexes. You should pass them as a string containing a combination of: - 'm' for re.MULTILINE - 'x' for re.VERBOSE - 'v' for re.VERBOSE - 's' for re.DOTALL - '.' for re.DOTALL - 'd' for re.DEBUG - 'i' for re.IGNORECASE - 'u' for re.UNICODE - 'l' for re.LOCALE cast: what to cast the result to Returns: An iterable of substrings. Raises: ValueError: if you pass a flag without separators. TypeError: if you pass something else than unicode strings. Example: >>> for word in multisplit(u'fat black cat, big'): print(word) fat black cat, big >>> string = u'a,b;c/d=a,b;c/d' >>> chunks = multisplit(string, u',', u';', u'[/=]', maxsplit=4) >>> for chunk in chunks: print(chunk) a b c d a,b;c/d """ cast = kwargs.pop('cast', list) flags = parse_re_flags(kwargs.get('flags', 0)) # 0 means "no limit" for re.split maxsplit = require_positive_number(kwargs.get('maxsplit', 0), 'maxsplit') # no separator means we use the default unicode.split behavior if not separators: if flags: raise ValueError(ww.s >> """ You can't pass flags without passing a separator. Flags only have sense if you split using a regex. """) maxsplit = maxsplit or -1 # -1 means "no limit" for unicode.split return unicode.split(string, None, maxsplit) # Check that all separators are strings for i, sep in enumerate(separators): if not isinstance(sep, unicode): raise TypeError(ww.s >> """ '{!r}', the separator at index '{}', is of type '{}'. multisplit() only accepts unicode strings. """.format(sep, i, type(sep))) # TODO: split let many empty strings in the result. Fix it. seps = list(separators) # cast to list so we can slice it # simple code for when you need to split the whole string if maxsplit == 0: return cast(_split(string, seps, flags)) # slow implementation with checks for recursive maxsplit return cast(_split_with_max(string, seps, maxsplit, flags))
python
def multisplit(string, # type: unicode *separators, # type: unicode **kwargs # type: Union[unicode, C[..., I[unicode]]] ): # type: (...) -> I """ Like unicode.split, but accept several separators and regexes Args: string: the string to split. separators: strings you can split on. Each string can be a regex. maxsplit: max number of time you wish to split. default is 0, which means no limit. flags: flags you wish to pass if you use regexes. You should pass them as a string containing a combination of: - 'm' for re.MULTILINE - 'x' for re.VERBOSE - 'v' for re.VERBOSE - 's' for re.DOTALL - '.' for re.DOTALL - 'd' for re.DEBUG - 'i' for re.IGNORECASE - 'u' for re.UNICODE - 'l' for re.LOCALE cast: what to cast the result to Returns: An iterable of substrings. Raises: ValueError: if you pass a flag without separators. TypeError: if you pass something else than unicode strings. Example: >>> for word in multisplit(u'fat black cat, big'): print(word) fat black cat, big >>> string = u'a,b;c/d=a,b;c/d' >>> chunks = multisplit(string, u',', u';', u'[/=]', maxsplit=4) >>> for chunk in chunks: print(chunk) a b c d a,b;c/d """ cast = kwargs.pop('cast', list) flags = parse_re_flags(kwargs.get('flags', 0)) # 0 means "no limit" for re.split maxsplit = require_positive_number(kwargs.get('maxsplit', 0), 'maxsplit') # no separator means we use the default unicode.split behavior if not separators: if flags: raise ValueError(ww.s >> """ You can't pass flags without passing a separator. Flags only have sense if you split using a regex. """) maxsplit = maxsplit or -1 # -1 means "no limit" for unicode.split return unicode.split(string, None, maxsplit) # Check that all separators are strings for i, sep in enumerate(separators): if not isinstance(sep, unicode): raise TypeError(ww.s >> """ '{!r}', the separator at index '{}', is of type '{}'. multisplit() only accepts unicode strings. """.format(sep, i, type(sep))) # TODO: split let many empty strings in the result. Fix it. seps = list(separators) # cast to list so we can slice it # simple code for when you need to split the whole string if maxsplit == 0: return cast(_split(string, seps, flags)) # slow implementation with checks for recursive maxsplit return cast(_split_with_max(string, seps, maxsplit, flags))
[ "def", "multisplit", "(", "string", ",", "# type: unicode", "*", "separators", ",", "# type: unicode", "*", "*", "kwargs", "# type: Union[unicode, C[..., I[unicode]]]", ")", ":", "# type: (...) -> I", "cast", "=", "kwargs", ".", "pop", "(", "'cast'", ",", "list", ")", "flags", "=", "parse_re_flags", "(", "kwargs", ".", "get", "(", "'flags'", ",", "0", ")", ")", "# 0 means \"no limit\" for re.split", "maxsplit", "=", "require_positive_number", "(", "kwargs", ".", "get", "(", "'maxsplit'", ",", "0", ")", ",", "'maxsplit'", ")", "# no separator means we use the default unicode.split behavior", "if", "not", "separators", ":", "if", "flags", ":", "raise", "ValueError", "(", "ww", ".", "s", ">>", "\"\"\"\n You can't pass flags without passing\n a separator. Flags only have sense if\n you split using a regex.\n \"\"\"", ")", "maxsplit", "=", "maxsplit", "or", "-", "1", "# -1 means \"no limit\" for unicode.split", "return", "unicode", ".", "split", "(", "string", ",", "None", ",", "maxsplit", ")", "# Check that all separators are strings", "for", "i", ",", "sep", "in", "enumerate", "(", "separators", ")", ":", "if", "not", "isinstance", "(", "sep", ",", "unicode", ")", ":", "raise", "TypeError", "(", "ww", ".", "s", ">>", "\"\"\"\n '{!r}', the separator at index '{}', is of type '{}'.\n multisplit() only accepts unicode strings.\n \"\"\"", ".", "format", "(", "sep", ",", "i", ",", "type", "(", "sep", ")", ")", ")", "# TODO: split let many empty strings in the result. Fix it.", "seps", "=", "list", "(", "separators", ")", "# cast to list so we can slice it", "# simple code for when you need to split the whole string", "if", "maxsplit", "==", "0", ":", "return", "cast", "(", "_split", "(", "string", ",", "seps", ",", "flags", ")", ")", "# slow implementation with checks for recursive maxsplit", "return", "cast", "(", "_split_with_max", "(", "string", ",", "seps", ",", "maxsplit", ",", "flags", ")", ")" ]
Like unicode.split, but accept several separators and regexes Args: string: the string to split. separators: strings you can split on. Each string can be a regex. maxsplit: max number of time you wish to split. default is 0, which means no limit. flags: flags you wish to pass if you use regexes. You should pass them as a string containing a combination of: - 'm' for re.MULTILINE - 'x' for re.VERBOSE - 'v' for re.VERBOSE - 's' for re.DOTALL - '.' for re.DOTALL - 'd' for re.DEBUG - 'i' for re.IGNORECASE - 'u' for re.UNICODE - 'l' for re.LOCALE cast: what to cast the result to Returns: An iterable of substrings. Raises: ValueError: if you pass a flag without separators. TypeError: if you pass something else than unicode strings. Example: >>> for word in multisplit(u'fat black cat, big'): print(word) fat black cat, big >>> string = u'a,b;c/d=a,b;c/d' >>> chunks = multisplit(string, u',', u';', u'[/=]', maxsplit=4) >>> for chunk in chunks: print(chunk) a b c d a,b;c/d
[ "Like", "unicode", ".", "split", "but", "accept", "several", "separators", "and", "regexes" ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/strings.py#L77-L163
train
Tygs/ww
src/ww/tools/strings.py
multireplace
def multireplace(string, # type: unicode patterns, # type: str_or_str_iterable substitutions, # type: str_istr_icallable maxreplace=0, # type: int flags=0 # type: unicode ): # type: (...) -> bool """ Like unicode.replace() but accept several substitutions and regexes Args: string: the string to split on. patterns: a string, or an iterable of strings to be replaced. substitutions: a string or an iterable of string to use as a replacement. You can pass either one string, or an iterable containing the same number of sustitutions that you passed as patterns. You can also pass a callable instead of a string. It should expact a match object as a parameter. maxreplace: the max number of replacement to make. 0 is no limit, which is the default. flags: flags you wish to pass if you use regexes. You should pass them as a string containing a combination of: - 'm' for re.MULTILINE - 'x' for re.VERBOSE - 'v' for re.VERBOSE - 's' for re.DOTALL - '.' for re.DOTALL - 'd' for re.DEBUG - 'i' for re.IGNORECASE - 'u' for re.UNICODE - 'l' for re.LOCALE Returns: The string with replaced bits. Raises: ValueError: if you pass the wrong number of substitution. Example: >>> print(multireplace(u'a,b;c/d', (u',', u';', u'/'), u',')) a,b,c,d >>> print(multireplace(u'a1b33c-d', u'\d+', u',')) a,b,c-d >>> print(multireplace(u'a-1,b-3,3c-d', u',|-', u'', maxreplace=3)) a1b3,3c-d >>> def upper(match): ... return match.group().upper() ... >>> print(multireplace(u'a-1,b-3,3c-d', u'[ab]', upper)) A-1,B-3,3c-d """ # we can pass either a string or an iterable of strings patterns = ensure_tuple(patterns) substitutions = ensure_tuple(substitutions) # you can either have: # - many patterns, one substitution # - many patterns, exactly as many substitutions # anything else is an error num_of_subs = len(substitutions) num_of_patterns = len(patterns) if num_of_subs == 1 and num_of_patterns > 0: substitutions *= num_of_patterns elif len(patterns) != num_of_subs: raise ValueError("You must have exactly one substitution " "for each pattern or only one substitution") flags = parse_re_flags(flags) # no limit for replacing, use a simple code if not maxreplace: for pattern, sub in zip(patterns, substitutions): string, count = re.subn(pattern, sub, string, flags=flags) return string # ensure we respect the max number of replace accross substitutions for pattern, sub in zip(patterns, substitutions): string, count = re.subn(pattern, sub, string, count=maxreplace, flags=flags) maxreplace -= count if maxreplace == 0: break return string
python
def multireplace(string, # type: unicode patterns, # type: str_or_str_iterable substitutions, # type: str_istr_icallable maxreplace=0, # type: int flags=0 # type: unicode ): # type: (...) -> bool """ Like unicode.replace() but accept several substitutions and regexes Args: string: the string to split on. patterns: a string, or an iterable of strings to be replaced. substitutions: a string or an iterable of string to use as a replacement. You can pass either one string, or an iterable containing the same number of sustitutions that you passed as patterns. You can also pass a callable instead of a string. It should expact a match object as a parameter. maxreplace: the max number of replacement to make. 0 is no limit, which is the default. flags: flags you wish to pass if you use regexes. You should pass them as a string containing a combination of: - 'm' for re.MULTILINE - 'x' for re.VERBOSE - 'v' for re.VERBOSE - 's' for re.DOTALL - '.' for re.DOTALL - 'd' for re.DEBUG - 'i' for re.IGNORECASE - 'u' for re.UNICODE - 'l' for re.LOCALE Returns: The string with replaced bits. Raises: ValueError: if you pass the wrong number of substitution. Example: >>> print(multireplace(u'a,b;c/d', (u',', u';', u'/'), u',')) a,b,c,d >>> print(multireplace(u'a1b33c-d', u'\d+', u',')) a,b,c-d >>> print(multireplace(u'a-1,b-3,3c-d', u',|-', u'', maxreplace=3)) a1b3,3c-d >>> def upper(match): ... return match.group().upper() ... >>> print(multireplace(u'a-1,b-3,3c-d', u'[ab]', upper)) A-1,B-3,3c-d """ # we can pass either a string or an iterable of strings patterns = ensure_tuple(patterns) substitutions = ensure_tuple(substitutions) # you can either have: # - many patterns, one substitution # - many patterns, exactly as many substitutions # anything else is an error num_of_subs = len(substitutions) num_of_patterns = len(patterns) if num_of_subs == 1 and num_of_patterns > 0: substitutions *= num_of_patterns elif len(patterns) != num_of_subs: raise ValueError("You must have exactly one substitution " "for each pattern or only one substitution") flags = parse_re_flags(flags) # no limit for replacing, use a simple code if not maxreplace: for pattern, sub in zip(patterns, substitutions): string, count = re.subn(pattern, sub, string, flags=flags) return string # ensure we respect the max number of replace accross substitutions for pattern, sub in zip(patterns, substitutions): string, count = re.subn(pattern, sub, string, count=maxreplace, flags=flags) maxreplace -= count if maxreplace == 0: break return string
[ "def", "multireplace", "(", "string", ",", "# type: unicode", "patterns", ",", "# type: str_or_str_iterable", "substitutions", ",", "# type: str_istr_icallable", "maxreplace", "=", "0", ",", "# type: int", "flags", "=", "0", "# type: unicode", ")", ":", "# type: (...) -> bool", "# we can pass either a string or an iterable of strings", "patterns", "=", "ensure_tuple", "(", "patterns", ")", "substitutions", "=", "ensure_tuple", "(", "substitutions", ")", "# you can either have:", "# - many patterns, one substitution", "# - many patterns, exactly as many substitutions", "# anything else is an error", "num_of_subs", "=", "len", "(", "substitutions", ")", "num_of_patterns", "=", "len", "(", "patterns", ")", "if", "num_of_subs", "==", "1", "and", "num_of_patterns", ">", "0", ":", "substitutions", "*=", "num_of_patterns", "elif", "len", "(", "patterns", ")", "!=", "num_of_subs", ":", "raise", "ValueError", "(", "\"You must have exactly one substitution \"", "\"for each pattern or only one substitution\"", ")", "flags", "=", "parse_re_flags", "(", "flags", ")", "# no limit for replacing, use a simple code", "if", "not", "maxreplace", ":", "for", "pattern", ",", "sub", "in", "zip", "(", "patterns", ",", "substitutions", ")", ":", "string", ",", "count", "=", "re", ".", "subn", "(", "pattern", ",", "sub", ",", "string", ",", "flags", "=", "flags", ")", "return", "string", "# ensure we respect the max number of replace accross substitutions", "for", "pattern", ",", "sub", "in", "zip", "(", "patterns", ",", "substitutions", ")", ":", "string", ",", "count", "=", "re", ".", "subn", "(", "pattern", ",", "sub", ",", "string", ",", "count", "=", "maxreplace", ",", "flags", "=", "flags", ")", "maxreplace", "-=", "count", "if", "maxreplace", "==", "0", ":", "break", "return", "string" ]
Like unicode.replace() but accept several substitutions and regexes Args: string: the string to split on. patterns: a string, or an iterable of strings to be replaced. substitutions: a string or an iterable of string to use as a replacement. You can pass either one string, or an iterable containing the same number of sustitutions that you passed as patterns. You can also pass a callable instead of a string. It should expact a match object as a parameter. maxreplace: the max number of replacement to make. 0 is no limit, which is the default. flags: flags you wish to pass if you use regexes. You should pass them as a string containing a combination of: - 'm' for re.MULTILINE - 'x' for re.VERBOSE - 'v' for re.VERBOSE - 's' for re.DOTALL - '.' for re.DOTALL - 'd' for re.DEBUG - 'i' for re.IGNORECASE - 'u' for re.UNICODE - 'l' for re.LOCALE Returns: The string with replaced bits. Raises: ValueError: if you pass the wrong number of substitution. Example: >>> print(multireplace(u'a,b;c/d', (u',', u';', u'/'), u',')) a,b,c,d >>> print(multireplace(u'a1b33c-d', u'\d+', u',')) a,b,c-d >>> print(multireplace(u'a-1,b-3,3c-d', u',|-', u'', maxreplace=3)) a1b3,3c-d >>> def upper(match): ... return match.group().upper() ... >>> print(multireplace(u'a-1,b-3,3c-d', u'[ab]', upper)) A-1,B-3,3c-d
[ "Like", "unicode", ".", "replace", "()", "but", "accept", "several", "substitutions", "and", "regexes" ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/strings.py#L214-L300
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/manager.py
status
def status(): '''Show the manager's current status.''' with Session() as session: resp = session.Manager.status() print(tabulate([('Status', 'Active Sessions'), (resp['status'], resp['active_sessions'])], headers='firstrow'))
python
def status(): '''Show the manager's current status.''' with Session() as session: resp = session.Manager.status() print(tabulate([('Status', 'Active Sessions'), (resp['status'], resp['active_sessions'])], headers='firstrow'))
[ "def", "status", "(", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "resp", "=", "session", ".", "Manager", ".", "status", "(", ")", "print", "(", "tabulate", "(", "[", "(", "'Status'", ",", "'Active Sessions'", ")", ",", "(", "resp", "[", "'status'", "]", ",", "resp", "[", "'active_sessions'", "]", ")", "]", ",", "headers", "=", "'firstrow'", ")", ")" ]
Show the manager's current status.
[ "Show", "the", "manager", "s", "current", "status", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/manager.py#L19-L25
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/manager.py
freeze
def freeze(wait, force_kill): '''Freeze manager.''' if wait and force_kill: print('You cannot use both --wait and --force-kill options ' 'at the same time.', file=sys.stderr) return with Session() as session: if wait: while True: resp = session.Manager.status() active_sessions_num = resp['active_sessions'] if active_sessions_num == 0: break print_wait('Waiting for all sessions terminated... ({0} left)' .format(active_sessions_num)) time.sleep(3) print_done('All sessions are terminated.') if force_kill: print_wait('Killing all sessions...') session.Manager.freeze(force_kill=force_kill) if force_kill: print_done('All sessions are killed.') print('Manager is successfully frozen.')
python
def freeze(wait, force_kill): '''Freeze manager.''' if wait and force_kill: print('You cannot use both --wait and --force-kill options ' 'at the same time.', file=sys.stderr) return with Session() as session: if wait: while True: resp = session.Manager.status() active_sessions_num = resp['active_sessions'] if active_sessions_num == 0: break print_wait('Waiting for all sessions terminated... ({0} left)' .format(active_sessions_num)) time.sleep(3) print_done('All sessions are terminated.') if force_kill: print_wait('Killing all sessions...') session.Manager.freeze(force_kill=force_kill) if force_kill: print_done('All sessions are killed.') print('Manager is successfully frozen.')
[ "def", "freeze", "(", "wait", ",", "force_kill", ")", ":", "if", "wait", "and", "force_kill", ":", "print", "(", "'You cannot use both --wait and --force-kill options '", "'at the same time.'", ",", "file", "=", "sys", ".", "stderr", ")", "return", "with", "Session", "(", ")", "as", "session", ":", "if", "wait", ":", "while", "True", ":", "resp", "=", "session", ".", "Manager", ".", "status", "(", ")", "active_sessions_num", "=", "resp", "[", "'active_sessions'", "]", "if", "active_sessions_num", "==", "0", ":", "break", "print_wait", "(", "'Waiting for all sessions terminated... ({0} left)'", ".", "format", "(", "active_sessions_num", ")", ")", "time", ".", "sleep", "(", "3", ")", "print_done", "(", "'All sessions are terminated.'", ")", "if", "force_kill", ":", "print_wait", "(", "'Killing all sessions...'", ")", "session", ".", "Manager", ".", "freeze", "(", "force_kill", "=", "force_kill", ")", "if", "force_kill", ":", "print_done", "(", "'All sessions are killed.'", ")", "print", "(", "'Manager is successfully frozen.'", ")" ]
Freeze manager.
[ "Freeze", "manager", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/manager.py#L34-L61
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
get_dev_vlans
def get_dev_vlans(auth, url, devid=None, devip=None): """Function takes input of devID to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devId as the only input parameter :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents one vlan on the target device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> vlans = get_dev_vlans('350', auth.creds, auth.url) >>> assert type(vlans) is list >>> assert 'vlanId' in vlans[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_dev_vlans_url = "/imcrs/vlan?devId=" + str(devid) + "&start=0&size=5000&total=false" f_url = url + get_dev_vlans_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_vlans = (json.loads(response.text)) return dev_vlans['vlan'] elif response.status_code == 409: return {'vlan': 'no vlans'} except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_vlans: An Error has occured'
python
def get_dev_vlans(auth, url, devid=None, devip=None): """Function takes input of devID to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devId as the only input parameter :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents one vlan on the target device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> vlans = get_dev_vlans('350', auth.creds, auth.url) >>> assert type(vlans) is list >>> assert 'vlanId' in vlans[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_dev_vlans_url = "/imcrs/vlan?devId=" + str(devid) + "&start=0&size=5000&total=false" f_url = url + get_dev_vlans_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_vlans = (json.loads(response.text)) return dev_vlans['vlan'] elif response.status_code == 409: return {'vlan': 'no vlans'} except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_vlans: An Error has occured'
[ "def", "get_dev_vlans", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "get_dev_vlans_url", "=", "\"/imcrs/vlan?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&start=0&size=5000&total=false\"", "f_url", "=", "url", "+", "get_dev_vlans_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_vlans", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "return", "dev_vlans", "[", "'vlan'", "]", "elif", "response", ".", "status_code", "==", "409", ":", "return", "{", "'vlan'", ":", "'no vlans'", "}", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_dev_vlans: An Error has occured'" ]
Function takes input of devID to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devId as the only input parameter :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents one vlan on the target device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> vlans = get_dev_vlans('350', auth.creds, auth.url) >>> assert type(vlans) is list >>> assert 'vlanId' in vlans[0]
[ "Function", "takes", "input", "of", "devID", "to", "issue", "RESTUL", "call", "to", "HP", "IMC" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L23-L64
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
get_trunk_interfaces
def get_trunk_interfaces(auth, url, devid=None, devip=None): """Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN trunk port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> trunk_interfaces = get_trunk_interfaces('10', auth.creds, auth.url) >>> assert type(trunk_interfaces) is list >>> assert len(trunk_interfaces[0]) == 3 >>> assert 'allowedVlans' in trunk_interfaces[0] >>> assert 'ifIndex' in trunk_interfaces[0] >>> assert 'pvid' in trunk_interfaces[0] >>> get_trunk_interfaces('350', auth.creds, auth.url) ['No trunk inteface'] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_trunk_interfaces_url = "/imcrs/vlan/trunk?devId=" + str(devid) + \ "&start=1&size=5000&total=false" f_url = url + get_trunk_interfaces_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_trunk_interfaces = (json.loads(response.text)) if len(dev_trunk_interfaces) == 2: if isinstance(dev_trunk_interfaces['trunkIf'], list): return dev_trunk_interfaces['trunkIf'] elif isinstance(dev_trunk_interfaces['trunkIf'], dict): return [dev_trunk_interfaces['trunkIf']] else: dev_trunk_interfaces['trunkIf'] = ["No trunk inteface"] return dev_trunk_interfaces['trunkIf'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_trunk_interfaces: An Error has occured'
python
def get_trunk_interfaces(auth, url, devid=None, devip=None): """Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN trunk port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> trunk_interfaces = get_trunk_interfaces('10', auth.creds, auth.url) >>> assert type(trunk_interfaces) is list >>> assert len(trunk_interfaces[0]) == 3 >>> assert 'allowedVlans' in trunk_interfaces[0] >>> assert 'ifIndex' in trunk_interfaces[0] >>> assert 'pvid' in trunk_interfaces[0] >>> get_trunk_interfaces('350', auth.creds, auth.url) ['No trunk inteface'] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_trunk_interfaces_url = "/imcrs/vlan/trunk?devId=" + str(devid) + \ "&start=1&size=5000&total=false" f_url = url + get_trunk_interfaces_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_trunk_interfaces = (json.loads(response.text)) if len(dev_trunk_interfaces) == 2: if isinstance(dev_trunk_interfaces['trunkIf'], list): return dev_trunk_interfaces['trunkIf'] elif isinstance(dev_trunk_interfaces['trunkIf'], dict): return [dev_trunk_interfaces['trunkIf']] else: dev_trunk_interfaces['trunkIf'] = ["No trunk inteface"] return dev_trunk_interfaces['trunkIf'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_trunk_interfaces: An Error has occured'
[ "def", "get_trunk_interfaces", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "get_trunk_interfaces_url", "=", "\"/imcrs/vlan/trunk?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&start=1&size=5000&total=false\"", "f_url", "=", "url", "+", "get_trunk_interfaces_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_trunk_interfaces", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "len", "(", "dev_trunk_interfaces", ")", "==", "2", ":", "if", "isinstance", "(", "dev_trunk_interfaces", "[", "'trunkIf'", "]", ",", "list", ")", ":", "return", "dev_trunk_interfaces", "[", "'trunkIf'", "]", "elif", "isinstance", "(", "dev_trunk_interfaces", "[", "'trunkIf'", "]", ",", "dict", ")", ":", "return", "[", "dev_trunk_interfaces", "[", "'trunkIf'", "]", "]", "else", ":", "dev_trunk_interfaces", "[", "'trunkIf'", "]", "=", "[", "\"No trunk inteface\"", "]", "return", "dev_trunk_interfaces", "[", "'trunkIf'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_trunk_interfaces: An Error has occured'" ]
Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN trunk port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> trunk_interfaces = get_trunk_interfaces('10', auth.creds, auth.url) >>> assert type(trunk_interfaces) is list >>> assert len(trunk_interfaces[0]) == 3 >>> assert 'allowedVlans' in trunk_interfaces[0] >>> assert 'ifIndex' in trunk_interfaces[0] >>> assert 'pvid' in trunk_interfaces[0] >>> get_trunk_interfaces('350', auth.creds, auth.url) ['No trunk inteface']
[ "Function", "takes", "devId", "as", "input", "to", "RESTFULL", "call", "to", "HP", "IMC", "platform" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L67-L123
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
get_device_access_interfaces
def get_device_access_interfaces(auth, url, devid=None, devip=None): """ Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN access port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> access_interfaces = get_device_access_interfaces('10', auth.creds, auth.url) >>> assert type(access_interfaces) is list >>> assert (len(access_interfaces[0])) is 2 >>> assert 'ifIndex' in access_interfaces[0] >>> assert 'pvid' in access_interfaces[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devid) + \ "&start=1&size=500&total=false" f_url = url + get_access_interface_vlan_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_access_interfaces = (json.loads(response.text)) if type(dev_access_interfaces['accessIf']) is dict: return [dev_access_interfaces['accessIf']] if len(dev_access_interfaces) == 2: return dev_access_interfaces['accessIf'] else: dev_access_interfaces['accessIf'] = ["No access inteface"] return dev_access_interfaces['accessIf'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_access_interfaces: An Error has occured"
python
def get_device_access_interfaces(auth, url, devid=None, devip=None): """ Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN access port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> access_interfaces = get_device_access_interfaces('10', auth.creds, auth.url) >>> assert type(access_interfaces) is list >>> assert (len(access_interfaces[0])) is 2 >>> assert 'ifIndex' in access_interfaces[0] >>> assert 'pvid' in access_interfaces[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devid) + \ "&start=1&size=500&total=false" f_url = url + get_access_interface_vlan_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_access_interfaces = (json.loads(response.text)) if type(dev_access_interfaces['accessIf']) is dict: return [dev_access_interfaces['accessIf']] if len(dev_access_interfaces) == 2: return dev_access_interfaces['accessIf'] else: dev_access_interfaces['accessIf'] = ["No access inteface"] return dev_access_interfaces['accessIf'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_access_interfaces: An Error has occured"
[ "def", "get_device_access_interfaces", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "get_access_interface_vlan_url", "=", "\"/imcrs/vlan/access?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&start=1&size=500&total=false\"", "f_url", "=", "url", "+", "get_access_interface_vlan_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_access_interfaces", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "type", "(", "dev_access_interfaces", "[", "'accessIf'", "]", ")", "is", "dict", ":", "return", "[", "dev_access_interfaces", "[", "'accessIf'", "]", "]", "if", "len", "(", "dev_access_interfaces", ")", "==", "2", ":", "return", "dev_access_interfaces", "[", "'accessIf'", "]", "else", ":", "dev_access_interfaces", "[", "'accessIf'", "]", "=", "[", "\"No access inteface\"", "]", "return", "dev_access_interfaces", "[", "'accessIf'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_device_access_interfaces: An Error has occured\"" ]
Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN access port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> access_interfaces = get_device_access_interfaces('10', auth.creds, auth.url) >>> assert type(access_interfaces) is list >>> assert (len(access_interfaces[0])) is 2 >>> assert 'ifIndex' in access_interfaces[0] >>> assert 'pvid' in access_interfaces[0]
[ "Function", "takes", "devid", "pr", "devip", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC", "platform" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L126-L178
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
get_device_hybrid_interfaces
def get_device_hybrid_interfaces(auth, url, devid=None, devip=None): """ Function takes devId as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN access port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> hybrid_interfaces = get_device_hybrid_interfaces('10', auth.creds, auth.url) >>> assert type(access_interfaces) is list >>> assert (len(access_interfaces[0])) is 2 >>> assert 'ifIndex' in access_interfaces[0] >>> assert 'pvid' in access_interfaces[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_hybrid_interface_vlan_url = "/imcrs/vlan/hybrid?devId=" + str(devid) + \ "&start=1&size=500&total=false" f_url = url + get_hybrid_interface_vlan_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_hybrid_interfaces = (json.loads(response.text)) if len(dev_hybrid_interfaces) == 2: dev_hybrid = dev_hybrid_interfaces['hybridIf'] if isinstance(dev_hybrid, dict): dev_hybrid = [dev_hybrid] return dev_hybrid else: dev_hybrid_interfaces['hybridIf'] = ["No hybrid inteface"] return dev_hybrid_interfaces['hybridIf'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_hybrid_interfaces: An Error has occured"
python
def get_device_hybrid_interfaces(auth, url, devid=None, devip=None): """ Function takes devId as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN access port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> hybrid_interfaces = get_device_hybrid_interfaces('10', auth.creds, auth.url) >>> assert type(access_interfaces) is list >>> assert (len(access_interfaces[0])) is 2 >>> assert 'ifIndex' in access_interfaces[0] >>> assert 'pvid' in access_interfaces[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_hybrid_interface_vlan_url = "/imcrs/vlan/hybrid?devId=" + str(devid) + \ "&start=1&size=500&total=false" f_url = url + get_hybrid_interface_vlan_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_hybrid_interfaces = (json.loads(response.text)) if len(dev_hybrid_interfaces) == 2: dev_hybrid = dev_hybrid_interfaces['hybridIf'] if isinstance(dev_hybrid, dict): dev_hybrid = [dev_hybrid] return dev_hybrid else: dev_hybrid_interfaces['hybridIf'] = ["No hybrid inteface"] return dev_hybrid_interfaces['hybridIf'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_hybrid_interfaces: An Error has occured"
[ "def", "get_device_hybrid_interfaces", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "get_hybrid_interface_vlan_url", "=", "\"/imcrs/vlan/hybrid?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&start=1&size=500&total=false\"", "f_url", "=", "url", "+", "get_hybrid_interface_vlan_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_hybrid_interfaces", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "len", "(", "dev_hybrid_interfaces", ")", "==", "2", ":", "dev_hybrid", "=", "dev_hybrid_interfaces", "[", "'hybridIf'", "]", "if", "isinstance", "(", "dev_hybrid", ",", "dict", ")", ":", "dev_hybrid", "=", "[", "dev_hybrid", "]", "return", "dev_hybrid", "else", ":", "dev_hybrid_interfaces", "[", "'hybridIf'", "]", "=", "[", "\"No hybrid inteface\"", "]", "return", "dev_hybrid_interfaces", "[", "'hybridIf'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_device_hybrid_interfaces: An Error has occured\"" ]
Function takes devId as input to RESTFUL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: list of dictionaries where each element of the list represents an interface which has been configured as a VLAN access port :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> hybrid_interfaces = get_device_hybrid_interfaces('10', auth.creds, auth.url) >>> assert type(access_interfaces) is list >>> assert (len(access_interfaces[0])) is 2 >>> assert 'ifIndex' in access_interfaces[0] >>> assert 'pvid' in access_interfaces[0]
[ "Function", "takes", "devId", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC", "platform" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L184-L237
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
add_hybrid_interface
def add_hybrid_interface(ifindex, pvid, taggedvlans, untaggedvlans, auth, url, devip=None, devid=None): """ Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid port to a HPE Comware based switch. These functions only apply to HPE Comware based devices. :param ifindex: str ifIndex value of target interface :param pvid: str 802.1q value (1-4094) of target VLAN :param taggedvlans: str 802.1q value, seperated by commas, of target tagged VLANs :param untaggedvlans: str 802.1q value, seperated by commas, of target untagged VLANs :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return int of http response code :rtype int """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] add_hybrid_interface_url = "/imcrs/vlan/hybrid?devId=" + str(devid) + \ "&start=1&size=500&total=false" f_url = url + add_hybrid_interface_url payload = '''{"ifIndex": "''' + ifindex + '''", "pvid": "''' + pvid + '''", "taggedVlans": "''' + taggedvlans + '''", "untagVlanFlag": "true", "untaggedVlans": "''' + untaggedvlans + '''" }''' response = requests.post(f_url, auth=auth, data=payload, headers=HEADERS) try: if response.status_code == 201: return 201 if response.status_code == 409: return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_hybrid_interfaces: An Error has occured"
python
def add_hybrid_interface(ifindex, pvid, taggedvlans, untaggedvlans, auth, url, devip=None, devid=None): """ Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid port to a HPE Comware based switch. These functions only apply to HPE Comware based devices. :param ifindex: str ifIndex value of target interface :param pvid: str 802.1q value (1-4094) of target VLAN :param taggedvlans: str 802.1q value, seperated by commas, of target tagged VLANs :param untaggedvlans: str 802.1q value, seperated by commas, of target untagged VLANs :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return int of http response code :rtype int """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] add_hybrid_interface_url = "/imcrs/vlan/hybrid?devId=" + str(devid) + \ "&start=1&size=500&total=false" f_url = url + add_hybrid_interface_url payload = '''{"ifIndex": "''' + ifindex + '''", "pvid": "''' + pvid + '''", "taggedVlans": "''' + taggedvlans + '''", "untagVlanFlag": "true", "untaggedVlans": "''' + untaggedvlans + '''" }''' response = requests.post(f_url, auth=auth, data=payload, headers=HEADERS) try: if response.status_code == 201: return 201 if response.status_code == 409: return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_hybrid_interfaces: An Error has occured"
[ "def", "add_hybrid_interface", "(", "ifindex", ",", "pvid", ",", "taggedvlans", ",", "untaggedvlans", ",", "auth", ",", "url", ",", "devip", "=", "None", ",", "devid", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "add_hybrid_interface_url", "=", "\"/imcrs/vlan/hybrid?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&start=1&size=500&total=false\"", "f_url", "=", "url", "+", "add_hybrid_interface_url", "payload", "=", "'''{\"ifIndex\": \"'''", "+", "ifindex", "+", "'''\",\n \"pvid\": \"'''", "+", "pvid", "+", "'''\",\n \"taggedVlans\": \"'''", "+", "taggedvlans", "+", "'''\",\n \"untagVlanFlag\": \"true\",\n \"untaggedVlans\": \"'''", "+", "untaggedvlans", "+", "'''\"\n }'''", "response", "=", "requests", ".", "post", "(", "f_url", ",", "auth", "=", "auth", ",", "data", "=", "payload", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "201", ":", "return", "201", "if", "response", ".", "status_code", "==", "409", ":", "return", "409", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_device_hybrid_interfaces: An Error has occured\"" ]
Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid port to a HPE Comware based switch. These functions only apply to HPE Comware based devices. :param ifindex: str ifIndex value of target interface :param pvid: str 802.1q value (1-4094) of target VLAN :param taggedvlans: str 802.1q value, seperated by commas, of target tagged VLANs :param untaggedvlans: str 802.1q value, seperated by commas, of target untagged VLANs :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return int of http response code :rtype int
[ "Function", "takes", "ifindex", "pvid", "tagged", "vlans", "untagged", "vlans", "as", "input", "values", "to", "add", "a", "hybrid", "port", "to", "a", "HPE", "Comware", "based", "switch", ".", "These", "functions", "only", "apply", "to", "HPE", "Comware", "based", "devices", ".", ":", "param", "ifindex", ":", "str", "ifIndex", "value", "of", "target", "interface", ":", "param", "pvid", ":", "str", "802", ".", "1q", "value", "(", "1", "-", "4094", ")", "of", "target", "VLAN", ":", "param", "taggedvlans", ":", "str", "802", ".", "1q", "value", "seperated", "by", "commas", "of", "target", "tagged", "VLANs", ":", "param", "untaggedvlans", ":", "str", "802", ".", "1q", "value", "seperated", "by", "commas", "of", "target", "untagged", "VLANs", ":", "param", "auth", ":", "requests", "auth", "object", "#usually", "auth", ".", "creds", "from", "auth", "pyhpeimc", ".", "auth", ".", "class", ":", "param", "url", ":", "base", "url", "of", "IMC", "RS", "interface", "#usually", "auth", ".", "url", "from", "pyhpeimc", ".", "auth", ".", "authclass", ":", "param", "devid", ":", "str", "requires", "devid", "of", "the", "target", "device", ":", "param", "devip", ":", "str", "of", "ipv4", "address", "of", "the", "target", "device", ":", "return", "int", "of", "http", "response", "code", ":", "rtype", "int" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L240-L274
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
delete_hybrid_interface
def delete_hybrid_interface(ifindex, auth, url, devip=None, devid=None): """ Function takes devip ( ipv4 address ), ifIndex and pvid (vlanid) of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param ifindex: str value of ifIndex for a specific interface on the device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: int of 204 if successful or 409 if not succesful :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_hybrid_interface('9', auth.creds, auth.url, devip='10.101.0.221') 409 >>> add_hybrid = add_hybrid_interface('9', '1', '10', '1', auth.creds, auth.url, devip='10.101.0.221') >>> delete_hybrid = delete_hybrid_interface('9', auth.creds, auth.url, devip='10.101.0.221') >>> assert type(delete_hybrid) is int >>> assert delete_hybrid == 204 """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] f_url = url + "/imcrs/vlan/hybrid?devId=" + devid + "&ifIndex=" + ifindex response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: return 204 if response.status_code == 409: return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_hybrid_interfaces: An Error has occured"
python
def delete_hybrid_interface(ifindex, auth, url, devip=None, devid=None): """ Function takes devip ( ipv4 address ), ifIndex and pvid (vlanid) of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param ifindex: str value of ifIndex for a specific interface on the device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: int of 204 if successful or 409 if not succesful :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_hybrid_interface('9', auth.creds, auth.url, devip='10.101.0.221') 409 >>> add_hybrid = add_hybrid_interface('9', '1', '10', '1', auth.creds, auth.url, devip='10.101.0.221') >>> delete_hybrid = delete_hybrid_interface('9', auth.creds, auth.url, devip='10.101.0.221') >>> assert type(delete_hybrid) is int >>> assert delete_hybrid == 204 """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] f_url = url + "/imcrs/vlan/hybrid?devId=" + devid + "&ifIndex=" + ifindex response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: return 204 if response.status_code == 409: return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_device_hybrid_interfaces: An Error has occured"
[ "def", "delete_hybrid_interface", "(", "ifindex", ",", "auth", ",", "url", ",", "devip", "=", "None", ",", "devid", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "f_url", "=", "url", "+", "\"/imcrs/vlan/hybrid?devId=\"", "+", "devid", "+", "\"&ifIndex=\"", "+", "ifindex", "response", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "204", ":", "return", "204", "if", "response", ".", "status_code", "==", "409", ":", "return", "409", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_device_hybrid_interfaces: An Error has occured\"" ]
Function takes devip ( ipv4 address ), ifIndex and pvid (vlanid) of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param ifindex: str value of ifIndex for a specific interface on the device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: int of 204 if successful or 409 if not succesful :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_hybrid_interface('9', auth.creds, auth.url, devip='10.101.0.221') 409 >>> add_hybrid = add_hybrid_interface('9', '1', '10', '1', auth.creds, auth.url, devip='10.101.0.221') >>> delete_hybrid = delete_hybrid_interface('9', auth.creds, auth.url, devip='10.101.0.221') >>> assert type(delete_hybrid) is int >>> assert delete_hybrid == 204
[ "Function", "takes", "devip", "(", "ipv4", "address", ")", "ifIndex", "and", "pvid", "(", "vlanid", ")", "of", "specific", "device", "and", "802", ".", "1q", "VLAN", "tag", "and", "issues", "a", "RESTFUL", "call", "to", "remove", "the", "specified", "VLAN", "from", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L313-L360
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
set_access_interface_pvid
def set_access_interface_pvid(ifindex, pvid, auth, url, devip=None, devid=None): """ Function takes devip ( ipv4 address ), ifIndex and pvid (vlanid) of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param ifindex: str value of ifIndex for a specific interface on the device :param pvid: str value of dot1q VLAN desired to apply to the device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: int of 204 if successful or 409 if not succesful :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> set_access_int_vlan = set_access_interface_pvid('9', '1', auth.creds, auth.url, devip='10.101.0.221') >>> set_access_int_vlan = set_access_interface_pvid('9', '10', auth.creds, auth.url, devip='10.101.0.221') >>> assert type(set_access_int_vlan) is int >>> assert set_access_int_vlan == 204 >>> set_access_int_vlan = set_access_interface_pvid('9', '1', auth.creds, auth.url, devip='10.101.0.221') """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_access_interface_pvid_url = "/imcrs/vlan/access?devId=" + devid + "&destVlanId=" + pvid \ + "&ifIndex=" + str(ifindex) f_url = url + set_access_interface_pvid_url response = requests.put(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: return 204 if response.status_code == 409: return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_access_interface_pvid: An Error has occured"
python
def set_access_interface_pvid(ifindex, pvid, auth, url, devip=None, devid=None): """ Function takes devip ( ipv4 address ), ifIndex and pvid (vlanid) of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param ifindex: str value of ifIndex for a specific interface on the device :param pvid: str value of dot1q VLAN desired to apply to the device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: int of 204 if successful or 409 if not succesful :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> set_access_int_vlan = set_access_interface_pvid('9', '1', auth.creds, auth.url, devip='10.101.0.221') >>> set_access_int_vlan = set_access_interface_pvid('9', '10', auth.creds, auth.url, devip='10.101.0.221') >>> assert type(set_access_int_vlan) is int >>> assert set_access_int_vlan == 204 >>> set_access_int_vlan = set_access_interface_pvid('9', '1', auth.creds, auth.url, devip='10.101.0.221') """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_access_interface_pvid_url = "/imcrs/vlan/access?devId=" + devid + "&destVlanId=" + pvid \ + "&ifIndex=" + str(ifindex) f_url = url + set_access_interface_pvid_url response = requests.put(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: return 204 if response.status_code == 409: return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_access_interface_pvid: An Error has occured"
[ "def", "set_access_interface_pvid", "(", "ifindex", ",", "pvid", ",", "auth", ",", "url", ",", "devip", "=", "None", ",", "devid", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "set_access_interface_pvid_url", "=", "\"/imcrs/vlan/access?devId=\"", "+", "devid", "+", "\"&destVlanId=\"", "+", "pvid", "+", "\"&ifIndex=\"", "+", "str", "(", "ifindex", ")", "f_url", "=", "url", "+", "set_access_interface_pvid_url", "response", "=", "requests", ".", "put", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "204", ":", "return", "204", "if", "response", ".", "status_code", "==", "409", ":", "return", "409", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" set_access_interface_pvid: An Error has occured\"" ]
Function takes devip ( ipv4 address ), ifIndex and pvid (vlanid) of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param ifindex: str value of ifIndex for a specific interface on the device :param pvid: str value of dot1q VLAN desired to apply to the device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: int of 204 if successful or 409 if not succesful :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> set_access_int_vlan = set_access_interface_pvid('9', '1', auth.creds, auth.url, devip='10.101.0.221') >>> set_access_int_vlan = set_access_interface_pvid('9', '10', auth.creds, auth.url, devip='10.101.0.221') >>> assert type(set_access_int_vlan) is int >>> assert set_access_int_vlan == 204 >>> set_access_int_vlan = set_access_interface_pvid('9', '1', auth.creds, auth.url, devip='10.101.0.221')
[ "Function", "takes", "devip", "(", "ipv4", "address", ")", "ifIndex", "and", "pvid", "(", "vlanid", ")", "of", "specific", "device", "and", "802", ".", "1q", "VLAN", "tag", "and", "issues", "a", "RESTFUL", "call", "to", "remove", "the", "specified", "VLAN", "from", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L365-L418
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
create_dev_vlan
def create_dev_vlan(vlanid, vlan_name, auth, url, devid=None, devip=None): """ function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: str HTTP Response code. Should be 201 if successfully created :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> create_dev_vlan = create_dev_vlan('350', '200', 'test vlan', auth.creds, auth.url) """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] create_dev_vlan_url = "/imcrs/vlan?devId=" + str(devid) f_url = url + create_dev_vlan_url payload = '''{"vlanId":"%s", "vlanName":"%s"}''' % (str(vlanid), vlan_name) response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 201: print('Vlan Created') return 201 elif response.status_code == 409: print('''Unable to create VLAN.\nVLAN Already Exists\nDevice does not support VLAN function''') return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " create_dev_vlan: An Error has occured"
python
def create_dev_vlan(vlanid, vlan_name, auth, url, devid=None, devip=None): """ function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: str HTTP Response code. Should be 201 if successfully created :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> create_dev_vlan = create_dev_vlan('350', '200', 'test vlan', auth.creds, auth.url) """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] create_dev_vlan_url = "/imcrs/vlan?devId=" + str(devid) f_url = url + create_dev_vlan_url payload = '''{"vlanId":"%s", "vlanName":"%s"}''' % (str(vlanid), vlan_name) response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 201: print('Vlan Created') return 201 elif response.status_code == 409: print('''Unable to create VLAN.\nVLAN Already Exists\nDevice does not support VLAN function''') return 409 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " create_dev_vlan: An Error has occured"
[ "def", "create_dev_vlan", "(", "vlanid", ",", "vlan_name", ",", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "create_dev_vlan_url", "=", "\"/imcrs/vlan?devId=\"", "+", "str", "(", "devid", ")", "f_url", "=", "url", "+", "create_dev_vlan_url", "payload", "=", "'''{\"vlanId\":\"%s\", \"vlanName\":\"%s\"}'''", "%", "(", "str", "(", "vlanid", ")", ",", "vlan_name", ")", "response", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "201", ":", "print", "(", "'Vlan Created'", ")", "return", "201", "elif", "response", ".", "status_code", "==", "409", ":", "print", "(", "'''Unable to create VLAN.\\nVLAN Already Exists\\nDevice does not support VLAN\n function'''", ")", "return", "409", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" create_dev_vlan: An Error has occured\"" ]
function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :return: str HTTP Response code. Should be 201 if successfully created :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> create_dev_vlan = create_dev_vlan('350', '200', 'test vlan', auth.creds, auth.url)
[ "function", "takes", "devid", "and", "vlanid", "vlan_name", "of", "specific", "device", "and", "802", ".", "1q", "VLAN", "tag", "and", "issues", "a", "RESTFUL", "call", "to", "add", "the", "specified", "VLAN", "from", "the", "target", "device", ".", "VLAN", "Name", "MUST", "be", "valid", "on", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L455-L502
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/vlanm.py
delete_dev_vlans
def delete_dev_vlans(vlanid, auth, url, devid=None, devip=None): """ function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param vlanid:int or str value of target 802.1q VLAN :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP response object from requests library. Status code should be 204 if Successful :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :rtype: requests.models.Response >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> create_dev_vlan = create_dev_vlan('350', '200', 'test vlan', auth.creds, auth.url) """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] remove_dev_vlan_url = "/imcrs/vlan/delvlan?devId=" + str(devid) + "&vlanId=" + str(vlanid) f_url = url + remove_dev_vlan_url response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('Vlan deleted') return response.status_code elif response.status_code == 409: print('Unable to delete VLAN.\nVLAN does not Exist\nDevice does not support VLAN ' 'function') return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_dev_vlans: An Error has occured"
python
def delete_dev_vlans(vlanid, auth, url, devid=None, devip=None): """ function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param vlanid:int or str value of target 802.1q VLAN :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP response object from requests library. Status code should be 204 if Successful :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :rtype: requests.models.Response >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> create_dev_vlan = create_dev_vlan('350', '200', 'test vlan', auth.creds, auth.url) """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] remove_dev_vlan_url = "/imcrs/vlan/delvlan?devId=" + str(devid) + "&vlanId=" + str(vlanid) f_url = url + remove_dev_vlan_url response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('Vlan deleted') return response.status_code elif response.status_code == 409: print('Unable to delete VLAN.\nVLAN does not Exist\nDevice does not support VLAN ' 'function') return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_dev_vlans: An Error has occured"
[ "def", "delete_dev_vlans", "(", "vlanid", ",", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "remove_dev_vlan_url", "=", "\"/imcrs/vlan/delvlan?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&vlanId=\"", "+", "str", "(", "vlanid", ")", "f_url", "=", "url", "+", "remove_dev_vlan_url", "response", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "204", ":", "print", "(", "'Vlan deleted'", ")", "return", "response", ".", "status_code", "elif", "response", ".", "status_code", "==", "409", ":", "print", "(", "'Unable to delete VLAN.\\nVLAN does not Exist\\nDevice does not support VLAN '", "'function'", ")", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" delete_dev_vlans: An Error has occured\"" ]
function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param vlanid:int or str value of target 802.1q VLAN :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP response object from requests library. Status code should be 204 if Successful :param devid: str requires devid of the target device :param devip: str of ipv4 address of the target device :rtype: requests.models.Response >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vlanm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> create_dev_vlan = create_dev_vlan('350', '200', 'test vlan', auth.creds, auth.url)
[ "function", "takes", "devid", "and", "vlanid", "of", "specific", "device", "and", "802", ".", "1q", "VLAN", "tag", "and", "issues", "a", "RESTFUL", "call", "to", "remove", "the", "specified", "VLAN", "from", "the", "target", "device", ".", ":", "param", "vlanid", ":", "int", "or", "str", "value", "of", "target", "802", ".", "1q", "VLAN" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/vlanm.py#L505-L545
train
housecanary/hc-api-python
housecanary/hc_api_export/hc_api_export.py
_get_results_from_api
def _get_results_from_api(identifiers, endpoints, api_key, api_secret): """Use the HouseCanary API Python Client to access the API""" if api_key is not None and api_secret is not None: client = housecanary.ApiClient(api_key, api_secret) else: client = housecanary.ApiClient() wrapper = getattr(client, endpoints[0].split('/')[0]) if len(endpoints) > 1: # use component_mget to request multiple endpoints in one call return wrapper.component_mget(identifiers, endpoints) else: return wrapper.fetch_identifier_component(endpoints[0], identifiers)
python
def _get_results_from_api(identifiers, endpoints, api_key, api_secret): """Use the HouseCanary API Python Client to access the API""" if api_key is not None and api_secret is not None: client = housecanary.ApiClient(api_key, api_secret) else: client = housecanary.ApiClient() wrapper = getattr(client, endpoints[0].split('/')[0]) if len(endpoints) > 1: # use component_mget to request multiple endpoints in one call return wrapper.component_mget(identifiers, endpoints) else: return wrapper.fetch_identifier_component(endpoints[0], identifiers)
[ "def", "_get_results_from_api", "(", "identifiers", ",", "endpoints", ",", "api_key", ",", "api_secret", ")", ":", "if", "api_key", "is", "not", "None", "and", "api_secret", "is", "not", "None", ":", "client", "=", "housecanary", ".", "ApiClient", "(", "api_key", ",", "api_secret", ")", "else", ":", "client", "=", "housecanary", ".", "ApiClient", "(", ")", "wrapper", "=", "getattr", "(", "client", ",", "endpoints", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", ")", "if", "len", "(", "endpoints", ")", ">", "1", ":", "# use component_mget to request multiple endpoints in one call", "return", "wrapper", ".", "component_mget", "(", "identifiers", ",", "endpoints", ")", "else", ":", "return", "wrapper", ".", "fetch_identifier_component", "(", "endpoints", "[", "0", "]", ",", "identifiers", ")" ]
Use the HouseCanary API Python Client to access the API
[ "Use", "the", "HouseCanary", "API", "Python", "Client", "to", "access", "the", "API" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/hc_api_export/hc_api_export.py#L154-L168
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/admin/images.py
images
def images(): ''' Show the list of registered images in this cluster. ''' fields = [ ('Name', 'name'), ('Registry', 'registry'), ('Tag', 'tag'), ('Digest', 'digest'), ('Size', 'size_bytes'), ('Aliases', 'aliases'), ] with Session() as session: try: items = session.Image.list(fields=(item[1] for item in fields)) except Exception as e: print_error(e) sys.exit(1) if len(items) == 0: print('There are no registered images.') return print(tabulate((item.values() for item in items), headers=(item[0] for item in fields), floatfmt=',.0f'))
python
def images(): ''' Show the list of registered images in this cluster. ''' fields = [ ('Name', 'name'), ('Registry', 'registry'), ('Tag', 'tag'), ('Digest', 'digest'), ('Size', 'size_bytes'), ('Aliases', 'aliases'), ] with Session() as session: try: items = session.Image.list(fields=(item[1] for item in fields)) except Exception as e: print_error(e) sys.exit(1) if len(items) == 0: print('There are no registered images.') return print(tabulate((item.values() for item in items), headers=(item[0] for item in fields), floatfmt=',.0f'))
[ "def", "images", "(", ")", ":", "fields", "=", "[", "(", "'Name'", ",", "'name'", ")", ",", "(", "'Registry'", ",", "'registry'", ")", ",", "(", "'Tag'", ",", "'tag'", ")", ",", "(", "'Digest'", ",", "'digest'", ")", ",", "(", "'Size'", ",", "'size_bytes'", ")", ",", "(", "'Aliases'", ",", "'aliases'", ")", ",", "]", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "items", "=", "session", ".", "Image", ".", "list", "(", "fields", "=", "(", "item", "[", "1", "]", "for", "item", "in", "fields", ")", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "if", "len", "(", "items", ")", "==", "0", ":", "print", "(", "'There are no registered images.'", ")", "return", "print", "(", "tabulate", "(", "(", "item", ".", "values", "(", ")", "for", "item", "in", "items", ")", ",", "headers", "=", "(", "item", "[", "0", "]", "for", "item", "in", "fields", ")", ",", "floatfmt", "=", "',.0f'", ")", ")" ]
Show the list of registered images in this cluster.
[ "Show", "the", "list", "of", "registered", "images", "in", "this", "cluster", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/admin/images.py#L11-L34
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/admin/images.py
rescan_images
def rescan_images(registry): '''Update the kernel image metadata from all configured docker registries.''' with Session() as session: try: result = session.Image.rescanImages(registry) except Exception as e: print_error(e) sys.exit(1) if result['ok']: print("kernel image metadata updated") else: print("rescanning failed: {0}".format(result['msg']))
python
def rescan_images(registry): '''Update the kernel image metadata from all configured docker registries.''' with Session() as session: try: result = session.Image.rescanImages(registry) except Exception as e: print_error(e) sys.exit(1) if result['ok']: print("kernel image metadata updated") else: print("rescanning failed: {0}".format(result['msg']))
[ "def", "rescan_images", "(", "registry", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "Image", ".", "rescanImages", "(", "registry", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "if", "result", "[", "'ok'", "]", ":", "print", "(", "\"kernel image metadata updated\"", ")", "else", ":", "print", "(", "\"rescanning failed: {0}\"", ".", "format", "(", "result", "[", "'msg'", "]", ")", ")" ]
Update the kernel image metadata from all configured docker registries.
[ "Update", "the", "kernel", "image", "metadata", "from", "all", "configured", "docker", "registries", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/admin/images.py#L40-L51
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/admin/images.py
alias_image
def alias_image(alias, target): '''Add an image alias.''' with Session() as session: try: result = session.Image.aliasImage(alias, target) except Exception as e: print_error(e) sys.exit(1) if result['ok']: print("alias {0} created for target {1}".format(alias, target)) else: print(result['msg'])
python
def alias_image(alias, target): '''Add an image alias.''' with Session() as session: try: result = session.Image.aliasImage(alias, target) except Exception as e: print_error(e) sys.exit(1) if result['ok']: print("alias {0} created for target {1}".format(alias, target)) else: print(result['msg'])
[ "def", "alias_image", "(", "alias", ",", "target", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "Image", ".", "aliasImage", "(", "alias", ",", "target", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "if", "result", "[", "'ok'", "]", ":", "print", "(", "\"alias {0} created for target {1}\"", ".", "format", "(", "alias", ",", "target", ")", ")", "else", ":", "print", "(", "result", "[", "'msg'", "]", ")" ]
Add an image alias.
[ "Add", "an", "image", "alias", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/admin/images.py#L56-L67
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/admin/images.py
dealias_image
def dealias_image(alias): '''Remove an image alias.''' with Session() as session: try: result = session.Image.dealiasImage(alias) except Exception as e: print_error(e) sys.exit(1) if result['ok']: print("alias {0} removed.".format(alias)) else: print(result['msg'])
python
def dealias_image(alias): '''Remove an image alias.''' with Session() as session: try: result = session.Image.dealiasImage(alias) except Exception as e: print_error(e) sys.exit(1) if result['ok']: print("alias {0} removed.".format(alias)) else: print(result['msg'])
[ "def", "dealias_image", "(", "alias", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "Image", ".", "dealiasImage", "(", "alias", ")", "except", "Exception", "as", "e", ":", "print_error", "(", "e", ")", "sys", ".", "exit", "(", "1", ")", "if", "result", "[", "'ok'", "]", ":", "print", "(", "\"alias {0} removed.\"", ".", "format", "(", "alias", ")", ")", "else", ":", "print", "(", "result", "[", "'msg'", "]", ")" ]
Remove an image alias.
[ "Remove", "an", "image", "alias", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/admin/images.py#L72-L83
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/__init__.py
run_alias
def run_alias(): """ Quick aliases for run command. """ mode = Path(sys.argv[0]).stem help = True if len(sys.argv) <= 1 else False if mode == 'lcc': sys.argv.insert(1, 'c') elif mode == 'lpython': sys.argv.insert(1, 'python') sys.argv.insert(1, 'run') if help: sys.argv.append('--help') main.main(prog_name='backend.ai')
python
def run_alias(): """ Quick aliases for run command. """ mode = Path(sys.argv[0]).stem help = True if len(sys.argv) <= 1 else False if mode == 'lcc': sys.argv.insert(1, 'c') elif mode == 'lpython': sys.argv.insert(1, 'python') sys.argv.insert(1, 'run') if help: sys.argv.append('--help') main.main(prog_name='backend.ai')
[ "def", "run_alias", "(", ")", ":", "mode", "=", "Path", "(", "sys", ".", "argv", "[", "0", "]", ")", ".", "stem", "help", "=", "True", "if", "len", "(", "sys", ".", "argv", ")", "<=", "1", "else", "False", "if", "mode", "==", "'lcc'", ":", "sys", ".", "argv", ".", "insert", "(", "1", ",", "'c'", ")", "elif", "mode", "==", "'lpython'", ":", "sys", ".", "argv", ".", "insert", "(", "1", ",", "'python'", ")", "sys", ".", "argv", ".", "insert", "(", "1", ",", "'run'", ")", "if", "help", ":", "sys", ".", "argv", ".", "append", "(", "'--help'", ")", "main", ".", "main", "(", "prog_name", "=", "'backend.ai'", ")" ]
Quick aliases for run command.
[ "Quick", "aliases", "for", "run", "command", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/__init__.py#L99-L112
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_asset_details
def get_dev_asset_details(ipaddress): """Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API :param ipaddress: IP address of the device you wish to gather the asset details :return: object of type list containing the device asset details """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_asset_url = "/imcrs/netasset/asset?assetDevice.ip=" + str(ipaddress) f_url = url + get_dev_asset_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_asset_info = (json.loads(r.text)) if len(dev_asset_info) > 0: dev_asset_info = dev_asset_info['netAsset'] if type(dev_asset_info) == dict: dev_asset_info = [dev_asset_info] if type(dev_asset_info) == list: dev_asset_info[:] = [dev for dev in dev_asset_info if dev.get('deviceIp') == ipaddress] return dev_asset_info else: print("get_dev_asset_details: An Error has occured")
python
def get_dev_asset_details(ipaddress): """Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API :param ipaddress: IP address of the device you wish to gather the asset details :return: object of type list containing the device asset details """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_asset_url = "/imcrs/netasset/asset?assetDevice.ip=" + str(ipaddress) f_url = url + get_dev_asset_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_asset_info = (json.loads(r.text)) if len(dev_asset_info) > 0: dev_asset_info = dev_asset_info['netAsset'] if type(dev_asset_info) == dict: dev_asset_info = [dev_asset_info] if type(dev_asset_info) == list: dev_asset_info[:] = [dev for dev in dev_asset_info if dev.get('deviceIp') == ipaddress] return dev_asset_info else: print("get_dev_asset_details: An Error has occured")
[ "def", "get_dev_asset_details", "(", "ipaddress", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_asset_url", "=", "\"/imcrs/netasset/asset?assetDevice.ip=\"", "+", "str", "(", "ipaddress", ")", "f_url", "=", "url", "+", "get_dev_asset_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "dev_asset_info", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "len", "(", "dev_asset_info", ")", ">", "0", ":", "dev_asset_info", "=", "dev_asset_info", "[", "'netAsset'", "]", "if", "type", "(", "dev_asset_info", ")", "==", "dict", ":", "dev_asset_info", "=", "[", "dev_asset_info", "]", "if", "type", "(", "dev_asset_info", ")", "==", "list", ":", "dev_asset_info", "[", ":", "]", "=", "[", "dev", "for", "dev", "in", "dev_asset_info", "if", "dev", ".", "get", "(", "'deviceIp'", ")", "==", "ipaddress", "]", "return", "dev_asset_info", "else", ":", "print", "(", "\"get_dev_asset_details: An Error has occured\"", ")" ]
Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API :param ipaddress: IP address of the device you wish to gather the asset details :return: object of type list containing the device asset details
[ "Takes", "in", "ipaddress", "as", "input", "to", "fetch", "device", "assett", "details", "from", "HP", "IMC", "RESTFUL", "API", ":", "param", "ipaddress", ":", "IP", "address", "of", "the", "device", "you", "wish", "to", "gather", "the", "asset", "details", ":", "return", ":", "object", "of", "type", "list", "containing", "the", "device", "asset", "details" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L150-L175
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_serial_numbers
def get_serial_numbers(assetList): """ Helper function: Uses return of get_dev_asset_details function to evaluate to evaluate for multipe serial objects. :param assetList: output of get_dev_asset_details function :return: the serial_list object of list type which contains one or more dictionaries of the asset details """ serial_list = [] if type(assetList) == list: for i in assetList: if len(i['serialNum']) > 0: serial_list.append(i) return serial_list
python
def get_serial_numbers(assetList): """ Helper function: Uses return of get_dev_asset_details function to evaluate to evaluate for multipe serial objects. :param assetList: output of get_dev_asset_details function :return: the serial_list object of list type which contains one or more dictionaries of the asset details """ serial_list = [] if type(assetList) == list: for i in assetList: if len(i['serialNum']) > 0: serial_list.append(i) return serial_list
[ "def", "get_serial_numbers", "(", "assetList", ")", ":", "serial_list", "=", "[", "]", "if", "type", "(", "assetList", ")", "==", "list", ":", "for", "i", "in", "assetList", ":", "if", "len", "(", "i", "[", "'serialNum'", "]", ")", ">", "0", ":", "serial_list", ".", "append", "(", "i", ")", "return", "serial_list" ]
Helper function: Uses return of get_dev_asset_details function to evaluate to evaluate for multipe serial objects. :param assetList: output of get_dev_asset_details function :return: the serial_list object of list type which contains one or more dictionaries of the asset details
[ "Helper", "function", ":", "Uses", "return", "of", "get_dev_asset_details", "function", "to", "evaluate", "to", "evaluate", "for", "multipe", "serial", "objects", ".", ":", "param", "assetList", ":", "output", "of", "get_dev_asset_details", "function", ":", "return", ":", "the", "serial_list", "object", "of", "list", "type", "which", "contains", "one", "or", "more", "dictionaries", "of", "the", "asset", "details" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L178-L189
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_trunk_interfaces
def get_trunk_interfaces(devId): """Function takes devId as input to RESTFULL call to HP IMC platform :param devId: output of get_dev_details :return: list of dictionaries containing of interfaces configured as an 802.1q trunk """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_trunk_interfaces_url = "/imcrs/vlan/trunk?devId=" + str(devId) + "&start=1&size=5000&total=false" f_url = url + get_trunk_interfaces_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_trunk_interfaces = (json.loads(r.text)) if len(dev_trunk_interfaces) == 2: return dev_trunk_interfaces['trunkIf'] else: dev_trunk_interfaces['trunkIf'] = ["No trunk inteface"] return dev_trunk_interfaces['trunkIf']
python
def get_trunk_interfaces(devId): """Function takes devId as input to RESTFULL call to HP IMC platform :param devId: output of get_dev_details :return: list of dictionaries containing of interfaces configured as an 802.1q trunk """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_trunk_interfaces_url = "/imcrs/vlan/trunk?devId=" + str(devId) + "&start=1&size=5000&total=false" f_url = url + get_trunk_interfaces_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_trunk_interfaces = (json.loads(r.text)) if len(dev_trunk_interfaces) == 2: return dev_trunk_interfaces['trunkIf'] else: dev_trunk_interfaces['trunkIf'] = ["No trunk inteface"] return dev_trunk_interfaces['trunkIf']
[ "def", "get_trunk_interfaces", "(", "devId", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_trunk_interfaces_url", "=", "\"/imcrs/vlan/trunk?devId=\"", "+", "str", "(", "devId", ")", "+", "\"&start=1&size=5000&total=false\"", "f_url", "=", "url", "+", "get_trunk_interfaces_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "dev_trunk_interfaces", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "len", "(", "dev_trunk_interfaces", ")", "==", "2", ":", "return", "dev_trunk_interfaces", "[", "'trunkIf'", "]", "else", ":", "dev_trunk_interfaces", "[", "'trunkIf'", "]", "=", "[", "\"No trunk inteface\"", "]", "return", "dev_trunk_interfaces", "[", "'trunkIf'", "]" ]
Function takes devId as input to RESTFULL call to HP IMC platform :param devId: output of get_dev_details :return: list of dictionaries containing of interfaces configured as an 802.1q trunk
[ "Function", "takes", "devId", "as", "input", "to", "RESTFULL", "call", "to", "HP", "IMC", "platform", ":", "param", "devId", ":", "output", "of", "get_dev_details", ":", "return", ":", "list", "of", "dictionaries", "containing", "of", "interfaces", "configured", "as", "an", "802", ".", "1q", "trunk" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L192-L214
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_device_access_interfaces
def get_device_access_interfaces(devId): """Function takes devId as input to RESTFUL call to HP IMC platform :param devId: requires deviceID as the only input parameter :return: list of dictionaries containing interfaces configured as access ports """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devId) + "&start=1&size=500&total=false" f_url = url + get_access_interface_vlan_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_access_interfaces = (json.loads(r.text)) if len(dev_access_interfaces) == 2: return dev_access_interfaces['accessIf'] else: dev_access_interfaces['accessIf'] = ["No access inteface"] return dev_access_interfaces['accessIf'] else: print("get_device_access_interfaces: An Error has occured")
python
def get_device_access_interfaces(devId): """Function takes devId as input to RESTFUL call to HP IMC platform :param devId: requires deviceID as the only input parameter :return: list of dictionaries containing interfaces configured as access ports """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devId) + "&start=1&size=500&total=false" f_url = url + get_access_interface_vlan_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_access_interfaces = (json.loads(r.text)) if len(dev_access_interfaces) == 2: return dev_access_interfaces['accessIf'] else: dev_access_interfaces['accessIf'] = ["No access inteface"] return dev_access_interfaces['accessIf'] else: print("get_device_access_interfaces: An Error has occured")
[ "def", "get_device_access_interfaces", "(", "devId", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_access_interface_vlan_url", "=", "\"/imcrs/vlan/access?devId=\"", "+", "str", "(", "devId", ")", "+", "\"&start=1&size=500&total=false\"", "f_url", "=", "url", "+", "get_access_interface_vlan_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "dev_access_interfaces", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "len", "(", "dev_access_interfaces", ")", "==", "2", ":", "return", "dev_access_interfaces", "[", "'accessIf'", "]", "else", ":", "dev_access_interfaces", "[", "'accessIf'", "]", "=", "[", "\"No access inteface\"", "]", "return", "dev_access_interfaces", "[", "'accessIf'", "]", "else", ":", "print", "(", "\"get_device_access_interfaces: An Error has occured\"", ")" ]
Function takes devId as input to RESTFUL call to HP IMC platform :param devId: requires deviceID as the only input parameter :return: list of dictionaries containing interfaces configured as access ports
[ "Function", "takes", "devId", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC", "platform", ":", "param", "devId", ":", "requires", "deviceID", "as", "the", "only", "input", "parameter", ":", "return", ":", "list", "of", "dictionaries", "containing", "interfaces", "configured", "as", "access", "ports" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L217-L240
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_details
def get_dev_details(ip_address): """Takes string input of IP address to issue RESTUL call to HP IMC :param ip_address: string object of dotted decimal notation of IPv4 address :return: dictionary of device details >>> get_dev_details('10.101.0.1') {'symbolLevel': '2', 'typeName': 'Cisco 2811', 'location': 'changed this too', 'status': '1', 'sysName': 'Cisco2811.haw.int', 'id': '30', 'symbolType': '3', 'symbolId': '1032', 'sysDescription': '', 'symbolName': 'Cisco2811.haw.int', 'mask': '255.255.255.0', 'label': 'Cisco2811.haw.int', 'symbolDesc': '', 'sysOid': '1.3.6.1.4.1.9.1.576', 'contact': 'changed this too', 'statusDesc': 'Normal', 'parentId': '1', 'categoryId': '0', 'topoIconName': 'iconroute', 'mac': '00:1b:d4:47:1e:68', 'devCategoryImgSrc': 'router', 'link': {'@rel': 'self', '@href': 'http://10.101.0.202:8080/imcrs/plat/res/device/30', '@op': 'GET'}, 'ip': '10.101.0.1'} >>> get_dev_details('8.8.8.8') Device not found 'Device not found' """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_details_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \ str(ip_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false" f_url = url + get_dev_details_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_details = (json.loads(r.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif type(dev_details['device']) == list: for i in dev_details['device']: if i['ip'] == ip_address: dev_details = i return dev_details elif type(dev_details['device']) == dict: return dev_details['device'] else: print("dev_details: An Error has occured")
python
def get_dev_details(ip_address): """Takes string input of IP address to issue RESTUL call to HP IMC :param ip_address: string object of dotted decimal notation of IPv4 address :return: dictionary of device details >>> get_dev_details('10.101.0.1') {'symbolLevel': '2', 'typeName': 'Cisco 2811', 'location': 'changed this too', 'status': '1', 'sysName': 'Cisco2811.haw.int', 'id': '30', 'symbolType': '3', 'symbolId': '1032', 'sysDescription': '', 'symbolName': 'Cisco2811.haw.int', 'mask': '255.255.255.0', 'label': 'Cisco2811.haw.int', 'symbolDesc': '', 'sysOid': '1.3.6.1.4.1.9.1.576', 'contact': 'changed this too', 'statusDesc': 'Normal', 'parentId': '1', 'categoryId': '0', 'topoIconName': 'iconroute', 'mac': '00:1b:d4:47:1e:68', 'devCategoryImgSrc': 'router', 'link': {'@rel': 'self', '@href': 'http://10.101.0.202:8080/imcrs/plat/res/device/30', '@op': 'GET'}, 'ip': '10.101.0.1'} >>> get_dev_details('8.8.8.8') Device not found 'Device not found' """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_details_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \ str(ip_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false" f_url = url + get_dev_details_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_details = (json.loads(r.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif type(dev_details['device']) == list: for i in dev_details['device']: if i['ip'] == ip_address: dev_details = i return dev_details elif type(dev_details['device']) == dict: return dev_details['device'] else: print("dev_details: An Error has occured")
[ "def", "get_dev_details", "(", "ip_address", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_details_url", "=", "\"/imcrs/plat/res/device?resPrivilegeFilter=false&ip=\"", "+", "str", "(", "ip_address", ")", "+", "\"&start=0&size=1000&orderBy=id&desc=false&total=false\"", "f_url", "=", "url", "+", "get_dev_details_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "dev_details", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "len", "(", "dev_details", ")", "==", "0", ":", "print", "(", "\"Device not found\"", ")", "return", "\"Device not found\"", "elif", "type", "(", "dev_details", "[", "'device'", "]", ")", "==", "list", ":", "for", "i", "in", "dev_details", "[", "'device'", "]", ":", "if", "i", "[", "'ip'", "]", "==", "ip_address", ":", "dev_details", "=", "i", "return", "dev_details", "elif", "type", "(", "dev_details", "[", "'device'", "]", ")", "==", "dict", ":", "return", "dev_details", "[", "'device'", "]", "else", ":", "print", "(", "\"dev_details: An Error has occured\"", ")" ]
Takes string input of IP address to issue RESTUL call to HP IMC :param ip_address: string object of dotted decimal notation of IPv4 address :return: dictionary of device details >>> get_dev_details('10.101.0.1') {'symbolLevel': '2', 'typeName': 'Cisco 2811', 'location': 'changed this too', 'status': '1', 'sysName': 'Cisco2811.haw.int', 'id': '30', 'symbolType': '3', 'symbolId': '1032', 'sysDescription': '', 'symbolName': 'Cisco2811.haw.int', 'mask': '255.255.255.0', 'label': 'Cisco2811.haw.int', 'symbolDesc': '', 'sysOid': '1.3.6.1.4.1.9.1.576', 'contact': 'changed this too', 'statusDesc': 'Normal', 'parentId': '1', 'categoryId': '0', 'topoIconName': 'iconroute', 'mac': '00:1b:d4:47:1e:68', 'devCategoryImgSrc': 'router', 'link': {'@rel': 'self', '@href': 'http://10.101.0.202:8080/imcrs/plat/res/device/30', '@op': 'GET'}, 'ip': '10.101.0.1'} >>> get_dev_details('8.8.8.8') Device not found 'Device not found'
[ "Takes", "string", "input", "of", "IP", "address", "to", "issue", "RESTUL", "call", "to", "HP", "IMC", ":", "param", "ip_address", ":", "string", "object", "of", "dotted", "decimal", "notation", "of", "IPv4", "address", ":", "return", ":", "dictionary", "of", "device", "details" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L269-L305
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_vlans
def get_dev_vlans(devId): """Function takes input of devID to issue RESTUL call to HP IMC :param devId: requires devId as the only input parameter :return: list dictionaries of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_vlans_url = "/imcrs/vlan?devId=" + str(devId) + "&start=0&size=5000&total=false" f_url = url + get_dev_vlans_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_details = (json.loads(r.text))['vlan'] return dev_details elif r.status_code == 409: return [{'vlan': 'None'}] else: print("get_dev_vlans: An Error has occured")
python
def get_dev_vlans(devId): """Function takes input of devID to issue RESTUL call to HP IMC :param devId: requires devId as the only input parameter :return: list dictionaries of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_vlans_url = "/imcrs/vlan?devId=" + str(devId) + "&start=0&size=5000&total=false" f_url = url + get_dev_vlans_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: dev_details = (json.loads(r.text))['vlan'] return dev_details elif r.status_code == 409: return [{'vlan': 'None'}] else: print("get_dev_vlans: An Error has occured")
[ "def", "get_dev_vlans", "(", "devId", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_vlans_url", "=", "\"/imcrs/vlan?devId=\"", "+", "str", "(", "devId", ")", "+", "\"&start=0&size=5000&total=false\"", "f_url", "=", "url", "+", "get_dev_vlans_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "dev_details", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "[", "'vlan'", "]", "return", "dev_details", "elif", "r", ".", "status_code", "==", "409", ":", "return", "[", "{", "'vlan'", ":", "'None'", "}", "]", "else", ":", "print", "(", "\"get_dev_vlans: An Error has occured\"", ")" ]
Function takes input of devID to issue RESTUL call to HP IMC :param devId: requires devId as the only input parameter :return: list dictionaries of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module
[ "Function", "takes", "input", "of", "devID", "to", "issue", "RESTUL", "call", "to", "HP", "IMC", ":", "param", "devId", ":", "requires", "devId", "as", "the", "only", "input", "parameter", ":", "return", ":", "list", "dictionaries", "of", "existing", "vlans", "on", "the", "devices", ".", "Device", "must", "be", "supported", "in", "HP", "IMC", "platform", "VLAN", "manager", "module" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L308-L330
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_interface
def get_dev_interface(devid): """ Function takes devid as input to RESTFUL call to HP IMC platform :param devid: requires devid as the only input :return: list object which contains a dictionary per interface """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_interface_url = "/imcrs/plat/res/device/" + str(devid) + \ "/interface?start=0&size=1000&desc=false&total=false" f_url = url + get_dev_interface_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: int_list = (json.loads(r.text))['interface'] return int_list else: print("An Error has occured")
python
def get_dev_interface(devid): """ Function takes devid as input to RESTFUL call to HP IMC platform :param devid: requires devid as the only input :return: list object which contains a dictionary per interface """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_interface_url = "/imcrs/plat/res/device/" + str(devid) + \ "/interface?start=0&size=1000&desc=false&total=false" f_url = url + get_dev_interface_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: int_list = (json.loads(r.text))['interface'] return int_list else: print("An Error has occured")
[ "def", "get_dev_interface", "(", "devid", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_interface_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devid", ")", "+", "\"/interface?start=0&size=1000&desc=false&total=false\"", "f_url", "=", "url", "+", "get_dev_interface_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "int_list", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "[", "'interface'", "]", "return", "int_list", "else", ":", "print", "(", "\"An Error has occured\"", ")" ]
Function takes devid as input to RESTFUL call to HP IMC platform :param devid: requires devid as the only input :return: list object which contains a dictionary per interface
[ "Function", "takes", "devid", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC", "platform", ":", "param", "devid", ":", "requires", "devid", "as", "the", "only", "input", ":", "return", ":", "list", "object", "which", "contains", "a", "dictionary", "per", "interface" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L333-L354
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_run_config
def get_dev_run_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentRun" f_url = url + get_dev_run_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # print (r.status_code) if r.status_code == 200: run_conf = (json.loads(r.text))['content'] type(run_conf) if run_conf is None: return "This features is no supported on this device" else: return run_conf else: return "This features is not supported on this device"
python
def get_dev_run_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentRun" f_url = url + get_dev_run_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # print (r.status_code) if r.status_code == 200: run_conf = (json.loads(r.text))['content'] type(run_conf) if run_conf is None: return "This features is no supported on this device" else: return run_conf else: return "This features is not supported on this device"
[ "def", "get_dev_run_config", "(", "devId", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_run_url", "=", "\"/imcrs/icc/deviceCfg/\"", "+", "str", "(", "devId", ")", "+", "\"/currentRun\"", "f_url", "=", "url", "+", "get_dev_run_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# print (r.status_code)", "if", "r", ".", "status_code", "==", "200", ":", "run_conf", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "[", "'content'", "]", "type", "(", "run_conf", ")", "if", "run_conf", "is", "None", ":", "return", "\"This features is no supported on this device\"", "else", ":", "return", "run_conf", "else", ":", "return", "\"This features is not supported on this device\"" ]
function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device"
[ "function", "takes", "the", "devId", "of", "a", "specific", "device", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "most", "current", "running", "config", "file", "as", "known", "by", "the", "HP", "IMC", "Base", "Platform", "ICC", "module", "for", "the", "target", "device", ".", ":", "param", "devId", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "return", ":", "str", "which", "contains", "the", "entire", "content", "of", "the", "target", "device", "running", "configuration", ".", "If", "the", "device", "is", "not", "currently", "supported", "in", "the", "HP", "IMC", "Base", "Platform", "ICC", "module", "this", "call", "returns", "a", "string", "of", "This", "feature", "is", "not", "supported", "on", "this", "device" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L357-L384
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_start_config
def get_dev_start_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentStart" f_url = url + get_dev_run_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) if r.status_code == 200: start_conf = (json.loads(r.text))['content'] return start_conf else: # print (r.status_code) return "This feature is not supported on this device"
python
def get_dev_start_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentStart" f_url = url + get_dev_run_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) if r.status_code == 200: start_conf = (json.loads(r.text))['content'] return start_conf else: # print (r.status_code) return "This feature is not supported on this device"
[ "def", "get_dev_start_config", "(", "devId", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_run_url", "=", "\"/imcrs/icc/deviceCfg/\"", "+", "str", "(", "devId", ")", "+", "\"/currentStart\"", "f_url", "=", "url", "+", "get_dev_run_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "if", "r", ".", "status_code", "==", "200", ":", "start_conf", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "[", "'content'", "]", "return", "start_conf", "else", ":", "# print (r.status_code)", "return", "\"This feature is not supported on this device\"" ]
function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device"
[ "function", "takes", "the", "devId", "of", "a", "specific", "device", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "most", "current", "startup", "config", "file", "as", "known", "by", "the", "HP", "IMC", "Base", "Platform", "ICC", "module", "for", "the", "target", "device", ".", ":", "param", "devId", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "return", ":", "str", "which", "contains", "the", "entire", "content", "of", "the", "target", "device", "startup", "configuration", ".", "If", "the", "device", "is", "not", "currently", "supported", "in", "the", "HP", "IMC", "Base", "Platform", "ICC", "module", "this", "call", "returns", "a", "string", "of", "This", "feature", "is", "not", "supported", "on", "this", "device" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L387-L410
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_dev_alarms
def get_dev_alarms(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_alarm_url = "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devId) + "&desc=false" f_url = url + get_dev_alarm_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) if r.status_code == 200: dev_alarm = (json.loads(r.text)) if 'alarm' in dev_alarm: return dev_alarm['alarm'] else: return "Device has no alarms"
python
def get_dev_alarms(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_alarm_url = "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devId) + "&desc=false" f_url = url + get_dev_alarm_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) if r.status_code == 200: dev_alarm = (json.loads(r.text)) if 'alarm' in dev_alarm: return dev_alarm['alarm'] else: return "Device has no alarms"
[ "def", "get_dev_alarms", "(", "devId", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_dev_alarm_url", "=", "\"/imcrs/fault/alarm?operatorName=admin&deviceId=\"", "+", "str", "(", "devId", ")", "+", "\"&desc=false\"", "f_url", "=", "url", "+", "get_dev_alarm_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "if", "r", ".", "status_code", "==", "200", ":", "dev_alarm", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "'alarm'", "in", "dev_alarm", ":", "return", "dev_alarm", "[", "'alarm'", "]", "else", ":", "return", "\"Device has no alarms\"" ]
function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device
[ "function", "takes", "the", "devId", "of", "a", "specific", "device", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "current", "alarms", "for", "the", "target", "device", ".", ":", "param", "devId", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "return", ":", "list", "of", "dictionaries", "containing", "the", "alarms", "for", "this", "device" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L413-L435
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_real_time_locate
def get_real_time_locate(ipAddress): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() real_time_locate_url = "/imcrs/res/access/realtimeLocate?type=2&value=" + str(ipAddress) + "&total=false" f_url = url + real_time_locate_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: return json.loads(r.text)['realtimeLocation'] else: print(r.status_code) print("An Error has occured")
python
def get_real_time_locate(ipAddress): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() real_time_locate_url = "/imcrs/res/access/realtimeLocate?type=2&value=" + str(ipAddress) + "&total=false" f_url = url + real_time_locate_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: return json.loads(r.text)['realtimeLocation'] else: print(r.status_code) print("An Error has occured")
[ "def", "get_real_time_locate", "(", "ipAddress", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "real_time_locate_url", "=", "\"/imcrs/res/access/realtimeLocate?type=2&value=\"", "+", "str", "(", "ipAddress", ")", "+", "\"&total=false\"", "f_url", "=", "url", "+", "real_time_locate_url", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "if", "r", ".", "status_code", "==", "200", ":", "return", "json", ".", "loads", "(", "r", ".", "text", ")", "[", "'realtimeLocation'", "]", "else", ":", "print", "(", "r", ".", "status_code", ")", "print", "(", "\"An Error has occured\"", ")" ]
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex
[ "function", "takes", "the", "ipAddress", "of", "a", "specific", "host", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "device", "and", "interface", "that", "the", "target", "host", "is", "currently", "connected", "to", ".", ":", "param", "ipAddress", ":", "str", "value", "valid", "IPv4", "IP", "address", ":", "return", ":", "dictionary", "containing", "hostIp", "devId", "deviceIP", "ifDesc", "ifIndex" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L441-L458
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_ip_mac_arp_list
def get_ip_mac_arp_list(devId): """ function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :return: list of dictionaries containing the IP/MAC/ARP list of the target device. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() ip_mac_arp_list_url = "/imcrs/res/access/ipMacArp/" + str(devId) f_url = url + ip_mac_arp_list_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: macarplist = (json.loads(r.text)) if len(macarplist) > 1: return macarplist['ipMacArp'] else: return ['this function is unsupported'] else: print(r.status_code) print("An Error has occured")
python
def get_ip_mac_arp_list(devId): """ function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :return: list of dictionaries containing the IP/MAC/ARP list of the target device. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() ip_mac_arp_list_url = "/imcrs/res/access/ipMacArp/" + str(devId) f_url = url + ip_mac_arp_list_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: macarplist = (json.loads(r.text)) if len(macarplist) > 1: return macarplist['ipMacArp'] else: return ['this function is unsupported'] else: print(r.status_code) print("An Error has occured")
[ "def", "get_ip_mac_arp_list", "(", "devId", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "ip_mac_arp_list_url", "=", "\"/imcrs/res/access/ipMacArp/\"", "+", "str", "(", "devId", ")", "f_url", "=", "url", "+", "ip_mac_arp_list_url", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "if", "r", ".", "status_code", "==", "200", ":", "macarplist", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "if", "len", "(", "macarplist", ")", ">", "1", ":", "return", "macarplist", "[", "'ipMacArp'", "]", "else", ":", "return", "[", "'this function is unsupported'", "]", "else", ":", "print", "(", "r", ".", "status_code", ")", "print", "(", "\"An Error has occured\"", ")" ]
function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :return: list of dictionaries containing the IP/MAC/ARP list of the target device.
[ "function", "takes", "devid", "of", "specific", "device", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "IP", "/", "MAC", "/", "ARP", "list", "from", "the", "target", "device", ".", ":", "param", "devId", ":", "int", "or", "str", "value", "of", "the", "target", "device", ".", ":", "return", ":", "list", "of", "dictionaries", "containing", "the", "IP", "/", "MAC", "/", "ARP", "list", "of", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L461-L481
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_custom_views
def get_custom_views(name=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() if name is None: get_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=false' elif name is not None: get_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name='+ name + '&desc=false&total=false' f_url = url + get_custom_views_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: customviewlist = (json.loads(r.text))['customView'] if type(customviewlist) is dict: customviewlist = [customviewlist] return customviewlist else: return customviewlist else: print(r.status_code) print("An Error has occured")
python
def get_custom_views(name=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() if name is None: get_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=false' elif name is not None: get_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name='+ name + '&desc=false&total=false' f_url = url + get_custom_views_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: customviewlist = (json.loads(r.text))['customView'] if type(customviewlist) is dict: customviewlist = [customviewlist] return customviewlist else: return customviewlist else: print(r.status_code) print("An Error has occured")
[ "def", "get_custom_views", "(", "name", "=", "None", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "if", "name", "is", "None", ":", "get_custom_views_url", "=", "'/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=false'", "elif", "name", "is", "not", "None", ":", "get_custom_views_url", "=", "'/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name='", "+", "name", "+", "'&desc=false&total=false'", "f_url", "=", "url", "+", "get_custom_views_url", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "if", "r", ".", "status_code", "==", "200", ":", "customviewlist", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "[", "'customView'", "]", "if", "type", "(", "customviewlist", ")", "is", "dict", ":", "customviewlist", "=", "[", "customviewlist", "]", "return", "customviewlist", "else", ":", "return", "customviewlist", "else", ":", "print", "(", "r", ".", "status_code", ")", "print", "(", "\"An Error has occured\"", ")" ]
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views.
[ "function", "takes", "no", "input", "and", "issues", "a", "RESTFUL", "call", "to", "get", "a", "list", "of", "custom", "views", "from", "HPE", "IMC", ".", "Optioanl", "Name", "input", "will", "return", "only", "the", "specified", "view", ".", ":", "param", "name", ":", "string", "containg", "the", "name", "of", "the", "desired", "custom", "view", ":", "return", ":", "list", "of", "dictionaries", "containing", "attributes", "of", "the", "custom", "views", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L488-L512
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
create_custom_views
def create_custom_views(name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=falsee' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(upperview)[0]['symbolId'] payload = '''{ "name": "'''+name+ '''"upperview" : "'''+str(parentviewid)+'''"}''' print (payload) r = requests.post(f_url, data = payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 201: return 'View ' + name +' created successfully' else: print(r.status_code) print("An Error has occured")
python
def create_custom_views(name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=falsee' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(upperview)[0]['symbolId'] payload = '''{ "name": "'''+name+ '''"upperview" : "'''+str(parentviewid)+'''"}''' print (payload) r = requests.post(f_url, data = payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 201: return 'View ' + name +' created successfully' else: print(r.status_code) print("An Error has occured")
[ "def", "create_custom_views", "(", "name", "=", "None", ",", "upperview", "=", "None", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "create_custom_views_url", "=", "'/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=falsee'", "f_url", "=", "url", "+", "create_custom_views_url", "if", "upperview", "is", "None", ":", "payload", "=", "'''{ \"name\": \"'''", "+", "name", "+", "'''\",\n \"upLevelSymbolId\" : \"\"}'''", "else", ":", "parentviewid", "=", "get_custom_views", "(", "upperview", ")", "[", "0", "]", "[", "'symbolId'", "]", "payload", "=", "'''{\n \"name\": \"'''", "+", "name", "+", "'''\"upperview\" : \"'''", "+", "str", "(", "parentviewid", ")", "+", "'''\"}'''", "print", "(", "payload", ")", "r", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "if", "r", ".", "status_code", "==", "201", ":", "return", "'View '", "+", "name", "+", "' created successfully'", "else", ":", "print", "(", "r", ".", "status_code", ")", "print", "(", "\"An Error has occured\"", ")" ]
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views.
[ "function", "takes", "no", "input", "and", "issues", "a", "RESTFUL", "call", "to", "get", "a", "list", "of", "custom", "views", "from", "HPE", "IMC", ".", "Optioanl", "Name", "input", "will", "return", "only", "the", "specified", "view", ".", ":", "param", "name", ":", "string", "containg", "the", "name", "of", "the", "desired", "custom", "view", ":", "return", ":", "list", "of", "dictionaries", "containing", "attributes", "of", "the", "custom", "views", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L514-L538
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
create_dev_vlan
def create_dev_vlan(devid, vlanid, vlan_name): """ function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_dev_vlan_url = "/imcrs/vlan?devId=" + str(devid) f_url = url + create_dev_vlan_url payload = '''{ "vlanId": "''' + str(vlanid) + '''", "vlanName" : "''' + str(vlan_name) + '''"}''' r = requests.post(f_url, data=payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print (r.status_code) if r.status_code == 201: print ('Vlan Created') return r.status_code elif r.status_code == 409: return '''Unable to create VLAN.\nVLAN Already Exists\nDevice does not support VLAN function''' else: print("An Error has occured")
python
def create_dev_vlan(devid, vlanid, vlan_name): """ function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_dev_vlan_url = "/imcrs/vlan?devId=" + str(devid) f_url = url + create_dev_vlan_url payload = '''{ "vlanId": "''' + str(vlanid) + '''", "vlanName" : "''' + str(vlan_name) + '''"}''' r = requests.post(f_url, data=payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print (r.status_code) if r.status_code == 201: print ('Vlan Created') return r.status_code elif r.status_code == 409: return '''Unable to create VLAN.\nVLAN Already Exists\nDevice does not support VLAN function''' else: print("An Error has occured")
[ "def", "create_dev_vlan", "(", "devid", ",", "vlanid", ",", "vlan_name", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "create_dev_vlan_url", "=", "\"/imcrs/vlan?devId=\"", "+", "str", "(", "devid", ")", "f_url", "=", "url", "+", "create_dev_vlan_url", "payload", "=", "'''{ \"vlanId\": \"'''", "+", "str", "(", "vlanid", ")", "+", "'''\", \"vlanName\" : \"'''", "+", "str", "(", "vlan_name", ")", "+", "'''\"}'''", "r", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "print", "(", "r", ".", "status_code", ")", "if", "r", ".", "status_code", "==", "201", ":", "print", "(", "'Vlan Created'", ")", "return", "r", ".", "status_code", "elif", "r", ".", "status_code", "==", "409", ":", "return", "'''Unable to create VLAN.\\nVLAN Already Exists\\nDevice does not support VLAN function'''", "else", ":", "print", "(", "\"An Error has occured\"", ")" ]
function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values.
[ "function", "takes", "devid", "and", "vlanid", "vlan_name", "of", "specific", "device", "and", "802", ".", "1q", "VLAN", "tag", "and", "issues", "a", "RESTFUL", "call", "to", "add", "the", "specified", "VLAN", "from", "the", "target", "device", ".", "VLAN", "Name", "MUST", "be", "valid", "on", "target", "device", ".", ":", "param", "devid", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "param", "vlanid", ":", "int", "or", "str", "value", "of", "target", "802", ".", "1q", "VLAN", ":", "param", "vlan_name", ":", "str", "value", "of", "the", "target", "802", ".", "1q", "VLAN", "name", ".", "MUST", "be", "valid", "name", "on", "target", "device", ".", ":", "return", ":", "HTTP", "Status", "code", "of", "201", "with", "no", "values", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L543-L566
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
delete_dev_vlans
def delete_dev_vlans(devid, vlanid): """ function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() remove_dev_vlan_url = "/imcrs/vlan/delvlan?devId=" + str(devid) + "&vlanId=" + str(vlanid) f_url = url + remove_dev_vlan_url payload = None r = requests.delete(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print (r.status_code) if r.status_code == 204: print ('Vlan deleted') return r.status_code elif r.status_code == 409: print ('Unable to delete VLAN.\nVLAN does not Exist\nDevice does not support VLAN function') return r.status_code else: print("An Error has occured")
python
def delete_dev_vlans(devid, vlanid): """ function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() remove_dev_vlan_url = "/imcrs/vlan/delvlan?devId=" + str(devid) + "&vlanId=" + str(vlanid) f_url = url + remove_dev_vlan_url payload = None r = requests.delete(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print (r.status_code) if r.status_code == 204: print ('Vlan deleted') return r.status_code elif r.status_code == 409: print ('Unable to delete VLAN.\nVLAN does not Exist\nDevice does not support VLAN function') return r.status_code else: print("An Error has occured")
[ "def", "delete_dev_vlans", "(", "devid", ",", "vlanid", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "remove_dev_vlan_url", "=", "\"/imcrs/vlan/delvlan?devId=\"", "+", "str", "(", "devid", ")", "+", "\"&vlanId=\"", "+", "str", "(", "vlanid", ")", "f_url", "=", "url", "+", "remove_dev_vlan_url", "payload", "=", "None", "r", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "print", "(", "r", ".", "status_code", ")", "if", "r", ".", "status_code", "==", "204", ":", "print", "(", "'Vlan deleted'", ")", "return", "r", ".", "status_code", "elif", "r", ".", "status_code", "==", "409", ":", "print", "(", "'Unable to delete VLAN.\\nVLAN does not Exist\\nDevice does not support VLAN function'", ")", "return", "r", ".", "status_code", "else", ":", "print", "(", "\"An Error has occured\"", ")" ]
function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values.
[ "function", "takes", "devid", "and", "vlanid", "of", "specific", "device", "and", "802", ".", "1q", "VLAN", "tag", "and", "issues", "a", "RESTFUL", "call", "to", "remove", "the", "specified", "VLAN", "from", "the", "target", "device", ".", ":", "param", "devid", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "param", "vlanid", ":", ":", "return", ":", "HTTP", "Status", "code", "of", "204", "with", "no", "values", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L569-L592
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
set_inteface_down
def set_inteface_down(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/down" f_url = url + set_int_down_url payload = None r = requests.put(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code else: print("An Error has occured")
python
def set_inteface_down(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/down" f_url = url + set_int_down_url payload = None r = requests.put(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code else: print("An Error has occured")
[ "def", "set_inteface_down", "(", "devid", ",", "ifindex", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "set_int_down_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devid", ")", "+", "\"/interface/\"", "+", "str", "(", "ifindex", ")", "+", "\"/down\"", "f_url", "=", "url", "+", "set_int_down_url", "payload", "=", "None", "r", "=", "requests", ".", "put", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "print", "(", "r", ".", "status_code", ")", "if", "r", ".", "status_code", "==", "204", ":", "return", "r", ".", "status_code", "else", ":", "print", "(", "\"An Error has occured\"", ")" ]
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values.
[ "function", "takest", "devid", "and", "ifindex", "of", "specific", "device", "and", "interface", "and", "issues", "a", "RESTFUL", "call", "to", "shut", "the", "specifie", "d", "interface", "on", "the", "target", "device", ".", ":", "param", "devid", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "param", "ifindex", ":", "int", "or", "str", "value", "of", "the", "target", "interface", ":", "return", ":", "HTTP", "status", "code", "204", "with", "no", "values", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L598-L617
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
set_inteface_up
def set_inteface_up(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url payload = None r = requests.put(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code else: print("An Error has occured")
python
def set_inteface_up(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url payload = None r = requests.put(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code else: print("An Error has occured")
[ "def", "set_inteface_up", "(", "devid", ",", "ifindex", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "set_int_up_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devid", ")", "+", "\"/interface/\"", "+", "str", "(", "ifindex", ")", "+", "\"/up\"", "f_url", "=", "url", "+", "set_int_up_url", "payload", "=", "None", "r", "=", "requests", ".", "put", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "print", "(", "r", ".", "status_code", ")", "if", "r", ".", "status_code", "==", "204", ":", "return", "r", ".", "status_code", "else", ":", "print", "(", "\"An Error has occured\"", ")" ]
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values.
[ "function", "takest", "devid", "and", "ifindex", "of", "specific", "device", "and", "interface", "and", "issues", "a", "RESTFUL", "call", "to", "undo", "shut", "the", "spec", "ified", "interface", "on", "the", "target", "device", ".", ":", "param", "devid", ":", "int", "or", "str", "value", "of", "the", "target", "device", ":", "param", "ifindex", ":", "int", "or", "str", "value", "of", "the", "target", "interface", ":", "return", ":", "HTTP", "status", "code", "204", "with", "no", "values", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L620-L639
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_vm_host_info
def get_vm_host_info(hostId): """ function takes hostId as input to RESTFUL call to HP IMC :param hostId: int or string of HostId of Hypervisor host :return:list of dictionatires contraining the VM Host information for the target hypervisor """ global r if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() get_vm_host_info_url = "/imcrs/vrm/host?hostId=" + str(hostId) f_url = url + get_vm_host_info_url payload = None r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents # print(r.status_code) if r.status_code == 200: if len(r.text) > 0: return json.loads(r.text) elif r.status_code == 204: print("Device is not a supported Hypervisor") return "Device is not a supported Hypervisor" else: print("An Error has occured")
python
def get_vm_host_info(hostId): """ function takes hostId as input to RESTFUL call to HP IMC :param hostId: int or string of HostId of Hypervisor host :return:list of dictionatires contraining the VM Host information for the target hypervisor """ global r if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() get_vm_host_info_url = "/imcrs/vrm/host?hostId=" + str(hostId) f_url = url + get_vm_host_info_url payload = None r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents # print(r.status_code) if r.status_code == 200: if len(r.text) > 0: return json.loads(r.text) elif r.status_code == 204: print("Device is not a supported Hypervisor") return "Device is not a supported Hypervisor" else: print("An Error has occured")
[ "def", "get_vm_host_info", "(", "hostId", ")", ":", "global", "r", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "get_vm_host_info_url", "=", "\"/imcrs/vrm/host?hostId=\"", "+", "str", "(", "hostId", ")", "f_url", "=", "url", "+", "get_vm_host_info_url", "payload", "=", "None", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# creates the URL using the payload variable as the contents", "# print(r.status_code)", "if", "r", ".", "status_code", "==", "200", ":", "if", "len", "(", "r", ".", "text", ")", ">", "0", ":", "return", "json", ".", "loads", "(", "r", ".", "text", ")", "elif", "r", ".", "status_code", "==", "204", ":", "print", "(", "\"Device is not a supported Hypervisor\"", ")", "return", "\"Device is not a supported Hypervisor\"", "else", ":", "print", "(", "\"An Error has occured\"", ")" ]
function takes hostId as input to RESTFUL call to HP IMC :param hostId: int or string of HostId of Hypervisor host :return:list of dictionatires contraining the VM Host information for the target hypervisor
[ "function", "takes", "hostId", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC", ":", "param", "hostId", ":", "int", "or", "string", "of", "HostId", "of", "Hypervisor", "host", ":", "return", ":", "list", "of", "dictionatires", "contraining", "the", "VM", "Host", "information", "for", "the", "target", "hypervisor" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L642-L664
train
HPENetworking/PYHPEIMC
archived/pyhpimc.py
get_trap_definitions
def get_trap_definitions(): """Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_trap_def_url = "/imcrs/fault/trapDefine/sync/query?enterpriseId=1.3.6.1.4.1.11&size=10000" f_url = url + get_trap_def_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: trap_def_list = (json.loads(r.text)) return trap_def_list['trapDefine'] else: print("get_dev_asset_details: An Error has occured")
python
def get_trap_definitions(): """Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_trap_def_url = "/imcrs/fault/trapDefine/sync/query?enterpriseId=1.3.6.1.4.1.11&size=10000" f_url = url + get_trap_def_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: trap_def_list = (json.loads(r.text)) return trap_def_list['trapDefine'] else: print("get_dev_asset_details: An Error has occured")
[ "def", "get_trap_definitions", "(", ")", ":", "# checks to see if the imc credentials are already available", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "set_imc_creds", "(", ")", "global", "r", "get_trap_def_url", "=", "\"/imcrs/fault/trapDefine/sync/query?enterpriseId=1.3.6.1.4.1.11&size=10000\"", "f_url", "=", "url", "+", "get_trap_def_url", "payload", "=", "None", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "# r.status_code", "if", "r", ".", "status_code", "==", "200", ":", "trap_def_list", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "return", "trap_def_list", "[", "'trapDefine'", "]", "else", ":", "print", "(", "\"get_dev_asset_details: An Error has occured\"", ")" ]
Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "SNMP", "TRAP", "definitions", "from", "HP", "IMC", "RESTFUL", "API", ":", "param", "None", ":", "return", ":", "object", "of", "type", "list", "containing", "the", "device", "asset", "details" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L741-L760
train
housecanary/hc-api-python
housecanary/exceptions.py
RateLimitException.rate_limits
def rate_limits(self): """Returns list of rate limit information from the response""" if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self._response) return self._rate_limits
python
def rate_limits(self): """Returns list of rate limit information from the response""" if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self._response) return self._rate_limits
[ "def", "rate_limits", "(", "self", ")", ":", "if", "not", "self", ".", "_rate_limits", ":", "self", ".", "_rate_limits", "=", "utilities", ".", "get_rate_limits", "(", "self", ".", "_response", ")", "return", "self", ".", "_rate_limits" ]
Returns list of rate limit information from the response
[ "Returns", "list", "of", "rate", "limit", "information", "from", "the", "response" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/exceptions.py#L30-L34
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/groups.py
get_custom_views
def get_custom_views(auth, url, name=None): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_views = get_custom_views(auth.creds, auth.url) >>> assert type(all_views) is list >>> assert 'name' in all_views[0] >>> non_existant_view = get_custom_views(auth.creds, auth.url, name = '''Doesn't Exist''') >>> assert non_existant_view is None """ get_custom_view_url = None if name is None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \ '&total=false' elif name is not None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name=' + \ name + '&desc=false&total=false' f_url = url + get_custom_view_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: custom_view_list = (json.loads(response.text)) if 'customView' in custom_view_list: custom_view_list = custom_view_list['customView'] if isinstance(custom_view_list, dict): custom_view_list = [custom_view_list] return custom_view_list else: return custom_view_list except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
python
def get_custom_views(auth, url, name=None): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_views = get_custom_views(auth.creds, auth.url) >>> assert type(all_views) is list >>> assert 'name' in all_views[0] >>> non_existant_view = get_custom_views(auth.creds, auth.url, name = '''Doesn't Exist''') >>> assert non_existant_view is None """ get_custom_view_url = None if name is None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \ '&total=false' elif name is not None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name=' + \ name + '&desc=false&total=false' f_url = url + get_custom_view_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: custom_view_list = (json.loads(response.text)) if 'customView' in custom_view_list: custom_view_list = custom_view_list['customView'] if isinstance(custom_view_list, dict): custom_view_list = [custom_view_list] return custom_view_list else: return custom_view_list except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
[ "def", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "None", ")", ":", "get_custom_view_url", "=", "None", "if", "name", "is", "None", ":", "get_custom_view_url", "=", "'/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false'", "'&total=false'", "elif", "name", "is", "not", "None", ":", "get_custom_view_url", "=", "'/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name='", "+", "name", "+", "'&desc=false&total=false'", "f_url", "=", "url", "+", "get_custom_view_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "custom_view_list", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "'customView'", "in", "custom_view_list", ":", "custom_view_list", "=", "custom_view_list", "[", "'customView'", "]", "if", "isinstance", "(", "custom_view_list", ",", "dict", ")", ":", "custom_view_list", "=", "[", "custom_view_list", "]", "return", "custom_view_list", "else", ":", "return", "custom_view_list", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_custom_views: An Error has occured'" ]
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_views = get_custom_views(auth.creds, auth.url) >>> assert type(all_views) is list >>> assert 'name' in all_views[0] >>> non_existant_view = get_custom_views(auth.creds, auth.url, name = '''Doesn't Exist''') >>> assert non_existant_view is None
[ "function", "requires", "no", "input", "and", "returns", "a", "list", "of", "dictionaries", "of", "custom", "views", "from", "an", "HPE", "IMC", ".", "Optional", "name", "argument", "will", "return", "only", "the", "specified", "view", ".", ":", "param", "name", ":", "str", "containing", "the", "name", "of", "the", "desired", "custom", "view" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/groups.py#L23-L77
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/groups.py
get_custom_view_details
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0] """ view_id = get_custom_views(auth, url, name=name) if view_id is None: return view_id view_id = get_custom_views(auth, url, name=name)[0]['symbolId'] get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + get_custom_view_details_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: current_devices = (json.loads(response.text)) if 'device' in current_devices: if isinstance(current_devices['device'], dict): return [current_devices['device']] else: return current_devices['device'] else: return [] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
python
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0] """ view_id = get_custom_views(auth, url, name=name) if view_id is None: return view_id view_id = get_custom_views(auth, url, name=name)[0]['symbolId'] get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + get_custom_view_details_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: current_devices = (json.loads(response.text)) if 'device' in current_devices: if isinstance(current_devices['device'], dict): return [current_devices['device']] else: return current_devices['device'] else: return [] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
[ "def", "get_custom_view_details", "(", "name", ",", "auth", ",", "url", ")", ":", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "name", ")", "if", "view_id", "is", "None", ":", "return", "view_id", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "name", ")", "[", "0", "]", "[", "'symbolId'", "]", "get_custom_view_details_url", "=", "'/imcrs/plat/res/view/custom/'", "+", "str", "(", "view_id", ")", "f_url", "=", "url", "+", "get_custom_view_details_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "current_devices", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "'device'", "in", "current_devices", ":", "if", "isinstance", "(", "current_devices", "[", "'device'", "]", ",", "dict", ")", ":", "return", "[", "current_devices", "[", "'device'", "]", "]", "else", ":", "return", "current_devices", "[", "'device'", "]", "else", ":", "return", "[", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_custom_views: An Error has occured'" ]
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0]
[ "function", "requires", "no", "input", "and", "returns", "a", "list", "of", "dictionaries", "of", "custom", "views", "from", "an", "HPE", "IMC", ".", "Optional", "name", "argument", "will", "return", "only", "the", "specified", "view", ".", ":", "param", "name", ":", "str", "containing", "the", "name", "of", "the", "desired", "custom", "view" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/groups.py#L80-L127
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/groups.py
create_custom_views
def create_custom_views(auth, url, name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optional Name input will return only the specified view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: string containg the name of the desired custom view :param upperview: str contraining the name of the desired parent custom view :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") #Create L1 custom view >>> create_custom_views(auth.creds, auth.url, name='L1 View') 'View L1 View created successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert type(view_1) is list >>> assert view_1[0]['name'] == 'L1 View' #Create Nested custome view >>> create_custom_views(auth.creds, auth.url, name='L2 View', upperview='L1 View') 'View L2 View created successfully' >>> view_2 = get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert type(view_2) is list >>> assert view_2[0]['name'] == 'L2 View' """ create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \ '&total=false' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(auth, url, upperview)[0]['symbolId'] payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : "''' + str(parentviewid) + '''"}''' response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 201: print('View ' + name + ' created successfully') return response.status_code elif response.status_code == 409: print("View " + name + " already exists") return response.status_code else: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
python
def create_custom_views(auth, url, name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optional Name input will return only the specified view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: string containg the name of the desired custom view :param upperview: str contraining the name of the desired parent custom view :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") #Create L1 custom view >>> create_custom_views(auth.creds, auth.url, name='L1 View') 'View L1 View created successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert type(view_1) is list >>> assert view_1[0]['name'] == 'L1 View' #Create Nested custome view >>> create_custom_views(auth.creds, auth.url, name='L2 View', upperview='L1 View') 'View L2 View created successfully' >>> view_2 = get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert type(view_2) is list >>> assert view_2[0]['name'] == 'L2 View' """ create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \ '&total=false' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(auth, url, upperview)[0]['symbolId'] payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : "''' + str(parentviewid) + '''"}''' response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 201: print('View ' + name + ' created successfully') return response.status_code elif response.status_code == 409: print("View " + name + " already exists") return response.status_code else: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
[ "def", "create_custom_views", "(", "auth", ",", "url", ",", "name", "=", "None", ",", "upperview", "=", "None", ")", ":", "create_custom_views_url", "=", "'/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false'", "'&total=false'", "f_url", "=", "url", "+", "create_custom_views_url", "if", "upperview", "is", "None", ":", "payload", "=", "'''{ \"name\": \"'''", "+", "name", "+", "'''\",\n \"upLevelSymbolId\" : \"\"}'''", "else", ":", "parentviewid", "=", "get_custom_views", "(", "auth", ",", "url", ",", "upperview", ")", "[", "0", "]", "[", "'symbolId'", "]", "payload", "=", "'''{ \"name\": \"'''", "+", "name", "+", "'''\",\n \"upLevelSymbolId\" : \"'''", "+", "str", "(", "parentviewid", ")", "+", "'''\"}'''", "response", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "201", ":", "print", "(", "'View '", "+", "name", "+", "' created successfully'", ")", "return", "response", ".", "status_code", "elif", "response", ".", "status_code", "==", "409", ":", "print", "(", "\"View \"", "+", "name", "+", "\" already exists\"", ")", "return", "response", ".", "status_code", "else", ":", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_custom_views: An Error has occured'" ]
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optional Name input will return only the specified view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: string containg the name of the desired custom view :param upperview: str contraining the name of the desired parent custom view :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") #Create L1 custom view >>> create_custom_views(auth.creds, auth.url, name='L1 View') 'View L1 View created successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert type(view_1) is list >>> assert view_1[0]['name'] == 'L1 View' #Create Nested custome view >>> create_custom_views(auth.creds, auth.url, name='L2 View', upperview='L1 View') 'View L2 View created successfully' >>> view_2 = get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert type(view_2) is list >>> assert view_2[0]['name'] == 'L2 View'
[ "function", "takes", "no", "input", "and", "issues", "a", "RESTFUL", "call", "to", "get", "a", "list", "of", "custom", "views", "from", "HPE", "IMC", ".", "Optional", "Name", "input", "will", "return", "only", "the", "specified", "view", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/groups.py#L130-L195
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/groups.py
add_devs_custom_views
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param custom_view_name: str of the target custom view name :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") """ view_id = get_custom_views(auth, url, name=custom_view_name) if view_id is None: print("View " + custom_view_name + " doesn't exist") return view_id view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId'] add_devs_custom_views_url = '/imcrs/plat/res/view/custom/' + str(view_id) device_list = [] for dev in dev_list: new_dev = {"id": dev} device_list.append(new_dev) payload = '''{"device" : ''' + json.dumps(device_list) + '''}''' print(payload) f_url = url + add_devs_custom_views_url response = requests.put(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('View ' + custom_view_name + ' : Devices Successfully Added') return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
python
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param custom_view_name: str of the target custom view name :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") """ view_id = get_custom_views(auth, url, name=custom_view_name) if view_id is None: print("View " + custom_view_name + " doesn't exist") return view_id view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId'] add_devs_custom_views_url = '/imcrs/plat/res/view/custom/' + str(view_id) device_list = [] for dev in dev_list: new_dev = {"id": dev} device_list.append(new_dev) payload = '''{"device" : ''' + json.dumps(device_list) + '''}''' print(payload) f_url = url + add_devs_custom_views_url response = requests.put(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('View ' + custom_view_name + ' : Devices Successfully Added') return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
[ "def", "add_devs_custom_views", "(", "custom_view_name", ",", "dev_list", ",", "auth", ",", "url", ")", ":", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "custom_view_name", ")", "if", "view_id", "is", "None", ":", "print", "(", "\"View \"", "+", "custom_view_name", "+", "\" doesn't exist\"", ")", "return", "view_id", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", "=", "custom_view_name", ")", "[", "0", "]", "[", "'symbolId'", "]", "add_devs_custom_views_url", "=", "'/imcrs/plat/res/view/custom/'", "+", "str", "(", "view_id", ")", "device_list", "=", "[", "]", "for", "dev", "in", "dev_list", ":", "new_dev", "=", "{", "\"id\"", ":", "dev", "}", "device_list", ".", "append", "(", "new_dev", ")", "payload", "=", "'''{\"device\" : '''", "+", "json", ".", "dumps", "(", "device_list", ")", "+", "'''}'''", "print", "(", "payload", ")", "f_url", "=", "url", "+", "add_devs_custom_views_url", "response", "=", "requests", ".", "put", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "204", ":", "print", "(", "'View '", "+", "custom_view_name", "+", "' : Devices Successfully Added'", ")", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_custom_views: An Error has occured'" ]
function takes a list of devIDs from devices discovered in the HPE IMC platform and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param custom_view_name: str of the target custom view name :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
[ "function", "takes", "a", "list", "of", "devIDs", "from", "devices", "discovered", "in", "the", "HPE", "IMC", "platform", "and", "issues", "a", "RESTFUL", "call", "to", "add", "the", "list", "of", "devices", "to", "a", "specific", "custom", "views", "from", "HPE", "IMC", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/groups.py#L200-L241
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/groups.py
delete_custom_view
def delete_custom_view(auth, url, name): """ function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 is None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 is None """ view_id = get_custom_views(auth, url, name) if view_id is None: print("View " + name + " doesn't exists") return view_id view_id = get_custom_views(auth, url, name)[0]['symbolId'] delete_custom_view_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + delete_custom_view_url response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('View ' + name + ' deleted successfully') return response.status_code else: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' delete_custom_view: An Error has occured'
python
def delete_custom_view(auth, url, name): """ function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 is None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 is None """ view_id = get_custom_views(auth, url, name) if view_id is None: print("View " + name + " doesn't exists") return view_id view_id = get_custom_views(auth, url, name)[0]['symbolId'] delete_custom_view_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + delete_custom_view_url response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('View ' + name + ' deleted successfully') return response.status_code else: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' delete_custom_view: An Error has occured'
[ "def", "delete_custom_view", "(", "auth", ",", "url", ",", "name", ")", ":", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", ")", "if", "view_id", "is", "None", ":", "print", "(", "\"View \"", "+", "name", "+", "\" doesn't exists\"", ")", "return", "view_id", "view_id", "=", "get_custom_views", "(", "auth", ",", "url", ",", "name", ")", "[", "0", "]", "[", "'symbolId'", "]", "delete_custom_view_url", "=", "'/imcrs/plat/res/view/custom/'", "+", "str", "(", "view_id", ")", "f_url", "=", "url", "+", "delete_custom_view_url", "response", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "204", ":", "print", "(", "'View '", "+", "name", "+", "' deleted successfully'", ")", "return", "response", ".", "status_code", "else", ":", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' delete_custom_view: An Error has occured'" ]
function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 is None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 is None
[ "function", "takes", "input", "of", "auth", "url", "and", "name", "and", "issues", "a", "RESTFUL", "call", "to", "delete", "a", "specific", "of", "custom", "views", "from", "HPE", "IMC", ".", ":", "param", "name", ":", "string", "containg", "the", "name", "of", "the", "desired", "custom", "view" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/groups.py#L244-L295
train
wilfilho/BingTranslator
BingTranslator/__init__.py
Translator._get_token
def _get_token(self): """ Get token for make request. The The data obtained herein are used in the variable header. Returns: To perform the request, receive in return a dictionary with several keys. With this method only return the token as it will use it for subsequent requests, such as a sentence translate. Returns one string type. """ informations = self._set_format_oauth() oauth_url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13" token = requests.post(oauth_url, informations).json() return token["access_token"]
python
def _get_token(self): """ Get token for make request. The The data obtained herein are used in the variable header. Returns: To perform the request, receive in return a dictionary with several keys. With this method only return the token as it will use it for subsequent requests, such as a sentence translate. Returns one string type. """ informations = self._set_format_oauth() oauth_url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13" token = requests.post(oauth_url, informations).json() return token["access_token"]
[ "def", "_get_token", "(", "self", ")", ":", "informations", "=", "self", ".", "_set_format_oauth", "(", ")", "oauth_url", "=", "\"https://datamarket.accesscontrol.windows.net/v2/OAuth2-13\"", "token", "=", "requests", ".", "post", "(", "oauth_url", ",", "informations", ")", ".", "json", "(", ")", "return", "token", "[", "\"access_token\"", "]" ]
Get token for make request. The The data obtained herein are used in the variable header. Returns: To perform the request, receive in return a dictionary with several keys. With this method only return the token as it will use it for subsequent requests, such as a sentence translate. Returns one string type.
[ "Get", "token", "for", "make", "request", ".", "The", "The", "data", "obtained", "herein", "are", "used", "in", "the", "variable", "header", ".", "Returns", ":", "To", "perform", "the", "request", "receive", "in", "return", "a", "dictionary", "with", "several", "keys", ".", "With", "this", "method", "only", "return", "the", "token", "as", "it", "will", "use", "it", "for", "subsequent", "requests", "such", "as", "a", "sentence", "translate", ".", "Returns", "one", "string", "type", "." ]
6bada6fe1ac4177cc7dc62ff16dab561ba714534
https://github.com/wilfilho/BingTranslator/blob/6bada6fe1ac4177cc7dc62ff16dab561ba714534/BingTranslator/__init__.py#L35-L49
train
wilfilho/BingTranslator
BingTranslator/__init__.py
Translator._set_format_oauth
def _set_format_oauth(self): """ Format and encode dict for make authentication on microsoft servers. """ format_oauth = urllib.parse.urlencode({ 'client_id': self._client_id, 'client_secret': self._client_secret, 'scope': self._url_request, 'grant_type': self._grant_type }).encode("utf-8") return format_oauth
python
def _set_format_oauth(self): """ Format and encode dict for make authentication on microsoft servers. """ format_oauth = urllib.parse.urlencode({ 'client_id': self._client_id, 'client_secret': self._client_secret, 'scope': self._url_request, 'grant_type': self._grant_type }).encode("utf-8") return format_oauth
[ "def", "_set_format_oauth", "(", "self", ")", ":", "format_oauth", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "'client_id'", ":", "self", ".", "_client_id", ",", "'client_secret'", ":", "self", ".", "_client_secret", ",", "'scope'", ":", "self", ".", "_url_request", ",", "'grant_type'", ":", "self", ".", "_grant_type", "}", ")", ".", "encode", "(", "\"utf-8\"", ")", "return", "format_oauth" ]
Format and encode dict for make authentication on microsoft servers.
[ "Format", "and", "encode", "dict", "for", "make", "authentication", "on", "microsoft", "servers", "." ]
6bada6fe1ac4177cc7dc62ff16dab561ba714534
https://github.com/wilfilho/BingTranslator/blob/6bada6fe1ac4177cc7dc62ff16dab561ba714534/BingTranslator/__init__.py#L51-L62
train
wilfilho/BingTranslator
BingTranslator/__init__.py
Translator._make_request
def _make_request(self, params, translation_url, headers): """ This is the final step, where the request is made, the data is retrieved and returned. """ resp = requests.get(translation_url, params=params, headers=headers) resp.encoding = "UTF-8-sig" result = resp.json() return result
python
def _make_request(self, params, translation_url, headers): """ This is the final step, where the request is made, the data is retrieved and returned. """ resp = requests.get(translation_url, params=params, headers=headers) resp.encoding = "UTF-8-sig" result = resp.json() return result
[ "def", "_make_request", "(", "self", ",", "params", ",", "translation_url", ",", "headers", ")", ":", "resp", "=", "requests", ".", "get", "(", "translation_url", ",", "params", "=", "params", ",", "headers", "=", "headers", ")", "resp", ".", "encoding", "=", "\"UTF-8-sig\"", "result", "=", "resp", ".", "json", "(", ")", "return", "result" ]
This is the final step, where the request is made, the data is retrieved and returned.
[ "This", "is", "the", "final", "step", "where", "the", "request", "is", "made", "the", "data", "is", "retrieved", "and", "returned", "." ]
6bada6fe1ac4177cc7dc62ff16dab561ba714534
https://github.com/wilfilho/BingTranslator/blob/6bada6fe1ac4177cc7dc62ff16dab561ba714534/BingTranslator/__init__.py#L64-L72
train