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
HPENetworking/PYHPEIMC
pyhpeimc/plat/system.py
delete_ssh_template
def delete_ssh_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific ssh template from the IMC system :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 template_name: str value of template name :param template_id: str value template template_id value :return: int HTTP response code :rtype int """ try: if template_id is None: ssh_templates = get_ssh_template(auth, url) if template_name is None: template_name = ssh_template['name'] template_id = None for template in ssh_templates: if template['name'] == template_name: template_id = template['id'] f_url = url + "/imcrs/plat/res/ssh/%s/delete" % template_id response = requests.delete(f_url, auth=auth, headers=HEADERS) return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_ssh_template: An Error has occured"
python
def delete_ssh_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific ssh template from the IMC system :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 template_name: str value of template name :param template_id: str value template template_id value :return: int HTTP response code :rtype int """ try: if template_id is None: ssh_templates = get_ssh_template(auth, url) if template_name is None: template_name = ssh_template['name'] template_id = None for template in ssh_templates: if template['name'] == template_name: template_id = template['id'] f_url = url + "/imcrs/plat/res/ssh/%s/delete" % template_id response = requests.delete(f_url, auth=auth, headers=HEADERS) return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_ssh_template: An Error has occured"
[ "def", "delete_ssh_template", "(", "auth", ",", "url", ",", "template_name", "=", "None", ",", "template_id", "=", "None", ")", ":", "try", ":", "if", "template_id", "is", "None", ":", "ssh_templates", "=", "get_ssh_template", "(", "auth", ",", "url", ")", "if", "template_name", "is", "None", ":", "template_name", "=", "ssh_template", "[", "'name'", "]", "template_id", "=", "None", "for", "template", "in", "ssh_templates", ":", "if", "template", "[", "'name'", "]", "==", "template_name", ":", "template_id", "=", "template", "[", "'id'", "]", "f_url", "=", "url", "+", "\"/imcrs/plat/res/ssh/%s/delete\"", "%", "template_id", "response", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" delete_ssh_template: An Error has occured\"" ]
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific ssh template from the IMC system :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 template_name: str value of template name :param template_id: str value template template_id value :return: int HTTP response code :rtype int
[ "Takes", "template_name", "as", "input", "to", "issue", "RESTUL", "call", "to", "HP", "IMC", "which", "will", "delete", "the", "specific", "ssh", "template", "from", "the", "IMC", "system" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/system.py#L442-L472
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/system.py
get_snmp_templates
def get_snmp_templates(auth, url, template_name=None): """ Takes no input, or template_name as input 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 template_name: str value of template name :return list object containing one or more dictionaries where each dictionary represents one snmp template :rtype list """ f_url = url + "/imcrs/plat/res/snmp?start=0&size=10000&desc=false&total=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: snmp_templates = (json.loads(response.text)) template = None if type(snmp_templates['snmpParamTemplate']) is dict: my_templates = [snmp_templates['snmpParamTemplate']] snmp_templates['snmpParamTemplate'] = my_templates if template_name is None: return snmp_templates['snmpParamTemplate'] elif template_name is not None: for snmp_template in snmp_templates['snmpParamTemplate']: if snmp_template['name'] == template_name: template = [snmp_template] if template == None: return 404 else: return template except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_snmp_templates: An Error has occured"
python
def get_snmp_templates(auth, url, template_name=None): """ Takes no input, or template_name as input 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 template_name: str value of template name :return list object containing one or more dictionaries where each dictionary represents one snmp template :rtype list """ f_url = url + "/imcrs/plat/res/snmp?start=0&size=10000&desc=false&total=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: snmp_templates = (json.loads(response.text)) template = None if type(snmp_templates['snmpParamTemplate']) is dict: my_templates = [snmp_templates['snmpParamTemplate']] snmp_templates['snmpParamTemplate'] = my_templates if template_name is None: return snmp_templates['snmpParamTemplate'] elif template_name is not None: for snmp_template in snmp_templates['snmpParamTemplate']: if snmp_template['name'] == template_name: template = [snmp_template] if template == None: return 404 else: return template except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_snmp_templates: An Error has occured"
[ "def", "get_snmp_templates", "(", "auth", ",", "url", ",", "template_name", "=", "None", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/plat/res/snmp?start=0&size=10000&desc=false&total=false\"", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "snmp_templates", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "template", "=", "None", "if", "type", "(", "snmp_templates", "[", "'snmpParamTemplate'", "]", ")", "is", "dict", ":", "my_templates", "=", "[", "snmp_templates", "[", "'snmpParamTemplate'", "]", "]", "snmp_templates", "[", "'snmpParamTemplate'", "]", "=", "my_templates", "if", "template_name", "is", "None", ":", "return", "snmp_templates", "[", "'snmpParamTemplate'", "]", "elif", "template_name", "is", "not", "None", ":", "for", "snmp_template", "in", "snmp_templates", "[", "'snmpParamTemplate'", "]", ":", "if", "snmp_template", "[", "'name'", "]", "==", "template_name", ":", "template", "=", "[", "snmp_template", "]", "if", "template", "==", "None", ":", "return", "404", "else", ":", "return", "template", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_snmp_templates: An Error has occured\"" ]
Takes no input, or template_name as input 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 template_name: str value of template name :return list object containing one or more dictionaries where each dictionary represents one snmp template :rtype list
[ "Takes", "no", "input", "or", "template_name", "as", "input", "to", "issue", "RESTUL", "call", "to", "HP", "IMC" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/system.py#L530-L566
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/system.py
modify_snmp_template
def modify_snmp_template(auth, url, snmp_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a snmp template. :param auth: :param url: :param ssh_template: Human readable label which is the name of the specific ssh template :param template_id Internal IMC number which designates the specific ssh template :return: int value of HTTP response code 201 for proper creation or 404 for failed creation :rtype int Sample of proper KV pairs. Please see documentation for valid values for different fields. snmp_template = { "version": "2", "name": "new_snmp_template", "type": "0", "paraType": "SNMPv2c", "roCommunity": "newpublic", "rwCommunity": "newprivate", "timeout": "4", "retries": "4", "contextName": "", "securityName": " ", "securityMode": "1", "authScheme": "0", "authPassword": "", "privScheme": "0", "privPassword": "", "snmpPort": "161", "isAutodiscoverTemp": "1", "creator": "admin", "accessType": "1", "operatorGroupStr": "" } """ if template_name is None: template_name = snmp_template['name'] if template_id is None: snmp_templates = get_snmp_templates(auth, url) template_id = None for template in snmp_templates: if template['name'] == template_name: template_id = template['id'] f_url = url + "/imcrs/plat/res/snmp/"+str(template_id)+"/update" response = requests.put(f_url, data = json.dumps(snmp_template), auth=auth, headers=HEADERS) try: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " modify_snmp_template: An Error has occured"
python
def modify_snmp_template(auth, url, snmp_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a snmp template. :param auth: :param url: :param ssh_template: Human readable label which is the name of the specific ssh template :param template_id Internal IMC number which designates the specific ssh template :return: int value of HTTP response code 201 for proper creation or 404 for failed creation :rtype int Sample of proper KV pairs. Please see documentation for valid values for different fields. snmp_template = { "version": "2", "name": "new_snmp_template", "type": "0", "paraType": "SNMPv2c", "roCommunity": "newpublic", "rwCommunity": "newprivate", "timeout": "4", "retries": "4", "contextName": "", "securityName": " ", "securityMode": "1", "authScheme": "0", "authPassword": "", "privScheme": "0", "privPassword": "", "snmpPort": "161", "isAutodiscoverTemp": "1", "creator": "admin", "accessType": "1", "operatorGroupStr": "" } """ if template_name is None: template_name = snmp_template['name'] if template_id is None: snmp_templates = get_snmp_templates(auth, url) template_id = None for template in snmp_templates: if template['name'] == template_name: template_id = template['id'] f_url = url + "/imcrs/plat/res/snmp/"+str(template_id)+"/update" response = requests.put(f_url, data = json.dumps(snmp_template), auth=auth, headers=HEADERS) try: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " modify_snmp_template: An Error has occured"
[ "def", "modify_snmp_template", "(", "auth", ",", "url", ",", "snmp_template", ",", "template_name", "=", "None", ",", "template_id", "=", "None", ")", ":", "if", "template_name", "is", "None", ":", "template_name", "=", "snmp_template", "[", "'name'", "]", "if", "template_id", "is", "None", ":", "snmp_templates", "=", "get_snmp_templates", "(", "auth", ",", "url", ")", "template_id", "=", "None", "for", "template", "in", "snmp_templates", ":", "if", "template", "[", "'name'", "]", "==", "template_name", ":", "template_id", "=", "template", "[", "'id'", "]", "f_url", "=", "url", "+", "\"/imcrs/plat/res/snmp/\"", "+", "str", "(", "template_id", ")", "+", "\"/update\"", "response", "=", "requests", ".", "put", "(", "f_url", ",", "data", "=", "json", ".", "dumps", "(", "snmp_template", ")", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" modify_snmp_template: An Error has occured\"" ]
Function takes input of a dictionry containing the required key/value pair for the modification of a snmp template. :param auth: :param url: :param ssh_template: Human readable label which is the name of the specific ssh template :param template_id Internal IMC number which designates the specific ssh template :return: int value of HTTP response code 201 for proper creation or 404 for failed creation :rtype int Sample of proper KV pairs. Please see documentation for valid values for different fields. snmp_template = { "version": "2", "name": "new_snmp_template", "type": "0", "paraType": "SNMPv2c", "roCommunity": "newpublic", "rwCommunity": "newprivate", "timeout": "4", "retries": "4", "contextName": "", "securityName": " ", "securityMode": "1", "authScheme": "0", "authPassword": "", "privScheme": "0", "privPassword": "", "snmpPort": "161", "isAutodiscoverTemp": "1", "creator": "admin", "accessType": "1", "operatorGroupStr": "" }
[ "Function", "takes", "input", "of", "a", "dictionry", "containing", "the", "required", "key", "/", "value", "pair", "for", "the", "modification", "of", "a", "snmp", "template", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/system.py#L569-L619
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/system.py
delete_snmp_template
def delete_snmp_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific snmp template from the IMC system :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 template_name: str value of template name :param template_id: str value template template_id value :return: int HTTP response code :rtype int """ try: if template_id is None: snmp_templates = get_snmp_templates(auth, url) if template_name is None: template_name = snmp_template['name'] template_id = None for template in snmp_templates: if template['name'] == template_name: template_id = template['id'] f_url = url + "/imcrs/plat/res/snmp/%s/delete" % template_id response = requests.delete(f_url, auth=auth, headers=HEADERS) return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_snmp_template: An Error has occured"
python
def delete_snmp_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific snmp template from the IMC system :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 template_name: str value of template name :param template_id: str value template template_id value :return: int HTTP response code :rtype int """ try: if template_id is None: snmp_templates = get_snmp_templates(auth, url) if template_name is None: template_name = snmp_template['name'] template_id = None for template in snmp_templates: if template['name'] == template_name: template_id = template['id'] f_url = url + "/imcrs/plat/res/snmp/%s/delete" % template_id response = requests.delete(f_url, auth=auth, headers=HEADERS) return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_snmp_template: An Error has occured"
[ "def", "delete_snmp_template", "(", "auth", ",", "url", ",", "template_name", "=", "None", ",", "template_id", "=", "None", ")", ":", "try", ":", "if", "template_id", "is", "None", ":", "snmp_templates", "=", "get_snmp_templates", "(", "auth", ",", "url", ")", "if", "template_name", "is", "None", ":", "template_name", "=", "snmp_template", "[", "'name'", "]", "template_id", "=", "None", "for", "template", "in", "snmp_templates", ":", "if", "template", "[", "'name'", "]", "==", "template_name", ":", "template_id", "=", "template", "[", "'id'", "]", "f_url", "=", "url", "+", "\"/imcrs/plat/res/snmp/%s/delete\"", "%", "template_id", "response", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" delete_snmp_template: An Error has occured\"" ]
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific snmp template from the IMC system :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 template_name: str value of template name :param template_id: str value template template_id value :return: int HTTP response code :rtype int
[ "Takes", "template_name", "as", "input", "to", "issue", "RESTUL", "call", "to", "HP", "IMC", "which", "will", "delete", "the", "specific", "snmp", "template", "from", "the", "IMC", "system" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/system.py#L622-L652
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/netassets.py
get_dev_asset_details
def get_dev_asset_details(ipaddress, auth, url): """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 :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: object of type list containing the device asset details, with each asset contained in a dictionary :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url) >>> assert type(single_asset) is list >>> assert 'name' in single_asset[0] """ ipaddress = get_dev_details(ipaddress, auth, url) if isinstance(ipaddress, dict): ipaddress = ipaddress['ip'] else: print("Asset Doesn't Exist") return 403 f_url = url + "/imcrs/netasset/asset?assetDevice.ip=" + str(ipaddress) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_asset_info = (json.loads(response.text)) if len(dev_asset_info) > 0: dev_asset_info = dev_asset_info['netAsset'] if isinstance(dev_asset_info, dict): dev_asset_info = [dev_asset_info] if isinstance(dev_asset_info, list): dev_asset_info[:] = [dev for dev in dev_asset_info if dev.get('deviceIp') == ipaddress] return dev_asset_info except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_asset_details: An Error has occured'
python
def get_dev_asset_details(ipaddress, auth, url): """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 :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: object of type list containing the device asset details, with each asset contained in a dictionary :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url) >>> assert type(single_asset) is list >>> assert 'name' in single_asset[0] """ ipaddress = get_dev_details(ipaddress, auth, url) if isinstance(ipaddress, dict): ipaddress = ipaddress['ip'] else: print("Asset Doesn't Exist") return 403 f_url = url + "/imcrs/netasset/asset?assetDevice.ip=" + str(ipaddress) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_asset_info = (json.loads(response.text)) if len(dev_asset_info) > 0: dev_asset_info = dev_asset_info['netAsset'] if isinstance(dev_asset_info, dict): dev_asset_info = [dev_asset_info] if isinstance(dev_asset_info, list): dev_asset_info[:] = [dev for dev in dev_asset_info if dev.get('deviceIp') == ipaddress] return dev_asset_info except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_asset_details: An Error has occured'
[ "def", "get_dev_asset_details", "(", "ipaddress", ",", "auth", ",", "url", ")", ":", "ipaddress", "=", "get_dev_details", "(", "ipaddress", ",", "auth", ",", "url", ")", "if", "isinstance", "(", "ipaddress", ",", "dict", ")", ":", "ipaddress", "=", "ipaddress", "[", "'ip'", "]", "else", ":", "print", "(", "\"Asset Doesn't Exist\"", ")", "return", "403", "f_url", "=", "url", "+", "\"/imcrs/netasset/asset?assetDevice.ip=\"", "+", "str", "(", "ipaddress", ")", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_asset_info", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "len", "(", "dev_asset_info", ")", ">", "0", ":", "dev_asset_info", "=", "dev_asset_info", "[", "'netAsset'", "]", "if", "isinstance", "(", "dev_asset_info", ",", "dict", ")", ":", "dev_asset_info", "=", "[", "dev_asset_info", "]", "if", "isinstance", "(", "dev_asset_info", ",", "list", ")", ":", "dev_asset_info", "[", ":", "]", "=", "[", "dev", "for", "dev", "in", "dev_asset_info", "if", "dev", ".", "get", "(", "'deviceIp'", ")", "==", "ipaddress", "]", "return", "dev_asset_info", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' 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 :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: object of type list containing the device asset details, with each asset contained in a dictionary :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url) >>> assert type(single_asset) is list >>> assert 'name' in single_asset[0]
[ "Takes", "in", "ipaddress", "as", "input", "to", "fetch", "device", "assett", "details", "from", "HP", "IMC", "RESTFUL", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/netassets.py#L21-L68
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/netassets.py
get_dev_asset_details_all
def get_dev_asset_details_all(auth, url): """Takes no input to fetch device assett details from HP 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 :return: list of dictionatires containing the device asset details :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_assets = get_dev_asset_details_all( auth.creds, auth.url) >>> assert type(all_assets) is list >>> assert 'asset' in all_assets[0] """ f_url = url + "/imcrs/netasset/asset?start=0&size=15000" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_asset_info = (json.loads(response.text))['netAsset'] return dev_asset_info except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_asset_details: An Error has occured'
python
def get_dev_asset_details_all(auth, url): """Takes no input to fetch device assett details from HP 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 :return: list of dictionatires containing the device asset details :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_assets = get_dev_asset_details_all( auth.creds, auth.url) >>> assert type(all_assets) is list >>> assert 'asset' in all_assets[0] """ f_url = url + "/imcrs/netasset/asset?start=0&size=15000" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_asset_info = (json.loads(response.text))['netAsset'] return dev_asset_info except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_dev_asset_details: An Error has occured'
[ "def", "get_dev_asset_details_all", "(", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/netasset/asset?start=0&size=15000\"", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_asset_info", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "[", "'netAsset'", "]", "return", "dev_asset_info", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "' get_dev_asset_details: An Error has occured'" ]
Takes no input to fetch device assett details from HP 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 :return: list of dictionatires containing the device asset details :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_assets = get_dev_asset_details_all( auth.creds, auth.url) >>> assert type(all_assets) is list >>> assert 'asset' in all_assets[0]
[ "Takes", "no", "input", "to", "fetch", "device", "assett", "details", "from", "HP", "IMC", "RESTFUL", "API" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/netassets.py#L71-L102
train
lablup/backend.ai-client-py
src/ai/backend/client/cli/proxy.py
proxy
def proxy(ctx, bind, port): """ Run a non-encrypted non-authorized API proxy server. Use this only for development and testing! """ app = web.Application() app.on_startup.append(startup_proxy) app.on_cleanup.append(cleanup_proxy) app.router.add_route("GET", r'/stream/{path:.*$}', websocket_handler) app.router.add_route("GET", r'/wsproxy/{path:.*$}', websocket_handler) app.router.add_route('*', r'/{path:.*$}', web_handler) if getattr(ctx.args, 'testing', False): return app web.run_app(app, host=bind, port=port)
python
def proxy(ctx, bind, port): """ Run a non-encrypted non-authorized API proxy server. Use this only for development and testing! """ app = web.Application() app.on_startup.append(startup_proxy) app.on_cleanup.append(cleanup_proxy) app.router.add_route("GET", r'/stream/{path:.*$}', websocket_handler) app.router.add_route("GET", r'/wsproxy/{path:.*$}', websocket_handler) app.router.add_route('*', r'/{path:.*$}', web_handler) if getattr(ctx.args, 'testing', False): return app web.run_app(app, host=bind, port=port)
[ "def", "proxy", "(", "ctx", ",", "bind", ",", "port", ")", ":", "app", "=", "web", ".", "Application", "(", ")", "app", ".", "on_startup", ".", "append", "(", "startup_proxy", ")", "app", ".", "on_cleanup", ".", "append", "(", "cleanup_proxy", ")", "app", ".", "router", ".", "add_route", "(", "\"GET\"", ",", "r'/stream/{path:.*$}'", ",", "websocket_handler", ")", "app", ".", "router", ".", "add_route", "(", "\"GET\"", ",", "r'/wsproxy/{path:.*$}'", ",", "websocket_handler", ")", "app", ".", "router", ".", "add_route", "(", "'*'", ",", "r'/{path:.*$}'", ",", "web_handler", ")", "if", "getattr", "(", "ctx", ".", "args", ",", "'testing'", ",", "False", ")", ":", "return", "app", "web", ".", "run_app", "(", "app", ",", "host", "=", "bind", ",", "port", "=", "port", ")" ]
Run a non-encrypted non-authorized API proxy server. Use this only for development and testing!
[ "Run", "a", "non", "-", "encrypted", "non", "-", "authorized", "API", "proxy", "server", ".", "Use", "this", "only", "for", "development", "and", "testing!" ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/proxy.py#L194-L208
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
get_all_devs
def get_all_devs(auth, url, network_address=None, category=None, label=None): """Takes string input of IP address to issue RESTUL call to HP IMC\n :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 network_address: str IPv4 Network Address :param category: str or int corresponding to device category (0=router, 1=switches, see API docs for other examples) :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.') >>> assert type(dev_list) is list >>> assert 'sysName' in dev_list[0] """ base_url = "/imcrs/plat/res/device?resPrivilegeFilter=false" end_url = "&start=0&size=1000&orderBy=id&desc=false&total=false" if network_address: network_address = "&ip=" + str(network_address) else: network_address = '' if label: label = "&label=" + str(label) else: label = '' if category: category = "&category" + category else: category = '' f_url = url + base_url + str(network_address) + str(label) + str(category) + end_url print(f_url) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_details = (json.loads(response.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif type(dev_details['device']) is dict: return [dev_details['device']] else: return dev_details['device'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_details: An Error has occured"
python
def get_all_devs(auth, url, network_address=None, category=None, label=None): """Takes string input of IP address to issue RESTUL call to HP IMC\n :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 network_address: str IPv4 Network Address :param category: str or int corresponding to device category (0=router, 1=switches, see API docs for other examples) :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.') >>> assert type(dev_list) is list >>> assert 'sysName' in dev_list[0] """ base_url = "/imcrs/plat/res/device?resPrivilegeFilter=false" end_url = "&start=0&size=1000&orderBy=id&desc=false&total=false" if network_address: network_address = "&ip=" + str(network_address) else: network_address = '' if label: label = "&label=" + str(label) else: label = '' if category: category = "&category" + category else: category = '' f_url = url + base_url + str(network_address) + str(label) + str(category) + end_url print(f_url) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_details = (json.loads(response.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif type(dev_details['device']) is dict: return [dev_details['device']] else: return dev_details['device'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_details: An Error has occured"
[ "def", "get_all_devs", "(", "auth", ",", "url", ",", "network_address", "=", "None", ",", "category", "=", "None", ",", "label", "=", "None", ")", ":", "base_url", "=", "\"/imcrs/plat/res/device?resPrivilegeFilter=false\"", "end_url", "=", "\"&start=0&size=1000&orderBy=id&desc=false&total=false\"", "if", "network_address", ":", "network_address", "=", "\"&ip=\"", "+", "str", "(", "network_address", ")", "else", ":", "network_address", "=", "''", "if", "label", ":", "label", "=", "\"&label=\"", "+", "str", "(", "label", ")", "else", ":", "label", "=", "''", "if", "category", ":", "category", "=", "\"&category\"", "+", "category", "else", ":", "category", "=", "''", "f_url", "=", "url", "+", "base_url", "+", "str", "(", "network_address", ")", "+", "str", "(", "label", ")", "+", "str", "(", "category", ")", "+", "end_url", "print", "(", "f_url", ")", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_details", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "len", "(", "dev_details", ")", "==", "0", ":", "print", "(", "\"Device not found\"", ")", "return", "\"Device not found\"", "elif", "type", "(", "dev_details", "[", "'device'", "]", ")", "is", "dict", ":", "return", "[", "dev_details", "[", "'device'", "]", "]", "else", ":", "return", "dev_details", "[", "'device'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_dev_details: An Error has occured\"" ]
Takes string input of IP address to issue RESTUL call to HP IMC\n :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 network_address: str IPv4 Network Address :param category: str or int corresponding to device category (0=router, 1=switches, see API docs for other examples) :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.') >>> assert type(dev_list) is list >>> assert 'sysName' in dev_list[0]
[ "Takes", "string", "input", "of", "IP", "address", "to", "issue", "RESTUL", "call", "to", "HP", "IMC", "\\", "n" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L174-L225
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
get_dev_details
def get_dev_details(ip_address, auth, url): """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 :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: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url) >>> assert type(dev_1) is dict >>> assert 'sysName' in dev_1 >>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url) Device not found >>> assert type(dev_2) is str """ 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 response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_details = (json.loads(response.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif isinstance(dev_details['device'], list): for i in dev_details['device']: if i['ip'] == ip_address: dev_details = i return dev_details elif isinstance(dev_details['device'], dict): return dev_details['device'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_details: An Error has occured"
python
def get_dev_details(ip_address, auth, url): """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 :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: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url) >>> assert type(dev_1) is dict >>> assert 'sysName' in dev_1 >>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url) Device not found >>> assert type(dev_2) is str """ 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 response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_details = (json.loads(response.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif isinstance(dev_details['device'], list): for i in dev_details['device']: if i['ip'] == ip_address: dev_details = i return dev_details elif isinstance(dev_details['device'], dict): return dev_details['device'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_details: An Error has occured"
[ "def", "get_dev_details", "(", "ip_address", ",", "auth", ",", "url", ")", ":", "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", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_details", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "if", "len", "(", "dev_details", ")", "==", "0", ":", "print", "(", "\"Device not found\"", ")", "return", "\"Device not found\"", "elif", "isinstance", "(", "dev_details", "[", "'device'", "]", ",", "list", ")", ":", "for", "i", "in", "dev_details", "[", "'device'", "]", ":", "if", "i", "[", "'ip'", "]", "==", "ip_address", ":", "dev_details", "=", "i", "return", "dev_details", "elif", "isinstance", "(", "dev_details", "[", "'device'", "]", ",", "dict", ")", ":", "return", "dev_details", "[", "'device'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_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 :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: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url) >>> assert type(dev_1) is dict >>> assert 'sysName' in dev_1 >>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url) Device not found >>> assert type(dev_2) is str
[ "Takes", "string", "input", "of", "IP", "address", "to", "issue", "RESTUL", "call", "to", "HP", "IMC" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L228-L277
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
get_dev_interface
def get_dev_interface(auth, url, devid=None, devip=None): """ Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: optional devid as the input :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 object which contains a dictionary per interface :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devid='15') >>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devip='10.101.0.221') >>> assert type(dev_interfaces) is list >>> assert 'ifAlias' in dev_interfaces[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] 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 response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: int_list = json.loads(response.text) if 'interface' in int_list: return int_list['interface'] else: return [] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_interface: An Error has occured"
python
def get_dev_interface(auth, url, devid=None, devip=None): """ Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: optional devid as the input :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 object which contains a dictionary per interface :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devid='15') >>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devip='10.101.0.221') >>> assert type(dev_interfaces) is list >>> assert 'ifAlias' in dev_interfaces[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] 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 response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: int_list = json.loads(response.text) if 'interface' in int_list: return int_list['interface'] else: return [] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_interface: An Error has occured"
[ "def", "get_dev_interface", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "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", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "int_list", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "if", "'interface'", "in", "int_list", ":", "return", "int_list", "[", "'interface'", "]", "else", ":", "return", "[", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_dev_interface: An Error has occured\"" ]
Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: optional devid as the input :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 object which contains a dictionary per interface :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devid='15') >>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devip='10.101.0.221') >>> assert type(dev_interfaces) is list >>> assert 'ifAlias' in dev_interfaces[0]
[ "Function", "takes", "devid", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC", "platform", "and", "returns", "list", "of", "device", "interfaces" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L280-L327
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
get_dev_mac_learn
def get_dev_mac_learn(auth, url, devid=None, devip=None): """ function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param devip: 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 dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devid='10') >>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] f_url = url + '/imcrs/res/access/ipMacLearn/' + str(devid) try: response = requests.get(f_url, auth=auth, headers=HEADERS) if response.status_code == 200: if len(json.loads(response.text)) < 1: mac_learn_query = [] return mac_learn_query else: mac_learn_query = (json.loads(response.text))['ipMacLearnResult'] if isinstance(mac_learn_query, dict): mac_learn_query = [mac_learn_query] return mac_learn_query except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_mac_learn: An Error has occured"
python
def get_dev_mac_learn(auth, url, devid=None, devip=None): """ function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param devip: 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 dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devid='10') >>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] f_url = url + '/imcrs/res/access/ipMacLearn/' + str(devid) try: response = requests.get(f_url, auth=auth, headers=HEADERS) if response.status_code == 200: if len(json.loads(response.text)) < 1: mac_learn_query = [] return mac_learn_query else: mac_learn_query = (json.loads(response.text))['ipMacLearnResult'] if isinstance(mac_learn_query, dict): mac_learn_query = [mac_learn_query] return mac_learn_query except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_dev_mac_learn: An Error has occured"
[ "def", "get_dev_mac_learn", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "f_url", "=", "url", "+", "'/imcrs/res/access/ipMacLearn/'", "+", "str", "(", "devid", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "if", "response", ".", "status_code", "==", "200", ":", "if", "len", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "<", "1", ":", "mac_learn_query", "=", "[", "]", "return", "mac_learn_query", "else", ":", "mac_learn_query", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "[", "'ipMacLearnResult'", "]", "if", "isinstance", "(", "mac_learn_query", ",", "dict", ")", ":", "mac_learn_query", "=", "[", "mac_learn_query", "]", "return", "mac_learn_query", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_dev_mac_learn: An Error has occured\"" ]
function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param devip: 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 dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devid='10') >>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0]
[ "function", "takes", "devid", "of", "specific", "device", "and", "issues", "a", "RESTFUL", "call", "to", "gather", "the", "current", "IP", "-", "MAC", "learning", "entries", "on", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L518-L565
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
run_dev_cmd
def run_dev_cmd(cmd_list, auth, url, devid=None, devip=None): """ Function takes devid of target device and a sequential list of strings which define the specific commands to be run on the target device and returns a str object containing the output of the commands. :param devid: int devid of the target device :param cmd_list: list of strings :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 devip: str of ipv4 address of the target device :return: str containing the response of the commands >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> cmd_list = ['display version'] >>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devid ='10') >>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devip='10.101.0.221') >>> assert type(cmd_output) is dict >>> assert 'cmdlist' in cmd_output >>> assert 'success' in cmd_output """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] run_dev_cmd_url = '/imcrs/icc/confFile/executeCmd' f_url = url + run_dev_cmd_url cmd_list = _make_cmd_list(cmd_list) payload = '''{ "deviceId" : "''' + str(devid) + '''", "cmdlist" : { "cmd" : [''' + cmd_list + '''] } }''' try: response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) if response.status_code == 200: if len(response.text) < 1: return '' else: return json.loads(response.text) except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " run_dev_cmd: An Error has occured"
python
def run_dev_cmd(cmd_list, auth, url, devid=None, devip=None): """ Function takes devid of target device and a sequential list of strings which define the specific commands to be run on the target device and returns a str object containing the output of the commands. :param devid: int devid of the target device :param cmd_list: list of strings :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 devip: str of ipv4 address of the target device :return: str containing the response of the commands >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> cmd_list = ['display version'] >>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devid ='10') >>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devip='10.101.0.221') >>> assert type(cmd_output) is dict >>> assert 'cmdlist' in cmd_output >>> assert 'success' in cmd_output """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] run_dev_cmd_url = '/imcrs/icc/confFile/executeCmd' f_url = url + run_dev_cmd_url cmd_list = _make_cmd_list(cmd_list) payload = '''{ "deviceId" : "''' + str(devid) + '''", "cmdlist" : { "cmd" : [''' + cmd_list + '''] } }''' try: response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) if response.status_code == 200: if len(response.text) < 1: return '' else: return json.loads(response.text) except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " run_dev_cmd: An Error has occured"
[ "def", "run_dev_cmd", "(", "cmd_list", ",", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "run_dev_cmd_url", "=", "'/imcrs/icc/confFile/executeCmd'", "f_url", "=", "url", "+", "run_dev_cmd_url", "cmd_list", "=", "_make_cmd_list", "(", "cmd_list", ")", "payload", "=", "'''{ \"deviceId\" : \"'''", "+", "str", "(", "devid", ")", "+", "'''\",\n \"cmdlist\" : { \"cmd\" :\n ['''", "+", "cmd_list", "+", "''']\n }\n }'''", "try", ":", "response", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "if", "response", ".", "status_code", "==", "200", ":", "if", "len", "(", "response", ".", "text", ")", "<", "1", ":", "return", "''", "else", ":", "return", "json", ".", "loads", "(", "response", ".", "text", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" run_dev_cmd: An Error has occured\"" ]
Function takes devid of target device and a sequential list of strings which define the specific commands to be run on the target device and returns a str object containing the output of the commands. :param devid: int devid of the target device :param cmd_list: list of strings :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 devip: str of ipv4 address of the target device :return: str containing the response of the commands >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> cmd_list = ['display version'] >>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devid ='10') >>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devip='10.101.0.221') >>> assert type(cmd_output) is dict >>> assert 'cmdlist' in cmd_output >>> assert 'success' in cmd_output
[ "Function", "takes", "devid", "of", "target", "device", "and", "a", "sequential", "list", "of", "strings", "which", "define", "the", "specific", "commands", "to", "be", "run", "on", "the", "target", "device", "and", "returns", "a", "str", "object", "containing", "the", "output", "of", "the", "commands", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L568-L623
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
get_all_interface_details
def get_all_interface_details(auth, url, devid=None, devip=None): """ function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for 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 :param devid: int or str value of the devId of the target device :param devip: ipv4 address of the target device :return: list of dict objects which contains the details of all interfaces on the target device :retype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devId='10') >>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(all_interface_details) is list >>> assert 'ifAlias' in all_interface_details[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_all_interface_details_url = "/imcrs/plat/res/device/" + str( devid) + "/interface/?start=0&size=1000&desc=false&total=false" f_url = url + get_all_interface_details_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_details = (json.loads(response.text)) return dev_details['interface'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_all_interface_details: An Error has occured"
python
def get_all_interface_details(auth, url, devid=None, devip=None): """ function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for 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 :param devid: int or str value of the devId of the target device :param devip: ipv4 address of the target device :return: list of dict objects which contains the details of all interfaces on the target device :retype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devId='10') >>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(all_interface_details) is list >>> assert 'ifAlias' in all_interface_details[0] """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] get_all_interface_details_url = "/imcrs/plat/res/device/" + str( devid) + "/interface/?start=0&size=1000&desc=false&total=false" f_url = url + get_all_interface_details_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_details = (json.loads(response.text)) return dev_details['interface'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_all_interface_details: An Error has occured"
[ "def", "get_all_interface_details", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "get_all_interface_details_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devid", ")", "+", "\"/interface/?start=0&size=1000&desc=false&total=false\"", "f_url", "=", "url", "+", "get_all_interface_details_url", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "dev_details", "=", "(", "json", ".", "loads", "(", "response", ".", "text", ")", ")", "return", "dev_details", "[", "'interface'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_all_interface_details: An Error has occured\"" ]
function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for 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 :param devid: int or str value of the devId of the target device :param devip: ipv4 address of the target device :return: list of dict objects which contains the details of all interfaces on the target device :retype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devId='10') >>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(all_interface_details) is list >>> assert 'ifAlias' in all_interface_details[0]
[ "function", "takes", "the", "devId", "of", "a", "specific", "device", "and", "the", "ifindex", "value", "assigned", "to", "a", "specific", "interface", "and", "issues", "a", "RESTFUL", "call", "to", "get", "the", "interface", "details", "file", "as", "known", "by", "the", "HP", "IMC", "Base", "Platform", "ICC", "module", "for", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L629-L674
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
set_interface_down
def set_interface_down(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devices :param ifindex: int or str value of the target interface :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 status code 204 with no values. :rtype:int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devip = '10.101.0.221') 204 >>> assert type(int_down_response) is int >>> assert int_down_response is 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + \ "/down" f_url = url + set_int_down_url try: response = requests.put(f_url, auth=auth, headers=HEADERS) print(response.status_code) if response.status_code == 204: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_inteface_down: An Error has occured"
python
def set_interface_down(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devices :param ifindex: int or str value of the target interface :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 status code 204 with no values. :rtype:int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devip = '10.101.0.221') 204 >>> assert type(int_down_response) is int >>> assert int_down_response is 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + \ "/down" f_url = url + set_int_down_url try: response = requests.put(f_url, auth=auth, headers=HEADERS) print(response.status_code) if response.status_code == 204: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_inteface_down: An Error has occured"
[ "def", "set_interface_down", "(", "ifindex", ",", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "set_int_down_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devid", ")", "+", "\"/interface/\"", "+", "str", "(", "ifindex", ")", "+", "\"/down\"", "f_url", "=", "url", "+", "set_int_down_url", "try", ":", "response", "=", "requests", ".", "put", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "print", "(", "response", ".", "status_code", ")", "if", "response", ".", "status_code", "==", "204", ":", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" set_inteface_down: An Error has occured\"" ]
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devices :param ifindex: int or str value of the target interface :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 status code 204 with no values. :rtype:int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devip = '10.101.0.221') 204 >>> assert type(int_down_response) is int >>> assert int_down_response is 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
[ "function", "takest", "devid", "and", "ifindex", "of", "specific", "device", "and", "interface", "and", "issues", "a", "RESTFUL", "call", "to", "shut", "the", "specified", "interface", "on", "the", "target", "device", ".", ":", "param", "devid", ":", "int", "or", "str", "value", "of", "the", "target", "device" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L726-L777
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
set_inteface_up
def set_inteface_up(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devices :param ifindex: int or str value of the target interface :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 status code 204 with no values. :rype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up( '9', auth.creds, auth.url, devid = '10') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> assert type(int_up_response) is int >>> assert int_up_response is 204 """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url try: response = requests.put(f_url, auth=auth, headers=HEADERS) if response.status_code == 204: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_inteface_up: An Error has occured"
python
def set_inteface_up(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devices :param ifindex: int or str value of the target interface :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 status code 204 with no values. :rype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up( '9', auth.creds, auth.url, devid = '10') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> assert type(int_up_response) is int >>> assert int_up_response is 204 """ if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url try: response = requests.put(f_url, auth=auth, headers=HEADERS) if response.status_code == 204: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_inteface_up: An Error has occured"
[ "def", "set_inteface_up", "(", "ifindex", ",", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "set_int_up_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devid", ")", "+", "\"/interface/\"", "+", "str", "(", "ifindex", ")", "+", "\"/up\"", "f_url", "=", "url", "+", "set_int_up_url", "try", ":", "response", "=", "requests", ".", "put", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "if", "response", ".", "status_code", "==", "204", ":", "return", "response", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" set_inteface_up: An Error has occured\"" ]
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devices :param ifindex: int or str value of the target interface :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 status code 204 with no values. :rype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up( '9', auth.creds, auth.url, devid = '10') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> assert type(int_up_response) is int >>> assert int_up_response is 204
[ "function", "takest", "devid", "and", "ifindex", "of", "specific", "device", "and", "interface", "and", "issues", "a", "RESTFUL", "call", "to", "undo", "shut", "the", "specified", "interface", "on", "the", "target", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L780-L829
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/device.py
_make_cmd_list
def _make_cmd_list(cmd_list): """ Helper function to easily create the proper json formated string from a list of strs :param cmd_list: list of strings :return: str json formatted """ cmd = '' for i in cmd_list: cmd = cmd + '"' + i + '",' cmd = cmd[:-1] return cmd
python
def _make_cmd_list(cmd_list): """ Helper function to easily create the proper json formated string from a list of strs :param cmd_list: list of strings :return: str json formatted """ cmd = '' for i in cmd_list: cmd = cmd + '"' + i + '",' cmd = cmd[:-1] return cmd
[ "def", "_make_cmd_list", "(", "cmd_list", ")", ":", "cmd", "=", "''", "for", "i", "in", "cmd_list", ":", "cmd", "=", "cmd", "+", "'\"'", "+", "i", "+", "'\",'", "cmd", "=", "cmd", "[", ":", "-", "1", "]", "return", "cmd" ]
Helper function to easily create the proper json formated string from a list of strs :param cmd_list: list of strings :return: str json formatted
[ "Helper", "function", "to", "easily", "create", "the", "proper", "json", "formated", "string", "from", "a", "list", "of", "strs", ":", "param", "cmd_list", ":", "list", "of", "strings", ":", "return", ":", "str", "json", "formatted" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L884-L894
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.create
async def create(cls, user_id: Union[int, str], is_active: bool = True, is_admin: bool = False, resource_policy: str = None, rate_limit: int = None, fields: Iterable[str] = None) -> dict: ''' Creates a new keypair with the given options. You need an admin privilege for this operation. ''' if fields is None: fields = ('access_key', 'secret_key') uid_type = 'Int!' if isinstance(user_id, int) else 'String!' q = 'mutation($user_id: {0}, $input: KeyPairInput!) {{'.format(uid_type) + \ ' create_keypair(user_id: $user_id, props: $input) {' \ ' ok msg keypair { $fields }' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'user_id': user_id, 'input': { 'is_active': is_active, 'is_admin': is_admin, 'resource_policy': resource_policy, 'rate_limit': rate_limit, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['create_keypair']
python
async def create(cls, user_id: Union[int, str], is_active: bool = True, is_admin: bool = False, resource_policy: str = None, rate_limit: int = None, fields: Iterable[str] = None) -> dict: ''' Creates a new keypair with the given options. You need an admin privilege for this operation. ''' if fields is None: fields = ('access_key', 'secret_key') uid_type = 'Int!' if isinstance(user_id, int) else 'String!' q = 'mutation($user_id: {0}, $input: KeyPairInput!) {{'.format(uid_type) + \ ' create_keypair(user_id: $user_id, props: $input) {' \ ' ok msg keypair { $fields }' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'user_id': user_id, 'input': { 'is_active': is_active, 'is_admin': is_admin, 'resource_policy': resource_policy, 'rate_limit': rate_limit, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['create_keypair']
[ "async", "def", "create", "(", "cls", ",", "user_id", ":", "Union", "[", "int", ",", "str", "]", ",", "is_active", ":", "bool", "=", "True", ",", "is_admin", ":", "bool", "=", "False", ",", "resource_policy", ":", "str", "=", "None", ",", "rate_limit", ":", "int", "=", "None", ",", "fields", ":", "Iterable", "[", "str", "]", "=", "None", ")", "->", "dict", ":", "if", "fields", "is", "None", ":", "fields", "=", "(", "'access_key'", ",", "'secret_key'", ")", "uid_type", "=", "'Int!'", "if", "isinstance", "(", "user_id", ",", "int", ")", "else", "'String!'", "q", "=", "'mutation($user_id: {0}, $input: KeyPairInput!) {{'", ".", "format", "(", "uid_type", ")", "+", "' create_keypair(user_id: $user_id, props: $input) {'", "' ok msg keypair { $fields }'", "' }'", "'}'", "q", "=", "q", ".", "replace", "(", "'$fields'", ",", "' '", ".", "join", "(", "fields", ")", ")", "variables", "=", "{", "'user_id'", ":", "user_id", ",", "'input'", ":", "{", "'is_active'", ":", "is_active", ",", "'is_admin'", ":", "is_admin", ",", "'resource_policy'", ":", "resource_policy", ",", "'rate_limit'", ":", "rate_limit", ",", "}", ",", "}", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "'variables'", ":", "variables", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'create_keypair'", "]" ]
Creates a new keypair with the given options. You need an admin privilege for this operation.
[ "Creates", "a", "new", "keypair", "with", "the", "given", "options", ".", "You", "need", "an", "admin", "privilege", "for", "this", "operation", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L24-L59
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.update
async def update(cls, access_key: str, is_active: bool = None, is_admin: bool = None, resource_policy: str = None, rate_limit: int = None) -> dict: """ Creates a new keypair with the given options. You need an admin privilege for this operation. """ q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, 'input': { 'is_active': is_active, 'is_admin': is_admin, 'resource_policy': resource_policy, 'rate_limit': rate_limit, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
python
async def update(cls, access_key: str, is_active: bool = None, is_admin: bool = None, resource_policy: str = None, rate_limit: int = None) -> dict: """ Creates a new keypair with the given options. You need an admin privilege for this operation. """ q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, 'input': { 'is_active': is_active, 'is_admin': is_admin, 'resource_policy': resource_policy, 'rate_limit': rate_limit, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
[ "async", "def", "update", "(", "cls", ",", "access_key", ":", "str", ",", "is_active", ":", "bool", "=", "None", ",", "is_admin", ":", "bool", "=", "None", ",", "resource_policy", ":", "str", "=", "None", ",", "rate_limit", ":", "int", "=", "None", ")", "->", "dict", ":", "q", "=", "'mutation($access_key: String!, $input: ModifyKeyPairInput!) {'", "+", "' modify_keypair(access_key: $access_key, props: $input) {'", "' ok msg'", "' }'", "'}'", "variables", "=", "{", "'access_key'", ":", "access_key", ",", "'input'", ":", "{", "'is_active'", ":", "is_active", ",", "'is_admin'", ":", "is_admin", ",", "'resource_policy'", ":", "resource_policy", ",", "'rate_limit'", ":", "rate_limit", ",", "}", ",", "}", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "'variables'", ":", "variables", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'modify_keypair'", "]" ]
Creates a new keypair with the given options. You need an admin privilege for this operation.
[ "Creates", "a", "new", "keypair", "with", "the", "given", "options", ".", "You", "need", "an", "admin", "privilege", "for", "this", "operation", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L63-L93
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.delete
async def delete(cls, access_key: str): """ Deletes an existing keypair with given ACCESSKEY. """ q = 'mutation($access_key: String!) {' \ ' delete_keypair(access_key: $access_key) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['delete_keypair']
python
async def delete(cls, access_key: str): """ Deletes an existing keypair with given ACCESSKEY. """ q = 'mutation($access_key: String!) {' \ ' delete_keypair(access_key: $access_key) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['delete_keypair']
[ "async", "def", "delete", "(", "cls", ",", "access_key", ":", "str", ")", ":", "q", "=", "'mutation($access_key: String!) {'", "' delete_keypair(access_key: $access_key) {'", "' ok msg'", "' }'", "'}'", "variables", "=", "{", "'access_key'", ":", "access_key", ",", "}", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "'variables'", ":", "variables", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'delete_keypair'", "]" ]
Deletes an existing keypair with given ACCESSKEY.
[ "Deletes", "an", "existing", "keypair", "with", "given", "ACCESSKEY", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L97-L116
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.list
async def list(cls, user_id: Union[int, str] = None, is_active: bool = None, fields: Iterable[str] = None) -> Sequence[dict]: ''' Lists the keypairs. You need an admin privilege for this operation. ''' if fields is None: fields = ( 'access_key', 'secret_key', 'is_active', 'is_admin', ) if user_id is None: q = 'query($is_active: Boolean) {' \ ' keypairs(is_active: $is_active) {' \ ' $fields' \ ' }' \ '}' else: uid_type = 'Int!' if isinstance(user_id, int) else 'String!' q = 'query($user_id: {0}, $is_active: Boolean) {{'.format(uid_type) + \ ' keypairs(user_id: $user_id, is_active: $is_active) {' \ ' $fields' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'is_active': is_active, } if user_id is not None: variables['user_id'] = user_id rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypairs']
python
async def list(cls, user_id: Union[int, str] = None, is_active: bool = None, fields: Iterable[str] = None) -> Sequence[dict]: ''' Lists the keypairs. You need an admin privilege for this operation. ''' if fields is None: fields = ( 'access_key', 'secret_key', 'is_active', 'is_admin', ) if user_id is None: q = 'query($is_active: Boolean) {' \ ' keypairs(is_active: $is_active) {' \ ' $fields' \ ' }' \ '}' else: uid_type = 'Int!' if isinstance(user_id, int) else 'String!' q = 'query($user_id: {0}, $is_active: Boolean) {{'.format(uid_type) + \ ' keypairs(user_id: $user_id, is_active: $is_active) {' \ ' $fields' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'is_active': is_active, } if user_id is not None: variables['user_id'] = user_id rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypairs']
[ "async", "def", "list", "(", "cls", ",", "user_id", ":", "Union", "[", "int", ",", "str", "]", "=", "None", ",", "is_active", ":", "bool", "=", "None", ",", "fields", ":", "Iterable", "[", "str", "]", "=", "None", ")", "->", "Sequence", "[", "dict", "]", ":", "if", "fields", "is", "None", ":", "fields", "=", "(", "'access_key'", ",", "'secret_key'", ",", "'is_active'", ",", "'is_admin'", ",", ")", "if", "user_id", "is", "None", ":", "q", "=", "'query($is_active: Boolean) {'", "' keypairs(is_active: $is_active) {'", "' $fields'", "' }'", "'}'", "else", ":", "uid_type", "=", "'Int!'", "if", "isinstance", "(", "user_id", ",", "int", ")", "else", "'String!'", "q", "=", "'query($user_id: {0}, $is_active: Boolean) {{'", ".", "format", "(", "uid_type", ")", "+", "' keypairs(user_id: $user_id, is_active: $is_active) {'", "' $fields'", "' }'", "'}'", "q", "=", "q", ".", "replace", "(", "'$fields'", ",", "' '", ".", "join", "(", "fields", ")", ")", "variables", "=", "{", "'is_active'", ":", "is_active", ",", "}", "if", "user_id", "is", "not", "None", ":", "variables", "[", "'user_id'", "]", "=", "user_id", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "'variables'", ":", "variables", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'keypairs'", "]" ]
Lists the keypairs. You need an admin privilege for this operation.
[ "Lists", "the", "keypairs", ".", "You", "need", "an", "admin", "privilege", "for", "this", "operation", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L120-L158
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.info
async def info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'access_key', 'secret_key', 'is_active', 'is_admin', ) q = 'query {' \ ' keypair {' \ ' $fields' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) rqst = Request(self.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypair']
python
async def info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'access_key', 'secret_key', 'is_active', 'is_admin', ) q = 'query {' \ ' keypair {' \ ' $fields' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) rqst = Request(self.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypair']
[ "async", "def", "info", "(", "self", ",", "fields", ":", "Iterable", "[", "str", "]", "=", "None", ")", "->", "dict", ":", "if", "fields", "is", "None", ":", "fields", "=", "(", "'access_key'", ",", "'secret_key'", ",", "'is_active'", ",", "'is_admin'", ",", ")", "q", "=", "'query {'", "' keypair {'", "' $fields'", "' }'", "'}'", "q", "=", "q", ".", "replace", "(", "'$fields'", ",", "' '", ".", "join", "(", "fields", ")", ")", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'keypair'", "]" ]
Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12
[ "Returns", "the", "keypair", "s", "information", "such", "as", "resource", "limits", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L161-L186
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.activate
async def activate(cls, access_key: str) -> dict: ''' Activates this keypair. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, 'input': { 'is_active': True, 'is_admin': None, 'resource_policy': None, 'rate_limit': None, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
python
async def activate(cls, access_key: str) -> dict: ''' Activates this keypair. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, 'input': { 'is_active': True, 'is_admin': None, 'resource_policy': None, 'rate_limit': None, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
[ "async", "def", "activate", "(", "cls", ",", "access_key", ":", "str", ")", "->", "dict", ":", "q", "=", "'mutation($access_key: String!, $input: ModifyKeyPairInput!) {'", "+", "' modify_keypair(access_key: $access_key, props: $input) {'", "' ok msg'", "' }'", "'}'", "variables", "=", "{", "'access_key'", ":", "access_key", ",", "'input'", ":", "{", "'is_active'", ":", "True", ",", "'is_admin'", ":", "None", ",", "'resource_policy'", ":", "None", ",", "'rate_limit'", ":", "None", ",", "}", ",", "}", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "'variables'", ":", "variables", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'modify_keypair'", "]" ]
Activates this keypair. You need an admin privilege for this operation.
[ "Activates", "this", "keypair", ".", "You", "need", "an", "admin", "privilege", "for", "this", "operation", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L190-L216
train
lablup/backend.ai-client-py
src/ai/backend/client/keypair.py
KeyPair.deactivate
async def deactivate(cls, access_key: str) -> dict: ''' Deactivates this keypair. Deactivated keypairs cannot make any API requests unless activated again by an administrator. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, 'input': { 'is_active': False, 'is_admin': None, 'resource_policy': None, 'rate_limit': None, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
python
async def deactivate(cls, access_key: str) -> dict: ''' Deactivates this keypair. Deactivated keypairs cannot make any API requests unless activated again by an administrator. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, 'input': { 'is_active': False, 'is_admin': None, 'resource_policy': None, 'rate_limit': None, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
[ "async", "def", "deactivate", "(", "cls", ",", "access_key", ":", "str", ")", "->", "dict", ":", "q", "=", "'mutation($access_key: String!, $input: ModifyKeyPairInput!) {'", "+", "' modify_keypair(access_key: $access_key, props: $input) {'", "' ok msg'", "' }'", "'}'", "variables", "=", "{", "'access_key'", ":", "access_key", ",", "'input'", ":", "{", "'is_active'", ":", "False", ",", "'is_admin'", ":", "None", ",", "'resource_policy'", ":", "None", ",", "'rate_limit'", ":", "None", ",", "}", ",", "}", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "{", "'query'", ":", "q", ",", "'variables'", ":", "variables", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "return", "data", "[", "'modify_keypair'", "]" ]
Deactivates this keypair. Deactivated keypairs cannot make any API requests unless activated again by an administrator. You need an admin privilege for this operation.
[ "Deactivates", "this", "keypair", ".", "Deactivated", "keypairs", "cannot", "make", "any", "API", "requests", "unless", "activated", "again", "by", "an", "administrator", ".", "You", "need", "an", "admin", "privilege", "for", "this", "operation", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/keypair.py#L220-L248
train
HPENetworking/PYHPEIMC
build/lib/pyhpimc/plat/termaccess.py
add_ip_scope
def add_ip_scope(auth, url,startIp, endIp, name, description): """ Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access in the HPE IMC base platform :param startIp: str Start of IP address scope ex. '10.101.0.1' :param endIp: str End of IP address scope ex. '10.101.0.254' :param name: str Name of the owner of this IP scope ex. 'admin' :param description: str description of the Ip scope :return: """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() add_ip_scope_url = "/imcrs/res/access/assignedIpScope" f_url = url + add_ip_scope_url payload = ('''{ "startIp": "%s", "endIp": "%s","name": "%s","description": "%s" }''' %(str(startIp), str(endIp), str(name), str(description))) r = requests.post(f_url, auth=auth, headers=HEADERS, data=payload) # creates the URL using the payload variable as the contents try: if r.status_code == 200: print("IP Scope Successfully Created") return r.status_code elif r.status_code == 409: print ("IP Scope Already Exists") return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " add_ip_scope: An Error has occured" #Add host to IP scope #http://10.101.0.203:8080/imcrs/res/access/assignedIpScope/ip?ipScopeId=1 '''{ "ip": "10.101.0.1", "name": "Cisco2811.lab.local", "description": "Cisco 2811", "parentId": "1" }'''
python
def add_ip_scope(auth, url,startIp, endIp, name, description): """ Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access in the HPE IMC base platform :param startIp: str Start of IP address scope ex. '10.101.0.1' :param endIp: str End of IP address scope ex. '10.101.0.254' :param name: str Name of the owner of this IP scope ex. 'admin' :param description: str description of the Ip scope :return: """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() add_ip_scope_url = "/imcrs/res/access/assignedIpScope" f_url = url + add_ip_scope_url payload = ('''{ "startIp": "%s", "endIp": "%s","name": "%s","description": "%s" }''' %(str(startIp), str(endIp), str(name), str(description))) r = requests.post(f_url, auth=auth, headers=HEADERS, data=payload) # creates the URL using the payload variable as the contents try: if r.status_code == 200: print("IP Scope Successfully Created") return r.status_code elif r.status_code == 409: print ("IP Scope Already Exists") return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " add_ip_scope: An Error has occured" #Add host to IP scope #http://10.101.0.203:8080/imcrs/res/access/assignedIpScope/ip?ipScopeId=1 '''{ "ip": "10.101.0.1", "name": "Cisco2811.lab.local", "description": "Cisco 2811", "parentId": "1" }'''
[ "def", "add_ip_scope", "(", "auth", ",", "url", ",", "startIp", ",", "endIp", ",", "name", ",", "description", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "add_ip_scope_url", "=", "\"/imcrs/res/access/assignedIpScope\"", "f_url", "=", "url", "+", "add_ip_scope_url", "payload", "=", "(", "'''{ \"startIp\": \"%s\", \"endIp\": \"%s\",\"name\": \"%s\",\"description\": \"%s\" }'''", "%", "(", "str", "(", "startIp", ")", ",", "str", "(", "endIp", ")", ",", "str", "(", "name", ")", ",", "str", "(", "description", ")", ")", ")", "r", "=", "requests", ".", "post", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ",", "data", "=", "payload", ")", "# creates the URL using the payload variable as the contents", "try", ":", "if", "r", ".", "status_code", "==", "200", ":", "print", "(", "\"IP Scope Successfully Created\"", ")", "return", "r", ".", "status_code", "elif", "r", ".", "status_code", "==", "409", ":", "print", "(", "\"IP Scope Already Exists\"", ")", "return", "r", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "\" add_ip_scope: An Error has occured\"", "#Add host to IP scope", "#http://10.101.0.203:8080/imcrs/res/access/assignedIpScope/ip?ipScopeId=1", "'''{\n \"ip\": \"10.101.0.1\",\n \"name\": \"Cisco2811.lab.local\",\n \"description\": \"Cisco 2811\",\n \"parentId\": \"1\"\n }'''" ]
Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access in the HPE IMC base platform :param startIp: str Start of IP address scope ex. '10.101.0.1' :param endIp: str End of IP address scope ex. '10.101.0.254' :param name: str Name of the owner of this IP scope ex. 'admin' :param description: str description of the Ip scope :return:
[ "Function", "takes", "input", "of", "four", "strings", "Start", "Ip", "endIp", "name", "and", "description", "to", "add", "new", "Ip", "Scope", "to", "terminal", "access", "in", "the", "HPE", "IMC", "base", "platform", ":", "param", "startIp", ":", "str", "Start", "of", "IP", "address", "scope", "ex", ".", "10", ".", "101", ".", "0", ".", "1", ":", "param", "endIp", ":", "str", "End", "of", "IP", "address", "scope", "ex", ".", "10", ".", "101", ".", "0", ".", "254", ":", "param", "name", ":", "str", "Name", "of", "the", "owner", "of", "this", "IP", "scope", "ex", ".", "admin", ":", "param", "description", ":", "str", "description", "of", "the", "Ip", "scope", ":", "return", ":" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpimc/plat/termaccess.py#L106-L142
train
lablup/backend.ai-client-py
src/ai/backend/client/resource.py
Resource.check_presets
async def check_presets(cls): ''' Lists all resource presets in the current scaling group with additiona information. ''' rqst = Request(cls.session, 'POST', '/resource/check-presets') async with rqst.fetch() as resp: return await resp.json()
python
async def check_presets(cls): ''' Lists all resource presets in the current scaling group with additiona information. ''' rqst = Request(cls.session, 'POST', '/resource/check-presets') async with rqst.fetch() as resp: return await resp.json()
[ "async", "def", "check_presets", "(", "cls", ")", ":", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/resource/check-presets'", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "await", "resp", ".", "json", "(", ")" ]
Lists all resource presets in the current scaling group with additiona information.
[ "Lists", "all", "resource", "presets", "in", "the", "current", "scaling", "group", "with", "additiona", "information", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/resource.py#L31-L38
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/perf.py
add_perf_task
def add_perf_task(task, auth, url): """ function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :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: 204 :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3','indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValue:1:0]','itemFunction': '1.3.6.1.4.1.9.9.13.1.3.1.3','itemName': 'Cisco_Temperature','selectDefaultUnit': '400','unit': 'Celsius'} >>> new_perf_task = add_perf_task(new_task, auth.creds, auth.url) """ add_perf_task_url = "/imcrs/perf/task" f_url = url + add_perf_task_url payload = json.dumps(task) # creates the URL using the payload variable as the contents r = requests.post(f_url, data = payload, auth=auth, headers=headers) try: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
python
def add_perf_task(task, auth, url): """ function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :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: 204 :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3','indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValue:1:0]','itemFunction': '1.3.6.1.4.1.9.9.13.1.3.1.3','itemName': 'Cisco_Temperature','selectDefaultUnit': '400','unit': 'Celsius'} >>> new_perf_task = add_perf_task(new_task, auth.creds, auth.url) """ add_perf_task_url = "/imcrs/perf/task" f_url = url + add_perf_task_url payload = json.dumps(task) # creates the URL using the payload variable as the contents r = requests.post(f_url, data = payload, auth=auth, headers=headers) try: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
[ "def", "add_perf_task", "(", "task", ",", "auth", ",", "url", ")", ":", "add_perf_task_url", "=", "\"/imcrs/perf/task\"", "f_url", "=", "url", "+", "add_perf_task_url", "payload", "=", "json", ".", "dumps", "(", "task", ")", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "post", "(", "f_url", ",", "data", "=", "payload", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "try", ":", "return", "r", ".", "status_code", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' get_dev_alarms: An Error has occured'" ]
function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :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: 204 :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3','indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValue:1:0]','itemFunction': '1.3.6.1.4.1.9.9.13.1.3.1.3','itemName': 'Cisco_Temperature','selectDefaultUnit': '400','unit': 'Celsius'} >>> new_perf_task = add_perf_task(new_task, auth.creds, auth.url)
[ "function", "takes", "the", "a", "python", "dict", "containing", "all", "necessary", "fields", "for", "a", "performance", "tasks", "transforms", "the", "dict", "into", "JSON", "and", "issues", "a", "RESTFUL", "call", "to", "create", "the", "performance", "task", ".", "device", "." ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/perf.py#L19-L54
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/perf.py
get_perf_task
def get_perf_task(task_name, auth, url): """ function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call to the IMC REST service. It will return a list :param task_name: str containing the name of the performance task :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: 204 :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url) >>> assert type(selected_task) is dict >>> assert 'taskName' in selected_task """ get_perf_task_url = "/imcrs/perf/task?name="+task_name+"&orderBy=taskId&desc=false" f_url = url + get_perf_task_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) try: if r.status_code == 200: perf_task_info = (json.loads(r.text))['task'] return perf_task_info except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
python
def get_perf_task(task_name, auth, url): """ function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call to the IMC REST service. It will return a list :param task_name: str containing the name of the performance task :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: 204 :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url) >>> assert type(selected_task) is dict >>> assert 'taskName' in selected_task """ get_perf_task_url = "/imcrs/perf/task?name="+task_name+"&orderBy=taskId&desc=false" f_url = url + get_perf_task_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) try: if r.status_code == 200: perf_task_info = (json.loads(r.text))['task'] return perf_task_info except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
[ "def", "get_perf_task", "(", "task_name", ",", "auth", ",", "url", ")", ":", "get_perf_task_url", "=", "\"/imcrs/perf/task?name=\"", "+", "task_name", "+", "\"&orderBy=taskId&desc=false\"", "f_url", "=", "url", "+", "get_perf_task_url", "# creates the URL using the payload variable as the contents", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ")", "try", ":", "if", "r", ".", "status_code", "==", "200", ":", "perf_task_info", "=", "(", "json", ".", "loads", "(", "r", ".", "text", ")", ")", "[", "'task'", "]", "return", "perf_task_info", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "' get_dev_alarms: An Error has occured'" ]
function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call to the IMC REST service. It will return a list :param task_name: str containing the name of the performance task :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: 204 :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url) >>> assert type(selected_task) is dict >>> assert 'taskName' in selected_task
[ "function", "takes", "the", "a", "str", "object", "containing", "the", "name", "of", "an", "existing", "performance", "tasks", "and", "issues", "a", "RESTFUL", "call", "to", "the", "IMC", "REST", "service", ".", "It", "will", "return", "a", "list" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/perf.py#L56-L92
train
HPENetworking/PYHPEIMC
build/lib/pyhpeimc/plat/vrm.py
get_vm_host_info
def get_vm_host_info(hostip, auth, url): """ function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :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: Dictionary contraining the information for the target VM host :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vrm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url) >>> assert type(host_info) is dict >>> assert len(host_info) == 10 >>> assert 'cpuFeg' in host_info >>> assert 'cpuNum' in host_info >>> assert 'devId' in host_info >>> assert 'devIp' in host_info >>> assert 'diskSize' in host_info >>> assert 'memory' in host_info >>> assert 'parentDevId' in host_info >>> assert 'porductFlag' in host_info >>> assert 'serverName' in host_info >>> assert 'vendor' in host_info """ hostId = get_dev_details(hostip, auth, url)['id'] 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) try: 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" except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_vm_host_info: An Error has occured"
python
def get_vm_host_info(hostip, auth, url): """ function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :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: Dictionary contraining the information for the target VM host :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vrm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url) >>> assert type(host_info) is dict >>> assert len(host_info) == 10 >>> assert 'cpuFeg' in host_info >>> assert 'cpuNum' in host_info >>> assert 'devId' in host_info >>> assert 'devIp' in host_info >>> assert 'diskSize' in host_info >>> assert 'memory' in host_info >>> assert 'parentDevId' in host_info >>> assert 'porductFlag' in host_info >>> assert 'serverName' in host_info >>> assert 'vendor' in host_info """ hostId = get_dev_details(hostip, auth, url)['id'] 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) try: 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" except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_vm_host_info: An Error has occured"
[ "def", "get_vm_host_info", "(", "hostip", ",", "auth", ",", "url", ")", ":", "hostId", "=", "get_dev_details", "(", "hostip", ",", "auth", ",", "url", ")", "[", "'id'", "]", "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)", "try", ":", "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\"", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "\" get_vm_host_info: An Error has occured\"" ]
function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :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: Dictionary contraining the information for the target VM host :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vrm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url) >>> assert type(host_info) is dict >>> assert len(host_info) == 10 >>> assert 'cpuFeg' in host_info >>> assert 'cpuNum' in host_info >>> assert 'devId' in host_info >>> assert 'devIp' in host_info >>> assert 'diskSize' in host_info >>> assert 'memory' in host_info >>> assert 'parentDevId' in host_info >>> assert 'porductFlag' in host_info >>> assert 'serverName' in host_info >>> assert 'vendor' in host_info
[ "function", "takes", "hostId", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/plat/vrm.py#L18-L80
train
HPENetworking/PYHPEIMC
pyhpeimc/wsm/acinfo.py
get_ac_info_all
def get_ac_info_all(auth, url): """ function takes no input as input to RESTFUL 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 :return: list of dictionaries where each element of the list represents a single wireless controller which has been discovered in the HPE IMC WSM module :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.wsm.acinfo import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ac_info_all = get_ac_info_all(auth.creds, auth.url) """ f_url = url + "/imcrs/wlan/acInfo/queryAcBasicInfo" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: if len(response.text) > 0: acs = json.loads(response.text)['acBasicInfo'] if type(acs) is dict: acs = [acs] return acs except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_ac_info_all: An Error has occured"
python
def get_ac_info_all(auth, url): """ function takes no input as input to RESTFUL 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 :return: list of dictionaries where each element of the list represents a single wireless controller which has been discovered in the HPE IMC WSM module :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.wsm.acinfo import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ac_info_all = get_ac_info_all(auth.creds, auth.url) """ f_url = url + "/imcrs/wlan/acInfo/queryAcBasicInfo" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: if len(response.text) > 0: acs = json.loads(response.text)['acBasicInfo'] if type(acs) is dict: acs = [acs] return acs except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_ac_info_all: An Error has occured"
[ "def", "get_ac_info_all", "(", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/wlan/acInfo/queryAcBasicInfo\"", "response", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "HEADERS", ")", "try", ":", "if", "response", ".", "status_code", "==", "200", ":", "if", "len", "(", "response", ".", "text", ")", ">", "0", ":", "acs", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "[", "'acBasicInfo'", "]", "if", "type", "(", "acs", ")", "is", "dict", ":", "acs", "=", "[", "acs", "]", "return", "acs", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "error", ":", "return", "\"Error:\\n\"", "+", "str", "(", "error", ")", "+", "\" get_ac_info_all: An Error has occured\"" ]
function takes no input as input to RESTFUL 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 :return: list of dictionaries where each element of the list represents a single wireless controller which has been discovered in the HPE IMC WSM module :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.wsm.acinfo import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ac_info_all = get_ac_info_all(auth.creds, auth.url)
[ "function", "takes", "no", "input", "as", "input", "to", "RESTFUL", "call", "to", "HP", "IMC" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/wsm/acinfo.py#L18-L50
train
HPENetworking/PYHPEIMC
build/lib/pyhpimc/auth.py
set_imc_creds
def set_imc_creds(h_url=None, imc_server=None, imc_port=None, imc_user=None,imc_pw=None): """ This function prompts user for IMC server information and credentuials and stores values in url and auth global variables""" global auth, url if h_url is None: imc_protocol = input( "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:") if imc_protocol == "1": h_url = 'http://' else: h_url = 'https://' imc_server = input("What is the ip address of the IMC server?") imc_port = input("What is the port number of the IMC server?") imc_user = input("What is the username of the IMC eAPI user?") imc_pw = input('''What is the password of the IMC eAPI user?''') url = h_url + imc_server + ":" + imc_port auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw) test_url = '/imcrs' f_url = url + test_url try: r = requests.get(f_url, auth=auth, headers=headers, verify=False) print (r.status_code) return auth # checks for reqeusts exceptions except requests.exceptions.RequestException as e: print("Error:\n" + str(e)) print("\n\nThe IMC server address is invalid. Please try again\n\n") set_imc_creds() if r.status_code != 200: # checks for valid IMC credentials print("Error: \n You're credentials are invalid. Please try again\n\n") set_imc_creds() else: print("You've successfully access the IMC eAPI")
python
def set_imc_creds(h_url=None, imc_server=None, imc_port=None, imc_user=None,imc_pw=None): """ This function prompts user for IMC server information and credentuials and stores values in url and auth global variables""" global auth, url if h_url is None: imc_protocol = input( "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:") if imc_protocol == "1": h_url = 'http://' else: h_url = 'https://' imc_server = input("What is the ip address of the IMC server?") imc_port = input("What is the port number of the IMC server?") imc_user = input("What is the username of the IMC eAPI user?") imc_pw = input('''What is the password of the IMC eAPI user?''') url = h_url + imc_server + ":" + imc_port auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw) test_url = '/imcrs' f_url = url + test_url try: r = requests.get(f_url, auth=auth, headers=headers, verify=False) print (r.status_code) return auth # checks for reqeusts exceptions except requests.exceptions.RequestException as e: print("Error:\n" + str(e)) print("\n\nThe IMC server address is invalid. Please try again\n\n") set_imc_creds() if r.status_code != 200: # checks for valid IMC credentials print("Error: \n You're credentials are invalid. Please try again\n\n") set_imc_creds() else: print("You've successfully access the IMC eAPI")
[ "def", "set_imc_creds", "(", "h_url", "=", "None", ",", "imc_server", "=", "None", ",", "imc_port", "=", "None", ",", "imc_user", "=", "None", ",", "imc_pw", "=", "None", ")", ":", "global", "auth", ",", "url", "if", "h_url", "is", "None", ":", "imc_protocol", "=", "input", "(", "\"What protocol would you like to use to connect to the IMC server: \\n Press 1 for HTTP: \\n Press 2 for HTTPS:\"", ")", "if", "imc_protocol", "==", "\"1\"", ":", "h_url", "=", "'http://'", "else", ":", "h_url", "=", "'https://'", "imc_server", "=", "input", "(", "\"What is the ip address of the IMC server?\"", ")", "imc_port", "=", "input", "(", "\"What is the port number of the IMC server?\"", ")", "imc_user", "=", "input", "(", "\"What is the username of the IMC eAPI user?\"", ")", "imc_pw", "=", "input", "(", "'''What is the password of the IMC eAPI user?'''", ")", "url", "=", "h_url", "+", "imc_server", "+", "\":\"", "+", "imc_port", "auth", "=", "requests", ".", "auth", ".", "HTTPDigestAuth", "(", "imc_user", ",", "imc_pw", ")", "test_url", "=", "'/imcrs'", "f_url", "=", "url", "+", "test_url", "try", ":", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ",", "verify", "=", "False", ")", "print", "(", "r", ".", "status_code", ")", "return", "auth", "# checks for reqeusts exceptions", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "print", "(", "\"Error:\\n\"", "+", "str", "(", "e", ")", ")", "print", "(", "\"\\n\\nThe IMC server address is invalid. Please try again\\n\\n\"", ")", "set_imc_creds", "(", ")", "if", "r", ".", "status_code", "!=", "200", ":", "# checks for valid IMC credentials", "print", "(", "\"Error: \\n You're credentials are invalid. Please try again\\n\\n\"", ")", "set_imc_creds", "(", ")", "else", ":", "print", "(", "\"You've successfully access the IMC eAPI\"", ")" ]
This function prompts user for IMC server information and credentuials and stores values in url and auth global variables
[ "This", "function", "prompts", "user", "for", "IMC", "server", "information", "and", "credentuials", "and", "stores", "values", "in", "url", "and", "auth", "global", "variables" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpimc/auth.py#L78-L110
train
HPENetworking/PYHPEIMC
build/lib/pyhpimc/auth.py
print_to_file
def print_to_file(object): """ Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt :param: Object: object of type str, list, or dict :return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt """ with open ('pyoutput.txt', 'w') as fh: x = None if type(object) is list: x = json.dumps(object, indent = 4) if type(object) is dict: x = json.dumps(object, indent = 4) if type (object) is str: x = object fh.write(x)
python
def print_to_file(object): """ Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt :param: Object: object of type str, list, or dict :return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt """ with open ('pyoutput.txt', 'w') as fh: x = None if type(object) is list: x = json.dumps(object, indent = 4) if type(object) is dict: x = json.dumps(object, indent = 4) if type (object) is str: x = object fh.write(x)
[ "def", "print_to_file", "(", "object", ")", ":", "with", "open", "(", "'pyoutput.txt'", ",", "'w'", ")", "as", "fh", ":", "x", "=", "None", "if", "type", "(", "object", ")", "is", "list", ":", "x", "=", "json", ".", "dumps", "(", "object", ",", "indent", "=", "4", ")", "if", "type", "(", "object", ")", "is", "dict", ":", "x", "=", "json", ".", "dumps", "(", "object", ",", "indent", "=", "4", ")", "if", "type", "(", "object", ")", "is", "str", ":", "x", "=", "object", "fh", ".", "write", "(", "x", ")" ]
Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt :param: Object: object of type str, list, or dict :return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt
[ "Function", "takes", "in", "object", "of", "type", "str", "list", "or", "dict", "and", "prints", "out", "to", "current", "working", "directory", "as", "pyoutput", ".", "txt", ":", "param", ":", "Object", ":", "object", "of", "type", "str", "list", "or", "dict", ":", "return", ":", "No", "return", ".", "Just", "prints", "out", "to", "file", "handler", "and", "save", "to", "current", "working", "directory", "as", "pyoutput", ".", "txt" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpimc/auth.py#L119-L133
train
HPENetworking/PYHPEIMC
build/lib/pyhpimc/auth.py
IMCAuth.get_auth
def get_auth(self): """ This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return: """ url = self.h_url + self.server + ":" + self.port auth = requests.auth.HTTPDigestAuth(self.username,self.password) auth_url = "/imcrs" f_url = url + auth_url try: r = requests.get(f_url, auth=auth, headers=headers, verify=False) return r.status_code # checks for reqeusts exceptions except requests.exceptions.RequestException as e: return ("Error:\n" + str(e) + '\n\nThe IMC server address is invalid. Please try again') set_imc_creds() if r.status_code != 200: # checks for valid IMC credentials return ("Error:\n" + str(e) +"Error: \n You're credentials are invalid. Please try again\n\n") set_imc_creds()
python
def get_auth(self): """ This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return: """ url = self.h_url + self.server + ":" + self.port auth = requests.auth.HTTPDigestAuth(self.username,self.password) auth_url = "/imcrs" f_url = url + auth_url try: r = requests.get(f_url, auth=auth, headers=headers, verify=False) return r.status_code # checks for reqeusts exceptions except requests.exceptions.RequestException as e: return ("Error:\n" + str(e) + '\n\nThe IMC server address is invalid. Please try again') set_imc_creds() if r.status_code != 200: # checks for valid IMC credentials return ("Error:\n" + str(e) +"Error: \n You're credentials are invalid. Please try again\n\n") set_imc_creds()
[ "def", "get_auth", "(", "self", ")", ":", "url", "=", "self", ".", "h_url", "+", "self", ".", "server", "+", "\":\"", "+", "self", ".", "port", "auth", "=", "requests", ".", "auth", ".", "HTTPDigestAuth", "(", "self", ".", "username", ",", "self", ".", "password", ")", "auth_url", "=", "\"/imcrs\"", "f_url", "=", "url", "+", "auth_url", "try", ":", "r", "=", "requests", ".", "get", "(", "f_url", ",", "auth", "=", "auth", ",", "headers", "=", "headers", ",", "verify", "=", "False", ")", "return", "r", ".", "status_code", "# checks for reqeusts exceptions", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "return", "(", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "'\\n\\nThe IMC server address is invalid. Please try again'", ")", "set_imc_creds", "(", ")", "if", "r", ".", "status_code", "!=", "200", ":", "# checks for valid IMC credentials", "return", "(", "\"Error:\\n\"", "+", "str", "(", "e", ")", "+", "\"Error: \\n You're credentials are invalid. Please try again\\n\\n\"", ")", "set_imc_creds", "(", ")" ]
This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return:
[ "This", "method", "requests", "an", "authentication", "object", "from", "the", "HPE", "IMC", "NMS", "and", "returns", "an", "HTTPDigest", "Auth", "Object", ":", "return", ":" ]
4fba31827573587e03a6233c7db60f188038c8e5
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpimc/auth.py#L55-L73
train
mozilla-services/python-dockerflow
src/dockerflow/version.py
get_version
def get_version(root): """ Load and return the contents of version.json. :param root: The root path that the ``version.json`` file will be opened :type root: str :returns: Content of ``version.json`` or None :rtype: dict or None """ version_json = os.path.join(root, 'version.json') if os.path.exists(version_json): with open(version_json, 'r') as version_json_file: return json.load(version_json_file) return None
python
def get_version(root): """ Load and return the contents of version.json. :param root: The root path that the ``version.json`` file will be opened :type root: str :returns: Content of ``version.json`` or None :rtype: dict or None """ version_json = os.path.join(root, 'version.json') if os.path.exists(version_json): with open(version_json, 'r') as version_json_file: return json.load(version_json_file) return None
[ "def", "get_version", "(", "root", ")", ":", "version_json", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'version.json'", ")", "if", "os", ".", "path", ".", "exists", "(", "version_json", ")", ":", "with", "open", "(", "version_json", ",", "'r'", ")", "as", "version_json_file", ":", "return", "json", ".", "load", "(", "version_json_file", ")", "return", "None" ]
Load and return the contents of version.json. :param root: The root path that the ``version.json`` file will be opened :type root: str :returns: Content of ``version.json`` or None :rtype: dict or None
[ "Load", "and", "return", "the", "contents", "of", "version", ".", "json", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/version.py#L10-L23
train
housecanary/hc-api-python
housecanary/apiclient.py
ApiClient.fetch
def fetch(self, endpoint_name, identifier_input, query_params=None): """Calls this instance's request_client's post method with the specified component endpoint Args: - endpoint_name (str) - The endpoint to call like "property/value". - identifier_input - One or more identifiers to request data for. An identifier can be in one of these forms: - A list of property identifier dicts: - A property identifier dict can contain the following keys: (address, zipcode, unit, city, state, slug, meta). One of 'address' or 'slug' is required. Ex: [{"address": "82 County Line Rd", "zipcode": "72173", "meta": "some ID"}] A slug is a URL-safe string that identifies a property. These are obtained from HouseCanary. Ex: [{"slug": "123-Example-St-San-Francisco-CA-94105"}] - A list of dicts representing a block: - A block identifier dict can contain the following keys: (block_id, num_bins, property_type, meta). 'block_id' is required. Ex: [{"block_id": "060750615003005", "meta": "some ID"}] - A list of dicts representing a zipcode: Ex: [{"zipcode": "90274", "meta": "some ID"}] - A list of dicts representing an MSA: Ex: [{"msa": "41860", "meta": "some ID"}] The "meta" field is always optional. Returns: A Response object, or the output of a custom OutputGenerator if one was specified in the constructor. """ endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} if len(identifier_input) == 1: # If only one identifier specified, use a GET request query_params.update(identifier_input[0]) return self._request_client.get(endpoint_url, query_params) # when more than one address, use a POST request return self._request_client.post(endpoint_url, identifier_input, query_params)
python
def fetch(self, endpoint_name, identifier_input, query_params=None): """Calls this instance's request_client's post method with the specified component endpoint Args: - endpoint_name (str) - The endpoint to call like "property/value". - identifier_input - One or more identifiers to request data for. An identifier can be in one of these forms: - A list of property identifier dicts: - A property identifier dict can contain the following keys: (address, zipcode, unit, city, state, slug, meta). One of 'address' or 'slug' is required. Ex: [{"address": "82 County Line Rd", "zipcode": "72173", "meta": "some ID"}] A slug is a URL-safe string that identifies a property. These are obtained from HouseCanary. Ex: [{"slug": "123-Example-St-San-Francisco-CA-94105"}] - A list of dicts representing a block: - A block identifier dict can contain the following keys: (block_id, num_bins, property_type, meta). 'block_id' is required. Ex: [{"block_id": "060750615003005", "meta": "some ID"}] - A list of dicts representing a zipcode: Ex: [{"zipcode": "90274", "meta": "some ID"}] - A list of dicts representing an MSA: Ex: [{"msa": "41860", "meta": "some ID"}] The "meta" field is always optional. Returns: A Response object, or the output of a custom OutputGenerator if one was specified in the constructor. """ endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} if len(identifier_input) == 1: # If only one identifier specified, use a GET request query_params.update(identifier_input[0]) return self._request_client.get(endpoint_url, query_params) # when more than one address, use a POST request return self._request_client.post(endpoint_url, identifier_input, query_params)
[ "def", "fetch", "(", "self", ",", "endpoint_name", ",", "identifier_input", ",", "query_params", "=", "None", ")", ":", "endpoint_url", "=", "constants", ".", "URL_PREFIX", "+", "\"/\"", "+", "self", ".", "_version", "+", "\"/\"", "+", "endpoint_name", "if", "query_params", "is", "None", ":", "query_params", "=", "{", "}", "if", "len", "(", "identifier_input", ")", "==", "1", ":", "# If only one identifier specified, use a GET request", "query_params", ".", "update", "(", "identifier_input", "[", "0", "]", ")", "return", "self", ".", "_request_client", ".", "get", "(", "endpoint_url", ",", "query_params", ")", "# when more than one address, use a POST request", "return", "self", ".", "_request_client", ".", "post", "(", "endpoint_url", ",", "identifier_input", ",", "query_params", ")" ]
Calls this instance's request_client's post method with the specified component endpoint Args: - endpoint_name (str) - The endpoint to call like "property/value". - identifier_input - One or more identifiers to request data for. An identifier can be in one of these forms: - A list of property identifier dicts: - A property identifier dict can contain the following keys: (address, zipcode, unit, city, state, slug, meta). One of 'address' or 'slug' is required. Ex: [{"address": "82 County Line Rd", "zipcode": "72173", "meta": "some ID"}] A slug is a URL-safe string that identifies a property. These are obtained from HouseCanary. Ex: [{"slug": "123-Example-St-San-Francisco-CA-94105"}] - A list of dicts representing a block: - A block identifier dict can contain the following keys: (block_id, num_bins, property_type, meta). 'block_id' is required. Ex: [{"block_id": "060750615003005", "meta": "some ID"}] - A list of dicts representing a zipcode: Ex: [{"zipcode": "90274", "meta": "some ID"}] - A list of dicts representing an MSA: Ex: [{"msa": "41860", "meta": "some ID"}] The "meta" field is always optional. Returns: A Response object, or the output of a custom OutputGenerator if one was specified in the constructor.
[ "Calls", "this", "instance", "s", "request_client", "s", "post", "method", "with", "the", "specified", "component", "endpoint" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L61-L117
train
housecanary/hc-api-python
housecanary/apiclient.py
ApiClient.fetch_synchronous
def fetch_synchronous(self, endpoint_name, query_params=None): """Calls this instance's request_client's get method with the specified component endpoint""" endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} return self._request_client.get(endpoint_url, query_params)
python
def fetch_synchronous(self, endpoint_name, query_params=None): """Calls this instance's request_client's get method with the specified component endpoint""" endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} return self._request_client.get(endpoint_url, query_params)
[ "def", "fetch_synchronous", "(", "self", ",", "endpoint_name", ",", "query_params", "=", "None", ")", ":", "endpoint_url", "=", "constants", ".", "URL_PREFIX", "+", "\"/\"", "+", "self", ".", "_version", "+", "\"/\"", "+", "endpoint_name", "if", "query_params", "is", "None", ":", "query_params", "=", "{", "}", "return", "self", ".", "_request_client", ".", "get", "(", "endpoint_url", ",", "query_params", ")" ]
Calls this instance's request_client's get method with the specified component endpoint
[ "Calls", "this", "instance", "s", "request_client", "s", "get", "method", "with", "the", "specified", "component", "endpoint" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L119-L128
train
housecanary/hc-api-python
housecanary/apiclient.py
ComponentWrapper.get_identifier_input
def get_identifier_input(self, identifier_data): """Convert the various formats of input identifier_data into the proper json format expected by the ApiClient fetch method, which is a list of dicts.""" identifier_input = [] if isinstance(identifier_data, list) and len(identifier_data) > 0: # if list, convert each item in the list to json for address in identifier_data: identifier_input.append(self._convert_to_identifier_json(address)) else: identifier_input.append(self._convert_to_identifier_json(identifier_data)) return identifier_input
python
def get_identifier_input(self, identifier_data): """Convert the various formats of input identifier_data into the proper json format expected by the ApiClient fetch method, which is a list of dicts.""" identifier_input = [] if isinstance(identifier_data, list) and len(identifier_data) > 0: # if list, convert each item in the list to json for address in identifier_data: identifier_input.append(self._convert_to_identifier_json(address)) else: identifier_input.append(self._convert_to_identifier_json(identifier_data)) return identifier_input
[ "def", "get_identifier_input", "(", "self", ",", "identifier_data", ")", ":", "identifier_input", "=", "[", "]", "if", "isinstance", "(", "identifier_data", ",", "list", ")", "and", "len", "(", "identifier_data", ")", ">", "0", ":", "# if list, convert each item in the list to json", "for", "address", "in", "identifier_data", ":", "identifier_input", ".", "append", "(", "self", ".", "_convert_to_identifier_json", "(", "address", ")", ")", "else", ":", "identifier_input", ".", "append", "(", "self", ".", "_convert_to_identifier_json", "(", "identifier_data", ")", ")", "return", "identifier_input" ]
Convert the various formats of input identifier_data into the proper json format expected by the ApiClient fetch method, which is a list of dicts.
[ "Convert", "the", "various", "formats", "of", "input", "identifier_data", "into", "the", "proper", "json", "format", "expected", "by", "the", "ApiClient", "fetch", "method", "which", "is", "a", "list", "of", "dicts", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L143-L157
train
housecanary/hc-api-python
housecanary/apiclient.py
ComponentWrapper.fetch_identifier_component
def fetch_identifier_component(self, endpoint_name, identifier_data, query_params=None): """Common method for handling parameters before passing to api_client""" if query_params is None: query_params = {} identifier_input = self.get_identifier_input(identifier_data) return self._api_client.fetch(endpoint_name, identifier_input, query_params)
python
def fetch_identifier_component(self, endpoint_name, identifier_data, query_params=None): """Common method for handling parameters before passing to api_client""" if query_params is None: query_params = {} identifier_input = self.get_identifier_input(identifier_data) return self._api_client.fetch(endpoint_name, identifier_input, query_params)
[ "def", "fetch_identifier_component", "(", "self", ",", "endpoint_name", ",", "identifier_data", ",", "query_params", "=", "None", ")", ":", "if", "query_params", "is", "None", ":", "query_params", "=", "{", "}", "identifier_input", "=", "self", ".", "get_identifier_input", "(", "identifier_data", ")", "return", "self", ".", "_api_client", ".", "fetch", "(", "endpoint_name", ",", "identifier_input", ",", "query_params", ")" ]
Common method for handling parameters before passing to api_client
[ "Common", "method", "for", "handling", "parameters", "before", "passing", "to", "api_client" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L159-L167
train
housecanary/hc-api-python
housecanary/apiclient.py
PropertyComponentWrapper._convert_to_identifier_json
def _convert_to_identifier_json(self, address_data): """Convert input address data into json format""" if isinstance(address_data, str): # allow just passing a slug string. return {"slug": address_data} if isinstance(address_data, tuple) and len(address_data) > 0: address_json = {"address": address_data[0]} if len(address_data) > 1: address_json["zipcode"] = address_data[1] if len(address_data) > 2: address_json["meta"] = address_data[2] return address_json if isinstance(address_data, dict): allowed_keys = ["address", "zipcode", "unit", "city", "state", "slug", "meta", "client_value", "client_value_sqft"] # ensure the dict does not contain any unallowed keys for key in address_data: if key not in allowed_keys: msg = "Key in address input not allowed: " + key raise housecanary.exceptions.InvalidInputException(msg) # ensure it contains an "address" key if "address" in address_data or "slug" in address_data: return address_data # if we made it here, the input was not valid. msg = ("Input is invalid. Must be a list of (address, zipcode) tuples, or a dict or list" " of dicts with each item containing at least an 'address' or 'slug' key.") raise housecanary.exceptions.InvalidInputException((msg))
python
def _convert_to_identifier_json(self, address_data): """Convert input address data into json format""" if isinstance(address_data, str): # allow just passing a slug string. return {"slug": address_data} if isinstance(address_data, tuple) and len(address_data) > 0: address_json = {"address": address_data[0]} if len(address_data) > 1: address_json["zipcode"] = address_data[1] if len(address_data) > 2: address_json["meta"] = address_data[2] return address_json if isinstance(address_data, dict): allowed_keys = ["address", "zipcode", "unit", "city", "state", "slug", "meta", "client_value", "client_value_sqft"] # ensure the dict does not contain any unallowed keys for key in address_data: if key not in allowed_keys: msg = "Key in address input not allowed: " + key raise housecanary.exceptions.InvalidInputException(msg) # ensure it contains an "address" key if "address" in address_data or "slug" in address_data: return address_data # if we made it here, the input was not valid. msg = ("Input is invalid. Must be a list of (address, zipcode) tuples, or a dict or list" " of dicts with each item containing at least an 'address' or 'slug' key.") raise housecanary.exceptions.InvalidInputException((msg))
[ "def", "_convert_to_identifier_json", "(", "self", ",", "address_data", ")", ":", "if", "isinstance", "(", "address_data", ",", "str", ")", ":", "# allow just passing a slug string.", "return", "{", "\"slug\"", ":", "address_data", "}", "if", "isinstance", "(", "address_data", ",", "tuple", ")", "and", "len", "(", "address_data", ")", ">", "0", ":", "address_json", "=", "{", "\"address\"", ":", "address_data", "[", "0", "]", "}", "if", "len", "(", "address_data", ")", ">", "1", ":", "address_json", "[", "\"zipcode\"", "]", "=", "address_data", "[", "1", "]", "if", "len", "(", "address_data", ")", ">", "2", ":", "address_json", "[", "\"meta\"", "]", "=", "address_data", "[", "2", "]", "return", "address_json", "if", "isinstance", "(", "address_data", ",", "dict", ")", ":", "allowed_keys", "=", "[", "\"address\"", ",", "\"zipcode\"", ",", "\"unit\"", ",", "\"city\"", ",", "\"state\"", ",", "\"slug\"", ",", "\"meta\"", ",", "\"client_value\"", ",", "\"client_value_sqft\"", "]", "# ensure the dict does not contain any unallowed keys", "for", "key", "in", "address_data", ":", "if", "key", "not", "in", "allowed_keys", ":", "msg", "=", "\"Key in address input not allowed: \"", "+", "key", "raise", "housecanary", ".", "exceptions", ".", "InvalidInputException", "(", "msg", ")", "# ensure it contains an \"address\" key", "if", "\"address\"", "in", "address_data", "or", "\"slug\"", "in", "address_data", ":", "return", "address_data", "# if we made it here, the input was not valid.", "msg", "=", "(", "\"Input is invalid. Must be a list of (address, zipcode) tuples, or a dict or list\"", "\" of dicts with each item containing at least an 'address' or 'slug' key.\"", ")", "raise", "housecanary", ".", "exceptions", ".", "InvalidInputException", "(", "(", "msg", ")", ")" ]
Convert input address data into json format
[ "Convert", "input", "address", "data", "into", "json", "format" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L218-L250
train
housecanary/hc-api-python
housecanary/apiclient.py
PropertyComponentWrapper.value_report
def value_report(self, address, zipcode, report_type="full", format_type="json"): """Call the value_report component Value Report only supports a single address. Args: - address - zipcode Kwargs: - report_type - "full" or "summary". Default is "full". - format_type - "json", "pdf", "xlsx" or "all". Default is "json". """ query_params = { "report_type": report_type, "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/value_report", query_params)
python
def value_report(self, address, zipcode, report_type="full", format_type="json"): """Call the value_report component Value Report only supports a single address. Args: - address - zipcode Kwargs: - report_type - "full" or "summary". Default is "full". - format_type - "json", "pdf", "xlsx" or "all". Default is "json". """ query_params = { "report_type": report_type, "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/value_report", query_params)
[ "def", "value_report", "(", "self", ",", "address", ",", "zipcode", ",", "report_type", "=", "\"full\"", ",", "format_type", "=", "\"json\"", ")", ":", "query_params", "=", "{", "\"report_type\"", ":", "report_type", ",", "\"format\"", ":", "format_type", ",", "\"address\"", ":", "address", ",", "\"zipcode\"", ":", "zipcode", "}", "return", "self", ".", "_api_client", ".", "fetch_synchronous", "(", "\"property/value_report\"", ",", "query_params", ")" ]
Call the value_report component Value Report only supports a single address. Args: - address - zipcode Kwargs: - report_type - "full" or "summary". Default is "full". - format_type - "json", "pdf", "xlsx" or "all". Default is "json".
[ "Call", "the", "value_report", "component" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L413-L433
train
housecanary/hc-api-python
housecanary/apiclient.py
PropertyComponentWrapper.rental_report
def rental_report(self, address, zipcode, format_type="json"): """Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json". """ # only json is supported by rental report. query_params = { "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/rental_report", query_params)
python
def rental_report(self, address, zipcode, format_type="json"): """Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json". """ # only json is supported by rental report. query_params = { "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/rental_report", query_params)
[ "def", "rental_report", "(", "self", ",", "address", ",", "zipcode", ",", "format_type", "=", "\"json\"", ")", ":", "# only json is supported by rental report.", "query_params", "=", "{", "\"format\"", ":", "format_type", ",", "\"address\"", ":", "address", ",", "\"zipcode\"", ":", "zipcode", "}", "return", "self", ".", "_api_client", ".", "fetch_synchronous", "(", "\"property/rental_report\"", ",", "query_params", ")" ]
Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json".
[ "Call", "the", "rental_report", "component" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L435-L455
train
housecanary/hc-api-python
housecanary/apiclient.py
ZipComponentWrapper.component_mget
def component_mget(self, zip_data, components): """Call the zip component_mget endpoint Args: - zip_data - As described in the class docstring. - components - A list of strings for each component to include in the request. Example: ["zip/details", "zip/volatility"] """ if not isinstance(components, list): print("Components param must be a list") return query_params = {"components": ",".join(components)} return self.fetch_identifier_component( "zip/component_mget", zip_data, query_params)
python
def component_mget(self, zip_data, components): """Call the zip component_mget endpoint Args: - zip_data - As described in the class docstring. - components - A list of strings for each component to include in the request. Example: ["zip/details", "zip/volatility"] """ if not isinstance(components, list): print("Components param must be a list") return query_params = {"components": ",".join(components)} return self.fetch_identifier_component( "zip/component_mget", zip_data, query_params)
[ "def", "component_mget", "(", "self", ",", "zip_data", ",", "components", ")", ":", "if", "not", "isinstance", "(", "components", ",", "list", ")", ":", "print", "(", "\"Components param must be a list\"", ")", "return", "query_params", "=", "{", "\"components\"", ":", "\",\"", ".", "join", "(", "components", ")", "}", "return", "self", ".", "fetch_identifier_component", "(", "\"zip/component_mget\"", ",", "zip_data", ",", "query_params", ")" ]
Call the zip component_mget endpoint Args: - zip_data - As described in the class docstring. - components - A list of strings for each component to include in the request. Example: ["zip/details", "zip/volatility"]
[ "Call", "the", "zip", "component_mget", "endpoint" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L645-L660
train
mozilla-services/python-dockerflow
src/dockerflow/django/views.py
version
def version(request): """ Returns the contents of version.json or a 404. """ version_json = import_string(version_callback)(settings.BASE_DIR) if version_json is None: return HttpResponseNotFound('version.json not found') else: return JsonResponse(version_json)
python
def version(request): """ Returns the contents of version.json or a 404. """ version_json = import_string(version_callback)(settings.BASE_DIR) if version_json is None: return HttpResponseNotFound('version.json not found') else: return JsonResponse(version_json)
[ "def", "version", "(", "request", ")", ":", "version_json", "=", "import_string", "(", "version_callback", ")", "(", "settings", ".", "BASE_DIR", ")", "if", "version_json", "is", "None", ":", "return", "HttpResponseNotFound", "(", "'version.json not found'", ")", "else", ":", "return", "JsonResponse", "(", "version_json", ")" ]
Returns the contents of version.json or a 404.
[ "Returns", "the", "contents", "of", "version", ".", "json", "or", "a", "404", "." ]
43703c5e8934ba6901b0a1520d6da4ed6457208c
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/views.py#L20-L28
train
mozilla-services/python-dockerflow
src/dockerflow/django/views.py
heartbeat
def heartbeat(request): """ Runs all the Django checks and returns a JsonResponse 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. """ all_checks = checks.registry.registry.get_checks( include_deployment_checks=not settings.DEBUG, ) details = {} statuses = {} level = 0 for check in all_checks: detail = heartbeat_check_detail(check) statuses[check.__name__] = detail['status'] level = max(level, detail['level']) if detail['level'] > 0: details[check.__name__] = detail if level < checks.messages.WARNING: status_code = 200 heartbeat_passed.send(sender=heartbeat, level=level) else: status_code = 500 heartbeat_failed.send(sender=heartbeat, level=level) payload = { 'status': level_to_text(level), 'checks': statuses, 'details': details, } return JsonResponse(payload, status=status_code)
python
def heartbeat(request): """ Runs all the Django checks and returns a JsonResponse 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. """ all_checks = checks.registry.registry.get_checks( include_deployment_checks=not settings.DEBUG, ) details = {} statuses = {} level = 0 for check in all_checks: detail = heartbeat_check_detail(check) statuses[check.__name__] = detail['status'] level = max(level, detail['level']) if detail['level'] > 0: details[check.__name__] = detail if level < checks.messages.WARNING: status_code = 200 heartbeat_passed.send(sender=heartbeat, level=level) else: status_code = 500 heartbeat_failed.send(sender=heartbeat, level=level) payload = { 'status': level_to_text(level), 'checks': statuses, 'details': details, } return JsonResponse(payload, status=status_code)
[ "def", "heartbeat", "(", "request", ")", ":", "all_checks", "=", "checks", ".", "registry", ".", "registry", ".", "get_checks", "(", "include_deployment_checks", "=", "not", "settings", ".", "DEBUG", ",", ")", "details", "=", "{", "}", "statuses", "=", "{", "}", "level", "=", "0", "for", "check", "in", "all_checks", ":", "detail", "=", "heartbeat_check_detail", "(", "check", ")", "statuses", "[", "check", ".", "__name__", "]", "=", "detail", "[", "'status'", "]", "level", "=", "max", "(", "level", ",", "detail", "[", "'level'", "]", ")", "if", "detail", "[", "'level'", "]", ">", "0", ":", "details", "[", "check", ".", "__name__", "]", "=", "detail", "if", "level", "<", "checks", ".", "messages", ".", "WARNING", ":", "status_code", "=", "200", "heartbeat_passed", ".", "send", "(", "sender", "=", "heartbeat", ",", "level", "=", "level", ")", "else", ":", "status_code", "=", "500", "heartbeat_failed", ".", "send", "(", "sender", "=", "heartbeat", ",", "level", "=", "level", ")", "payload", "=", "{", "'status'", ":", "level_to_text", "(", "level", ")", ",", "'checks'", ":", "statuses", ",", "'details'", ":", "details", ",", "}", "return", "JsonResponse", "(", "payload", ",", "status", "=", "status_code", ")" ]
Runs all the Django checks and returns a JsonResponse 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", "Django", "checks", "and", "returns", "a", "JsonResponse", "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/django/views.py#L40-L75
train
housecanary/hc-api-python
housecanary/object.py
_create_component_results
def _create_component_results(json_data, result_key): """ Returns a list of ComponentResult from the json_data""" component_results = [] for key, value in list(json_data.items()): if key not in [result_key, "meta"]: component_result = ComponentResult( key, value["result"], value["api_code"], value["api_code_description"] ) component_results.append(component_result) return component_results
python
def _create_component_results(json_data, result_key): """ Returns a list of ComponentResult from the json_data""" component_results = [] for key, value in list(json_data.items()): if key not in [result_key, "meta"]: component_result = ComponentResult( key, value["result"], value["api_code"], value["api_code_description"] ) component_results.append(component_result) return component_results
[ "def", "_create_component_results", "(", "json_data", ",", "result_key", ")", ":", "component_results", "=", "[", "]", "for", "key", ",", "value", "in", "list", "(", "json_data", ".", "items", "(", ")", ")", ":", "if", "key", "not", "in", "[", "result_key", ",", "\"meta\"", "]", ":", "component_result", "=", "ComponentResult", "(", "key", ",", "value", "[", "\"result\"", "]", ",", "value", "[", "\"api_code\"", "]", ",", "value", "[", "\"api_code_description\"", "]", ")", "component_results", ".", "append", "(", "component_result", ")", "return", "component_results" ]
Returns a list of ComponentResult from the json_data
[ "Returns", "a", "list", "of", "ComponentResult", "from", "the", "json_data" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L13-L27
train
housecanary/hc-api-python
housecanary/object.py
HouseCanaryObject.has_error
def has_error(self): """Returns whether there was a business logic error when fetching data for any components for this property. Returns: boolean """ return next( (True for cr in self.component_results if cr.has_error()), False )
python
def has_error(self): """Returns whether there was a business logic error when fetching data for any components for this property. Returns: boolean """ return next( (True for cr in self.component_results if cr.has_error()), False )
[ "def", "has_error", "(", "self", ")", ":", "return", "next", "(", "(", "True", "for", "cr", "in", "self", ".", "component_results", "if", "cr", ".", "has_error", "(", ")", ")", ",", "False", ")" ]
Returns whether there was a business logic error when fetching data for any components for this property. Returns: boolean
[ "Returns", "whether", "there", "was", "a", "business", "logic", "error", "when", "fetching", "data", "for", "any", "components", "for", "this", "property", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L42-L53
train
housecanary/hc-api-python
housecanary/object.py
HouseCanaryObject.get_errors
def get_errors(self): """If there were any business errors fetching data for this property, returns the error messages. Returns: string - the error message, or None if there was no error. """ return [{cr.component_name: cr.get_error()} for cr in self.component_results if cr.has_error()]
python
def get_errors(self): """If there were any business errors fetching data for this property, returns the error messages. Returns: string - the error message, or None if there was no error. """ return [{cr.component_name: cr.get_error()} for cr in self.component_results if cr.has_error()]
[ "def", "get_errors", "(", "self", ")", ":", "return", "[", "{", "cr", ".", "component_name", ":", "cr", ".", "get_error", "(", ")", "}", "for", "cr", "in", "self", ".", "component_results", "if", "cr", ".", "has_error", "(", ")", "]" ]
If there were any business errors fetching data for this property, returns the error messages. Returns: string - the error message, or None if there was no error.
[ "If", "there", "were", "any", "business", "errors", "fetching", "data", "for", "this", "property", "returns", "the", "error", "messages", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L55-L64
train
housecanary/hc-api-python
housecanary/object.py
Property.create_from_json
def create_from_json(cls, json_data): """Deserialize property json data into a Property object Args: json_data (dict): The json data for this property Returns: Property object """ prop = Property() address_info = json_data["address_info"] prop.address = address_info["address"] prop.block_id = address_info["block_id"] prop.zipcode = address_info["zipcode"] prop.zipcode_plus4 = address_info["zipcode_plus4"] prop.address_full = address_info["address_full"] prop.city = address_info["city"] prop.county_fips = address_info["county_fips"] prop.geo_precision = address_info["geo_precision"] prop.lat = address_info["lat"] prop.lng = address_info["lng"] prop.slug = address_info["slug"] prop.state = address_info["state"] prop.unit = address_info["unit"] prop.meta = None if "meta" in json_data: prop.meta = json_data["meta"] prop.component_results = _create_component_results(json_data, "address_info") return prop
python
def create_from_json(cls, json_data): """Deserialize property json data into a Property object Args: json_data (dict): The json data for this property Returns: Property object """ prop = Property() address_info = json_data["address_info"] prop.address = address_info["address"] prop.block_id = address_info["block_id"] prop.zipcode = address_info["zipcode"] prop.zipcode_plus4 = address_info["zipcode_plus4"] prop.address_full = address_info["address_full"] prop.city = address_info["city"] prop.county_fips = address_info["county_fips"] prop.geo_precision = address_info["geo_precision"] prop.lat = address_info["lat"] prop.lng = address_info["lng"] prop.slug = address_info["slug"] prop.state = address_info["state"] prop.unit = address_info["unit"] prop.meta = None if "meta" in json_data: prop.meta = json_data["meta"] prop.component_results = _create_component_results(json_data, "address_info") return prop
[ "def", "create_from_json", "(", "cls", ",", "json_data", ")", ":", "prop", "=", "Property", "(", ")", "address_info", "=", "json_data", "[", "\"address_info\"", "]", "prop", ".", "address", "=", "address_info", "[", "\"address\"", "]", "prop", ".", "block_id", "=", "address_info", "[", "\"block_id\"", "]", "prop", ".", "zipcode", "=", "address_info", "[", "\"zipcode\"", "]", "prop", ".", "zipcode_plus4", "=", "address_info", "[", "\"zipcode_plus4\"", "]", "prop", ".", "address_full", "=", "address_info", "[", "\"address_full\"", "]", "prop", ".", "city", "=", "address_info", "[", "\"city\"", "]", "prop", ".", "county_fips", "=", "address_info", "[", "\"county_fips\"", "]", "prop", ".", "geo_precision", "=", "address_info", "[", "\"geo_precision\"", "]", "prop", ".", "lat", "=", "address_info", "[", "\"lat\"", "]", "prop", ".", "lng", "=", "address_info", "[", "\"lng\"", "]", "prop", ".", "slug", "=", "address_info", "[", "\"slug\"", "]", "prop", ".", "state", "=", "address_info", "[", "\"state\"", "]", "prop", ".", "unit", "=", "address_info", "[", "\"unit\"", "]", "prop", ".", "meta", "=", "None", "if", "\"meta\"", "in", "json_data", ":", "prop", ".", "meta", "=", "json_data", "[", "\"meta\"", "]", "prop", ".", "component_results", "=", "_create_component_results", "(", "json_data", ",", "\"address_info\"", ")", "return", "prop" ]
Deserialize property json data into a Property object Args: json_data (dict): The json data for this property Returns: Property object
[ "Deserialize", "property", "json", "data", "into", "a", "Property", "object" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L102-L134
train
housecanary/hc-api-python
housecanary/object.py
Block.create_from_json
def create_from_json(cls, json_data): """Deserialize block json data into a Block object Args: json_data (dict): The json data for this block Returns: Block object """ block = Block() block_info = json_data["block_info"] block.block_id = block_info["block_id"] block.num_bins = block_info["num_bins"] if "num_bins" in block_info else None block.property_type = block_info["property_type"] if "property_type" in block_info else None block.meta = json_data["meta"] if "meta" in json_data else None block.component_results = _create_component_results(json_data, "block_info") return block
python
def create_from_json(cls, json_data): """Deserialize block json data into a Block object Args: json_data (dict): The json data for this block Returns: Block object """ block = Block() block_info = json_data["block_info"] block.block_id = block_info["block_id"] block.num_bins = block_info["num_bins"] if "num_bins" in block_info else None block.property_type = block_info["property_type"] if "property_type" in block_info else None block.meta = json_data["meta"] if "meta" in json_data else None block.component_results = _create_component_results(json_data, "block_info") return block
[ "def", "create_from_json", "(", "cls", ",", "json_data", ")", ":", "block", "=", "Block", "(", ")", "block_info", "=", "json_data", "[", "\"block_info\"", "]", "block", ".", "block_id", "=", "block_info", "[", "\"block_id\"", "]", "block", ".", "num_bins", "=", "block_info", "[", "\"num_bins\"", "]", "if", "\"num_bins\"", "in", "block_info", "else", "None", "block", ".", "property_type", "=", "block_info", "[", "\"property_type\"", "]", "if", "\"property_type\"", "in", "block_info", "else", "None", "block", ".", "meta", "=", "json_data", "[", "\"meta\"", "]", "if", "\"meta\"", "in", "json_data", "else", "None", "block", ".", "component_results", "=", "_create_component_results", "(", "json_data", ",", "\"block_info\"", ")", "return", "block" ]
Deserialize block json data into a Block object Args: json_data (dict): The json data for this block Returns: Block object
[ "Deserialize", "block", "json", "data", "into", "a", "Block", "object" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L160-L179
train
housecanary/hc-api-python
housecanary/object.py
ZipCode.create_from_json
def create_from_json(cls, json_data): """Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip object """ zipcode = ZipCode() zipcode.zipcode = json_data["zipcode_info"]["zipcode"] zipcode.meta = json_data["meta"] if "meta" in json_data else None zipcode.component_results = _create_component_results(json_data, "zipcode_info") return zipcode
python
def create_from_json(cls, json_data): """Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip object """ zipcode = ZipCode() zipcode.zipcode = json_data["zipcode_info"]["zipcode"] zipcode.meta = json_data["meta"] if "meta" in json_data else None zipcode.component_results = _create_component_results(json_data, "zipcode_info") return zipcode
[ "def", "create_from_json", "(", "cls", ",", "json_data", ")", ":", "zipcode", "=", "ZipCode", "(", ")", "zipcode", ".", "zipcode", "=", "json_data", "[", "\"zipcode_info\"", "]", "[", "\"zipcode\"", "]", "zipcode", ".", "meta", "=", "json_data", "[", "\"meta\"", "]", "if", "\"meta\"", "in", "json_data", "else", "None", "zipcode", ".", "component_results", "=", "_create_component_results", "(", "json_data", ",", "\"zipcode_info\"", ")", "return", "zipcode" ]
Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip object
[ "Deserialize", "zipcode", "json", "data", "into", "a", "ZipCode", "object" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L203-L219
train
housecanary/hc-api-python
housecanary/object.py
Msa.create_from_json
def create_from_json(cls, json_data): """Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object """ msa = Msa() msa.msa = json_data["msa_info"]["msa"] msa.meta = json_data["meta"] if "meta" in json_data else None msa.component_results = _create_component_results(json_data, "msa_info") return msa
python
def create_from_json(cls, json_data): """Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object """ msa = Msa() msa.msa = json_data["msa_info"]["msa"] msa.meta = json_data["meta"] if "meta" in json_data else None msa.component_results = _create_component_results(json_data, "msa_info") return msa
[ "def", "create_from_json", "(", "cls", ",", "json_data", ")", ":", "msa", "=", "Msa", "(", ")", "msa", ".", "msa", "=", "json_data", "[", "\"msa_info\"", "]", "[", "\"msa\"", "]", "msa", ".", "meta", "=", "json_data", "[", "\"meta\"", "]", "if", "\"meta\"", "in", "json_data", "else", "None", "msa", ".", "component_results", "=", "_create_component_results", "(", "json_data", ",", "\"msa_info\"", ")", "return", "msa" ]
Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object
[ "Deserialize", "msa", "json", "data", "into", "a", "Msa", "object" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L243-L259
train
Tygs/ww
src/ww/tools/iterables.py
starts_when
def starts_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Start yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, start yielding items. If it's not a callable, it will be converted to one as `lambda condition: condition == item`. Example: >>> list(starts_when(range(10), lambda x: x > 5)) [6, 7, 8, 9] >>> list(starts_when(range(10), 7)) [7, 8, 9] """ if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.dropwhile(lambda x: not condition(x), iterable)
python
def starts_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Start yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, start yielding items. If it's not a callable, it will be converted to one as `lambda condition: condition == item`. Example: >>> list(starts_when(range(10), lambda x: x > 5)) [6, 7, 8, 9] >>> list(starts_when(range(10), 7)) [7, 8, 9] """ if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.dropwhile(lambda x: not condition(x), iterable)
[ "def", "starts_when", "(", "iterable", ",", "condition", ")", ":", "# type: (Iterable, Union[Callable, Any]) -> Iterable", "if", "not", "callable", "(", "condition", ")", ":", "cond_value", "=", "condition", "def", "condition", "(", "x", ")", ":", "return", "x", "==", "cond_value", "return", "itertools", ".", "dropwhile", "(", "lambda", "x", ":", "not", "condition", "(", "x", ")", ",", "iterable", ")" ]
Start yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, start yielding items. If it's not a callable, it will be converted to one as `lambda condition: condition == item`. Example: >>> list(starts_when(range(10), lambda x: x > 5)) [6, 7, 8, 9] >>> list(starts_when(range(10), 7)) [7, 8, 9]
[ "Start", "yielding", "items", "when", "a", "condition", "arise", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L49-L71
train
Tygs/ww
src/ww/tools/iterables.py
stops_when
def stops_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Stop yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, stop yielding items. If it's not a callable, it will be converted to one as `lambda condition: condition == item`. Example: >>> list(stops_when(range(10), lambda x: x > 5)) [0, 1, 2, 3, 4, 5] >>> list(stops_when(range(10), 7)) [0, 1, 2, 3, 4, 5, 6] """ if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.takewhile(lambda x: not condition(x), iterable)
python
def stops_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Stop yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, stop yielding items. If it's not a callable, it will be converted to one as `lambda condition: condition == item`. Example: >>> list(stops_when(range(10), lambda x: x > 5)) [0, 1, 2, 3, 4, 5] >>> list(stops_when(range(10), 7)) [0, 1, 2, 3, 4, 5, 6] """ if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.takewhile(lambda x: not condition(x), iterable)
[ "def", "stops_when", "(", "iterable", ",", "condition", ")", ":", "# type: (Iterable, Union[Callable, Any]) -> Iterable", "if", "not", "callable", "(", "condition", ")", ":", "cond_value", "=", "condition", "def", "condition", "(", "x", ")", ":", "return", "x", "==", "cond_value", "return", "itertools", ".", "takewhile", "(", "lambda", "x", ":", "not", "condition", "(", "x", ")", ",", "iterable", ")" ]
Stop yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, stop yielding items. If it's not a callable, it will be converted to one as `lambda condition: condition == item`. Example: >>> list(stops_when(range(10), lambda x: x > 5)) [0, 1, 2, 3, 4, 5] >>> list(stops_when(range(10), 7)) [0, 1, 2, 3, 4, 5, 6]
[ "Stop", "yielding", "items", "when", "a", "condition", "arise", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L74-L96
train
Tygs/ww
src/ww/tools/iterables.py
skip_duplicates
def skip_duplicates(iterable, key=None, fingerprints=()): # type: (Iterable, Callable, Any) -> Iterable """ Returns a generator that will yield all objects from iterable, skipping duplicates. Duplicates are identified using the `key` function to calculate a unique fingerprint. This does not use natural equality, but the result use a set() to remove duplicates, so defining __eq__ on your objects would have no effect. By default the fingerprint is the object itself, which ensure the functions works as-is with an iterable of primitives such as int, str or tuple. :Example: >>> list(skip_duplicates([1, 2, 3, 4, 4, 2, 1, 3 , 4])) [1, 2, 3, 4] The return value of `key` MUST be hashable, which means for non hashable objects such as dict, set or list, you need to specify a a function that returns a hashable fingerprint. :Example: >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: tuple(x))) [[], [1, 2]] >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: (type(x), tuple(x)))) [[], (), [1, 2], (1, 2)] For more complex types, such as custom classes, the default behavior is to remove nothing. You MUST provide a `key` function is you wish to filter those. :Example: >>> class Test(object): ... def __init__(self, foo='bar'): ... self.foo = foo ... def __repr__(self): ... return "Test('%s')" % self.foo ... >>> list(skip_duplicates([Test(), Test(), Test('other')])) [Test('bar'), Test('bar'), Test('other')] >>> list(skip_duplicates([Test(), Test(), Test('other')],\ lambda x: x.foo)) [Test('bar'), Test('other')] """ fingerprints = fingerprints or set() fingerprint = None # needed on type errors unrelated to hashing try: # duplicate some code to gain perf in the most common case if key is None: for x in iterable: if x not in fingerprints: yield x fingerprints.add(x) else: for x in iterable: fingerprint = key(x) if fingerprint not in fingerprints: yield x fingerprints.add(fingerprint) except TypeError: try: hash(fingerprint) except TypeError: raise TypeError( "The 'key' function returned a non hashable object of type " "'%s' when receiving '%s'. Make sure this function always " "returns a hashable object. Hint: immutable primitives like" "int, str or tuple, are hashable while dict, set and list are " "not." % (type(fingerprint), x)) else: raise
python
def skip_duplicates(iterable, key=None, fingerprints=()): # type: (Iterable, Callable, Any) -> Iterable """ Returns a generator that will yield all objects from iterable, skipping duplicates. Duplicates are identified using the `key` function to calculate a unique fingerprint. This does not use natural equality, but the result use a set() to remove duplicates, so defining __eq__ on your objects would have no effect. By default the fingerprint is the object itself, which ensure the functions works as-is with an iterable of primitives such as int, str or tuple. :Example: >>> list(skip_duplicates([1, 2, 3, 4, 4, 2, 1, 3 , 4])) [1, 2, 3, 4] The return value of `key` MUST be hashable, which means for non hashable objects such as dict, set or list, you need to specify a a function that returns a hashable fingerprint. :Example: >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: tuple(x))) [[], [1, 2]] >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: (type(x), tuple(x)))) [[], (), [1, 2], (1, 2)] For more complex types, such as custom classes, the default behavior is to remove nothing. You MUST provide a `key` function is you wish to filter those. :Example: >>> class Test(object): ... def __init__(self, foo='bar'): ... self.foo = foo ... def __repr__(self): ... return "Test('%s')" % self.foo ... >>> list(skip_duplicates([Test(), Test(), Test('other')])) [Test('bar'), Test('bar'), Test('other')] >>> list(skip_duplicates([Test(), Test(), Test('other')],\ lambda x: x.foo)) [Test('bar'), Test('other')] """ fingerprints = fingerprints or set() fingerprint = None # needed on type errors unrelated to hashing try: # duplicate some code to gain perf in the most common case if key is None: for x in iterable: if x not in fingerprints: yield x fingerprints.add(x) else: for x in iterable: fingerprint = key(x) if fingerprint not in fingerprints: yield x fingerprints.add(fingerprint) except TypeError: try: hash(fingerprint) except TypeError: raise TypeError( "The 'key' function returned a non hashable object of type " "'%s' when receiving '%s'. Make sure this function always " "returns a hashable object. Hint: immutable primitives like" "int, str or tuple, are hashable while dict, set and list are " "not." % (type(fingerprint), x)) else: raise
[ "def", "skip_duplicates", "(", "iterable", ",", "key", "=", "None", ",", "fingerprints", "=", "(", ")", ")", ":", "# type: (Iterable, Callable, Any) -> Iterable", "fingerprints", "=", "fingerprints", "or", "set", "(", ")", "fingerprint", "=", "None", "# needed on type errors unrelated to hashing", "try", ":", "# duplicate some code to gain perf in the most common case", "if", "key", "is", "None", ":", "for", "x", "in", "iterable", ":", "if", "x", "not", "in", "fingerprints", ":", "yield", "x", "fingerprints", ".", "add", "(", "x", ")", "else", ":", "for", "x", "in", "iterable", ":", "fingerprint", "=", "key", "(", "x", ")", "if", "fingerprint", "not", "in", "fingerprints", ":", "yield", "x", "fingerprints", ".", "add", "(", "fingerprint", ")", "except", "TypeError", ":", "try", ":", "hash", "(", "fingerprint", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "\"The 'key' function returned a non hashable object of type \"", "\"'%s' when receiving '%s'. Make sure this function always \"", "\"returns a hashable object. Hint: immutable primitives like\"", "\"int, str or tuple, are hashable while dict, set and list are \"", "\"not.\"", "%", "(", "type", "(", "fingerprint", ")", ",", "x", ")", ")", "else", ":", "raise" ]
Returns a generator that will yield all objects from iterable, skipping duplicates. Duplicates are identified using the `key` function to calculate a unique fingerprint. This does not use natural equality, but the result use a set() to remove duplicates, so defining __eq__ on your objects would have no effect. By default the fingerprint is the object itself, which ensure the functions works as-is with an iterable of primitives such as int, str or tuple. :Example: >>> list(skip_duplicates([1, 2, 3, 4, 4, 2, 1, 3 , 4])) [1, 2, 3, 4] The return value of `key` MUST be hashable, which means for non hashable objects such as dict, set or list, you need to specify a a function that returns a hashable fingerprint. :Example: >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: tuple(x))) [[], [1, 2]] >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: (type(x), tuple(x)))) [[], (), [1, 2], (1, 2)] For more complex types, such as custom classes, the default behavior is to remove nothing. You MUST provide a `key` function is you wish to filter those. :Example: >>> class Test(object): ... def __init__(self, foo='bar'): ... self.foo = foo ... def __repr__(self): ... return "Test('%s')" % self.foo ... >>> list(skip_duplicates([Test(), Test(), Test('other')])) [Test('bar'), Test('bar'), Test('other')] >>> list(skip_duplicates([Test(), Test(), Test('other')],\ lambda x: x.foo)) [Test('bar'), Test('other')]
[ "Returns", "a", "generator", "that", "will", "yield", "all", "objects", "from", "iterable", "skipping", "duplicates", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L99-L179
train
Tygs/ww
src/ww/tools/iterables.py
chunks
def chunks(iterable, chunksize, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields items from an iterator in iterable chunks. """ it = iter(iterable) while True: yield cast(itertools.chain([next(it)], itertools.islice(it, chunksize - 1)))
python
def chunks(iterable, chunksize, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields items from an iterator in iterable chunks. """ it = iter(iterable) while True: yield cast(itertools.chain([next(it)], itertools.islice(it, chunksize - 1)))
[ "def", "chunks", "(", "iterable", ",", "chunksize", ",", "cast", "=", "tuple", ")", ":", "# type: (Iterable, int, Callable) -> Iterable", "it", "=", "iter", "(", "iterable", ")", "while", "True", ":", "yield", "cast", "(", "itertools", ".", "chain", "(", "[", "next", "(", "it", ")", "]", ",", "itertools", ".", "islice", "(", "it", ",", "chunksize", "-", "1", ")", ")", ")" ]
Yields items from an iterator in iterable chunks.
[ "Yields", "items", "from", "an", "iterator", "in", "iterable", "chunks", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L183-L191
train
Tygs/ww
src/ww/tools/iterables.py
window
def window(iterable, size=2, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields iterms by bunch of a given size, but rolling only one item in and out at a time when iterating. >>> list(window([1, 2, 3])) [(1, 2), (2, 3)] By default, this will cast the window to a tuple before yielding it; however, any function that will accept an iterable as its argument is a valid target. If you pass None as a cast value, the deque will be returned as-is, which is more performant. However, since only one deque is used for the entire iteration, you'll get the same reference everytime, only the deque will contains different items. The result might not be what you want : >>> list(window([1, 2, 3], cast=None)) [deque([2, 3], maxlen=2), deque([2, 3], maxlen=2)] """ iterable = iter(iterable) d = deque(itertools.islice(iterable, size), size) if cast: yield cast(d) for x in iterable: d.append(x) yield cast(d) else: yield d for x in iterable: d.append(x) yield d
python
def window(iterable, size=2, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields iterms by bunch of a given size, but rolling only one item in and out at a time when iterating. >>> list(window([1, 2, 3])) [(1, 2), (2, 3)] By default, this will cast the window to a tuple before yielding it; however, any function that will accept an iterable as its argument is a valid target. If you pass None as a cast value, the deque will be returned as-is, which is more performant. However, since only one deque is used for the entire iteration, you'll get the same reference everytime, only the deque will contains different items. The result might not be what you want : >>> list(window([1, 2, 3], cast=None)) [deque([2, 3], maxlen=2), deque([2, 3], maxlen=2)] """ iterable = iter(iterable) d = deque(itertools.islice(iterable, size), size) if cast: yield cast(d) for x in iterable: d.append(x) yield cast(d) else: yield d for x in iterable: d.append(x) yield d
[ "def", "window", "(", "iterable", ",", "size", "=", "2", ",", "cast", "=", "tuple", ")", ":", "# type: (Iterable, int, Callable) -> Iterable", "iterable", "=", "iter", "(", "iterable", ")", "d", "=", "deque", "(", "itertools", ".", "islice", "(", "iterable", ",", "size", ")", ",", "size", ")", "if", "cast", ":", "yield", "cast", "(", "d", ")", "for", "x", "in", "iterable", ":", "d", ".", "append", "(", "x", ")", "yield", "cast", "(", "d", ")", "else", ":", "yield", "d", "for", "x", "in", "iterable", ":", "d", ".", "append", "(", "x", ")", "yield", "d" ]
Yields iterms by bunch of a given size, but rolling only one item in and out at a time when iterating. >>> list(window([1, 2, 3])) [(1, 2), (2, 3)] By default, this will cast the window to a tuple before yielding it; however, any function that will accept an iterable as its argument is a valid target. If you pass None as a cast value, the deque will be returned as-is, which is more performant. However, since only one deque is used for the entire iteration, you'll get the same reference everytime, only the deque will contains different items. The result might not be what you want : >>> list(window([1, 2, 3], cast=None)) [deque([2, 3], maxlen=2), deque([2, 3], maxlen=2)]
[ "Yields", "iterms", "by", "bunch", "of", "a", "given", "size", "but", "rolling", "only", "one", "item", "in", "and", "out", "at", "a", "time", "when", "iterating", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L194-L228
train
Tygs/ww
src/ww/tools/iterables.py
at_index
def at_index(iterable, index): # type: (Iterable[T], int) -> T """" Return the item at the index of this iterable or raises IndexError. WARNING: this will consume generators. Negative indices are allowed but be aware they will cause n items to be held in memory, where n = abs(index) """ try: if index < 0: return deque(iterable, maxlen=abs(index)).popleft() return next(itertools.islice(iterable, index, index + 1)) except (StopIteration, IndexError) as e: raise_from(IndexError('Index "%d" out of range' % index), e)
python
def at_index(iterable, index): # type: (Iterable[T], int) -> T """" Return the item at the index of this iterable or raises IndexError. WARNING: this will consume generators. Negative indices are allowed but be aware they will cause n items to be held in memory, where n = abs(index) """ try: if index < 0: return deque(iterable, maxlen=abs(index)).popleft() return next(itertools.islice(iterable, index, index + 1)) except (StopIteration, IndexError) as e: raise_from(IndexError('Index "%d" out of range' % index), e)
[ "def", "at_index", "(", "iterable", ",", "index", ")", ":", "# type: (Iterable[T], int) -> T", "try", ":", "if", "index", "<", "0", ":", "return", "deque", "(", "iterable", ",", "maxlen", "=", "abs", "(", "index", ")", ")", ".", "popleft", "(", ")", "return", "next", "(", "itertools", ".", "islice", "(", "iterable", ",", "index", ",", "index", "+", "1", ")", ")", "except", "(", "StopIteration", ",", "IndexError", ")", "as", "e", ":", "raise_from", "(", "IndexError", "(", "'Index \"%d\" out of range'", "%", "index", ")", ",", "e", ")" ]
Return the item at the index of this iterable or raises IndexError. WARNING: this will consume generators. Negative indices are allowed but be aware they will cause n items to be held in memory, where n = abs(index)
[ "Return", "the", "item", "at", "the", "index", "of", "this", "iterable", "or", "raises", "IndexError", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L231-L246
train
Tygs/ww
src/ww/tools/iterables.py
first_true
def first_true(iterable, func): # type: (Iterable[T], Callable) -> T """" Return the first item of the iterable for which func(item) == True. Or raises IndexError. WARNING: this will consume generators. """ try: return next((x for x in iterable if func(x))) except StopIteration as e: # TODO: Find a better error message raise_from(IndexError('No match for %s' % func), e)
python
def first_true(iterable, func): # type: (Iterable[T], Callable) -> T """" Return the first item of the iterable for which func(item) == True. Or raises IndexError. WARNING: this will consume generators. """ try: return next((x for x in iterable if func(x))) except StopIteration as e: # TODO: Find a better error message raise_from(IndexError('No match for %s' % func), e)
[ "def", "first_true", "(", "iterable", ",", "func", ")", ":", "# type: (Iterable[T], Callable) -> T", "try", ":", "return", "next", "(", "(", "x", "for", "x", "in", "iterable", "if", "func", "(", "x", ")", ")", ")", "except", "StopIteration", "as", "e", ":", "# TODO: Find a better error message", "raise_from", "(", "IndexError", "(", "'No match for %s'", "%", "func", ")", ",", "e", ")" ]
Return the first item of the iterable for which func(item) == True. Or raises IndexError. WARNING: this will consume generators.
[ "Return", "the", "first", "item", "of", "the", "iterable", "for", "which", "func", "(", "item", ")", "==", "True", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L250-L262
train
Tygs/ww
src/ww/tools/iterables.py
iterslice
def iterslice(iterable, start=0, stop=None, step=1): # type: (Iterable[T], int, int, int) -> Iterable[T] """ Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice after the first time stop(item) == True. """ if step < 0: raise ValueError("The step can not be negative: '%s' given" % step) if not isinstance(start, int): # [Callable:Callable] if not isinstance(stop, int) and stop: return stops_when(starts_when(iterable, start), stop) # [Callable:int] return starts_when(itertools.islice(iterable, None, stop, step), start) # [int:Callable] if not isinstance(stop, int) and stop: return stops_when(itertools.islice(iterable, start, None, step), stop) # [int:int] return itertools.islice(iterable, start, stop, step)
python
def iterslice(iterable, start=0, stop=None, step=1): # type: (Iterable[T], int, int, int) -> Iterable[T] """ Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice after the first time stop(item) == True. """ if step < 0: raise ValueError("The step can not be negative: '%s' given" % step) if not isinstance(start, int): # [Callable:Callable] if not isinstance(stop, int) and stop: return stops_when(starts_when(iterable, start), stop) # [Callable:int] return starts_when(itertools.islice(iterable, None, stop, step), start) # [int:Callable] if not isinstance(stop, int) and stop: return stops_when(itertools.islice(iterable, start, None, step), stop) # [int:int] return itertools.islice(iterable, start, stop, step)
[ "def", "iterslice", "(", "iterable", ",", "start", "=", "0", ",", "stop", "=", "None", ",", "step", "=", "1", ")", ":", "# type: (Iterable[T], int, int, int) -> Iterable[T]", "if", "step", "<", "0", ":", "raise", "ValueError", "(", "\"The step can not be negative: '%s' given\"", "%", "step", ")", "if", "not", "isinstance", "(", "start", ",", "int", ")", ":", "# [Callable:Callable]", "if", "not", "isinstance", "(", "stop", ",", "int", ")", "and", "stop", ":", "return", "stops_when", "(", "starts_when", "(", "iterable", ",", "start", ")", ",", "stop", ")", "# [Callable:int]", "return", "starts_when", "(", "itertools", ".", "islice", "(", "iterable", ",", "None", ",", "stop", ",", "step", ")", ",", "start", ")", "# [int:Callable]", "if", "not", "isinstance", "(", "stop", ",", "int", ")", "and", "stop", ":", "return", "stops_when", "(", "itertools", ".", "islice", "(", "iterable", ",", "start", ",", "None", ",", "step", ")", ",", "stop", ")", "# [int:int]", "return", "itertools", ".", "islice", "(", "iterable", ",", "start", ",", "stop", ",", "step", ")" ]
Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice after the first time stop(item) == True.
[ "Like", "itertools", ".", "islice", "but", "accept", "int", "and", "callables", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L265-L293
train
Tygs/ww
src/ww/tools/iterables.py
firsts
def firsts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the first x items from this iterable or default. """ try: items = int(items) except (ValueError, TypeError): raise ValueError("items should be usable as an int but is currently " "'{}' of type '{}'".format(items, type(items))) # TODO: replace this so that it returns lasts() if items < 0: raise ValueError(ww.f("items is {items} but should " "be greater than 0. If you wish to get the last " "items, use the lasts() function.")) i = 0 for i, item in zip(range(items), iterable): yield item for x in range(items - (i + 1)): yield default
python
def firsts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the first x items from this iterable or default. """ try: items = int(items) except (ValueError, TypeError): raise ValueError("items should be usable as an int but is currently " "'{}' of type '{}'".format(items, type(items))) # TODO: replace this so that it returns lasts() if items < 0: raise ValueError(ww.f("items is {items} but should " "be greater than 0. If you wish to get the last " "items, use the lasts() function.")) i = 0 for i, item in zip(range(items), iterable): yield item for x in range(items - (i + 1)): yield default
[ "def", "firsts", "(", "iterable", ",", "items", "=", "1", ",", "default", "=", "None", ")", ":", "# type: (Iterable[T], int, T) -> Iterable[T]", "try", ":", "items", "=", "int", "(", "items", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "raise", "ValueError", "(", "\"items should be usable as an int but is currently \"", "\"'{}' of type '{}'\"", ".", "format", "(", "items", ",", "type", "(", "items", ")", ")", ")", "# TODO: replace this so that it returns lasts()", "if", "items", "<", "0", ":", "raise", "ValueError", "(", "ww", ".", "f", "(", "\"items is {items} but should \"", "\"be greater than 0. If you wish to get the last \"", "\"items, use the lasts() function.\"", ")", ")", "i", "=", "0", "for", "i", ",", "item", "in", "zip", "(", "range", "(", "items", ")", ",", "iterable", ")", ":", "yield", "item", "for", "x", "in", "range", "(", "items", "-", "(", "i", "+", "1", ")", ")", ":", "yield", "default" ]
Lazily return the first x items from this iterable or default.
[ "Lazily", "return", "the", "first", "x", "items", "from", "this", "iterable", "or", "default", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L309-L330
train
Tygs/ww
src/ww/tools/iterables.py
lasts
def lasts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the last x items from this iterable or default. """ last_items = deque(iterable, maxlen=items) for _ in range(items - len(last_items)): yield default for y in last_items: yield y
python
def lasts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the last x items from this iterable or default. """ last_items = deque(iterable, maxlen=items) for _ in range(items - len(last_items)): yield default for y in last_items: yield y
[ "def", "lasts", "(", "iterable", ",", "items", "=", "1", ",", "default", "=", "None", ")", ":", "# type: (Iterable[T], int, T) -> Iterable[T]", "last_items", "=", "deque", "(", "iterable", ",", "maxlen", "=", "items", ")", "for", "_", "in", "range", "(", "items", "-", "len", "(", "last_items", ")", ")", ":", "yield", "default", "for", "y", "in", "last_items", ":", "yield", "y" ]
Lazily return the last x items from this iterable or default.
[ "Lazily", "return", "the", "last", "x", "items", "from", "this", "iterable", "or", "default", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/tools/iterables.py#L333-L343
train
lablup/backend.ai-client-py
src/ai/backend/client/session.py
is_legacy_server
def is_legacy_server(): '''Determine execution mode. Legacy mode: <= v4.20181215 ''' with Session() as session: ret = session.Kernel.hello() bai_version = ret['version'] legacy = True if bai_version <= 'v4.20181215' else False return legacy
python
def is_legacy_server(): '''Determine execution mode. Legacy mode: <= v4.20181215 ''' with Session() as session: ret = session.Kernel.hello() bai_version = ret['version'] legacy = True if bai_version <= 'v4.20181215' else False return legacy
[ "def", "is_legacy_server", "(", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "ret", "=", "session", ".", "Kernel", ".", "hello", "(", ")", "bai_version", "=", "ret", "[", "'version'", "]", "legacy", "=", "True", "if", "bai_version", "<=", "'v4.20181215'", "else", "False", "return", "legacy" ]
Determine execution mode. Legacy mode: <= v4.20181215
[ "Determine", "execution", "mode", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/session.py#L18-L27
train
lablup/backend.ai-client-py
src/ai/backend/client/session.py
Session.close
def close(self): ''' Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining. ''' if self._closed: return self._closed = True self._worker_thread.work_queue.put(self.aiohttp_session.close()) self._worker_thread.work_queue.put(self.worker_thread.sentinel) self._worker_thread.join()
python
def close(self): ''' Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining. ''' if self._closed: return self._closed = True self._worker_thread.work_queue.put(self.aiohttp_session.close()) self._worker_thread.work_queue.put(self.worker_thread.sentinel) self._worker_thread.join()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "self", ".", "_worker_thread", ".", "work_queue", ".", "put", "(", "self", ".", "aiohttp_session", ".", "close", "(", ")", ")", "self", ".", "_worker_thread", ".", "work_queue", ".", "put", "(", "self", ".", "worker_thread", ".", "sentinel", ")", "self", ".", "_worker_thread", ".", "join", "(", ")" ]
Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining.
[ "Terminates", "the", "session", ".", "It", "schedules", "the", "close", "()", "coroutine", "of", "the", "underlying", "aiohttp", "session", "and", "then", "enqueues", "a", "sentinel", "object", "to", "indicate", "termination", ".", "Then", "it", "waits", "until", "the", "worker", "thread", "to", "self", "-", "terminate", "by", "joining", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/session.py#L214-L226
train
lablup/backend.ai-client-py
src/ai/backend/client/compat.py
asyncio_run_forever
def asyncio_run_forever(setup_coro, shutdown_coro, *, stop_signals={signal.SIGINT}, debug=False): ''' A proposed-but-not-implemented asyncio.run_forever() API based on @vxgmichel's idea. See discussions on https://github.com/python/asyncio/pull/465 ''' async def wait_for_stop(): loop = current_loop() future = loop.create_future() for stop_sig in stop_signals: loop.add_signal_handler(stop_sig, future.set_result, stop_sig) try: recv_sig = await future finally: loop.remove_signal_handler(recv_sig) loop = asyncio.new_event_loop() try: asyncio.set_event_loop(loop) loop.set_debug(debug) loop.run_until_complete(setup_coro) loop.run_until_complete(wait_for_stop()) finally: try: loop.run_until_complete(shutdown_coro) _cancel_all_tasks(loop) if hasattr(loop, 'shutdown_asyncgens'): # Python 3.6+ loop.run_until_complete(loop.shutdown_asyncgens()) finally: asyncio.set_event_loop(None) loop.close()
python
def asyncio_run_forever(setup_coro, shutdown_coro, *, stop_signals={signal.SIGINT}, debug=False): ''' A proposed-but-not-implemented asyncio.run_forever() API based on @vxgmichel's idea. See discussions on https://github.com/python/asyncio/pull/465 ''' async def wait_for_stop(): loop = current_loop() future = loop.create_future() for stop_sig in stop_signals: loop.add_signal_handler(stop_sig, future.set_result, stop_sig) try: recv_sig = await future finally: loop.remove_signal_handler(recv_sig) loop = asyncio.new_event_loop() try: asyncio.set_event_loop(loop) loop.set_debug(debug) loop.run_until_complete(setup_coro) loop.run_until_complete(wait_for_stop()) finally: try: loop.run_until_complete(shutdown_coro) _cancel_all_tasks(loop) if hasattr(loop, 'shutdown_asyncgens'): # Python 3.6+ loop.run_until_complete(loop.shutdown_asyncgens()) finally: asyncio.set_event_loop(None) loop.close()
[ "def", "asyncio_run_forever", "(", "setup_coro", ",", "shutdown_coro", ",", "*", ",", "stop_signals", "=", "{", "signal", ".", "SIGINT", "}", ",", "debug", "=", "False", ")", ":", "async", "def", "wait_for_stop", "(", ")", ":", "loop", "=", "current_loop", "(", ")", "future", "=", "loop", ".", "create_future", "(", ")", "for", "stop_sig", "in", "stop_signals", ":", "loop", ".", "add_signal_handler", "(", "stop_sig", ",", "future", ".", "set_result", ",", "stop_sig", ")", "try", ":", "recv_sig", "=", "await", "future", "finally", ":", "loop", ".", "remove_signal_handler", "(", "recv_sig", ")", "loop", "=", "asyncio", ".", "new_event_loop", "(", ")", "try", ":", "asyncio", ".", "set_event_loop", "(", "loop", ")", "loop", ".", "set_debug", "(", "debug", ")", "loop", ".", "run_until_complete", "(", "setup_coro", ")", "loop", ".", "run_until_complete", "(", "wait_for_stop", "(", ")", ")", "finally", ":", "try", ":", "loop", ".", "run_until_complete", "(", "shutdown_coro", ")", "_cancel_all_tasks", "(", "loop", ")", "if", "hasattr", "(", "loop", ",", "'shutdown_asyncgens'", ")", ":", "# Python 3.6+", "loop", ".", "run_until_complete", "(", "loop", ".", "shutdown_asyncgens", "(", ")", ")", "finally", ":", "asyncio", ".", "set_event_loop", "(", "None", ")", "loop", ".", "close", "(", ")" ]
A proposed-but-not-implemented asyncio.run_forever() API based on @vxgmichel's idea. See discussions on https://github.com/python/asyncio/pull/465
[ "A", "proposed", "-", "but", "-", "not", "-", "implemented", "asyncio", ".", "run_forever", "()", "API", "based", "on" ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/compat.py#L80-L111
train
hustcc/wrapcache
wrapcache/database/__init__.py
LruCacheDB.clear
def clear(self): ''' claar all the cache, and release memory ''' for node in self.dli(): node.empty = True node.key = None node.value = None self.head = _dlnode() self.head.next = self.head self.head.prev = self.head self.listSize = 1 self.table.clear() # status var self.hit_cnt = 0 self.miss_cnt = 0 self.remove_cnt = 0
python
def clear(self): ''' claar all the cache, and release memory ''' for node in self.dli(): node.empty = True node.key = None node.value = None self.head = _dlnode() self.head.next = self.head self.head.prev = self.head self.listSize = 1 self.table.clear() # status var self.hit_cnt = 0 self.miss_cnt = 0 self.remove_cnt = 0
[ "def", "clear", "(", "self", ")", ":", "for", "node", "in", "self", ".", "dli", "(", ")", ":", "node", ".", "empty", "=", "True", "node", ".", "key", "=", "None", "node", ".", "value", "=", "None", "self", ".", "head", "=", "_dlnode", "(", ")", "self", ".", "head", ".", "next", "=", "self", ".", "head", "self", ".", "head", ".", "prev", "=", "self", ".", "head", "self", ".", "listSize", "=", "1", "self", ".", "table", ".", "clear", "(", ")", "# status var", "self", ".", "hit_cnt", "=", "0", "self", ".", "miss_cnt", "=", "0", "self", ".", "remove_cnt", "=", "0" ]
claar all the cache, and release memory
[ "claar", "all", "the", "cache", "and", "release", "memory" ]
3c6f52bb81a278e1dd60c27abe87d169cb4395aa
https://github.com/hustcc/wrapcache/blob/3c6f52bb81a278e1dd60c27abe87d169cb4395aa/wrapcache/database/__init__.py#L56-L75
train
hustcc/wrapcache
wrapcache/database/__init__.py
LruCacheDB.pop
def pop(self, key, default = None): """Delete the item""" node = self.get(key, None) if node == None: value = default else: value = node try: del self[key] except: return value return value
python
def pop(self, key, default = None): """Delete the item""" node = self.get(key, None) if node == None: value = default else: value = node try: del self[key] except: return value return value
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "node", "=", "self", ".", "get", "(", "key", ",", "None", ")", "if", "node", "==", "None", ":", "value", "=", "default", "else", ":", "value", "=", "node", "try", ":", "del", "self", "[", "key", "]", "except", ":", "return", "value", "return", "value" ]
Delete the item
[ "Delete", "the", "item" ]
3c6f52bb81a278e1dd60c27abe87d169cb4395aa
https://github.com/hustcc/wrapcache/blob/3c6f52bb81a278e1dd60c27abe87d169cb4395aa/wrapcache/database/__init__.py#L195-L207
train
AoiKuiyuyou/AoikLiveReload
src/aoiklivereload/demo/bottle_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 request handler @bottle.get('/') def hello_handler(): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return 'hello' # Run server bottle.run(host=server_host, port=server_port) # 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 request handler @bottle.get('/') def hello_handler(): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return 'hello' # Run server bottle.run(host=server_host, port=server_port) # 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 request handler", "@", "bottle", ".", "get", "(", "'/'", ")", "def", "hello_handler", "(", ")", ":", "# pylint: disable=unused-variable", "\"\"\"\n Request handler.\n\n :return:\n Response body.\n \"\"\"", "# Return response body", "return", "'hello'", "# Run server", "bottle", ".", "run", "(", "host", "=", "server_host", ",", "port", "=", "server_port", ")", "# 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/bottle_demo.py#L15-L84
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.get_or_create
async def get_or_create(cls, lang: str, *, client_token: str = None, mounts: Iterable[str] = None, envs: Mapping[str, str] = None, resources: Mapping[str, int] = None, cluster_size: int = 1, tag: str = None, owner_access_key: str = None) -> 'Kernel': ''' Get-or-creates a compute session. If *client_token* is ``None``, it creates a new compute session as long as the server has enough resources and your API key has remaining quota. If *client_token* is a valid string and there is an existing compute session with the same token and the same *lang*, then it returns the :class:`Kernel` instance representing the existing session. :param lang: The image name and tag for the compute session. Example: ``python:3.6-ubuntu``. Check out the full list of available images in your server using (TODO: new API). :param client_token: A client-side identifier to seamlessly reuse the compute session already created. :param mounts: The list of vfolder names that belongs to the currrent API access key. :param envs: The environment variables which always bypasses the jail policy. :param resources: The resource specification. (TODO: details) :param cluster_size: The number of containers in this compute session. Must be at least 1. :param tag: An optional string to annotate extra information. :param owner: An optional access key that owns the created session. (Only available to administrators) :returns: The :class:`Kernel` instance. ''' if client_token: assert 4 <= len(client_token) <= 64, \ 'Client session token should be 4 to 64 characters long.' else: client_token = uuid.uuid4().hex if mounts is None: mounts = [] if resources is None: resources = {} mounts.extend(cls.session.config.vfolder_mounts) rqst = Request(cls.session, 'POST', '/kernel/create') rqst.set_json({ 'lang': lang, 'tag': tag, 'clientSessionToken': client_token, 'config': { 'mounts': mounts, 'environ': envs, 'clusterSize': cluster_size, 'resources': resources, }, }) async with rqst.fetch() as resp: data = await resp.json() o = cls(data['kernelId'], owner_access_key) # type: ignore o.created = data.get('created', True) # True is for legacy o.service_ports = data.get('servicePorts', []) return o
python
async def get_or_create(cls, lang: str, *, client_token: str = None, mounts: Iterable[str] = None, envs: Mapping[str, str] = None, resources: Mapping[str, int] = None, cluster_size: int = 1, tag: str = None, owner_access_key: str = None) -> 'Kernel': ''' Get-or-creates a compute session. If *client_token* is ``None``, it creates a new compute session as long as the server has enough resources and your API key has remaining quota. If *client_token* is a valid string and there is an existing compute session with the same token and the same *lang*, then it returns the :class:`Kernel` instance representing the existing session. :param lang: The image name and tag for the compute session. Example: ``python:3.6-ubuntu``. Check out the full list of available images in your server using (TODO: new API). :param client_token: A client-side identifier to seamlessly reuse the compute session already created. :param mounts: The list of vfolder names that belongs to the currrent API access key. :param envs: The environment variables which always bypasses the jail policy. :param resources: The resource specification. (TODO: details) :param cluster_size: The number of containers in this compute session. Must be at least 1. :param tag: An optional string to annotate extra information. :param owner: An optional access key that owns the created session. (Only available to administrators) :returns: The :class:`Kernel` instance. ''' if client_token: assert 4 <= len(client_token) <= 64, \ 'Client session token should be 4 to 64 characters long.' else: client_token = uuid.uuid4().hex if mounts is None: mounts = [] if resources is None: resources = {} mounts.extend(cls.session.config.vfolder_mounts) rqst = Request(cls.session, 'POST', '/kernel/create') rqst.set_json({ 'lang': lang, 'tag': tag, 'clientSessionToken': client_token, 'config': { 'mounts': mounts, 'environ': envs, 'clusterSize': cluster_size, 'resources': resources, }, }) async with rqst.fetch() as resp: data = await resp.json() o = cls(data['kernelId'], owner_access_key) # type: ignore o.created = data.get('created', True) # True is for legacy o.service_ports = data.get('servicePorts', []) return o
[ "async", "def", "get_or_create", "(", "cls", ",", "lang", ":", "str", ",", "*", ",", "client_token", ":", "str", "=", "None", ",", "mounts", ":", "Iterable", "[", "str", "]", "=", "None", ",", "envs", ":", "Mapping", "[", "str", ",", "str", "]", "=", "None", ",", "resources", ":", "Mapping", "[", "str", ",", "int", "]", "=", "None", ",", "cluster_size", ":", "int", "=", "1", ",", "tag", ":", "str", "=", "None", ",", "owner_access_key", ":", "str", "=", "None", ")", "->", "'Kernel'", ":", "if", "client_token", ":", "assert", "4", "<=", "len", "(", "client_token", ")", "<=", "64", ",", "'Client session token should be 4 to 64 characters long.'", "else", ":", "client_token", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "if", "mounts", "is", "None", ":", "mounts", "=", "[", "]", "if", "resources", "is", "None", ":", "resources", "=", "{", "}", "mounts", ".", "extend", "(", "cls", ".", "session", ".", "config", ".", "vfolder_mounts", ")", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/kernel/create'", ")", "rqst", ".", "set_json", "(", "{", "'lang'", ":", "lang", ",", "'tag'", ":", "tag", ",", "'clientSessionToken'", ":", "client_token", ",", "'config'", ":", "{", "'mounts'", ":", "mounts", ",", "'environ'", ":", "envs", ",", "'clusterSize'", ":", "cluster_size", ",", "'resources'", ":", "resources", ",", "}", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "o", "=", "cls", "(", "data", "[", "'kernelId'", "]", ",", "owner_access_key", ")", "# type: ignore", "o", ".", "created", "=", "data", ".", "get", "(", "'created'", ",", "True", ")", "# True is for legacy", "o", ".", "service_ports", "=", "data", ".", "get", "(", "'servicePorts'", ",", "[", "]", ")", "return", "o" ]
Get-or-creates a compute session. If *client_token* is ``None``, it creates a new compute session as long as the server has enough resources and your API key has remaining quota. If *client_token* is a valid string and there is an existing compute session with the same token and the same *lang*, then it returns the :class:`Kernel` instance representing the existing session. :param lang: The image name and tag for the compute session. Example: ``python:3.6-ubuntu``. Check out the full list of available images in your server using (TODO: new API). :param client_token: A client-side identifier to seamlessly reuse the compute session already created. :param mounts: The list of vfolder names that belongs to the currrent API access key. :param envs: The environment variables which always bypasses the jail policy. :param resources: The resource specification. (TODO: details) :param cluster_size: The number of containers in this compute session. Must be at least 1. :param tag: An optional string to annotate extra information. :param owner: An optional access key that owns the created session. (Only available to administrators) :returns: The :class:`Kernel` instance.
[ "Get", "-", "or", "-", "creates", "a", "compute", "session", ".", "If", "*", "client_token", "*", "is", "None", "it", "creates", "a", "new", "compute", "session", "as", "long", "as", "the", "server", "has", "enough", "resources", "and", "your", "API", "key", "has", "remaining", "quota", ".", "If", "*", "client_token", "*", "is", "a", "valid", "string", "and", "there", "is", "an", "existing", "compute", "session", "with", "the", "same", "token", "and", "the", "same", "*", "lang", "*", "then", "it", "returns", "the", ":", "class", ":", "Kernel", "instance", "representing", "the", "existing", "session", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L51-L112
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.destroy
async def destroy(self): ''' Destroys the compute session. Since the server literally kills the container(s), all ongoing executions are forcibly interrupted. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'DELETE', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch() as resp: if resp.status == 200: return await resp.json()
python
async def destroy(self): ''' Destroys the compute session. Since the server literally kills the container(s), all ongoing executions are forcibly interrupted. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'DELETE', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch() as resp: if resp.status == 200: return await resp.json()
[ "async", "def", "destroy", "(", "self", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'DELETE'", ",", "'/kernel/{}'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "if", "resp", ".", "status", "==", "200", ":", "return", "await", "resp", ".", "json", "(", ")" ]
Destroys the compute session. Since the server literally kills the container(s), all ongoing executions are forcibly interrupted.
[ "Destroys", "the", "compute", "session", ".", "Since", "the", "server", "literally", "kills", "the", "container", "(", "s", ")", "all", "ongoing", "executions", "are", "forcibly", "interrupted", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L119-L133
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.restart
async def restart(self): ''' Restarts the compute session. The server force-destroys the current running container(s), but keeps their temporary scratch directories intact. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'PATCH', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch(): pass
python
async def restart(self): ''' Restarts the compute session. The server force-destroys the current running container(s), but keeps their temporary scratch directories intact. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'PATCH', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch(): pass
[ "async", "def", "restart", "(", "self", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'PATCH'", ",", "'/kernel/{}'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "async", "with", "rqst", ".", "fetch", "(", ")", ":", "pass" ]
Restarts the compute session. The server force-destroys the current running container(s), but keeps their temporary scratch directories intact.
[ "Restarts", "the", "compute", "session", ".", "The", "server", "force", "-", "destroys", "the", "current", "running", "container", "(", "s", ")", "but", "keeps", "their", "temporary", "scratch", "directories", "intact", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L136-L149
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.complete
async def complete(self, code: str, opts: dict = None) -> Iterable[str]: ''' Gets the auto-completion candidates from the given code string, as if a user has pressed the tab key just after the code in IDEs. Depending on the language of the compute session, this feature may not be supported. Unsupported sessions returns an empty list. :param code: An (incomplete) code text. :param opts: Additional information about the current cursor position, such as row, col, line and the remainder text. :returns: An ordered list of strings. ''' opts = {} if opts is None else opts params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'POST', '/kernel/{}/complete'.format(self.kernel_id), params=params) rqst.set_json({ 'code': code, 'options': { 'row': int(opts.get('row', 0)), 'col': int(opts.get('col', 0)), 'line': opts.get('line', ''), 'post': opts.get('post', ''), }, }) async with rqst.fetch() as resp: return await resp.json()
python
async def complete(self, code: str, opts: dict = None) -> Iterable[str]: ''' Gets the auto-completion candidates from the given code string, as if a user has pressed the tab key just after the code in IDEs. Depending on the language of the compute session, this feature may not be supported. Unsupported sessions returns an empty list. :param code: An (incomplete) code text. :param opts: Additional information about the current cursor position, such as row, col, line and the remainder text. :returns: An ordered list of strings. ''' opts = {} if opts is None else opts params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'POST', '/kernel/{}/complete'.format(self.kernel_id), params=params) rqst.set_json({ 'code': code, 'options': { 'row': int(opts.get('row', 0)), 'col': int(opts.get('col', 0)), 'line': opts.get('line', ''), 'post': opts.get('post', ''), }, }) async with rqst.fetch() as resp: return await resp.json()
[ "async", "def", "complete", "(", "self", ",", "code", ":", "str", ",", "opts", ":", "dict", "=", "None", ")", "->", "Iterable", "[", "str", "]", ":", "opts", "=", "{", "}", "if", "opts", "is", "None", "else", "opts", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/kernel/{}/complete'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "set_json", "(", "{", "'code'", ":", "code", ",", "'options'", ":", "{", "'row'", ":", "int", "(", "opts", ".", "get", "(", "'row'", ",", "0", ")", ")", ",", "'col'", ":", "int", "(", "opts", ".", "get", "(", "'col'", ",", "0", ")", ")", ",", "'line'", ":", "opts", ".", "get", "(", "'line'", ",", "''", ")", ",", "'post'", ":", "opts", ".", "get", "(", "'post'", ",", "''", ")", ",", "}", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "await", "resp", ".", "json", "(", ")" ]
Gets the auto-completion candidates from the given code string, as if a user has pressed the tab key just after the code in IDEs. Depending on the language of the compute session, this feature may not be supported. Unsupported sessions returns an empty list. :param code: An (incomplete) code text. :param opts: Additional information about the current cursor position, such as row, col, line and the remainder text. :returns: An ordered list of strings.
[ "Gets", "the", "auto", "-", "completion", "candidates", "from", "the", "given", "code", "string", "as", "if", "a", "user", "has", "pressed", "the", "tab", "key", "just", "after", "the", "code", "in", "IDEs", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L168-L200
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.get_info
async def get_info(self): ''' Retrieves a brief information about the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch() as resp: return await resp.json()
python
async def get_info(self): ''' Retrieves a brief information about the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch() as resp: return await resp.json()
[ "async", "def", "get_info", "(", "self", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'GET'", ",", "'/kernel/{}'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "await", "resp", ".", "json", "(", ")" ]
Retrieves a brief information about the compute session.
[ "Retrieves", "a", "brief", "information", "about", "the", "compute", "session", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L203-L214
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.execute
async def execute(self, run_id: str = None, code: str = None, mode: str = 'query', opts: dict = None): ''' Executes a code snippet directly in the compute session or sends a set of build/clean/execute commands to the compute session. For more details about using this API, please refer :doc:`the official API documentation <user-api/intro>`. :param run_id: A unique identifier for a particular run loop. In the first call, it may be ``None`` so that the server auto-assigns one. Subsequent calls must use the returned ``runId`` value to request continuation or to send user inputs. :param code: A code snippet as string. In the continuation requests, it must be an empty string. When sending user inputs, this is where the user input string is stored. :param mode: A constant string which is one of ``"query"``, ``"batch"``, ``"continue"``, and ``"user-input"``. :param opts: A dict for specifying additional options. Mainly used in the batch mode to specify build/clean/execution commands. See :ref:`the API object reference <batch-execution-query-object>` for details. :returns: :ref:`An execution result object <execution-result-object>` ''' opts = opts if opts is not None else {} params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key if mode in {'query', 'continue', 'input'}: assert code is not None, \ 'The code argument must be a valid string even when empty.' rqst = Request(self.session, 'POST', '/kernel/{}'.format(self.kernel_id), params=params) rqst.set_json({ 'mode': mode, 'code': code, 'runId': run_id, }) elif mode == 'batch': rqst = Request(self.session, 'POST', '/kernel/{}'.format(self.kernel_id), params=params) rqst.set_json({ 'mode': mode, 'code': code, 'runId': run_id, 'options': { 'clean': opts.get('clean', None), 'build': opts.get('build', None), 'buildLog': bool(opts.get('buildLog', False)), 'exec': opts.get('exec', None), }, }) elif mode == 'complete': rqst = Request(self.session, 'POST', '/kernel/{}/complete'.format(self.kernel_id), params=params) rqst.set_json({ 'code': code, 'options': { 'row': int(opts.get('row', 0)), 'col': int(opts.get('col', 0)), 'line': opts.get('line', ''), 'post': opts.get('post', ''), }, }) else: raise BackendClientError('Invalid execution mode: {0}'.format(mode)) async with rqst.fetch() as resp: return (await resp.json())['result']
python
async def execute(self, run_id: str = None, code: str = None, mode: str = 'query', opts: dict = None): ''' Executes a code snippet directly in the compute session or sends a set of build/clean/execute commands to the compute session. For more details about using this API, please refer :doc:`the official API documentation <user-api/intro>`. :param run_id: A unique identifier for a particular run loop. In the first call, it may be ``None`` so that the server auto-assigns one. Subsequent calls must use the returned ``runId`` value to request continuation or to send user inputs. :param code: A code snippet as string. In the continuation requests, it must be an empty string. When sending user inputs, this is where the user input string is stored. :param mode: A constant string which is one of ``"query"``, ``"batch"``, ``"continue"``, and ``"user-input"``. :param opts: A dict for specifying additional options. Mainly used in the batch mode to specify build/clean/execution commands. See :ref:`the API object reference <batch-execution-query-object>` for details. :returns: :ref:`An execution result object <execution-result-object>` ''' opts = opts if opts is not None else {} params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key if mode in {'query', 'continue', 'input'}: assert code is not None, \ 'The code argument must be a valid string even when empty.' rqst = Request(self.session, 'POST', '/kernel/{}'.format(self.kernel_id), params=params) rqst.set_json({ 'mode': mode, 'code': code, 'runId': run_id, }) elif mode == 'batch': rqst = Request(self.session, 'POST', '/kernel/{}'.format(self.kernel_id), params=params) rqst.set_json({ 'mode': mode, 'code': code, 'runId': run_id, 'options': { 'clean': opts.get('clean', None), 'build': opts.get('build', None), 'buildLog': bool(opts.get('buildLog', False)), 'exec': opts.get('exec', None), }, }) elif mode == 'complete': rqst = Request(self.session, 'POST', '/kernel/{}/complete'.format(self.kernel_id), params=params) rqst.set_json({ 'code': code, 'options': { 'row': int(opts.get('row', 0)), 'col': int(opts.get('col', 0)), 'line': opts.get('line', ''), 'post': opts.get('post', ''), }, }) else: raise BackendClientError('Invalid execution mode: {0}'.format(mode)) async with rqst.fetch() as resp: return (await resp.json())['result']
[ "async", "def", "execute", "(", "self", ",", "run_id", ":", "str", "=", "None", ",", "code", ":", "str", "=", "None", ",", "mode", ":", "str", "=", "'query'", ",", "opts", ":", "dict", "=", "None", ")", ":", "opts", "=", "opts", "if", "opts", "is", "not", "None", "else", "{", "}", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "if", "mode", "in", "{", "'query'", ",", "'continue'", ",", "'input'", "}", ":", "assert", "code", "is", "not", "None", ",", "'The code argument must be a valid string even when empty.'", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/kernel/{}'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "set_json", "(", "{", "'mode'", ":", "mode", ",", "'code'", ":", "code", ",", "'runId'", ":", "run_id", ",", "}", ")", "elif", "mode", "==", "'batch'", ":", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/kernel/{}'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "set_json", "(", "{", "'mode'", ":", "mode", ",", "'code'", ":", "code", ",", "'runId'", ":", "run_id", ",", "'options'", ":", "{", "'clean'", ":", "opts", ".", "get", "(", "'clean'", ",", "None", ")", ",", "'build'", ":", "opts", ".", "get", "(", "'build'", ",", "None", ")", ",", "'buildLog'", ":", "bool", "(", "opts", ".", "get", "(", "'buildLog'", ",", "False", ")", ")", ",", "'exec'", ":", "opts", ".", "get", "(", "'exec'", ",", "None", ")", ",", "}", ",", "}", ")", "elif", "mode", "==", "'complete'", ":", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/kernel/{}/complete'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "set_json", "(", "{", "'code'", ":", "code", ",", "'options'", ":", "{", "'row'", ":", "int", "(", "opts", ".", "get", "(", "'row'", ",", "0", ")", ")", ",", "'col'", ":", "int", "(", "opts", ".", "get", "(", "'col'", ",", "0", ")", ")", ",", "'line'", ":", "opts", ".", "get", "(", "'line'", ",", "''", ")", ",", "'post'", ":", "opts", ".", "get", "(", "'post'", ",", "''", ")", ",", "}", ",", "}", ")", "else", ":", "raise", "BackendClientError", "(", "'Invalid execution mode: {0}'", ".", "format", "(", "mode", ")", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "(", "await", "resp", ".", "json", "(", ")", ")", "[", "'result'", "]" ]
Executes a code snippet directly in the compute session or sends a set of build/clean/execute commands to the compute session. For more details about using this API, please refer :doc:`the official API documentation <user-api/intro>`. :param run_id: A unique identifier for a particular run loop. In the first call, it may be ``None`` so that the server auto-assigns one. Subsequent calls must use the returned ``runId`` value to request continuation or to send user inputs. :param code: A code snippet as string. In the continuation requests, it must be an empty string. When sending user inputs, this is where the user input string is stored. :param mode: A constant string which is one of ``"query"``, ``"batch"``, ``"continue"``, and ``"user-input"``. :param opts: A dict for specifying additional options. Mainly used in the batch mode to specify build/clean/execution commands. See :ref:`the API object reference <batch-execution-query-object>` for details. :returns: :ref:`An execution result object <execution-result-object>`
[ "Executes", "a", "code", "snippet", "directly", "in", "the", "compute", "session", "or", "sends", "a", "set", "of", "build", "/", "clean", "/", "execute", "commands", "to", "the", "compute", "session", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L231-L304
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.upload
async def upload(self, files: Sequence[Union[str, Path]], basedir: Union[str, Path] = None, show_progress: bool = False): ''' Uploads the given list of files to the compute session. You may refer them in the batch-mode execution or from the code executed in the server afterwards. :param files: The list of file paths in the client-side. If the paths include directories, the location of them in the compute session is calculated from the relative path to *basedir* and all intermediate parent directories are automatically created if not exists. For example, if a file path is ``/home/user/test/data.txt`` (or ``test/data.txt``) where *basedir* is ``/home/user`` (or the current working directory is ``/home/user``), the uploaded file is located at ``/home/work/test/data.txt`` in the compute session container. :param basedir: The directory prefix where the files reside. The default value is the current working directory. :param show_progress: Displays a progress bar during uploads. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key base_path = (Path.cwd() if basedir is None else Path(basedir).resolve()) files = [Path(file).resolve() for file in files] total_size = 0 for file_path in files: total_size += file_path.stat().st_size tqdm_obj = tqdm(desc='Uploading files', unit='bytes', unit_scale=True, total=total_size, disable=not show_progress) with tqdm_obj: attachments = [] for file_path in files: try: attachments.append(AttachedFile( str(file_path.relative_to(base_path)), ProgressReportingReader(str(file_path), tqdm_instance=tqdm_obj), 'application/octet-stream', )) except ValueError: msg = 'File "{0}" is outside of the base directory "{1}".' \ .format(file_path, base_path) raise ValueError(msg) from None rqst = Request(self.session, 'POST', '/kernel/{}/upload'.format(self.kernel_id), params=params) rqst.attach_files(attachments) async with rqst.fetch() as resp: return resp
python
async def upload(self, files: Sequence[Union[str, Path]], basedir: Union[str, Path] = None, show_progress: bool = False): ''' Uploads the given list of files to the compute session. You may refer them in the batch-mode execution or from the code executed in the server afterwards. :param files: The list of file paths in the client-side. If the paths include directories, the location of them in the compute session is calculated from the relative path to *basedir* and all intermediate parent directories are automatically created if not exists. For example, if a file path is ``/home/user/test/data.txt`` (or ``test/data.txt``) where *basedir* is ``/home/user`` (or the current working directory is ``/home/user``), the uploaded file is located at ``/home/work/test/data.txt`` in the compute session container. :param basedir: The directory prefix where the files reside. The default value is the current working directory. :param show_progress: Displays a progress bar during uploads. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key base_path = (Path.cwd() if basedir is None else Path(basedir).resolve()) files = [Path(file).resolve() for file in files] total_size = 0 for file_path in files: total_size += file_path.stat().st_size tqdm_obj = tqdm(desc='Uploading files', unit='bytes', unit_scale=True, total=total_size, disable=not show_progress) with tqdm_obj: attachments = [] for file_path in files: try: attachments.append(AttachedFile( str(file_path.relative_to(base_path)), ProgressReportingReader(str(file_path), tqdm_instance=tqdm_obj), 'application/octet-stream', )) except ValueError: msg = 'File "{0}" is outside of the base directory "{1}".' \ .format(file_path, base_path) raise ValueError(msg) from None rqst = Request(self.session, 'POST', '/kernel/{}/upload'.format(self.kernel_id), params=params) rqst.attach_files(attachments) async with rqst.fetch() as resp: return resp
[ "async", "def", "upload", "(", "self", ",", "files", ":", "Sequence", "[", "Union", "[", "str", ",", "Path", "]", "]", ",", "basedir", ":", "Union", "[", "str", ",", "Path", "]", "=", "None", ",", "show_progress", ":", "bool", "=", "False", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "base_path", "=", "(", "Path", ".", "cwd", "(", ")", "if", "basedir", "is", "None", "else", "Path", "(", "basedir", ")", ".", "resolve", "(", ")", ")", "files", "=", "[", "Path", "(", "file", ")", ".", "resolve", "(", ")", "for", "file", "in", "files", "]", "total_size", "=", "0", "for", "file_path", "in", "files", ":", "total_size", "+=", "file_path", ".", "stat", "(", ")", ".", "st_size", "tqdm_obj", "=", "tqdm", "(", "desc", "=", "'Uploading files'", ",", "unit", "=", "'bytes'", ",", "unit_scale", "=", "True", ",", "total", "=", "total_size", ",", "disable", "=", "not", "show_progress", ")", "with", "tqdm_obj", ":", "attachments", "=", "[", "]", "for", "file_path", "in", "files", ":", "try", ":", "attachments", ".", "append", "(", "AttachedFile", "(", "str", "(", "file_path", ".", "relative_to", "(", "base_path", ")", ")", ",", "ProgressReportingReader", "(", "str", "(", "file_path", ")", ",", "tqdm_instance", "=", "tqdm_obj", ")", ",", "'application/octet-stream'", ",", ")", ")", "except", "ValueError", ":", "msg", "=", "'File \"{0}\" is outside of the base directory \"{1}\".'", ".", "format", "(", "file_path", ",", "base_path", ")", "raise", "ValueError", "(", "msg", ")", "from", "None", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/kernel/{}/upload'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "attach_files", "(", "attachments", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "resp" ]
Uploads the given list of files to the compute session. You may refer them in the batch-mode execution or from the code executed in the server afterwards. :param files: The list of file paths in the client-side. If the paths include directories, the location of them in the compute session is calculated from the relative path to *basedir* and all intermediate parent directories are automatically created if not exists. For example, if a file path is ``/home/user/test/data.txt`` (or ``test/data.txt``) where *basedir* is ``/home/user`` (or the current working directory is ``/home/user``), the uploaded file is located at ``/home/work/test/data.txt`` in the compute session container. :param basedir: The directory prefix where the files reside. The default value is the current working directory. :param show_progress: Displays a progress bar during uploads.
[ "Uploads", "the", "given", "list", "of", "files", "to", "the", "compute", "session", ".", "You", "may", "refer", "them", "in", "the", "batch", "-", "mode", "execution", "or", "from", "the", "code", "executed", "in", "the", "server", "afterwards", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L307-L361
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.download
async def download(self, files: Sequence[Union[str, Path]], dest: Union[str, Path] = '.', show_progress: bool = False): ''' Downloads the given list of files from the compute session. :param files: The list of file paths in the compute session. If they are relative paths, the path is calculated from ``/home/work`` in the compute session container. :param dest: The destination directory in the client-side. :param show_progress: Displays a progress bar during downloads. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}/download'.format(self.kernel_id), params=params) rqst.set_json({ 'files': [*map(str, files)], }) async with rqst.fetch() as resp: chunk_size = 1 * 1024 file_names = None tqdm_obj = tqdm(desc='Downloading files', unit='bytes', unit_scale=True, total=resp.content.total_bytes, disable=not show_progress) with tqdm_obj as pbar: fp = None while True: chunk = await resp.aread(chunk_size) if not chunk: break pbar.update(len(chunk)) # TODO: more elegant parsing of multipart response? for part in chunk.split(b'\r\n'): if part.startswith(b'--'): if fp: fp.close() with tarfile.open(fp.name) as tarf: tarf.extractall(path=dest) file_names = tarf.getnames() os.unlink(fp.name) fp = tempfile.NamedTemporaryFile(suffix='.tar', delete=False) elif part.startswith(b'Content-') or part == b'': continue else: fp.write(part) if fp: fp.close() os.unlink(fp.name) result = {'file_names': file_names} return result
python
async def download(self, files: Sequence[Union[str, Path]], dest: Union[str, Path] = '.', show_progress: bool = False): ''' Downloads the given list of files from the compute session. :param files: The list of file paths in the compute session. If they are relative paths, the path is calculated from ``/home/work`` in the compute session container. :param dest: The destination directory in the client-side. :param show_progress: Displays a progress bar during downloads. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}/download'.format(self.kernel_id), params=params) rqst.set_json({ 'files': [*map(str, files)], }) async with rqst.fetch() as resp: chunk_size = 1 * 1024 file_names = None tqdm_obj = tqdm(desc='Downloading files', unit='bytes', unit_scale=True, total=resp.content.total_bytes, disable=not show_progress) with tqdm_obj as pbar: fp = None while True: chunk = await resp.aread(chunk_size) if not chunk: break pbar.update(len(chunk)) # TODO: more elegant parsing of multipart response? for part in chunk.split(b'\r\n'): if part.startswith(b'--'): if fp: fp.close() with tarfile.open(fp.name) as tarf: tarf.extractall(path=dest) file_names = tarf.getnames() os.unlink(fp.name) fp = tempfile.NamedTemporaryFile(suffix='.tar', delete=False) elif part.startswith(b'Content-') or part == b'': continue else: fp.write(part) if fp: fp.close() os.unlink(fp.name) result = {'file_names': file_names} return result
[ "async", "def", "download", "(", "self", ",", "files", ":", "Sequence", "[", "Union", "[", "str", ",", "Path", "]", "]", ",", "dest", ":", "Union", "[", "str", ",", "Path", "]", "=", "'.'", ",", "show_progress", ":", "bool", "=", "False", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'GET'", ",", "'/kernel/{}/download'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "set_json", "(", "{", "'files'", ":", "[", "*", "map", "(", "str", ",", "files", ")", "]", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "chunk_size", "=", "1", "*", "1024", "file_names", "=", "None", "tqdm_obj", "=", "tqdm", "(", "desc", "=", "'Downloading files'", ",", "unit", "=", "'bytes'", ",", "unit_scale", "=", "True", ",", "total", "=", "resp", ".", "content", ".", "total_bytes", ",", "disable", "=", "not", "show_progress", ")", "with", "tqdm_obj", "as", "pbar", ":", "fp", "=", "None", "while", "True", ":", "chunk", "=", "await", "resp", ".", "aread", "(", "chunk_size", ")", "if", "not", "chunk", ":", "break", "pbar", ".", "update", "(", "len", "(", "chunk", ")", ")", "# TODO: more elegant parsing of multipart response?", "for", "part", "in", "chunk", ".", "split", "(", "b'\\r\\n'", ")", ":", "if", "part", ".", "startswith", "(", "b'--'", ")", ":", "if", "fp", ":", "fp", ".", "close", "(", ")", "with", "tarfile", ".", "open", "(", "fp", ".", "name", ")", "as", "tarf", ":", "tarf", ".", "extractall", "(", "path", "=", "dest", ")", "file_names", "=", "tarf", ".", "getnames", "(", ")", "os", ".", "unlink", "(", "fp", ".", "name", ")", "fp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.tar'", ",", "delete", "=", "False", ")", "elif", "part", ".", "startswith", "(", "b'Content-'", ")", "or", "part", "==", "b''", ":", "continue", "else", ":", "fp", ".", "write", "(", "part", ")", "if", "fp", ":", "fp", ".", "close", "(", ")", "os", ".", "unlink", "(", "fp", ".", "name", ")", "result", "=", "{", "'file_names'", ":", "file_names", "}", "return", "result" ]
Downloads the given list of files from the compute session. :param files: The list of file paths in the compute session. If they are relative paths, the path is calculated from ``/home/work`` in the compute session container. :param dest: The destination directory in the client-side. :param show_progress: Displays a progress bar during downloads.
[ "Downloads", "the", "given", "list", "of", "files", "from", "the", "compute", "session", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L364-L418
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.list_files
async def list_files(self, path: Union[str, Path] = '.'): ''' Gets the list of files in the given path inside the compute session container. :param path: The directory path in the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}/files'.format(self.kernel_id), params=params) rqst.set_json({ 'path': path, }) async with rqst.fetch() as resp: return await resp.json()
python
async def list_files(self, path: Union[str, Path] = '.'): ''' Gets the list of files in the given path inside the compute session container. :param path: The directory path in the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}/files'.format(self.kernel_id), params=params) rqst.set_json({ 'path': path, }) async with rqst.fetch() as resp: return await resp.json()
[ "async", "def", "list_files", "(", "self", ",", "path", ":", "Union", "[", "str", ",", "Path", "]", "=", "'.'", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'GET'", ",", "'/kernel/{}/files'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "set_json", "(", "{", "'path'", ":", "path", ",", "}", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "await", "resp", ".", "json", "(", ")" ]
Gets the list of files in the given path inside the compute session container. :param path: The directory path in the compute session.
[ "Gets", "the", "list", "of", "files", "in", "the", "given", "path", "inside", "the", "compute", "session", "container", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L421-L438
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.stream_pty
def stream_pty(self) -> 'StreamPty': ''' Opens a pseudo-terminal of the kernel (if supported) streamed via websockets. :returns: a :class:`StreamPty` object. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key request = Request(self.session, 'GET', '/stream/kernel/{}/pty'.format(self.kernel_id), params=params) return request.connect_websocket(response_cls=StreamPty)
python
def stream_pty(self) -> 'StreamPty': ''' Opens a pseudo-terminal of the kernel (if supported) streamed via websockets. :returns: a :class:`StreamPty` object. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key request = Request(self.session, 'GET', '/stream/kernel/{}/pty'.format(self.kernel_id), params=params) return request.connect_websocket(response_cls=StreamPty)
[ "def", "stream_pty", "(", "self", ")", "->", "'StreamPty'", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "request", "=", "Request", "(", "self", ".", "session", ",", "'GET'", ",", "'/stream/kernel/{}/pty'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "return", "request", ".", "connect_websocket", "(", "response_cls", "=", "StreamPty", ")" ]
Opens a pseudo-terminal of the kernel (if supported) streamed via websockets. :returns: a :class:`StreamPty` object.
[ "Opens", "a", "pseudo", "-", "terminal", "of", "the", "kernel", "(", "if", "supported", ")", "streamed", "via", "websockets", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L441-L454
train
lablup/backend.ai-client-py
src/ai/backend/client/kernel.py
Kernel.stream_execute
def stream_execute(self, code: str = '', *, mode: str = 'query', opts: dict = None) -> WebSocketResponse: ''' Executes a code snippet in the streaming mode. Since the returned websocket represents a run loop, there is no need to specify *run_id* explicitly. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key opts = {} if opts is None else opts if mode == 'query': opts = {} elif mode == 'batch': opts = { 'clean': opts.get('clean', None), 'build': opts.get('build', None), 'buildLog': bool(opts.get('buildLog', False)), 'exec': opts.get('exec', None), } else: msg = 'Invalid stream-execution mode: {0}'.format(mode) raise BackendClientError(msg) request = Request(self.session, 'GET', '/stream/kernel/{}/execute'.format(self.kernel_id), params=params) async def send_code(ws): await ws.send_json({ 'code': code, 'mode': mode, 'options': opts, }) return request.connect_websocket(on_enter=send_code)
python
def stream_execute(self, code: str = '', *, mode: str = 'query', opts: dict = None) -> WebSocketResponse: ''' Executes a code snippet in the streaming mode. Since the returned websocket represents a run loop, there is no need to specify *run_id* explicitly. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key opts = {} if opts is None else opts if mode == 'query': opts = {} elif mode == 'batch': opts = { 'clean': opts.get('clean', None), 'build': opts.get('build', None), 'buildLog': bool(opts.get('buildLog', False)), 'exec': opts.get('exec', None), } else: msg = 'Invalid stream-execution mode: {0}'.format(mode) raise BackendClientError(msg) request = Request(self.session, 'GET', '/stream/kernel/{}/execute'.format(self.kernel_id), params=params) async def send_code(ws): await ws.send_json({ 'code': code, 'mode': mode, 'options': opts, }) return request.connect_websocket(on_enter=send_code)
[ "def", "stream_execute", "(", "self", ",", "code", ":", "str", "=", "''", ",", "*", ",", "mode", ":", "str", "=", "'query'", ",", "opts", ":", "dict", "=", "None", ")", "->", "WebSocketResponse", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "opts", "=", "{", "}", "if", "opts", "is", "None", "else", "opts", "if", "mode", "==", "'query'", ":", "opts", "=", "{", "}", "elif", "mode", "==", "'batch'", ":", "opts", "=", "{", "'clean'", ":", "opts", ".", "get", "(", "'clean'", ",", "None", ")", ",", "'build'", ":", "opts", ".", "get", "(", "'build'", ",", "None", ")", ",", "'buildLog'", ":", "bool", "(", "opts", ".", "get", "(", "'buildLog'", ",", "False", ")", ")", ",", "'exec'", ":", "opts", ".", "get", "(", "'exec'", ",", "None", ")", ",", "}", "else", ":", "msg", "=", "'Invalid stream-execution mode: {0}'", ".", "format", "(", "mode", ")", "raise", "BackendClientError", "(", "msg", ")", "request", "=", "Request", "(", "self", ".", "session", ",", "'GET'", ",", "'/stream/kernel/{}/execute'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "async", "def", "send_code", "(", "ws", ")", ":", "await", "ws", ".", "send_json", "(", "{", "'code'", ":", "code", ",", "'mode'", ":", "mode", ",", "'options'", ":", "opts", ",", "}", ")", "return", "request", ".", "connect_websocket", "(", "on_enter", "=", "send_code", ")" ]
Executes a code snippet in the streaming mode. Since the returned websocket represents a run loop, there is no need to specify *run_id* explicitly.
[ "Executes", "a", "code", "snippet", "in", "the", "streaming", "mode", ".", "Since", "the", "returned", "websocket", "represents", "a", "run", "loop", "there", "is", "no", "need", "to", "specify", "*", "run_id", "*", "explicitly", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L457-L492
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
init_interface
def init_interface(): sys.stdout = LoggerWriter(LOGGER.debug) sys.stderr = LoggerWriter(LOGGER.error) """ Grab the ~/.polyglot/.env file for variables If you are running Polyglot v2 on this same machine then it should already exist. If not create it. """ warnings.simplefilter('error', UserWarning) try: load_dotenv(join(expanduser("~") + '/.polyglot/.env')) except (UserWarning) as err: LOGGER.warning('File does not exist: {}.'.format(join(expanduser("~") + '/.polyglot/.env')), exc_info=True) # sys.exit(1) warnings.resetwarnings() """ If this NodeServer is co-resident with Polyglot it will receive a STDIN config on startup that looks like: {"token":"2cb40e507253fc8f4cbbe247089b28db79d859cbed700ec151", "mqttHost":"localhost","mqttPort":"1883","profileNum":"10"} """ init = select.select([sys.stdin], [], [], 1)[0] if init: line = sys.stdin.readline() try: line = json.loads(line) os.environ['PROFILE_NUM'] = line['profileNum'] os.environ['MQTT_HOST'] = line['mqttHost'] os.environ['MQTT_PORT'] = line['mqttPort'] os.environ['TOKEN'] = line['token'] LOGGER.info('Received Config from STDIN.') except (Exception) as err: # e = sys.exc_info()[0] LOGGER.error('Invalid formatted input. Skipping. %s', err, exc_info=True)
python
def init_interface(): sys.stdout = LoggerWriter(LOGGER.debug) sys.stderr = LoggerWriter(LOGGER.error) """ Grab the ~/.polyglot/.env file for variables If you are running Polyglot v2 on this same machine then it should already exist. If not create it. """ warnings.simplefilter('error', UserWarning) try: load_dotenv(join(expanduser("~") + '/.polyglot/.env')) except (UserWarning) as err: LOGGER.warning('File does not exist: {}.'.format(join(expanduser("~") + '/.polyglot/.env')), exc_info=True) # sys.exit(1) warnings.resetwarnings() """ If this NodeServer is co-resident with Polyglot it will receive a STDIN config on startup that looks like: {"token":"2cb40e507253fc8f4cbbe247089b28db79d859cbed700ec151", "mqttHost":"localhost","mqttPort":"1883","profileNum":"10"} """ init = select.select([sys.stdin], [], [], 1)[0] if init: line = sys.stdin.readline() try: line = json.loads(line) os.environ['PROFILE_NUM'] = line['profileNum'] os.environ['MQTT_HOST'] = line['mqttHost'] os.environ['MQTT_PORT'] = line['mqttPort'] os.environ['TOKEN'] = line['token'] LOGGER.info('Received Config from STDIN.') except (Exception) as err: # e = sys.exc_info()[0] LOGGER.error('Invalid formatted input. Skipping. %s', err, exc_info=True)
[ "def", "init_interface", "(", ")", ":", "sys", ".", "stdout", "=", "LoggerWriter", "(", "LOGGER", ".", "debug", ")", "sys", ".", "stderr", "=", "LoggerWriter", "(", "LOGGER", ".", "error", ")", "warnings", ".", "simplefilter", "(", "'error'", ",", "UserWarning", ")", "try", ":", "load_dotenv", "(", "join", "(", "expanduser", "(", "\"~\"", ")", "+", "'/.polyglot/.env'", ")", ")", "except", "(", "UserWarning", ")", "as", "err", ":", "LOGGER", ".", "warning", "(", "'File does not exist: {}.'", ".", "format", "(", "join", "(", "expanduser", "(", "\"~\"", ")", "+", "'/.polyglot/.env'", ")", ")", ",", "exc_info", "=", "True", ")", "# sys.exit(1)", "warnings", ".", "resetwarnings", "(", ")", "\"\"\"\n If this NodeServer is co-resident with Polyglot it will receive a STDIN config on startup\n that looks like:\n {\"token\":\"2cb40e507253fc8f4cbbe247089b28db79d859cbed700ec151\",\n \"mqttHost\":\"localhost\",\"mqttPort\":\"1883\",\"profileNum\":\"10\"}\n \"\"\"", "init", "=", "select", ".", "select", "(", "[", "sys", ".", "stdin", "]", ",", "[", "]", ",", "[", "]", ",", "1", ")", "[", "0", "]", "if", "init", ":", "line", "=", "sys", ".", "stdin", ".", "readline", "(", ")", "try", ":", "line", "=", "json", ".", "loads", "(", "line", ")", "os", ".", "environ", "[", "'PROFILE_NUM'", "]", "=", "line", "[", "'profileNum'", "]", "os", ".", "environ", "[", "'MQTT_HOST'", "]", "=", "line", "[", "'mqttHost'", "]", "os", ".", "environ", "[", "'MQTT_PORT'", "]", "=", "line", "[", "'mqttPort'", "]", "os", ".", "environ", "[", "'TOKEN'", "]", "=", "line", "[", "'token'", "]", "LOGGER", ".", "info", "(", "'Received Config from STDIN.'", ")", "except", "(", "Exception", ")", "as", "err", ":", "# e = sys.exc_info()[0]", "LOGGER", ".", "error", "(", "'Invalid formatted input. Skipping. %s'", ",", "err", ",", "exc_info", "=", "True", ")" ]
Grab the ~/.polyglot/.env file for variables If you are running Polyglot v2 on this same machine then it should already exist. If not create it.
[ "Grab", "the", "~", "/", ".", "polyglot", "/", ".", "env", "file", "for", "variables", "If", "you", "are", "running", "Polyglot", "v2", "on", "this", "same", "machine", "then", "it", "should", "already", "exist", ".", "If", "not", "create", "it", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L76-L112
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._connect
def _connect(self, mqttc, userdata, flags, rc): """ The callback for when the client receives a CONNACK response from the server. Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param rc: Result code of connection, 0 = Success, anything else is a failure """ if rc == 0: self.connected = True results = [] LOGGER.info("MQTT Connected with result code " + str(rc) + " (Success)") # result, mid = self._mqttc.subscribe(self.topicInput) results.append((self.topicInput, tuple(self._mqttc.subscribe(self.topicInput)))) results.append((self.topicPolyglotConnection, tuple(self._mqttc.subscribe(self.topicPolyglotConnection)))) for (topic, (result, mid)) in results: if result == 0: LOGGER.info("MQTT Subscribing to topic: " + topic + " - " + " MID: " + str(mid) + " Result: " + str(result)) else: LOGGER.info("MQTT Subscription to " + topic + " failed. This is unusual. MID: " + str(mid) + " Result: " + str(result)) # If subscription fails, try to reconnect. self._mqttc.reconnect() self._mqttc.publish(self.topicSelfConnection, json.dumps( { 'connected': True, 'node': self.profileNum }), retain=True) LOGGER.info('Sent Connected message to Polyglot') else: LOGGER.error("MQTT Failed to connect. Result code: " + str(rc))
python
def _connect(self, mqttc, userdata, flags, rc): """ The callback for when the client receives a CONNACK response from the server. Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param rc: Result code of connection, 0 = Success, anything else is a failure """ if rc == 0: self.connected = True results = [] LOGGER.info("MQTT Connected with result code " + str(rc) + " (Success)") # result, mid = self._mqttc.subscribe(self.topicInput) results.append((self.topicInput, tuple(self._mqttc.subscribe(self.topicInput)))) results.append((self.topicPolyglotConnection, tuple(self._mqttc.subscribe(self.topicPolyglotConnection)))) for (topic, (result, mid)) in results: if result == 0: LOGGER.info("MQTT Subscribing to topic: " + topic + " - " + " MID: " + str(mid) + " Result: " + str(result)) else: LOGGER.info("MQTT Subscription to " + topic + " failed. This is unusual. MID: " + str(mid) + " Result: " + str(result)) # If subscription fails, try to reconnect. self._mqttc.reconnect() self._mqttc.publish(self.topicSelfConnection, json.dumps( { 'connected': True, 'node': self.profileNum }), retain=True) LOGGER.info('Sent Connected message to Polyglot') else: LOGGER.error("MQTT Failed to connect. Result code: " + str(rc))
[ "def", "_connect", "(", "self", ",", "mqttc", ",", "userdata", ",", "flags", ",", "rc", ")", ":", "if", "rc", "==", "0", ":", "self", ".", "connected", "=", "True", "results", "=", "[", "]", "LOGGER", ".", "info", "(", "\"MQTT Connected with result code \"", "+", "str", "(", "rc", ")", "+", "\" (Success)\"", ")", "# result, mid = self._mqttc.subscribe(self.topicInput)", "results", ".", "append", "(", "(", "self", ".", "topicInput", ",", "tuple", "(", "self", ".", "_mqttc", ".", "subscribe", "(", "self", ".", "topicInput", ")", ")", ")", ")", "results", ".", "append", "(", "(", "self", ".", "topicPolyglotConnection", ",", "tuple", "(", "self", ".", "_mqttc", ".", "subscribe", "(", "self", ".", "topicPolyglotConnection", ")", ")", ")", ")", "for", "(", "topic", ",", "(", "result", ",", "mid", ")", ")", "in", "results", ":", "if", "result", "==", "0", ":", "LOGGER", ".", "info", "(", "\"MQTT Subscribing to topic: \"", "+", "topic", "+", "\" - \"", "+", "\" MID: \"", "+", "str", "(", "mid", ")", "+", "\" Result: \"", "+", "str", "(", "result", ")", ")", "else", ":", "LOGGER", ".", "info", "(", "\"MQTT Subscription to \"", "+", "topic", "+", "\" failed. This is unusual. MID: \"", "+", "str", "(", "mid", ")", "+", "\" Result: \"", "+", "str", "(", "result", ")", ")", "# If subscription fails, try to reconnect.", "self", ".", "_mqttc", ".", "reconnect", "(", ")", "self", ".", "_mqttc", ".", "publish", "(", "self", ".", "topicSelfConnection", ",", "json", ".", "dumps", "(", "{", "'connected'", ":", "True", ",", "'node'", ":", "self", ".", "profileNum", "}", ")", ",", "retain", "=", "True", ")", "LOGGER", ".", "info", "(", "'Sent Connected message to Polyglot'", ")", "else", ":", "LOGGER", ".", "error", "(", "\"MQTT Failed to connect. Result code: \"", "+", "str", "(", "rc", ")", ")" ]
The callback for when the client receives a CONNACK response from the server. Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param rc: Result code of connection, 0 = Success, anything else is a failure
[ "The", "callback", "for", "when", "the", "client", "receives", "a", "CONNACK", "response", "from", "the", "server", ".", "Subscribing", "in", "on_connect", "()", "means", "that", "if", "we", "lose", "the", "connection", "and", "reconnect", "then", "subscriptions", "will", "be", "renewed", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L207-L239
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._message
def _message(self, mqttc, userdata, msg): """ The callback for when a PUBLISH message is received from the server. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param msg: Dictionary of MQTT received message. Uses: msg.topic, msg.qos, msg.payload """ try: inputCmds = ['query', 'command', 'result', 'status', 'shortPoll', 'longPoll', 'delete'] parsed_msg = json.loads(msg.payload.decode('utf-8')) if 'node' in parsed_msg: if parsed_msg['node'] != 'polyglot': return del parsed_msg['node'] for key in parsed_msg: # LOGGER.debug('MQTT Received Message: {}: {}'.format(msg.topic, parsed_msg)) if key == 'config': self.inConfig(parsed_msg[key]) elif key == 'connected': self.polyglotConnected = parsed_msg[key] elif key == 'stop': LOGGER.debug('Received stop from Polyglot... Shutting Down.') self.stop() elif key in inputCmds: self.input(parsed_msg) else: LOGGER.error('Invalid command received in message from Polyglot: {}'.format(key)) except (ValueError) as err: LOGGER.error('MQTT Received Payload Error: {}'.format(err), exc_info=True)
python
def _message(self, mqttc, userdata, msg): """ The callback for when a PUBLISH message is received from the server. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param msg: Dictionary of MQTT received message. Uses: msg.topic, msg.qos, msg.payload """ try: inputCmds = ['query', 'command', 'result', 'status', 'shortPoll', 'longPoll', 'delete'] parsed_msg = json.loads(msg.payload.decode('utf-8')) if 'node' in parsed_msg: if parsed_msg['node'] != 'polyglot': return del parsed_msg['node'] for key in parsed_msg: # LOGGER.debug('MQTT Received Message: {}: {}'.format(msg.topic, parsed_msg)) if key == 'config': self.inConfig(parsed_msg[key]) elif key == 'connected': self.polyglotConnected = parsed_msg[key] elif key == 'stop': LOGGER.debug('Received stop from Polyglot... Shutting Down.') self.stop() elif key in inputCmds: self.input(parsed_msg) else: LOGGER.error('Invalid command received in message from Polyglot: {}'.format(key)) except (ValueError) as err: LOGGER.error('MQTT Received Payload Error: {}'.format(err), exc_info=True)
[ "def", "_message", "(", "self", ",", "mqttc", ",", "userdata", ",", "msg", ")", ":", "try", ":", "inputCmds", "=", "[", "'query'", ",", "'command'", ",", "'result'", ",", "'status'", ",", "'shortPoll'", ",", "'longPoll'", ",", "'delete'", "]", "parsed_msg", "=", "json", ".", "loads", "(", "msg", ".", "payload", ".", "decode", "(", "'utf-8'", ")", ")", "if", "'node'", "in", "parsed_msg", ":", "if", "parsed_msg", "[", "'node'", "]", "!=", "'polyglot'", ":", "return", "del", "parsed_msg", "[", "'node'", "]", "for", "key", "in", "parsed_msg", ":", "# LOGGER.debug('MQTT Received Message: {}: {}'.format(msg.topic, parsed_msg))", "if", "key", "==", "'config'", ":", "self", ".", "inConfig", "(", "parsed_msg", "[", "key", "]", ")", "elif", "key", "==", "'connected'", ":", "self", ".", "polyglotConnected", "=", "parsed_msg", "[", "key", "]", "elif", "key", "==", "'stop'", ":", "LOGGER", ".", "debug", "(", "'Received stop from Polyglot... Shutting Down.'", ")", "self", ".", "stop", "(", ")", "elif", "key", "in", "inputCmds", ":", "self", ".", "input", "(", "parsed_msg", ")", "else", ":", "LOGGER", ".", "error", "(", "'Invalid command received in message from Polyglot: {}'", ".", "format", "(", "key", ")", ")", "except", "(", "ValueError", ")", "as", "err", ":", "LOGGER", ".", "error", "(", "'MQTT Received Payload Error: {}'", ".", "format", "(", "err", ")", ",", "exc_info", "=", "True", ")" ]
The callback for when a PUBLISH message is received from the server. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param msg: Dictionary of MQTT received message. Uses: msg.topic, msg.qos, msg.payload
[ "The", "callback", "for", "when", "a", "PUBLISH", "message", "is", "received", "from", "the", "server", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L241-L272
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._disconnect
def _disconnect(self, mqttc, userdata, rc): """ The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean """ self.connected = False if rc != 0: LOGGER.info("MQTT Unexpected disconnection. Trying reconnect.") try: self._mqttc.reconnect() except Exception as ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) LOGGER.error("MQTT Connection error: " + message) else: LOGGER.info("MQTT Graceful disconnection.")
python
def _disconnect(self, mqttc, userdata, rc): """ The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean """ self.connected = False if rc != 0: LOGGER.info("MQTT Unexpected disconnection. Trying reconnect.") try: self._mqttc.reconnect() except Exception as ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) LOGGER.error("MQTT Connection error: " + message) else: LOGGER.info("MQTT Graceful disconnection.")
[ "def", "_disconnect", "(", "self", ",", "mqttc", ",", "userdata", ",", "rc", ")", ":", "self", ".", "connected", "=", "False", "if", "rc", "!=", "0", ":", "LOGGER", ".", "info", "(", "\"MQTT Unexpected disconnection. Trying reconnect.\"", ")", "try", ":", "self", ".", "_mqttc", ".", "reconnect", "(", ")", "except", "Exception", "as", "ex", ":", "template", "=", "\"An exception of type {0} occured. Arguments:\\n{1!r}\"", "message", "=", "template", ".", "format", "(", "type", "(", "ex", ")", ".", "__name__", ",", "ex", ".", "args", ")", "LOGGER", ".", "error", "(", "\"MQTT Connection error: \"", "+", "message", ")", "else", ":", "LOGGER", ".", "info", "(", "\"MQTT Graceful disconnection.\"", ")" ]
The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean
[ "The", "callback", "for", "when", "a", "DISCONNECT", "occurs", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L274-L292
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface._startMqtt
def _startMqtt(self): """ The client start method. Starts the thread for the MQTT Client and publishes the connected message. """ LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port)) try: # self._mqttc.connect_async(str(self._server), int(self._port), 10) self._mqttc.connect_async('{}'.format(self._server), int(self._port), 10) self._mqttc.loop_forever() except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) LOGGER.error("MQTT Connection error: {}".format(message), exc_info=True)
python
def _startMqtt(self): """ The client start method. Starts the thread for the MQTT Client and publishes the connected message. """ LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port)) try: # self._mqttc.connect_async(str(self._server), int(self._port), 10) self._mqttc.connect_async('{}'.format(self._server), int(self._port), 10) self._mqttc.loop_forever() except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) LOGGER.error("MQTT Connection error: {}".format(message), exc_info=True)
[ "def", "_startMqtt", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'Connecting to MQTT... {}:{}'", ".", "format", "(", "self", ".", "_server", ",", "self", ".", "_port", ")", ")", "try", ":", "# self._mqttc.connect_async(str(self._server), int(self._port), 10)", "self", ".", "_mqttc", ".", "connect_async", "(", "'{}'", ".", "format", "(", "self", ".", "_server", ")", ",", "int", "(", "self", ".", "_port", ")", ",", "10", ")", "self", ".", "_mqttc", ".", "loop_forever", "(", ")", "except", "Exception", "as", "ex", ":", "template", "=", "\"An exception of type {0} occurred. Arguments:\\n{1!r}\"", "message", "=", "template", ".", "format", "(", "type", "(", "ex", ")", ".", "__name__", ",", "ex", ".", "args", ")", "LOGGER", ".", "error", "(", "\"MQTT Connection error: {}\"", ".", "format", "(", "message", ")", ",", "exc_info", "=", "True", ")" ]
The client start method. Starts the thread for the MQTT Client and publishes the connected message.
[ "The", "client", "start", "method", ".", "Starts", "the", "thread", "for", "the", "MQTT", "Client", "and", "publishes", "the", "connected", "message", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L313-L326
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.stop
def stop(self): """ The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdown. """ # self.loop.call_soon_threadsafe(self.loop.stop) # self.loop.stop() # self._longPoll.cancel() # self._shortPoll.cancel() if self.connected: LOGGER.info('Disconnecting from MQTT... {}:{}'.format(self._server, self._port)) self._mqttc.publish(self.topicSelfConnection, json.dumps({'node': self.profileNum, 'connected': False}), retain=True) self._mqttc.loop_stop() self._mqttc.disconnect() try: for watcher in self.__stopObservers: watcher() except KeyError as e: LOGGER.exception('KeyError in gotConfig: {}'.format(e), exc_info=True)
python
def stop(self): """ The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdown. """ # self.loop.call_soon_threadsafe(self.loop.stop) # self.loop.stop() # self._longPoll.cancel() # self._shortPoll.cancel() if self.connected: LOGGER.info('Disconnecting from MQTT... {}:{}'.format(self._server, self._port)) self._mqttc.publish(self.topicSelfConnection, json.dumps({'node': self.profileNum, 'connected': False}), retain=True) self._mqttc.loop_stop() self._mqttc.disconnect() try: for watcher in self.__stopObservers: watcher() except KeyError as e: LOGGER.exception('KeyError in gotConfig: {}'.format(e), exc_info=True)
[ "def", "stop", "(", "self", ")", ":", "# self.loop.call_soon_threadsafe(self.loop.stop)", "# self.loop.stop()", "# self._longPoll.cancel()", "# self._shortPoll.cancel()", "if", "self", ".", "connected", ":", "LOGGER", ".", "info", "(", "'Disconnecting from MQTT... {}:{}'", ".", "format", "(", "self", ".", "_server", ",", "self", ".", "_port", ")", ")", "self", ".", "_mqttc", ".", "publish", "(", "self", ".", "topicSelfConnection", ",", "json", ".", "dumps", "(", "{", "'node'", ":", "self", ".", "profileNum", ",", "'connected'", ":", "False", "}", ")", ",", "retain", "=", "True", ")", "self", ".", "_mqttc", ".", "loop_stop", "(", ")", "self", ".", "_mqttc", ".", "disconnect", "(", ")", "try", ":", "for", "watcher", "in", "self", ".", "__stopObservers", ":", "watcher", "(", ")", "except", "KeyError", "as", "e", ":", "LOGGER", ".", "exception", "(", "'KeyError in gotConfig: {}'", ".", "format", "(", "e", ")", ",", "exc_info", "=", "True", ")" ]
The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdown.
[ "The", "client", "stop", "method", ".", "If", "the", "client", "is", "currently", "connected", "stop", "the", "thread", "and", "disconnect", ".", "Publish", "the", "disconnected", "message", "if", "clean", "shutdown", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L328-L347
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.send
def send(self, message): """ Formatted Message to send to Polyglot. Connection messages are sent automatically from this module so this method is used to send commands to/from Polyglot and formats it for consumption """ if not isinstance(message, dict) and self.connected: warnings.warn('payload not a dictionary') return False try: message['node'] = self.profileNum self._mqttc.publish(self.topicInput, json.dumps(message), retain=False) except TypeError as err: LOGGER.error('MQTT Send Error: {}'.format(err), exc_info=True)
python
def send(self, message): """ Formatted Message to send to Polyglot. Connection messages are sent automatically from this module so this method is used to send commands to/from Polyglot and formats it for consumption """ if not isinstance(message, dict) and self.connected: warnings.warn('payload not a dictionary') return False try: message['node'] = self.profileNum self._mqttc.publish(self.topicInput, json.dumps(message), retain=False) except TypeError as err: LOGGER.error('MQTT Send Error: {}'.format(err), exc_info=True)
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "dict", ")", "and", "self", ".", "connected", ":", "warnings", ".", "warn", "(", "'payload not a dictionary'", ")", "return", "False", "try", ":", "message", "[", "'node'", "]", "=", "self", ".", "profileNum", "self", ".", "_mqttc", ".", "publish", "(", "self", ".", "topicInput", ",", "json", ".", "dumps", "(", "message", ")", ",", "retain", "=", "False", ")", "except", "TypeError", "as", "err", ":", "LOGGER", ".", "error", "(", "'MQTT Send Error: {}'", ".", "format", "(", "err", ")", ",", "exc_info", "=", "True", ")" ]
Formatted Message to send to Polyglot. Connection messages are sent automatically from this module so this method is used to send commands to/from Polyglot and formats it for consumption
[ "Formatted", "Message", "to", "send", "to", "Polyglot", ".", "Connection", "messages", "are", "sent", "automatically", "from", "this", "module", "so", "this", "method", "is", "used", "to", "send", "commands", "to", "/", "from", "Polyglot", "and", "formats", "it", "for", "consumption" ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L349-L361
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.addNode
def addNode(self, node): """ Add a node to the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required. """ LOGGER.info('Adding node {}({})'.format(node.name, node.address)) message = { 'addnode': { 'nodes': [{ 'address': node.address, 'name': node.name, 'node_def_id': node.id, 'primary': node.primary, 'drivers': node.drivers, 'hint': node.hint }] } } self.send(message)
python
def addNode(self, node): """ Add a node to the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required. """ LOGGER.info('Adding node {}({})'.format(node.name, node.address)) message = { 'addnode': { 'nodes': [{ 'address': node.address, 'name': node.name, 'node_def_id': node.id, 'primary': node.primary, 'drivers': node.drivers, 'hint': node.hint }] } } self.send(message)
[ "def", "addNode", "(", "self", ",", "node", ")", ":", "LOGGER", ".", "info", "(", "'Adding node {}({})'", ".", "format", "(", "node", ".", "name", ",", "node", ".", "address", ")", ")", "message", "=", "{", "'addnode'", ":", "{", "'nodes'", ":", "[", "{", "'address'", ":", "node", ".", "address", ",", "'name'", ":", "node", ".", "name", ",", "'node_def_id'", ":", "node", ".", "id", ",", "'primary'", ":", "node", ".", "primary", ",", "'drivers'", ":", "node", ".", "drivers", ",", "'hint'", ":", "node", ".", "hint", "}", "]", "}", "}", "self", ".", "send", "(", "message", ")" ]
Add a node to the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
[ "Add", "a", "node", "to", "the", "NodeServer" ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L363-L382
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.saveCustomData
def saveCustomData(self, data): """ Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database. """ LOGGER.info('Sending customData to Polyglot.') message = { 'customdata': data } self.send(message)
python
def saveCustomData(self, data): """ Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database. """ LOGGER.info('Sending customData to Polyglot.') message = { 'customdata': data } self.send(message)
[ "def", "saveCustomData", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "info", "(", "'Sending customData to Polyglot.'", ")", "message", "=", "{", "'customdata'", ":", "data", "}", "self", ".", "send", "(", "message", ")" ]
Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database.
[ "Send", "custom", "dictionary", "to", "Polyglot", "to", "save", "and", "be", "retrieved", "on", "startup", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L384-L392
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.saveCustomParams
def saveCustomParams(self, data): """ Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database. """ LOGGER.info('Sending customParams to Polyglot.') message = { 'customparams': data } self.send(message)
python
def saveCustomParams(self, data): """ Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database. """ LOGGER.info('Sending customParams to Polyglot.') message = { 'customparams': data } self.send(message)
[ "def", "saveCustomParams", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "info", "(", "'Sending customParams to Polyglot.'", ")", "message", "=", "{", "'customparams'", ":", "data", "}", "self", ".", "send", "(", "message", ")" ]
Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database.
[ "Send", "custom", "dictionary", "to", "Polyglot", "to", "save", "and", "be", "retrieved", "on", "startup", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L394-L402
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.addNotice
def addNotice(self, data): """ Add custom notice to front-end for this NodeServers :param data: String of characters to add as a notification in the front-end. """ LOGGER.info('Sending addnotice to Polyglot: {}'.format(data)) message = { 'addnotice': data } self.send(message)
python
def addNotice(self, data): """ Add custom notice to front-end for this NodeServers :param data: String of characters to add as a notification in the front-end. """ LOGGER.info('Sending addnotice to Polyglot: {}'.format(data)) message = { 'addnotice': data } self.send(message)
[ "def", "addNotice", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "info", "(", "'Sending addnotice to Polyglot: {}'", ".", "format", "(", "data", ")", ")", "message", "=", "{", "'addnotice'", ":", "data", "}", "self", ".", "send", "(", "message", ")" ]
Add custom notice to front-end for this NodeServers :param data: String of characters to add as a notification in the front-end.
[ "Add", "custom", "notice", "to", "front", "-", "end", "for", "this", "NodeServers" ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L404-L412
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.removeNotice
def removeNotice(self, data): """ Add custom notice to front-end for this NodeServers :param data: Index of notices list to remove. """ LOGGER.info('Sending removenotice to Polyglot for index {}'.format(data)) message = { 'removenotice': data } self.send(message)
python
def removeNotice(self, data): """ Add custom notice to front-end for this NodeServers :param data: Index of notices list to remove. """ LOGGER.info('Sending removenotice to Polyglot for index {}'.format(data)) message = { 'removenotice': data } self.send(message)
[ "def", "removeNotice", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "info", "(", "'Sending removenotice to Polyglot for index {}'", ".", "format", "(", "data", ")", ")", "message", "=", "{", "'removenotice'", ":", "data", "}", "self", ".", "send", "(", "message", ")" ]
Add custom notice to front-end for this NodeServers :param data: Index of notices list to remove.
[ "Add", "custom", "notice", "to", "front", "-", "end", "for", "this", "NodeServers" ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L414-L422
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.delNode
def delNode(self, address): """ Delete a node from the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required. """ LOGGER.info('Removing node {}'.format(address)) message = { 'removenode': { 'address': address } } self.send(message)
python
def delNode(self, address): """ Delete a node from the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required. """ LOGGER.info('Removing node {}'.format(address)) message = { 'removenode': { 'address': address } } self.send(message)
[ "def", "delNode", "(", "self", ",", "address", ")", ":", "LOGGER", ".", "info", "(", "'Removing node {}'", ".", "format", "(", "address", ")", ")", "message", "=", "{", "'removenode'", ":", "{", "'address'", ":", "address", "}", "}", "self", ".", "send", "(", "message", ")" ]
Delete a node from the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
[ "Delete", "a", "node", "from", "the", "NodeServer" ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L439-L451
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.getNode
def getNode(self, address): """ Get Node by Address of existing nodes. """ try: for node in self.config['nodes']: if node['address'] == address: return node return False except KeyError: LOGGER.error('Usually means we have not received the config yet.', exc_info=True) return False
python
def getNode(self, address): """ Get Node by Address of existing nodes. """ try: for node in self.config['nodes']: if node['address'] == address: return node return False except KeyError: LOGGER.error('Usually means we have not received the config yet.', exc_info=True) return False
[ "def", "getNode", "(", "self", ",", "address", ")", ":", "try", ":", "for", "node", "in", "self", ".", "config", "[", "'nodes'", "]", ":", "if", "node", "[", "'address'", "]", "==", "address", ":", "return", "node", "return", "False", "except", "KeyError", ":", "LOGGER", ".", "error", "(", "'Usually means we have not received the config yet.'", ",", "exc_info", "=", "True", ")", "return", "False" ]
Get Node by Address of existing nodes.
[ "Get", "Node", "by", "Address", "of", "existing", "nodes", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L453-L464
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.inConfig
def inConfig(self, config): """ Save incoming config received from Polyglot to Interface.config and then do any functions that are waiting on the config to be received. """ self.config = config self.isyVersion = config['isyVersion'] try: for watcher in self.__configObservers: watcher(config) self.send_custom_config_docs() except KeyError as e: LOGGER.error('KeyError in gotConfig: {}'.format(e), exc_info=True)
python
def inConfig(self, config): """ Save incoming config received from Polyglot to Interface.config and then do any functions that are waiting on the config to be received. """ self.config = config self.isyVersion = config['isyVersion'] try: for watcher in self.__configObservers: watcher(config) self.send_custom_config_docs() except KeyError as e: LOGGER.error('KeyError in gotConfig: {}'.format(e), exc_info=True)
[ "def", "inConfig", "(", "self", ",", "config", ")", ":", "self", ".", "config", "=", "config", "self", ".", "isyVersion", "=", "config", "[", "'isyVersion'", "]", "try", ":", "for", "watcher", "in", "self", ".", "__configObservers", ":", "watcher", "(", "config", ")", "self", ".", "send_custom_config_docs", "(", ")", "except", "KeyError", "as", "e", ":", "LOGGER", ".", "error", "(", "'KeyError in gotConfig: {}'", ".", "format", "(", "e", ")", ",", "exc_info", "=", "True", ")" ]
Save incoming config received from Polyglot to Interface.config and then do any functions that are waiting on the config to be received.
[ "Save", "incoming", "config", "received", "from", "Polyglot", "to", "Interface", ".", "config", "and", "then", "do", "any", "functions", "that", "are", "waiting", "on", "the", "config", "to", "be", "received", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L466-L480
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Interface.save_typed_params
def save_typed_params(self, data): """ Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'. Defaults to 'STRING' desc - optional, shown in tooltip in UI isRequired - optional, True/False, when set, will not validate UI input if it's empty isList - optional, True/False, if set this will be treated as list of values or objects by UI params - optional, can contain a list of objects. If present, then this (parent) is treated as object / list of objects by UI, otherwise, it's treated as a single / list of single values """ LOGGER.info('Sending typed parameters to Polyglot.') if type(data) is not list: data = [ data ] message = { 'typedparams': data } self.send(message)
python
def save_typed_params(self, data): """ Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'. Defaults to 'STRING' desc - optional, shown in tooltip in UI isRequired - optional, True/False, when set, will not validate UI input if it's empty isList - optional, True/False, if set this will be treated as list of values or objects by UI params - optional, can contain a list of objects. If present, then this (parent) is treated as object / list of objects by UI, otherwise, it's treated as a single / list of single values """ LOGGER.info('Sending typed parameters to Polyglot.') if type(data) is not list: data = [ data ] message = { 'typedparams': data } self.send(message)
[ "def", "save_typed_params", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "info", "(", "'Sending typed parameters to Polyglot.'", ")", "if", "type", "(", "data", ")", "is", "not", "list", ":", "data", "=", "[", "data", "]", "message", "=", "{", "'typedparams'", ":", "data", "}", "self", ".", "send", "(", "message", ")" ]
Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'. Defaults to 'STRING' desc - optional, shown in tooltip in UI isRequired - optional, True/False, when set, will not validate UI input if it's empty isList - optional, True/False, if set this will be treated as list of values or objects by UI params - optional, can contain a list of objects. If present, then this (parent) is treated as object / list of objects by UI, otherwise, it's treated as a single / list of single values
[ "Send", "custom", "parameters", "descriptions", "to", "Polyglot", "to", "be", "used", "in", "front", "end", "UI", "configuration", "screen", "Accepts", "list", "of", "objects", "with", "the", "followin", "properties", "name", "-", "used", "as", "a", "key", "when", "data", "is", "sent", "from", "UI", "title", "-", "displayed", "in", "UI", "defaultValue", "-", "optionanl", "type", "-", "optional", "can", "be", "NUMBER", "STRING", "or", "BOOLEAN", ".", "Defaults", "to", "STRING", "desc", "-", "optional", "shown", "in", "tooltip", "in", "UI", "isRequired", "-", "optional", "True", "/", "False", "when", "set", "will", "not", "validate", "UI", "input", "if", "it", "s", "empty", "isList", "-", "optional", "True", "/", "False", "if", "set", "this", "will", "be", "treated", "as", "list", "of", "values", "or", "objects", "by", "UI", "params", "-", "optional", "can", "contain", "a", "list", "of", "objects", ".", "If", "present", "then", "this", "(", "parent", ")", "is", "treated", "as", "object", "/", "list", "of", "objects", "by", "UI", "otherwise", "it", "s", "treated", "as", "a", "single", "/", "list", "of", "single", "values" ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L519-L542
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
Controller.delNode
def delNode(self, address): """ Just send it along if requested, should be able to delete the node even if it isn't in our config anywhere. Usually used for normalization. """ if address in self.nodes: del self.nodes[address] self.poly.delNode(address)
python
def delNode(self, address): """ Just send it along if requested, should be able to delete the node even if it isn't in our config anywhere. Usually used for normalization. """ if address in self.nodes: del self.nodes[address] self.poly.delNode(address)
[ "def", "delNode", "(", "self", ",", "address", ")", ":", "if", "address", "in", "self", ".", "nodes", ":", "del", "self", ".", "nodes", "[", "address", "]", "self", ".", "poly", ".", "delNode", "(", "address", ")" ]
Just send it along if requested, should be able to delete the node even if it isn't in our config anywhere. Usually used for normalization.
[ "Just", "send", "it", "along", "if", "requested", "should", "be", "able", "to", "delete", "the", "node", "even", "if", "it", "isn", "t", "in", "our", "config", "anywhere", ".", "Usually", "used", "for", "normalization", "." ]
fe613135b762731a41a081222e43d2a8ae4fc53f
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L844-L851
train
lablup/backend.ai-client-py
src/ai/backend/client/admin.py
Admin.query
async def query(cls, query: str, variables: Optional[Mapping[str, Any]] = None, ) -> Any: ''' Sends the GraphQL query and returns the response. :param query: The GraphQL query string. :param variables: An optional key-value dictionary to fill the interpolated template variables in the query. :returns: The object parsed from the response JSON string. ''' gql_query = { 'query': query, 'variables': variables if variables else {}, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json(gql_query) async with rqst.fetch() as resp: return await resp.json()
python
async def query(cls, query: str, variables: Optional[Mapping[str, Any]] = None, ) -> Any: ''' Sends the GraphQL query and returns the response. :param query: The GraphQL query string. :param variables: An optional key-value dictionary to fill the interpolated template variables in the query. :returns: The object parsed from the response JSON string. ''' gql_query = { 'query': query, 'variables': variables if variables else {}, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json(gql_query) async with rqst.fetch() as resp: return await resp.json()
[ "async", "def", "query", "(", "cls", ",", "query", ":", "str", ",", "variables", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", "=", "None", ",", ")", "->", "Any", ":", "gql_query", "=", "{", "'query'", ":", "query", ",", "'variables'", ":", "variables", "if", "variables", "else", "{", "}", ",", "}", "rqst", "=", "Request", "(", "cls", ".", "session", ",", "'POST'", ",", "'/admin/graphql'", ")", "rqst", ".", "set_json", "(", "gql_query", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "await", "resp", ".", "json", "(", ")" ]
Sends the GraphQL query and returns the response. :param query: The GraphQL query string. :param variables: An optional key-value dictionary to fill the interpolated template variables in the query. :returns: The object parsed from the response JSON string.
[ "Sends", "the", "GraphQL", "query", "and", "returns", "the", "response", "." ]
a063d774fea6f4350b89498c40d3c837ec3029a7
https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/admin.py#L27-L47
train
housecanary/hc-api-python
housecanary/utilities.py
get_readable_time_string
def get_readable_time_string(seconds): """Returns human readable string from number of seconds""" seconds = int(seconds) minutes = seconds // 60 seconds = seconds % 60 hours = minutes // 60 minutes = minutes % 60 days = hours // 24 hours = hours % 24 result = "" if days > 0: result += "%d %s " % (days, "Day" if (days == 1) else "Days") if hours > 0: result += "%d %s " % (hours, "Hour" if (hours == 1) else "Hours") if minutes > 0: result += "%d %s " % (minutes, "Minute" if (minutes == 1) else "Minutes") if seconds > 0: result += "%d %s " % (seconds, "Second" if (seconds == 1) else "Seconds") return result.strip()
python
def get_readable_time_string(seconds): """Returns human readable string from number of seconds""" seconds = int(seconds) minutes = seconds // 60 seconds = seconds % 60 hours = minutes // 60 minutes = minutes % 60 days = hours // 24 hours = hours % 24 result = "" if days > 0: result += "%d %s " % (days, "Day" if (days == 1) else "Days") if hours > 0: result += "%d %s " % (hours, "Hour" if (hours == 1) else "Hours") if minutes > 0: result += "%d %s " % (minutes, "Minute" if (minutes == 1) else "Minutes") if seconds > 0: result += "%d %s " % (seconds, "Second" if (seconds == 1) else "Seconds") return result.strip()
[ "def", "get_readable_time_string", "(", "seconds", ")", ":", "seconds", "=", "int", "(", "seconds", ")", "minutes", "=", "seconds", "//", "60", "seconds", "=", "seconds", "%", "60", "hours", "=", "minutes", "//", "60", "minutes", "=", "minutes", "%", "60", "days", "=", "hours", "//", "24", "hours", "=", "hours", "%", "24", "result", "=", "\"\"", "if", "days", ">", "0", ":", "result", "+=", "\"%d %s \"", "%", "(", "days", ",", "\"Day\"", "if", "(", "days", "==", "1", ")", "else", "\"Days\"", ")", "if", "hours", ">", "0", ":", "result", "+=", "\"%d %s \"", "%", "(", "hours", ",", "\"Hour\"", "if", "(", "hours", "==", "1", ")", "else", "\"Hours\"", ")", "if", "minutes", ">", "0", ":", "result", "+=", "\"%d %s \"", "%", "(", "minutes", ",", "\"Minute\"", "if", "(", "minutes", "==", "1", ")", "else", "\"Minutes\"", ")", "if", "seconds", ">", "0", ":", "result", "+=", "\"%d %s \"", "%", "(", "seconds", ",", "\"Second\"", "if", "(", "seconds", "==", "1", ")", "else", "\"Seconds\"", ")", "return", "result", ".", "strip", "(", ")" ]
Returns human readable string from number of seconds
[ "Returns", "human", "readable", "string", "from", "number", "of", "seconds" ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/utilities.py#L6-L26
train
housecanary/hc-api-python
housecanary/utilities.py
get_rate_limits
def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.headers['X-RateLimit-Limit'].split(',') remaining = response.headers['X-RateLimit-Remaining'].split(',') reset = response.headers['X-RateLimit-Reset'].split(',') for idx, period in enumerate(periods): rate_limit = {} limit_period = get_readable_time_string(period) rate_limit["period"] = limit_period rate_limit["period_seconds"] = period rate_limit["request_limit"] = limits[idx] rate_limit["requests_remaining"] = remaining[idx] reset_datetime = get_datetime_from_timestamp(reset[idx]) rate_limit["reset"] = reset_datetime right_now = datetime.now() if (reset_datetime is not None) and (right_now < reset_datetime): # add 1 second because of rounding seconds_remaining = (reset_datetime - right_now).seconds + 1 else: seconds_remaining = 0 rate_limit["reset_in_seconds"] = seconds_remaining rate_limit["time_to_reset"] = get_readable_time_string(seconds_remaining) rate_limits.append(rate_limit) return rate_limits
python
def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.headers['X-RateLimit-Limit'].split(',') remaining = response.headers['X-RateLimit-Remaining'].split(',') reset = response.headers['X-RateLimit-Reset'].split(',') for idx, period in enumerate(periods): rate_limit = {} limit_period = get_readable_time_string(period) rate_limit["period"] = limit_period rate_limit["period_seconds"] = period rate_limit["request_limit"] = limits[idx] rate_limit["requests_remaining"] = remaining[idx] reset_datetime = get_datetime_from_timestamp(reset[idx]) rate_limit["reset"] = reset_datetime right_now = datetime.now() if (reset_datetime is not None) and (right_now < reset_datetime): # add 1 second because of rounding seconds_remaining = (reset_datetime - right_now).seconds + 1 else: seconds_remaining = 0 rate_limit["reset_in_seconds"] = seconds_remaining rate_limit["time_to_reset"] = get_readable_time_string(seconds_remaining) rate_limits.append(rate_limit) return rate_limits
[ "def", "get_rate_limits", "(", "response", ")", ":", "periods", "=", "response", ".", "headers", "[", "'X-RateLimit-Period'", "]", "if", "not", "periods", ":", "return", "[", "]", "rate_limits", "=", "[", "]", "periods", "=", "periods", ".", "split", "(", "','", ")", "limits", "=", "response", ".", "headers", "[", "'X-RateLimit-Limit'", "]", ".", "split", "(", "','", ")", "remaining", "=", "response", ".", "headers", "[", "'X-RateLimit-Remaining'", "]", ".", "split", "(", "','", ")", "reset", "=", "response", ".", "headers", "[", "'X-RateLimit-Reset'", "]", ".", "split", "(", "','", ")", "for", "idx", ",", "period", "in", "enumerate", "(", "periods", ")", ":", "rate_limit", "=", "{", "}", "limit_period", "=", "get_readable_time_string", "(", "period", ")", "rate_limit", "[", "\"period\"", "]", "=", "limit_period", "rate_limit", "[", "\"period_seconds\"", "]", "=", "period", "rate_limit", "[", "\"request_limit\"", "]", "=", "limits", "[", "idx", "]", "rate_limit", "[", "\"requests_remaining\"", "]", "=", "remaining", "[", "idx", "]", "reset_datetime", "=", "get_datetime_from_timestamp", "(", "reset", "[", "idx", "]", ")", "rate_limit", "[", "\"reset\"", "]", "=", "reset_datetime", "right_now", "=", "datetime", ".", "now", "(", ")", "if", "(", "reset_datetime", "is", "not", "None", ")", "and", "(", "right_now", "<", "reset_datetime", ")", ":", "# add 1 second because of rounding", "seconds_remaining", "=", "(", "reset_datetime", "-", "right_now", ")", ".", "seconds", "+", "1", "else", ":", "seconds_remaining", "=", "0", "rate_limit", "[", "\"reset_in_seconds\"", "]", "=", "seconds_remaining", "rate_limit", "[", "\"time_to_reset\"", "]", "=", "get_readable_time_string", "(", "seconds_remaining", ")", "rate_limits", ".", "append", "(", "rate_limit", ")", "return", "rate_limits" ]
Returns a list of rate limit information from a given response's headers.
[ "Returns", "a", "list", "of", "rate", "limit", "information", "from", "a", "given", "response", "s", "headers", "." ]
2bb9e2208b34e8617575de45934357ee33b8531c
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/utilities.py#L37-L73
train
Tygs/ww
src/ww/wrappers/dicts.py
DictWrapper.isubset
def isubset(self, *keys): # type: (*Hashable) -> ww.g """Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3)) [(1, 1), (3, 3)] """ return ww.g((key, self[key]) for key in keys)
python
def isubset(self, *keys): # type: (*Hashable) -> ww.g """Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3)) [(1, 1), (3, 3)] """ return ww.g((key, self[key]) for key in keys)
[ "def", "isubset", "(", "self", ",", "*", "keys", ")", ":", "# type: (*Hashable) -> ww.g", "return", "ww", ".", "g", "(", "(", "key", ",", "self", "[", "key", "]", ")", "for", "key", "in", "keys", ")" ]
Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3)) [(1, 1), (3, 3)]
[ "Return", "key", "self", "[", "key", "]", "as", "generator", "for", "key", "in", "keys", "." ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/wrappers/dicts.py#L18-L33
train
Tygs/ww
src/ww/wrappers/dicts.py
DictWrapper.swap
def swap(self): # type: () -> DictWrapper """Swap key and value /!\ Be carreful, if there are duplicate values, only one will survive /!\ Example: >>> from ww import d >>> d({1: 2, 2: 2, 3: 3}).swap() {2: 2, 3: 3} """ return self.__class__((v, k) for k, v in self.items())
python
def swap(self): # type: () -> DictWrapper """Swap key and value /!\ Be carreful, if there are duplicate values, only one will survive /!\ Example: >>> from ww import d >>> d({1: 2, 2: 2, 3: 3}).swap() {2: 2, 3: 3} """ return self.__class__((v, k) for k, v in self.items())
[ "def", "swap", "(", "self", ")", ":", "# type: () -> DictWrapper", "return", "self", ".", "__class__", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ")" ]
Swap key and value /!\ Be carreful, if there are duplicate values, only one will survive /!\ Example: >>> from ww import d >>> d({1: 2, 2: 2, 3: 3}).swap() {2: 2, 3: 3}
[ "Swap", "key", "and", "value" ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/wrappers/dicts.py#L52-L65
train
Tygs/ww
src/ww/wrappers/dicts.py
DictWrapper.fromkeys
def fromkeys(cls, iterable, value=None): # TODO : type: (Iterable, Union[Any, Callable]) -> DictWrapper # https://github.com/python/mypy/issues/2254 """Create a new d from Args: iterable: Iterable containing keys value: value to associate with each key. If callable, will be value[key] Returns: new DictWrapper Example: >>> from ww import d >>> sorted(d.fromkeys('123', value=4).items()) [('1', 4), ('2', 4), ('3', 4)] >>> sorted(d.fromkeys(range(3), value=lambda e:e**2).items()) [(0, 0), (1, 1), (2, 4)] """ if not callable(value): return cls(dict.fromkeys(iterable, value)) return cls((key, value(key)) for key in iterable)
python
def fromkeys(cls, iterable, value=None): # TODO : type: (Iterable, Union[Any, Callable]) -> DictWrapper # https://github.com/python/mypy/issues/2254 """Create a new d from Args: iterable: Iterable containing keys value: value to associate with each key. If callable, will be value[key] Returns: new DictWrapper Example: >>> from ww import d >>> sorted(d.fromkeys('123', value=4).items()) [('1', 4), ('2', 4), ('3', 4)] >>> sorted(d.fromkeys(range(3), value=lambda e:e**2).items()) [(0, 0), (1, 1), (2, 4)] """ if not callable(value): return cls(dict.fromkeys(iterable, value)) return cls((key, value(key)) for key in iterable)
[ "def", "fromkeys", "(", "cls", ",", "iterable", ",", "value", "=", "None", ")", ":", "# TODO : type: (Iterable, Union[Any, Callable]) -> DictWrapper", "# https://github.com/python/mypy/issues/2254", "if", "not", "callable", "(", "value", ")", ":", "return", "cls", "(", "dict", ".", "fromkeys", "(", "iterable", ",", "value", ")", ")", "return", "cls", "(", "(", "key", ",", "value", "(", "key", ")", ")", "for", "key", "in", "iterable", ")" ]
Create a new d from Args: iterable: Iterable containing keys value: value to associate with each key. If callable, will be value[key] Returns: new DictWrapper Example: >>> from ww import d >>> sorted(d.fromkeys('123', value=4).items()) [('1', 4), ('2', 4), ('3', 4)] >>> sorted(d.fromkeys(range(3), value=lambda e:e**2).items()) [(0, 0), (1, 1), (2, 4)]
[ "Create", "a", "new", "d", "from" ]
6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4
https://github.com/Tygs/ww/blob/6a4b85141c9b74026abe8f3fa9bc7021f3c99fd4/src/ww/wrappers/dicts.py#L94-L117
train