Taken from https://github.com/mafintosh/dns-discovery/blob/4710835fcf83b3e8ab00ae311dcffc63fab5faf1/index.js#L709
422869
function decodeTxt (bufs) {
    var data = {}

    for (var i = 0; i < bufs.length; i++) {
      var buf = bufs[i]
      var j = buf.indexOf(61) // '='
      if (j === -1) data[buf.toString()] = true
      else data[buf.slice(0, j).toString()] = buf.slice(j + 1).toString()
    }

    return data
  }
1292778
def _dnsname_match(dn, hostname, max_wildcards=1):
    
    pats = []
    if not dn:
        return False

    split_dn = dn.split(r'.')
    leftmost, remainder = split_dn[0], split_dn[1:]

    wildcards = leftmost.count('*')
    if wildcards > max_wildcards:
        # Issue #17980: avoid denials of service by refusing more
        # than one wildcard per fragment.  A survey of established
        # policy among SSL implementations showed it to be a
        # reasonable choice.
        raise CertificateError(
            "too many wildcards in certificate DNS name: " + repr(dn))

    # speed up common case w/o wildcards
    if not wildcards:
        return dn.lower() == hostname.lower()

    # RFC 6125, section 6.4.3, subitem 1.
    # The client SHOULD NOT attempt to match a presented identifier in which
    # the wildcard character comprises a label other than the left-most label.
    if leftmost == '*':
        # When '*' is a fragment by itself, it matches a non-empty dotless
        # fragment.
        pats.append('[^.]+')
    elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
        # RFC 6125, section 6.4.3, subitem 3.
        # The client SHOULD NOT attempt to match a presented identifier
        # where the wildcard character is embedded within an A-label or
        # U-label of an internationalized domain name.
        pats.append(re.escape(leftmost))
    else:
        # Otherwise, '*' matches any dotless string, e.g. www*
        pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))

    # add the remaining fragments, ignore any wildcards
    for frag in remainder:
        pats.append(re.escape(frag))

    pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
    return pat.match(hostname)
981559
function convertToZipkinSpan(span) {
  const result = {};
  result.traceId = utility.md5(span.traceId);
  result.parentId = span.parentSpanId;
  result.id = span.spanId;
  result.name = span.name;
  // it's microseconds
  result.timestamp = span.startTime * 1000;
  // it's microseconds
  result.duration = (span.finishTime - span.startTime) * 1000;
  result.tags = span.getTags();

  result.localEndpoint = {
    serviceName: span.getTag('appname'),
    ipv4: span.getTag('local.ipv4'),
    ipv6: span.getTag('local.ipv6'),
    port: span.getTag('local.port'),
  };

  let kind = span.getTag('span.kind');
  if (kind) {
    kind = kind.toUpperCase();
  }
  if ([ 'CLIENT', 'SERVER', 'PRODUCER', 'CONSUMER' ].includes(kind)) {
    result.kind = kind;
    result.remoteEndpoint = {
      serviceName: span.getTag('peer.service'),
      ipv6: span.getTag('peer.ipv6'),
      ipv4: span.getTag('peer.ipv4'),
      port: span.getTag('peer.port'),
    };
  }

  result.annotations = [];
  result.debug = false;
  result.shared = false;
  return result;
}
575326
private function __dnsBucketName($bucket)
	{
		if (strlen($bucket) > 63 || preg_match("/[^a-z0-9\.-]/", $bucket) > 0) return false;
		if (S3::$useSSL && strstr($bucket, '.') !== false) return false;
		if (strstr($bucket, '-.') !== false) return false;
		if (strstr($bucket, '..') !== false) return false;
		if (!preg_match("/^[0-9a-z]/", $bucket)) return false;
		if (!preg_match("/[0-9a-z]$/", $bucket)) return false;
		return true;
	}
434108
function () {
		var host = server.address().address,
			port = server.address().port;
		return "http://" + ((host === "0.0.0.0" || host === "::") ? "localhost" : host) + ":" + port;
	}
304338
function urlJoin() {
    var args = Array.prototype.slice.call(arguments),
        prefixDoubleSlash = false,
        url;

    // Remove empty item at the beginning
    if (args[0] === '') {
        args.shift();
    }

    // Handle schemeless protocols
    if (args[0].indexOf('//') === 0) {
        prefixDoubleSlash = true;
    }

    // join the elements using a slash
    url = args.join('/');

    // Fix multiple slashes
    url = url.replace(/(^|[^:])\/\/+/g, '$1/');

    // Put the double slash back at the beginning if this was a schemeless protocol
    if (prefixDoubleSlash) {
        url = url.replace(/^\//, '//');
    }

    url = deduplicateSubDir(url);
    return url;
}
524202
function (s) {
      if(!net) return null
      var ary = s.split(':')
      if(ary.length < 3) return null
      if('net' !== ary.shift()) return null
      var port = +ary.pop()
      if(isNaN(port)) return null
      return {
        name: 'net',
        host: ary.join(':') || 'localhost',
        port: port
      }
    }
1218185
def namify(root_uri):
    ''''''

    root_uri = unidecode.unidecode(decode(unquote(root_uri), 'utf-8'))

    generic_domains = set(['localhost', 'herokuapp', 'appspot'])
    urlp = urlparse.urlparse(fix_scheme(root_uri))
    formatargs = collections.defaultdict(list)

    netloc = urlp.netloc.lower()
    if ']' in netloc:
        domain = netloc.rsplit(']:', 1)[0]  # don't need port
    elif ':' in netloc:
        domain = netloc.rsplit(':', 1)[0]  # don't need port
    else:
        domain = netloc

    if not translate(domain,"abcdef:.[]").isdigit():
        if '.' in domain:
            domain, tld = domain.rsplit('.', 1)
        else:
            tld = ''
        if '.' in domain:
            subdomain, domain = domain.rsplit('.', 1)
        else:
            subdomain = ''

        if subdomain != 'www':
            formatargs['subdomain'] = subdomain.split('.')
        if domain not in generic_domains:
            formatargs['domain'].append(domain)
        if len(tld) == 2:
            formatargs['tld'].append(tld.upper())
        elif tld != 'com':
            formatargs['tld'].append(tld)

    formatargs['path'].extend(p for p in urlp.path.lower().split('/') if p)
    formatargs['qargs'].extend(r for q in urlp.query.split(',')
                               for r in q.split('=') if q and r)

    def capify(s):
        '''Capitalizes the first letter of a string, but doesn't downcase the
        rest like .title()'''
        return s if not s else s[0].upper() + s[1:]

    def piece_filter(piece):
        if piece.lower() == 'api':
            formatargs['api'] = True
            return ''
        elif re.match(r'v[\d.]+', piece):
            formatargs['version'].extend(['.', piece])
            return ''
        elif 'api' in piece:
            return piece.replace('api', 'API')
        else:
            return piece

    chain = itertools.chain
    pieces = map(capify, map(piece_filter, chain(
        formatargs['subdomain'],
        formatargs['domain'],
        formatargs['tld'],
        formatargs['path'],
        formatargs['qargs'],
    )))
    return '{pieces}{api}{vrsn}'.format(pieces=''.join(pieces),
                                        api='API' if formatargs['api'] else '',
                                        vrsn=''.join(formatargs['version']),
    )
1314766
def _NDP_Attack_DAD_DoS(reply_callback, iface=None, mac_src_filter=None,
                        tgt_filter=None, reply_mac=None):
    

    def is_request(req, mac_src_filter, tgt_filter):
        """
        Check if packet req is a request
        """

        # Those simple checks are based on Section 5.4.2 of RFC 4862
        if not (Ether in req and IPv6 in req and ICMPv6ND_NS in req):
            return 0

        # Get and compare the MAC address
        mac_src = req[Ether].src
        if mac_src_filter and mac_src != mac_src_filter:
            return 0

        # Source must be the unspecified address
        if req[IPv6].src != "::":
            return 0

        # Check destination is the link-local solicited-node multicast
        # address associated with target address in received NS
        tgt = inet_pton(socket.AF_INET6, req[ICMPv6ND_NS].tgt)
        if tgt_filter and tgt != tgt_filter:
            return 0
        received_snma = inet_pton(socket.AF_INET6, req[IPv6].dst)
        expected_snma = in6_getnsma(tgt)
        if received_snma != expected_snma:
            return 0

        return 1

    if not iface:
        iface = conf.iface

    # To prevent sniffing our own traffic
    if not reply_mac:
        reply_mac = get_if_hwaddr(iface)
    sniff_filter = "icmp6 and not ether src %s" % reply_mac

    sniff(store=0,
          filter=sniff_filter,
          lfilter=lambda x: is_request(x, mac_src_filter, tgt_filter),
          prn=lambda x: reply_callback(x, reply_mac, iface),
          iface=iface)
1137845
def lookup(sock, domain, cache = None):
    """"""
    domain = normalize_domain(domain)

    # cache miss, perform lookup
    reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain)

    b64_dest = reply.get('VALUE')
    if b64_dest:
        dest = Dest(b64_dest, encoding='base64')
        if cache:
            cache[dest.base32 + '.b32.i2p'] = dest
        return dest
    else:
        raise NSError('Domain name %r not resolved because %r' % (domain, reply))
265699
function buildNatSecurityGroup(subnets = [], { name = 'NatSecurityGroup' } = {}) {
  const SecurityGroupIngress = [];

  if (Array.isArray(subnets) && subnets.length > 0) {
    subnets.forEach((subnet, index) => {
      const position = index + 1;

      const http = {
        Description: `Allow inbound HTTP traffic from ${APP_SUBNET}Subnet${position}`,
        IpProtocol: 'tcp',
        FromPort: 80,
        ToPort: 80,
        CidrIp: subnet,
      };
      const https = {
        Description: `Allow inbound HTTPS traffic from ${APP_SUBNET}Subnet${position}`,
        IpProtocol: 'tcp',
        FromPort: 443,
        ToPort: 443,
        CidrIp: subnet,
      };
      SecurityGroupIngress.push(http, https);
    });
  }

  return {
    [name]: {
      Type: 'AWS::EC2::SecurityGroup',
      Properties: {
        GroupDescription: 'NAT Instance',
        VpcId: {
          Ref: 'VPC',
        },
        SecurityGroupEgress: [
          {
            Description: 'Allow outbound HTTP access to the Internet',
            IpProtocol: 'tcp',
            FromPort: 80,
            ToPort: 80,
            CidrIp: '0.0.0.0/0',
          },
          {
            Description: 'Allow outbound HTTPS access to the Internet',
            IpProtocol: 'tcp',
            FromPort: 443,
            ToPort: 443,
            CidrIp: '0.0.0.0/0',
          },
        ],
        SecurityGroupIngress,
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  'nat',
                ],
              ],
            },
          },
        ],
      },
    },
  };
}
163382
function getProxyUri(uri) {

	if (uri.protocol === 'https:' && env.httpsProxy || uri.protocol === 'http:' && env.httpProxy) {

		if (env.noProxy) {
			var canonicalHost = uri.host.replace(/^\.*/, '.');
			var port = uri.port || (uri.protocol === 'https:' ? '443' : '80');

			var patterns = env.noProxy.split(',');
			for (var i = patterns.length - 1; i >= 0; i--) {
				var pattern = patterns[i].trim().toLowerCase();

				// don't use a proxy at all
				if (pattern === '*') {
					return null;
				}

				// Remove leading * and make sure to have exact one leading dot (.)
				pattern = pattern.replace(/^[\*]+/, '').replace(/^\.*/, '.');

				// add port if no specified
				if (pattern.indexOf(':') === -1) {
					pattern += ':' + port;
				}

				// if host ends with pattern, no proxy should be used
				if (canonicalHost.indexOf(pattern) === canonicalHost.length - pattern.length) {
					return null;
				}
			}
		}

		if (uri.protocol === 'https:' && env.httpsProxy) {
			return env.httpsProxy;
		} else if (uri.protocol === 'http:' && env.httpProxy) {
			return env.httpProxy;
		}
	}

	return null;
}
118890
function parseDomains(cert) {
    const altNames = [];
    let commonName = null;
    const commonNameMatch = cert.match(/Subject:.*? CN\s?=\s?([^\s,;/]+)/);
    const altNamesMatch = cert.match(/X509v3 Subject Alternative Name:\s?\n\s*([^\n]+)\n/);

    /* Subject common name */
    if (commonNameMatch) {
        commonName = commonNameMatch[1];
    }

    /* Alternative names */
    if (altNamesMatch) {
        altNamesMatch[1].split(/,\s*/).forEach((altName) => {
            if (altName.match(/^DNS:/)) {
                altNames.push(altName.replace(/^DNS:/, ''));
            }
        });
    }

    return {
        commonName,
        altNames
    };
}
920905
def ip_address_subnet(self):
        
        return "{}/{}".format(
            self.interface.ip.compressed, self.interface.exploded.split("/")[-1]
        )
297267
function getAddressNetwork (address) {
  const prefix = base58.decode(address).toString('hex').substring(0, 2).toUpperCase()
  const networkKey = findKey(networks,
    network => [network.pubKeyHash, network.scriptHash].includes(prefix))
  return networks[networkKey]
}
1353428
def version():
    '''
    
    '''
    cmd = 'dnsmasq -v'
    out = __salt__['cmd.run'](cmd).splitlines()
    comps = out[0].split()
    return comps[2]
1253199
function _mapOutDNs(&$root, $path, $asn1)
    {
        $dns = &$this->_subArray($root, $path);

        if (is_array($dns)) {
            $size = count($dns);
            for ($i = 0; $i < $size; $i++) {
                for ($j = 0; $j < count($dns[$i]); $j++) {
                    $type = $dns[$i][$j]['type'];
                    $value = &$dns[$i][$j]['value'];
                    if (is_object($value) && strtolower(get_class($value)) == 'file_asn1_element') {
                        continue;
                    }

                    $map = $this->_getMapping($type);
                    if (!is_bool($map)) {
                        $value = new File_ASN1_Element($asn1->encodeDER($value, $map));
                    }
                }
            }
        }
    }