Best JavaScript code snippet using sinon
ipwhois_cli.py
Source:ipwhois_cli.py  
1# Copyright (c) 2013-2020 Philip Hane2# All rights reserved.3#4# Redistribution and use in source and binary forms, with or without5# modification, are permitted provided that the following conditions are met:6#7# 1. Redistributions of source code must retain the above copyright notice,8#    this list of conditions and the following disclaimer.9# 2. Redistributions in binary form must reproduce the above copyright notice,10#    this list of conditions and the following disclaimer in the documentation11#    and/or other materials provided with the distribution.12#13# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"14# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE17# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR18# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF19# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS20# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN21# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)22# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE23# POSSIBILITY OF SUCH DAMAGE.24# CLI python script interface for ipwhois.IPWhois lookups.25import argparse26import json27from os import path28from ipwhois import IPWhois29from ipwhois.hr import (HR_ASN, HR_RDAP, HR_RDAP_COMMON, HR_WHOIS,30                        HR_WHOIS_NIR)31try:  # pragma: no cover32    from urllib.request import (ProxyHandler,33                                build_opener)34except ImportError:  # pragma: no cover35    from urllib2 import (ProxyHandler,36                         build_opener)37# CLI ANSI rendering38ANSI = {39    'end': '\033[0m',40    'b': '\033[1m',41    'ul': '\033[4m',42    'red': '\033[31m',43    'green': '\033[32m',44    'yellow': '\033[33m',45    'cyan': '\033[36m'46}47# Color definitions for sub lines48COLOR_DEPTH = {49    '0': ANSI['green'],50    '1': ANSI['yellow'],51    '2': ANSI['red'],52    '3': ANSI['cyan']53}54# Line formatting, keys ending in C are colorized versions.55LINES = {56    '1': '>> ',57    '2': '>> >>> ',58    '3': '>> >>> >>>> ',59    '4': '>> >>> >>>> >>>>> ',60    '1C': '{0}>>{1} '.format(COLOR_DEPTH['0'], ANSI['end']),61    '2C': '{0}>>{1} >>>{2} '.format(62        COLOR_DEPTH['0'], COLOR_DEPTH['1'], ANSI['end']63    ),64    '3C': '{0}>>{1} >>>{2} >>>>{3} '.format(65        COLOR_DEPTH['0'], COLOR_DEPTH['1'], COLOR_DEPTH['2'], ANSI['end']66    ),67    '4C': '{0}>>{1} >>>{2} >>>>{3} >>>>>{4} '.format(68        COLOR_DEPTH['0'], COLOR_DEPTH['1'], COLOR_DEPTH['2'], COLOR_DEPTH['3'],69        ANSI['end']70    ),71}72# Setup the arg parser.73parser = argparse.ArgumentParser(74    description='ipwhois CLI interface'75)76parser.add_argument(77    '--whois',78    action='store_true',79    help='Retrieve whois data via legacy Whois (port 43) instead of RDAP '80         '(default).'81)82parser.add_argument(83    '--exclude_nir',84    action='store_true',85    help='Disable NIR whois lookups (JPNIC, KRNIC). This is the opposite of '86         'the ipwhois inc_nir, in order to enable inc_nir by default in the '87         'CLI.',88    default=False89)90parser.add_argument(91    '--json',92    action='store_true',93    help='Output results in JSON format.',94    default=False95)96# Output options97group = parser.add_argument_group('Output options')98group.add_argument(99    '--hr',100    action='store_true',101    help='If set, returns results with human readable key translations.'102)103group.add_argument(104    '--show_name',105    action='store_true',106    help='If this and --hr are set, the key name is shown in parentheses after'107         'its short value'108)109group.add_argument(110    '--colorize',111    action='store_true',112    help='If set, colorizes the output using ANSI. Should work in most '113         'platform consoles.'114)115# IPWhois settings (common)116group = parser.add_argument_group('IPWhois settings')117group.add_argument(118    '--timeout',119    type=int,120    default=5,121    metavar='TIMEOUT',122    help='The default timeout for socket connections in seconds.'123)124group.add_argument(125    '--proxy_http',126    type=str,127    nargs=1,128    default='',129    metavar='"PROXY_HTTP"',130    help='The proxy HTTP address passed to request.ProxyHandler. User auth '131         'can be passed like "http://user:pass@192.168.0.1:80"',132    required=False133)134group.add_argument(135    '--proxy_https',136    type=str,137    nargs=1,138    default='',139    metavar='"PROXY_HTTPS"',140    help='The proxy HTTPS address passed to request.ProxyHandler. User auth'141         'can be passed like "https://user:pass@192.168.0.1:443"',142    required=False143)144# Common (RDAP & Legacy Whois)145group = parser.add_argument_group('Common settings (RDAP & Legacy Whois)')146group.add_argument(147    '--inc_raw',148    action='store_true',149    help='Include the raw whois results in the output.'150)151group.add_argument(152    '--retry_count',153    type=int,154    default=3,155    metavar='RETRY_COUNT',156    help='The number of times to retry in case socket errors, timeouts, '157         'connection resets, etc. are encountered.'158)159group.add_argument(160    '--asn_methods',161    type=str,162    nargs=1,163    default='dns,whois,http',164    metavar='"ASN_METHODS"',165    help='List of ASN lookup types to attempt, in order. '166         'Defaults to all [\'dns\', \'whois\', \'http\'].'167)168group.add_argument(169    '--extra_org_map',170    type=json.loads,171    nargs=1,172    default='{"DNIC": "arin"}',173    metavar='"EXTRA_ORG_MAP"',174    help='Dictionary mapping org handles to RIRs. This is for limited cases '175         'where ARIN REST (ASN fallback HTTP lookup) does not show an RIR as '176         'the org handle e.g., DNIC (which is now the built in ORG_MAP) e.g., '177         '{\\"DNIC\\": \\"arin\\"}. Valid RIR values are (note the '178         'case-sensitive - this is meant to match the REST result): '179         '\'ARIN\', \'RIPE\', \'apnic\', \'lacnic\', \'afrinic\''180)181group.add_argument(182    '--skip_asn_description',183    action='store_true',184    help='Don\'t run an additional query when pulling ASN information via dns '185         '(to get the ASN description). This is the opposite of the ipwhois '186         'get_asn_description argument, in order to enable '187         'get_asn_description by default in the CLI.',188    default=False189)190# RDAP191group = parser.add_argument_group('RDAP settings')192group.add_argument(193    '--depth',194    type=int,195    default=0,196    metavar='COLOR_DEPTH',197    help='If not --whois, how many levels deep to run RDAP queries when '198         'additional referenced objects are found.'199)200group.add_argument(201    '--excluded_entities',202    type=str,203    nargs=1,204    default=None,205    metavar='"EXCLUDED_ENTITIES"',206    help='If not --whois, a comma delimited list of entity handles to not '207         'perform lookups.'208)209group.add_argument(210    '--bootstrap',211    action='store_true',212    help='If not --whois, performs lookups via ARIN bootstrap rather than '213         'lookups based on ASN data. ASN lookups are not performed and no '214         'output for any of the asn* fields is provided.'215)216group.add_argument(217    '--rate_limit_timeout',218    type=int,219    default=120,220    metavar='RATE_LIMIT_TIMEOUT',221    help='If not --whois, the number of seconds to wait before retrying when '222         'a rate limit notice is returned via rdap+json.'223)224# Legacy Whois225group = parser.add_argument_group('Legacy Whois settings')226group.add_argument(227    '--get_referral',228    action='store_true',229    help='If --whois, retrieve referral whois information, if available.'230)231group.add_argument(232    '--extra_blacklist',233    type=str,234    nargs=1,235    default='',236    metavar='"EXTRA_BLACKLIST"',237    help='If --whois, A list of blacklisted whois servers in addition to the '238         'global BLACKLIST.'239)240group.add_argument(241    '--ignore_referral_errors',242    action='store_true',243    help='If --whois, ignore and continue when an exception is encountered on '244         'referral whois lookups.'245)246group.add_argument(247    '--field_list',248    type=str,249    nargs=1,250    default='',251    metavar='"FIELD_LIST"',252    help='If --whois, a list of fields to parse: '253         '[\'name\', \'handle\', \'description\', \'country\', \'state\', '254         '\'city\', \'address\', \'postal_code\', \'emails\', \'created\', '255         '\'updated\']'256)257# NIR (National Internet Registry -- JPNIC, KRNIC)258group = parser.add_argument_group('NIR (National Internet Registry) settings')259group.add_argument(260    '--nir_field_list',261    type=str,262    nargs=1,263    default='',264    metavar='"NIR_FIELD_LIST"',265    help='If not --exclude_nir, a list of fields to parse: '266         '[\'name\', \'handle\', \'country\', \'address\', \'postal_code\', '267         '\'nameservers\', \'created\', \'updated\', \'contact_admin\', '268         '\'contact_tech\']'269)270# Input (required)271group = parser.add_argument_group('Input (Required)')272group.add_argument(273    '--addr',274    type=str,275    nargs=1,276    metavar='"IP"',277    help='An IPv4 or IPv6 address as a string.',278    required=True279)280# Get the args281script_args = parser.parse_args()282# Get the current working directory.283CUR_DIR = path.dirname(__file__)284def generate_output(line='0', short=None, name=None, value=None,285                    is_parent=False, colorize=True):286    """287    The function for formatting CLI output results.288    Args:289        line (:obj:`str`): The line number (0-4). Determines indentation.290            Defaults to '0'.291        short (:obj:`str`): The optional abbreviated name for a field.292            See hr.py for values.293        name (:obj:`str`): The optional name for a field. See hr.py for values.294        value (:obj:`str`): The field data (required).295        is_parent (:obj:`bool`): Set to True if the field value has sub-items296            (dicts/lists). Defaults to False.297        colorize (:obj:`bool`): Colorize the console output with ANSI colors.298            Defaults to True.299    Returns:300        str: The generated output.301    """302    # TODO: so ugly303    output = '{0}{1}{2}{3}{4}{5}{6}{7}\n'.format(304        LINES['{0}{1}'.format(line, 'C' if colorize else '')] if (305            line in LINES.keys()) else '',306        COLOR_DEPTH[line] if (colorize and line in COLOR_DEPTH) else '',307        ANSI['b'],308        short if short is not None else (309            name if (name is not None) else ''310        ),311        '' if (name is None or short is None) else ' ({0})'.format(312            name),313        '' if (name is None and short is None) else ': ',314        ANSI['end'] if colorize else '',315        '' if is_parent else value316    )317    return output318class IPWhoisCLI:319    """320    The CLI wrapper class for outputting formatted IPWhois results.321    Args:322        addr (:obj:`str`/:obj:`int`/:obj:`IPv4Address`/:obj:`IPv6Address`):323            An IPv4 or IPv6 address324        timeout (:obj:`int`): The default timeout for socket connections in325            seconds. Defaults to 5.326        proxy_http (:obj:`urllib.request.OpenerDirector`): The request for327            proxy HTTP support or None.328        proxy_https (:obj:`urllib.request.OpenerDirector`): The request for329            proxy HTTPS support or None.330    """331    def __init__(332        self,333        addr,334        timeout,335        proxy_http,336        proxy_https337    ):338        self.addr = addr339        self.timeout = timeout340        handler_dict = None341        if proxy_http is not None:342            handler_dict = {'http': proxy_http}343        if proxy_https is not None:344            if handler_dict is None:345                handler_dict = {'https': proxy_https}346            else:347                handler_dict['https'] = proxy_https348        if handler_dict is None:349            self.opener = None350        else:351            handler = ProxyHandler(handler_dict)352            self.opener = build_opener(handler)353        self.obj = IPWhois(address=self.addr,354                           timeout=self.timeout,355                           proxy_opener=self.opener)356    def generate_output_header(self, query_type='RDAP'):357        """358        The function for generating the CLI output header.359        Args:360            query_type (:obj:`str`): The IPWhois query type. Defaults to361                'RDAP'.362        Returns:363            str: The generated output.364        """365        output = '\n{0}{1}{2} query for {3}:{4}\n\n'.format(366            ANSI['ul'],367            ANSI['b'],368            query_type,369            self.obj.address_str,370            ANSI['end']371        )372        return output373    def generate_output_newline(self, line='0', colorize=True):374        """375        The function for generating a CLI output new line.376        Args:377            line (:obj:`str`): The line number (0-4). Determines indentation.378                Defaults to '0'.379            colorize (:obj:`bool`): Colorize the console output with ANSI380                colors. Defaults to True.381        Returns:382            str: The generated output.383        """384        return generate_output(385            line=line,386            is_parent=True,387            colorize=colorize388        )389    def generate_output_asn(self, json_data=None, hr=True, show_name=False,390                            colorize=True):391        """392        The function for generating CLI output ASN results.393        Args:394            json_data (:obj:`dict`): The data to process. Defaults to None.395            hr (:obj:`bool`): Enable human readable key translations. Defaults396                to True.397            show_name (:obj:`bool`): Show human readable name (default is to398                only show short). Defaults to False.399            colorize (:obj:`bool`): Colorize the console output with ANSI400                colors. Defaults to True.401        Returns:402            str: The generated output.403        """404        if json_data is None:405            json_data = {}406        keys = {'asn', 'asn_cidr', 'asn_country_code', 'asn_date',407                'asn_registry', 'asn_description'}.intersection(json_data)408        output = ''409        for key in keys:410            output += generate_output(411                line='0',412                short=HR_ASN[key]['_short'] if hr else key,413                name=HR_ASN[key]['_name'] if (hr and show_name) else None,414                value=(json_data[key] if (415                    json_data[key] is not None and416                    len(json_data[key]) > 0 and417                    json_data[key] != 'NA') else 'None'),418                colorize=colorize419            )420        return output421    def generate_output_entities(self, json_data=None, hr=True,422                                 show_name=False, colorize=True):423        """424        The function for generating CLI output RDAP entity results.425        Args:426            json_data (:obj:`dict`): The data to process. Defaults to None.427            hr (:obj:`bool`): Enable human readable key translations. Defaults428                to True.429            show_name (:obj:`bool`): Show human readable name (default is to430                only show short). Defaults to False.431            colorize (:obj:`bool`): Colorize the console output with ANSI432                colors. Defaults to True.433        Returns:434            str: The generated output.435        """436        output = ''437        short = HR_RDAP['entities']['_short'] if hr else 'entities'438        name = HR_RDAP['entities']['_name'] if (hr and show_name) else None439        output += generate_output(440            line='0',441            short=short,442            name=name,443            is_parent=False if (json_data is None or444                                json_data['entities'] is None) else True,445            value='None' if (json_data is None or446                             json_data['entities'] is None) else None,447            colorize=colorize448        )449        if json_data is not None:450            for ent in json_data['entities']:451                output += generate_output(452                    line='1',453                    value=ent,454                    colorize=colorize455                )456        return output457    def generate_output_events(self, source, key, val, line='2', hr=True,458                               show_name=False, colorize=True):459        """460        The function for generating CLI output RDAP events results.461        Args:462            source (:obj:`str`): The parent key 'network' or 'objects'463                (required).464            key (:obj:`str`): The event key 'events' or 'events_actor'465                (required).466            val (:obj:`dict`): The event dictionary (required).467            line (:obj:`str`): The line number (0-4). Determines indentation.468                Defaults to '0'.469            hr (:obj:`bool`): Enable human readable key translations. Defaults470                to True.471            show_name (:obj:`bool`): Show human readable name (default is to472                only show short). Defaults to False.473            colorize (:obj:`bool`): Colorize the console output with ANSI474                colors. Defaults to True.475        Returns:476            str: The generated output.477        """478        output = generate_output(479            line=line,480            short=HR_RDAP[source][key]['_short'] if hr else key,481            name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,482            is_parent=False if (val is None or483                                len(val) == 0) else True,484            value='None' if (val is None or485                             len(val) == 0) else None,486            colorize=colorize487        )488        if val is not None:489            count = 0490            for item in val:491                try:492                    action = item['action']493                except KeyError:494                    action = None495                try:496                    timestamp = item['timestamp']497                except KeyError:498                    timestamp = None499                try:500                    actor = item['actor']501                except KeyError:502                    actor = None503                if count > 0:504                    output += generate_output(505                        line=str(int(line)+1),506                        is_parent=True,507                        colorize=colorize508                    )509                output += generate_output(510                    line=str(int(line)+1),511                    short=HR_RDAP_COMMON[key]['action'][512                        '_short'] if hr else 'action',513                    name=HR_RDAP_COMMON[key]['action'][514                        '_name'] if (hr and show_name) else None,515                    value=action,516                    colorize=colorize517                )518                output += generate_output(519                    line=str(int(line)+1),520                    short=HR_RDAP_COMMON[key]['timestamp'][521                        '_short'] if hr else 'timestamp',522                    name=HR_RDAP_COMMON[key]['timestamp'][523                        '_name'] if (hr and show_name) else None,524                    value=timestamp,525                    colorize=colorize526                )527                output += generate_output(528                    line=str(int(line)+1),529                    short=HR_RDAP_COMMON[key]['actor'][530                        '_short'] if hr else 'actor',531                    name=HR_RDAP_COMMON[key]['actor'][532                        '_name'] if (hr and show_name) else None,533                    value=actor,534                    colorize=colorize535                )536                count += 1537        return output538    def generate_output_list(self, source, key, val, line='2', hr=True,539                             show_name=False, colorize=True):540        """541        The function for generating CLI output RDAP list results.542        Args:543            source (:obj:`str`): The parent key 'network' or 'objects'544                (required).545            key (:obj:`str`): The event key 'events' or 'events_actor'546                (required).547            val (:obj:`dict`): The event dictionary (required).548            line (:obj:`str`): The line number (0-4). Determines indentation.549                Defaults to '0'.550            hr (:obj:`bool`): Enable human readable key translations. Defaults551                to True.552            show_name (:obj:`bool`): Show human readable name (default is to553                only show short). Defaults to False.554            colorize (:obj:`bool`): Colorize the console output with ANSI555                colors. Defaults to True.556        Returns:557            str: The generated output.558        """559        output = generate_output(560            line=line,561            short=HR_RDAP[source][key]['_short'] if hr else key,562            name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,563            is_parent=False if (val is None or564                                len(val) == 0) else True,565            value='None' if (val is None or566                             len(val) == 0) else None,567            colorize=colorize568        )569        if val is not None:570            for item in val:571                output += generate_output(572                    line=str(int(line)+1),573                    value=item,574                    colorize=colorize575                )576        return output577    def generate_output_notices(self, source, key, val, line='1', hr=True,578                                show_name=False, colorize=True):579        """580        The function for generating CLI output RDAP notices results.581        Args:582            source (:obj:`str`): The parent key 'network' or 'objects'583                (required).584            key (:obj:`str`): The event key 'events' or 'events_actor'585                (required).586            val (:obj:`dict`): The event dictionary (required).587            line (:obj:`str`): The line number (0-4). Determines indentation.588                Defaults to '0'.589            hr (:obj:`bool`): Enable human readable key translations. Defaults590                to True.591            show_name (:obj:`bool`): Show human readable name (default is to592                only show short). Defaults to False.593            colorize (:obj:`bool`): Colorize the console output with ANSI594                colors. Defaults to True.595        Returns:596            str: The generated output.597        """598        output = generate_output(599            line=line,600            short=HR_RDAP[source][key]['_short'] if hr else key,601            name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,602            is_parent=False if (val is None or603                                len(val) == 0) else True,604            value='None' if (val is None or605                             len(val) == 0) else None,606            colorize=colorize607        )608        if val is not None:609            count = 0610            for item in val:611                title = item['title']612                description = item['description']613                links = item['links']614                if count > 0:615                    output += generate_output(616                        line=str(int(line)+1),617                        is_parent=True,618                        colorize=colorize619                    )620                output += generate_output(621                    line=str(int(line)+1),622                    short=HR_RDAP_COMMON[key]['title']['_short'] if hr else (623                        'title'),624                    name=HR_RDAP_COMMON[key]['title']['_name'] if (625                        hr and show_name) else None,626                    value=title,627                    colorize=colorize628                )629                output += generate_output(630                    line=str(int(line)+1),631                    short=HR_RDAP_COMMON[key]['description'][632                        '_short'] if hr else 'description',633                    name=HR_RDAP_COMMON[key]['description'][634                        '_name'] if (hr and show_name) else None,635                    value=description.replace(636                        '\n',637                        '\n{0}'.format(generate_output(line='3'))638                    ),639                    colorize=colorize640                )641                output += self.generate_output_list(642                    source=source,643                    key='links',644                    val=links,645                    line=str(int(line)+1),646                    hr=hr,647                    show_name=show_name,648                    colorize=colorize649                )650                count += 1651        return output652    def generate_output_network(self, json_data=None, hr=True, show_name=False,653                                colorize=True):654        """655        The function for generating CLI output RDAP network results.656        Args:657            json_data (:obj:`dict`): The data to process. Defaults to None.658            hr (:obj:`bool`): Enable human readable key translations. Defaults659                to True.660            show_name (:obj:`bool`): Show human readable name (default is to661                only show short). Defaults to False.662            colorize (:obj:`bool`): Colorize the console output with ANSI663                colors. Defaults to True.664        Returns:665            str: The generated output.666        """667        if json_data is None:668            json_data = {}669        output = generate_output(670            line='0',671            short=HR_RDAP['network']['_short'] if hr else 'network',672            name=HR_RDAP['network']['_name'] if (hr and show_name) else None,673            is_parent=True,674            colorize=colorize675        )676        for key, val in json_data['network'].items():677            if key in ['links', 'status']:678                output += self.generate_output_list(679                    source='network',680                    key=key,681                    val=val,682                    line='1',683                    hr=hr,684                    show_name=show_name,685                    colorize=colorize686                )687            elif key in ['notices', 'remarks']:688                output += self.generate_output_notices(689                    source='network',690                    key=key,691                    val=val,692                    line='1',693                    hr=hr,694                    show_name=show_name,695                    colorize=colorize696                )697            elif key == 'events':698                output += self.generate_output_events(699                    source='network',700                    key=key,701                    val=val,702                    line='1',703                    hr=hr,704                    show_name=show_name,705                    colorize=colorize706                )707            elif key not in ['raw']:708                output += generate_output(709                    line='1',710                    short=HR_RDAP['network'][key]['_short'] if hr else key,711                    name=HR_RDAP['network'][key]['_name'] if (712                        hr and show_name) else None,713                    value=val,714                    colorize=colorize715                )716        return output717    def generate_output_objects(self, json_data=None, hr=True, show_name=False,718                                colorize=True):719        """720        The function for generating CLI output RDAP object results.721        Args:722            json_data (:obj:`dict`): The data to process. Defaults to None.723            hr (:obj:`bool`): Enable human readable key translations. Defaults724                to True.725            show_name (:obj:`bool`): Show human readable name (default is to726                only show short). Defaults to False.727            colorize (:obj:`bool`): Colorize the console output with ANSI728                colors. Defaults to True.729        Returns:730            str: The generated output.731        """732        if json_data is None:733            json_data = {}734        output = generate_output(735            line='0',736            short=HR_RDAP['objects']['_short'] if hr else 'objects',737            name=HR_RDAP['objects']['_name'] if (hr and show_name) else None,738            is_parent=True,739            colorize=colorize740        )741        count = 0742        for obj_name, obj in json_data['objects'].items():743            if count > 0:744                output += self.generate_output_newline(745                    line='1',746                    colorize=colorize747                )748            count += 1749            output += generate_output(750                line='1',751                short=obj_name,752                is_parent=True,753                colorize=colorize754            )755            for key, val in obj.items():756                if key in ['links', 'entities', 'roles', 'status']:757                    output += self.generate_output_list(758                        source='objects',759                        key=key,760                        val=val,761                        line='2',762                        hr=hr,763                        show_name=show_name,764                        colorize=colorize765                    )766                elif key in ['notices', 'remarks']:767                    output += self.generate_output_notices(768                        source='objects',769                        key=key,770                        val=val,771                        line='2',772                        hr=hr,773                        show_name=show_name,774                        colorize=colorize775                    )776                elif key == 'events':777                    output += self.generate_output_events(778                        source='objects',779                        key=key,780                        val=val,781                        line='2',782                        hr=hr,783                        show_name=show_name,784                        colorize=colorize785                    )786                elif key == 'contact':787                    output += generate_output(788                        line='2',789                        short=HR_RDAP['objects']['contact'][790                            '_short'] if hr else 'contact',791                        name=HR_RDAP['objects']['contact']['_name'] if (792                            hr and show_name) else None,793                        is_parent=False if (val is None or794                                            len(val) == 0) else True,795                        value='None' if (val is None or796                                         len(val) == 0) else None,797                        colorize=colorize798                    )799                    if val is not None:800                        for k, v in val.items():801                            if k in ['phone', 'address', 'email']:802                                output += generate_output(803                                    line='3',804                                    short=HR_RDAP['objects']['contact'][k][805                                        '_short'] if hr else k,806                                    name=HR_RDAP['objects']['contact'][k][807                                        '_name'] if (808                                        hr and show_name) else None,809                                    is_parent=False if (810                                        val is None or811                                        len(val) == 0812                                    ) else True,813                                    value='None' if (val is None or814                                                     len(val) == 0) else None,815                                    colorize=colorize816                                )817                                if v is not None:818                                    for item in v:819                                        i_type = ', '.join(item['type']) if (820                                            isinstance(item['type'], list)821                                        ) else item['type']822                                        i_type = i_type if (823                                            i_type is not None and824                                            len(i_type) > 0) else ''825                                        i_value = item['value'].replace(826                                            '\n',827                                            '\n{0}'.format(828                                                generate_output(829                                                    line='4',830                                                    is_parent=True,831                                                    colorize=colorize832                                                ).replace('\n', ''))833                                        )834                                        tmp_out = '{0}{1}{2}'.format(835                                            i_type,836                                            ': ' if i_type != '' else '',837                                            i_value838                                        )839                                        output += generate_output(840                                            line='4',841                                            value=tmp_out,842                                            colorize=colorize843                                        )844                            else:845                                output += generate_output(846                                    line='3',847                                    short=HR_RDAP['objects']['contact'][k][848                                        '_short'] if hr else k,849                                    name=HR_RDAP['objects']['contact'][k][850                                        '_name'] if (851                                        hr and show_name) else None,852                                    value=v,853                                    colorize=colorize854                                )855                elif key not in ['raw']:856                    output += generate_output(857                        line='2',858                        short=HR_RDAP['objects'][key]['_short'] if hr else key,859                        name=HR_RDAP['objects'][key]['_name'] if (860                            hr and show_name) else None,861                        value=val,862                        colorize=colorize863                    )864        return output865    def lookup_rdap(self, hr=True, show_name=False, colorize=True, **kwargs):866        """867        The function for wrapping IPWhois.lookup_rdap() and generating868        formatted CLI output.869        Args:870            hr (:obj:`bool`): Enable human readable key translations. Defaults871                to True.872            show_name (:obj:`bool`): Show human readable name (default is to873                only show short). Defaults to False.874            colorize (:obj:`bool`): Colorize the console output with ANSI875                colors. Defaults to True.876            kwargs: Arguments to pass to IPWhois.lookup_rdap().877        Returns:878            str: The generated output.879        """880        # Perform the RDAP lookup881        ret = self.obj.lookup_rdap(**kwargs)882        if script_args.json:883            output = json.dumps(ret)884        else:885            # Header886            output = self.generate_output_header(query_type='RDAP')887            # ASN888            output += self.generate_output_asn(889                json_data=ret, hr=hr, show_name=show_name, colorize=colorize890            )891            output += self.generate_output_newline(colorize=colorize)892            # Entities893            output += self.generate_output_entities(894                json_data=ret, hr=hr, show_name=show_name, colorize=colorize895            )896            output += self.generate_output_newline(colorize=colorize)897            # Network898            output += self.generate_output_network(899                json_data=ret, hr=hr, show_name=show_name, colorize=colorize900            )901            output += self.generate_output_newline(colorize=colorize)902            # Objects903            output += self.generate_output_objects(904                json_data=ret, hr=hr, show_name=show_name, colorize=colorize905            )906            output += self.generate_output_newline(colorize=colorize)907            if 'nir' in ret:908                # NIR909                output += self.generate_output_nir(910                    json_data=ret, hr=hr, show_name=show_name,911                    colorize=colorize912                )913                output += self.generate_output_newline(colorize=colorize)914        return output915    def generate_output_whois_nets(self, json_data=None, hr=True,916                                   show_name=False, colorize=True):917        """918        The function for generating CLI output Legacy Whois networks results.919        Args:920            json_data (:obj:`dict`): The data to process. Defaults to None.921            hr (:obj:`bool`): Enable human readable key translations. Defaults922                to True.923            show_name (:obj:`bool`): Show human readable name (default is to924                only show short). Defaults to False.925            colorize (:obj:`bool`): Colorize the console output with ANSI926                colors. Defaults to True.927        Returns:928            str: The generated output.929        """930        if json_data is None:931            json_data = {}932        output = generate_output(933            line='0',934            short=HR_WHOIS['nets']['_short'] if hr else 'nets',935            name=HR_WHOIS['nets']['_name'] if (hr and show_name) else None,936            is_parent=True,937            colorize=colorize938        )939        count = 0940        for net in json_data['nets']:941            if count > 0:942                output += self.generate_output_newline(943                    line='1',944                    colorize=colorize945                )946            count += 1947            output += generate_output(948                line='1',949                short=net['handle'],950                is_parent=True,951                colorize=colorize952            )953            for key, val in net.items():954                if val and '\n' in val:955                    output += generate_output(956                        line='2',957                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,958                        name=HR_WHOIS['nets'][key]['_name'] if (959                            hr and show_name) else None,960                        is_parent=False if (val is None or961                                            len(val) == 0) else True,962                        value='None' if (val is None or963                                         len(val) == 0) else None,964                        colorize=colorize965                    )966                    for v in val.split('\n'):967                        output += generate_output(968                            line='3',969                            value=v,970                            colorize=colorize971                        )972                else:973                    output += generate_output(974                        line='2',975                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,976                        name=HR_WHOIS['nets'][key]['_name'] if (977                            hr and show_name) else None,978                        value=val,979                        colorize=colorize980                    )981        return output982    def generate_output_whois_referral(self, json_data=None, hr=True,983                                       show_name=False, colorize=True):984        """985        The function for generating CLI output Legacy Whois referral results.986        Args:987            json_data (:obj:`dict`): The data to process. Defaults to None.988            hr (:obj:`bool`): Enable human readable key translations. Defaults989                to True.990            show_name (:obj:`bool`): Show human readable name (default is to991                only show short). Defaults to False.992            colorize (:obj:`bool`): Colorize the console output with ANSI993                colors. Defaults to True.994        Returns:995            str: The generated output.996        """997        if json_data is None:998            json_data = {}999        output = generate_output(1000            line='0',1001            short=HR_WHOIS['referral']['_short'] if hr else 'referral',1002            name=HR_WHOIS['referral']['_name'] if (hr and show_name) else None,1003            is_parent=False if json_data['referral'] is None else True,1004            value='None' if json_data['referral'] is None else None,1005            colorize=colorize1006        )1007        if json_data['referral']:1008            for key, val in json_data['referral'].items():1009                if val and '\n' in val:1010                    output += generate_output(1011                        line='1',1012                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,1013                        name=HR_WHOIS['nets'][key]['_name'] if (1014                            hr and show_name) else None,1015                        is_parent=False if (val is None or1016                                            len(val) == 0) else True,1017                        value='None' if (val is None or1018                                         len(val) == 0) else None,1019                        colorize=colorize1020                    )1021                    for v in val.split('\n'):1022                        output += generate_output(1023                            line='2',1024                            value=v,1025                            colorize=colorize1026                        )1027                else:1028                    output += generate_output(1029                        line='1',1030                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,1031                        name=HR_WHOIS['nets'][key]['_name'] if (1032                            hr and show_name) else None,1033                        value=val,1034                        colorize=colorize1035                    )1036        return output1037    def generate_output_nir(self, json_data=None, hr=True, show_name=False,1038                            colorize=True):1039        """1040        The function for generating CLI output NIR network results.1041        Args:1042            json_data (:obj:`dict`): The data to process. Defaults to None.1043            hr (:obj:`bool`): Enable human readable key translations. Defaults1044                to True.1045            show_name (:obj:`bool`): Show human readable name (default is to1046                only show short). Defaults to False.1047            colorize (:obj:`bool`): Colorize the console output with ANSI1048                colors. Defaults to True.1049        Returns:1050            str: The generated output.1051        """1052        if json_data is None:1053            json_data = {}1054        output = generate_output(1055            line='0',1056            short=HR_WHOIS_NIR['nets']['_short'] if hr else 'nir_nets',1057            name=HR_WHOIS_NIR['nets']['_name'] if (hr and show_name) else None,1058            is_parent=True,1059            colorize=colorize1060        )1061        count = 01062        if json_data['nir']:1063            for net in json_data['nir']['nets']:1064                if count > 0:1065                    output += self.generate_output_newline(1066                        line='1',1067                        colorize=colorize1068                    )1069                count += 11070                output += generate_output(1071                    line='1',1072                    short=net['handle'],1073                    is_parent=True,1074                    colorize=colorize1075                )1076                for key, val in net.items():1077                    if val and (isinstance(val, dict) or '\n' in val or1078                                key == 'nameservers'):1079                        output += generate_output(1080                            line='2',1081                            short=(1082                                HR_WHOIS_NIR['nets'][key]['_short'] if (1083                                    hr) else key1084                            ),1085                            name=HR_WHOIS_NIR['nets'][key]['_name'] if (1086                                hr and show_name) else None,1087                            is_parent=False if (val is None or1088                                                len(val) == 0) else True,1089                            value='None' if (val is None or1090                                             len(val) == 0) else None,1091                            colorize=colorize1092                        )1093                        if key == 'contacts':1094                            for k, v in val.items():1095                                if v:1096                                    output += generate_output(1097                                        line='3',1098                                        is_parent=False if (1099                                            len(v) == 0) else True,1100                                        name=k,1101                                        colorize=colorize1102                                    )1103                                    for contact_key, contact_val in v.items():1104                                        if v is not None:1105                                            tmp_out = '{0}{1}{2}'.format(1106                                                contact_key,1107                                                ': ',1108                                                contact_val1109                                            )1110                                            output += generate_output(1111                                                line='4',1112                                                value=tmp_out,1113                                                colorize=colorize1114                                            )1115                        elif key == 'nameservers':1116                            for v in val:1117                                output += generate_output(1118                                    line='3',1119                                    value=v,1120                                    colorize=colorize1121                                )1122                        else:1123                            for v in val.split('\n'):1124                                output += generate_output(1125                                    line='3',1126                                    value=v,1127                                    colorize=colorize1128                                )1129                    else:1130                        output += generate_output(1131                            line='2',1132                            short=(1133                                HR_WHOIS_NIR['nets'][key]['_short'] if (1134                                    hr) else key1135                            ),1136                            name=HR_WHOIS_NIR['nets'][key]['_name'] if (1137                                hr and show_name) else None,1138                            value=val,1139                            colorize=colorize1140                        )1141        else:1142            output += 'None'1143        return output1144    def lookup_whois(self, hr=True, show_name=False, colorize=True, **kwargs):1145        """1146        The function for wrapping IPWhois.lookup_whois() and generating1147        formatted CLI output.1148        Args:1149            hr (:obj:`bool`): Enable human readable key translations. Defaults1150                to True.1151            show_name (:obj:`bool`): Show human readable name (default is to1152                only show short). Defaults to False.1153            colorize (:obj:`bool`): Colorize the console output with ANSI1154                colors. Defaults to True.1155            kwargs: Arguments to pass to IPWhois.lookup_whois().1156        Returns:1157            str: The generated output.1158        """1159        # Perform the RDAP lookup1160        ret = self.obj.lookup_whois(**kwargs)1161        if script_args.json:1162            output = json.dumps(ret)1163        else:1164            # Header1165            output = self.generate_output_header(query_type='Legacy Whois')1166            # ASN1167            output += self.generate_output_asn(1168                json_data=ret, hr=hr, show_name=show_name, colorize=colorize1169            )1170            output += self.generate_output_newline(colorize=colorize)1171            # Network1172            output += self.generate_output_whois_nets(1173                json_data=ret, hr=hr, show_name=show_name, colorize=colorize1174            )1175            output += self.generate_output_newline(colorize=colorize)1176            # Referral1177            output += self.generate_output_whois_referral(1178                json_data=ret, hr=hr, show_name=show_name, colorize=colorize1179            )1180            output += self.generate_output_newline(colorize=colorize)1181            if 'nir' in ret:1182                # NIR1183                output += self.generate_output_nir(1184                    json_data=ret, hr=hr, show_name=show_name,1185                    colorize=colorize1186                )1187                output += self.generate_output_newline(colorize=colorize)1188        return output1189if script_args.addr:1190    results = IPWhoisCLI(1191        addr=script_args.addr[0],1192        timeout=script_args.timeout,1193        proxy_http=script_args.proxy_http if (1194            script_args.proxy_http and len(script_args.proxy_http) > 01195        ) else None,1196        proxy_https=script_args.proxy_https if (1197            script_args.proxy_https and len(script_args.proxy_https) > 01198        ) else None1199    )1200    if script_args.whois:1201        print(results.lookup_whois(1202            hr=script_args.hr,1203            show_name=script_args.show_name,1204            colorize=script_args.colorize,1205            inc_raw=script_args.inc_raw,1206            retry_count=script_args.retry_count,1207            get_referral=script_args.get_referral,1208            extra_blacklist=script_args.extra_blacklist.split(',') if (1209                script_args.extra_blacklist and1210                len(script_args.extra_blacklist) > 0) else None,1211            ignore_referral_errors=script_args.ignore_referral_errors,1212            field_list=script_args.field_list.split(',') if (1213                script_args.field_list and1214                len(script_args.field_list) > 0) else None,1215            extra_org_map=script_args.extra_org_map,1216            inc_nir=(not script_args.exclude_nir),1217            nir_field_list=script_args.nir_field_list.split(',') if (1218                script_args.nir_field_list and1219                len(script_args.nir_field_list) > 0) else None,1220            asn_methods=script_args.asn_methods.split(',') if (1221                script_args.asn_methods and1222                len(script_args.asn_methods) > 0) else None,1223            get_asn_description=(not script_args.skip_asn_description)1224        ))1225    else:1226        print(results.lookup_rdap(1227            hr=script_args.hr,1228            show_name=script_args.show_name,1229            colorize=script_args.colorize,1230            inc_raw=script_args.inc_raw,1231            retry_count=script_args.retry_count,1232            depth=script_args.depth,1233            excluded_entities=script_args.excluded_entities.split(',') if (1234                script_args.excluded_entities and1235                len(script_args.excluded_entities) > 0) else None,1236            bootstrap=script_args.bootstrap,1237            rate_limit_timeout=script_args.rate_limit_timeout,1238            extra_org_map=script_args.extra_org_map,1239            inc_nir=(not script_args.exclude_nir),1240            nir_field_list=script_args.nir_field_list.split(',') if (1241                script_args.nir_field_list and1242                len(script_args.nir_field_list) > 0) else None,1243            asn_methods=script_args.asn_methods.split(',') if (1244                script_args.asn_methods and1245                len(script_args.asn_methods) > 0) else None,1246            get_asn_description=(not script_args.skip_asn_description)...ls.py
Source:ls.py  
1"""2Look inside HDF5 files from the terminal, especially those created by deepdish.3"""4from __future__ import division, print_function, absolute_import5from .hdf5io import (DEEPDISH_IO_VERSION_STR, DEEPDISH_IO_PREFIX,6                     DEEPDISH_IO_UNPACK, DEEPDISH_IO_ROOT_IS_SNS,7                     IO_VERSION, _sns, is_pandas_dataframe)8import tables9import numpy as np10import sys11import os12import re13from deepdish import io, six, __version__14COLORS = dict(15    black='30',16    darkgray='2;39',17    red='0;31',18    green='0;32',19    brown='0;33',20    yellow='0;33',21    blue='0;34',22    purple='0;35',23    cyan='0;36',24    white='0;39',25    reset='0'26)27MIN_COLUMN_WIDTH = 528MIN_AUTOMATIC_COLUMN_WIDTH = 2029MAX_AUTOMATIC_COLUMN_WIDTH = 8030ABRIDGE_OVER_N_CHILDREN = 5031ABRIDGE_SHOW_EACH_SIDE = 532def _format_dtype(dtype):33    dtype = np.dtype(dtype)34    dtype_str = dtype.name35    if dtype.byteorder == '<':36        dtype_str += ' little-endian'37    elif dtype.byteorder == '>':38        dtype_str += ' big-endian'39    return dtype_str40def _pandas_shape(level):41    if 'ndim' in level._v_attrs:42        ndim = level._v_attrs['ndim']43        shape = []44        for i in range(ndim):45            axis_name = 'axis{}'.format(i)46            if axis_name in level._v_children:47                axis = len(level._v_children[axis_name])48                shape.append(axis)49            elif axis_name + '_label0' in level._v_children:50                axis = len(level._v_children[axis_name + '_label0'])51                shape.append(axis)52            else:53                return None54        return tuple(shape)55def sorted_maybe_numeric(x):56    """57    Sorts x with numeric semantics if all keys are nonnegative integers.58    Otherwise uses standard string sorting.59    """60    all_numeric = all(map(str.isdigit, x))61    if all_numeric:62        return sorted(x, key=int)63    else:64        return sorted(x)65def paint(s, color, colorize=True):66    if colorize:67        if color in COLORS:68            return '\033[{}m{}\033[0m'.format(COLORS[color], s)69        else:70            raise ValueError('Invalid color')71    else:72        return s73def type_string(typename, dtype=None, extra=None,74                type_color='red', colorize=True):75    ll = [paint(typename, type_color, colorize=colorize)]76    if extra:77        ll += [extra]78    if dtype:79        ll += [paint('[' + dtype + ']', 'darkgray', colorize=colorize)]80    return ' '.join(ll)81def container_info(name, size=None, colorize=True, type_color=None,82                   final_level=False):83    if final_level:84        d = {}85        if size is not None:86            d['extra'] = '(' + str(size) + ')'87        if type_color is not None:88            d['type_color'] = type_color89        s = type_string(name, colorize=colorize, **d)90        # Mark that it's abbreviated91        s += ' ' + paint('[...]', 'darkgray', colorize=colorize)92        return s93    else:94        # If not abbreviated, then display the type in dark gray, since95        # the information is already conveyed through the children96        return type_string(name, colorize=colorize, type_color='darkgray')97def abbreviate(s, maxlength=25):98    """Color-aware abbreviator"""99    assert maxlength >= 4100    skip = False101    abbrv = None102    i = 0103    for j, c in enumerate(s):104        if c == '\033':105            skip = True106        elif skip:107            if c == 'm':108                skip = False109        else:110            i += 1111        if i == maxlength - 1:112            abbrv = s[:j] + '\033[0m...'113        elif i > maxlength:114            break115    if i <= maxlength:116        return s117    else:118        return abbrv119def print_row(key, value, level=0, parent='/', colorize=True,120              file=sys.stdout, unpack=False, settings={},121              parent_color='darkgray',122              key_color='white'):123    s = '{}{}'.format(paint(parent, parent_color, colorize=colorize),124                      paint(key, key_color, colorize=colorize))125    s_raw = '{}{}'.format(parent, key)126    if 'filter' in settings:127        if not re.search(settings['filter'], s_raw):128            settings['filtered_count'] += 1129            return130    if unpack:131        extra_str = '*'132        s_raw += extra_str133        s += paint(extra_str, 'purple', colorize=colorize)134    print('{}{} {}'.format(abbreviate(s, settings['left-column-width']),135                           ' '*max(0, (settings['left-column-width'] + 1 - len(s_raw))),136                           value))137class Node(object):138    def __repr__(self):139        return 'Node'140    def print(self, level=0, parent='/', colorize=True, max_level=None,141              file=sys.stdout, settings={}):142        pass143    def info(self, colorize=True, final_level=False):144        return paint('Node', 'red', colorize=colorize)145class FileNotFoundNode(Node):146    def __init__(self, filename):147        self.filename = filename148    def __repr__(self):149        return 'FileNotFoundNode'150    def print(self, level=0, parent='/', colorize=True, max_level=None,151              file=sys.stdout, settings={}):152        print(paint('File not found', 'red', colorize=colorize),153              file=file)154    def info(self, colorize=True, final_level=False):155        return paint('FileNotFoundNode', 'red', colorize=colorize)156class InvalidFileNode(Node):157    def __init__(self, filename):158        self.filename = filename159    def __repr__(self):160        return 'InvalidFileNode'161    def print(self, level=0, parent='/', colorize=True, max_level=None,162              file=sys.stdout, settings={}):163        print(paint('Invalid HDF5 file', 'red', colorize=colorize),164              file=file)165    def info(self, colorize=True, final_level=False):166        return paint('InvalidFileNode', 'red', colorize=colorize)167class DictNode(Node):168    def __init__(self):169        self.children = {}170        self.header = {}171    def add(self, k, v):172        self.children[k] = v173    def print(self, level=0, parent='/', colorize=True, max_level=None,174              file=sys.stdout, settings={}):175        if level < max_level:176            ch = sorted_maybe_numeric(self.children)177            N = len(ch)178            if N > ABRIDGE_OVER_N_CHILDREN and not settings.get('all'):179                ch = ch[:ABRIDGE_SHOW_EACH_SIDE] + [None] + ch[-ABRIDGE_SHOW_EACH_SIDE:]180            for k in ch:#sorted(self.children):181                if k is None:182                    #print(paint('... ({} omitted)'.format(N-20), 'darkgray', colorize=colorize))183                    omitted = N-2 * ABRIDGE_SHOW_EACH_SIDE184                    info = paint('{} omitted ({} in total)'.format(omitted, N),185                                 'darkgray', colorize=colorize)186                    print_row('...', info,187                              level=level,188                              parent=parent,189                              unpack=self.header.get('dd_io_unpack'),190                              colorize=colorize, file=file,191                              key_color='darkgray',192                              settings=settings)193                    continue194                v = self.children[k]195                final = level+1 == max_level196                if (not settings.get('leaves-only') or197                        not isinstance(v, DictNode)):198                    print_row(k,199                              v.info(colorize=colorize, final_level=final),200                              level=level,201                              parent=parent,202                              unpack=self.header.get('dd_io_unpack'),203                              colorize=colorize, file=file,204                              settings=settings)205                v.print(level=level+1, parent='{}{}/'.format(parent, k),206                        colorize=colorize, max_level=max_level, file=file,207                        settings=settings)208    def info(self, colorize=True, final_level=False):209        return container_info('dict', size=len(self.children),210                              colorize=colorize,211                              type_color='purple',212                              final_level=final_level)213    def __repr__(self):214        s = ['{}={}'.format(k, repr(v)) for k, v in self.children.items()]215        return 'DictNode({})'.format(', '.join(s))216class SimpleNamespaceNode(DictNode):217    def info(self, colorize=True, final_level=False):218        return container_info('SimpleNamespace', size=len(self.children),219                              colorize=colorize,220                              type_color='purple',221                              final_level=final_level)222    def print(self, level=0, parent='/', colorize=True, max_level=None,223              file=sys.stdout):224        if level == 0 and not self.header.get('dd_io_unpack'):225            print_row('', self.info(colorize=colorize,226                                    final_level=(0 == max_level)),227                      level=level, parent=parent, unpack=False,228                      colorize=colorize, file=file)229        DictNode.print(self, level, parent, colorize, max_level, file)230    def __repr__(self):231        s = ['{}={}'.format(k, repr(v)) for k, v in self.children.items()]232        return 'SimpleNamespaceNode({})'.format(', '.join(s))233class PandasDataFrameNode(Node):234    def __init__(self, shape):235        self.shape = shape236    def info(self, colorize=True, final_level=False):237        d = {}238        if self.shape is not None:239            d['extra'] = repr(self.shape)240        return type_string('DataFrame',241                           type_color='red',242                           colorize=colorize, **d)243    def __repr__(self):244        return 'PandasDataFrameNode({})'.format(self.shape)245class PandasPanelNode(Node):246    def __init__(self, shape):247        self.shape = shape248    def info(self, colorize=True, final_level=False):249        d = {}250        if self.shape is not None:251            d['extra'] = repr(self.shape)252        return type_string('Panel',253                           type_color='red',254                           colorize=colorize, **d)255    def __repr__(self):256        return 'PandasPanelNode({})'.format(self.shape)257class PandasSeriesNode(Node):258    def __init__(self, size, dtype):259        self.size = size260        self.dtype = dtype261    def info(self, colorize=True, final_level=False):262        d = {}263        if self.size is not None:264            d['extra'] = repr((self.size,))265        if self.dtype is not None:266            d['dtype'] = str(self.dtype)267        return type_string('Series',268                           type_color='red',269                           colorize=colorize, **d)270    def __repr__(self):271        return 'SeriesNode()'272class ListNode(Node):273    def __init__(self, typename='list'):274        self.children = []275        self.typename = typename276    def append(self, v):277        self.children.append(v)278    def __repr__(self):279        s = [repr(v) for v in self.children]280        return 'ListNode({})'.format(', '.join(s))281    def print(self, level=0, parent='/', colorize=True,282              max_level=None, file=sys.stdout, settings={}):283        if level < max_level:284            for i, v in enumerate(self.children):285                k = str(i)286                final = level + 1 == max_level287                print_row(k, v.info(colorize=colorize,288                                    final_level=final),289                          level=level, parent=parent + 'i',290                          colorize=colorize, file=file,291                          settings=settings)292                v.print(level=level+1, parent='{}{}/'.format(parent + 'i', k),293                        colorize=colorize, max_level=max_level, file=file,294                        settings=settings)295    def info(self, colorize=True, final_level=False):296        return container_info(self.typename, size=len(self.children),297                              colorize=colorize,298                              type_color='purple',299                              final_level=final_level)300class NumpyArrayNode(Node):301    def __init__(self, shape, dtype, statistics=None, compression=None):302        self.shape = shape303        self.dtype = dtype304        self.statistics = statistics305        self.compression = compression306    def info(self, colorize=True, final_level=False):307        if not self.statistics:308            s = type_string('array', extra=repr(self.shape),309                            dtype=str(self.dtype),310                            type_color='red',311                            colorize=colorize)312            if self.compression:313                if self.compression['complib'] is not None:314                    compstr = '{} lvl{}'.format(self.compression['complib'],315                                                self.compression['complevel'])316                else:317                    compstr = 'none'318                s += ' ' + paint(compstr, 'yellow', colorize=colorize)319        else:320            s = type_string('array', extra=repr(self.shape),321                            type_color='red',322                            colorize=colorize)323            raw_s = type_string('array', extra=repr(self.shape),324                                type_color='red',325                                colorize=False)326            if len(raw_s) < 25:327                s += ' ' * (25 - len(raw_s))328            s += paint(' {:14.2g}'.format(self.statistics.get('mean')),329                       'white', colorize=colorize)330            s += paint(u' \u00b1 ', 'darkgray', colorize=colorize)331            s += paint('{:.2g}'.format(self.statistics.get('std')),332                       'reset', colorize=colorize)333        return s334    def __repr__(self):335        return ('NumpyArrayNode(shape={}, dtype={})'336                .format(self.shape, self.dtype))337class SparseMatrixNode(Node):338    def __init__(self, fmt, shape, dtype):339        self.sparse_format = fmt340        self.shape = shape341        self.dtype = dtype342    def info(self, colorize=True, final_level=False):343        return type_string('sparse {}'.format(self.sparse_format),344                           extra=repr(self.shape),345                           dtype=str(self.dtype),346                           type_color='red',347                           colorize=colorize)348    def __repr__(self):349        return ('NumpyArrayNode(shape={}, dtype={})'350                .format(self.shape, self.dtype))351class ValueNode(Node):352    def __init__(self, value):353        self.value = value354    def __repr__(self):355        return 'ValueNode(type={})'.format(type(self.value))356    def info(self, colorize=True, final_level=False):357        if isinstance(self.value, six.text_type):358            if len(self.value) > 25:359                s = repr(self.value[:22] + '...')360            else:361                s = repr(self.value)362            return type_string(s, dtype='unicode',363                               type_color='green',364                               extra='({})'.format(len(self.value)),365                               colorize=colorize)366        elif isinstance(self.value, six.binary_type):367            if len(self.value) > 25:368                s = repr(self.value[:22] + b'...')369            else:370                s = repr(self.value)371            return type_string(s, dtype='ascii',372                               type_color='green',373                               extra='({})'.format(len(self.value)),374                               colorize=colorize)375        elif self.value is None:376            return type_string('None', dtype='python',377                               type_color='blue',378                               colorize=colorize)379        else:380            return type_string(repr(self.value)[:20],381                               dtype=str(np.dtype(type(self.value))),382                               type_color='blue',383                               colorize=colorize)384class ObjectNode(Node):385    def __init__(self):386        pass387    def __repr__(self):388        return 'ObjectNode'389    def info(self, colorize=True, final_level=False):390        return type_string('pickled', dtype='object', type_color='yellow',391                           colorize=colorize)392class SoftLinkNode(Node):393    def __init__(self, target):394        self.target = target395    def info(self, colorize=True, final_level=False):396        return type_string('link -> {}'.format(self.target),397                           dtype='SoftLink',398                           type_color='cyan',399                           colorize=colorize)400    def __repr__(self):401        return ('SoftLinkNode(target={})'402                .format(self.target))403def _tree_level(level, raw=False, settings={}):404    if isinstance(level, tables.Group):405        if _sns and (level._v_title.startswith('SimpleNamespace:') or406                     DEEPDISH_IO_ROOT_IS_SNS in level._v_attrs):407            node = SimpleNamespaceNode()408        else:409            node = DictNode()410        for grp in level:411            node.add(grp._v_name, _tree_level(grp, raw=raw, settings=settings))412        for name in level._v_attrs._f_list():413            v = level._v_attrs[name]414            if name == DEEPDISH_IO_VERSION_STR:415                node.header['dd_io_version'] = v416            if name == DEEPDISH_IO_UNPACK:417                node.header['dd_io_unpack'] = v418            if name.startswith(DEEPDISH_IO_PREFIX):419                continue420            if isinstance(v, np.ndarray):421                node.add(name, NumpyArrayNode(v.shape, _format_dtype(v.dtype)))422            else:423                node.add(name, ValueNode(v))424        if (level._v_title.startswith('list:') or425                level._v_title.startswith('tuple:')):426            s = level._v_title.split(':', 1)[1]427            N = int(s)428            lst = ListNode(typename=level._v_title.split(':')[0])429            for i in range(N):430                t = node.children['i{}'.format(i)]431                lst.append(t)432            return lst433        elif level._v_title.startswith('nonetype:'):434            return ValueNode(None)435        elif is_pandas_dataframe(level):436            pandas_type = level._v_attrs['pandas_type']437            if raw:438                # Treat as regular dictionary439                pass440            elif pandas_type == 'frame':441                shape = _pandas_shape(level)442                new_node = PandasDataFrameNode(shape)443                return new_node444            elif pandas_type == 'series':445                try:446                    values = level._v_children['values']447                    size = len(values)448                    dtype = values.dtype449                except:450                    size = None451                    dtype = None452                new_node = PandasSeriesNode(size, dtype)453                return new_node454            elif pandas_type == 'wide':455                shape = _pandas_shape(level)456                new_node = PandasPanelNode(shape)457                return new_node458            # else: it will simply be treated as a dict459        elif level._v_title.startswith('sparse:') and not raw:460            frm = level._v_attrs.format461            dtype = level.data.dtype462            shape = tuple(level.shape[:])463            node = SparseMatrixNode(frm, shape, dtype)464            return node465        return node466    elif isinstance(level, tables.VLArray):467        if level.shape == (1,):468            return ObjectNode()469        node = NumpyArrayNode(level.shape, 'unknown')470        return node471    elif isinstance(level, tables.Array):472        stats = {}473        if settings.get('summarize'):474            stats['mean'] = level[:].mean()475            stats['std'] = level[:].std()476        compression = {}477        if settings.get('compression'):478            compression['complib'] = level.filters.complib479            compression['shuffle'] = level.filters.shuffle480            compression['complevel'] = level.filters.complevel481        node = NumpyArrayNode(level.shape, _format_dtype(level.dtype),482                              statistics=stats, compression=compression)483        if hasattr(level._v_attrs, 'zeroarray_dtype'):484            dtype = level._v_attrs.zeroarray_dtype485            node = NumpyArrayNode(tuple(level), _format_dtype(dtype))486        elif hasattr(level._v_attrs, 'strtype'):487            strtype = level._v_attrs.strtype488            itemsize = level._v_attrs.itemsize489            if strtype == b'unicode':490                shape = level.shape[:-1] + (level.shape[-1] // itemsize // 4,)491            elif strtype == b'ascii':492                shape = level.shape493            node = NumpyArrayNode(shape, strtype.decode('ascii'))494        return node495    elif isinstance(level, tables.link.SoftLink):496        node = SoftLinkNode(level.target)497        return node498    else:499        return Node()500def get_tree(path, raw=False, settings={}):501    fn = os.path.basename(path)502    try:503        with tables.open_file(path, mode='r') as h5file:504            grp = h5file.root505            s = _tree_level(grp, raw=raw, settings=settings)506            s.header['filename'] = fn507            return s508    except OSError:509        return FileNotFoundNode(fn)510    except IOError:511        return FileNotFoundNode(fn)512    except tables.exceptions.HDF5ExtError:513        return InvalidFileNode(fn)514def _column_width(level):515    if isinstance(level, tables.Group):516        max_w = 0517        for grp in level:518            max_w = max(max_w, _column_width(grp))519        for name in level._v_attrs._f_list():520            if name.startswith(DEEPDISH_IO_PREFIX):521                continue522            max_w = max(max_w, len(level._v_pathname) + 1 + len(name))523        return max_w524    else:525        return len(level._v_pathname)526def _discover_column_width(path):527    if not os.path.isfile(path):528        return MIN_AUTOMATIC_COLUMN_WIDTH529    with tables.open_file(path, mode='r') as h5file:530        return _column_width(h5file.root)531def main():532    import argparse533    parser = argparse.ArgumentParser(534        description=("Look inside HDF5 files. Works particularly well "535                     "for HDF5 files saved with deepdish.io.save()."),536        prog='ddls',537        epilog='example: ddls test.h5 -i /foo/bar --ipython')538    parser.add_argument('file', nargs='+',539                        help='filename of HDF5 file')540    parser.add_argument('-d', '--depth', type=int, default=4,541                        help='max depth, defaults to 4')542    parser.add_argument('-nc', '--no-color', action='store_true',543                        help='turn off bash colors')544    parser.add_argument('-i', '--inspect', metavar='GRP',545                        help='print a specific variable (e.g. /data)')546    parser.add_argument('--ipython', action='store_true',547                        help=('load file into an IPython session. '548                              'Works with -i'))549    parser.add_argument('--raw', action='store_true',550                        help=('print the raw HDF5 structure for complex '551                              'data types, such as sparse matrices and pandas '552                              'data frames'))553    parser.add_argument('-f', '--filter', type=str,554                        help=('print only entries that match this regular '555                              'expression'))556    parser.add_argument('-l', '--leaves-only', action='store_true',557                        help=('print only leaves'))558    parser.add_argument('-a', '--all', action='store_true',559                        help=('do not abridge'))560    parser.add_argument('-s', '--summarize', action='store_true',561                        help=('print summary statistics of numpy arrays'))562    parser.add_argument('-c', '--compression', action='store_true',563                        help=('print compression method for each array'))564    parser.add_argument('-v', '--version', action='version',565                        version='deepdish {} (io protocol {})'.format(566                            __version__, IO_VERSION))567    parser.add_argument('--column-width', type=int, default=None)568    args = parser.parse_args()569    colorize = sys.stdout.isatty() and not args.no_color570    settings = {}571    if args.filter:572        settings['filter'] = args.filter573    if args.leaves_only:574        settings['leaves-only'] = True575    if args.summarize:576        settings['summarize'] = True577    if args.compression:578        settings['compression'] = True579    if args.all:580        settings['all'] = True581    def single_file(files):582        if len(files) >= 2:583            s = 'Error: Select a single file when using --inspect'584            print(paint(s, 'red', colorize=colorize))585            sys.exit(1)586        return files[0]587    def run_ipython(fn, group=None, data=None):588        file_desc = paint(fn, 'yellow', colorize=colorize)589        if group is None:590            path_desc = file_desc591        else:592            path_desc = '{}:{}'.format(593                file_desc,594                paint(group, 'white', colorize=colorize))595        welcome = "Loaded {} into '{}':".format(596            path_desc,597            paint('data', 'blue', colorize=colorize))598        # Import deepdish for the session599        import deepdish as dd600        import IPython601        IPython.embed(header=welcome)602    i = 0603    if args.inspect is not None:604        fn = single_file(args.file)605        try:606            data = io.load(fn, args.inspect)607        except ValueError:608            s = 'Error: Could not find group: {}'.format(args.inspect)609            print(paint(s, 'red', colorize=colorize))610            sys.exit(1)611        if args.ipython:612            run_ipython(fn, group=args.inspect, data=data)613        else:614            print(data)615    elif args.ipython:616        fn = single_file(args.file)617        data = io.load(fn)618        run_ipython(fn, data=data)619    else:620        for f in args.file:621            # State that will be incremented622            settings['filtered_count'] = 0623            if args.column_width is None:624                settings['left-column-width'] = max(MIN_AUTOMATIC_COLUMN_WIDTH, min(MAX_AUTOMATIC_COLUMN_WIDTH, _discover_column_width(f)))625            else:626                settings['left-column-width'] = args.column_width627            s = get_tree(f, raw=args.raw, settings=settings)628            if s is not None:629                if i > 0:630                    print()631                if len(args.file) >= 2:632                    print(paint(f, 'yellow', colorize=colorize))633                s.print(colorize=colorize, max_level=args.depth,634                        settings=settings)635                i += 1636            if settings.get('filter'):637                print('Filtered on: {} ({} rows omitted)'.format(638                    paint(args.filter, 'purple', colorize=colorize),639                    paint(str(settings['filtered_count']), 'white',640                          colorize=colorize)))641if __name__ == '__main__':...colorize_nicks.py
Source:colorize_nicks.py  
1# -*- coding: utf-8 -*-2#3# Copyright (c) 2010 by xt <xt@bash.no>4#5# This program is free software; you can redistribute it and/or modify6# it under the terms of the GNU General Public License as published by7# the Free Software Foundation; either version 3 of the License, or8# (at your option) any later version.9#10# This program is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with this program.  If not, see <http://www.gnu.org/licenses/>.17#18# This script colors nicks in IRC channels in the actual message19# not just in the prefix section.20#21#22# History:23# 2014-09-17, holomorph24#   version 16: use weechat config facilities25#               clean unused, minor linting, some simplification26# 2014-05-05, holomorph27#   version 15: fix python2-specific re.search check28# 2013-01-29, nils_229#   version 14: make script compatible with Python 3.x30# 2012-10-19, ldvx31#   version 13: Iterate over every word to prevent incorrect colorization of32#               nicks. Added option greedy_matching.33# 2012-04-28, ldvx34#   version 12: added ignore_tags to avoid colorizing nicks if tags are present35# 2012-01-14, nesthib36#   version 11: input_text_display hook and modifier to colorize nicks in input bar37# 2010-12-22, xt38#   version 10: hook config option for updating blacklist39# 2010-12-20, xt40#   version 0.9: hook new config option for weechat 0.3.441# 2010-11-01, nils_242#   version 0.8: hook_modifier() added to communicate with rainbow_text43# 2010-10-01, xt44#   version 0.7: changes to support non-irc-plugins45# 2010-07-29, xt46#   version 0.6: compile regexp as per patch from Chris quigybo@hotmail.com47# 2010-07-19, xt48#   version 0.5: fix bug with incorrect coloring of own nick49# 2010-06-02, xt50#   version 0.4: update to reflect API changes51# 2010-03-26, xt52#   version 0.3: fix error with exception53# 2010-03-24, xt54#   version 0.2: use ignore_channels when populating to increase performance.55# 2010-02-03, xt56#   version 0.1: initial (based on ruby script by dominikh)57#58# Known issues: nicks will not get colorized if they begin with a character59# such as ~ (which some irc networks do happen to accept)60import weechat61import re62w = weechat63SCRIPT_NAME    = "colorize_nicks"64SCRIPT_AUTHOR  = "xt <xt@bash.no>"65SCRIPT_VERSION = "16"66SCRIPT_LICENSE = "GPL"67SCRIPT_DESC    = "Use the weechat nick colors in the chat area"68VALID_NICK = r'([@~&!%+])?([-a-zA-Z0-9\[\]\\`_^\{|\}]+)'69valid_nick_re = re.compile(VALID_NICK)70ignore_channels = []71ignore_nicks = []72# Dict with every nick on every channel with its color as lookup value73colored_nicks = {}74CONFIG_FILE_NAME = "colorize_nicks"75# config file and options76colorize_config_file = ""77colorize_config_option = {}78def colorize_config_init():79    '''80    Initialization of configuration file.81    Sections: look.82    '''83    global colorize_config_file, colorize_config_option84    colorize_config_file = weechat.config_new(CONFIG_FILE_NAME,85                                              "colorize_config_reload_cb", "")86    if colorize_config_file == "":87        return88    # section "look"89    section_look = weechat.config_new_section(90        colorize_config_file, "look", 0, 0, "", "", "", "", "", "", "", "", "", "")91    if section_look == "":92        weechat.config_free(colorize_config_file)93        return94    colorize_config_option["blacklist_channels"] = weechat.config_new_option(95        colorize_config_file, section_look, "blacklist_channels",96        "string", "Comma separated list of channels", "", 0, 0,97        "", "", 0, "", "", "", "", "", "")98    colorize_config_option["blacklist_nicks"] = weechat.config_new_option(99        colorize_config_file, section_look, "blacklist_nicks",100        "string", "Comma separated list of nicks", "", 0, 0,101        "so,root", "so,root", 0, "", "", "", "", "", "")102    colorize_config_option["min_nick_length"] = weechat.config_new_option(103        colorize_config_file, section_look, "min_nick_length",104        "integer", "Minimum length nick to colorize", "",105        2, 20, "", "", 0, "", "", "", "", "", "")106    colorize_config_option["colorize_input"] = weechat.config_new_option(107        colorize_config_file, section_look, "colorize_input",108        "boolean", "Whether to colorize input", "", 0,109        0, "off", "off", 0, "", "", "", "", "", "")110    colorize_config_option["ignore_tags"] = weechat.config_new_option(111        colorize_config_file, section_look, "ignore_tags",112        "string", "Comma separated list of tags to ignore; i.e. irc_join,irc_part,irc_quit", "", 0, 0,113        "", "", 0, "", "", "", "", "", "")114    colorize_config_option["greedy_matching"] = weechat.config_new_option(115        colorize_config_file, section_look, "greedy_matching",116        "boolean", "If off, then use lazy matching instead", "", 0,117        0, "on", "on", 0, "", "", "", "", "", "")118def colorize_config_read():119    ''' Read configuration file. '''120    global colorize_config_file121    return weechat.config_read(colorize_config_file)122def colorize_nick_color(nick, my_nick):123    ''' Retrieve nick color from weechat. '''124    if nick == my_nick:125        return w.color(w.config_string(w.config_get('weechat.color.chat_nick_self')))126    else:127        return w.info_get('irc_nick_color', nick)128def colorize_cb(data, modifier, modifier_data, line):129    ''' Callback that does the colorizing, and returns new line if changed '''130    global ignore_nicks, ignore_channels, colored_nicks131    full_name = modifier_data.split(';')[1]132    channel = '.'.join(full_name.split('.')[1:])133    buffer = w.buffer_search('', full_name)134    # Check if buffer has colorized nicks135    if buffer not in colored_nicks:136        return line137    if channel in ignore_channels:138        return line139    min_length = w.config_integer(colorize_config_option['min_nick_length'])140    reset = w.color('reset')141    # Don't colorize if the ignored tag is present in message142    tags_line = modifier_data.rsplit(';')143    if len(tags_line) >= 3:144        tags_line = tags_line[2].split(',')145        for i in w.config_string(colorize_config_option['ignore_tags']).split(','):146            if i in tags_line:147                return line148    for words in valid_nick_re.findall(line):149        nick = words[1]150        # Check that nick is not ignored and longer than minimum length151        if len(nick) < min_length or nick in ignore_nicks:152            continue153        # Check that nick is in the dictionary colored_nicks154        if nick in colored_nicks[buffer]:155            nick_color = colored_nicks[buffer][nick]156            # Let's use greedy matching. Will check against every word in a line.157            if w.config_boolean(colorize_config_option['greedy_matching']):158                for word in line.split():159                    if nick in word:160                        # Is there a nick that contains nick and has a greater lenght?161                        # If so let's save that nick into var biggest_nick162                        biggest_nick = ""163                        for i in colored_nicks[buffer]:164                            if nick in i and nick != i and len(i) > len(nick):165                                if i in word:166                                    # If a nick with greater len is found, and that word167                                    # also happens to be in word, then let's save this nick168                                    biggest_nick = i169                        # If there's a nick with greater len, then let's skip this170                        # As we will have the chance to colorize when biggest_nick171                        # iterates being nick.172                        if len(biggest_nick) > 0 and biggest_nick in word:173                            pass174                        elif len(word) < len(biggest_nick) or len(biggest_nick) == 0:175                            new_word = word.replace(nick, '%s%s%s' % (nick_color, nick, reset))176                            line = line.replace(word, new_word)177            # Let's use lazy matching for nick178            else:179                nick_color = colored_nicks[buffer][nick]180                # The two .? are in case somebody writes "nick:", "nick,", etc181                # to address somebody182                regex = r"(\A|\s).?(%s).?(\Z|\s)" % re.escape(nick)183                match = re.search(regex, line)184                if match is not None:185                    new_line = line[:match.start(2)] + nick_color+nick+reset + line[match.end(2):]186                    line = new_line187    return line188def colorize_input_cb(data, modifier, modifier_data, line):189    ''' Callback that does the colorizing in input '''190    global ignore_nicks, ignore_channels, colored_nicks191    min_length = w.config_integer(colorize_config_option['min_nick_length'])192    if not w.config_boolean(colorize_config_option['colorize_input']):193        return line194    buffer = w.current_buffer()195    # Check if buffer has colorized nicks196    if buffer not in colored_nicks:197        return line198    channel = w.buffer_get_string(buffer, 'name')199    if channel in ignore_channels:200        return line201    reset = w.color('reset')202    for words in valid_nick_re.findall(line):203        nick = words[1]204        # Check that nick is not ignored and longer than minimum length205        if len(nick) < min_length or nick in ignore_nicks:206            continue207        if nick in colored_nicks[buffer]:208            nick_color = colored_nicks[buffer][nick]209            line = line.replace(nick, '%s%s%s' % (nick_color, nick, reset))210    return line211def populate_nicks(*args):212    ''' Fills entire dict with all nicks weechat can see and what color it has213    assigned to it. '''214    global colored_nicks215    colored_nicks = {}216    servers = w.infolist_get('irc_server', '', '')217    while w.infolist_next(servers):218        servername = w.infolist_string(servers, 'name')219        colored_nicks[servername] = {}220        my_nick = w.info_get('irc_nick', servername)221        channels = w.infolist_get('irc_channel', '', servername)222        while w.infolist_next(channels):223            pointer = w.infolist_pointer(channels, 'buffer')224            nicklist = w.infolist_get('nicklist', pointer, '')225            if pointer not in colored_nicks:226                colored_nicks[pointer] = {}227            while w.infolist_next(nicklist):228                nick = w.infolist_string(nicklist, 'name')229                nick_color = colorize_nick_color(nick, my_nick)230                colored_nicks[pointer][nick] = nick_color231            w.infolist_free(nicklist)232        w.infolist_free(channels)233    w.infolist_free(servers)234    return w.WEECHAT_RC_OK235def add_nick(data, signal, type_data):236    ''' Add nick to dict of colored nicks '''237    global colored_nicks238    pointer, nick = type_data.split(',')239    if pointer not in colored_nicks:240        colored_nicks[pointer] = {}241    my_nick = w.buffer_get_string(pointer, 'localvar_nick')242    nick_color = colorize_nick_color(nick, my_nick)243    colored_nicks[pointer][nick] = nick_color244    return w.WEECHAT_RC_OK245def remove_nick(data, signal, type_data):246    ''' Remove nick from dict with colored nicks '''247    global colored_nicks248    pointer, nick = type_data.split(',')249    if pointer in colored_nicks and nick in colored_nicks[pointer]:250        del colored_nicks[pointer][nick]251    return w.WEECHAT_RC_OK252def update_blacklist(*args):253    ''' Set the blacklist for channels and nicks. '''254    global ignore_channels, ignore_nicks255    ignore_channels = w.config_string(colorize_config_option['blacklist_channels']).split(',')256    ignore_nicks = w.config_string(colorize_config_option['blacklist_nicks']).split(',')257    return w.WEECHAT_RC_OK258if __name__ == "__main__":259    if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,260                  SCRIPT_DESC, "", ""):261        colorize_config_init()262        colorize_config_read()263        # Run once to get data ready264        update_blacklist()265        populate_nicks()266        w.hook_signal('nicklist_nick_added', 'add_nick', '')267        w.hook_signal('nicklist_nick_removed', 'remove_nick', '')268        w.hook_modifier('weechat_print', 'colorize_cb', '')269        # Hook config for changing colors270        w.hook_config('weechat.color.chat_nick_colors', 'populate_nicks', '')271        # Hook for working togheter with other scripts (like colorize_lines)272        w.hook_modifier('colorize_nicks', 'colorize_cb', '')273        # Hook for modifying input274        w.hook_modifier('250|input_text_display', 'colorize_input_cb', '')275        # Hook for updating blacklist (this could be improved to use fnmatch)...color.py
Source:color.py  
...6    Example without parsing logic: Color('{red}Sample Text{/red}', keep_tags=True)7    For a list of codes, call: colorclass.list_tags()8    """9    @classmethod10    def colorize(cls, color, string, auto=False):11        """Color-code entire string using specified color.12        :param str color: Color of string.13        :param str string: String to colorize.14        :param bool auto: Enable auto-color (dark/light terminal).15        :return: Class instance for colorized string.16        :rtype: Color17        """18        tag = '{0}{1}'.format('auto' if auto else '', color)19        return cls('{%s}%s{/%s}' % (tag, string, tag))20    @classmethod21    def black(cls, string, auto=False):22        """Color-code entire string.23        :param str string: String to colorize.24        :param bool auto: Enable auto-color (dark/light terminal).25        :return: Class instance for colorized string.26        :rtype: Color27        """28        return cls.colorize('black', string, auto=auto)29    @classmethod30    def bgblack(cls, string, auto=False):31        """Color-code entire string.32        :param str string: String to colorize.33        :param bool auto: Enable auto-color (dark/light terminal).34        :return: Class instance for colorized string.35        :rtype: Color36        """37        return cls.colorize('bgblack', string, auto=auto)38    @classmethod39    def red(cls, string, auto=False):40        """Color-code entire string.41        :param str string: String to colorize.42        :param bool auto: Enable auto-color (dark/light terminal).43        :return: Class instance for colorized string.44        :rtype: Color45        """46        return cls.colorize('red', string, auto=auto)47    @classmethod48    def bgred(cls, string, auto=False):49        """Color-code entire string.50        :param str string: String to colorize.51        :param bool auto: Enable auto-color (dark/light terminal).52        :return: Class instance for colorized string.53        :rtype: Color54        """55        return cls.colorize('bgred', string, auto=auto)56    @classmethod57    def green(cls, string, auto=False):58        """Color-code entire string.59        :param str string: String to colorize.60        :param bool auto: Enable auto-color (dark/light terminal).61        :return: Class instance for colorized string.62        :rtype: Color63        """64        return cls.colorize('green', string, auto=auto)65    @classmethod66    def bggreen(cls, string, auto=False):67        """Color-code entire string.68        :param str string: String to colorize.69        :param bool auto: Enable auto-color (dark/light terminal).70        :return: Class instance for colorized string.71        :rtype: Color72        """73        return cls.colorize('bggreen', string, auto=auto)74    @classmethod75    def yellow(cls, string, auto=False):76        """Color-code entire string.77        :param str string: String to colorize.78        :param bool auto: Enable auto-color (dark/light terminal).79        :return: Class instance for colorized string.80        :rtype: Color81        """82        return cls.colorize('yellow', string, auto=auto)83    @classmethod84    def bgyellow(cls, string, auto=False):85        """Color-code entire string.86        :param str string: String to colorize.87        :param bool auto: Enable auto-color (dark/light terminal).88        :return: Class instance for colorized string.89        :rtype: Color90        """91        return cls.colorize('bgyellow', string, auto=auto)92    @classmethod93    def blue(cls, string, auto=False):94        """Color-code entire string.95        :param str string: String to colorize.96        :param bool auto: Enable auto-color (dark/light terminal).97        :return: Class instance for colorized string.98        :rtype: Color99        """100        return cls.colorize('blue', string, auto=auto)101    @classmethod102    def bgblue(cls, string, auto=False):103        """Color-code entire string.104        :param str string: String to colorize.105        :param bool auto: Enable auto-color (dark/light terminal).106        :return: Class instance for colorized string.107        :rtype: Color108        """109        return cls.colorize('bgblue', string, auto=auto)110    @classmethod111    def magenta(cls, string, auto=False):112        """Color-code entire string.113        :param str string: String to colorize.114        :param bool auto: Enable auto-color (dark/light terminal).115        :return: Class instance for colorized string.116        :rtype: Color117        """118        return cls.colorize('magenta', string, auto=auto)119    @classmethod120    def bgmagenta(cls, string, auto=False):121        """Color-code entire string.122        :param str string: String to colorize.123        :param bool auto: Enable auto-color (dark/light terminal).124        :return: Class instance for colorized string.125        :rtype: Color126        """127        return cls.colorize('bgmagenta', string, auto=auto)128    @classmethod129    def cyan(cls, string, auto=False):130        """Color-code entire string.131        :param str string: String to colorize.132        :param bool auto: Enable auto-color (dark/light terminal).133        :return: Class instance for colorized string.134        :rtype: Color135        """136        return cls.colorize('cyan', string, auto=auto)137    @classmethod138    def bgcyan(cls, string, auto=False):139        """Color-code entire string.140        :param str string: String to colorize.141        :param bool auto: Enable auto-color (dark/light terminal).142        :return: Class instance for colorized string.143        :rtype: Color144        """145        return cls.colorize('bgcyan', string, auto=auto)146    @classmethod147    def white(cls, string, auto=False):148        """Color-code entire string.149        :param str string: String to colorize.150        :param bool auto: Enable auto-color (dark/light terminal).151        :return: Class instance for colorized string.152        :rtype: Color153        """154        return cls.colorize('white', string, auto=auto)155    @classmethod156    def bgwhite(cls, string, auto=False):157        """Color-code entire string.158        :param str string: String to colorize.159        :param bool auto: Enable auto-color (dark/light terminal).160        :return: Class instance for colorized string.161        :rtype: Color162        """...test_utils_colorize.py
Source:test_utils_colorize.py  
1import re2import colorama3import mock4from nutcli.utils import Colorize5@mock.patch(6    'nutcli.utils.Colorize.print_colors',7    new_callable=mock.PropertyMock,8    return_value=True9)10def test_Colorize_all__enabled(_):11    result = Colorize.all('hello', colorama.Style.BRIGHT)12    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}hello{colorama.Style.RESET_ALL}'13    result = Colorize.all('hello', colorama.Style.BRIGHT, colorama.Fore.RED)14    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}{colorama.Fore.RED}hello{colorama.Style.RESET_ALL}'   # noqa: E50115    result = Colorize.all('', colorama.Style.BRIGHT)16    assert result == ''17@mock.patch(18    'nutcli.utils.Colorize.print_colors',19    new_callable=mock.PropertyMock,20    return_value=False21)22def test_Colorize_all__disabled(_):23    result = Colorize.all('hello', colorama.Style.BRIGHT)24    assert result == 'hello'25    result = Colorize.all('hello', colorama.Style.BRIGHT, colorama.Fore.RED)26    assert result == 'hello'27@mock.patch(28    'nutcli.utils.Colorize.print_colors',29    new_callable=mock.PropertyMock,30    return_value=True31)32def test_Colorize_bold__enabled(_):33    result = Colorize.bold('hello')34    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}hello{colorama.Style.RESET_ALL}'35@mock.patch(36    'nutcli.utils.Colorize.print_colors',37    new_callable=mock.PropertyMock,38    return_value=False39)40def test_Colorize_bold__disabled(_):41    result = Colorize.bold('hello')42    assert result == 'hello'43@mock.patch(44    'nutcli.utils.Colorize.print_colors',45    new_callable=mock.PropertyMock,46    return_value=True47)48def test_Colorize_re__enabled(_):49    result = Colorize.re('hello', r'(.+)', colorama.Style.BRIGHT)50    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}hello{colorama.Style.RESET_ALL}'51    result = Colorize.re('hello', r'(.*)', colorama.Style.BRIGHT)52    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}hello{colorama.Style.RESET_ALL}'53    result = Colorize.re('hello', r'(he)(llo)', colorama.Style.BRIGHT, colorama.Fore.RED)54    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}he{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.RED}llo{colorama.Style.RESET_ALL}'  # noqa: E50155    result = Colorize.re('hello', r'(he(llo))', colorama.Style.BRIGHT, colorama.Fore.RED)56    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}he{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.RED}llo{colorama.Style.RESET_ALL}'  # noqa: E50157    result = Colorize.re('hello', r'(h(e)(llo))', colorama.Style.BRIGHT, colorama.Fore.RED, colorama.Fore.BLUE)58    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}h{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.RED}e{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.BLUE}llo{colorama.Style.RESET_ALL}'  # noqa: E50159    result = Colorize.re('hello', r'(h(e)(llo))', colorama.Style.BRIGHT, colorama.Fore.RED)60    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}h{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.RED}e{colorama.Style.RESET_ALL}llo'  # noqa: E50161    result = Colorize.re('hello', r'(h(e)llo)', colorama.Style.BRIGHT, colorama.Fore.RED)62    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}h{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.RED}e{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}llo{colorama.Style.RESET_ALL}'  # noqa: E50163    result = Colorize.re('hello', r'h(e)llo', colorama.Style.BRIGHT)64    assert result == f'h{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}e{colorama.Style.RESET_ALL}llo'65    result = Colorize.re('hello', r'(h(e)(llo))', colorama.Style.BRIGHT,66                         colorama.Fore.RED, [colorama.Fore.BLUE, colorama.Style.BRIGHT])67    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}h{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.RED}e{colorama.Style.RESET_ALL}{colorama.Style.RESET_ALL}{colorama.Fore.BLUE}{colorama.Style.BRIGHT}llo{colorama.Style.RESET_ALL}'  # noqa: E50168@mock.patch(69    'nutcli.utils.Colorize.print_colors',70    new_callable=mock.PropertyMock,71    return_value=True72)73def test_Colorize_re__enabled_compiled(_):74    result = Colorize.re('hello', re.compile(r'(.+)'), colorama.Style.BRIGHT)75    assert result == f'{colorama.Style.RESET_ALL}{colorama.Style.BRIGHT}hello{colorama.Style.RESET_ALL}'76@mock.patch(77    'nutcli.utils.Colorize.print_colors',78    new_callable=mock.PropertyMock,79    return_value=False80)81def test_Colorize_re__disabled(_):82    result = Colorize.re('hello', r'(.+)', colorama.Style.BRIGHT)...display.py
Source:display.py  
1# Note that `DisplayCodec` is deliberately omitted from the documentation,2# as it is considered an implementation detail.3# It may move into a utility function in the future.4from __future__ import unicode_literals5from coreapi.codecs.base import BaseCodec6from coreapi.compat import console_style, string_types7from coreapi.document import Document, Link, Array, Object, Error8import json9def _colorize_document(text):10    return console_style(text, fg='green')  # pragma: nocover11def _colorize_error(text):12    return console_style(text, fg='red')  # pragma: nocover13def _colorize_keys(text):14    return console_style(text, fg='cyan')  # pragma: nocover15def _to_plaintext(node, indent=0, base_url=None, colorize=False, extra_offset=None):16    colorize_document = _colorize_document if colorize else lambda x: x17    colorize_error = _colorize_error if colorize else lambda x: x18    colorize_keys = _colorize_keys if colorize else lambda x: x19    if isinstance(node, Document):20        head_indent = '    ' * indent21        body_indent = '    ' * (indent + 1)22        body = '\n'.join([23            body_indent + colorize_keys(str(key) + ': ') +24            _to_plaintext(value, indent + 1, base_url=base_url, colorize=colorize, extra_offset=len(str(key)))25            for key, value in node.data.items()26        ] + [27            body_indent + colorize_keys(str(key) + '(') +28            _fields_to_plaintext(value, colorize=colorize) + colorize_keys(')')29            for key, value in node.links.items()30        ])31        head = colorize_document('<%s %s>' % (32            node.title.strip() or 'Document',33            json.dumps(node.url)34        ))35        return head if (not body) else head + '\n' + body36    elif isinstance(node, Object):37        head_indent = '    ' * indent38        body_indent = '    ' * (indent + 1)39        body = '\n'.join([40            body_indent + colorize_keys(str(key)) + ': ' +41            _to_plaintext(value, indent + 1, base_url=base_url, colorize=colorize, extra_offset=len(str(key)))42            for key, value in node.data.items()43        ] + [44            body_indent + colorize_keys(str(key) + '(') +45            _fields_to_plaintext(value, colorize=colorize) + colorize_keys(')')46            for key, value in node.links.items()47        ])48        return '{}' if (not body) else '{\n' + body + '\n' + head_indent + '}'49    if isinstance(node, Error):50        head_indent = '    ' * indent51        body_indent = '    ' * (indent + 1)52        body = '\n'.join([53            body_indent + colorize_keys(str(key) + ': ') +54            _to_plaintext(value, indent + 1, base_url=base_url, colorize=colorize, extra_offset=len(str(key)))55            for key, value in node.items()56        ])57        head = colorize_error('<Error: %s>' % node.title.strip() if node.title else '<Error>')58        return head if (not body) else head + '\n' + body59    elif isinstance(node, Array):60        head_indent = '    ' * indent61        body_indent = '    ' * (indent + 1)62        body = ',\n'.join([63            body_indent + _to_plaintext(value, indent + 1, base_url=base_url, colorize=colorize)64            for value in node65        ])66        return '[]' if (not body) else '[\n' + body + '\n' + head_indent + ']'67    elif isinstance(node, Link):68        return (69            colorize_keys('link(') +70            _fields_to_plaintext(node, colorize=colorize) +71            colorize_keys(')')72        )73    if isinstance(node, string_types) and (extra_offset is not None) and ('\n' in node):74        # Display newlines in strings gracefully.75        text = json.dumps(node)76        spacing = ('    ' * indent) + (' ' * extra_offset) + '   '77        return text.replace('\\n', '\n' + spacing)78    return json.dumps(node)79def _fields_to_plaintext(link, colorize=False):80    colorize_keys = _colorize_keys if colorize else lambda x: x81    return colorize_keys(', ').join([82        field.name for field in link.fields if field.required83    ] + [84        '[%s]' % field.name for field in link.fields if not field.required85    ])86class DisplayCodec(BaseCodec):87    """88    A plaintext representation of a Document, intended for readability.89    """90    media_type = 'text/plain'91    def encode(self, document, **options):92        colorize = options.get('colorize', False)...loggers.py
Source:loggers.py  
...16        colors = [Color.GREY, Color.GREEN, Color.YELLOW, Color.RED, Color.RED]17        print "HTTP/{0} {1} {2}".format(18            response.version / 10.0,19            response.status,20            colorize(response.reason, colors[response.status / 100 - 1],21                     Attribute.BRIGHT))22    def print_headers(self, headers, sending=False):23        for header in headers:24            print "{0}{1}: {2}".format(25                colorize("<" if sending else ">", Color.WHITE),26                colorize(header[0], Color.BLUE, Attribute.BRIGHT),27                header[1])28    def print_tackons(self, params):29        for param in params:30            print "{0}{1}{2}".format(31                colorize(param[0], Color.BLUE, Attribute.BRIGHT),32                "=" if len(param[1]) > 0 else "",33                param[1])34    def print_cookies(self, cookie):35        for morsel in cookie.values():36            print colorize("Name:", Color.BLUE), morsel.key37            print colorize("Value:", Color.BLUE), morsel.value38            print colorize("Expires:", Color.BLUE), morsel["expires"]39            print colorize("Domain:", Color.BLUE), morsel["domain"]40            print colorize("Path:", Color.BLUE), morsel["path"]41            print42    def print_data(self, data):43        if data:44            print45            print highlight(data,46                            guess_lexer(data),47                            TerminalFormatter())48    def print_help(self):49        print "Verbs"50        print "  head", colorize("[</path/to/resource>]", Color.GREY)51        print "  get", colorize("[</path/to/resource>] [| <external command>]", Color.GREY)52        print "  post", colorize("[</path/to/resource>] [| <external command>]", Color.GREY)53        print "  put", colorize("[</path/to/resource>] [| <external command>]", Color.GREY)54        print "  delete", colorize("</path/to/resource>", Color.GREY, Attribute.BRIGHT), colorize(" [| <external command>]", Color.GREY)55        print "  options", colorize("[</path/to/resource>] [| <external command>]", Color.GREY)56        print "  trace", colorize("[</path/to/resource>] [| <external command>]", Color.GREY)57        print "Navigation"58        print "  cd", colorize("</path/to/resource> or ..", Color.GREY, Attribute.BRIGHT)59        print "  open",  colorize("<url>", Color.GREY, Attribute.BRIGHT)60        print "Metacommands"61        print "  headers", colorize("[<name>]:[<value>]", Color.GREY)62        print "  tackons", colorize("[<name>]=[<value>]", Color.GREY)63        print "  cookies", colorize("[<name>]=[<value>]", Color.GREY)64        print "  debuglevel", colorize("[#]", Color.GREY)65        print "  quit"66        print67        print "Full documentation available at https://github.com/chrislongo/HttpShell#readme"68    def print_error(self, text):...colorize.py
Source:colorize.py  
1import director.applogic as app2import director.objectmodel as om3from director import cameraview4import functools5actionName = 'ActionColorizeLidar'6def setVisProperties(obj, colorModeEnabled):7    if colorModeEnabled:8        alpha = 1.09        pointSize = 4.010        colorBy = 'rgb'11    else:12        alpha = 0.513        pointSize = 1.014        colorBy = None15    obj.setProperty('Alpha', alpha)16    obj.setProperty('Point Size', pointSize)17def colorizePoints(polyData):18    cameras = ['CAMERACHEST_RIGHT', 'CAMERACHEST_LEFT', 'CAMERA_LEFT']19    for camera in cameras:20        cameraview.colorizePoints(polyData, camera)21def colorizeSegmentationLidar(enabled):22    obj = om.findObjectByName('pointcloud snapshot')23    if not obj:24        return25    if enabled:26        colorizePoints(obj.polyData)27    else:28        obj.polyData.GetPointData().RemoveArray('rgb')29    setVisProperties(obj, enabled)30_colorizeMapNames = ['HEIGHT_MAP_SCENE', 'SCANS_HALF_SWEEP']31def colorizeMapCallback(obj):32    if obj and obj.getProperty('Name') in _colorizeMapNames:33        colorizePoints(obj.polyData)34        obj._updateColorByProperty()35        obj.setProperty('Color By', 'rgb')36def colorizeMaps(enabled):37    if enabled:38        om.findObjectByName('Map Server').source.colorizeCallback = colorizeMapCallback39        for name in _colorizeMapNames:40            colorizeMapCallback(om.findObjectByName(name))41    else:42        om.findObjectByName('Map Server').source.colorizeCallback = None43def colorizeMultisense(enabled):44    obj = om.findObjectByName('Multisense')45    if not obj:46        return47    setVisProperties(obj, enabled)48    colorBy = 'Camera RGB' if enabled else 'Solid Color'49    obj.setProperty('Color By', colorBy)50def colorizeMapsOff():51    obj = om.findObjectByName('Map Server')52    obj.source.colorizeCallback = None53    alpha = 0.754    pointSize = 1.055    obj.setProperty('Alpha', alpha)56    obj.setProperty('Point Size', pointSize)57def onColorizeLidar():58    colorizeEnabled = app.getToolBarActions()[actionName].checked59    colorizeMaps(colorizeEnabled)60    colorizeMultisense(colorizeEnabled)61    colorizeSegmentationLidar(colorizeEnabled)62def initColorizeCallbacks():63    obj = om.findObjectByName('Multisense')64    assert(obj)65    def callback():66        colorizePoints(obj.model.polyDataObj.polyData)67    obj.model.colorizeCallback = callback68def init():69    action = app.getToolBarActions()[actionName]70    action.connect(action, 'triggered()', onColorizeLidar)...Using AI Code Generation
1const chai = require('chai');2const sinonChai = require('sinon-chai');3chai.use(sinonChai);4const chai = require('chai');5const sinonChai = require('sinon-chai');6chai.use(sinonChai);7const chai = require('chai');8const sinonChai = require('sinon-chai');9chai.use(sinonChai);10const chai = require('chai');11const sinonChai = require('sinon-chai');12chai.use(sinonChai);13const chai = require('chai');14const sinonChai = require('sinon-chai');15chai.use(sinonChai);16const chai = require('chai');17const sinonChai = require('sinon-chai');18chai.use(sinonChai);19const chai = require('chai');20const sinonChai = require('sinon-chai');21chai.use(sinonChai);22const chai = require('chai');23const sinonChai = require('sinon-chai');24chai.use(sinonChai);25const chai = require('chai');26const sinonChai = require('sinon-chai');27chai.use(sinonChai);28const chai = require('chai');29const sinonChai = require('sinon-chai');30chai.use(sinonChai);31const chai = require('chai');32const sinonChai = require('sinon-chai');33chai.use(sinonChai);34const chai = require('chai');Using AI Code Generation
1var chai = require('chai');2var sinonChai = require('sinon-chai');3chai.use(sinonChai);4var expect = chai.expect;5var chaiAsPromised = require('chai-as-promised');6chai.use(chaiAsPromised);7var should = chai.should();8var chaiThings = require('chai-things');9chai.use(chaiThings);10var chaiJquery = require('chai-jquery');11chai.use(chaiJquery);12var chaiDatetime = require('chai-datetime');13chai.use(chaiDatetime);14var chaiFuzzy = require('chai-fuzzy');15chai.use(chaiFuzzy);16var chaiSpies = require('chai-spies');17chai.use(chaiSpies);18var chaiArrays = require('chai-arrays');19chai.use(chaiArrays);20var chaiXml = require('chai-xml');21chai.use(chaiXml);22var chaiJsonSchema = require('chai-json-schema');23chai.use(chaiJsonSchema);24var sinon = require('sinon');25var should = chai.should();26var expect = chai.expect;27var test = require('..');28describe('test', function() {29  describe('#test()', function() {30    it('should return 1', function() {31      test.test().should.equal(1);32    });33  });34});35exports.test = function() {36  return 1;37};38{39  "scripts": {40  },41  "devDependencies": {Using AI Code Generation
1const chai = require('chai');2const sinonChai = require('sinon-chai');3chai.use(sinonChai);4const expect = chai.expect;5const chaiAsPromised = require('chai-as-promised');6chai.use(chaiAsPromised);7const chaiThings = require('chai-things');8chai.use(chaiThings);9const chaiFs = require('chai-fs');10chai.use(chaiFs);11const chaiJsonSchema = require('chai-json-schema');12chai.use(chaiJsonSchema);13const chaiJsonSchemaAjv = require('chai-json-schema-ajv');14chai.use(chaiJsonSchemaAjv);15const chaiSubset = require('chai-subset');16chai.use(chaiSubset);Using AI Code Generation
1var expect = require('chai').use(require('sinon-chai')).expect;2var chai = require('chai');3chai.use(require('chai-as-promised'));4var expect = chai.expect;5var chai = require('chai');6chai.use(require('sinon-chai'));7chai.use(require('chai-as-promised'));8var expect = chai.expect;9var expect = require('chai').use(require('sinon-chai')).use(require('chai-as-promised')).expect;10var chai = require('chai');11chai.use(require('chai-as-promised'));12chai.use(require('sinon-chai'));13var expect = chai.expect;14var expect = require('chai').use(require('chai-as-promised')).use(require('sinon-chai')).expect;15var expect = require('chai').use(require('chai-as-promised'), require('sinon-chai')).expect;16var expect = require('chai').use(require('sinon-chai'), require('chai-as-promised')).expect;17var chai = require('chai');18chai.use(require('chai-as-promised'), require('sinon-chai'));19var expect = chai.expect;20var chai = require('chai');21chai.use(require('sinon-chai'), require('chai-as-promised'));22var expect = chai.expect;23var chai = require('chai');24chai.use(require('chai-as-promised')).use(require('sinon-chai'));25var expect = chai.expect;26var chai = require('chai');27chai.use(require('sinon-chai')).use(require('chai-as-promised'));Using AI Code Generation
1var chai = require("chai");2var sinonChai = require("sinon-chai");3chai.use(sinonChai);4var expect = chai.expect;5var sinon = require("sinon");6var chaiAsPromised = require("chai-as-promised");7chai.use(chaiAsPromised);8var myModule = require("myModule");9var myModuleInstance = new myModule();10describe("myModule", function() {11    describe("myMethod", function() {12        it("should call myMethod", function() {13            var spy = sinon.spy(myModuleInstance, "myMethod");14            myModuleInstance.myMethod();15            expect(spy).to.have.been.called;16        });17    });18});19{20}Using AI Code Generation
1var chai = require("chai");2var sinon = require("sinon");3var sinonChai = require("sinon-chai");4chai.use(sinonChai);5var sandbox = sinon.sandbox.create();6var expect = chai.expect;7describe("test", function() {8    it("test", function() {9        var spy = sandbox.spy();10        spy();11        expect(spy).to.have.been.called;12    });13});14  1 passing (10ms)Using AI Code Generation
1var chai = require('chai');2chai.use(require('sinon-chai'));3var sinon = require('sinon');4var expect = chai.expect;5describe('test', function () {6    it('should work', function () {7        var spy = sinon.spy();8        spy();9        expect(spy).to.have.been.called;10    });11});12var chai = require('chai');13chai.use(require('sinon-chai'));14var sinon = require('sinon');15var expect = chai.expect;16describe('test', function () {17    it('should work', function () {18        var spy = sinon.spy();19        spy();20        expect(spy).to.have.been.called;21    });22});23var chai = require('chai');24chai.use(require('sinon-chai'));25var sinon = require('sinon');26var expect = chai.expect;27describe('test', function () {28    it('should work', function () {29        var spy = sinon.spy();30        spy();31        expect(spy).to.have.been.called;32    });33});34var chai = require('chai');35chai.use(require('sinon-chai'));36var sinon = require('sinon');37var expect = chai.expect;38describe('test', function () {39    it('should work', function () {40        var spy = sinon.spy();41        spy();42        expect(spy).to.have.been.called;43    });44});45var chai = require('chai');46chai.use(require('sinon-chai'));47var sinon = require('sinon');48var expect = chai.expect;49describe('test', function () {50    it('should work', function () {51        var spy = sinon.spy();52        spy();53        expect(spy).to.have.been.called;54    });55});56var chai = require('chai');57chai.use(require('sinon-chai'));58var sinon = require('sinon');59var expect = chai.expect;60describe('test', function () {61    it('should work', function () {62        var spy = sinon.spy();63        spy();Using AI Code Generation
1sinonChai.use(require('sinon-chai'));2chai.should();3chai.use(sinonChai);4var expect = chai.expect;5var assert = chai.assert;6var should = chai.should();7describe('test', function() {8  it('should return a function', function() {9    var a = function() {};10    expect(a).to.be.a('function');11  });12});13describe('test', function() {14  it('should return a function', function() {15    var a = function() {};16    expect(a).to.be.a('function');17  });18  it('should return a string', function() {19    var b = 'b';20    expect(b).to.be.a('string');21  });22});23describe('test', function() {24  it('should return a function', function() {25    var a = function() {};26    expect(a).to.be.a('function');27  });28  it('should return a string', function() {29    var b = 'b';30    expect(b).to.be.a('string');31  });32  it('should return an object', function() {33    var c = {a: 'a'};34    expect(c).to.be.an('object');35  });36});37describe('test', function() {38  it('should return a function', function() {39    var a = function() {};40    expect(a).to.be.a('function');41  });42  it('should return a string', function() {43    var b = 'b';44    expect(b).to.be.a('string');45  });46  it('should return an object', function() {47    var c = {a: 'a'};48    expect(c).to.be.an('object');49  });50  it('should return an array', function() {51    var d = [1, 2, 3];52    expect(d).to.be.an('array');53  });54});55describe('test', function() {56  it('should return a function', function() {57    var a = function() {};58    expect(a).to.be.a('function');59  });60  it('should return a string', function() {61    var b = 'b';62    expect(b).to.be.a('string');63  });64  it('should return an object', function() {65    var c = {Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
