idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
6,300
def _get_showcase_dataset_dict ( self , dataset ) : if isinstance ( dataset , hdx . data . dataset . Dataset ) or isinstance ( dataset , dict ) : if 'id' not in dataset : dataset = hdx . data . dataset . Dataset . read_from_hdx ( dataset [ 'name' ] ) dataset = dataset [ 'id' ] elif not isinstance ( dataset , str ) : ra...
Get showcase dataset dict
6,301
def add_dataset ( self , dataset , datasets_to_check = None ) : showcase_dataset = self . _get_showcase_dataset_dict ( dataset ) if datasets_to_check is None : datasets_to_check = self . get_datasets ( ) for dataset in datasets_to_check : if showcase_dataset [ 'package_id' ] == dataset [ 'id' ] : return False self . _w...
Add a dataset
6,302
def add_datasets ( self , datasets , datasets_to_check = None ) : if datasets_to_check is None : datasets_to_check = self . get_datasets ( ) alldatasetsadded = True for dataset in datasets : if not self . add_dataset ( dataset , datasets_to_check = datasets_to_check ) : alldatasetsadded = False return alldatasetsadded
Add multiple datasets
6,303
def join ( self , joiner , formatter = lambda s , t : t . format ( s ) , template = "{}" ) : return ww . s ( joiner ) . join ( self , formatter , template )
Join values and convert to string
6,304
def append ( self , * values ) : for value in values : list . append ( self , value ) return self
Append values at the end of the list
6,305
def extend ( self , * iterables ) : for value in iterables : list . extend ( self , value ) return self
Add all values of all iterables at the end of the list
6,306
def normalize_cell_value ( value ) : if isinstance ( value , dict ) or isinstance ( value , list ) : return json . dumps ( value ) return value
Process value for writing into a cell .
6,307
def get_addresses_from_input_file ( input_file_name ) : mode = 'r' if sys . version_info [ 0 ] < 3 : mode = 'rb' with io . open ( input_file_name , mode ) as input_file : reader = csv . reader ( input_file , delimiter = ',' , quotechar = '"' ) addresses = list ( map ( tuple , reader ) ) if len ( addresses ) == 0 : rais...
Read addresses from input file into list of tuples . This only supports address and zipcode headers
6,308
def get_identifiers_from_input_file ( input_file_name ) : valid_identifiers = [ 'address' , 'zipcode' , 'unit' , 'city' , 'state' , 'slug' , 'block_id' , 'msa' , 'num_bins' , 'property_type' , 'client_value' , 'client_value_sqft' , 'meta' ] mode = 'r' if sys . version_info [ 0 ] < 3 : mode = 'rb' with io . open ( input...
Read identifiers from input file into list of dicts with the header row values as keys and the rest of the rows as values .
6,309
def delete_host_from_segment ( ipaddress , networkaddress , auth , url ) : host_id = get_host_id ( ipaddress , networkaddress , auth , url ) remove_scope_ip ( host_id , auth . creds , auth . url )
Function to abstract
6,310
def generate_signature ( method , version , endpoint , date , rel_url , content_type , content , access_key , secret_key , hash_type ) : hash_type = hash_type hostname = endpoint . _val . netloc if version >= 'v4.20181215' : content = b'' else : if content_type . startswith ( 'multipart/' ) : content = b'' body_hash = ...
Generates the API request signature from the given parameters .
6,311
async def list_with_limit ( cls , limit , offset , status : str = 'ALIVE' , fields : Iterable [ str ] = None ) -> Sequence [ dict ] : if fields is None : fields = ( 'id' , 'addr' , 'status' , 'first_contact' , 'mem_slots' , 'cpu_slots' , 'gpu_slots' , ) q = 'query($limit: Int!, $offset: Int!, $status: String) {' ' age...
Fetches the list of agents with the given status with limit and offset for pagination .
6,312
def set_content ( self , value : RequestContent , * , content_type : str = None ) : assert self . _attached_files is None , 'cannot set content because you already attached files.' guessed_content_type = 'application/octet-stream' if value is None : guessed_content_type = 'text/plain' self . _content = b'' elif isinsta...
Sets the content of the request .
6,313
def attach_files ( self , files : Sequence [ AttachedFile ] ) : assert not self . _content , 'content must be empty to attach files.' self . content_type = 'multipart/form-data' self . _attached_files = files
Attach a list of files represented as AttachedFile .
6,314
def _sign ( self , rel_url , access_key = None , secret_key = None , hash_type = None ) : if access_key is None : access_key = self . config . access_key if secret_key is None : secret_key = self . config . secret_key if hash_type is None : hash_type = self . config . hash_type hdrs , _ = generate_signature ( self . me...
Calculates the signature of the given request and adds the Authorization HTTP header . It should be called at the very end of request preparation and before sending the request to the server .
6,315
def fetch ( self , ** kwargs ) -> 'FetchContextManager' : assert self . method in self . _allowed_methods , 'Disallowed HTTP method: {}' . format ( self . method ) self . date = datetime . now ( tzutc ( ) ) self . headers [ 'Date' ] = self . date . isoformat ( ) if self . content_type is not None : self . headers [ 'Co...
Sends the request to the server and reads the response .
6,316
def connect_websocket ( self , ** kwargs ) -> 'WebSocketContextManager' : assert isinstance ( self . session , AsyncSession ) , 'Cannot use websockets with sessions in the synchronous mode' assert self . method == 'GET' , 'Invalid websocket method' self . date = datetime . now ( tzutc ( ) ) self . headers [ 'Date' ] = ...
Creates a WebSocket connection .
6,317
def process_json_response ( self , response ) : response_json = response . json ( ) code_key = "code" if code_key in response_json and response_json [ code_key ] != constants . HTTP_CODE_OK : code = response_json [ code_key ] message = response_json if "message" in response_json : message = response_json [ "message" ] ...
For a json response check if there was any error and throw exception . Otherwise create a housecanary . response . Response .
6,318
def start_watcher_thread ( self ) : watcher_thread = threading . Thread ( target = self . run_watcher ) if self . _reload_mode == self . RELOAD_MODE_V_SPAWN_WAIT : daemon = False else : daemon = True watcher_thread . setDaemon ( daemon ) watcher_thread . start ( ) return watcher_thread
Start watcher thread .
6,319
def run_watcher ( self ) : observer = Observer ( ) observer . start ( ) watche_obj_map = { } while not self . _watcher_to_stop : old_watch_path_s = set ( watche_obj_map ) new_watch_path_s = self . _find_watch_paths ( ) for new_watch_path in new_watch_path_s : old_watch_path_s . discard ( new_watch_path ) if new_watch_p...
Watcher thread s function .
6,320
def _find_watch_paths ( self ) : watch_path_s = set ( os . path . abspath ( x ) for x in sys . path ) for extra_path in self . _extra_paths or ( ) : extra_dir_path = os . path . dirname ( os . path . abspath ( extra_path ) ) watch_path_s . add ( extra_dir_path ) for module in list ( sys . modules . values ( ) ) : modul...
Find paths to watch .
6,321
def _find_short_paths ( self , paths ) : path_parts_s = [ path . split ( os . path . sep ) for path in paths ] root_node = { } for parts in sorted ( path_parts_s , key = len , reverse = True ) : node = root_node for part in parts : node = node . setdefault ( part , { } ) node . clear ( ) short_path_s = set ( ) self . _...
Find short paths of given paths .
6,322
def _collect_leaf_paths ( self , node , path_parts , leaf_paths ) : if not node : node_path = '/' . join ( path_parts ) leaf_paths . add ( node_path ) else : for child_path_part , child_node in node . items ( ) : child_path_part_s = path_parts + ( child_path_part , ) self . _collect_leaf_paths ( node = child_node , pat...
Collect paths of leaf nodes .
6,323
def dispatch ( self , event ) : file_path = event . src_path if file_path in self . _extra_paths : self . reload ( ) if file_path . endswith ( ( '.pyc' , '.pyo' ) ) : file_path = file_path [ : - 1 ] if file_path . endswith ( '.py' ) : file_dir = os . path . dirname ( file_path ) if file_dir . startswith ( tuple ( self ...
Dispatch file system event .
6,324
def reload ( self ) : reload_mode = self . _reload_mode if self . _reload_mode == self . RELOAD_MODE_V_EXEC : self . reload_using_exec ( ) elif self . _reload_mode == self . RELOAD_MODE_V_SPAWN_EXIT : self . reload_using_spawn_exit ( ) elif self . _reload_mode == self . RELOAD_MODE_V_SPAWN_WAIT : self . reload_using_sp...
Reload the program .
6,325
def reload_using_exec ( self ) : cmd_parts = [ sys . executable ] + sys . argv env_copy = os . environ . copy ( ) os . execvpe ( sys . executable , cmd_parts , env_copy , )
Reload the program process .
6,326
def reload_using_spawn_exit ( self ) : cmd_parts = [ sys . executable ] + sys . argv env_copy = os . environ . copy ( ) subprocess . Popen ( cmd_parts , env = env_copy , close_fds = True ) if self . _force_exit : os . _exit ( 0 ) else : interrupt_main ( ) self . _watcher_to_stop = True sys . exit ( 0 )
Spawn a subprocess and exit the current process .
6,327
def reload_using_spawn_wait ( self ) : cmd_parts = [ sys . executable ] + sys . argv env_copy = os . environ . copy ( ) interrupt_main ( ) subprocess . call ( cmd_parts , env = env_copy , close_fds = True ) sys . exit ( 0 )
Spawn a subprocess and wait until it finishes .
6,328
def agent ( agent_id ) : fields = [ ( 'ID' , 'id' ) , ( 'Status' , 'status' ) , ( 'Region' , 'region' ) , ( 'First Contact' , 'first_contact' ) , ( 'CPU Usage (%)' , 'cpu_cur_pct' ) , ( 'Used Memory (MiB)' , 'mem_cur_bytes' ) , ( 'Total slots' , 'available_slots' ) , ( 'Occupied slots' , 'occupied_slots' ) , ] if is_le...
Show the information about the given agent .
6,329
def resource_policy ( name ) : fields = [ ( 'Name' , 'name' ) , ( 'Created At' , 'created_at' ) , ( 'Default for Unspecified' , 'default_for_unspecified' ) , ( 'Total Resource Slot' , 'total_resource_slots' ) , ( 'Max Concurrent Sessions' , 'max_concurrent_sessions' ) , ( 'Max Containers per Session' , 'max_containers_...
Show details about a keypair resource policy . When name option is omitted the resource policy for the current access_key will be returned .
6,330
def add ( name , default_for_unspecified , total_resource_slots , max_concurrent_sessions , max_containers_per_session , max_vfolder_count , max_vfolder_size , idle_timeout , allowed_vfolder_hosts ) : with Session ( ) as session : try : data = session . ResourcePolicy . create ( name , default_for_unspecified = default...
Add a new keypair resource policy .
6,331
def delete ( name ) : with Session ( ) as session : if input ( 'Are you sure? (y/n): ' ) . lower ( ) . strip ( ) [ : 1 ] != 'y' : print ( 'Canceled.' ) sys . exit ( 1 ) try : data = session . ResourcePolicy . delete ( name ) except Exception as e : print_error ( e ) sys . exit ( 1 ) if not data [ 'ok' ] : print_fail ( ...
Delete a keypair resource policy .
6,332
def app ( session_id , app , bind , port ) : api_session = None runner = None async def app_setup ( ) : nonlocal api_session , runner loop = current_loop ( ) api_session = AsyncSession ( ) protocol = 'http' runner = ProxyRunner ( api_session , session_id , app , protocol , bind , port , loop = loop ) await runner . rea...
Run a local proxy to a service provided by Backend . AI compute sessions .
6,333
def logs ( sess_id_or_alias ) : with Session ( ) as session : try : print_wait ( 'Retrieving container logs...' ) kernel = session . Kernel ( sess_id_or_alias ) result = kernel . get_logs ( ) . get ( 'result' ) logs = result . get ( 'logs' ) if 'logs' in result else '' print ( logs ) print_done ( 'End of logs.' ) excep...
Shows the output logs of a running container .
6,334
def _wrap_key ( function , args , kws ) : return hashlib . md5 ( pickle . dumps ( ( _from_file ( function ) + function . __name__ , args , kws ) ) ) . hexdigest ( )
get the key from the function input .
6,335
def get ( key , adapter = MemoryAdapter ) : try : return pickle . loads ( adapter ( ) . get ( key ) ) except CacheExpiredException : return None
get the cache value
6,336
def set ( key , value , timeout = - 1 , adapter = MemoryAdapter ) : if adapter ( timeout = timeout ) . set ( key , pickle . dumps ( value ) ) : return value else : return None
set cache by code must set timeout length
6,337
def wrapcache ( timeout = - 1 , adapter = MemoryAdapter ) : def _wrapcache ( function ) : @ wraps ( function ) def __wrapcache ( * args , ** kws ) : hash_key = _wrap_key ( function , args , kws ) try : adapter_instance = adapter ( ) return pickle . loads ( adapter_instance . get ( hash_key ) ) except CacheExpiredExcept...
the Decorator to cache Function .
6,338
def export_analytics_data_to_excel ( data , output_file_name , result_info_key , identifier_keys ) : workbook = create_excel_workbook ( data , result_info_key , identifier_keys ) workbook . save ( output_file_name ) print ( 'Saved Excel file to {}' . format ( output_file_name ) )
Creates an Excel file containing data returned by the Analytics API
6,339
def export_analytics_data_to_csv ( data , output_folder , result_info_key , identifier_keys ) : workbook = create_excel_workbook ( data , result_info_key , identifier_keys ) suffix = '.csv' if not os . path . exists ( output_folder ) : os . makedirs ( output_folder ) for worksheet in workbook . worksheets : file_name =...
Creates CSV files containing data returned by the Analytics API . Creates one file per requested endpoint and saves it into the specified output_folder
6,340
def concat_excel_reports ( addresses , output_file_name , endpoint , report_type , retry , api_key , api_secret , files_path ) : master_workbook = openpyxl . Workbook ( ) if api_key is not None and api_secret is not None : client = ApiClient ( api_key , api_secret ) else : client = ApiClient ( ) errors = [ ] for index ...
Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses .
6,341
def create_excel_workbook ( data , result_info_key , identifier_keys ) : workbook = analytics_data_excel . get_excel_workbook ( data , result_info_key , identifier_keys ) adjust_column_width_workbook ( workbook ) return workbook
Calls the analytics_data_excel module to create the Workbook
6,342
def adjust_column_width ( worksheet ) : dims = { } padding = 1 for row in worksheet . rows : for cell in row : if not cell . value : continue dims [ cell . column ] = max ( dims . get ( cell . column , 0 ) , len ( str ( cell . value ) ) ) for col , value in list ( dims . items ( ) ) : worksheet . column_dimensions [ co...
Adjust column width in worksheet .
6,343
def get_ap_info ( ipaddress , auth , url ) : get_ap_info_url = "/imcrs/wlan/apInfo/queryApBasicInfoByCondition?ipAddress=" + str ( ipaddress ) f_url = url + get_ap_info_url payload = None r = requests . get ( f_url , auth = auth , headers = HEADERS ) try : if r . status_code == 200 : if len ( r . text ) > 0 : return js...
function takes input of ipaddress to RESTFUL call to HP IMC
6,344
def session ( sess_id_or_alias ) : fields = [ ( 'Session ID' , 'sess_id' ) , ( 'Role' , 'role' ) , ( 'Image' , 'image' ) , ( 'Tag' , 'tag' ) , ( 'Created At' , 'created_at' ) , ( 'Terminated At' , 'terminated_at' ) , ( 'Agent' , 'agent' ) , ( 'Status' , 'status' ) , ( 'Status Info' , 'status_info' ) , ( 'Occupied Resou...
Show detailed information for a running compute session .
6,345
def get_object_errors ( self ) : if self . _object_errors is None : self . _object_errors = [ { str ( o ) : o . get_errors ( ) } for o in self . objects ( ) if o . has_error ( ) ] return self . _object_errors
Gets a list of business error message strings for each of the requested objects that had a business error . If there was no error returns an empty list
6,346
def has_object_error ( self ) : if self . _has_object_error is None : self . _has_object_error = next ( ( True for o in self . objects ( ) if o . has_error ( ) ) , False ) return self . _has_object_error
Returns true if any requested object had a business logic error otherwise returns false
6,347
def rate_limits ( self ) : if not self . _rate_limits : self . _rate_limits = utilities . get_rate_limits ( self . response ) return self . _rate_limits
Returns a list of rate limit details .
6,348
def check_imc_creds ( auth , url ) : test_url = '/imcrs' f_url = url + test_url try : response = requests . get ( f_url , auth = auth , headers = HEADERS , verify = False ) return bool ( response . status_code == 200 ) except requests . exceptions . RequestException as error : return "Error:\n" + str ( error ) + " test...
Function takes input of auth class object auth object and URL and returns a BOOL of TRUE if the authentication was successful .
6,349
def get_full_python_version ( ) : version_part = '.' . join ( str ( x ) for x in sys . version_info ) int_width = struct . calcsize ( 'P' ) * 8 int_width_part = str ( int_width ) + 'bit' return version_part + '.' + int_width_part
Get full Python version .
6,350
def get_python_path ( venv_path ) : bin_path = get_bin_path ( venv_path ) program_path = os . path . join ( bin_path , 'python' ) if sys . platform . startswith ( 'win' ) : program_path = program_path + '.exe' return program_path
Get given virtual environment s python program path .
6,351
def add_options ( ctx ) : ctx . add_option ( '--always' , action = 'store_true' , default = False , dest = 'always' , help = 'whether always run tasks.' , ) ctx . add_option ( '--check-import' , action = 'store_true' , default = False , dest = 'check_import' , help = 'whether import module for dirty checking.' , ) ctx ...
Add command line options .
6,352
def add_pythonpath ( path ) : pythonpath = os . environ . setdefault ( 'PYTHONPATH' , '' ) if path not in pythonpath . split ( os . pathsep ) : pythonpath = os . environ [ 'PYTHONPATH' ] = ( path + os . pathsep + pythonpath ) if pythonpath else path return pythonpath
Prepend given path to environment variable PYTHONPATH .
6,353
def mark_path ( path ) : if not isinstance ( path , str ) or os . path . isabs ( path ) : msg = 'Error (2D9ZA): Given path is not relative path: {0}.' . format ( path ) raise ValueError ( msg ) return _ItemWrapper ( type = 'path' , item = path )
Wrap given path as relative path relative to top directory .
6,354
def _mark_target ( type , item ) : if type not in ( 'input' , 'output' ) : msg = 'Error (7D74X): Type is not valid: {0}' . format ( type ) raise ValueError ( msg ) orig_item = item if isinstance ( item , list ) : item_s = item else : item_s = [ item ] for item in item_s : if isinstance ( item , str ) and os . path . is...
Wrap given item as input or output target that should be added to task .
6,355
def create_node ( ctx , path ) : _ensure_build_context ( ctx ) top_dir_relpath = os . path . relpath ( ctx . top_dir , ctx . run_dir , ) node_path = os . path . join ( top_dir_relpath , path ) node = ctx . path . make_node ( node_path ) return node
Create node for given relative path .
6,356
def _normalize_items ( ctx , items , str_to_node = False , node_to_str = False , allow_task = False , ) : _ensure_build_context ( ctx ) norm_tuple_s = [ ] if not items : return norm_tuple_s for item in items : if isinstance ( item , _ItemWrapper ) : wrapper_type = item . type ( ) item = item . item ( ) else : wrapper_t...
Normalize given items .
6,357
def update_touch_file ( ctx , path , check_import = False , check_import_module = None , check_import_python = None , always = False , ) : _ensure_build_context ( ctx ) print_title ( 'Update touch file: {}' . format ( path ) ) touch_node = create_node ( ctx , path ) need_run = False if not touch_node . exists ( ) or al...
Update touch file at given path .
6,358
def chain_tasks ( tasks ) : if tasks : previous_task = None for task in tasks : if task is not None : if previous_task is not None : task . set_run_after ( previous_task ) previous_task = task return tasks
Chain given tasks . Set each task to run after its previous task .
6,359
def build_ctx ( pythonpath = None ) : if isinstance ( pythonpath , str ) : path_s = [ pythonpath ] elif isinstance ( pythonpath , list ) : path_s = pythonpath else : path_s = None def _noarg_decorator ( func ) : class _BuildContext ( BuildContext ) : cmd = func . __name__ fun = func . __name__ @ wraps ( func ) def _new...
Decorator that makes decorated function use BuildContext instead of \ Context instance . BuildContext instance has more methods .
6,360
def config_ctx ( func ) : class _ConfigurationContext ( ConfigurationContext ) : cmd = func . __name__ fun = func . __name__ func . _context_class = _ConfigurationContext return func
Decorator that makes decorated function use ConfigurationContext instead \ of Context instance .
6,361
def print_ctx ( ctx ) : print_title ( 'ctx attributes' ) print_text ( dir ( ctx ) ) print_title ( 'ctx attributes' , is_end = True ) print_title ( 'ctx.options' ) print_text ( pformat ( vars ( ctx . options ) , indent = 4 , width = 1 ) ) print_title ( 'ctx.options' , is_end = True ) if hasattr ( ctx , 'env' ) : print_t...
Print given context s info .
6,362
def virtualenv_setup ( ctx , python , inputs = None , outputs = None , touch = None , check_import = False , pip_setup_file = None , pip_setup_touch = None , cache_key = None , always = False , ) : _ensure_build_context ( ctx ) if pip_setup_file is None : pip_setup_task = None else : pip_setup_task = pip_setup ( ctx = ...
Create task that sets up virtualenv package .
6,363
def create_venv ( ctx , python , venv_path , inputs = None , outputs = None , pip_setup_file = None , pip_setup_touch = None , virtualenv_setup_touch = None , task_name = None , cache_key = None , always = False , ) : _ensure_build_context ( ctx ) virtualenv_setup_task = virtualenv_setup ( ctx = ctx , python = python ,...
Create task that sets up virtual environment .
6,364
def pip_ins_req ( ctx , python , req_path , venv_path = None , inputs = None , outputs = None , touch = None , check_import = False , check_import_module = None , pip_setup_file = None , pip_setup_touch = None , virtualenv_setup_touch = None , always = False , ) : _ensure_build_context ( ctx ) if venv_path is None : ve...
Create task that uses given virtual environment s pip to sets up \ packages listed in given requirements file .
6,365
def git_clean ( ctx ) : cmd_part_s = [ 'git' , 'clean' , '-x' , '-d' , '-f' , '-f' , ] print_title ( 'git_clean' ) print_text ( _format_multi_line_command ( cmd_part_s ) ) proc = subprocess . Popen ( cmd_part_s , cwd = ctx . top_dir ) proc . wait ( ) print_title ( 'git_clean' , is_end = True )
Delete all files untracked by git .
6,366
def delete_telnet_template ( auth , url , template_name = None , template_id = None ) : try : if template_id is None : telnet_templates = get_telnet_template ( auth , url ) if template_name is None : template_name = telnet_template [ 'name' ] template_id = None for template in telnet_templates : if template [ 'name' ] ...
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific telnet template from the IMC system
6,367
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_nam...
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific ssh template from the IMC system
6,368
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' ] == templa...
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific snmp template from the IMC system
6,369
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 . route...
Run a non - encrypted non - authorized API proxy server . Use this only for development and testing!
6,370
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 res...
Takes string input of IP address to issue RESTUL call to HP IMC
6,371
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 ( ...
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 .
6,372
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 , }...
Deletes an existing keypair with given ACCESSKEY .
6,373
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_a...
Lists the keypairs . You need an admin privilege for this operation .
6,374
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/grap...
Returns the keypair s information such as resource limits .
6,375
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_polic...
Activates this keypair . You need an admin privilege for this operation .
6,376
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_po...
Deactivates this keypair . Deactivated keypairs cannot make any API requests unless activated again by an administrator . You need an admin privilege for this operation .
6,377
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 .
6,378
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...
This function prompts user for IMC server information and credentuials and stores values in url and auth global variables
6,379
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 .
6,380
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 : query_params . update ( identifier_input [ 0 ] ) return self . _request_client...
Calls this instance s request_client s post method with the specified component endpoint
6,381
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
6,382
def get_identifier_input ( self , identifier_data ) : identifier_input = [ ] if isinstance ( identifier_data , list ) and len ( identifier_data ) > 0 : for address in identifier_data : identifier_input . append ( self . _convert_to_identifier_json ( address ) ) else : identifier_input . append ( self . _convert_to_iden...
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 .
6,383
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
6,384
def _convert_to_identifier_json ( self , address_data ) : if isinstance ( address_data , str ) : 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_dat...
Convert input address data into json format
6,385
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
6,386
def rental_report ( self , address , zipcode , format_type = "json" ) : 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
6,387
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
6,388
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 .
6,389
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 , d...
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 .
6,390
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 . app...
Returns a list of ComponentResult from the json_data
6,391
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 .
6,392
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 .
6,393
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 = a...
Deserialize property json data into a Property object
6,394
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 els...
Deserialize block json data into a Block object
6,395
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
6,396
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
6,397
def starts_when ( iterable , condition ) : 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 .
6,398
def stops_when ( iterable , condition ) : 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 .
6,399
def skip_duplicates ( iterable , key = None , fingerprints = ( ) ) : fingerprints = fingerprints or set ( ) fingerprint = None try : 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 : yi...
Returns a generator that will yield all objects from iterable skipping duplicates .