Score matches based upon the position in the dns search domain that matches the result
961897
private List<ScoredHost> scoreMatches(final List<String> results) {
    final ImmutableList.Builder<ScoredHost> scored = ImmutableList.builder();
    for (final String name : results) {
      int score = Integer.MAX_VALUE;
      for (int i = 0; i < searchPath.length; i++) {
        if (name.endsWith(searchPath[i].toString())) {
          if (i < score) {
            score = i;
          }
        }
      }
      scored.add(new ScoredHost(name, score));
    }
    return scored.build();
  }
1219176
def _results(self, product, path, cls=Results, **kwargs):
        """"""
        if product != 'account-information' and self.rate_limit and not self.limits_set and not self.limits:
            self._rate_limit()

        uri = '/'.join(('{0}://api.domaintools.com'.format('https' if self.https else 'http'), path.lstrip('/')))
        parameters = self.default_parameters.copy()
        parameters['api_username'] = self.username
        if self.https:
            parameters['api_key'] = self.key
        else:
            parameters['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
            parameters['signature'] = hmac(self.key.encode('utf8'), ''.join([self.username, parameters['timestamp'],
                                                                             path]).encode('utf8'),
                                           digestmod=sha1).hexdigest()
        parameters.update(dict((key, str(value).lower() if value in (True, False) else value) for
                               key, value in kwargs.items() if value is not None))
        return cls(self, product, uri, **parameters)
1164127
def matches(self, address, name=None):
        

        if self.controller:
            return address == 8

        return self.address == address
382872
def _find_nn_pos_before_site(self, siteindex):
        
        alldist = [(self._mol.get_distance(siteindex, i), i)
                   for i in range(siteindex)]
        alldist = sorted(alldist, key=lambda x: x[0])
        return [d[1] for d in alldist]
938398
def lookup_domain(domain, nameservers=[], rtype="A",
                  exclude_nameservers=[], timeout=2):
    """"""
    dns_exp = DNSQuery(domains=[domain], nameservers=nameservers, rtype=rtype,
                       exclude_nameservers=exclude_nameservers, timeout=timeout)
    return dns_exp.lookup_domain(domain)
955678
def _domain_differs(self, href):
        
        target = utils.get_domain(href)
        if not target:
            return False

        origin = utils.get_domain(self.url)
        return target != origin
568460
def match(self, dom, act):
        
        return self.match_domain(dom) and self.match_action(act)
174486
def _match_net(self, net):
        """"""
        if self.network:
            return match_list(self.network, net)
        else:
            return True
154505
def _hostname_matches(self, hostname, entry):
        
        for h in entry.hostnames:
            if (
                h == hostname
                or h.startswith("|1|")
                and not hostname.startswith("|1|")
                and constant_time_bytes_eq(self.hash_host(hostname, h), h)
            ):
                return True
        return False
1090706
def _encode_query(item,itemtype,domain,apikey=nil)
			label = nil
			if itemtype == 'ip'
				label = item.split(/\./).reverse.join(".")
			elsif itemtype == 'domain'
				label = normalize(item)
			end
			lookup = "#{label}.#{domain}"
			if apikey
				lookup = "#{apikey}.#{lookup}"
			end
			txid = lookup.sum
			message = Resolv::DNS::Message.new(txid)
			message.rd = 1
			message.add_question(lookup,Resolv::DNS::Resource::IN::A)
			message.encode
		end
17026
def _match_registers(self, query):
        
        if query in self._status_registers:
            register = self._status_registers[query]
            response = register.value
            logger.debug('Found response in status register: %s',
                         repr(response))
            register.clear()

            return response
1192397
function maybeCreateAliasRecords(result, callback) {

      let records = result.records.ResourceRecordSets.filter(r=> r.Type === 'A').map(r=> r.Name)
      let stagingExists = records.includes(`staging.${domain}.`)
      let productionExists = records.includes(`${domain}.`)
      let skip = stagingExists && productionExists
      if (skip) {
        let records = result.records.ResourceRecordSets.filter(r=> r.Type === 'A')
        let staging = records.find(r=> r.Name === `staging.${domain}.`)
        let production = records.find(r=> r.Name === `${domain}.`)
        console.log(chalk.green.dim('✔ A Records'))
        console.log(chalk.grey(`          Production ${chalk.green.bold.underline(production.Name)}`))
        console.log(chalk.grey(`             Staging ${chalk.green.bold.underline(staging.Name)}`))
        callback()
      }
      else {

        let staging = result.apis.items.find(api=> api.domainName === `staging.${domain}`)
        let production = result.apis.items.find(api=> api.domainName === domain)
        route53.changeResourceRecordSets({
          ChangeBatch: {
            Changes: [{
              Action: 'UPSERT',
              ResourceRecordSet: {
                AliasTarget: {
                  DNSName: production.distributionDomainName,
                  EvaluateTargetHealth: false,
                  HostedZoneId: 'Z2FDTNDATAQYW2', /* ah, yes of course */
                },
                Name: domain,
                Type: "A"
              }
            },
            {
              Action: 'UPSERT',
              ResourceRecordSet: {
                AliasTarget: {
                  DNSName: staging.distributionDomainName,
                  EvaluateTargetHealth: false,
                  HostedZoneId: 'Z2FDTNDATAQYW2', /* ah, yes of course */
                },
                Name: `staging.${domain}`,
                Type: "A"
              }

            }],
            Comment: "defined by .arc @domain " + domain
          },
          HostedZoneId
        },
        function done(err) {
          if (err) callback(err)
          else {
            console.log(chalk.green.dim('✔ Created A Records'))
            callback()
          }
        })
      }
    }
1175551
function sortMatches(self, matches, basename) {
  var weights  = {};

  var ext_name = path.extname(basename);
  var aliases  = has(self.__aliases__, ext_name) ? self.__aliases__[ext_name] : [];


  matches.forEach(function(match) {
    // XXX: this doesn't work well with aliases
    //      i.e. entry=index.php, extnames=index.html
    var extnames = match.replace(basename, '').split('.');

    weights[match] = extnames.reduce(function(sum, ext) {
      if (!ext) {
        return sum;
      }

      ext = '.' + ext;

      if (self.__extensions__.indexOf(ext) >= 0) {
        return sum + self.__extensions__.indexOf(ext) + 1;
      }

      if (aliases.indexOf(ext) >= 0) {
        return sum + aliases.indexOf(ext) + 11;
      }

      return sum;
    }, 0);
  });

  return matches.sort(function(a, b) {
    return weights[a] > weights[b] ? 1 : -1;
  });
}
1115707
function searchBar_checkSearchResultPage(searchTerm) {
    // Retrieve the URL which is used for the currently selected search engine
    var targetUrl = this._bss.currentEngine.getSubmission(searchTerm, null).uri;
    var currentUrl = this._controller.tabs.activeTabWindow.document.location.href;

    // Check if pure domain names are identical
    var domainName = targetUrl.host.replace(/.+\.(\w+)\.\w+$/gi, "$1");
    var index = currentUrl.indexOf(domainName);

    this._controller.assertJS("subject.URLContainsDomain == true",
                              {URLContainsDomain: currentUrl.indexOf(domainName) != -1});

    // Check if search term is listed in URL
    this._controller.assertJS("subject.URLContainsText == true",
                              {URLContainsText: currentUrl.toLowerCase().indexOf(searchTerm.toLowerCase()) != -1});
  }
920292
def status(DomainName,
             region=None, key=None, keyid=None, profile=None):
    '''
    

    '''

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        domain = conn.describe_elasticsearch_domain(DomainName=DomainName)
        if domain and 'DomainStatus' in domain:
            domain = domain.get('DomainStatus', {})
            keys = ('Endpoint', 'Created', 'Deleted',
                    'DomainName', 'DomainId', 'EBSOptions', 'SnapshotOptions',
                    'AccessPolicies', 'Processing', 'AdvancedOptions', 'ARN',
                    'ElasticsearchVersion')
            return {'domain': dict([(k, domain.get(k)) for k in keys if k in domain])}
        else:
            return {'domain': None}
    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
754268
function sortByCn(certsList) {
  return certsList.concat().sort((a, b) => {
    const domainA = psl.get(a.cns[0].replace('*', 'wildcard'));
    const domainB = psl.get(b.cns[0].replace('*', 'wildcard'));
    if (!domainA || !domainB) return 0;
    return domainA.localeCompare(domainB);
  });
}
482898
def NS(domain, resolve=True, nameserver=None):
    '''
    
    '''
    dig = ['dig', '+short', six.text_type(domain), 'NS']

    if nameserver is not None:
        dig.append('@{0}'.format(nameserver))

    cmd = __salt__['cmd.run_all'](dig, python_shell=False)
    # In this case, 0 is not the same as False
    if cmd['retcode'] != 0:
        log.warning(
            'dig returned exit code \'%s\'. Returning empty list as fallback.',
            cmd['retcode']
        )
        return []

    if resolve:
        ret = []
        for ns_host in cmd['stdout'].split('\n'):
            for ip_addr in A(ns_host, nameserver):
                ret.append(ip_addr)
        return ret

    return cmd['stdout'].split('\n')