sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def check_storage_controllers(): """ Check the status of the storage controllers Skip this check, if --noController is set """ if ctrl_flag: ctrl = walk_data(sess, oid_ctrl, helper)[0] for x, data in enumerate(ctrl, 1): ctrl_summary_output, ctrl_long_output = state_summar...
Check the status of the storage controllers Skip this check, if --noController is set
entailment
def check_temperature_sensors(): """ Check all temperature sensors of the server All sensors with the value or threshold is -99 or 0 are ignored """ # walk all temperature sensor values and thresholds env_temp = walk_data(sess, oid_env_temp, helper)[0] env_temp_thresh = walk_data(sess, o...
Check all temperature sensors of the server All sensors with the value or threshold is -99 or 0 are ignored
entailment
def check_ps(): """ Check if the power supplies are ok, and we have the configured amount The check is skipped if --ps=0 """ if int(input_pwr_sply) != 0: ps_data = walk_data(sess, oid_ps, helper)[0] ps_ok_count = 0 for x, state in enumerate(ps_data, 1): ...
Check if the power supplies are ok, and we have the configured amount The check is skipped if --ps=0
entailment
def check_power_redundancy(): """ Check if the power supplies are redundant The check is skipped if --noPowerRedundancy is set """ # skip the check if --noPowerRedundancy is set if power_redundancy_flag: # walk the data ps_redundant_data = walk_data(sess, oid_ps_redundant...
Check if the power supplies are redundant The check is skipped if --noPowerRedundancy is set
entailment
def check_fan(input_fan): """ check the fans """ # get a list of all fans fan_data = walk_data(sess, oid_fan, helper)[0] fan_count = 0 summary_output = '' long_output = '' for x, fan in enumerate(fan_data, 1): fan = int(fan) if normal_state[fan] == 'ok': ...
check the fans
entailment
def get_snmp_from_host1(self): """ Get SNMP values from 1st host. """ response = self.snmp1.get_oids(ps1_oid, ps2_oid, fan1_oid, fan2_oid, bat_oid, temp_oid, activity_oid, logfill_oid) self.ps1_value = states[int(response[0])] self.ps2_value = states[int(response[1])] ...
Get SNMP values from 1st host.
entailment
def get_snmp_from_host2(self): """ Get SNMP values from 2nd host. """ if not self.snmp2: self.activity_value2 = None else: response = self.snmp2.get_oids(activity_oid) self.activity_value2 = activity[int(response[0])]
Get SNMP values from 2nd host.
entailment
def check(self): """ Evaluate health status from device parameters. """ try: self.get_snmp_from_host1() self.get_snmp_from_host2() except (health_monitoring_plugins.SnmpException, TypeError, KeyError): self.helper.status(unknown) se...
Evaluate health status from device parameters.
entailment
def update_status(self, helper, status): """ update the helper """ if status: self.status(status[0]) # if the status is ok, add it to the long output if status[0] == 0: self.add_long_output(status[1]) # if the status is not ok, add it to t...
update the helper
entailment
def get_snmp_value(sess, helper, oid): """ return a snmp value or exits the plugin with unknown""" snmp_result = sess.get_oids(oid)[0] if snmp_result is None: helper.exit(summary="No response from device for oid " + oid, exit_code=unknown, perfdata='') else: retu...
return a snmp value or exits the plugin with unknown
entailment
def walk_snmp_values(sess, helper, oid, check): """ return a snmp value or exits the plugin with unknown""" try: snmp_walk = sess.walk_oid(oid) result_list = [] for x in range(len(snmp_walk)): result_list.append(snmp_walk[x].val) if resul...
return a snmp value or exits the plugin with unknown
entailment
def walk_oid(self, oid): """Get a list of SNMP varbinds in response to a walk for oid. Each varbind in response list has a tag, iid, val and type attribute.""" var = netsnmp.Varbind(oid) varlist = netsnmp.VarList(var) data = self.walk(varlist) if len(data) == 0: ...
Get a list of SNMP varbinds in response to a walk for oid. Each varbind in response list has a tag, iid, val and type attribute.
entailment
def run_scan(): """ show all available partitions """ all_disks = walk_data(sess, oid_hrStorageDescr, helper)[0] print "All available disks at: " + host for disk in all_disks: print "Disk: \t'" + disk + "'" quit()
show all available partitions
entailment
def partition_found(partition, description): """ returns True, if the partition (--partition) is in the description we received from the host """ # if we want to have a linux partition (/) we use the full path (startswith "/" would result in / /var /dev etc). # if we start with something else, we u...
returns True, if the partition (--partition) is in the description we received from the host
entailment
def check_partition(): """ check the defined partition """ all_index = walk_data(sess, oid_hrStorageIndex, helper)[0] all_descriptions = walk_data(sess, oid_hrStorageDescr, helper)[0] # we need the sucess flag for the error handling (partition found or not found) sucess ...
check the defined partition
entailment
def check_sensors(): """ collect and check all available sensors """ all_sensors = walk_data(sess, oid_description, helper)[0] all_status = walk_data(sess, oid_status, helper)[0] # here we zip all index and descriptions to have a list like # [('Fan Sensor', '2'), ('Power Supply Sensor', '4...
collect and check all available sensors
entailment
def check_basic_battery_status(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0 MIB Excerpt The status of the UPS batteries. A batteryLow(3) value indicates the UPS will be unable to sustain the current load, and its services will be lost if power is not ...
OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0 MIB Excerpt The status of the UPS batteries. A batteryLow(3) value indicates the UPS will be unable to sustain the current load, and its services will be lost if power is not restored. The amount of run time in reserve at the time of low battery can be c...
entailment
def check_runtime_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second """ a_minute_value = calc_minutes_from_ticks(the_s...
OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second
entailment
def check_battery_replace_indicator(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.2.4.0 MIB Excerpt Indicates whether the UPS batteries need replacing. Value List noBatteryNeedsReplacing (1) batteryNeedsReplacing (2) """ apc_states = { '1' : 'Bat...
OID .1.3.6.1.4.1.318.1.1.1.2.2.4.0 MIB Excerpt Indicates whether the UPS batteries need replacing. Value List noBatteryNeedsReplacing (1) batteryNeedsReplacing (2)
entailment
def check_environment_temperature(the_session, the_helper, the_snmp_value, the_unit=1): """ OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1 MIB Excerpt The current temperature reading from the probe displayed in the units shown in the 'iemStatusProbeTempUnits' OID (Celsius or Fahrenheit). Descripti...
OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1 MIB Excerpt The current temperature reading from the probe displayed in the units shown in the 'iemStatusProbeTempUnits' OID (Celsius or Fahrenheit). Description of unit OID OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.5 The temperature scale used to display t...
entailment
def check_typ(helper, typ): """ check if typ parameter is TCP or UDP """ if typ != "tcp" and typ != "udp": helper.exit(summary="Type (-t) must be udp or tcp.", exit_code=unknown, perfdata='')
check if typ parameter is TCP or UDP
entailment
def check_port(helper, port): """ check if the port parameter is really a port or "scan" """ try: int(port) except ValueError: helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='')
check if the port parameter is really a port or "scan"
entailment
def check_udp(helper, host, port, session): """ the check logic for UDP ports """ open_ports = walk_data(session, '.1.3.6.1.2.1.7.5.1.2', helper)[0] # the udpLocaLPort from UDP-MIB.mib (deprecated) # here we show all open UDP ports if scan: print "All open UDP ports at host " + host...
the check logic for UDP ports
entailment
def check_tcp(helper, host, port, warning_param, critical_param, session): """ the check logic for check TCP ports """ # from tcpConnState from TCP-MIB tcp_translate = { "1" : "closed", "2" : "listen", "3" : "synSent", "4" : "synReceived", "5" : "established",...
the check logic for check TCP ports
entailment
def to_json(obj): """Return a json string representing the python object obj.""" i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
Return a json string representing the python object obj.
entailment
def get_data(self): "Get SNMP values from host" alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']] response = se...
Get SNMP values from host
entailment
def process_alarms(self, snmp_data): "Build list with active alarms" self.active_alarms = [] for i in range(0, len(self.models[self.modem_type]['alarms'])): if bool(int(snmp_data[i])) == True: self.active_alarms.append(self.models[self.modem_type]['alarms'][i])
Build list with active alarms
entailment
def process_metrics(self, snmp_data): "Build list with metrics" self.metrics = {} for i in range(0, len(snmp_data)): metric_id = self.models[self.modem_type]['metrics'][i] value = int(snmp_data[i]) self.metrics[metric_id] = value
Build list with metrics
entailment
def convert_in_oid(service_name): """ calculate the correct OID for the service name """ s = service_name # convert the service_name to ascci service_ascii = [ord(c) for c in s] # we need the length of the service name length = str(len(s)) # make the oid oid = base_oid + "." + l...
calculate the correct OID for the service name
entailment
def get_data(self): "Return one SNMP response list for all status OIDs, and one list for all metric OIDs." alarm_oids = [netsnmp.Varbind(status_mib[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metric_mib[metric_id]['oid']) for metric_id...
Return one SNMP response list for all status OIDs, and one list for all metric OIDs.
entailment
def process_alarms(self, snmp_data): "Build list with active alarms" self.active_alarms = {} for i in range(0, len(self.models[self.modem_type]['alarms'])): mib_name = self.models[self.modem_type]['alarms'][i] conv = status_mib[mib_name]['conv'] self.active_al...
Build list with active alarms
entailment
def process_metrics(self, snmp_data): "Build list with metrics" self.metrics = {} for i in range(0, len(snmp_data)): mib_name = self.models[self.modem_type]['metrics'][i] conv = metric_mib[mib_name]['conv'] self.metrics[mib_name] = conv(snmp_data[i])
Build list with metrics
entailment
def real_value(value, digit): """ function to calculate the real value we need to devide the value by the digit e.g. value = 100 digit = 2 return: "1.0" """ return str(float(value) / math.pow(10, float(digit)))
function to calculate the real value we need to devide the value by the digit e.g. value = 100 digit = 2 return: "1.0"
entailment
def check_inlet(self, helper): """ check the Inlets of Raritan PDUs """ # walk the data try: inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value']) inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit']) inlet_digits = self.sess....
check the Inlets of Raritan PDUs
entailment
def check_outlet(self, helper): """ check the status of the specified outlet """ try: outlet_name, outlet_state = self.sess.get_oids(self.oids['oid_outlet_name'], self.oids['oid_outlet_state']) except health_monitoring_plugins.SnmpException as e: helper.ex...
check the status of the specified outlet
entailment
def check_sensor(self, helper): """ check the status of the specified sensor """ try: sensor_name, sensor_state, sensor_type = self.sess.get_oids( self.oids['oid_sensor_name'], self.oids['oid_sensor_state'], self.oids['oid_sensor_type']) except health_...
check the status of the specified sensor
entailment
def dev_null_wrapper(func, *a, **kwargs): """ Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null. This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases. """ os.dup2(dev_null, sys.stdout.fileno()) return_object = f...
Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null. This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases.
entailment
def state_summary(value, name, state_list, helper, ok_value = 'ok', info = None): """ Always add the status to the long output, and if the status is not ok (or ok_value), we show it in the summary and set the status to critical """ # translate the value (integer) we receive to a human readable valu...
Always add the status to the long output, and if the status is not ok (or ok_value), we show it in the summary and set the status to critical
entailment
def add_output(summary_output, long_output, helper): """ if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report """ if summary_output != '': helper.add_summary(summary_output) helper.add_long_output(long_outp...
if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report
entailment
def process_gps_position(self, helper, sess): """ just print the current GPS position """ gps_position = helper.get_snmp_value(sess, helper, self.oids['oid_gps_position']) if gps_position: helper.add_summary(gps_position) else: helper.add_summary...
just print the current GPS position
entailment
def process_status(self, helper, sess, check): """ get the snmp value, check the status and update the helper""" if check == 'ntp_current_state': ntp_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_ntp_current_state_int']) result = self.check_ntp_status(ntp_statu...
get the snmp value, check the status and update the helper
entailment
def check_ntp_status(self, ntp_status_int): """ check the NTP status """ # convert the ntp_status integer value in a human readable value ntp_status_string = self.ntp_status.get(ntp_status_int, "unknown") if ntp_status_string == "unknown": return unknown, ("N...
check the NTP status
entailment
def check_gps_status(self, gps_status_int): """ check the GPS status """ gps_mode_string = self.gps_mode.get(gps_status_int, "unknown") if gps_mode_string == "unknown": return unknown, ("GPS status: " + gps_mode_string) elif gps_mode_string != "normalOperati...
check the GPS status
entailment
def process_satellites(self, helper, sess): """ check and show the good satellites """ good_satellites = helper.get_snmp_value(sess, helper, self.oids['oid_gps_satellites_good']) # Show the summary and add the metric and afterwards check the metric helper.add_summary("Go...
check and show the good satellites
entailment
def login_password(self, value): """Set the value of the login password field.""" password = self.selenium.find_element(*self._password_input_locator) password.clear() password.send_keys(value)
Set the value of the login password field.
entailment
def email(self, value): """Set the value of the email field.""" email = self.wait.until(expected.visibility_of_element_located( self._email_input_locator)) email.clear() email.send_keys(value)
Set the value of the email field.
entailment
def sign_in(self, email, password): """Signs in using the specified email address and password.""" self.email = email self.login_password = password if self.is_element_present(*self._next_button_locator): self.wait.until(expected.visibility_of_element_located( ...
Signs in using the specified email address and password.
entailment
def sign_in(self, email=None, password=None): """Signs in a user, either with the specified email address and password, or a returning user.""" from .pages.sign_in import SignIn sign_in = SignIn(self.selenium, self.timeout) sign_in.sign_in(email, password)
Signs in a user, either with the specified email address and password, or a returning user.
entailment
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT): """Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.""" csvwriter = csv.writer(fileobj, dialect=dialect) csv_writerows(csvwriter, rows, encoding)
Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.
entailment
def write_dataframe(rows, encoding=ENCODING, dialect=DIALECT, **kwargs): """Dump ``rows`` to string buffer and load with ``pandas.read_csv()`` using ``kwargs``.""" global pandas if pandas is None: # pragma: no cover import pandas with contextlib.closing(CsvBuffer()) as fd: write_csv(fd,...
Dump ``rows`` to string buffer and load with ``pandas.read_csv()`` using ``kwargs``.
entailment
def from_string(cls, link): """Return a new SheetUrl instance from parsed URL string. >>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam') <SheetUrl id='spam' gid=0> """ ma = cls._pattern.search(link) if ma is None: raise ValueError(link) ...
Return a new SheetUrl instance from parsed URL string. >>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam') <SheetUrl id='spam' gid=0>
entailment
def doctemplate(*args): """Return a decorator putting ``args`` into the docstring of the decorated ``func``. >>> @doctemplate('spam', 'spam') ... def spam(): ... '''Returns %s, lovely %s.''' ... return 'Spam' >>> spam.__doc__ 'Returns spam, lovely spam.' """ def decorator(f...
Return a decorator putting ``args`` into the docstring of the decorated ``func``. >>> @doctemplate('spam', 'spam') ... def spam(): ... '''Returns %s, lovely %s.''' ... return 'Spam' >>> spam.__doc__ 'Returns spam, lovely spam.'
entailment
def group_dict(items, keyfunc): """Return a list defaultdict with ``items`` grouped by ``keyfunc``. >>> sorted(group_dict('eggs', lambda x: x).items()) [('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])] """ result = collections.defaultdict(list) for i in items: key = keyfunc(i) res...
Return a list defaultdict with ``items`` grouped by ``keyfunc``. >>> sorted(group_dict('eggs', lambda x: x).items()) [('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])]
entailment
def uniqued(iterable): """Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g'] """ seen = set() return [item for item in iterable if item not in seen and not seen.add(item)]
Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g']
entailment
def build_service(name=None, **kwargs): """Return a service endpoint for interacting with a Google API.""" if name is not None: for kw, value in iteritems(SERVICES[name]): kwargs.setdefault(kw, value) return apiclient.discovery.build(**kwargs)
Return a service endpoint for interacting with a Google API.
entailment
def iterfiles(service, name=None, mimeType=SHEET, order=FILEORDER): """Fetch and yield ``(id, name)`` pairs for Google drive files.""" params = {'orderBy': order, 'pageToken': None} q = [] if name is not None: q.append("name='%s'" % name) if mimeType is not None: q.append("mimeType='...
Fetch and yield ``(id, name)`` pairs for Google drive files.
entailment
def spreadsheet(service, id): """Fetch and return spreadsheet meta data with Google sheets API.""" request = service.spreadsheets().get(spreadsheetId=id) try: response = request.execute() except apiclient.errors.HttpError as e: if e.resp.status == 404: raise KeyError(id) ...
Fetch and return spreadsheet meta data with Google sheets API.
entailment
def values(service, id, ranges): """Fetch and return spreadsheet cell values with Google sheets API.""" params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE', 'dateTimeRenderOption': 'FORMATTED_STRING'} params.update(spreadsheetId=id, ranges=ranges) response = servic...
Fetch and return spreadsheet cell values with Google sheets API.
entailment
def get_credentials(scopes=None, secrets=None, storage=None, no_webserver=False): """Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files. Args: scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``) secrets: location of secrets file (default: ``%r``) ...
Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files. Args: scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``) secrets: location of secrets file (default: ``%r``) storage: location of storage file (default: ``%r``) no_webserver: url/code prompt...
entailment
def get(cls, scope=None): """Return default or predefined URLs from keyword, pass through ``scope``.""" if scope is None: scope = cls.default if isinstance(scope, string_types) and scope in cls._keywords: return getattr(cls, scope) return scope
Return default or predefined URLs from keyword, pass through ``scope``.
entailment
def search_all(self, limit=50, format='json'): ''' Returns a single list containing up to 'limit' Result objects''' desired_limit = limit results = self._search(limit, format) limit = limit - len(results) while len(results) < desired_limit: more_results = self._search...
Returns a single list containing up to 'limit' Result objects
entailment
def _search(self, limit, format): ''' Returns a list of result objects, with the url for the next page bing search url. ''' url = self.QUERY_URL.format(requests.utils.quote("'{}'".format(self.query)), min(50, limit), self.current_offset, format) r = requests.get(url, auth=("", se...
Returns a list of result objects, with the url for the next page bing search url.
entailment
def base26int(s, _start=1 - ord('A')): """Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799 """ return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799
entailment
def base26(x, _alphabet=string.ascii_uppercase): """Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 2...
Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0 'SPAM' >>> base26(256) 'IV'
entailment
def _parse(coord, _match=_regex.match): """Return match groups from single sheet coordinate. >>> Coordinates._parse('A1') ('A', '1', None, None) >>> Coordinates._parse('A'), Coordinates._parse('1') ((None, None, 'A', None), (None, None, None, '1')) >>> Coordinates._par...
Return match groups from single sheet coordinate. >>> Coordinates._parse('A1') ('A', '1', None, None) >>> Coordinates._parse('A'), Coordinates._parse('1') ((None, None, 'A', None), (None, None, None, '1')) >>> Coordinates._parse('spam') Traceback (most recent call last...
entailment
def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}): """Return zero-based column index from bijective base26 string. >>> Coordinates._cint('Ab') 27 >>> Coordinates._cint('spam') Traceback (most recent call last): ... ValueError: spam """ ...
Return zero-based column index from bijective base26 string. >>> Coordinates._cint('Ab') 27 >>> Coordinates._cint('spam') Traceback (most recent call last): ... ValueError: spam
entailment
def from_slice(cls, coord): """Return a value fetching callable given a slice of coordinate strings.""" if coord.step is not None: raise NotImplementedError('no slice step support') elif coord.start is not None and coord.stop is not None: return DoubleSlice.from_slice(coo...
Return a value fetching callable given a slice of coordinate strings.
entailment
def find(self, title): """Return the first worksheet with the given title. Args: title(str): title/name of the worksheet to return Returns: WorkSheet: contained worksheet object Raises: KeyError: if the spreadsheet has no no worksheet with the given `...
Return the first worksheet with the given title. Args: title(str): title/name of the worksheet to return Returns: WorkSheet: contained worksheet object Raises: KeyError: if the spreadsheet has no no worksheet with the given ``title``
entailment
def findall(self, title=None): """Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty) """ if title is None: ...
Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty)
entailment
def to_csv(self, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object...
Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a str...
entailment
def titles(self, unique=False): """Return a list of contained worksheet titles. Args: unique (bool): drop duplicates Returns: list: list of titles/name strings """ if unique: return tools.uniqued(s.title for s in self._items) return [s...
Return a list of contained worksheet titles. Args: unique (bool): drop duplicates Returns: list: list of titles/name strings
entailment
def at(self, row, col): """Return the value at the given cell position. Args: row (int): zero-based row number col (int): zero-based column number Returns: cell value Raises: TypeError: if ``row`` or ``col`` is not an ``int`` Ind...
Return the value at the given cell position. Args: row (int): zero-based row number col (int): zero-based column number Returns: cell value Raises: TypeError: if ``row`` or ``col`` is not an ``int`` IndexError: if the position is out of ...
entailment
def values(self, column_major=False): """Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values """ if column_major: return list(map(list, z...
Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values
entailment
def to_csv(self, filename=None, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump the worksheet to a CSV file. Args: filename (str): result filename (if ``None`` use ``make_filename``) encoding (str): res...
Dump the worksheet to a CSV file. Args: filename (str): result filename (if ``None`` use ``make_filename``) encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning t...
entailment
def to_frame(self, **kwargs): r"""Return a pandas DataFrame loaded from the worksheet data. Args: \**kwargs: passed to ``pandas.read_csv()`` (e.g. ``header``, ``index_col``) Returns: pandas.DataFrame: new ``DataFrame`` instance """ df = export.write_dataf...
r"""Return a pandas DataFrame loaded from the worksheet data. Args: \**kwargs: passed to ``pandas.read_csv()`` (e.g. ``header``, ``index_col``) Returns: pandas.DataFrame: new ``DataFrame`` instance
entailment
def from_files(cls, secrets=None, storage=None, scopes=None, no_webserver=False): """Return a spreadsheet collection making OAauth 2.0 credentials. Args: secrets (str): location of secrets file (default: ``%r``) storage (str): location of storage file (default: ``%r``) ...
Return a spreadsheet collection making OAauth 2.0 credentials. Args: secrets (str): location of secrets file (default: ``%r``) storage (str): location of storage file (default: ``%r``) scopes: scope URL(s) or ``'read'`` or ``'write'`` (default: ``%r``) no_webserv...
entailment
def get(self, id_or_url, default=None): """Fetch and return the spreadsheet with the given id or url. Args: id_or_url (str): unique alphanumeric id or URL of the spreadsheet Returns: New SpreadSheet instance or given default if none is found Raises: V...
Fetch and return the spreadsheet with the given id or url. Args: id_or_url (str): unique alphanumeric id or URL of the spreadsheet Returns: New SpreadSheet instance or given default if none is found Raises: ValueError: if an URL is given from which no id coul...
entailment
def find(self, title): """Fetch and return the first spreadsheet with the given title. Args: title(str): title/name of the spreadsheet to return Returns: SpreadSheet: new SpreadSheet instance Raises: KeyError: if no spreadsheet with the given ``title`...
Fetch and return the first spreadsheet with the given title. Args: title(str): title/name of the spreadsheet to return Returns: SpreadSheet: new SpreadSheet instance Raises: KeyError: if no spreadsheet with the given ``title`` is found
entailment
def findall(self, title=None): """Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty) """ if title ...
Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty)
entailment
def titles(self, unique=False): """Return a list of all available spreadsheet titles. Args: unique (bool): drop duplicates Returns: list: list of title/name strings """ if unique: return tools.uniqued(title for _, title in self.iterfiles()) ...
Return a list of all available spreadsheet titles. Args: unique (bool): drop duplicates Returns: list: list of title/name strings
entailment
def create(self, name, description, data_source_type, url, credential_user=None, credential_pass=None, is_public=None, is_protected=None, s3_credentials=None): """Create a Data Source.""" data = { 'name': name, 'description': description, ...
Create a Data Source.
entailment
def update(self, data_source_id, update_data): """Update a Data Source. :param dict update_data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * type * url ...
Update a Data Source. :param dict update_data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * type * url * is_public * is_protected * credenti...
entailment
def getitem_by_path(d, path): """Access item in d using path. a = { 0: { 1: 'item' } } getitem_by_path(a, [0, 1]) == 'item' """ return reduce( lambda d, k: d[k], path, d )
Access item in d using path. a = { 0: { 1: 'item' } } getitem_by_path(a, [0, 1]) == 'item'
entailment
def clean_empty(self, d=DEFAULT): """Returns a copy of d without empty leaves. https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074 """ if d is DEFAULT: d = self if isinstance(d, list): return [v for...
Returns a copy of d without empty leaves. https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074
entailment
def compress(self, d=DEFAULT): """Returns a copy of d with compressed leaves.""" if d is DEFAULT: d = self if isinstance(d, list): l = [v for v in (self.compress(v) for v in d)] try: return list(set(l)) except TypeError: ...
Returns a copy of d with compressed leaves.
entailment
def cast_dicts(self, to=DEFAULT, d=DEFAULT): """Returns a copy of d with all dicts casted to the type 'to'.""" if to is DEFAULT: to = type(self) if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.cast_dicts(to, v) for v in d)] ...
Returns a copy of d with all dicts casted to the type 'to'.
entailment
def merge(self, b, a=DEFAULT): """Merges b into a recursively, if a is not given: merges into self. also merges lists and: * merge({a:a},{a:b}) = {a:[a,b]} * merge({a:[a]},{a:b}) = {a:[a,b]} * merge({a:a},{a:[b]}) = {a:[a,b]} * merge({a:[a]},{a:[b]}) = {a...
Merges b into a recursively, if a is not given: merges into self. also merges lists and: * merge({a:a},{a:b}) = {a:[a,b]} * merge({a:[a]},{a:b}) = {a:[a,b]} * merge({a:a},{a:[b]}) = {a:[a,b]} * merge({a:[a]},{a:[b]}) = {a:[a,b]}
entailment
def create(self, name, url, description=None, extra=None, is_public=None, is_protected=None): """Create a Job Binary. :param dict extra: authentication info needed for some job binaries, containing the keys `user` and `password` for job binary in Swift or the keys...
Create a Job Binary. :param dict extra: authentication info needed for some job binaries, containing the keys `user` and `password` for job binary in Swift or the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3
entailment
def get_file(self, job_binary_id): """Download a Job Binary.""" resp = self.api.get('/job-binaries/%s/data' % job_binary_id) if resp.status_code != 200: self._raise_api_exception(resp) return resp.content
Download a Job Binary.
entailment
def update(self, job_binary_id, data): """Update Job Binary. :param dict data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * url * is_public * is_protected ...
Update Job Binary. :param dict data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * url * is_public * is_protected * extra - dict with the keys `user` and `passwo...
entailment
def set(conf): """Applies a configuration to the global config object""" for name, value in conf.items(): if value is not None: setattr(Conf, name.upper(), value)
Applies a configuration to the global config object
entailment
def get(): """Gets the configuration as a dict""" return { attr: getattr(Conf, attr) for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith("__") }
Gets the configuration as a dict
entailment
def load(description, add_arguments_cb = lambda x: None, postprocess_conf_cb = lambda x: None): """Loads the global Conf object from command line arguments. Encode the next argument after +plugin to ensure that it does not start with a prefix_char """ argparser = ArgumentParser...
Loads the global Conf object from command line arguments. Encode the next argument after +plugin to ensure that it does not start with a prefix_char
entailment
def _format_usage_without_prefix(parser): """ Use private argparse APIs to get the usage string without the 'usage: ' prefix. """ fmt = parser._get_formatter() fmt.add_usage(parser.usage, parser._actions, parser._mutually_exclusive_groups, prefix='') return fmt.format_help(...
Use private argparse APIs to get the usage string without the 'usage: ' prefix.
entailment
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated, hadoop_version=NotUpdated, flavor_id=NotUpdated, description=NotUpdated, volumes_per_node=NotUpdated, volumes_size=NotUpdated, node_processes=NotUpdated, node_configs=NotUpdated, floatin...
Update a Node Group Template.
entailment
def create(self, name, plugin_name, plugin_version, flavor_id, description=None, volumes_per_node=None, volumes_size=None, node_processes=None, node_configs=None, floating_ip_pool=None, security_groups=None, auto_security_group=None, availability_zone=None, vo...
Create a Node Group Template.
entailment
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated, plugin_version=NotUpdated, flavor_id=NotUpdated, description=NotUpdated, volumes_per_node=NotUpdated, volumes_size=NotUpdated, node_processes=NotUpdated, node_configs=NotUpdated, floatin...
Update a Node Group Template.
entailment
def update_image(self, image_id, user_name, desc=None): """Create or update an Image in Image Registry.""" desc = desc if desc else '' data = {"username": user_name, "description": desc} return self._post('/images/%s' % image_id, data)
Create or update an Image in Image Registry.
entailment
def update_tags(self, image_id, new_tags): """Update an Image tags. :param new_tags: list of tags that will replace currently assigned tags """ # Do not add :param list in the docstring above until this is solved: # https://github.com/sphinx-doc/sp...
Update an Image tags. :param new_tags: list of tags that will replace currently assigned tags
entailment
def build_option_parser(parser): """Hook to add global options.""" parser.add_argument( "--os-data-processing-api-version", metavar="<data-processing-api-version>", default=utils.env( 'OS_DATA_PROCESSING_API_VERSION', default=DEFAULT_DATA_PROCESSING_API_VERSION), ...
Hook to add global options.
entailment