Parse the lease file and return a dict of active and valid Lease instances.
        The key for this dict is the ethernet address of the lease.
16312
def get_current(self):
        
        all_leases = self.get()
        leases = {}
        for lease in all_leases:
            if lease.valid and lease.active:
                if type(lease) is Lease:
                    leases[lease.ethernet] = lease
                elif type(lease) is Lease6:
                    leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease
        return leases
1013977
def get_example(cls) -> dict:
        
        if cls.example is not None:
            return cls.example
        return {k: v.get_example() for k, v in cls.properties.items()}
276990
def parse(self):
        
        index_server = None
        for num, line in enumerate(self.iter_lines()):
            line = line.rstrip()
            if not line:
                continue
            if line.startswith('#'):
                # comments are lines that start with # only
                continue
            if line.startswith('-i') or \
                line.startswith('--index-url') or \
                line.startswith('--extra-index-url'):
                # this file is using a private index server, try to parse it
                index_server = self.parse_index_server(line)
                continue
            elif self.obj.path and (line.startswith('-r') or line.startswith('--requirement')):
                self.obj.resolved_files.append(self.resolve_file(self.obj.path, line))
            elif line.startswith('-f') or line.startswith('--find-links') or \
                line.startswith('--no-index') or line.startswith('--allow-external') or \
                line.startswith('--allow-unverified') or line.startswith('-Z') or \
                line.startswith('--always-unzip'):
                continue
            elif self.is_marked_line(line):
                continue
            else:
                try:

                    parseable_line = line

                    # multiline requirements are not parseable
                    if "\\" in line:
                        parseable_line = line.replace("\\", "")
                        for next_line in self.iter_lines(num + 1):
                            parseable_line += next_line.strip().replace("\\", "")
                            line += "\n" + next_line
                            if "\\" in next_line:
                                continue
                            break
                        # ignore multiline requirements if they are marked
                        if self.is_marked_line(parseable_line):
                            continue

                    hashes = []
                    if "--hash" in parseable_line:
                        parseable_line, hashes = Parser.parse_hashes(parseable_line)

                    req = RequirementsTXTLineParser.parse(parseable_line)
                    if req:
                        req.hashes = hashes
                        req.index_server = index_server
                        # replace the requirements line with the 'real' line
                        req.line = line
                        self.obj.dependencies.append(req)
                except ValueError:
                    continue
1272790
def solidity_get_contract_data(all_contracts, filepath, contract_name):
    
    try:
        contract_data = all_contracts[contract_name]
    except BaseException:
        if filepath is None:
            filename = '<stdin>'
        else:
            _, filename = os.path.split(filepath)
        contract_data = all_contracts[filename + ":" + contract_name]
    return contract_data
1348285
def _ParseIndexTable(self, file_object):
    
    cache_address_map = self._GetDataTypeMap('uint32le')
    file_offset = file_object.get_offset()

    cache_address_data = file_object.read(4)

    while len(cache_address_data) == 4:
      try:
        value = self._ReadStructureFromByteStream(
            cache_address_data, file_offset, cache_address_map)
      except (ValueError, errors.ParseError) as exception:
        raise errors.ParseError((
            'Unable to map cache address at offset: 0x{0:08x} with error: '
            '{1!s}').format(file_offset, exception))

      if value:
        cache_address = CacheAddress(value)
        self.index_table.append(cache_address)

      file_offset += 4

      cache_address_data = file_object.read(4)
675953
def _parse_properties(self):
        
        props_dict = self.data.get('properties', {})
        for prop_name in self.KNOWN_PROPERTIES:
            if prop_name in props_dict:
                setattr(self, prop_name, props_dict.get(prop_name))
            else:
                setattr(self, prop_name, None)
742722
def get(self):
        
        resource = dict()
        resource.update(self._parse_hostname())
        resource.update(self._parse_iprouting())
        resource.update(self._parse_banners())

        return resource
312253
def parse(self, file_obj):
        
        configs = [self._config[0]]
        for line in file_obj:
            line = line.rstrip('\n').lstrip()
            if (line == '') or (line[0] == '#'):
                continue
            if '=' in line:
                key, value = line.split('=', 1)
                key = key.strip().lower()
            else:
                # find first whitespace, and split there
                i = 0
                while (i < len(line)) and not line[i].isspace():
                    i += 1
                if i == len(line):
                    raise Exception('Unparsable line: %r' % line)
                key = line[:i].lower()
                value = line[i:].lstrip()

            if key == 'host':
                del configs[:]
                # the value may be multiple hosts, space-delimited
                for host in value.split():
                    # do we have a pre-existing host config to append to?
                    matches = [c for c in self._config if c['host'] == host]
                    if len(matches) > 0:
                        configs.append(matches[0])
                    else:
                        config = { 'host': host }
                        self._config.append(config)
                        configs.append(config)
            else:
                for config in configs:
                    config[key] = value
297756
async def run_loop_async(self):
        
        while not self.cancellation_token.is_cancelled:
            lease_manager = self.host.storage_manager
            # Inspect all leases.
            # Acquire any expired leases.
            # Renew any leases that currently belong to us.
            getting_all_leases = await lease_manager.get_all_leases()
            leases_owned_by_others_q = Queue()
            renew_tasks = [
                self.attempt_renew_lease_async(
                    get_lease_task,
                    owned_by_others_q=leases_owned_by_others_q,
                    lease_manager=lease_manager)
                for get_lease_task in getting_all_leases]
            await asyncio.gather(*renew_tasks)

            # Extract all leasees leases_owned_by_others and our_lease_count from the
            all_leases = {}
            leases_owned_by_others = []
            our_lease_count = 0
            while not leases_owned_by_others_q.empty():
                lease_owned_by_other = leases_owned_by_others_q.get()
                # Check if lease is owned by other and append
                if lease_owned_by_other[0]:
                    leases_owned_by_others.append(lease_owned_by_other[1])
                else:
                    our_lease_count += 1
                all_leases[lease_owned_by_other[1].partition_id] = lease_owned_by_other[1]

            # Grab more leases if available and needed for load balancing
            leases_owned_by_others_count = len(leases_owned_by_others)
            if leases_owned_by_others_count > 0:
                steal_this_lease = self.which_lease_to_steal(
                    leases_owned_by_others, our_lease_count)
                if steal_this_lease:
                    try:
                        _logger.info("Lease to steal %r", steal_this_lease.serializable())
                        if await lease_manager.acquire_lease_async(steal_this_lease):
                            _logger.info("Stole lease sucessfully %r %r",
                                         self.host.guid, steal_this_lease.partition_id)
                        else:
                            _logger.info("Failed to steal lease for partition %r %r",
                                         self.host.guid, steal_this_lease.partition_id)
                    except Exception as err:  # pylint: disable=broad-except
                        _logger.error("Failed to steal lease %r", err)

            for partition_id in all_leases:
                try:
                    updated_lease = all_leases[partition_id]
                    if updated_lease.owner == self.host.host_name:
                        _logger.debug("Attempting to renew lease %r %r",
                                      self.host.guid, partition_id)
                        await self.check_and_add_pump_async(partition_id, updated_lease)
                    else:
                        _logger.debug("Removing pump due to lost lease.")
                        await self.remove_pump_async(partition_id, "LeaseLost")
                except Exception as err:  # pylint: disable=broad-except
                    _logger.error("Failed to update lease %r", err)
            await asyncio.sleep(lease_manager.lease_renew_interval)
64594
private void parseSSLCertFile() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "parseSSLCertFile");
        }

        String fileName = null;
        String lineRead = null;
        BufferedReader bufferReader = null;

        // Obtain Default Cert Label
        certDefaultLabel = getProperty(PROTOCOL_HTTPS_CERT_DEFAULT_LABEL);

        // Obtain Cert Mapping File
        try {
            fileName = getProperty(PROTOCOL_HTTPS_CERT_MAPPING_FILE);

            if (fileName != null && 0 < fileName.length()) {
                bufferReader = new BufferedReader(new FileReader(fileName));

                // For each entry, parse the label and ip address
                lineRead = bufferReader.readLine();
                while (lineRead != null) {
                    extractSSLServerCert(lineRead.trim());
                    lineRead = bufferReader.readLine();
                }
            }
        } catch (Exception e) {
            FFDCFilter.processException(e, getClass().getName(), "parseSSLCertFile", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Error parsing file; " + e);
        } finally {
            if (null != bufferReader) {
                try {
                    bufferReader.close();
                } catch (IOException ioe) {
                    // ignore
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "parseSSLCertFile");
        }
    }
513430
def _parse_current_network_settings():
    '''
    
    '''
    opts = salt.utils.odict.OrderedDict()
    opts['networking'] = ''

    if os.path.isfile(_DEB_NETWORKING_FILE):
        with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
            for line in contents:
                salt.utils.stringutils.to_unicode(line)
                if line.startswith('#'):
                    continue
                elif line.startswith('CONFIGURE_INTERFACES'):
                    opts['networking'] = line.split('=', 1)[1].strip()

    hostname = _parse_hostname()
    domainname = _parse_domainname()
    searchdomain = _parse_searchdomain()

    opts['hostname'] = hostname
    opts['domainname'] = domainname
    opts['searchdomain'] = searchdomain
    return opts
185293
def print_http_nfc_lease_info(info):
    
    print 'Lease timeout: {0.leaseTimeout}\n' \
          'Disk Capacity KB: {0.totalDiskCapacityInKB}'.format(info)
    device_number = 1
    if info.deviceUrl:
        for device_url in info.deviceUrl:
            print 'HttpNfcLeaseDeviceUrl: {1}\n' \
                  'Device URL Import Key: {0.importKey}\n' \
                  'Device URL Key: {0.key}\n' \
                  'Device URL: {0.url}\n' \
                  'Device URL Size: {0.fileSize}\n' \
                  'SSL Thumbprint: {0.sslThumbprint}\n'.format(device_url,
                                                               device_number)
            if not device_url.targetId:
                print "No targetId found for this device"
                print "Device is not eligible for export. This could be a mounted iso or img of some sort"
                print "It will NOT be downloaded\n"

            device_number += 1
    else:
        print 'No devices were found.'
513998
def _LeaseMessageHandlerRequests(self, lease_time, limit):
    """"""
    leased_requests = []

    now = rdfvalue.RDFDatetime.Now()
    zero = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(0)
    expiration_time = now + lease_time

    leases = self.message_handler_leases
    for requests in itervalues(self.message_handler_requests):
      for r in itervalues(requests):
        existing_lease = leases.get(r.handler_name, {}).get(r.request_id, zero)
        if existing_lease < now:
          leases.setdefault(r.handler_name, {})[r.request_id] = expiration_time
          r.leased_until = expiration_time
          r.leased_by = utils.ProcessIdString()
          leased_requests.append(r)
          if len(leased_requests) >= limit:
            break

    return leased_requests
1293132
def parseLedgerForHaAndKeys(ledger, returnActive=True, ledger_size=None):
        
        nodeReg = OrderedDict()
        cliNodeReg = OrderedDict()
        nodeKeys = {}
        activeValidators = set()
        try:
            TxnStackManager._parse_pool_transaction_file(
                ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
                ledger_size=ledger_size)
        except ValueError:
            errMsg = 'Pool transaction file corrupted. Rebuild pool transactions.'
            logger.exception(errMsg)
            exit(errMsg)

        if returnActive:
            allNodes = tuple(nodeReg.keys())
            for nodeName in allNodes:
                if nodeName not in activeValidators:
                    nodeReg.pop(nodeName, None)
                    cliNodeReg.pop(nodeName + CLIENT_STACK_SUFFIX, None)
                    nodeKeys.pop(nodeName, None)

            return nodeReg, cliNodeReg, nodeKeys
        else:
            return nodeReg, cliNodeReg, nodeKeys, activeValidators
56055
void internalReleaseLease(Lease lease, String src,
      INodeFileUnderConstruction pendingFile) throws IOException {
    if (lease.hasPath()) {
      // make a copy of the paths because internalReleaseLeaseOne removes
      // pathnames from the lease record.
      String[] leasePaths = new String[lease.getPaths().size()];
      lease.getPaths().toArray(leasePaths);
      LOG.info("Recovering lease: " + lease + " for paths "
          + Arrays.toString(leasePaths));
      for (String p: leasePaths) {
        internalReleaseLeaseOne(lease, p);
      }
    } else {
      internalReleaseLeaseOne(lease, src, pendingFile, false);
    }
  }
368009
def _parse_connection_string(connstr):
    
    res = {}
    for item in connstr.split(';'):
        item = item.strip()
        if not item:
            continue
        key, value = item.split('=', 1)
        key = key.strip().lower().replace(' ', '_')
        value = value.strip()
        res[key] = value
    return res
1256232
def _get_instance_key(self, host, namespace, wmi_class, other=None):
        
        if other:
            return "{host}:{namespace}:{wmi_class}-{other}".format(
                host=host, namespace=namespace, wmi_class=wmi_class, other=other
            )

        return "{host}:{namespace}:{wmi_class}".format(host=host, namespace=namespace, wmi_class=wmi_class)