Format as detached DNS information as text.
11302
def to_text_format(self):
        ''''''
        return '\n'.join(itertools.chain(
            (self.fetch_date.strftime('%Y%m%d%H%M%S'), ),
            (rr.to_text() for rr in self.resource_records),
            (),
        ))
472459
def TXT(host, nameserver=None):
    '''
    
    '''
    dig = ['dig', '+short', six.text_type(host), 'TXT']

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

    cmd = __salt__['cmd.run_all'](dig, python_shell=False)

    if cmd['retcode'] != 0:
        log.warning(
            'dig returned exit code \'%s\'. Returning empty list as fallback.',
            cmd['retcode']
        )
        return []

    return [i for i in cmd['stdout'].split('\n')]
584056
def reverse_dns_sna(ipaddress):
    """"""

    r = requests.get("http://api.statdns.com/x/%s" % ipaddress)

    if r.status_code == 200:
        names = []

        for item in r.json()['answer']:
            name = str(item['rdata']).strip(".")
            names.append(name)

        return names
    elif r.json()['code'] == 503:
        # NXDOMAIN - no PTR record
        return None
706885
def _format_msg(text, width, indent=0, prefix=""):
    
    """
    text = repr(text).replace("`", "\\`").replace("\\n", " ``\\n`` ")
    sindent = " " * indent if not prefix else prefix
    wrapped_text = textwrap.wrap(text, width, subsequent_indent=sindent)
    # [1:-1] eliminates quotes generated by repr in first line
    return ("\n".join(wrapped_text))[1:-1].rstrip()
1142168
def page_erase(addr):
    """"""
    if __verbose:
        print("Erasing page: 0x%x..." % (addr))

    # Send DNLOAD with first byte=0x41 and page address
    buf = struct.pack("<BI", 0x41, addr)
    __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)

    # Execute last command
    if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
        raise Exception("DFU: erase failed")

    # Check command state
    if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:

        raise Exception("DFU: erase failed")
760355
def netstat(name):
    '''
    
    '''
    sanitize_name = six.text_type(name)
    netstat_infos = __salt__['cmd.run']("netstat -nap")
    found_infos = []
    ret = []
    for info in netstat_infos.splitlines():
        if info.find(sanitize_name) != -1:
            found_infos.append(info)
    ret.extend([sanitize_name, found_infos])
    return ret
154078
def print_info(ds, ds_path=None):
    ""

    if ds_path is None:
        bname = ''
    else:
        bname = basename(ds_path)

    dashes = '-' * len(bname)
    print('\n{}\n{}\n{:full}'.format(dashes, bname, ds))

    return
276027
def url_unsplit (parts):
    """"""
    if parts[2] == default_ports.get(parts[0]):
        return "%s://%s%s" % (parts[0], parts[1], parts[3])
    return "%s://%s:%d%s" % parts
723487
def stripped_db_url(url):
    """"""
    parsed = urlparse(url)

    if parsed.password is None:
        return url

    return parsed._replace(
        netloc="{}:***@{}".format(parsed.username, parsed.hostname)
    ).geturl()
833860
def process_dns_frame(self,
                          id=None,
                          msg=None):
        

        # normalize into a dataframe
        df = json_normalize(msg)
        # convert to a flattened dictionary
        dt = json.loads(df.to_json())

        flat_msg = {}

        for k in dt:
            new_key = "dns_{}".format(k)
            flat_msg[new_key] = dt[k]["0"]
            if new_key not in self.dns_keys:
                self.dns_keys[new_key] = k
        # end of capturing all unique keys

        dt["dns_id"] = id
        self.all_dns.append(dt)

        log.debug("DNS data updated:")
        log.debug(self.dns_keys)
        log.debug(self.all_dns)
        log.debug("")

        return flat_msg
839484
def detached(name):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    zones = __salt__['zoneadm.list'](installed=True, configured=True)
    if name in zones:
        if zones[name]['state'] != 'configured':
            if __opts__['test']:
                res_detach = {'status': True}
            else:
                res_detach = __salt__['zoneadm.detach'](name)
            ret['result'] = res_detach['status']
            if ret['result']:
                ret['changes'][name] = 'detached'
                ret['comment'] = 'The zone {0} was detached.'.format(name)
            else:
                ret['comment'] = []
                ret['comment'].append('Failed to detach zone {0}!'.format(name))
                if 'message' in res_detach:
                    ret['comment'].append(res_detach['message'])
                ret['comment'] = "\n".join(ret['comment'])
        else:
            ret['result'] = True
            ret['comment'] = 'zone {0} already detached.'.format(name)
    else:
        ## note: a non existing zone is not attached, we do not consider this a failure
        ret['result'] = True
        ret['comment'] = 'zone {0} is not configured!'.format(name)

    return ret
1132749
def format_output(instances, flag):
    """"""
    out = []
    line_format = '{0}\t{1}\t{2}\t{3}'
    name_len = _get_max_name_len(instances) + 3
    if flag:
        line_format = '{0:<' + str(name_len+5) + '}{1:<16}{2:<65}{3:<16}'

    for i in instances:
        endpoint = "{0}:{1}".format(i['Endpoint']['Address'], i['Endpoint']['Port'])
        out.append(
            line_format.format(i['DBInstanceIdentifier'], i['DBInstanceStatus'], endpoint, i['Engine']))
    return out
36559
def cmd_dns_lookup_reverse(ip_address, verbose):
    
    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')
        print("Looking up %s..." % ip_address, file=sys.stderr)

    answer = lookup_reverse(ip_address)

    if answer:
        print(json.dumps(answer, indent=4))
    else:
        print("[X] %s is not valid IPv4/IPV6 address" % ip_address)

    return True
738459
def dedent(s):
    """"""
    head, _, tail = s.partition('\n')
    dedented_tail = textwrap.dedent(tail)
    result = "{head}\n{tail}".format(
        head=head,
        tail=dedented_tail)
    return result
361523
def decamelise(text):
    """"""
    s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower()
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')
647121
def output_dns_records(gandi, records, output_keys, justify=12):
    
    for key in output_keys:
        real_key = 'rrset_%s' % key
        if real_key in records:
            val = records[real_key]
            if key == 'values':
                val = format_list(records[real_key])
            output_line(gandi, key, val, justify)