def get_datetime(self, timestamp: str, unix=True):

time = datetime.strptime(timestamp, '<STR_LIT>')<EOL>if unix:<EOL><INDENT>return int(time.timestamp())<EOL><DEDENT>else:<EOL><INDENT>return time<EOL><DEDENT>

Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp
        or a datetime.datetime object

        Parameters
        ---------
        timestamp: str
            A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API
            in the ``created_time`` field for example (eg. 20180718T145906.000Z)
        unix: Optional[bool] = True
            Whether to return a POSIX timestamp (seconds since epoch) or not

        Returns int or datetime.datetime


@typecasted<EOL><INDENT>def get_player_chests(self, tag: crtag, timeout: int=None):<DEDENT>

url = self.api.PLAYER + '<STR_LIT:/>' + tag + '<STR_LIT>'<EOL>return self._get_model(url, timeout=timeout)<EOL>

Get information about a player's chest cycle

        Parameters
        ----------
        tag: str
            A valid tournament tag. Minimum length: 3
            Valid characters: 0289PYLQGRJCUV
        timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


@typecasted<EOL><INDENT>def get_tournament(self, tag: crtag, timeout=<NUM_LIT:0>):<DEDENT>

url = self.api.TOURNAMENT + '<STR_LIT:/>' + tag<EOL>return self._get_model(url, PartialTournament, timeout=timeout)<EOL>

Get a tournament information

        Parameters
        ----------
        tag: str
            A valid tournament tag. Minimum length: 3
            Valid characters: 0289PYLQGRJCUV
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


@typecasted<EOL><INDENT>def get_player_battles(self, tag: crtag, **params: keys):<DEDENT>

url = self.api.PLAYER + '<STR_LIT:/>' + tag + '<STR_LIT>'<EOL>return self._get_model(url, **params)<EOL>

Get a player's battle log

        Parameters
        ----------
        tag: str
            A valid tournament tag. Minimum length: 3
            Valid characters: 0289PYLQGRJCUV
        \*\*limit: Optional[int] = None
            Limit the number of items returned in the response
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


@typecasted<EOL><INDENT>def get_top_clanwar_clans(self, location_id='<STR_LIT>', **params: keys):<DEDENT>

url = self.api.LOCATIONS + '<STR_LIT:/>' + str(location_id) + '<STR_LIT>'<EOL>return self._get_model(url, PartialClan, **params)<EOL>

Get a list of top clan war clans

        Parameters
        ----------
        location_id: Optional[str] = 'global'
            A location ID or global
            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json
            for a list of acceptable location IDs
        \*\*limit: Optional[int] = None
            Limit the number of items returned in the response
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


@typecasted<EOL><INDENT>def get_location(self, location_id: int, timeout: int=None):<DEDENT>

url = self.api.LOCATIONS + '<STR_LIT:/>' + str(location_id)<EOL>return self._get_model(url, timeout=timeout)<EOL>

Get a location information

        Parameters
        ----------
        location_id: int
            A location ID
            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json
            for a list of acceptable location IDs
        timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


@typecasted<EOL><INDENT>def get_player_verify(self, tag: crtag, apikey: str, timeout=None):<DEDENT>

url = self.api.PLAYER + '<STR_LIT:/>' + tag + '<STR_LIT>'<EOL>return self._get_model(url, FullPlayer, timeout=timeout, method='<STR_LIT:POST>', json={'<STR_LIT>': apikey})<EOL>

Check the API Key of a player.
        This endpoint has been **restricted** to
        certain members of the community

        Raises BadRequest if the apikey is invalid

        Parameters
        ----------
        tag: str
            A valid tournament tag. Minimum length: 3
            Valid characters: 0289PYLQGRJCUV
        apikey: str
            The API Key in the player's settings
        timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


def get_deck_link(self, deck: BaseAttrDict):

deck_link = '<STR_LIT>'<EOL>for i in deck:<EOL><INDENT>card = self.get_card_info(i.name)<EOL>deck_link += '<STR_LIT>'.format(card)<EOL><DEDENT>return deck_link<EOL>

Form a deck link

        Parameters
        ---------
        deck: official_api.models.BaseAttrDict
            An object is a deck. Can be retrieved from ``Player.current_deck``

        Returns str


def get_arena_image(self, obj: BaseAttrDict):

badge_id = obj.arena.id<EOL>for i in self.constants.arenas:<EOL><INDENT>if i.id == badge_id:<EOL><INDENT>return '<STR_LIT>'.format(i.arena_id)<EOL><DEDENT><DEDENT>

Get the arena image URL

        Parameters
        ---------
        obj: official_api.models.BaseAttrDict
            An object that has the arena ID in ``.arena.id``
            Can be ``Profile`` for example.

        Returns None or str


@typecasted<EOL><INDENT>def get_all_locations(self, timeout: int=None):<DEDENT>

url = self.api.LOCATIONS<EOL>return self._get_model(url, timeout=timeout)<EOL>

Get a list of all locations

        Parameters
        ----------
        timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout


try:<EOL><INDENT>return self.client.get_clan(self.clan.tag)<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>return self.client.get_clan(self.tag)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>


return self.client.get_player(self.tag)<EOL>


def wrapper(resource, parent):<EOL><INDENT>if isinstance(resource, DeclarativeMeta):<EOL><INDENT>resource = ListResource(resource)<EOL><DEDENT>if not getattr(resource, '<STR_LIT>', None):<EOL><INDENT>resource.__parent__ = parent<EOL><DEDENT>return resource<EOL><DEDENT>resources_preparing_factory(app, wrapper)<EOL>


pass<EOL>

Mock constructor to accept the query_config parameters.


if start_date >= end_date:<EOL><INDENT>for n in range((start_date - end_date).days + <NUM_LIT:1>):<EOL><INDENT>yield end_date + datetime.timedelta(n)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for n in range((end_date - start_date).days + <NUM_LIT:1>):<EOL><INDENT>yield start_date + datetime.timedelta(n)<EOL><DEDENT><DEDENT>


from pkg_resources import iter_entry_points<EOL>def entrypoints(group, name=None):<EOL><INDENT>if group == mocked_group:<EOL><INDENT>for entrypoint in data:<EOL><INDENT>yield entrypoint<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for x in iter_entry_points(group=group, name=name):<EOL><INDENT>yield x<EOL><DEDENT><DEDENT><DEDENT>return entrypoints<EOL>

Create a mock iter_entry_points function.


doc['<STR_LIT>'] = '<STR_LIT>'.format(doc['<STR_LIT>'], doc['<STR_LIT>'])<EOL>return doc<EOL>


def file_download_event_builder(event, sender_app, obj=None, **kwargs):


return query.filter('<STR_LIT>', is_robot=False)<EOL>

Modify an elasticsearch query so that robot events are filtered out.


return '<STR_LIT>'.format(<EOL>self.event, self.aggregation_interval)<EOL>


if not isinstance(d, six.string_types):<EOL><INDENT>d = d.isoformat()<EOL><DEDENT>return '<STR_LIT>'.format(<EOL>d, self.dt_rounding_map[self.aggregation_interval])<EOL>

Format range filter datetime to the closest aggregation interval.


def agg_iter(self, lower_limit=None, upper_limit=None):

lower_limit = lower_limit or self.get_bookmark().isoformat()<EOL>upper_limit = upper_limit or (<EOL>datetime.datetime.utcnow().replace(microsecond=<NUM_LIT:0>).isoformat())<EOL>aggregation_data = {}<EOL>self.agg_query = Search(using=self.client,<EOL>index=self.event_index).filter('<STR_LIT>', timestamp={<EOL>'<STR_LIT>': self._format_range_dt(lower_limit),<EOL>'<STR_LIT>': self._format_range_dt(upper_limit)})<EOL>for modifier in self.query_modifiers:<EOL><INDENT>self.agg_query = modifier(self.agg_query)<EOL><DEDENT>hist = self.agg_query.aggs.bucket(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>field='<STR_LIT>',<EOL>interval=self.aggregation_interval<EOL>)<EOL>terms = hist.bucket(<EOL>'<STR_LIT>', '<STR_LIT>', field=self.aggregation_field, size=<NUM_LIT:0><EOL>)<EOL>top = terms.metric(<EOL>'<STR_LIT>', '<STR_LIT>', size=<NUM_LIT:1>, sort={'<STR_LIT>': '<STR_LIT>'}<EOL>)<EOL>for dst, (metric, src, opts) in self.metric_aggregation_fields.items():<EOL><INDENT>terms.metric(dst, metric, field=src, **opts)<EOL><DEDENT>results = self.agg_query.execute()<EOL>index_name = None<EOL>for interval in results.aggregations['<STR_LIT>'].buckets:<EOL><INDENT>interval_date = datetime.datetime.strptime(<EOL>interval['<STR_LIT>'], '<STR_LIT>')<EOL>for aggregation in interval['<STR_LIT>'].buckets:<EOL><INDENT>aggregation_data['<STR_LIT>'] = interval_date.isoformat()<EOL>aggregation_data[self.aggregation_field] = aggregation['<STR_LIT:key>']<EOL>aggregation_data['<STR_LIT:count>'] = aggregation['<STR_LIT>']<EOL>if self.metric_aggregation_fields:<EOL><INDENT>for f in self.metric_aggregation_fields:<EOL><INDENT>aggregation_data[f] = aggregation[f]['<STR_LIT:value>']<EOL><DEDENT><DEDENT>doc = aggregation.top_hit.hits.hits[<NUM_LIT:0>]['<STR_LIT>']<EOL>for destination, source in self.copy_fields.items():<EOL><INDENT>if isinstance(source, six.string_types):<EOL><INDENT>aggregation_data[destination] = doc[source]<EOL><DEDENT>else:<EOL><INDENT>aggregation_data[destination] = source(<EOL>doc,<EOL>aggregation_data<EOL>)<EOL><DEDENT><DEDENT>index_name = '<STR_LIT>'.format(self.event,<EOL>interval_date.strftime(<EOL>self.index_name_suffix))<EOL>self.indices.add(index_name)<EOL>yield dict(_id='<STR_LIT>'.<EOL>format(aggregation['<STR_LIT:key>'],<EOL>interval_date.strftime(<EOL>self.doc_id_suffix)),<EOL>_index=index_name,<EOL>_type=self.aggregation_doc_type,<EOL>_source=aggregation_data)<EOL><DEDENT><DEDENT>self.last_index_written = index_name<EOL>

Aggregate and return dictionary to be indexed in ES.


def delete(self, start_date=None, end_date=None):

aggs_query = Search(<EOL>using=self.client,<EOL>index=self.aggregation_alias,<EOL>doc_type=self.aggregation_doc_type<EOL>).extra(_source=False)<EOL>range_args = {}<EOL>if start_date:<EOL><INDENT>range_args['<STR_LIT>'] = self._format_range_dt(<EOL>start_date.replace(microsecond=<NUM_LIT:0>))<EOL><DEDENT>if end_date:<EOL><INDENT>range_args['<STR_LIT>'] = self._format_range_dt(<EOL>end_date.replace(microsecond=<NUM_LIT:0>))<EOL><DEDENT>if range_args:<EOL><INDENT>aggs_query = aggs_query.filter('<STR_LIT>', timestamp=range_args)<EOL><DEDENT>bookmarks_query = Search(<EOL>using=self.client,<EOL>index=self.aggregation_alias,<EOL>doc_type=self.bookmark_doc_type<EOL>).sort({'<STR_LIT:date>': {'<STR_LIT>': '<STR_LIT>'}})<EOL>if range_args:<EOL><INDENT>bookmarks_query = bookmarks_query.filter('<STR_LIT>', date=range_args)<EOL><DEDENT>def _delete_actions():<EOL><INDENT>for query in (aggs_query, bookmarks_query):<EOL><INDENT>affected_indices = set()<EOL>for doc in query.scan():<EOL><INDENT>affected_indices.add(doc.meta.index)<EOL>yield dict(_index=doc.meta.index,<EOL>_op_type='<STR_LIT>',<EOL>_id=doc.meta.id,<EOL>_type=doc.meta.doc_type)<EOL><DEDENT>current_search_client.indices.flush(<EOL>index='<STR_LIT:U+002C>'.join(affected_indices), wait_if_ongoing=True)<EOL><DEDENT><DEDENT>bulk(self.client, _delete_actions(), refresh=True)<EOL>


def _success_date():<EOL><INDENT>bookmark = {<EOL>'<STR_LIT:date>': self.new_bookmark or datetime.datetime.utcnow().<EOL>strftime(self.doc_id_suffix)<EOL>}<EOL>yield dict(_index=self.last_index_written,<EOL>_type=self.bookmark_doc_type,<EOL>_source=bookmark)<EOL><DEDENT>if self.last_index_written:<EOL><INDENT>bulk(self.client,<EOL>_success_date(),<EOL>stats_only=True)<EOL><DEDENT>

Set bookmark for starting next aggregation.


def list_bookmarks(self, start_date=None, end_date=None, limit=None):

query = Search(<EOL>using=self.client,<EOL>index=self.aggregation_alias,<EOL>doc_type=self.bookmark_doc_type<EOL>).sort({'<STR_LIT:date>': {'<STR_LIT>': '<STR_LIT>'}})<EOL>range_args = {}<EOL>if start_date:<EOL><INDENT>range_args['<STR_LIT>'] = self._format_range_dt(<EOL>start_date.replace(microsecond=<NUM_LIT:0>))<EOL><DEDENT>if end_date:<EOL><INDENT>range_args['<STR_LIT>'] = self._format_range_dt(<EOL>end_date.replace(microsecond=<NUM_LIT:0>))<EOL><DEDENT>if range_args:<EOL><INDENT>query = query.filter('<STR_LIT>', date=range_args)<EOL><DEDENT>return query[<NUM_LIT:0>:limit].execute() if limit else query.scan()<EOL>


aggregation_types = (aggregation_types or<EOL>list(current_stats.enabled_aggregations))<EOL>for a in aggregation_types:<EOL><INDENT>aggr_cfg = current_stats.aggregations[a]<EOL>aggregator = aggr_cfg.aggregator_class(<EOL>name=aggr_cfg.name, **aggr_cfg.aggregator_config)<EOL>aggregator.delete(start_date, end_date)<EOL><DEDENT>


event_types = event_types or list(current_stats.enabled_events)<EOL>if eager:<EOL><INDENT>process_events.apply((event_types,), throw=True)<EOL>click.secho('<STR_LIT>', fg='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>process_events.delay(event_types)<EOL>click.secho('<STR_LIT>', fg='<STR_LIT>')<EOL><DEDENT>


if app:<EOL><INDENT>self.init_app(app, **kwargs)<EOL><DEDENT>


return load_or_import_from_config(<EOL>'<STR_LIT>', app=self.app<EOL>)<EOL>

Load default permission factory for Buckets collections.


def consume(self, event_type, no_ack=True, payload=True):

assert event_type in self.events<EOL>return current_queues.queues['<STR_LIT>'.format(event_type)].consume(<EOL>payload=payload)<EOL>


result = {}<EOL>for ep in iter_entry_points(<EOL>group=self.entry_point_group_aggs):<EOL><INDENT>for cfg in ep.load()():<EOL><INDENT>if cfg['<STR_LIT>'] not in self.enabled_aggregations:<EOL><INDENT>continue<EOL><DEDENT>elif cfg['<STR_LIT>'] in result:<EOL><INDENT>raise DuplicateAggregationError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(cfg['<STR_LIT>'], ep.name))<EOL><DEDENT>cfg.update(<EOL>self.enabled_aggregations[cfg['<STR_LIT>']] or {}<EOL>)<EOL>result[cfg['<STR_LIT>']] = cfg<EOL><DEDENT><DEDENT>return result<EOL>


for k in dir(config):<EOL><INDENT>if k.startswith('<STR_LIT>'):<EOL><INDENT>app.config.setdefault(k, getattr(config, k))<EOL><DEDENT><DEDENT>


assert event_type in self.events<EOL>current_queues.queues['<STR_LIT>'.format(event_type)].publish(events)<EOL>


def validate_arguments(self, start_date, end_date, **kwargs):

if set(kwargs) < set(self.required_filters):<EOL><INDENT>raise InvalidRequestInputError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(set(self.required_filters.keys()),<EOL>self.query_name)<EOL>)<EOL><DEDENT>


def __init__(self, query_name, doc_type, index, client=None,<EOL>*args, **kwargs):

super(ESQuery, self).__init__()<EOL>self.index = index<EOL>self.client = client or current_search_client<EOL>self.query_name = query_name<EOL>self.doc_type = doc_type<EOL>

Constructor.

        :param doc_type: queried document type.
        :param index: queried index.
        :param client: elasticsearch client used to query.


def __init__(self, time_field='<STR_LIT>', copy_fields=None,<EOL>query_modifiers=None, required_filters=None,<EOL>metric_fields=None, *args, **kwargs):

super(ESDateHistogramQuery, self).__init__(*args, **kwargs)<EOL>self.time_field = time_field<EOL>self.copy_fields = copy_fields or {}<EOL>self.query_modifiers = query_modifiers or []<EOL>self.required_filters = required_filters or {}<EOL>self.metric_fields = metric_fields or {'<STR_LIT:value>': ('<STR_LIT>', '<STR_LIT:count>', {})}<EOL>self.allowed_metrics = {<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}<EOL>if any(v not in self.allowed_metrics<EOL>for k, (v, _, _) in (self.metric_fields or {}).items()):<EOL><INDENT>raise(ValueError('<STR_LIT>'<EOL>.format('<STR_LIT:U+002CU+0020>'.join(self.allowed_metrics))))<EOL><DEDENT>

Constructor.

        :param time_field: name of the timestamp field.
        :param copy_fields: list of fields to copy from the top hit document
            into the resulting aggregation.
        :param query_modifiers: List of functions accepting a ``query`` and
            ``**kwargs`` (same as provided to the ``run`` method), that will
            be applied to the aggregation query.
        :param required_filters: Dict of "mandatory query parameter" ->
            "filtered field".
        :param metric_fields: Dict of "destination field" ->
            tuple("metric type", "source field", "metric_options").


return '<STR_LIT>'.format(iso_timestamp,<EOL>hashlib.sha1(<EOL>msg.get('<STR_LIT>').encode('<STR_LIT:utf-8>') +<EOL>str(msg.get('<STR_LIT>')).<EOL>encode('<STR_LIT:utf-8>')).<EOL>hexdigest())<EOL>


def __init__(self, queue, prefix='<STR_LIT>', suffix='<STR_LIT>', client=None,<EOL>preprocessors=None, double_click_window=<NUM_LIT:10>):

self.queue = queue<EOL>self.client = client or current_search_client<EOL>self.doctype = queue.routing_key<EOL>self.index = '<STR_LIT>'.format(prefix, self.queue.routing_key)<EOL>self.suffix = suffix<EOL>self.preprocessors = [<EOL>obj_or_import_string(preproc) for preproc in preprocessors<EOL>] if preprocessors is not None else self.default_preprocessors<EOL>self.double_click_window = double_click_window<EOL>

Initialize indexer.

        :param prefix: prefix appended to elasticsearch indices' name.
        :param suffix: suffix appended to elasticsearch indices' name.
        :param double_click_window: time window during which similar events are
            deduplicated (counted as one occurence).
        :param client: elasticsearch client.
        :param preprocessors: a list of functions which are called on every
            event before it is indexed. Each function should return the
            processed event. If it returns None, the event is filtered and
            won't be indexed.


doc['<STR_LIT>'] = '<STR_LIT>' in doc and is_robot(doc['<STR_LIT>'])<EOL>return doc<EOL>

Flag events which are created by robots.

    The list of robots is defined by the `COUNTER-robots Python package
    <https://github.com/inveniosoftware/counter-robots>`_ , which follows the
    `list defined by Project COUNTER
    <https://www.projectcounter.org/appendices/850-2/>`_ that was later split
    into robots and machines by `the Make Data Count project
    <https://github.com/CDLUC3/Make-Data-Count/tree/master/user-agents>`_.


for msg in self.queue.consume():<EOL><INDENT>try:<EOL><INDENT>for preproc in self.preprocessors:<EOL><INDENT>msg = preproc(msg)<EOL>if msg is None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if msg is None:<EOL><INDENT>continue<EOL><DEDENT>suffix = arrow.get(msg.get('<STR_LIT>')).strftime(self.suffix)<EOL>ts = parser.parse(msg.get('<STR_LIT>'))<EOL>ts = ts.replace(microsecond=<NUM_LIT:0>)<EOL>msg['<STR_LIT>'] = ts.isoformat()<EOL>if self.double_click_window > <NUM_LIT:0>:<EOL><INDENT>timestamp = mktime(utc.localize(ts).utctimetuple())<EOL>ts = ts.fromtimestamp(<EOL>timestamp // self.double_click_window *<EOL>self.double_click_window<EOL>)<EOL><DEDENT>yield dict(<EOL>_id=hash_id(ts.isoformat(), msg),<EOL>_op_type='<STR_LIT:index>',<EOL>_index='<STR_LIT>'.format(self.index, suffix),<EOL>_type=self.doctype,<EOL>_source=msg,<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>current_app.logger.exception(u'<STR_LIT>')<EOL><DEDENT><DEDENT>


results = []<EOL>for e in event_types:<EOL><INDENT>processor = current_stats.events[e].processor_class(<EOL>**current_stats.events[e].processor_config)<EOL>results.append((e, processor.run()))<EOL><DEDENT>return results<EOL>


return dict(<EOL>ip_address=request.remote_addr,<EOL>user_agent=request.user_agent.string,<EOL>user_id=(<EOL>current_user.get_id() if current_user.is_authenticated else None<EOL>),<EOL>session_id=session.get('<STR_LIT>')<EOL>)<EOL>

User information.

    .. note::

       **Privacy note** A users IP address, user agent string, and user id
       (if logged in) is sent to a message queue, where it is stored for about
       5 minutes. The information is used to:

       - Detect robot visits from the user agent string.
       - Generate an anonymized visitor id (using a random salt per day).
       - Detect the users host contry based on the IP address.

       The information is then discarded.


from invenio_stats import current_stats<EOL>if current_stats.queries[query_name].permission_factory is None:<EOL><INDENT>return AllowAllPermission<EOL><DEDENT>else:<EOL><INDENT>return current_stats.queries[query_name].permission_factory(<EOL>query_name, params<EOL>)<EOL><DEDENT>

Default permission factory.

    It enables by default the statistics if they don't have a dedicated
    permission factory.


def load_or_import_from_config(key, app=None, default=None):

app = app or current_app<EOL>imp = app.config.get(key)<EOL>return obj_or_import_string(imp, default=default)<EOL>

Load or import value from config.

    :returns: The loaded value.


result = []<EOL>if ranges:<EOL><INDENT>ranges.sort(key=lambda tup: tup[<NUM_LIT:0>])<EOL>result.append(ranges[<NUM_LIT:0>])<EOL>for i in range(<NUM_LIT:1>, len(ranges)):<EOL><INDENT>if result[-<NUM_LIT:1>][<NUM_LIT:1>] + <NUM_LIT:1> >= ranges[i][<NUM_LIT:0>]:<EOL><INDENT>result[-<NUM_LIT:1>] = (result[-<NUM_LIT:1>][<NUM_LIT:0>], max(result[-<NUM_LIT:1>][<NUM_LIT:1>], ranges[i][<NUM_LIT:1>]))<EOL><DEDENT>else:<EOL><INDENT>result.append(ranges[i])<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>


r = []<EOL>s = environ.get(cls.header_range, '<STR_LIT>').replace('<STR_LIT:U+0020>','<STR_LIT>').lower()<EOL>if s:<EOL><INDENT>l = s.split('<STR_LIT:=>')<EOL>if len(l) == <NUM_LIT:2>:<EOL><INDENT>unit, vals = tuple(l)<EOL>if unit == '<STR_LIT>' and vals:<EOL><INDENT>gen_rng = ( tuple(rng.split('<STR_LIT:->')) for rng in vals.split('<STR_LIT:U+002C>') if '<STR_LIT:->' in rng )<EOL>for start, end in gen_rng:<EOL><INDENT>if start or end:<EOL><INDENT>r.append( (int(start) if start else None, int(end) if end else None) )<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return r<EOL>

Outputs a list of tuples with ranges or the empty list
According to the rfc, start or end values can be omitted


@classmethod<EOL><INDENT>def check_ranges(cls, ranges, length):<DEDENT>

result = []<EOL>for start, end in ranges:<EOL><INDENT>if isinstance(start, int) or isinstance(end, int):<EOL><INDENT>if isinstance(start, int) and not (<NUM_LIT:0> <= start < length):<EOL><INDENT>continue<EOL><DEDENT>elif isinstance(start, int) and isinstance(end, int) and not (start <= end):<EOL><INDENT>continue<EOL><DEDENT>elif start is None and end == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>result.append( (start,end) )<EOL><DEDENT><DEDENT>return result<EOL>


frequencies = OrderedDict([<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')])<EOL>pref_freq = '<STR_LIT>'<EOL>for source in frequencies.keys():<EOL><INDENT>freq_key = '<STR_LIT>' + source<EOL>if freq_key in self.info:<EOL><INDENT>frequencies[source] = self.info[freq_key]<EOL>if pref_freq == '<STR_LIT>':<EOL><INDENT>pref_freq = frequencies[source]<EOL><DEDENT><DEDENT><DEDENT>return pref_freq, frequencies<EOL>


self_as_dict = super(ClinVarAllele, self).as_dict(*args, **kwargs)<EOL>self_as_dict['<STR_LIT>'] = self.hgvs<EOL>self_as_dict['<STR_LIT>'] = self.clnalleleid<EOL>self_as_dict['<STR_LIT>'] = self.clnsig<EOL>self_as_dict['<STR_LIT>'] = self.clndn<EOL>self_as_dict['<STR_LIT>'] = self.clndisdb<EOL>self_as_dict['<STR_LIT>'] = self.clnvi<EOL>return self_as_dict<EOL>

Return ClinVarAllele data as dict object.


self_as_dict = dict()<EOL>self_as_dict['<STR_LIT>'] = self.sequence<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self_as_dict['<STR_LIT>'] = self.frequency<EOL><DEDENT>return self_as_dict<EOL>


sequence = kwargs['<STR_LIT>']<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>frequency = kwargs['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>frequency = '<STR_LIT>'<EOL><DEDENT>if not (re.match(r'<STR_LIT>', sequence) or<EOL>re.match(r'<STR_LIT>', sequence)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.sequence = sequence<EOL>if frequency:<EOL><INDENT>try:<EOL><INDENT>if (float(frequency) < <NUM_LIT:0.0> or<EOL>float(frequency) > <NUM_LIT:1.0>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>if not frequency == '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>' +<EOL>'<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>self.frequency = frequency<EOL><DEDENT>

Initialize Allele object

Required arguments:
sequence:  Short string of DNA letters (ACGT) for the allele.
           May be empty (to represent a deletion).

Optional arguments:
frequency: a string representation of a float between 0 and 1


vcf_line = kwargs['<STR_LIT>']<EOL>skip_info = ('<STR_LIT>' in kwargs and kwargs['<STR_LIT>'])<EOL>vcf_fields = vcf_line.strip().split('<STR_LIT:\t>')<EOL>self.chrom = vcf_fields[<NUM_LIT:0>]<EOL>self.start = int(vcf_fields[<NUM_LIT:1>])<EOL>self.ref_allele = vcf_fields[<NUM_LIT:3>]<EOL>if vcf_fields[<NUM_LIT:4>] == '<STR_LIT:.>':<EOL><INDENT>self.alt_alleles = []<EOL><DEDENT>else:<EOL><INDENT>self.alt_alleles = vcf_fields[<NUM_LIT:4>].split('<STR_LIT:U+002C>')<EOL><DEDENT>if not skip_info:<EOL><INDENT>self.info = self._parse_info(vcf_fields[<NUM_LIT:7>])<EOL><DEDENT>self.alleles = self._parse_allele_data()<EOL>


self_as_dict = {'<STR_LIT>': self.chrom,<EOL>'<STR_LIT:start>': self.start,<EOL>'<STR_LIT>': self.ref_allele,<EOL>'<STR_LIT>': self.alt_alleles,<EOL>'<STR_LIT>': [x.as_dict() for x in self.alleles]}<EOL>try:<EOL><INDENT>self_as_dict['<STR_LIT:info>'] = self.info<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>return self_as_dict<EOL>


return self.as_json()<EOL>

Print Allele object as dict object data.


return self.as_json()<EOL>


format_col = vcf_fields[<NUM_LIT:8>].split('<STR_LIT::>')<EOL>genome_data = vcf_fields[<NUM_LIT:9>].split('<STR_LIT::>')<EOL>try:<EOL><INDENT>gt_idx = format_col.index('<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>return []<EOL><DEDENT>return [int(x) for x in re.split(r'<STR_LIT>', genome_data[gt_idx]) if<EOL>x != '<STR_LIT:.>']<EOL>


for item in table:<EOL><INDENT>res = {<EOL>k.lower(): nfd(v) if isinstance(v, text_type) else v for k, v in item.items()}<EOL>for extra in res.pop('<STR_LIT>', []):<EOL><INDENT>k, _, v = extra.partition('<STR_LIT::>')<EOL>res[k.strip()] = v.strip()<EOL><DEDENT>yield res<EOL><DEDENT>

Auxiliary function for iterating over a data table.


return self.resolve_sound(sound)<EOL>

Return a Sound instance matching the specification.


nstring = norm(string)<EOL>if "<STR_LIT:/>" in string:<EOL><INDENT>s, t = string.split('<STR_LIT:/>')<EOL>nstring = t<EOL><DEDENT>return self.normalize(nstring)<EOL>

Extended normalization: normalize by list of norm-characers, split
        by character "/".


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>assert id_<EOL>system = pkg_path('<STR_LIT>', id_)<EOL>if not (system.exists() and system.is_dir()):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(id_))<EOL><DEDENT>self.system = TableGroup.from_file(<EOL>pkg_path('<STR_LIT>', '<STR_LIT>'))<EOL>self.system._fname = system / '<STR_LIT>'<EOL>self.features = {'<STR_LIT>': {}, '<STR_LIT>': {}, '<STR_LIT>': {}}<EOL>self._feature_values = {}<EOL>features = jsonlib.load(pkg_path('<STR_LIT>', '<STR_LIT>'))<EOL>self.diacritics = dict(<EOL>consonant={}, vowel={}, click={}, diphthong={}, tone={}, cluster={})<EOL>for dia in itertable(self.system.tabledict['<STR_LIT>']):<EOL><INDENT>if not dia['<STR_LIT>'] and not dia['<STR_LIT>']:<EOL><INDENT>self.features[dia['<STR_LIT:type>']][dia['<STR_LIT:value>']] = dia['<STR_LIT>']<EOL><DEDENT>self._feature_values[dia['<STR_LIT:value>']] = dia['<STR_LIT>']<EOL>self.diacritics[dia['<STR_LIT:type>']][dia['<STR_LIT>']] = dia['<STR_LIT:value>']<EOL><DEDENT>self.sound_classes = {}<EOL>self.columns = {}  <EOL>self.sounds = {}  <EOL>self._covered = {}<EOL>aliases = []<EOL>for cls in [Consonant, Vowel, Tone, Marker]:  <EOL><INDENT>type_ = cls.__name__.lower()<EOL>self.sound_classes[type_] = cls<EOL>self.columns[type_] = [<EOL>c['<STR_LIT:name>'].lower() for c in<EOL>self.system.tabledict['<STR_LIT>'.format(type_)]<EOL>.asdict()['<STR_LIT>']['<STR_LIT>']]<EOL>for l, item in enumerate(itertable(<EOL>self.system.tabledict['<STR_LIT>'.format(type_)])):<EOL><INDENT>if item['<STR_LIT>'] in self.sounds:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(<EOL>type_ + '<STR_LIT>', l + <NUM_LIT:2>, item['<STR_LIT>']))<EOL><DEDENT>sound = cls(ts=self, **item)<EOL>for key, value in item.items():<EOL><INDENT>if key not in {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'} andvalue and value not in self._feature_values:<EOL><INDENT>self._feature_values[value] = key<EOL>if type_ != '<STR_LIT>' and value not in features[type_][key]:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>key, value, l + <NUM_LIT:2>))<EOL><DEDENT><DEDENT><DEDENT>self.sounds[item['<STR_LIT>']] = sound<EOL>if not sound.alias:<EOL><INDENT>if sound.featureset in self.features:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(<EOL>type_ + '<STR_LIT>', l + <NUM_LIT:2>, sound.name))<EOL><DEDENT>self.features[sound.featureset] = sound<EOL><DEDENT>else:<EOL><INDENT>aliases += [(l, sound.type, sound.featureset)]<EOL><DEDENT><DEDENT><DEDENT>if [x for x in aliases if x[<NUM_LIT:2>] not in self.features]:  <EOL><INDENT>error = '<STR_LIT:U+002CU+0020>'.join(<EOL>text_type(x[<NUM_LIT:0>] + <NUM_LIT:2>) + '<STR_LIT:/>' + text_type(x[<NUM_LIT:1>])<EOL>for x in aliases if x[<NUM_LIT:2>] not in self.features)<EOL>raise ValueError(<EOL>'<STR_LIT>'.format(error))<EOL><DEDENT>self._regex = None<EOL>self._update_regex()<EOL>self._normalize = {<EOL>norm(r['<STR_LIT:source>']): norm(r['<STR_LIT:target>'])<EOL>for r in itertable(self.system.tabledict['<STR_LIT>'])}<EOL>

:param system: The name of a transcription system or a directory containing one.


nstring = self._norm(string)<EOL>if nstring in self.sounds:<EOL><INDENT>sound = self.sounds[nstring]<EOL>sound.normalized = nstring != string<EOL>sound.source = string<EOL>return sound<EOL><DEDENT>match = list(self._regex.finditer(nstring))<EOL>if len(match) == <NUM_LIT:2>:<EOL><INDENT>sound1 = self._parse(nstring[:match[<NUM_LIT:1>].start()])<EOL>sound2 = self._parse(nstring[match[<NUM_LIT:1>].start():])<EOL>if '<STR_LIT>' not in (sound1.type, sound2.type) andsound1.type == sound2.type:<EOL><INDENT>if sound1.type == '<STR_LIT>':<EOL><INDENT>return Diphthong.from_sounds(  <EOL>string, sound1, sound2, self)<EOL><DEDENT>elif sound1.type == '<STR_LIT>' andsound1.manner in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>') andsound2.manner in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return Cluster.from_sounds(  <EOL>string, sound1, sound2, self)<EOL><DEDENT><DEDENT>return UnknownSound(grapheme=nstring, source=string, ts=self)  <EOL><DEDENT>if len(match) != <NUM_LIT:1>:<EOL><INDENT>return UnknownSound(grapheme=nstring, source=string, ts=self)  <EOL><DEDENT>pre, mid, post = nstring.partition(nstring[match[<NUM_LIT:0>].start():match[<NUM_LIT:0>].end()])<EOL>base_sound = self.sounds[mid]<EOL>if isinstance(base_sound, Marker):  <EOL><INDENT>assert pre or post<EOL>return UnknownSound(grapheme=nstring, source=string, ts=self)  <EOL><DEDENT>features = attr.asdict(base_sound)<EOL>features.update(<EOL>source=string,<EOL>generated=True,<EOL>normalized=nstring != string,<EOL>base=base_sound.grapheme)<EOL>grapheme, sound = '<STR_LIT>', '<STR_LIT>'<EOL>for dia in [p + EMPTY for p in pre]:<EOL><INDENT>feature = self.diacritics[base_sound.type].get(dia, {})<EOL>if not feature:<EOL><INDENT>return UnknownSound(  <EOL>grapheme=nstring, source=string, ts=self)<EOL><DEDENT>features[self._feature_values[feature]] = feature<EOL>grapheme += dia[<NUM_LIT:0>]<EOL>sound += self.features[base_sound.type][feature][<NUM_LIT:0>]<EOL><DEDENT>grapheme += base_sound.grapheme<EOL>sound += base_sound.s<EOL>for dia in [EMPTY + p for p in post]:<EOL><INDENT>feature = self.diacritics[base_sound.type].get(dia, {})<EOL>if not feature:<EOL><INDENT>return UnknownSound(  <EOL>grapheme=nstring, source=string, ts=self)<EOL><DEDENT>features[self._feature_values[feature]] = feature<EOL>grapheme += dia[<NUM_LIT:1>]<EOL>sound += self.features[base_sound.type][feature][<NUM_LIT:1>]<EOL><DEDENT>features['<STR_LIT>'] = sound<EOL>new_sound = self.sound_classes[base_sound.type](**features)<EOL>if text_type(new_sound) != sound:<EOL><INDENT>new_sound.alias = True<EOL><DEDENT>if grapheme != sound:<EOL><INDENT>new_sound.alias = True<EOL>new_sound.grapheme = grapheme<EOL><DEDENT>return new_sound<EOL>

Parse a string and return its features.

        :param string: A one-symbol string in NFD

        Notes
        -----
        Strategy is rather simple: we determine the base part of a string and
        then search left and right of this part for the additional features as
        expressed by the diacritics. Fails if a segment has more than one basic
        part.


return '<STR_LIT>'.join([self._normalize.get(x, x) for x in nfd(string)])<EOL>

Normalize the string according to normalization list


return '<STR_LIT:U+0020>'.join('<STR_LIT>' + ('<STR_LIT>' + hex(ord(x))[<NUM_LIT:2>:])[-<NUM_LIT:4>:] for x in self.__unicode__())<EOL>

Return unicode codepoint(s) for a grapheme.


tbl = []<EOL>features = [<EOL>f for f in self._name_order if f not in self.ts.columns[self.type]]<EOL>if self.generated and self.s != self.source:<EOL><INDENT>tbl += [self.__unicode__() + '<STR_LIT>' + self.source]<EOL><DEDENT>else:<EOL><INDENT>tbl += [self.__unicode__()]<EOL><DEDENT>for name in self.ts.columns[self.type][<NUM_LIT:1>:]:<EOL><INDENT>if name != '<STR_LIT>' and name != '<STR_LIT>':<EOL><INDENT>tbl += [getattr(self, name) or '<STR_LIT>']<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>tbl += ['<STR_LIT:+>' if getattr(self, name) else '<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>bundle = []<EOL>for f in features:<EOL><INDENT>val = getattr(self, f)<EOL>if val:<EOL><INDENT>bundle += ['<STR_LIT>'.format(f, val)]<EOL><DEDENT><DEDENT>tbl += ['<STR_LIT:U+002C>'.join(bundle)]<EOL><DEDENT><DEDENT>return tbl<EOL>

Returns the tabular representation of the sound as given in our data


try:<EOL><INDENT>return '<STR_LIT>'.join(unicodedata.name(ss) for ss in self.__unicode__())<EOL><DEDENT>except TypeError:<EOL><INDENT>return '<STR_LIT:->'<EOL><DEDENT>except ValueError:<EOL><INDENT>return '<STR_LIT:?>'<EOL><DEDENT>

Return unicode name(s) for a character set.


<EOL>if not self.generated:<EOL><INDENT>if not self.alias and self.grapheme in self.ts.sounds:<EOL><INDENT>return self.grapheme<EOL><DEDENT>elif self.alias and self.featureset in self.ts.features:<EOL><INDENT>return text_type(self.ts.features[self.featureset])<EOL><DEDENT>raise ValueError(<EOL>'<STR_LIT>'.format(self.grapheme))  <EOL><DEDENT>elements = [f for f in self._features() if f not in EXCLUDE_FEATURES] + [self.type]<EOL>base_str = self.base or '<STR_LIT>'<EOL>base_graphemes = []<EOL>while elements:<EOL><INDENT>base = self.ts.features.get(frozenset(elements))<EOL>if base:<EOL><INDENT>base_graphemes.append(base.grapheme)<EOL><DEDENT>elements.pop(<NUM_LIT:0>)<EOL><DEDENT>base_str = base_graphemes[-<NUM_LIT:1>] if base_graphemes else base_str or '<STR_LIT>'<EOL>base_vals = {<EOL>self.ts._feature_values[elm] for elm in<EOL>self.ts.sounds[base_str].name.split('<STR_LIT:U+0020>')[:-<NUM_LIT:1>]} ifbase_str != '<STR_LIT>' else {}<EOL>out = []<EOL>for p in self._write_order['<STR_LIT>']:<EOL><INDENT>if p not in base_vals and getattr(self, p, '<STR_LIT>') in self._features():<EOL><INDENT>out.append(<EOL>norm(self.ts.features[self.type].get(getattr(self, p, '<STR_LIT>'), '<STR_LIT>')))<EOL><DEDENT><DEDENT>out.append(base_str)<EOL>for p in self._write_order['<STR_LIT>']:<EOL><INDENT>if p not in base_vals and getattr(self, p, '<STR_LIT>') in self._features():<EOL><INDENT>out.append(<EOL>norm(self.ts.features[self.type].get(getattr(self, p, '<STR_LIT>'), '<STR_LIT>')))<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(out)<EOL>

Return the reference representation of the sound.

Note
----
We first try to return the non-alias value in our data. If this fails,
we create the sound based on it's feature representation.


sound = sound if isinstance(sound, Symbol) else self.system[sound]<EOL>if sound.name in self.data:<EOL><INDENT>return self.data[sound.name]['<STR_LIT>']<EOL><DEDENT>if not sound.type == '<STR_LIT>':<EOL><INDENT>if sound.type in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return self.resolve_sound(sound.from_sound)<EOL><DEDENT>name = [<EOL>s for s in sound.name.split('<STR_LIT:U+0020>') if<EOL>self.system._feature_values.get(s, '<STR_LIT>') not in<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']]<EOL>while len(name) >= <NUM_LIT:4>:<EOL><INDENT>sound = self.system.get('<STR_LIT:U+0020>'.join(name))<EOL>if sound and sound.name in self.data:<EOL><INDENT>return self.resolve_sound(sound)<EOL><DEDENT>name.pop(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>raise KeyError("<STR_LIT>")<EOL>

Function tries to identify a sound in the data.

        Notes
        -----
        The function tries to resolve sounds to take a sound with less complex
        features in order to yield the next approximate sound class, if the
        transcription data are sound classes.


return {p.strip() for p in (header or '<STR_LIT>').split('<STR_LIT:;>')}<EOL>

Normalize a CSP header for consistent comparisons.


self.limiter = None<EOL>self.talisman = None<EOL>if app:<EOL><INDENT>self.init_app(app, **kwargs)<EOL><DEDENT>

r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.


<EOL>local_templates_path = os.path.join(app.instance_path, '<STR_LIT>')<EOL>if os.path.exists(local_templates_path):<EOL><INDENT>app.jinja_loader = ChoiceLoader([<EOL>FileSystemLoader(local_templates_path),<EOL>app.jinja_loader,<EOL>])<EOL><DEDENT>app.jinja_options = dict(<EOL>app.jinja_options,<EOL>cache_size=<NUM_LIT:1000>,<EOL>bytecode_cache=BytecodeCache(app)<EOL>)<EOL>invenio_config_loader(app, **kwargs_config)<EOL>

Configuration loader.

    Adds support for loading templates from the Flask application's instance
    folder (``<instance_folder>/templates``).


self._rules = rules or []<EOL>self._dict = config or {}<EOL>self.enforce_rules()<EOL>

:param config: Old configuration
:type config: behaving like dict or Config


if type(value) is str:<EOL><INDENT>try:<EOL><INDENT>value=float(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return (option,value)<EOL>

Converts string values to floats when appropriate


src_path = Path(source_dir).expanduser().resolve()<EOL>with ZipFile(zip_name, '<STR_LIT:w>', ZIP_DEFLATED) as zf:<EOL><INDENT>for file in src_path.rglob('<STR_LIT:*>'):<EOL><INDENT>path_in_zip = str(file.relative_to(src_path.parent))<EOL>if rename_source_dir != False:<EOL><INDENT>_,tail = path_in_zip.split(os.sep,<NUM_LIT:1>)<EOL>path_in_zip=os.sep.join([rename_source_dir,tail])<EOL><DEDENT>zf.write(str(file.resolve()), path_in_zip)<EOL><DEDENT><DEDENT>


has = []<EOL>return [x for x in seq if not (x in has or has.append(x))]<EOL>


F = RFunction()<EOL>for key in self.keys():<EOL><INDENT>F[key] = other * self[key]<EOL><DEDENT>return F<EOL>

Vector space operation: Multiply real-valued function with real


F = RFunction()<EOL>for key in self.keys():<EOL><INDENT>F[key] = self[key]<EOL><DEDENT>for key in other.keys():<EOL><INDENT>if key in F.keys():<EOL><INDENT>F[key] += other[key]<EOL><DEDENT>else:<EOL><INDENT>F[key] = other[key]<EOL><DEDENT><DEDENT>return F<EOL>

Vector space operation: Add two real-valued functions


for x in X:<EOL><INDENT>self[x] = None<EOL><DEDENT>

Expand domain

:param X: New elements of domain
:type X: Iterable


dict.__init__(self)<EOL>if init_dict:<EOL><INDENT>for key in init_dict:<EOL><INDENT>self[key] = init_dict[key]<EOL><DEDENT><DEDENT>

:param init_dict: Initial state of function
:type init_dict: Dictionary whos values support addition and scalar multiplication


if self.__tight:<EOL><INDENT>return array(self.__wrapped)<EOL><DEDENT>return self.__wrapped<EOL>

r'''Returns the encapsulated ndarray.

            If the wrapper is "tight", a copy of the encapsulated ndarray is
            returned. Otherwise, the encapsulated ndarray itself is returned.


def integral(A=None,dF=None,F=None,axis = <NUM_LIT:0>,trapez = False,cumulative = False):

ndim = max(v.ndim for v in (A,dF,F) if v is not None)<EOL>def broadcast(x):<EOL><INDENT>new_shape = [<NUM_LIT:1>]*ndim<EOL>new_shape[axis] = -<NUM_LIT:1><EOL>return np.reshape(x,new_shape)<EOL><DEDENT>if F is not None:<EOL><INDENT>assert(dF is None)<EOL>if F.ndim<ndim:<EOL><INDENT>F = broadcast(F)<EOL><DEDENT>N = F.shape[axis]<EOL>dF = F.take(indices = range(<NUM_LIT:1>,N),axis = axis)-F.take(indices = range(N-<NUM_LIT:1>),axis = axis)<EOL><DEDENT>elif dF is not None:<EOL><INDENT>if dF.ndim<ndim:<EOL><INDENT>dF = broadcast(dF)<EOL><DEDENT>N = dF.shape[axis]+<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>if A.ndim<ndim:<EOL><INDENT>A = broadcast(A)<EOL><DEDENT>N = A.shape[axis]<EOL><DEDENT>if A is not None:<EOL><INDENT>if trapez:<EOL><INDENT>midA = (A.take(indices = range(<NUM_LIT:1>,N),axis = axis)+A.take(indices = range(N-<NUM_LIT:1>),axis = axis))/<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>midA = A.take(indices=range(N-<NUM_LIT:1>),axis=axis)<EOL><DEDENT>if dF is not None:<EOL><INDENT>dY = midA*dF<EOL><DEDENT>else:<EOL><INDENT>dY = midA<EOL><DEDENT><DEDENT>else:<EOL><INDENT>dY = dF<EOL><DEDENT>pad_shape = list(dY.shape)<EOL>pad_shape[axis] = <NUM_LIT:1><EOL>pad = np.zeros(pad_shape)<EOL>if cumulative:<EOL><INDENT>return np.concatenate((pad,np.cumsum(dY,axis = axis)),axis = axis)<EOL><DEDENT>else:<EOL><INDENT>return np.sum(dY,axis = axis)<EOL><DEDENT>

Turns an array A of length N (the function values in N points)
and an array dF of length N-1 (the masses of the N-1 intervals)
into an array of length N (the integral \int A dF at N points, with first entry 0)

:param A: Integrand (optional, default ones, length N)
:param dF: Integrator (optional, default ones, length N-1)
:param F: Alternative to dF (optional, length N)
:param trapez: Use trapezoidal rule (else left point)


def grid_evaluation(X, Y, f,vectorized=True):

XX = np.reshape(np.concatenate([X[..., None], Y[..., None]], axis=<NUM_LIT:2>), (X.size, <NUM_LIT:2>), order='<STR_LIT:C>')<EOL>if vectorized:<EOL><INDENT>ZZ = f(XX)<EOL><DEDENT>else:<EOL><INDENT>ZZ = np.array([f(x) for x in XX])<EOL><DEDENT>return np.reshape(ZZ, X.shape, order='<STR_LIT:C>')<EOL>

Evaluate function on given grid and return values in grid format

Assume X and Y are 2-dimensional arrays containing x and y coordinates,
respectively, of a two-dimensional grid, and f is a function that takes
1-d arrays with two entries. This function evaluates f on the grid points
described by X and Y and returns another 2-dimensional array of the shape
of X and Y that contains the values of f.

:param X: 2-dimensional array of x-coordinates
:param Y: 2-dimensional array of y-coordinates
:param f: function to be evaluated on grid
:param vectorized: `f` can handle arrays of inputs
:return: 2-dimensional array of values of f


if len(values) == <NUM_LIT:1>:<EOL><INDENT>return values[<NUM_LIT:0>]<EOL><DEDENT>if len(values) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>values = [float(value) for value in values]<EOL>indices_sorted = np.argsort(values)<EOL>values = [values[ind] for ind in indices_sorted]<EOL>weights = [weights[ind] for ind in indices_sorted]<EOL>total_weight = sum(weights)<EOL>below_weight = <NUM_LIT:0><EOL>i = -<NUM_LIT:1><EOL>while below_weight < total_weight / <NUM_LIT:2>:<EOL><INDENT>i += <NUM_LIT:1><EOL>below_weight += weights[i]<EOL><DEDENT>return values[i]<EOL>

Returns element such that sum of weights below and above are (roughly) equal

:param values: Values whose median is sought
:type values: List of reals
:param weights: Weights of each value
:type weights: List of positive reals
:return: value of weighted median
:rtype: Real


@validate_args(warnings=False)<EOL>def EasyHPC(backend:In('<STR_LIT>', '<STR_LIT>')|Function='<STR_LIT>',<EOL>n_tasks:In('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:count>')='<STR_LIT>',<EOL>n_results:In('<STR_LIT>', '<STR_LIT>')='<STR_LIT>',<EOL>aux_output:Bool=True,  <EOL>reduce:Function=None,<EOL>split_job=NotPassed,<EOL>parallel = True,<EOL>method = None,<EOL>pool = None<EOL>):

self = argparse.Namespace()<EOL>direct_call =  (~String&Function).valid(backend)<EOL>if direct_call:<EOL><INDENT>f = backend<EOL>backend = '<STR_LIT>'<EOL><DEDENT>if backend == '<STR_LIT>': <EOL><INDENT>self.processor = _MPI_processor<EOL>self.finalizer = _MPI_finalizer<EOL><DEDENT>if backend == '<STR_LIT>':<EOL><INDENT>self.processor = _MP_processor<EOL>self.finalizer = None<EOL><DEDENT>self.info = argparse.Namespace()<EOL>self.info.n_tasks = n_tasks<EOL>self.info.n_results = n_results<EOL>self.info.parallel = parallel<EOL>self.info.reduce = reduce<EOL>self.info.wrap_MPI = False<EOL>self.info.aux_output = aux_output <EOL>self.info.method = method<EOL>self.info.pool = pool or Pool()<EOL>self.info.split_job = split_job<EOL>if self.info.n_tasks == '<STR_LIT>':<EOL><INDENT>if self.info.n_results == '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if NotPassed(self.info.split_job):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if direct_call:<EOL><INDENT>def _lam(*args,**kwargs):<EOL><INDENT>return _MultiProcessorWrapper_call(args,kwargs,f,self.processor,self.finalizer,self.info)<EOL><DEDENT>return _lam<EOL><DEDENT>return lambda f: _easy_hpc_call(f,self)<EOL>

:param n_tasks: How many tasks does the decorated function handle?
:param n_results: If the decorated function handles many tasks at once, are the results reduced (n_results = 'one') or not (as many results as tasks)?
:param reduce: Function that reduces multiple outputs to a single output
:param splitjob: Function that converts an input (to the decorated function) that represents one large job to two smaller jobs

NOTE: don't turn this into a class, you'll run into strange pickling errors


def plot_indices(mis, dims=None, weights=None, groups=<NUM_LIT:1>,legend = True,index_labels=None, colors = None,axis_labels = None,size_exponent=<NUM_LIT:0.1>,ax=None):

if weights is None:<EOL><INDENT>weights = {mi: <NUM_LIT:1> for mi in mis}<EOL><DEDENT>if Function.valid(weights):<EOL><INDENT>weights = {mi:weights(mi) for mi in mis}<EOL><DEDENT>values = list(weights.values())<EOL>if Integer.valid(groups):<EOL><INDENT>N_g = groups<EOL>groups = [[mi for mi in mis if (weights[mi] > np.percentile(values, <NUM_LIT:100>/groups*g) or g==<NUM_LIT:0>) and weights[mi] <= np.percentile(values, <NUM_LIT:100>/groups*(g+<NUM_LIT:1>))] for g in range(N_g)]<EOL>group_names = ['<STR_LIT>'.format(<NUM_LIT:100>/N_g*(N_g-i-<NUM_LIT:1>),<NUM_LIT:100>/N_g*(N_g-i)) for i in reversed(range(N_g))]<EOL><DEDENT>else:<EOL><INDENT>if Function.valid(groups):<EOL><INDENT>groups = {mi:groups(mi) for mi in mis}<EOL><DEDENT>group_names = unique(list(groups.values()))<EOL>groups = [[mi for mi in mis if groups[mi]==name] for name in group_names]<EOL>N_g = len(group_names)<EOL><DEDENT>if colors is None: <EOL><INDENT>colors = matplotlib.cm.rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, N_g))  <EOL><DEDENT>if Dict.valid(mis):<EOL><INDENT>if index_labels is None or weights is None:<EOL><INDENT>temp = list(mis.keys())<EOL>if (List|Tuple).valid(temp[<NUM_LIT:0>]):<EOL><INDENT>if not (index_labels is None and weights is None):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>weights = {mi:mis[mi][<NUM_LIT:0>] for mi in mis}<EOL>index_labels=  {mi:mis[mi][<NUM_LIT:1>] for mi in mis}<EOL><DEDENT>else:<EOL><INDENT>if weights is None:<EOL><INDENT>weights = mis<EOL><DEDENT>else:<EOL><INDENT>index_labels = mis<EOL><DEDENT><DEDENT>mis = temp<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if dims is None:<EOL><INDENT>try:<EOL><INDENT>dims = len(mis[<NUM_LIT:0>])<EOL><DEDENT>except TypeError:<EOL><INDENT>dims = sorted(list(set.union(*(set(mi.active_dims()) for mi in mis))))   <EOL><DEDENT><DEDENT>if len(dims) > <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(dims) < <NUM_LIT:1>:<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL>return<EOL><DEDENT>if ax is None:<EOL><INDENT>fig = plt.figure() <EOL>if len(dims) == <NUM_LIT:3>:<EOL><INDENT>ax = fig.gca(projection='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>ax = fig.gca()<EOL><DEDENT><DEDENT>size_function = lambda mi: sum([weights[mi2] for mi2 in mis if mi.equal_mod(mi2, lambda dim: dim not in dims)]) <EOL>sizes = {mi: np.power(size_function(mi), size_exponent) for mi in mis}<EOL>for i,plot_indices in enumerate(groups):<EOL><INDENT>X = np.array([mi[dims[<NUM_LIT:0>]] for mi in plot_indices])<EOL>if len(dims) > <NUM_LIT:1>:<EOL><INDENT>Y = np.array([mi[dims[<NUM_LIT:1>]] for mi in plot_indices])<EOL><DEDENT>else:<EOL><INDENT>Y = np.array([<NUM_LIT:0> for mi in plot_indices])<EOL><DEDENT>if len(dims) > <NUM_LIT:2>:<EOL><INDENT>Z = np.array([mi[dims[<NUM_LIT:2>]] for mi in plot_indices])<EOL><DEDENT>else:<EOL><INDENT>Z = np.array([<NUM_LIT:0> for mi in plot_indices])   <EOL><DEDENT>sizes_plot = np.array([sizes[mi] for mi in plot_indices])<EOL>if weights:<EOL><INDENT>if len(dims) == <NUM_LIT:3>:<EOL><INDENT>ax.scatter(X, Y, Z, s = <NUM_LIT:50> * sizes_plot / max(sizes.values()), color=colors[i], alpha=<NUM_LIT:1>)            <EOL><DEDENT>else:<EOL><INDENT>ax.scatter(X, Y, s = <NUM_LIT:50> * sizes_plot / max(sizes.values()), color=colors[i], alpha=<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if len(dims) == <NUM_LIT:3>:<EOL><INDENT>ax.scatter(X, Y, Z,color = colors[i],alpha=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>ax.scatter(X, Y,color=colors[i],alpha=<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if True:<EOL><INDENT>if len(dims)==<NUM_LIT:3>:<EOL><INDENT>axs='<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>axs='<STR_LIT>'<EOL><DEDENT>extents = np.array([getattr(ax, '<STR_LIT>'.format(dim))() for dim in axs])<EOL>sz = extents[:,<NUM_LIT:1>] - extents[:,<NUM_LIT:0>]<EOL>maxsize = max(abs(sz))<EOL>for dim in axs:<EOL><INDENT>getattr(ax, '<STR_LIT>'.format(dim))(<NUM_LIT:0>, maxsize)<EOL><DEDENT><DEDENT><DEDENT>if axis_labels is not None:<EOL><INDENT>ax.set_xlabel(axis_labels[<NUM_LIT:0>])<EOL>if len(dims)><NUM_LIT:1>:<EOL><INDENT>ax.set_ylabel(axis_labels[<NUM_LIT:1>])<EOL><DEDENT>if len(dims)><NUM_LIT:1>:<EOL><INDENT>ax.set_zlabel(axis_labels[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ax.set_xlabel('<STR_LIT>' + str(dims[<NUM_LIT:0>])+'<STR_LIT:$>',size=<NUM_LIT:20>)<EOL>if len(dims) > <NUM_LIT:1>:<EOL><INDENT>ax.set_ylabel('<STR_LIT>' + str(dims[<NUM_LIT:1>])+'<STR_LIT:$>',size=<NUM_LIT:20>)<EOL><DEDENT>if len(dims) > <NUM_LIT:2>:<EOL><INDENT>ax.set_zlabel('<STR_LIT>' + str(dims[<NUM_LIT:2>])+'<STR_LIT:$>',size=<NUM_LIT:20>)<EOL><DEDENT>plt.grid()<EOL><DEDENT>x_coordinates = [mi[dims[<NUM_LIT:0>]] for mi in mis]<EOL>xticks=list(range(min(x_coordinates),max(x_coordinates)+<NUM_LIT:1>))<EOL>ax.set_xticks(xticks)<EOL>if len(dims)><NUM_LIT:1>:<EOL><INDENT>y_coordinates = [mi[dims[<NUM_LIT:1>]] for mi in mis]<EOL>ax.set_yticks(list(range(min(y_coordinates),max(y_coordinates)+<NUM_LIT:1>)))<EOL><DEDENT>if len(dims)><NUM_LIT:2>:<EOL><INDENT>z_coordinates = [mi[dims[<NUM_LIT:2>]] for mi in mis]<EOL>ax.set_zticks(list(range(min(z_coordinates),max(z_coordinates)+<NUM_LIT:1>)))<EOL><DEDENT>if index_labels:<EOL><INDENT>for mi in index_labels:<EOL><INDENT>ax.annotate('<STR_LIT>'.format(index_labels[mi]),xy=(mi[<NUM_LIT:0>],mi[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>if legend and len(group_names)><NUM_LIT:1>:<EOL><INDENT>ax.legend([patches.Patch(color=color) for color in np.flipud(colors)],group_names)<EOL><DEDENT>return ax<EOL>

Plot multi-index set

:param mis: Multi-index set
:type mis: Iterable of SparseIndices
:param dims: Which dimensions to use for plotting
:type dims: List of integers.
:param weights: Weights associated with each multi-index
:type weights: Dictionary
:param quantiles: Number of groups plotted in different colors
:type quantiles: Integer>=1 or list of colors

TODO: exchange index_labels and dims, exchange quantiles and dims


fig = plt.figure()<EOL>ax = Axes3D(fig)<EOL>light = LightSource(<NUM_LIT>, <NUM_LIT>)<EOL>illuminated_surface = light.shade(Z, cmap=cm.coolwarm)  <EOL>Xmin = np.amin(X)<EOL>Xmax = np.amax(X)<EOL>Ymin = np.amin(Y)<EOL>Ymax = np.amax(Y)<EOL>Zmin = np.amin(Z)<EOL>Zmax = np.amax(Z)<EOL>ax.contourf(X, Y, Z, zdir='<STR_LIT:x>', offset=Xmin - <NUM_LIT:0.1> * (Xmax - Xmin), cmap=cm.coolwarm, alpha=<NUM_LIT:1>)  <EOL>ax.contourf(X, Y, Z, zdir='<STR_LIT:y>', offset=Ymax + <NUM_LIT:0.1> * (Ymax - Ymin), cmap=cm.coolwarm, alpha=<NUM_LIT:1>)  <EOL>ax.contourf(X, Y, Z, zdir='<STR_LIT:z>', offset=Zmin - <NUM_LIT:0.1> * (Zmax - Zmin), cmap=cm.coolwarm, alpha=<NUM_LIT:1>)  <EOL>ax.plot_surface(X, Y, Z, cstride=<NUM_LIT:5>, rstride=<NUM_LIT:5>, facecolors=illuminated_surface, alpha=<NUM_LIT:0.5>)<EOL>plt.show()<EOL>

Surface plot.

Generate X and Y using, for example
      X,Y = np.mgrid[0:1:50j, 0:1:50j]
    or
      X,Y= np.meshgrid([0,1,2],[1,2,3]).

:param X: 2D-Array of x-coordinates
:param Y: 2D-Array of y-coordinates
:param Z: 2D-Array of z-coordinates


def wrapper(*args,**kwargs):  <EOL><INDENT>pr=cProfile.Profile()<EOL>pr.enable()<EOL>output = function(*args,**kwargs)<EOL>pr.disable()<EOL>return pr,output<EOL><DEDENT>return wrapper<EOL>

Decorator that adds a runtime profile object to the output


import memory_profiler<EOL>def wrapper(*args,**kwargs):<EOL><INDENT>m = StringIO()<EOL>temp_func = memory_profiler.profile(func = function,stream=m,precision=<NUM_LIT:4>)<EOL>output = temp_func(*args,**kwargs)<EOL>print(m.getvalue())<EOL>m.close()<EOL>return output<EOL><DEDENT>return wrapper<EOL>

Decorator that prints memory information at each call of the function


def wrapper(*args,**kwargs):<EOL><INDENT>pr=cProfile.Profile()<EOL>pr.enable()<EOL>output = function(*args,**kwargs)<EOL>pr.disable()<EOL>ps = pstats.Stats(pr)<EOL>ps.sort_stats('<STR_LIT>').print_stats(<NUM_LIT:20>)<EOL>return output<EOL><DEDENT>return wrapper<EOL>

Decorator that prints running time information at each call of the function


def wrapper(self,*args,**kwargs):  <EOL><INDENT>self.log.log(group=function.__name__,message='<STR_LIT>') <EOL>function(self,*args,**kwargs)<EOL>self.log.log(group=function.__name__,message='<STR_LIT>') <EOL><DEDENT>return wrapper<EOL>

Decorator that logs function calls in their self.log


import memory_profiler<EOL>def wrapper(*args,**kwargs):<EOL><INDENT>m=StringIO()<EOL>pr=cProfile.Profile()<EOL>pr.enable()<EOL>temp_func = memory_profiler.profile(func=function,stream=m,precision=<NUM_LIT:4>)<EOL>output = temp_func(*args,**kwargs)<EOL>print(m.getvalue())<EOL>pr.disable()<EOL>ps = pstats.Stats(pr)<EOL>ps.sort_stats('<STR_LIT>').print_stats('<STR_LIT>',<NUM_LIT:20>)<EOL>m.close()<EOL>return output<EOL><DEDENT>return wrapper<EOL>

Decorator that prints memory and runtime information at each call of the function


function,name=_strip_function(function)<EOL>if not function.__code__.co_code in [empty_function.__code__.co_code, doc_string_only_function.__code__.co_code]: <EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>def not_implemented_function(*args,**kwargs):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(args[<NUM_LIT:0>],name))<EOL><DEDENT>not_implemented_function.__qualname__=not_implemented_function.__name__ <EOL>return default(not_implemented_function,name=name)<EOL>

Declare abstract function.

Requires function to be empty except for docstring describing semantics.
To apply function, first argument must come with implementation of semantics.


npmode = isinstance(l,np.ndarray)<EOL>if npmode:<EOL><INDENT>l=list(l)<EOL><DEDENT>g=np.concatenate((np.array([<NUM_LIT:0>]),np.cumsum(split_integer(len(l),length=N))))<EOL>s=[l[g[i]:g[i+<NUM_LIT:1>]] for i in range(N)]<EOL>if npmode:<EOL><INDENT>s=[np.array(sl) for sl in s]<EOL><DEDENT>return s<EOL>


return shutil.which(cmd) is not None<EOL>

Check whether given command is available on system


def random_word(length,dictionary = False):

if dictionary:<EOL><INDENT>try:<EOL><INDENT>with open('<STR_LIT>') as fp:<EOL><INDENT>words = [word.lower()[:-<NUM_LIT:1>] for word in fp.readlines() if re.match('<STR_LIT>'.format('<STR_LIT:{>'+str(length)+'<STR_LIT:}>'),word)]<EOL><DEDENT>return random.choice(words)<EOL><DEDENT>except FileNotFoundError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>vowels = list('<STR_LIT>')<EOL>consonants = list('<STR_LIT>')<EOL>pairs = [(random.choice(consonants),random.choice(vowels)) for _ in range(length//<NUM_LIT:2>+<NUM_LIT:1>)] <EOL>return '<STR_LIT>'.join([l for p in pairs for l in p])[:length]<EOL>

Creates random lowercase words from dictionary or by alternating vowels and consonants

The second method chooses from 85**length words.
The dictionary method chooses from 3000--12000 words for 3<=length<=12
(though this of course depends on the available dictionary)

:param length: word length
:param dictionary: Try reading from dictionary, else fall back to artificial words


if ld:<EOL><INDENT>keys = list(ld[<NUM_LIT:0>])<EOL>dl = {key:[d[key] for d in ld] for key in keys}<EOL>return dl<EOL><DEDENT>else:<EOL><INDENT>return {}<EOL><DEDENT>

Convert list of dictionaries to dictionary of lists


if len(args)==<NUM_LIT:1>:<EOL><INDENT>string_input = True<EOL>string = args[<NUM_LIT:0>].replace('<STR_LIT:U+0020>','<STR_LIT>')<EOL>original_args=string.split('<STR_LIT:U+002C>')<EOL>args = []<EOL>for arg in original_args:<EOL><INDENT>try:<EOL><INDENT>args.append(ast.literal_eval(arg))<EOL><DEDENT>except (ValueError,SyntaxError):<EOL><INDENT>try:<EOL><INDENT>args.append(eval(arg,{'<STR_LIT>':{}}))<EOL><DEDENT>except (NameError,SyntaxError):<EOL><INDENT>args.append(arg)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>string_input = False<EOL><DEDENT>arg_start = args[<NUM_LIT:0>]<EOL>if len(args)><NUM_LIT:2>:<EOL><INDENT>arg_step = args[<NUM_LIT:1>]<EOL>if len(args)><NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>arg_step = None<EOL><DEDENT>arg_end = args[-<NUM_LIT:1>]<EOL>if String.valid(arg_start) and len(arg_start)==<NUM_LIT:1>:<EOL><INDENT>range_type = '<STR_LIT>'<EOL><DEDENT>elif all(Integer.valid(arg) for arg in args):<EOL><INDENT>range_type = '<STR_LIT>'<EOL><DEDENT>else: <EOL><INDENT>if string_input and original_args[<NUM_LIT:0>][<NUM_LIT:0>] in ['<STR_LIT:(>','<STR_LIT:[>']:<EOL><INDENT>range_type = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>range_type = '<STR_LIT:float>'<EOL><DEDENT><DEDENT>if range_type == '<STR_LIT>':<EOL><INDENT>start = ord(arg_start)<EOL>step = (ord(arg_step)- start) if arg_step else <NUM_LIT:1><EOL>end = ord(arg_end)<EOL>out = [chr(i) for i in range(start,end+step,step)]<EOL>if np.sign(step)*(ord(out[-<NUM_LIT:1>])-end)><NUM_LIT:0>:<EOL><INDENT>del out[-<NUM_LIT:1>]<EOL><DEDENT>return out<EOL><DEDENT>elif range_type == '<STR_LIT>':<EOL><INDENT>if string_input:<EOL><INDENT>if len(args)==<NUM_LIT:2> and all('<STR_LIT>' in oa for oa in original_args):<EOL><INDENT>bases,exponents = zip(*[oa.split('<STR_LIT>') for oa in original_args])<EOL>if len(set(bases))==<NUM_LIT:1>:<EOL><INDENT>return [int(bases[<NUM_LIT:0>])**exponent for exponent in smart_range('<STR_LIT:U+002C>'.join(exponents))]<EOL><DEDENT><DEDENT><DEDENT>start = arg_start<EOL>step = (arg_step - arg_start) if arg_step is not None else <NUM_LIT:1><EOL>end = arg_end<EOL>out = list(range(start,end+step,step))<EOL>if np.sign(step)*(out[-<NUM_LIT:1>]-end)><NUM_LIT:0>:<EOL><INDENT>del out[-<NUM_LIT:1>]<EOL><DEDENT>return out<EOL><DEDENT>elif range_type == '<STR_LIT:float>':<EOL><INDENT>if len(args)==<NUM_LIT:2> and all('<STR_LIT>' in oa for oa in original_args):<EOL><INDENT>bases,exponents = zip(*[oa.split('<STR_LIT>') for oa in original_args])<EOL>if len(set(bases))==<NUM_LIT:1>:<EOL><INDENT>return [float(bases[<NUM_LIT:0>])**exponent for exponent in smart_range('<STR_LIT:U+002C>'.join(exponents)) ]<EOL><DEDENT><DEDENT>if len(args) == <NUM_LIT:2>:<EOL><INDENT>raise ValueError()<EOL><DEDENT>start = arg_start<EOL>step = arg_step - arg_start<EOL>end = arg_end<EOL>out = list(np.arange(start,end+<NUM_LIT>*step,step))<EOL>return out<EOL><DEDENT>elif range_type == '<STR_LIT>':<EOL><INDENT>lopen,start = (original_args[<NUM_LIT:0>][<NUM_LIT:0>]=='<STR_LIT:(>'),float(original_args[<NUM_LIT:0>][<NUM_LIT:1>:])<EOL>end,N = original_args[<NUM_LIT:1>].split('<STR_LIT:/>')<EOL>end,ropen = float(end[:-<NUM_LIT:1>]),(end[-<NUM_LIT:1>]=='<STR_LIT:)>')<EOL>N = ast.literal_eval(N)+lopen +ropen<EOL>points = np.linspace(start,end,num=N)<EOL>return points[lopen:len(points)-ropen]<EOL><DEDENT>


td = str(timedelta(seconds = seconds))<EOL>parts = td.split('<STR_LIT:.>')<EOL>if len(parts) == <NUM_LIT:1>:<EOL><INDENT>td = td+'<STR_LIT>'<EOL><DEDENT>elif len(parts) == <NUM_LIT:2>:<EOL><INDENT>td = '<STR_LIT:.>'.join([parts[<NUM_LIT:0>],parts[<NUM_LIT:1>][:<NUM_LIT:2>]])<EOL><DEDENT>return td<EOL>

Converts seconds into elapsed time string of form

(X days(s)?,)? HH:MM:SS.YY


<EOL>ts_range = self.value(max(sequence)) - self.value(min(sequence))<EOL>package = self.determine_package(sequence[<NUM_LIT:0>])<EOL>if package == '<STR_LIT>':<EOL><INDENT>cuts = [<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT>, '<STR_LIT:s>'),<EOL>(<NUM_LIT:9>, '<STR_LIT:m>'),<EOL>(<NUM_LIT:6>, '<STR_LIT:h>'),<EOL>(<NUM_LIT:4>, '<STR_LIT:d>'),<EOL>(<NUM_LIT:4>, '<STR_LIT:w>'),<EOL>(<NUM_LIT:4>, '<STR_LIT:M>'),<EOL>(<NUM_LIT:3>, '<STR_LIT:y>')]<EOL>denomination = NANOSECONDS<EOL>base_units = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>cuts = [<EOL>(<NUM_LIT>, '<STR_LIT:s>'),<EOL>(<NUM_LIT:9>, '<STR_LIT:m>'),<EOL>(<NUM_LIT:6>, '<STR_LIT:h>'),<EOL>(<NUM_LIT:4>, '<STR_LIT:d>'),<EOL>(<NUM_LIT:4>, '<STR_LIT:w>'),<EOL>(<NUM_LIT:4>, '<STR_LIT:M>'),<EOL>(<NUM_LIT:3>, '<STR_LIT:y>')]<EOL>denomination = SECONDS<EOL>base_units = '<STR_LIT>'<EOL><DEDENT>for size, units in reversed(cuts):<EOL><INDENT>if ts_range >= size*denomination[units]:<EOL><INDENT>return units<EOL><DEDENT><DEDENT>return base_units<EOL>

Determine good units for representing a sequence of timedeltas


def __call__(self, major, limits=None, n=None):

if not self.trans.dataspace_is_numerical:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if limits is None:<EOL><INDENT>limits = min_max(major)<EOL><DEDENT>if n is None:<EOL><INDENT>n = self.n<EOL><DEDENT>major = self._extend_breaks(major)<EOL>major = self.trans.inverse(major)<EOL>limits = self.trans.inverse(limits)<EOL>minor = minor_breaks(n)(major, limits)<EOL>return self.trans.transform(minor)<EOL>

Minor breaks for transformed scales

Parameters
----------
major : array_like
    Major breaks
limits : array_like | None
    Limits of the scale. If *array_like*, must be
    of size 2. If **None**, then the minimum and
    maximum of the major breaks are used.
n : int
    Number of minor breaks between the major
    breaks. If **None**, then *self.n* is used.

Returns
-------
out : array_like
    Minor breaks


Q = self.Q<EOL>w = self.w<EOL>only_inside = self.only_inside<EOL>simplicity_max = self.simplicity_max<EOL>density_max = self.density_max<EOL>coverage_max = self.coverage_max<EOL>simplicity = self.simplicity<EOL>coverage = self.coverage<EOL>density = self.density<EOL>legibility = self.legibility<EOL>log10 = np.log10<EOL>ceil = np.ceil<EOL>floor = np.floor<EOL>dmin, dmax = limits<EOL>if dmin > dmax:<EOL><INDENT>dmin, dmax = dmax, dmin<EOL><DEDENT>elif dmin == dmax:<EOL><INDENT>return np.array([dmin])<EOL><DEDENT>best_score = -<NUM_LIT:2><EOL>j = <NUM_LIT:1><EOL>while j < float('<STR_LIT>'):<EOL><INDENT>for q in Q:<EOL><INDENT>sm = simplicity_max(q, j)<EOL>if w[<NUM_LIT:0>]*sm + w[<NUM_LIT:1>] + w[<NUM_LIT:2>] + w[<NUM_LIT:3>] < best_score:<EOL><INDENT>j = float('<STR_LIT>')<EOL>break<EOL><DEDENT>k = <NUM_LIT:2><EOL>while k < float('<STR_LIT>'):<EOL><INDENT>dm = density_max(k)<EOL>if w[<NUM_LIT:0>]*sm + w[<NUM_LIT:1>] + w[<NUM_LIT:2>]*dm + w[<NUM_LIT:3>] < best_score:<EOL><INDENT>break<EOL><DEDENT>delta = (dmax-dmin)/(k+<NUM_LIT:1>)/j/q<EOL>z = ceil(log10(delta))<EOL>while z < float('<STR_LIT>'):<EOL><INDENT>step = j*q*(<NUM_LIT:10>**z)<EOL>cm = coverage_max(dmin, dmax, step*(k-<NUM_LIT:1>))<EOL>if w[<NUM_LIT:0>]*sm + w[<NUM_LIT:1>]*cm + w[<NUM_LIT:2>]*dm + w[<NUM_LIT:3>] < best_score:<EOL><INDENT>break<EOL><DEDENT>min_start = int(floor(dmax/step)*j - (k-<NUM_LIT:1>)*j)<EOL>max_start = int(ceil(dmin/step)*j)<EOL>if min_start > max_start:<EOL><INDENT>z = z+<NUM_LIT:1><EOL>break<EOL><DEDENT>for start in range(min_start, max_start+<NUM_LIT:1>):<EOL><INDENT>lmin = start * (step/j)<EOL>lmax = lmin + step*(k-<NUM_LIT:1>)<EOL>lstep = step<EOL>s = simplicity(q, j, lmin, lmax, lstep)<EOL>c = coverage(dmin, dmax, lmin, lmax)<EOL>d = density(k, dmin, dmax, lmin, lmax)<EOL>l = legibility(lmin, lmax, lstep)<EOL>score = w[<NUM_LIT:0>]*s + w[<NUM_LIT:1>]*c + w[<NUM_LIT:2>]*d + w[<NUM_LIT:3>]*l<EOL>if (score > best_score and<EOL>(not only_inside or<EOL>(lmin >= dmin and lmax <= dmax))):<EOL><INDENT>best_score = score<EOL>best = (lmin, lmax, lstep, q, k)<EOL><DEDENT><DEDENT>z = z+<NUM_LIT:1><EOL><DEDENT>k = k+<NUM_LIT:1><EOL><DEDENT><DEDENT>j = j+<NUM_LIT:1><EOL><DEDENT>try:<EOL><INDENT>locs = best[<NUM_LIT:0>] + np.arange(best[<NUM_LIT:4>])*best[<NUM_LIT:2>]<EOL><DEDENT>except UnboundLocalError:<EOL><INDENT>locs = []<EOL><DEDENT>return locs<EOL>

Calculate the breaks

Parameters
----------
limits : array
    Minimum and maximum values.

Returns
-------
out : array_like
    Sequence of break points.


if self.package == '<STR_LIT>':<EOL><INDENT>return td.value<EOL><DEDENT>else:<EOL><INDENT>return td.total_seconds()<EOL><DEDENT>

Return the numeric value representation on a timedelta


def rescale(x, to=(<NUM_LIT:0>, <NUM_LIT:1>), _from=None):

if _from is None:<EOL><INDENT>_from = np.min(x), np.max(x)<EOL><DEDENT>return np.interp(x, _from, to)<EOL>

Rescale numeric vector to have specified minimum and maximum.

Parameters
----------
x : array_like | numeric
    1D vector of values to manipulate.
to : tuple
    output range (numeric vector of length two)
_from : tuple
    input range (numeric vector of length two).
    If not given, is calculated from the range of x

Returns
-------
out : array_like
    Rescaled values

Examples
--------
>>> x = [0, 2, 4, 6, 8, 10]
>>> rescale(x)
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
>>> rescale(x, to=(0, 2))
array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])
>>> rescale(x, to=(0, 2), _from=(0, 20))
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])


def expand_range_distinct(range, expand=(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>), zero_width=<NUM_LIT:1>):

if len(expand) == <NUM_LIT:2>:<EOL><INDENT>expand = tuple(expand) * <NUM_LIT:2><EOL><DEDENT>lower = expand_range(range, expand[<NUM_LIT:0>], expand[<NUM_LIT:1>], zero_width)[<NUM_LIT:0>]<EOL>upper = expand_range(range, expand[<NUM_LIT:2>], expand[<NUM_LIT:3>], zero_width)[<NUM_LIT:1>]<EOL>return (lower, upper)<EOL>

Expand a range with a multiplicative or additive constants

Similar to :func:`expand_range` but both sides of the range
expanded using different constants

Parameters
----------
range : tuple
    Range of data. Size 2
expand : tuple
    Length 2 or 4. If length is 2, then the same constants
    are used for both sides. If length is 4 then the first
    two are are the Multiplicative (*mul*) and Additive (*add*)
    constants for the lower limit, and the second two are
    the constants for the upper limit.
zero_width : int | float | timedelta
    Distance to use if range has zero width

Returns
-------
out : tuple
    Expanded range

Examples
--------
>>> expand_range_distinct((3, 8))
(3, 8)
>>> expand_range_distinct((0, 10), (0.1, 0))
(-1.0, 11.0)
>>> expand_range_distinct((0, 10), (0.1, 0, 0.1, 0))
(-1.0, 11.0)
>>> expand_range_distinct((0, 10), (0.1, 0, 0, 0))
(-1.0, 10)
>>> expand_range_distinct((0, 10), (0, 2))
(-2, 12)
>>> expand_range_distinct((0, 10), (0, 2, 0, 2))
(-2, 12)
>>> expand_range_distinct((0, 10), (0, 0, 0, 2))
(0, 12)
>>> expand_range_distinct((0, 10), (.1, 2))
(-3.0, 13.0)
>>> expand_range_distinct((0, 10), (.1, 2, .1, 2))
(-3.0, 13.0)
>>> expand_range_distinct((0, 10), (0, 0, .1, 2))
(0, 13.0)


def squish_infinite(x, range=(<NUM_LIT:0>, <NUM_LIT:1>)):

xtype = type(x)<EOL>if not hasattr(x, '<STR_LIT>'):<EOL><INDENT>x = np.asarray(x)<EOL><DEDENT>x[x == -np.inf] = range[<NUM_LIT:0>]<EOL>x[x == np.inf] = range[<NUM_LIT:1>]<EOL>if not isinstance(x, xtype):<EOL><INDENT>x = xtype(x)<EOL><DEDENT>return x<EOL>

Truncate infinite values to a range.

Parameters
----------
x : array_like
    Values that should have infinities squished.
range : tuple
    The range onto which to squish the infinites.
    Must be of size 2.

Returns
-------
out : array_like
    Values with infinites squished.

Examples
--------
>>> squish_infinite([0, .5, .25, np.inf, .44])
[0.0, 0.5, 0.25, 1.0, 0.44]
>>> squish_infinite([0, -np.inf, .5, .25, np.inf], (-10, 9))
[0.0, -10.0, 0.5, 0.25, 9.0]


def squish(x, range=(<NUM_LIT:0>, <NUM_LIT:1>), only_finite=True):

xtype = type(x)<EOL>if not hasattr(x, '<STR_LIT>'):<EOL><INDENT>x = np.asarray(x)<EOL><DEDENT>finite = np.isfinite(x) if only_finite else True<EOL>x[np.logical_and(x < range[<NUM_LIT:0>], finite)] = range[<NUM_LIT:0>]<EOL>x[np.logical_and(x > range[<NUM_LIT:1>], finite)] = range[<NUM_LIT:1>]<EOL>if not isinstance(x, xtype):<EOL><INDENT>x = xtype(x)<EOL><DEDENT>return x<EOL>

Squish values into range.

Parameters
----------
x : array_like
    Values that should have out of range values squished.
range : tuple
    The range onto which to squish the values.
only_finite: boolean
    When true, only squishes finite values.

Returns
-------
out : array_like
    Values with out of range values squished.

Examples
--------
>>> squish([-1.5, 0.2, 0.5, 0.8, 1.0, 1.2])
[0.0, 0.2, 0.5, 0.8, 1.0, 1.0]

>>> squish([-np.inf, -1.5, 0.2, 0.5, 0.8, 1.0, np.inf], only_finite=False)
[0.0, 0.0, 0.2, 0.5, 0.8, 1.0, 1.0]


return num2date(x)<EOL>


obj = t<EOL>if isinstance(obj, str):<EOL><INDENT>name = '<STR_LIT>'.format(obj)<EOL>obj = globals()[name]()<EOL><DEDENT>if callable(obj):<EOL><INDENT>obj = obj()<EOL><DEDENT>if isinstance(obj, type):<EOL><INDENT>obj = obj()<EOL><DEDENT>if not isinstance(obj, trans):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return obj<EOL>

Return a trans object

Parameters
----------
t : str | callable | type | trans
    name of transformation function

Returns
-------
out : trans


<EOL>try:<EOL><INDENT>x = np.array([_x.total_seconds()*<NUM_LIT:10>**<NUM_LIT:6> for _x in x])<EOL><DEDENT>except TypeError:<EOL><INDENT>x = x.total_seconds()*<NUM_LIT:10>**<NUM_LIT:6><EOL><DEDENT>return x<EOL>

Transform from Timeddelta to numerical format


<EOL>if base is None:<EOL><INDENT>name = '<STR_LIT>'<EOL>base = np.exp(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>name = '<STR_LIT>'.format(base)<EOL><DEDENT>def transform(x):<EOL><INDENT>return base ** x<EOL><DEDENT>def inverse(x):<EOL><INDENT>return np.log(x)/np.log(base)<EOL><DEDENT>kwargs['<STR_LIT>'] = base<EOL>return trans_new(name, transform, inverse, **kwargs)<EOL>

Create a exponential transform class for *base*

This is inverse of the log transform.

Parameters
----------
base : float
    Base of the logarithm
kwargs : dict
    Keyword arguments passed onto
    :func:`trans_new`. Should not include
    the `transform` or `inverse`.

Returns
-------
out : type
    Exponential transform class


@classmethod<EOL><INDENT>def train(cls, new_data, old=None):<DEDENT>

if not len(new_data):<EOL><INDENT>return old<EOL><DEDENT>if not hasattr(new_data, '<STR_LIT>'):<EOL><INDENT>new_data = np.asarray(new_data)<EOL><DEDENT>if new_data.dtype.kind not in CONTINUOUS_KINDS:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>if old is not None:<EOL><INDENT>new_data = np.hstack([new_data, old])<EOL><DEDENT>return min_max(new_data, na_rm=True, finite=True)<EOL>

Train a continuous scale

Parameters
----------
new_data : array_like
    New values
old : array_like
    Old range. Most likely a tuple of length 2.

Returns
-------
out : tuple
    Limits(range) of the scale


@classmethod<EOL><INDENT>def apply(cls, x, palette, na_value=None):<DEDENT>

limits = cls.train(x)<EOL>return cls.map(x, palette, limits, na_value)<EOL>

Scale data discretely

Parameters
----------
x : array_like
    Discrete values to scale
palette : callable ``f(x)``
    Palette to use
na_value : object
    Value to use for missing values.

Returns
-------
out : array_like
    Scaled values


@classmethod<EOL><INDENT>def map(cls, x, palette, limits, na_value=None, oob=censor):<DEDENT>

x = oob(rescale(x, _from=limits))<EOL>pal = palette(x)<EOL>try:<EOL><INDENT>pal[pd.isnull(x)] = na_value<EOL><DEDENT>except TypeError:<EOL><INDENT>pal = [v if not pd.isnull(v) else na_value for v in pal]<EOL><DEDENT>return pal<EOL>

Map values to a continuous palette

Parameters
----------
x : array_like
    Continuous values to scale
palette : callable ``f(x)``
    palette to use
na_value : object
    Value to use for missing values.
oob : callable ``f(x)``
    Function to deal with values that are
    beyond the limits

Returns
-------
out : array_like
    Values mapped onto a palette


@classmethod<EOL><INDENT>def apply(cls, x, palette, na_value=None, trans=None):<DEDENT>

if trans is not None:<EOL><INDENT>x = trans.transform(x)<EOL><DEDENT>limits = cls.train(x)<EOL>return cls.map(x, palette, limits, na_value)<EOL>

Scale data continuously

Parameters
----------
x : array_like
    Continuous values to scale
palette : callable ``f(x)``
    Palette to use
na_value : object
    Value to use for missing values.
trans : trans
    How to transform the data before scaling. If
    ``None``, no transformation is done.

Returns
-------
out : array_like
    Scaled values


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>

Render the given version pieces into the requested style.


<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information or return default if unable to do so.


<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>

Get the keywords needed to look up the version information.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):

if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information from git keywords.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


def remove_zeroes(s):<EOL><INDENT>"""<STR_LIT>"""<EOL>tup = s.split('<STR_LIT:e>')<EOL>if len(tup) == <NUM_LIT:2>:<EOL><INDENT>mantissa = tup[<NUM_LIT:0>].rstrip('<STR_LIT:0>').rstrip('<STR_LIT:.>')<EOL>exponent = int(tup[<NUM_LIT:1>])<EOL>if exponent:<EOL><INDENT>s = '<STR_LIT>' % (mantissa, exponent)<EOL><DEDENT>else:<EOL><INDENT>s = mantissa<EOL><DEDENT><DEDENT>return s<EOL><DEDENT>def as_exp(s):<EOL><INDENT>"""<STR_LIT>"""<EOL>return s if '<STR_LIT:e>' in s else '<STR_LIT>'.format(float(s))<EOL><DEDENT>has_e = np.array(['<STR_LIT:e>' in x for x in labels])<EOL>if not np.all(has_e) and not np.all(~has_e):<EOL><INDENT>labels = [as_exp(x) for x in labels]<EOL><DEDENT>labels = [remove_zeroes(x) for x in labels]<EOL>return labels<EOL>

Make all labels uniform in format and remove redundant zeros
for labels in exponential format.

Parameters
----------
labels : list-like
    Labels to be tidied.

Returns
-------
out : list-like
    Labels


if self.style == '<STR_LIT>':<EOL><INDENT>return [self.fmt.format(val) for val in x]<EOL><DEDENT>elif self.style == '<STR_LIT>':<EOL><INDENT>return [self.fmt % val for val in x]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>

Format a sequence of inputs

Parameters
----------
x : array
    Input

Returns
-------
out : list
    List of strings.


if len(x) == <NUM_LIT:0>:<EOL><INDENT>return []<EOL><DEDENT>if self.base == <NUM_LIT:10>:<EOL><INDENT>xmin = int(np.floor(np.log10(np.min(x))))<EOL>xmax = int(np.ceil(np.log10(np.max(x))))<EOL>emin, emax = self.exponent_limits<EOL>all_multiples = np.all(<EOL>[np.log10(num).is_integer() for num in x])<EOL>if same_log10_order_of_magnitude(x):<EOL><INDENT>f = mpl_format()<EOL>f.formatter.set_powerlimits((emin, emax))<EOL>return f(x)<EOL><DEDENT>elif all_multiples and (xmin <= emin or xmax >= emax):<EOL><INDENT>fmt = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>fmt = '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fmt = '<STR_LIT>'<EOL><DEDENT>labels = [fmt.format(num) for num in x]<EOL>return self._tidyup_labels(labels)<EOL>


if len(x) == <NUM_LIT:0>:<EOL><INDENT>return []<EOL><DEDENT>_precision = precision(x)<EOL>x = round_any(x, _precision / <NUM_LIT:100>) * <NUM_LIT:100><EOL>if _precision > <NUM_LIT:1>:<EOL><INDENT>digits = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>digits = abs(int(np.log10(_precision)))<EOL><DEDENT>formatter = currency_format(prefix='<STR_LIT>',<EOL>suffix='<STR_LIT:%>',<EOL>digits=digits,<EOL>big_mark=self.big_mark)<EOL>labels = formatter(x)<EOL>pattern = re.compile(r'<STR_LIT>')<EOL>if all(pattern.search(val) for val in labels):<EOL><INDENT>labels = [pattern.sub('<STR_LIT:%>', val) for val in labels]<EOL><DEDENT>return labels<EOL>


<EOL>formatter.create_dummy_axis()<EOL>formatter.set_locs([val for val in x if ~np.isnan(val)])<EOL>try:<EOL><INDENT>oom = int(formatter.orderOfMagnitude)<EOL><DEDENT>except AttributeError:<EOL><INDENT>oom = <NUM_LIT:0><EOL><DEDENT>labels = [formatter(tick) for tick in x]<EOL>pattern = re.compile(r'<STR_LIT>')<EOL>for i, label in enumerate(labels):<EOL><INDENT>match = pattern.search(label)<EOL>if match:<EOL><INDENT>labels[i] = pattern.sub('<STR_LIT>', label)<EOL><DEDENT><DEDENT>if oom:<EOL><INDENT>labels = ['<STR_LIT>'.format(s, oom) if s != '<STR_LIT:0>' else s<EOL>for s in labels]<EOL><DEDENT>return labels<EOL>


def min_max(x, na_rm=False, finite=True):

if not hasattr(x, '<STR_LIT>'):<EOL><INDENT>x = np.asarray(x)<EOL><DEDENT>if na_rm and finite:<EOL><INDENT>x = x[np.isfinite(x)]<EOL><DEDENT>elif not na_rm and np.any(np.isnan(x)):<EOL><INDENT>return np.nan, np.nan<EOL><DEDENT>elif na_rm:<EOL><INDENT>x = x[~np.isnan(x)]<EOL><DEDENT>elif finite:<EOL><INDENT>x = x[~np.isinf(x)]<EOL><DEDENT>if (len(x)):<EOL><INDENT>return np.min(x), np.max(x)<EOL><DEDENT>else:<EOL><INDENT>return float('<STR_LIT>'), float('<STR_LIT>')<EOL><DEDENT>

Return the minimum and maximum of x

Parameters
----------
x : array_like
    Sequence
na_rm : bool
    Whether to remove ``nan`` values.
finite : bool
    Whether to consider only finite values.

Returns
-------
out : tuple
    (minimum, maximum) of x


if isinstance(obj, Iterator):<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>")<EOL><DEDENT>return next(iter(obj))<EOL>

Return the first element of `obj`

Parameters
----------
obj : iterable
    Should not be an iterator

Returns
-------
out : object
    First element of `obj`. Raise a class:`StopIteration`
    exception if `obj` is empty.


def match(v1, v2, nomatch=-<NUM_LIT:1>, incomparables=None, start=<NUM_LIT:0>):

v2_indices = {}<EOL>for i, x in enumerate(v2):<EOL><INDENT>if x not in v2_indices:<EOL><INDENT>v2_indices[x] = i<EOL><DEDENT><DEDENT>v1_to_v2_map = [nomatch] * len(v1)<EOL>skip = set(incomparables) if incomparables else set()<EOL>for i, x in enumerate(v1):<EOL><INDENT>if x in skip:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>v1_to_v2_map[i] = v2_indices[x] + start<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return v1_to_v2_map<EOL>

Return a vector of the positions of (first)
matches of its first argument in its second.

Parameters
----------
v1: array_like
    Values to be matched

v2: array_like
    Values to be matched against

nomatch: int
    Value to be returned in the case when
    no match is found.

incomparables: array_like
    Values that cannot be matched. Any value in ``v1``
    matching a value in this list is assigned the nomatch
    value.
start: int
    Type of indexing to use. Most likely 0 or 1


return [crayon_rgb[name] for name in colors]<EOL>

Make a palette with color names from Crayola crayons.

The colors come from
http://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors

Parameters
----------
colors : list of strings
    List of keys in the ``mizani.external.crayloax_rgb`` dictionary.

Returns
-------
palette : list
    List of colors as RGB hex strings.

Examples
--------
>>> palette = crayon_palette(['almond', 'silver', 'yellow'])
>>> palette
['#eed9c4', '#c9c0bb', '#fbe870']

>>> from mizani.external import crayon_rgb
>>> list(sorted(crayon_rgb.keys()))[:5]
['almond', 'antique brass', 'apricot', 'aquamarine', 'asparagus']


def gradient_n_pal(colors, values=None, name='<STR_LIT>'):

<EOL>if values is None:<EOL><INDENT>colormap = mcolors.LinearSegmentedColormap.from_list(<EOL>name, colors)<EOL><DEDENT>else:<EOL><INDENT>colormap = mcolors.LinearSegmentedColormap.from_list(<EOL>name, list(zip(values, colors)))<EOL><DEDENT>def _gradient_n_pal(vals):<EOL><INDENT>return ratios_to_colors(vals, colormap)<EOL><DEDENT>return _gradient_n_pal<EOL>

Create a n color gradient palette

Parameters
----------
colors : list
    list of colors
values : list, optional
    list of points in the range [0, 1] at which to
    place each color. Must be the same size as
    `colors`. Default to evenly space the colors
name : str
    Name to call the resultant MPL colormap

Returns
-------
out : function
    Continuous color palette that takes a single
    parameter either a :class:`float` or a sequence
    of floats maps those value(s) onto the palette
    and returns color(s). The float(s) must be
    in the range [0, 1].

Examples
--------
>>> palette = gradient_n_pal(['red', 'blue'])
>>> palette([0, .25, .5, .75, 1])
['#ff0000', '#bf0040', '#7f0080', '#3f00c0', '#0000ff']


return [xkcd_rgb[name] for name in colors]<EOL>

Make a palette with color names from the xkcd color survey.

See xkcd for the full list of colors: http://xkcd.com/color/rgb/

Parameters
----------
colors : list of strings
    List of keys in the ``mizani.external.xkcd_rgb`` dictionary.

Returns
-------
palette : list
    List of colors as RGB hex strings.

Examples
--------
>>> palette = xkcd_palette(['red', 'green', 'blue'])
>>> palette
['#e50000', '#15b01a', '#0343df']

>>> from mizani.external import xkcd_rgb
>>> list(sorted(xkcd_rgb.keys()))[:5]
['acid green', 'adobe', 'algae', 'algae green', 'almost black']


def hue_pal(h=<NUM_LIT>, l=<NUM_LIT>, s=<NUM_LIT>, color_space='<STR_LIT>'):

if not all([<NUM_LIT:0> <= val <= <NUM_LIT:1> for val in (h, l, s)]):<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>".format(h, l, s))<EOL>raise ValueError(msg)<EOL><DEDENT>if color_space not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>name = '<STR_LIT>'.format(color_space)<EOL>palette = globals()[name]<EOL>def _hue_pal(n):<EOL><INDENT>colors = palette(n, h=h, l=l, s=s)<EOL>return [mcolors.rgb2hex(c) for c in colors]<EOL><DEDENT>return _hue_pal<EOL>

Utility for making hue palettes for color schemes.

Parameters
----------
h : float
    first hue. In the [0, 1] range
l : float
    lightness. In the [0, 1] range
s : float
    saturation. In the [0, 1] range
color_space : 'hls' | 'husl'
    Color space to use for the palette

Returns
-------
out : function
    A discrete color palette that takes a single
    :class:`int` parameter ``n`` and returns ``n``
    equally spaced colors. Though the palette
    is continuous, since it is varies the hue it
    is good for categorical data. However if ``n``
    is large enough the colors show continuity.

Examples
--------
>>> hue_pal()(5)
['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']
>>> hue_pal(color_space='husl')(5)
['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']


max_n = len(values)<EOL>def _manual_pal(n):<EOL><INDENT>if n > max_n:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>warnings.warn(msg.format(max_n, n))<EOL><DEDENT>return values[:n]<EOL><DEDENT>return _manual_pal<EOL>

Create a palette from a list of values

Parameters
----------
values : sequence
    Values that will be returned by the palette function.

Returns
-------
out : function
    A function palette that takes a single
    :class:`int` parameter ``n`` and returns ``n`` values.

Examples
--------
>>> palette = manual_pal(['a', 'b', 'c', 'd', 'e'])
>>> palette(3)
['a', 'b', 'c']


gamma = <NUM_LIT><EOL>ends = ((<NUM_LIT:0.0>, start, start), (<NUM_LIT:1.0>, end, end))<EOL>cdict = {'<STR_LIT>': ends, '<STR_LIT>': ends, '<STR_LIT>': ends}<EOL>grey_cmap = mcolors.LinearSegmentedColormap('<STR_LIT>', cdict)<EOL>def continuous_grey_palette(n):<EOL><INDENT>colors = []<EOL>for x in np.linspace(start**gamma, end**gamma, n):<EOL><INDENT>x = (x ** (<NUM_LIT:1.>/gamma) - start) / (end - start)<EOL>colors.append(mcolors.rgb2hex(grey_cmap(x)))<EOL><DEDENT>return colors<EOL><DEDENT>return continuous_grey_palette<EOL>

Utility for creating continuous grey scale palette

Parameters
----------
start : float
    grey value at low end of palette
end : float
    grey value at high end of palette

Returns
-------
out : function
    Continuous color palette that takes a single
    :class:`int` parameter ``n`` and returns ``n``
    equally spaced colors.

Examples
--------
>>> palette = grey_pal()
>>> palette(5)
['#333333', '#737373', '#989898', '#b5b5b5', '#cccccc']


def cubehelix_pal(start=<NUM_LIT:0>, rot=<NUM_LIT>, gamma=<NUM_LIT:1.0>, hue=<NUM_LIT>,<EOL>light=<NUM_LIT>, dark=<NUM_LIT>, reverse=False):

cdict = mpl._cm.cubehelix(gamma, start, rot, hue)<EOL>cubehelix_cmap = mpl.colors.LinearSegmentedColormap('<STR_LIT>', cdict)<EOL>def cubehelix_palette(n):<EOL><INDENT>values = np.linspace(light, dark, n)<EOL>return [mcolors.rgb2hex(cubehelix_cmap(x)) for x in values]<EOL><DEDENT>return cubehelix_palette<EOL>

Utility for creating continuous palette from the cubehelix system.

This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind.

Parameters
----------
start : float (0 <= start <= 3)
    The hue at the start of the helix.
rot : float
    Rotations around the hue wheel over the range of the palette.
gamma : float (0 <= gamma)
    Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
    colors.
hue : float (0 <= hue <= 1)
    Saturation of the colors.
dark : float (0 <= dark <= 1)
    Intensity of the darkest color in the palette.
light : float (0 <= light <= 1)
    Intensity of the lightest color in the palette.
reverse : bool
    If True, the palette will go from dark to light.

Returns
-------
out : function
    Continuous color palette that takes a single
    :class:`int` parameter ``n`` and returns ``n``
    equally spaced colors.

References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295.

Examples
--------
>>> palette = cubehelix_pal()
>>> palette(5)
['#edd1cb', '#d499a7', '#aa688f', '#6e4071', '#2d1e3e']


def area_palette(x):<EOL><INDENT>return rescale(np.sqrt(x), to=range, _from=(<NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>return area_palette<EOL>

Point area palette (continuous).

Parameters
----------
range : tuple
    Numeric vector of length two, giving range of possible sizes.
    Should be greater than 0.

Returns
-------
out : function
    Palette function that takes a sequence of values
    in the range ``[0, 1]`` and returns values in
    the specified range.

Examples
--------
>>> x = np.arange(0, .6, .1)**2
>>> palette = area_pal()
>>> palette(x)
array([1. , 1.5, 2. , 2.5, 3. , 3.5])

The results are equidistant because the input ``x`` is in
area space, i.e it is squared.


def desaturate_pal(color, prop, reverse=False):

if not <NUM_LIT:0> <= prop <= <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>rgb = mcolors.colorConverter.to_rgb(color)<EOL>h, l, s = colorsys.rgb_to_hls(*rgb)<EOL>s *= prop<EOL>desaturated_color = colorsys.hls_to_rgb(h, l, s)<EOL>colors = [color, desaturated_color]<EOL>if reverse:<EOL><INDENT>colors = colors[::-<NUM_LIT:1>]<EOL><DEDENT>return gradient_n_pal(colors, name='<STR_LIT>')<EOL>

Create a palette that desaturate a color by some proportion

Parameters
----------
color : matplotlib color
    hex, rgb-tuple, or html color name
prop : float
    saturation channel of color will be multiplied by
    this value
reverse : bool
    Whether to reverse the palette.

Returns
-------
out : function
    Continuous color palette that takes a single
    parameter either a :class:`float` or a sequence
    of floats maps those value(s) onto the palette
    and returns color(s). The float(s) must be
    in the range [0, 1].

Examples
--------
>>> palette = desaturate_pal('red', .1)
>>> palette([0, .25, .5, .75, 1])
['#ff0000', '#e21d1d', '#c53a3a', '#a95656', '#8c7373']


def abs_area_palette(x):<EOL><INDENT>return rescale(np.sqrt(np.abs(x)), to=(<NUM_LIT:0>, max), _from=(<NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>return abs_area_palette<EOL>

Point area palette (continuous), with area proportional to value.

Parameters
----------
max : float
    A number representing the maximum size

Returns
-------
out : function
    Palette function that takes a sequence of values
    in the range ``[0, 1]`` and returns values in the range
    ``[0, max]``.

Examples
--------
>>> x = np.arange(0, .8, .1)**2
>>> palette = abs_area(5)
>>> palette(x)
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5])

Compared to :func:`area_pal`, :func:`abs_area` will handle values
in the range ``[-1, 0]`` without returning ``np.nan``. And values
whose absolute value is greater than 1 will be clipped to the
maximum.


def hls_palette(n_colors=<NUM_LIT:6>, h=<NUM_LIT>, l=<NUM_LIT>, s=<NUM_LIT>):

hues = np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, n_colors + <NUM_LIT:1>)[:-<NUM_LIT:1>]<EOL>hues += h<EOL>hues %= <NUM_LIT:1><EOL>hues -= hues.astype(int)<EOL>palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]<EOL>return palette<EOL>

Get a set of evenly spaced colors in HLS hue space.

h, l, and s should be between 0 and 1

Parameters
----------

n_colors : int
    number of colors in the palette
h : float
    first hue
l : float
    lightness
s : float
    saturation

Returns
-------
palette : list
    List of colors as RGB hex strings.

See Also
--------
husl_palette : Make a palette using evenly spaced circular
    hues in the HUSL system.

Examples
--------
>>> len(hls_palette(2))
2
>>> len(hls_palette(9))
9


pass<EOL>


return {}<EOL>

Return package data

For example:

    {'': ['*.txt', '*.rst'],
     'hello': ['*.msg']}

means:
    - If any package contains *.txt or *.rst files,
      include them
    - And include any *.msg files found in
      the 'hello' package, too: