code stringlengths 1 18.2k |
|---|
def _update_resource_view(self, log=False): # type: () -> bool """Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not """ update = False if 'id' in self.data and self._load_from_hdx('resource view', self.data['id']): update = True else: if 'resource_id' i... |
self.data = resource_view.data update = True break if update: if log: logger.warning('resource view exists. Updating %s' % self.data['id']) self._merge_hdx_update('resource view', 'id') return update |
def create_in_hdx(self): # type: () -> None """Check if resource view exists in HDX and if so, update it, otherwise create resource view Returns: None """ self.check_required_fields() if not self._update_resource_view(log=True): self._save_to_hdx('create', 'title') |
def copy(self, resource_view): # type: (Union[ResourceView,Dict,str]) -> None """Copies all fields except id, resource_id and package_id from another resource view. Args: resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary R... |
if not isinstance(resource_view, dict) and not isinstance(resource_view, ResourceView): raise HDXError('%s is not a valid resource view!' % resource_view) for key in resource_view: if key not in ('id', 'resource_id', 'package_id'): self.data[key] = resource_view[key] |
def tagscleanupdicts(configuration=None, url=None, keycolumn=5, failchained=True): # type: (Optional[Configuration], Optional[str], int, bool) -> Tuple[Dict,List] """ Get tags cleanup dictionaries Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. url (Optional[str]): Ur... |
Returns (Tags dictionary, Wildcard tags list) """ if not Tags._tags_dict: if configuration is None: configuration = Configuration.read() with Download(full_agent=configuration.get_user_agent()) as downloader: if url is None: url = configuration['tags_cleanup_url'] Tags._tags_dict = downloader.download_tabular_rows_as_d... |
= list(keys).index(final_tag) if index != i: whattodo2 = Tags._tags_dict[final_tag] action2 = whattodo2[u'action'] if action2 != 'OK' and action2 != 'Other': final_tags2 = whattodo2[u'final tags (semicolon separated)'] if final_tag not in final_tags2.split(';'): chainerror = True if failchained: logger.error('Chained r... |
Tags._wildcard_tags = list() for tag in Tags._tags_dict: if '*' in tag: Tags._wildcard_tags.append(tag) return Tags._tags_dict, Tags._wildcard_tags |
def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['User'] """Reads the user given by identifier from HDX and returns User object Args: identifier (str): Identifier of user configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Re... |
def update_in_hdx(self): # type: () -> None """Check if user exists in HDX and if so, update user Returns: None """ capacity = self.data.get('capacity') if capacity is not None: del self.data['capacity'] # remove capacity (which comes from users from Organization) self._update_in_hdx('user', 'id') if capacity is not No... |
def create_in_hdx(self): # type: () -> None """Check if user exists in HDX and if so, update it, otherwise create user Returns: None """ capacity = self.data.get('capacity') if capacity is not None: del self.data['capacity'] self._create_in_hdx('user', 'id', 'name') if capacity is not None: self.data['capacity'] = capa... |
def email(self, subject, text_body, html_body=None, sender=None, **kwargs): # type: (str, str, Optional[str], Optional[str], Any) -> None """Emails a user. Args: subject (str): Email subject text_body (str): Plain text email body html_body (str): HTML email body sender (Optional[str]): Email sender. Defaults to SMTP us... |
subject, text_body, html_body=html_body, sender=sender, **kwargs) |
def get_all_users(configuration=None, **kwargs): # type: (Optional[Configuration], Any) -> List['User'] """Get all users in HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. **kwargs: See below q (str): Restrict to names containing a string. Defaults to all users. o... |
user = User(configuration=configuration) user['id'] = 'all users' # only for error message if produced result = user._write_to_hdx('list', kwargs, 'id') users = list() if result: for userdict in result: user = User(userdict, configuration=configuration) users.append(user) else: logger.debug(result) return users |
def email_users(users, subject, text_body, html_body=None, sender=None, configuration=None, **kwargs): # type: (List['User'], str, str, Optional[str], Optional[str], Optional[Configuration], Any) -> None """Email a list of users Args: users (List[User]): List of users subject (str): Email subject text_body (str): Plain... |
list. **kwargs: See below mail_options (List): Mail options (see smtplib documentation) rcpt_options (List): Recipient options (see smtplib documentation) Returns: None """ if not users: raise ValueError('No users supplied') recipients = list() for user in users: recipients.append(user.data['email']) if configuration i... |
def get_organizations(self, permission='read'): # type: (str) -> List['Organization'] """Get organizations in HDX that this user is a member of. Args: permission (str): Permission to check for. Defaults to 'read'. Returns: List[Organization]: List of organizations in HDX that this user is a member of """ success, resul... |
organizations.append(organization) return organizations |
def facade(projectmainfn, **kwargs): # (Callable[[None], None], Any) -> None """Facade to simplify project setup that calls project main function Args: projectmainfn ((None) -> None): main function of project **kwargs: configuration parameters to pass to HDX Configuration class Returns: None """ # # Setting up configur... |
site_url) UserAgent.user_agent = Configuration.read().user_agent projectmainfn() |
def get_lint_config(config_path=None): """ Tries loading the config from the given path. If no path is specified, the default config path is tried, and if that is not specified, we the default config is returned. """ # config path specified if config_path: config = LintConfig.load_from_file(config_path) click.echo("Usi... |
file else: config = LintConfig() return config |
def cli(list_files, config, ignore, path): """ Markdown lint tool, checks your markdown for styling issues """ files = MarkdownFileFinder.find_files(path) if list_files: echo_files(files) lint_config = get_lint_config(config) lint_config.apply_on_csv_string(ignore, lint_config.disable_rule) linter = MarkdownLinter(lint... |
def main(): """ Main function """ # Read configuration from the config file if present, else fall back to # command line options if args.config: config = config_file_parser.get_configuration(args.config) access_key_id = config['access-key-id'] secret_access_key = config['secret-access-key'] region = config['region'] el... |
daemon.stop() sys.exit(0) elif args.daemon == 'restart': daemon.restart() elif args.daemon in ['foreground', 'fg']: daemon.run() else: print 'Valid options for --daemon are start, stop and restart' sys.exit(1) # Connect to AWS connection = connection_manager.connect_to_ec2( region, access_key_id, secret_access_key) if ... |
def run(self, check_interval=300): """ Run the daemon :type check_interval: int :param check_interval: Delay in seconds between checks """ while True: # Read configuration from the config file if present, else fall # back to command line options if args.config: config = config_file_parser.get_configuration(args.config)... |
AWS connection = connection_manager.connect_to_ec2( region, access_key_id, secret_access_key) snapshot_manager.run(connection) logger.info('Sleeping {} seconds until next check'.format( check_interval)) time.sleep(check_interval) |
def _apply_line_rules(self, markdown_string): """ Iterates over the lines in a given markdown string and applies all the enabled line rules to each line """ all_violations = [] lines = markdown_string.split("\n") line_rules = self.line_rules line_nr = 1 ignoring = False for line in lines: if ignoring: if line.strip() =... |
continue for rule in line_rules: violation = rule.validate(line) if violation: violation.line_nr = line_nr all_violations.append(violation) line_nr += 1 return all_violations |
def lint_files(self, files): """ Lints a list of files. :param files: list of files to lint :return: a list of violations found in the files """ all_violations = [] for filename in files: with open(filename, 'r') as f: content = f.read() violations = self.lint(content) all_violations.extend(violations) for e in violati... |
def ReadFrom(self, byte_stream): """Read values from a byte stream. Args: byte_stream (bytes): byte stream. Returns: tuple[object, ...]: values copies from the byte stream. Raises: IOError: if byte stream cannot be read. OSError: if byte stream cannot be read. """ try: return self._struct.unpack_from(byte_stream) excep... |
def WriteTo(self, values): """Writes values to a byte stream. Args: values (tuple[object, ...]): values to copy to the byte stream. Returns: bytes: byte stream. Raises: IOError: if byte stream cannot be written. OSError: if byte stream cannot be read. """ try: return self._struct.pack(*values) except (TypeError, struct... |
def run(connection): """ Ensure that we have snapshots for a given volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :returns: None """ volumes = volume_manager.get_watched_volumes(connection) for volume in volumes: _ensure_snapshot(connection, volume) _remove_old_snaps... |
def _create_snapshot(volume): """ Create a new snapshot :type volume: boto.ec2.volume.Volume :param volume: Volume to snapshot :returns: boto.ec2.snapshot.Snapshot -- The new snapshot """ logger.info('Creating new snapshot for {}'.format(volume.id)) snapshot = volume.create_snapshot( description="Automatic snapshot by ... |
def _ensure_snapshot(connection, volume): """ Ensure that a given volume has an appropriate snapshot :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume: boto.ec2.volume.Volume :param volume: Volume to check :returns: None """ if 'AutomatedEBSSnapshots' not in volum... |
{}'.format( interval, volume.id)) return snapshots = connection.get_all_snapshots(filters={'volume-id': volume.id}) # Create a snapshot if we don't have any if not snapshots: _create_snapshot(volume) return min_delta = 3600*24*365*10 # 10 years :) for snapshot in snapshots: timestamp = datetime.datetime.strptime( snaps... |
== 'hourly' and min_delta > 3600: _create_snapshot(volume) elif interval == 'daily' and min_delta > 3600*24: _create_snapshot(volume) elif interval == 'weekly' and min_delta > 3600*24*7: _create_snapshot(volume) elif interval == 'monthly' and min_delta > 3600*24*30: _create_snapshot(volume) elif interval == 'yearly' an... |
def _remove_old_snapshots(connection, volume): """ Remove old snapshots :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume: boto.ec2.volume.Volume :param volume: Volume to check :returns: None """ if 'AutomatedEBSSnapshotsRetention' not in volume.tags: logger.warni... |
to keep snapshots = snapshots[:-int(retention)] if not snapshots: logger.info('No old snapshots to remove') return for snapshot in snapshots: logger.info('Deleting snapshot {}'.format(snapshot.id)) try: snapshot.delete() except EC2ResponseError as error: logger.warning('Could not remove snapshot: {}'.format( error.mess... |
def list(connection): """ List watched EBS volumes :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :returns: None """ volumes = get_watched_volumes(connection) if not volumes: logger.info('No watched volumes found') return logger.info( '+-----------------------' '+----------... |
not in volume.tags: interval = 'Interval tag not found' elif volume.tags['AutomatedEBSSnapshots'] not in VALID_INTERVALS: interval = 'Invalid interval' else: interval = volume.tags['AutomatedEBSSnapshots'] if 'AutomatedEBSSnapshotsRetention' not in volume.tags: retention = 0 else: retention = volume.tags['AutomatedEBSS... |
retention=retention)) logger.info( '+-----------------------' '+----------------------' '+--------------' '+------------+') |
def unwatch(connection, volume_id): """ Remove watching of a volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume_id: str :param volume_id: VolumeID to add to the watchlist :returns: bool - True if the watch was successful """ try: volume = connection.get_all_... |
def watch(connection, volume_id, interval='daily', retention=0): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume_id: str :param volume_id: VolumeID to add to the watchlist :type interval: str :param interval: Backup interval [hour... |
= connection.get_all_volumes(volume_ids=[volume_id])[0] except EC2ResponseError: logger.warning('Volume {} not found'.format(volume_id)) return False if interval not in VALID_INTERVALS: logger.warning( '{} is not a valid interval. Valid intervals are {}'.format( interval, ', '.join(VALID_INTERVALS))) # Remove the tag f... |
True |
def get_volume_id(connection, volume): """ Get Volume ID from the given volume. Input can be volume id or its Name tag. :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume: str :param volume: Volume ID or Volume Name :returns: Volume ID or None if the given volume d... |
re.compile('vol-\w{8}') if volume_id_pattern.match(volume): # input is volume id try: # Check whether it exists connection.get_all_volumes(volume_ids=[volume]) volume_id = volume except EC2ResponseError: logger.warning('Volume {} not found'.format(volume)) return None else: # input is volume name name_filter = {'tag-ke... |
def watch_from_file(connection, file_name): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None """ with open(file_name, 'r') as filehandle: for line in filehandle.xreadline... |
def unwatch_from_file(connection, file_name): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None """ with open(file_name, 'r') as filehandle: for line in filehandle.xreadli... |
def list_snapshots(connection, volume): """ List all snapshots for the volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume: str :param volume: Volume ID or Volume Name :returns: None """ logger.info( '+----------------' '+----------------------' '+-----------... |
snap in vol.snapshots(): logger.info( '| {snapshot:<14} ' '| {snapshot_name:<20.20} ' '| {created:<25} |'.format( snapshot=snap.id, snapshot_name=snap.tags.get('Name', ''), created=snap.start_time)) logger.info( '+----------------' '+----------------------' '+---------------------------+') |
def stem(self, words, parser, **kwargs): """ Get stems for the words using a given parser Example: from .parsing import ListParser parser = ListParser() stemmer = Morfologik() stemmer.stem(['ja tańczę a ona śpi], parser) [ ('ja': ['ja']), ('tańczę': ['tańczyć']), ('a': ['a']), ('ona': ['on']), ('śpi': ['spać']) ] """ o... |
def _run_morfologik(self, words): """ Runs morfologik java jar and assumes that input and output is UTF-8 encoded. """ p = subprocess.Popen( ['java', '-jar', self.jar_path, 'plstem', '-ie', 'UTF-8', '-oe', 'UTF-8'], bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communic... |
def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['Showcase'] """Reads the showcase given by identifier from HDX and returns Showcase object Args: identifier (str): Identifier of showcase configuration (Optional[Configuration]): HDX configuration. Defaults to global c... |
def get_datasets(self): # type: () -> List[hdx.data.dataset.Dataset] """Get any datasets in the showcase Returns: List[Dataset]: List of datasets """ assoc_result, datasets_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='showcase_id', action=self.actions()['list_datasets']) datasets = list() if asso... |
def _get_showcase_dataset_dict(self, dataset): # type: (Union[hdx.data.dataset.Dataset,Dict,str]) -> Dict """Get showcase dataset dict Args: showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary Returns: Dict: showcase dataset dict """ if isinstance(dataset,... |
% type(dataset).__name__) if is_valid_uuid(dataset) is False: raise hdx.data.hdxobject.HDXError('%s is not a valid dataset id!' % dataset) return {'showcase_id': self.data['id'], 'package_id': dataset} |
def add_dataset(self, dataset, datasets_to_check=None): # type: (Union[hdx.data.dataset.Dataset,Dict,str], List[hdx.data.dataset.Dataset]) -> bool """Add a dataset Args: dataset (Union[Dataset,Dict,str]): Either a dataset id or dataset metadata either from a Dataset object or a dictionary datasets_to_check (List[Datase... |
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._write_to_hdx('associate', showcase_dataset, 'package_id') return True |
def add_datasets(self, datasets, datasets_to_check=None): # type: (List[Union[hdx.data.dataset.Dataset,Dict,str]], List[hdx.data.dataset.Dataset]) -> bool """Add multiple datasets Args: datasets (List[Union[Dataset,Dict,str]]): A list of either dataset ids or dataset metadata from Dataset objects or dictionaries datase... |
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 |
def possible_parameter(nb, jsonable_parameter=True, end_cell_index=None): """ Find the possible parameters from a jupyter notebook (python3 only). The possible parameters are obtained by parsing the abstract syntax tree of the python code generated from the jupyter notebook. For a jupuyter notebook, a variable can be a... |
not used in the current cell beside the assignment nor previously. Parameters ---------- nb : str, nbformat.notebooknode.NotebookNode Jupyter notebook path or its content as a NotebookNode object. jsonable_parameter: bool, optional Consider only jsonable parameters. end_cell_index : int, optional End cell index used to... |
'cell_index'). The list is ordered by the name of the parameters. """ jh = _JupyterNotebookHelper(nb, jsonable_parameter, end_cell_index) if jsonable_parameter is True: PossibleParameter=collections.namedtuple('PossibleParameter',['name','value','cell_index']) else: PossibleParameter=collections.namedtuple('PossiblePar... |
def run_jnb(input_path, output_path=r"///_run_jnb/*-output", execution_path=r'///input', return_mode='except', overwrite=False, timeout=ExecutePreprocessor.timeout.default_value, kernel_name=ExecutePreprocessor.kernel_name.default_value, ep_kwargs=None, jsonable_parameter=True, end_cell_index=None, arg=None, **kwargs):... |
in json format using the standard json encoder. The json content is decoded into python objects using the standard json decoder and it is mapped to a variable assignment by unpacking it. The assignments are appended at the end of the cell where they are initially defined. Parameters ---------- input_path : str Path of ... |
the output jupyter notebook. One can use the input_path location as relative path by starting with "///" . * can be used once in the beggining or end (excluding the ".ipynb" extension) as a wildcard of the input_path filename. "///_run_jnb/*-output" is the default value and states that the output is in the run_jnb fold... |
to the input name. execution_path : str, optional The path of the folder where to execute the notebook. r'///input' or r'///output' can be used to denote the input / output folder. return_mode : ['parametrised_only','except',True, False], optional Flag to write the generated notebook to the output_path: "parametrised_o... |
writes never. overwrite : bool, optional Flag to overwrite or not the output_path. If the parameter is False the used output_path will be incremented until a valid one is found. timeout : int, optional ExecutePreprocessor.timeout kernel_name : str, optional ExecutePreprocessor.kernel_name ep_kwargs : dict, optional Oth... |
to slice the notebook in finding the possible parameters. arg : str Path of a json file (it should end in ".json") or json formatted string used to parametrise the jupyter notebook. It should containt json objects. It is decoded into python objects following https://docs.python.org/3.6/library/json.html#json-to-py-tabl... |
'error_prompt_number','error_type','error_value','error_traceback'). If the generated file is written the output path is returned otherwise None. If an error is catched the details are return otherwise None. """ if os.path.splitext(input_path)[1] != '.ipynb': raise ValueError("The extension of input_path = '{}' is not ... |
output_path[3:] else: input_rel = False output_path_dir, output_path_base = os.path.split(output_path) if input_rel: output_path_dir = os.path.join(input_path_dir, output_path_dir) output_path_dir = os.path.normpath(output_path_dir) if os.path.exists(output_path_dir) is False: os.makedirs(output_path_dir) if output_pat... |
execution_path.startswith(r'///input'): execution_path = os.path.join(input_path_dir, execution_path[8:]) elif execution_path.startswith(r'///output'): execution_path = os.path.join(input_path_dir, execution_path[8:]) execution_path = os.path.normpath(execution_path) if os.path.exists(execution_path) is False: os.maked... |
{}'.format(multiple_kwarg)) jupyter_kwargs = {**arg_as_kwarg, **kwarg_as_kwarg} nb = _read_nb(input_path) # clean notebook for i, cell in enumerate(nb['cells']): if cell['cell_type'] == 'code': nb['cells'][i]['outputs'] = [] nb['cells'][i]['execution_count'] = None if jupyter_kwargs != {}: params_of_interest = {} jnh =... |
= group_dict_by_value(params_of_interest) for key, value in cell_index_param.items(): cell_param = {k: jupyter_kwargs[k] for k in value} cell_code = kwargs_to_variable_assignment(cell_param) marked_code = _mark_auto_generated_code(cell_code) nb['cells'][key]['source'] += marked_code if return_mode != 'parametrised_only... |
and cell.get('outputs') != []: for output in cell['outputs']: if output.get('output_type') == 'error': error = (cell['execution_count'], output.get('ename'), output.get('evalue'), output.get('traceback')) break if error[0] is not None: break else: raise ValueError('Cell expected to have an error.') except: raise if ret... |
False: nb_return = None if nb_return is not None: if overwrite is False: while os.path.exists(output_path): dirname, basename = os.path.split(output_path) root, ext = os.path.splitext(basename) new_root = increment_name(root) output_path = os.path.join(dirname, new_root+ext) nb_return = output_path # update the output_... |
def join(self, joiner, formatter=lambda s, t: t.format(s), template="{}"): """Join values and convert to string Example: >>> from ww import l >>> lst = l('012') >>> lst.join(',') u'0,1,2' >>> lst.join(',', template="{}#") u'0#,1#,2#' >>> string = lst.join(',',\ formatter = lambda x, y: str(int(x) ** 2)) >>> string u'0,... |
def append(self, *values): """Append values at the end of the list Allow chaining. Args: values: values to be appened at the end. Example: >>> from ww import l >>> lst = l([]) >>> lst.append(1) [1] >>> lst [1] >>> lst.append(2, 3).append(4,5) [1, 2, 3, 4, 5] >>> lst [1, 2, 3, 4, 5] """ for value in values: list.append(... |
def extend(self, *iterables): """Add all values of all iterables at the end of the list Args: iterables: iterable which content to add at the end Example: >>> from ww import l >>> lst = l([]) >>> lst.extend([1, 2]) [1, 2] >>> lst [1, 2] >>> lst.extend([3, 4]).extend([5, 6]) [1, 2, 3, 4, 5, 6] >>> lst [1, 2, 3, 4, 5, 6]... |
value in iterables: list.extend(self, value) return self |
def normalize_cell_value(value): """Process value for writing into a cell. Args: value: any type of variable Returns: json serialized value if value is list or dict, else value """ if isinstance(value, dict) or isinstance(value, list): return json.dumps(value) return value |
def get_addresses_from_input_file(input_file_name): """Read addresses from input file into list of tuples. This only supports address and zipcode headers """ 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='"'... |
header_columns.index('address') zipcode_index = header_columns.index('zipcode') except ValueError: raise Exception("""The first row of the input CSV must be a header that contains \ a column labeled 'address' and a column labeled 'zipcode'.""") return list((row[address_index], row[zipcode_index]) for row in addresses) |
def get_identifiers_from_input_file(input_file_name): """Read identifiers from input file into list of dicts with the header row values as keys, and the rest of the rows as values. """ valid_identifiers = ['address', 'zipcode', 'unit', 'city', 'state', 'slug', 'block_id', 'msa', 'num_bins', 'property_type', 'client_val... |
in list(row.items()) if identifier in valid_identifiers} for row in csv.DictReader(input_file, skipinitialspace=True)] return result |
def get_real_time_locate(ipAddress, auth, url): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a... |
IP 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: list of dictionaries where each element of the list represents the location of the target host :rtype: list >>> from pyhpeimc.au... |
get_real_time_locate('10.101.0.51', auth.creds, auth.url) >>> assert type(found_device) is list >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> no_device = get_real_time_locate('192.168.254.254', auth... |
the URL using the payload variable as the contents try: if r.status_code == 200: response = json.loads(r.text) if 'realtimeLocation' in response: real_time_locate = json.loads(r.text)['realtimeLocation'] if type(real_time_locate) is dict: real_time_locate = [real_time_locate] return real_time_locate else: return json.l... |
def get_ip_mac_arp_list(devId, auth,url): """ function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url... |
of the target device. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ip_mac_list = get_ip_mac_arp_list('10', auth.creds, auth.url) >>> assert type(ip_mac_list) is list >>> assert 'deviceId' in ip_mac_lis... |
+ str(devId) f_url = url + ip_mac_arp_list_url r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 200: macarplist = (json.loads(r.text)) if len(macarplist) > 1: return macarplist['ipMacArp'] else: return ['this function is unsupporte... |
def get_ip_scope_detail(scopeId, auth, url ): """ function requires no inputs and returns all IP address scopes currently configured on the HPE IMC server. If the optional scopeId parameter is included, this will automatically return only the desired scope id. :param scopeId: integer of the desired scope id ( optional ... |
of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: dictionary, may containing multiple entries if sub-scopes have been created :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ip_s... |
r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 200: ipscopelist = (json.loads(r.text)) return ipscopelist except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_ip_scope: An Error has occured" |
def delete_ip_scope(network_address, auth, url): '''Function to delete an entire IP segment from the IMC IP Address management under terminal access :param network_address :param auth :param url >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "808... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.