message_user(user, message, constants.DEBUG)<EOL>

Adds a message with the ``DEBUG`` level.

:param user: User instance
:param message: Message to show


message_user(user, message, constants.SUCCESS)<EOL>

Adds a message with the ``SUCCESS`` level.

:param user: User instance
:param message: Message to show


def process_response(self, request, response):

if hasattr(request, "<STR_LIT>") and hasattr(request, "<STR_LIT:user>") and request.user.is_authenticated():<EOL><INDENT>msgs = get_messages(request.user)<EOL>if msgs:<EOL><INDENT>for msg, level in msgs:<EOL><INDENT>messages.add_message(request, level, msg)<EOL><DEDENT><DEDENT><DEDENT>return response<EOL>

Check for messages for this user and, if it exists,
call the messages API with it


auth = auth or []<EOL>dynamodb = boto.connect_dynamodb(*auth)<EOL>table = dynamodb.get_table(name)<EOL>return Table(table=table, eager=eager)<EOL>

Returns a given table for the given user.


def decorator(view_func):<EOL><INDENT>@wraps(view_func, assigned=available_attrs(view_func))<EOL>def _wrapped_view(request, *args, **kwargs):<EOL><INDENT>ApiToken = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>m = methods if methods is not None else DEFAULT_API_METHODS<EOL>if request.method not in m:<EOL><INDENT>response = ApiResponse(False, '<STR_LIT>', status=<NUM_LIT>)<EOL>response['<STR_LIT>'] = '<STR_LIT:U+002CU+0020>'.join(methods)<EOL>return response<EOL><DEDENT>try:<EOL><INDENT>data = json.loads(request.body.decode('<STR_LIT:utf-8>')) if request.body else {}<EOL>if require_token:<EOL><INDENT>token_string = request.GET['<STR_LIT>'] if request.method == '<STR_LIT:GET>' else data['<STR_LIT>']<EOL>try:<EOL><INDENT>token = ApiToken.objects.get(token=token_string)<EOL>token.save()  <EOL>data['<STR_LIT>'] = token<EOL><DEDENT>except ApiToken.DoesNotExist:<EOL><INDENT>logger.exception('<STR_LIT>'.format(token_string))<EOL>return ApiResponse(False, '<STR_LIT>', status=<NUM_LIT>)<EOL><DEDENT><DEDENT>return ApiResponse(data=view_func(request, data=data, *args, **kwargs))<EOL><DEDENT>except Exception as e:<EOL><INDENT>if e.__class__.__name__ == '<STR_LIT>':<EOL><INDENT>logger.exception('<STR_LIT>')<EOL>return ApiResponse(False, '<STR_LIT>'.format(e), status=<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>logger.exception('<STR_LIT>')<EOL>return ApiResponse(False, '<STR_LIT>'.format(e), status=<NUM_LIT>)<EOL><DEDENT><DEDENT><DEDENT>return _wrapped_view<EOL><DEDENT>return decorator<EOL>

View decorator that handles JSON based API requests and responses consistently.
:param methods: A list of allowed methods
:param require_token: Whether API token is checked automatically or not


url = f'<STR_LIT>'<EOL>headers = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': f'<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:yes>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>def gen_tweets(pages):<EOL><INDENT>r = session.get(url, headers=headers)<EOL>while pages > <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>html = HTML(html=r.json()['<STR_LIT>'],<EOL>url='<STR_LIT>', default_encoding='<STR_LIT:utf-8>')<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError(<EOL>f'<STR_LIT>')<EOL><DEDENT>comma = "<STR_LIT:U+002C>"<EOL>dot = "<STR_LIT:.>"<EOL>tweets = []<EOL>for tweet in html.find('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>text = tweet.find('<STR_LIT>')[<NUM_LIT:0>].full_text<EOL><DEDENT>except IndexError:  <EOL><INDENT>continue<EOL><DEDENT>tweet_id = tweet.find('<STR_LIT>')[<NUM_LIT:0>].attrs['<STR_LIT>']<EOL>time = datetime.fromtimestamp(int(tweet.find('<STR_LIT>')[<NUM_LIT:0>].attrs['<STR_LIT>']) / <NUM_LIT>)<EOL>interactions = [<EOL>x.text<EOL>for x in tweet.find('<STR_LIT>')<EOL>]<EOL>replies = int(<EOL>interactions[<NUM_LIT:0>].split('<STR_LIT:U+0020>')[<NUM_LIT:0>].replace(comma, '<STR_LIT>').replace(dot, '<STR_LIT>')<EOL>or interactions[<NUM_LIT:3>]<EOL>)<EOL>retweets = int(<EOL>interactions[<NUM_LIT:1>].split('<STR_LIT:U+0020>')[<NUM_LIT:0>].replace(comma, '<STR_LIT>').replace(dot, '<STR_LIT>')<EOL>or interactions[<NUM_LIT:4>]<EOL>or interactions[<NUM_LIT:5>]<EOL>)<EOL>likes = int(<EOL>interactions[<NUM_LIT:2>].split('<STR_LIT:U+0020>')[<NUM_LIT:0>].replace(comma, '<STR_LIT>').replace(dot, '<STR_LIT>')<EOL>or interactions[<NUM_LIT:6>]<EOL>or interactions[<NUM_LIT:7>]<EOL>)<EOL>hashtags = [<EOL>hashtag_node.full_text<EOL>for hashtag_node in tweet.find('<STR_LIT>')<EOL>]<EOL>urls = [<EOL>url_node.attrs['<STR_LIT>']<EOL>for url_node in tweet.find('<STR_LIT>')<EOL>]<EOL>photos = [<EOL>photo_node.attrs['<STR_LIT>']<EOL>for photo_node in tweet.find('<STR_LIT>')<EOL>]<EOL>videos = []<EOL>video_nodes = tweet.find("<STR_LIT>")<EOL>for node in video_nodes:<EOL><INDENT>styles = node.attrs['<STR_LIT>'].split()<EOL>for style in styles:<EOL><INDENT>if style.startswith('<STR_LIT>'):<EOL><INDENT>tmp = style.split('<STR_LIT:/>')[-<NUM_LIT:1>]<EOL>video_id = tmp[:tmp.index('<STR_LIT>')]<EOL>videos.append({'<STR_LIT:id>': video_id})<EOL><DEDENT><DEDENT><DEDENT>tweets.append({<EOL>'<STR_LIT>': tweet_id,<EOL>'<STR_LIT:time>': time,<EOL>'<STR_LIT:text>': text,<EOL>'<STR_LIT>': replies,<EOL>'<STR_LIT>': retweets,<EOL>'<STR_LIT>': likes,<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': hashtags, '<STR_LIT>': urls,<EOL>'<STR_LIT>': photos, '<STR_LIT>': videos<EOL>}<EOL>})<EOL><DEDENT>last_tweet = html.find('<STR_LIT>')[-<NUM_LIT:1>].attrs['<STR_LIT>']<EOL>for tweet in tweets:<EOL><INDENT>if tweet:<EOL><INDENT>tweet['<STR_LIT:text>'] = re.sub('<STR_LIT:http>', '<STR_LIT>', tweet['<STR_LIT:text>'], <NUM_LIT:1>)<EOL>yield tweet<EOL><DEDENT><DEDENT>r = session.get(url, params={'<STR_LIT>': last_tweet}, headers=headers)<EOL>pages += -<NUM_LIT:1><EOL><DEDENT><DEDENT>yield from gen_tweets(pages)<EOL>

Gets tweets for a given user, via the Twitter frontend API.


if "<STR_LIT>" not in chn_names:<EOL><INDENT>for ii, ch in enumerate(chn_names):<EOL><INDENT>if ch == "<STR_LIT>":<EOL><INDENT>chn_names.append("<STR_LIT>")<EOL>data.append(<NUM_LIT:1>-data[ii])<EOL><DEDENT><DEDENT><DEDENT>return chn_names, data<EOL>

From circularity, compute the deformation

    This method is useful for RT-DC data sets that contain
    the circularity but not the deformation.


return [n for n in self.walk() if n.is_leaf]<EOL>

Get all the leaf nodes of the subtree descending from this node.

:return: List of Nodes with no descendants.


for n in self.walk():<EOL><INDENT>if n.name == label:<EOL><INDENT>return n<EOL><DEDENT><DEDENT>

Gets the specified node by name.

:return: Node or None if name does not exist in tree


return [n.name for n in self.get_leaves()]<EOL>

Get the names of all the leaf nodes of the subtree descending from
this node.

:return: List of names of Nodes with no descendants.


@classmethod<EOL><INDENT>def create(cls, name=None, length=None, descendants=None, **kw):<DEDENT>

node = cls(name=name, length=length, **kw)<EOL>for descendant in descendants or []:<EOL><INDENT>node.add_descendant(descendant)<EOL><DEDENT>return node<EOL>

Create a new `Node` object.

:param name: Node label.
:param length: Branch length from the new node to its parent.
:param descendants: list of descendants or `None`.
:param kw: Additonal keyword arguments are passed through to `Node.__init__`.
:return: `Node` instance.


label = self.name or '<STR_LIT>'<EOL>if self._length:<EOL><INDENT>label += '<STR_LIT::>' + self._length<EOL><DEDENT>descendants = '<STR_LIT:U+002C>'.join([n.newick for n in self.descendants])<EOL>if descendants:<EOL><INDENT>descendants = '<STR_LIT:(>' + descendants + '<STR_LIT:)>'<EOL><DEDENT>return descendants + label<EOL>

The representation of the Node in Newick format.


def loads(s, strip_comments=False, **kw):

kw['<STR_LIT>'] = strip_comments<EOL>return [parse_node(ss.strip(), **kw) for ss in s.split('<STR_LIT:;>') if ss.strip()]<EOL>

Load a list of trees from a Newick formatted string.

:param s: Newick formatted string.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.


def visit(self, visitor, predicate=None, **kw):

predicate = predicate or bool<EOL>for n in self.walk(**kw):<EOL><INDENT>if predicate(n):<EOL><INDENT>visitor(n)<EOL><DEDENT><DEDENT>

Apply a function to matching nodes in the (sub)tree rooted at self.

:param visitor: A callable accepting a Node object as single argument..
:param predicate: A callable accepting a Node object as single argument and \
returning a boolean signaling whether Node matches; if `None` all nodes match.
:param kw: Addtional keyword arguments are passed through to self.walk.


def ascii_art(self, strict=False, show_internal=True):

cmap = {<EOL>'<STR_LIT>': '<STR_LIT:->',<EOL>'<STR_LIT>': '<STR_LIT:|>',<EOL>'<STR_LIT>': '<STR_LIT:/>',<EOL>'<STR_LIT>': '<STR_LIT:\\>',<EOL>'<STR_LIT>': '<STR_LIT:|>',<EOL>'<STR_LIT>': '<STR_LIT:|>',<EOL>'<STR_LIT>': '<STR_LIT:+>',<EOL>}<EOL>def normalize(line):<EOL><INDENT>m = re.compile('<STR_LIT>')<EOL>line = m.sub(lambda m: m.group('<STR_LIT:s>')[<NUM_LIT:1>:], line)<EOL>line = re.sub('<STR_LIT>', '<STR_LIT>', line)  <EOL>line = re.sub('<STR_LIT>', '<STR_LIT>', line)  <EOL>line = re.sub('<STR_LIT>', '<STR_LIT>', line)  <EOL>if strict:<EOL><INDENT>for u, a in cmap.items():<EOL><INDENT>line = line.replace(u, a)<EOL><DEDENT><DEDENT>return line<EOL><DEDENT>return '<STR_LIT:\n>'.join(<EOL>normalize(l) for l in self._ascii_art(show_internal=show_internal)[<NUM_LIT:0>]<EOL>if set(l) != {'<STR_LIT:U+0020>', '<STR_LIT>'})<EOL>

Return a unicode string representing a tree in ASCII art fashion.

:param strict: Use ASCII characters strictly (for the tree symbols).
:param show_internal: Show labels of internal nodes.
:return: unicode string

>>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
>>> print(node.ascii_art(show_internal=False, strict=True))
        /-A
    /---|
    |   \-B
----|       /-D
    |   /---|
    |   |   \-E
    \---|
        |-G
        \-H


pass<EOL>


return self.msg[<NUM_LIT:0>:buffer_size]<EOL>


self.msg = msg<EOL>


async def wait_for(self, cmd, value=None, timeout=<NUM_LIT>):

try:<EOL><INDENT>async with async_timeout(timeout * <NUM_LIT>):<EOL><INDENT>while True:<EOL><INDENT>msgs = await self.receive()<EOL>msg = check_messages(msgs, cmd, value=value)<EOL>if msg:<EOL><INDENT>return msg<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except asyncio.TimeoutError:<EOL><INDENT>return OrderedDict()<EOL><DEDENT>

Hang until command is received.

        If value is supplied, it will hang until ``cmd:value`` is received.

        Parameters
        ----------
        cmd : string
            Command to wait for in bytestring from microscope CAM interface. If
            ``value`` is falsey, value of received command does not matter.
        value : string
            Wait until ``cmd:value`` is received.
        timeout : int
            Minutes to wait for command. If timeout is reached, an empty
            OrderedDict will be returned.

        Returns
        -------
        collections.OrderedDict
            Last received messsage or empty message if timeout is reached.


self.reader, self.writer = await asyncio.open_connection(<EOL>self.host, self.port, loop=self.loop)<EOL>self.welcome_msg = await self.reader.read(self.buffer_size)<EOL>


msg = self._prepare_send(commands)<EOL>self.writer.write(msg)<EOL>await self.writer.drain()<EOL>

Send commands to LASAF through CAM-socket.

        Parameters
        ----------
        commands : list of tuples or bytes string
            Commands as a list of tuples or a bytes string. cam.prefix is
            allways prepended before sending.

        Returns
        -------
        int
            Bytes sent.

        Example
        -------
        ::

            >>> # send list of tuples
            >>> await cam.send([('cmd', 'enableall'), ('value', 'true')])

            >>> # send bytes string
            >>> await cam.send(b'/cmd:enableall /value:true')


if self.writer.can_write_eof():<EOL><INDENT>self.writer.write_eof()<EOL><DEDENT>self.writer.close()<EOL>


@functools.wraps(function)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>sep = kwargs.get('<STR_LIT>', '<STR_LIT:U+0020>')<EOL>end = kwargs.get('<STR_LIT:end>', '<STR_LIT>')  <EOL>out = sep.join([repr(x) for x in args])<EOL>out = out + end<EOL>_LOGGER.debug(out)<EOL>return function(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>

Decorate passed in function and log message to module logger.


cmd = [('<STR_LIT>', '<STR_LIT>')]<EOL>self.send(cmd)<EOL>return self.wait_for(*cmd[<NUM_LIT:0>])<EOL>


self.socket.close()<EOL>


for qc in QUOTES:<EOL><INDENT>if qc != q:<EOL><INDENT>return qc<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(u'<STR_LIT>'.format(q))<EOL><DEDENT>

When you pass a quote character, returns you an another one if possible


return self.filter(Q.from_dict(params))<EOL>

Searches in ManageIQ using the ``filter[]`` get parameter.

        This method only supports logical AND so all key/value pairs are considered as equality
        comparision and all are logically anded.


href_result = result['<STR_LIT>']<EOL>if self.collection._href.startswith(href_result):<EOL><INDENT>return Entity(self.collection, result, incomplete=True)<EOL><DEDENT>href_match = re.match(r"<STR_LIT>", href_result)<EOL>if not href_match:<EOL><INDENT>raise ValueError("<STR_LIT>".format(href_result))<EOL><DEDENT>collection_name = href_match.group(<NUM_LIT:2>)<EOL>entry_point = href_match.group(<NUM_LIT:1>)<EOL>new_collection = Collection(<EOL>self.collection.api,<EOL>"<STR_LIT>".format(entry_point, collection_name),<EOL>collection_name<EOL>)<EOL>return Entity(new_collection, result, incomplete=True)<EOL>

Returns entity in correct collection.

        If the "href" value in result doesn't match the current collection,
        try to find the collection that the "href" refers to.


return SearchResult(self, self._api.get(self._href, **params))<EOL>

Specify query string to use with the collection.

        Returns: :py:class:`SearchResult`


if not value:<EOL><INDENT>value = section<EOL>section = None<EOL><DEDENT>try:<EOL><INDENT>logger.debug('<STR_LIT>')<EOL>settings = config.Settings(section=section)<EOL>conf = s3conf.S3Conf(settings=settings)<EOL>env_vars = conf.get_envfile()<EOL>env_vars.set(value, create=create)<EOL><DEDENT>except exceptions.EnvfilePathNotDefinedError:<EOL><INDENT>raise exceptions.EnvfilePathNotDefinedUsageError()<EOL><DEDENT>

Set value of a variable in an environment file for the given section.
If the variable is already defined, its value is replaced, otherwise, it is added to the end of the file.
The value is given as "ENV_VAR_NAME=env_var_value", e.g.:

s3conf set test ENV_VAR_NAME=env_var_value


try:<EOL><INDENT>logger.debug('<STR_LIT>')<EOL>settings = config.Settings(section=section)<EOL>storage = STORAGES['<STR_LIT>'](settings=settings)<EOL>conf = s3conf.S3Conf(storage=storage, settings=settings)<EOL>if edit:<EOL><INDENT>conf.edit(create=create)<EOL><DEDENT>else:<EOL><INDENT>env_vars = conf.get_envfile().as_dict()<EOL>if env_vars.get('<STR_LIT>') and map_files:<EOL><INDENT>conf.download_mapping(env_vars.get('<STR_LIT>'))<EOL><DEDENT>if not quiet:<EOL><INDENT>for var_name, var_value in sorted(env_vars.items(), key=lambda x: x[<NUM_LIT:0>]):<EOL><INDENT>click.echo('<STR_LIT>'.format(var_name, var_value))<EOL><DEDENT><DEDENT>if phusion:<EOL><INDENT>s3conf.phusion_dump(env_vars, phusion_path)<EOL><DEDENT><DEDENT><DEDENT>except exceptions.EnvfilePathNotDefinedError:<EOL><INDENT>raise exceptions.EnvfilePathNotDefinedUsageError()<EOL><DEDENT>except exceptions.FileDoesNotExist as e:<EOL><INDENT>raise UsageError('<STR_LIT>'.format(str(e)))<EOL><DEDENT>

Reads the file defined by the S3CONF variable and output its contents to stdout. Logs are printed to stderr.
See options for added functionality: editing file, mapping files, dumping in the phusion-baseimage format, etc.


<EOL>try:<EOL><INDENT>click_log.basic_config('<STR_LIT>')<EOL>logger.debug('<STR_LIT>')<EOL>if edit:<EOL><INDENT>if ctx.invoked_subcommand is None:<EOL><INDENT>logger.debug('<STR_LIT>', config.LOCAL_CONFIG_FILE)<EOL>config.ConfigFileResolver(config.LOCAL_CONFIG_FILE).edit(create=create)<EOL>return<EOL><DEDENT>else:<EOL><INDENT>raise UsageError('<STR_LIT>')<EOL><DEDENT><DEDENT>if ctx.invoked_subcommand is None:<EOL><INDENT>click.echo(main.get_help(ctx))<EOL><DEDENT><DEDENT>except exceptions.FileDoesNotExist as e:<EOL><INDENT>raise UsageError('<STR_LIT>'.format(str(e)))<EOL><DEDENT>

Simple command line tool to help manage environment variables stored in a S3-like system. Facilitates editing text
files remotely stored, as well as downloading and uploading files.


if not remote_file.startswith('<STR_LIT>'):<EOL><INDENT>raise UsageError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>logger.debug('<STR_LIT>')<EOL>config_file_path = os.path.join(os.getcwd(), '<STR_LIT>', '<STR_LIT>')<EOL>config_file = config.ConfigFileResolver(config_file_path, section=section)<EOL>config_file.set('<STR_LIT>', remote_file)<EOL>gitignore_file_path = os.path.join(os.getcwd(), '<STR_LIT>', '<STR_LIT>')<EOL>config_file.save()<EOL>open(gitignore_file_path, '<STR_LIT:w>').write('<STR_LIT>')<EOL>

Creates the .s3conf config folder and .s3conf/config config file
with the provided section name and configuration file. It is a very
basic config file. Manually edit it in order to add credentials. E.g.:

s3conf init development s3://my-project/development.env


if version is None:<EOL><INDENT>if not getattr(settings, '<STR_LIT>', False):<EOL><INDENT>version = getattr(settings, '<STR_LIT>', DJFRONTEND_TWBS_VERSION_DEFAULT)<EOL><DEDENT>else:<EOL><INDENT>version = getattr(settings, '<STR_LIT>', DJFRONTEND_TWBS_VERSION_DEFAULT)<EOL><DEDENT><DEDENT>return format_html(<EOL>'<STR_LIT>',<EOL>static=_static_url, v=version, min=_min)<EOL>

Returns Twitter Bootstrap Theme CSS file.


if version is None:<EOL><INDENT>version = getattr(settings, '<STR_LIT>', DJFRONTEND_JQUERY_DEFAULT)<EOL><DEDENT>if getattr(settings, '<STR_LIT>', False):<EOL><INDENT>template = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>template = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return format_html(template, static=_static_url, v=version)<EOL>

Returns jQuery JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
Included in HTML5 Boilerplate.


if version is None:<EOL><INDENT>if not getattr(settings, '<STR_LIT>', False):<EOL><INDENT>version = getattr(settings, '<STR_LIT>', DJFRONTEND_TWBS_VERSION_DEFAULT)<EOL><DEDENT>else:<EOL><INDENT>version = getattr(settings, '<STR_LIT>', DJFRONTEND_TWBS_VERSION_DEFAULT)<EOL><DEDENT><DEDENT>if files:<EOL><INDENT>if files != '<STR_LIT:all>':<EOL><INDENT>files = files.split('<STR_LIT:U+0020>')<EOL><DEDENT><DEDENT>elif getattr(settings, '<STR_LIT>', False) and settings.DJFRONTEND_TWBS_JS_FILES != '<STR_LIT:all>':<EOL><INDENT>files = settings.DJFRONTEND_TWBS_JS_FILES.split('<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>files = '<STR_LIT:all>'<EOL><DEDENT>if files == '<STR_LIT:all>':<EOL><INDENT>return format_html(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>v=version, static=_static_url)<EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in files and '<STR_LIT>' not in files:<EOL><INDENT>files.append('<STR_LIT>')<EOL><DEDENT>for file in files:<EOL><INDENT>file = ['<STR_LIT>' %<EOL>(_static_url, version, file) for file in files]<EOL><DEDENT>return mark_safe('<STR_LIT:\n>'.join(file))<EOL><DEDENT>

Returns Twitter Bootstrap JavaScript file(s).
all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.

Other choice are:
    affix,
    alert,
    button,
    carousel,
    collapse,
    dropdown,
    modal,
    popover (adds tooltip if not included),
    scrollspy,
    tab,
    tooltip,
    transition.

Individual files are not minified.


params = {}<EOL>available_params = [<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT:q>", "<STR_LIT:start>",<EOL>"<STR_LIT:count>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>for key in available_params:<EOL><INDENT>if key in kwargs:<EOL><INDENT>params[key] = kwargs[key]<EOL><DEDENT><DEDENT>results = self.api.get("<STR_LIT>", params)<EOL>return results<EOL>

:param entity_id: location id
:param entity_type: location type (city, subzone, zone, lanmark, metro , group)
:param q: search keyword
:param start: fetch results after offset
:param count: max number of results to display
:param lat: latitude
:param lon: longitude
:param radius: radius around (lat,lon); to define search area, defined in meters(M)
:param cuisines: list of cuisine id's separated by comma
:param establishment_type: estblishment id obtained from establishments call
:param collection_id: collection id obtained from collections call
:param category: category ids obtained from categories call
:param sort: sort restaurants by (cost, rating, real_distance)
:param order: used with 'sort' parameter to define ascending / descending
:return: json response
The location input can be specified using Zomato location ID or coordinates. Cuisine / Establishment /
Collection IDs can be obtained from respective api calls.

Partner Access is required to access photos and reviews.

Examples:
- To search for 'Italian' restaurants in 'Manhattan, New York City',
set cuisines = 55, entity_id = 94741 and entity_type = zone
- To search for 'cafes' in 'Manhattan, New York City',
set establishment_type = 1, entity_type = zone and entity_id = 94741
- Get list of all restaurants in 'Trending this Week' collection in 'New York City' by using
entity_id = 280, entity_type = city and collection_id = 1


params = {"<STR_LIT>": restaurant_id}<EOL>restaurant_details = self.api.get("<STR_LIT>", params)<EOL>return restaurant_details<EOL>

:param restaurant_id: id of restaurant whose details are requested
:return: json response
Get detailed restaurant information using Zomato restaurant ID.
Partner Access is required to access photos and reviews.


def getEstablishments(self, city_id, **kwargs):

params = {"<STR_LIT>": city_id}<EOL>optional_params = ["<STR_LIT>", "<STR_LIT>"]<EOL>for key in optional_params:<EOL><INDENT>if key in kwargs:<EOL><INDENT>params[key] = kwargs[key]<EOL><DEDENT><DEDENT>establishments = self.api.get("<STR_LIT>", params)<EOL>return establishments<EOL>

:param city_id: id of the city for which collections are needed
:param lat: latitude
:param lon: longitude
Get a list of restaurant types in a city. The location/City input can be provided in the following ways
- Using Zomato City ID
- Using coordinates of any location within a city
List of all restaurants categorized under a particular restaurant type can obtained using
/Search API with Establishment ID and location details as inputs


nevents_wrong = <NUM_LIT:0><EOL>feed_json = json.loads(self.feed)<EOL>if '<STR_LIT>' not in feed_json['<STR_LIT>']:<EOL><INDENT>return<EOL><DEDENT>self.cells = feed_json['<STR_LIT>']['<STR_LIT>']<EOL>self.ncell = <NUM_LIT:0><EOL>event_fields = self.__get_event_fields()<EOL>while self.ncell < len(self.cells):<EOL><INDENT>event = self.__get_next_event(event_fields)<EOL>if event['<STR_LIT>'] is None or event['<STR_LIT>'] is None:<EOL><INDENT>logger.warning("<STR_LIT>", event)<EOL>nevents_wrong += <NUM_LIT:1><EOL>continue<EOL><DEDENT>yield event<EOL><DEDENT>logger.info("<STR_LIT>", nevents_wrong)<EOL>

Parse the MozillaClub spreadsheet feed cells json.


event_fields = {}<EOL>while self.ncell < len(self.cells):<EOL><INDENT>cell = self.cells[self.ncell]<EOL>row = cell['<STR_LIT>']['<STR_LIT>']<EOL>if int(row) > <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT>ncol = int(cell['<STR_LIT>']['<STR_LIT>'])<EOL>name = cell['<STR_LIT:content>']['<STR_LIT>']<EOL>event_fields[ncol] = name<EOL>if ncol in EVENT_TEMPLATE:<EOL><INDENT>if event_fields[ncol] != EVENT_TEMPLATE[ncol]:<EOL><INDENT>logger.warning("<STR_LIT>",<EOL>name, EVENT_TEMPLATE[ncol])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning("<STR_LIT>", name)<EOL><DEDENT>self.ncell += <NUM_LIT:1><EOL><DEDENT>return event_fields<EOL>

Get the events fields (columns) from the cells received.


return False<EOL>

Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming


def get_items(self, category=CATEGORY_EVENT, offset=REMO_DEFAULT_OFFSET):

more = True  <EOL>next_uri = None  <EOL>page = ReMoClient.FIRST_PAGE<EOL>page += int(offset / ReMoClient.ITEMS_PER_PAGE)<EOL>if category == CATEGORY_EVENT:<EOL><INDENT>api = self.api_events_url<EOL><DEDENT>elif category == CATEGORY_ACTIVITY:<EOL><INDENT>api = self.api_activities_url<EOL><DEDENT>elif category == CATEGORY_USER:<EOL><INDENT>api = self.api_users_url<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(category + '<STR_LIT>')<EOL><DEDENT>while more:<EOL><INDENT>params = {<EOL>"<STR_LIT>": page,<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL>logger.debug("<STR_LIT>",<EOL>api, str(params))<EOL>raw_items = self.fetch(api, payload=params)<EOL>yield raw_items<EOL>items_data = json.loads(raw_items)<EOL>next_uri = items_data['<STR_LIT>']<EOL>if not next_uri:<EOL><INDENT>more = False<EOL><DEDENT>else:<EOL><INDENT>parsed_uri = urllib.parse.urlparse(next_uri)<EOL>parsed_params = urllib.parse.parse_qs(parsed_uri.query)<EOL>page = parsed_params['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT><DEDENT>

Retrieve all items for category using pagination


def metadata(self, item, filter_classified=False):

item = super().metadata(item, filter_classified=filter_classified)<EOL>item['<STR_LIT>'] = item['<STR_LIT:data>'].pop('<STR_LIT>')<EOL>return item<EOL>

ReMo metadata.

        This method takes items overrides `metadata` method to add extra
        information related to Remo (offset of the item).

        :param item: an item fetched by a backend
        :param filter_classified: sets if classified fields were filtered


return True<EOL>

Returns whether it supports archiving items on the fetch process.

        :returns: this backend supports items archive


def fetch_items(self, category, **kwargs):

offset = kwargs['<STR_LIT>']<EOL>logger.info("<STR_LIT>",<EOL>self.url, category, offset)<EOL>nitems = <NUM_LIT:0>  <EOL>titems = <NUM_LIT:0>  <EOL>page = int(offset / ReMoClient.ITEMS_PER_PAGE)<EOL>page_offset = page * ReMoClient.ITEMS_PER_PAGE<EOL>drop_items = offset - page_offset<EOL>logger.debug("<STR_LIT>",<EOL>drop_items, offset, page, page_offset)<EOL>current_offset = offset<EOL>for raw_items in self.client.get_items(category, offset):<EOL><INDENT>items_data = json.loads(raw_items)<EOL>titems = items_data['<STR_LIT:count>']<EOL>logger.info("<STR_LIT>",<EOL>titems - current_offset, current_offset)<EOL>items = items_data['<STR_LIT>']<EOL>for item in items:<EOL><INDENT>if drop_items > <NUM_LIT:0>:<EOL><INDENT>drop_items -= <NUM_LIT:1><EOL>continue<EOL><DEDENT>raw_item_details = self.client.fetch(item['<STR_LIT>'])<EOL>item_details = json.loads(raw_item_details)<EOL>item_details['<STR_LIT>'] = current_offset<EOL>current_offset += <NUM_LIT:1><EOL>yield item_details<EOL>nitems += <NUM_LIT:1><EOL><DEDENT><DEDENT>logger.info("<STR_LIT>", nitems, titems, offset)<EOL>

Fetch items

        :param category: the category of items to fetch
        :param kwargs: backend arguments

        :returns: a generator of items


parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,<EOL>offset=True,<EOL>archive=True)<EOL>parser.parser.add_argument('<STR_LIT:url>', nargs='<STR_LIT:?>',<EOL>default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>return parser<EOL>


path = urijoin(CRATES_API_URL, CATEGORY_CRATES)<EOL>raw_crates = self.__fetch_items(path, from_page)<EOL>return raw_crates<EOL>


return False<EOL>


response = super().fetch(url, payload=payload)<EOL>return response.text<EOL>

Return the textual content associated to the Response object


def __fetch_items(self, path, page=<NUM_LIT:1>):

fetch_data = True<EOL>parsed_crates = <NUM_LIT:0><EOL>total_crates = <NUM_LIT:0><EOL>while fetch_data:<EOL><INDENT>logger.debug("<STR_LIT>", page)<EOL>try:<EOL><INDENT>payload = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': page}<EOL>raw_content = self.fetch(path, payload=payload)<EOL>content = json.loads(raw_content)<EOL>parsed_crates += len(content['<STR_LIT>'])<EOL>if not total_crates:<EOL><INDENT>total_crates = content['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT><DEDENT>except requests.exceptions.HTTPError as e:<EOL><INDENT>logger.error("<STR_LIT>", e.response.text)<EOL>raise e<EOL><DEDENT>yield raw_content<EOL>page += <NUM_LIT:1><EOL>if parsed_crates >= total_crates:<EOL><INDENT>fetch_data = False<EOL><DEDENT><DEDENT>

Return the items from Crates.io API using pagination


return CratesClient(self.sleep_time, self.archive, from_archive)<EOL>


if '<STR_LIT>' in item:<EOL><INDENT>return CATEGORY_SUMMARY<EOL><DEDENT>else:<EOL><INDENT>return CATEGORY_CRATES<EOL><DEDENT>

Extracts the category from an item.

        This backend generates two types of item: 'summary' and 'crate'.


parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,<EOL>from_date=True,<EOL>archive=True,<EOL>token_auth=True)<EOL>group = parser.parser.add_argument_group('<STR_LIT>')<EOL>group.add_argument('<STR_LIT>', dest='<STR_LIT>',<EOL>default=SLEEP_TIME, type=int,<EOL>help="<STR_LIT>")<EOL>return parser<EOL>


def fetch(self, category=CATEGORY_CRATES, from_date=DEFAULT_DATETIME):

if not from_date:<EOL><INDENT>from_date = DEFAULT_DATETIME<EOL><DEDENT>from_date = datetime_to_utc(from_date)<EOL>kwargs = {"<STR_LIT>": from_date}<EOL>items = super().fetch(category, **kwargs)<EOL>return items<EOL>

Fetch package data.

        The method retrieves packages and summary from Crates.io.

        :param category: the category of items to fetch
        :param from_date: obtain packages updated since this date

        :returns: a summary and crate items


path = urijoin(CRATES_API_URL, CATEGORY_SUMMARY)<EOL>raw_content = self.fetch(path)<EOL>return raw_content<EOL>


page = KitsuneClient.FIRST_PAGE<EOL>while True:<EOL><INDENT>api_answers_url = urijoin(self.base_url, '<STR_LIT>') + '<STR_LIT:/>'<EOL>params = {<EOL>"<STR_LIT>": page,<EOL>"<STR_LIT>": question_id,<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL>answers_raw = self.fetch(api_answers_url, params)<EOL>yield answers_raw<EOL>answers = json.loads(answers_raw)<EOL>if not answers['<STR_LIT>']:<EOL><INDENT>break<EOL><DEDENT>page += <NUM_LIT:1><EOL><DEDENT>

Retrieve all answers for a question from older to newer (updated)


page = KitsuneClient.FIRST_PAGE<EOL>if offset:<EOL><INDENT>page += int(offset / KitsuneClient.ITEMS_PER_PAGE)<EOL><DEDENT>while True:<EOL><INDENT>api_questions_url = urijoin(self.base_url, '<STR_LIT>') + '<STR_LIT:/>'<EOL>params = {<EOL>"<STR_LIT>": page,<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL>questions = self.fetch(api_questions_url, params)<EOL>yield questions<EOL>questions_json = json.loads(questions)<EOL>next_uri = questions_json['<STR_LIT>']<EOL>if not next_uri:<EOL><INDENT>break<EOL><DEDENT>page += <NUM_LIT:1><EOL><DEDENT>

Retrieve questions from older to newer updated starting offset


return KitsuneClient(self.url, self.archive, from_archive)<EOL>


Kitsune metadata.

        This method takes items overrides `metadata` method to add extra
        information related to Kitsune (offset of the question).

        :param item: an item fetched by a backend
        :param filter_classified: sets if classified fields were filtered


try:<EOL><INDENT>for x in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if not data.get(x):<EOL><INDENT>raise TypeError("<STR_LIT>".format(x))<EOL><DEDENT><DEDENT>if '<STR_LIT>' in data:<EOL><INDENT>return self.refresh_token(**data)<EOL><DEDENT>for x in ['<STR_LIT>', '<STR_LIT:code>']:<EOL><INDENT>if not data.get(x):<EOL><INDENT>raise TypeError("<STR_LIT>".format(x))            <EOL><DEDENT><DEDENT>return self.get_token(**data)<EOL><DEDENT>except TypeError as exc:<EOL><INDENT>self._handle_exception(exc)<EOL>return self._make_json_error_response('<STR_LIT>')<EOL><DEDENT>except StandardError as exc:<EOL><INDENT>self._handle_exception(exc)<EOL>return self._make_json_error_response('<STR_LIT>')<EOL><DEDENT>

Get a token response from POST data.

        :param data: POST data containing authorization information.
        :type data: dict
        :rtype: requests.Response


params = utils.url_query_params(uri)<EOL>try:<EOL><INDENT>if '<STR_LIT>' not in params:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' not in params:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' not in params:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return self.get_authorization_code(**params)<EOL><DEDENT>except TypeError as exc:<EOL><INDENT>self._handle_exception(exc)<EOL>err = '<STR_LIT>'<EOL>if '<STR_LIT>' in params:<EOL><INDENT>u = params['<STR_LIT>']<EOL>return self._make_redirect_error_response(u, err)<EOL><DEDENT>else:<EOL><INDENT>return self._invalid_redirect_uri_response()<EOL><DEDENT><DEDENT>except StandardError as exc:<EOL><INDENT>self._handle_exception(exc)<EOL>err = '<STR_LIT>'<EOL>u = params['<STR_LIT>']<EOL>return self._make_redirect_error_response(u, err)<EOL><DEDENT>

Get authorization code response from a URI. This method will
        ignore the domain and path of the request, instead
        automatically parsing the query string parameters.

        :param uri: URI to parse for authorization information.
        :type uri: str
        :rtype: requests.Response


return self._make_json_error_response('<STR_LIT>')<EOL>

What to return when the redirect_uri parameter is missing.

        :rtype: requests.Response


<EOL>if grant_type != '<STR_LIT>':<EOL><INDENT>return self._make_json_error_response('<STR_LIT>')<EOL><DEDENT>is_valid_client_id = self.validate_client_id(client_id)<EOL>is_valid_client_secret = self.validate_client_secret(client_id,<EOL>client_secret)<EOL>is_valid_redirect_uri = self.validate_redirect_uri(client_id,<EOL>redirect_uri)<EOL>scope = params.get('<STR_LIT>', '<STR_LIT>')<EOL>is_valid_scope = self.validate_scope(client_id, scope)<EOL>data = self.from_authorization_code(client_id, code, scope)<EOL>is_valid_grant = data is not None<EOL>if not (is_valid_client_id and is_valid_client_secret):<EOL><INDENT>return self._make_json_error_response('<STR_LIT>')<EOL><DEDENT>if not is_valid_grant or not is_valid_redirect_uri:<EOL><INDENT>return self._make_json_error_response('<STR_LIT>')<EOL><DEDENT>if not is_valid_scope:<EOL><INDENT>return self._make_json_error_response('<STR_LIT>')<EOL><DEDENT>self.discard_authorization_code(client_id, code)<EOL>access_token = self.generate_access_token()<EOL>token_type = self.token_type<EOL>expires_in = self.token_expires_in<EOL>refresh_token = self.generate_refresh_token()<EOL>self.persist_token_information(client_id=client_id,<EOL>scope=scope,<EOL>access_token=access_token,<EOL>token_type=token_type,<EOL>expires_in=expires_in,<EOL>refresh_token=refresh_token,<EOL>data=data)<EOL>return self._make_json_response({<EOL>'<STR_LIT>': access_token,<EOL>'<STR_LIT>': token_type,<EOL>'<STR_LIT>': expires_in,<EOL>'<STR_LIT>': refresh_token<EOL>})<EOL>

Generate access token HTTP response.

        :param grant_type: Desired grant type. Must be "authorization_code".
        :type grant_type: str
        :param client_id: Client ID.
        :type client_id: str
        :param client_secret: Client secret.
        :type client_secret: str
        :param redirect_uri: Client redirect URI.
        :type redirect_uri: str
        :param code: Authorization code.
        :type code: str
        :rtype: requests.Response


return <NUM_LIT><EOL>

Property method to get the length used to generate tokens.

        :rtype: int


logger = logging.getLogger(__name__)<EOL>logger.exception(exc)<EOL>

Handle an internal exception that was caught and suppressed.

        :param exc: Exception to process.
        :type exc: Exception


params['<STR_LIT:code>'] = code<EOL>if '<STR_LIT>' not in params:<EOL><INDENT>params['<STR_LIT>'] = self.default_grant_type<EOL><DEDENT>params.update({'<STR_LIT>': self.client_id,<EOL>'<STR_LIT>': self.client_secret,<EOL>'<STR_LIT>': self.redirect_uri})<EOL>response = self.http_post(self.token_uri, params)<EOL>try:<EOL><INDENT>return response.json()<EOL><DEDENT>except TypeError:<EOL><INDENT>return response.json<EOL><DEDENT>

Get an access token from the provider token URI.

        :param code: Authorization code.
        :type code: str
        :return: Dict containing access token, refresh token, etc.
        :rtype: dict


return dict(urlparse.parse_qsl(urlparse.urlparse(url).query, True))<EOL>

Return query parameters as a dict from the specified URL.

    :param url: URL.
    :type url: str
    :rtype: dict


self.places = ctllib.Places(config='<STR_LIT>', messages='<STR_LIT>')<EOL>def _cleanup():<EOL><INDENT>for d in self.places:<EOL><INDENT>if os.path.exists(d):<EOL><INDENT>shutil.rmtree(d)<EOL><DEDENT><DEDENT><DEDENT>_cleanup()<EOL>self.addCleanup(_cleanup)<EOL>for d in self.places:<EOL><INDENT>os.mkdir(d)<EOL><DEDENT>

Set up configuration and build/cleanup directories


self.parser = ctllib.PARSER<EOL>self.base = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>

Initialize the parser, required arguments


with io.open(fname, "<STR_LIT:r>", encoding='<STR_LIT:utf-8>') as fp:<EOL><INDENT>return json.loads(fp.read())<EOL><DEDENT>


self.events.append(('<STR_LIT>', name))<EOL>


DirectoryBasedTest.setUp(self)<EOL>self.receiver = EventRecorder()<EOL>self.monitor = directory_monitor.checker(self.testDirectory,<EOL>self.receiver)<EOL>self.assertFalse(self.receiver.events)<EOL>


def _cleanup(testDir):<EOL><INDENT>if os.path.exists(testDir):<EOL><INDENT>shutil.rmtree(testDir)<EOL><DEDENT><DEDENT>self.testDirs = {}<EOL>for subd in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>testDir = self.testDirs[subd] = os.path.join(os.getcwd(), subd)<EOL>self.addCleanup(_cleanup, testDir)<EOL>_cleanup(testDir)<EOL>os.makedirs(testDir)<EOL><DEDENT>self.my_reactor = test_procmon.DummyProcessReactor()<EOL>self.service = service.get(self.testDirs['<STR_LIT>'],<EOL>self.testDirs['<STR_LIT>'],<EOL><NUM_LIT:5>, reactor=self.my_reactor)<EOL>self._finishSetUp()<EOL>


self.content = content<EOL>


def request(self, method, url, headers, body):

d = defer.Deferred()<EOL>self.calls.append((method, url, headers, body))<EOL>self.pending[url].append(d)<EOL>return d<EOL>


return '<STR_LIT:U+0020>'.join('<STR_LIT:U+0020>'.join('<STR_LIT>' % (key, vpart)<EOL>for vpart in value.split())<EOL>for key, value in six.iteritems(self.args)).split()<EOL>


path = filepath.FilePath(location)<EOL>files = set()<EOL>filesContents = {}<EOL>def _check(path):<EOL><INDENT>currentFiles = set(fname for fname in os.listdir(location)<EOL>if not fname.endswith('<STR_LIT>'))<EOL>removed = files - currentFiles<EOL>added = currentFiles - files<EOL>for fname in added:<EOL><INDENT>contents = path.child(fname).getContent()<EOL>filesContents[fname] = contents<EOL>receiver.add(fname, contents)<EOL><DEDENT>for fname in removed:<EOL><INDENT>receiver.remove(fname)<EOL><DEDENT>same = currentFiles & files<EOL>for fname in same:<EOL><INDENT>newContents = path.child(fname).getContent()<EOL>oldContents = filesContents[fname]<EOL>if newContents == oldContents:<EOL><INDENT>continue<EOL><DEDENT>receiver.remove(fname)<EOL>filesContents[fname] = newContents<EOL>receiver.add(fname, newContents)<EOL><DEDENT>files.clear()<EOL>files.update(currentFiles)<EOL><DEDENT>return functools.partial(_check, path)<EOL>

Construct a function that checks a directory for process configuration

    The function checks for additions or removals
    of JSON process configuration files and calls the appropriate receiver
    methods.

    :param location: string, the directory to monitor
    :param receiver: IEventReceiver
    :returns: a function with no parameters


path = filepath.FilePath(location)<EOL>def _check(path):<EOL><INDENT>messageFiles = path.globChildren('<STR_LIT:*>')<EOL>for message in messageFiles:<EOL><INDENT>if message.basename().endswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>receiver.message(message.getContent())<EOL>message.remove()<EOL><DEDENT><DEDENT>return functools.partial(_check, path)<EOL>

Construct a function that checks a directory for messages

    The function checks for new messages and
    calls the appropriate method on the receiver. Sent messages are
    deleted.

    :param location: string, the directory to monitor
    :param receiver: IEventReceiver
    :returns: a function with no parameters


if self.closed:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._maybeReset()<EOL>if self.url is None:<EOL><INDENT>return False<EOL><DEDENT>return self._maybeCheck()<EOL>


self.bad += <NUM_LIT:1><EOL>


self.bad = <NUM_LIT:0><EOL>


restarter, path = beatcheck.parseConfig(opt)<EOL>pool = client.HTTPConnectionPool(reactor)<EOL>agent = client.Agent(reactor=reactor, pool=pool)<EOL>settings = Settings(reactor=reactor, agent=agent)<EOL>states = {}<EOL>checker = functools.partial(check, settings, states, path)<EOL>httpcheck = tainternet.TimerService(opt['<STR_LIT>'], run, restarter, checker)<EOL>httpcheck.setName('<STR_LIT>')<EOL>return heart.wrapHeart(httpcheck)<EOL>

Make a service

    :params opt: dictionary-like object with 'freq', 'config' and 'messages'
    :returns: twisted.application.internet.TimerService that at opt['freq']
              checks for stale processes in opt['config'], and sends
              restart messages through opt['messages']


for bad in checker():<EOL><INDENT>restarter(bad)<EOL><DEDENT>

Run restarter on the checker's output

    :params restarter: something to run on the output of the checker
    :params checker: a function expected to get one argument (current time)
                     and return a list of stale names
    :params timer: a function of zero arguments, intended to return current
                   time
    :returns: None


def runProcess(args, timeout, grace, reactor):

deferred = defer.Deferred()<EOL>protocol = ProcessProtocol(deferred)<EOL>process = reactor.spawnProcess(protocol, args[<NUM_LIT:0>], args, env=os.environ)<EOL>def _logEnded(err):<EOL><INDENT>err.trap(tierror.ProcessDone, tierror.ProcessTerminated)<EOL>print(err.value)<EOL><DEDENT>deferred.addErrback(_logEnded)<EOL>def _cancelTermination(dummy):<EOL><INDENT>for termination in terminations:<EOL><INDENT>if termination.active():<EOL><INDENT>termination.cancel()<EOL><DEDENT><DEDENT><DEDENT>deferred.addCallback(_cancelTermination)<EOL>terminations = []<EOL>terminations.append(reactor.callLater(timeout, process.signalProcess,<EOL>"<STR_LIT>"))<EOL>terminations.append(reactor.callLater(timeout+grace,<EOL>process.signalProcess, "<STR_LIT>"))<EOL>return deferred<EOL>

Run a process, return a deferred that fires when it is done

    :params args: Process arguments
    :params timeout: Time before terminating process
    :params grace: Time before killing process after terminating it
    :params reactor: IReactorProcess and IReactorTime
    :returns: deferred that fires with success when the process ends,
              or fails if there was a problem spawning/terminating
              the process


pass<EOL>


if myEnv is None:<EOL><INDENT>myEnv = buildEnv()<EOL><DEDENT>oldEnviron = os.environ<EOL>def _cleanup():<EOL><INDENT>os.environ = oldEnviron<EOL><DEDENT>case.addCleanup(_cleanup)<EOL>os.environ = myEnv<EOL>

Replace environment temporarily, restoring it at end of test

    :params myEnv: a dict-like object


heartSer = makeService()<EOL>if heartSer is None:<EOL><INDENT>return<EOL><DEDENT>heartSer.setName('<STR_LIT>')<EOL>heartSer.setServiceParent(master)<EOL>

Add a heart to a service collection

    Add a heart to a service.IServiceCollector if
    the heart is not None.

    :params master: a service.IServiceCollector


contents = json.loads(contents.decode('<STR_LIT:utf-8>'))<EOL>tp = contents['<STR_LIT:type>']<EOL>if tp == '<STR_LIT>':<EOL><INDENT>self.monitor.stopProcess(contents['<STR_LIT:name>'])<EOL>log.msg("<STR_LIT>", contents['<STR_LIT:name>'])<EOL><DEDENT>elif tp == '<STR_LIT>':<EOL><INDENT>self.monitor.restartAll()<EOL>log.msg("<STR_LIT>")<EOL><DEDENT>elif tp == '<STR_LIT>':<EOL><INDENT>log.msg("<STR_LIT>", contents['<STR_LIT>'])<EOL>for name in self._groupToProcess[contents['<STR_LIT>']]:<EOL><INDENT>log.msg("<STR_LIT>", name)<EOL>self.monitor.stopProcess(name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>', contents)<EOL><DEDENT>

Respond to a restart or a restart-all message

        :params contents: string, contents of message
           parsed as JSON, and assumed to have a 'type'
           key, with value either 'restart' or 'restart-all'.
           If the value is 'restart', another key
           ('value') should exist with a logical process
           name.


self.monitor.removeProcess(name)<EOL>log.msg("<STR_LIT>", name)<EOL>for group in self._processToGroups.pop(name):<EOL><INDENT>self._groupToProcess[group].remove(name)<EOL><DEDENT>

Remove a process

        :params name: string, name of process


ns = PARSER.parse_args(argv[<NUM_LIT:1>:])<EOL>call(ns)<EOL>

command-line entry point

        --messages: messages directory

        --config: configuration directory

    subcommands:
        add:
            name (positional)

            --cmd (required) -- executable

            --arg -- add an argument

            --env -- add an environment variable (VAR=value)

            --uid -- set uid

            --gid -- set gid

            --extras -- a JSON file with more parameters

            --env-inherit -- add an environment variable to inherit

        remove:
            name (positional)
        restart:
            name (positional)
        restart-all:
            no arguments


content = _dumps(dict(type='<STR_LIT>', name=name))<EOL>_addMessage(places, content)<EOL>

Restart a process

    :params places: a Places instance
    :params name: string, the logical name of the process
    :returns: None


restarter, path = parseConfig(opt)<EOL>now = time.time()<EOL>checker = functools.partial(check, path, now)<EOL>beatcheck = tainternet.TimerService(opt['<STR_LIT>'], run, restarter,<EOL>checker, time.time)<EOL>beatcheck.setName('<STR_LIT>')<EOL>return heart.wrapHeart(beatcheck)<EOL>


for bad in checker(timer()):<EOL><INDENT>restarter(bad)<EOL><DEDENT>


places = ctllib.Places(config=opt['<STR_LIT>'], messages=opt['<STR_LIT>'])<EOL>restarter = functools.partial(ctllib.restart, places)<EOL>path = filepath.FilePath(opt['<STR_LIT>'])<EOL>return restarter, path<EOL>

Parse configuration

    :params opt: dict-like object with config and messages keys
    :returns: restarter, path


def hash_eth2(data: Union[bytes, bytearray]) -> Hash32:

return Hash32(keccak(data))<EOL>

Return Keccak-256 hashed result.
Note: it's a placeholder and we aim to migrate to a S[T/N]ARK-friendly hash function in
a future Ethereum 2.0 deployment phase.


def create_access_request(pid_value, users, confirmed):

datastore = current_app.extensions['<STR_LIT>'].datastore<EOL>receiver = datastore.get_user(users['<STR_LIT>']['<STR_LIT:id>'])<EOL>sender = datastore.get_user(users['<STR_LIT>']['<STR_LIT:id>'])<EOL>return AccessRequest.create(<EOL>recid=pid_value,<EOL>receiver=receiver,<EOL>sender_full_name="<STR_LIT>",<EOL>sender_email="<STR_LIT>",<EOL>sender=sender if confirmed else None,<EOL>justification="<STR_LIT>",<EOL>)<EOL>


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>from cryptography.fernet import Fernet<EOL>from cryptography.hazmat.backends import default_backend<EOL>from cryptography.hazmat.primitives import hashes<EOL>digest = hashes.Hash(hashes.SHA256(), backend=default_backend())<EOL>digest.update(current_app.config['<STR_LIT>'].encode('<STR_LIT:utf8>'))<EOL>fernet_key = urlsafe_b64encode(digest.finalize())<EOL>self._engine = Fernet(fernet_key)<EOL><DEDENT>return self._engine<EOL>


def __init__(self, expires_at=None, **kwargs):

assert isinstance(expires_at, datetime) or expires_at is None<EOL>dt = expires_at - datetime.now() if expires_at else None<EOL>super(TimedSecretLinkSerializer, self).__init__(<EOL>current_app.config['<STR_LIT>'],<EOL>expires_in=int(dt.total_seconds()) if dt else None,<EOL>salt='<STR_LIT>',<EOL>**kwargs<EOL>)<EOL>


if field.data and form.accept.data:<EOL><INDENT>raise validators.ValidationError(<EOL>_("<STR_LIT>")<EOL>)<EOL><DEDENT>


if col in self.options:<EOL><INDENT>if self.is_selected(col):<EOL><INDENT>return col if not self.asc else '<STR_LIT>'.format(col)<EOL><DEDENT>else:<EOL><INDENT>return col<EOL><DEDENT><DEDENT>return None<EOL>


self.options = options<EOL>if selected in options:<EOL><INDENT>self._selected = selected<EOL>self.asc = True<EOL><DEDENT>elif selected and selected[<NUM_LIT:0>] == '<STR_LIT:->' and selected[<NUM_LIT:1>:] in options:<EOL><INDENT>self._selected = selected[<NUM_LIT:1>:]<EOL>self.asc = False<EOL><DEDENT>else:<EOL><INDENT>self._selected = None<EOL>self.asc = None<EOL><DEDENT>

Initialize ordering with possible options the selected option.

        :param options: List of column options.
        :param selected: Selected column. Prefix name with ``-`` to denote
            descending ordering.


def dir(self, col, asc='<STR_LIT>', desc='<STR_LIT>'):

if col == self._selected and self.asc is not None:<EOL><INDENT>return asc if self.asc else desc<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Get direction (ascending/descending) of ordering.


pid, record = get_record(request.recid)<EOL>if record is None:<EOL><INDENT>current_app.logger.error("<STR_LIT>"<EOL>% request.recid)<EOL>return<EOL><DEDENT>title = _("<STR_LIT>", record=record["<STR_LIT:title>"])<EOL>_send_notification(<EOL>request.receiver.email,<EOL>title,<EOL>"<STR_LIT>",<EOL>request=request,<EOL>record=record,<EOL>pid=pid,<EOL>)<EOL>_send_notification(<EOL>request.sender_email,<EOL>title,<EOL>"<STR_LIT>",<EOL>request=request,<EOL>record=record,<EOL>pid=pid,<EOL>)<EOL>

Receiver for request-confirmed signal to send email notification.


def send_accept_notification(request, message=None, expires_at=None):

Receiver for request-accepted signal to send email notification.


def create_secret_link(request, message=None, expires_at=None):

pid, record = get_record(request.recid)<EOL>if not record:<EOL><INDENT>raise RecordNotFound(request.recid)<EOL><DEDENT>description = render_template(<EOL>"<STR_LIT>",<EOL>request=request,<EOL>record=record,<EOL>pid=pid,<EOL>expires_at=expires_at,<EOL>message=message,<EOL>)<EOL>request.create_secret_link(<EOL>record["<STR_LIT:title>"],<EOL>description=description,<EOL>expires_at=expires_at<EOL>)<EOL>


def _send_notification(to, subject, template, **ctx):

msg = Message(<EOL>subject,<EOL>sender=current_app.config.get('<STR_LIT>'),<EOL>recipients=[to]<EOL>)<EOL>msg.body = render_template(template, **ctx)<EOL>send_email.delay(msg.__dict__)<EOL>


self._icon = icon<EOL>


return cls.query.filter_by(<EOL>owner_user_id=user.id<EOL>)<EOL>


return not(self.is_expired() or self.is_revoked())<EOL>


return current_app.config['<STR_LIT>'].encode('<STR_LIT:utf-8>')<EOL>


with db.session.begin_nested():<EOL><INDENT>if self.status != RequestStatus.EMAIL_VALIDATION:<EOL><INDENT>raise InvalidRequestStateError(RequestStatus.EMAIL_VALIDATION)<EOL><DEDENT>self.status = RequestStatus.PENDING<EOL><DEDENT>request_confirmed.send(self)<EOL>


def confirm(pid, record, template, **kwargs):

recid = int(pid.pid_value)<EOL>token = request.view_args['<STR_LIT>']<EOL>data = EmailConfirmationSerializer.compat_validate_token(token)<EOL>if data is None:<EOL><INDENT>flash(_("<STR_LIT>"), category='<STR_LIT>')<EOL>return redirect(url_for("<STR_LIT>", pid_value=recid))<EOL><DEDENT>r = AccessRequest.query.get(data['<STR_LIT:id>'])<EOL>if not r:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>if r.status != RequestStatus.EMAIL_VALIDATION:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>r.confirm_email()<EOL>db.session.commit()<EOL>flash(_("<STR_LIT>"), category='<STR_LIT:info>')<EOL>return redirect(url_for("<STR_LIT>", pid_value=recid))<EOL>


result = u'<STR_LIT>'.join(u'<STR_LIT>' % p.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>for p in _paragraph_re.split(escape(value)))<EOL>if eval_ctx.autoescape:<EOL><INDENT>result = Markup(result)<EOL><DEDENT>return result<EOL>

Template filter to convert newlines to <br>-tags.


def propagate_astrometry(self, phi, theta, parallax, muphistar, mutheta, vrad, t0, t1):

t = t1-t0<EOL>p0, q0, r0 = normalTriad(phi, theta)<EOL>pmra0 = muphistar*self.mastorad<EOL>pmdec0 = mutheta*self.mastorad<EOL>plx0 = parallax*self.mastorad<EOL>pmr0 = vrad*parallax/auKmYearPerSec*self.mastorad<EOL>pmtot0sqr = (muphistar**<NUM_LIT:2> + mutheta**<NUM_LIT:2>) * self.mastorad**<NUM_LIT:2><EOL>pmvec0 = pmra0*p0+pmdec0*q0<EOL>f = (<NUM_LIT:1> + <NUM_LIT:2>*pmr0*t + (pmtot0sqr+pmr0**<NUM_LIT:2>)*t**<NUM_LIT:2>)**(-<NUM_LIT:0.5>)<EOL>u = (r0*(<NUM_LIT:1>+pmr0*t) + pmvec0*t)*f<EOL>_, phi1, theta1 = cartesianToSpherical(u[<NUM_LIT:0>], u[<NUM_LIT:1>], u[<NUM_LIT:2>])<EOL>parallax1 = parallax*f<EOL>pmr1 = (pmr0+(pmtot0sqr + pmr0**<NUM_LIT:2>)*t)*f**<NUM_LIT:2><EOL>pmvec1 = (pmvec0*(<NUM_LIT:1>+pmr0*t) - r0*pmr0**<NUM_LIT:2>*t)*f**<NUM_LIT:3><EOL>p1, q1, r1 = normalTriad(phi1, theta1)<EOL>muphistar1 = sum(p1*pmvec1/self.mastorad, axis=<NUM_LIT:0>)<EOL>mutheta1 = sum(q1*pmvec1/self.mastorad, axis =<NUM_LIT:0>)<EOL>murad1 = pmr1/self.mastorad<EOL>return phi1, theta1, parallax1, muphistar1, mutheta1, murad1<EOL>

Propagate the position of a source from the reference epoch t0 to the new epoch t1.

Parameters
----------

phi : float
    Longitude at reference epoch (radians).
theta : float
    Latitude at reference epoch (radians).
parallax : float
    Parallax at the reference epoch (mas).
muphistar : float
    Proper motion in longitude (including cos(latitude) term) at reference epoch (mas/yr).
mutheta : float
    Proper motion in latitude at reference epoch (mas/yr).
vrad : float
    Radial velocity at reference epoch (km/s).
t0 : float
    Reference epoch (Julian years).
t1 : float
    New epoch (Julian years).

Returns
-------

Astrometric parameters, including the "radial proper motion" (NOT the radial velocity), at the new epoch.
phi1, theta1, parallax1, muphistar1, mutheta1, mur1 = epoch_prop_pos(..., t0, t1)


def propagate_astrometry_and_covariance_matrix(self, a0, c0, t0, t1):

zero, one, two, three = <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3><EOL>tau = t1-t0<EOL>p0, q0, r0 = normalTriad(a0[<NUM_LIT:0>], a0[<NUM_LIT:1>])<EOL>par0 = a0[<NUM_LIT:2>]*self.mastorad<EOL>pma0 = a0[<NUM_LIT:3>]*self.mastorad<EOL>pmd0 = a0[<NUM_LIT:4>]*self.mastorad<EOL>pmr0 = a0[<NUM_LIT:5>]*a0[<NUM_LIT:2>]/auKmYearPerSec*self.mastorad<EOL>pmvec0 = pma0*p0+pmd0*q0<EOL>tau2 = tau*tau<EOL>pm02 = pma0**<NUM_LIT:2> + pmd0**<NUM_LIT:2><EOL>w = one + pmr0*tau<EOL>f2 = one/(one + two*pmr0*tau + (pm02+pmr0**<NUM_LIT:2>)*tau2)<EOL>f = sqrt(f2)<EOL>f3 = f2*f<EOL>f4 = f2*f2<EOL>u = (r0*w + pmvec0*tau)*f<EOL>_, ra, dec = cartesianToSpherical(u[<NUM_LIT:0>], u[<NUM_LIT:1>], u[<NUM_LIT:2>])<EOL>par = par0*f<EOL>pmvec = (pmvec0*(one+pmr0*tau) - r0*pmr0**<NUM_LIT:2>*tau)*f3<EOL>pmr = (pmr0+(pm02 + pmr0**<NUM_LIT:2>)*tau)*f2<EOL>p, q, r = normalTriad(ra, dec)<EOL>pma = sum(p*pmvec, axis=<NUM_LIT:0>)<EOL>pmd = sum(q*pmvec, axis =<NUM_LIT:0>)<EOL>a = zeros_like(a0)<EOL>a[<NUM_LIT:0>] = ra<EOL>a[<NUM_LIT:1>] = dec<EOL>a[<NUM_LIT:2>] = par/self.mastorad<EOL>a[<NUM_LIT:3>] = pma/self.mastorad<EOL>a[<NUM_LIT:4>] = pmd/self.mastorad<EOL>a[<NUM_LIT:5>] = pmr/self.mastorad<EOL>pmz = pmvec0*f - three*pmvec*w<EOL>pp0 = sum(p*p0, axis=<NUM_LIT:0>)<EOL>pq0 = sum(p*q0, axis=<NUM_LIT:0>)<EOL>pr0 = sum(p*r0, axis=<NUM_LIT:0>)<EOL>qp0 = sum(q*p0, axis=<NUM_LIT:0>)<EOL>qq0 = sum(q*q0, axis=<NUM_LIT:0>)<EOL>qr0 = sum(q*r0, axis=<NUM_LIT:0>)<EOL>ppmz = sum(p*pmz, axis=<NUM_LIT:0>)<EOL>qpmz = sum(q*pmz, axis=<NUM_LIT:0>)<EOL>J = zeros_like(c0)<EOL>if (c0.ndim==<NUM_LIT:2>):<EOL><INDENT>J = J[newaxis,:,:]<EOL><DEDENT>J[:,<NUM_LIT:0>,<NUM_LIT:0>] = pp0*w*f - pr0*pma0*tau*f<EOL>J[:,<NUM_LIT:0>,<NUM_LIT:1>] = pq0*w*f - pr0*pmd0*tau*f<EOL>J[:,<NUM_LIT:0>,<NUM_LIT:2>] = zero<EOL>J[:,<NUM_LIT:0>,<NUM_LIT:3>] = pp0*tau*f<EOL>J[:,<NUM_LIT:0>,<NUM_LIT:4>] = pq0*tau*f<EOL>J[:,<NUM_LIT:0>,<NUM_LIT:5>] = -pma*tau2<EOL>J[:,<NUM_LIT:1>,<NUM_LIT:0>] = qp0*w*f - qr0*pma0*tau*f<EOL>J[:,<NUM_LIT:1>,<NUM_LIT:1>] = qq0*w*f - qr0*pmd0*tau*f<EOL>J[:,<NUM_LIT:1>,<NUM_LIT:2>] = zero<EOL>J[:,<NUM_LIT:1>,<NUM_LIT:3>] = qp0*tau*f<EOL>J[:,<NUM_LIT:1>,<NUM_LIT:4>] = qq0*tau*f<EOL>J[:,<NUM_LIT:1>,<NUM_LIT:5>] = -pmd*tau2<EOL>J[:,<NUM_LIT:2>,<NUM_LIT:0>] = zero<EOL>J[:,<NUM_LIT:2>,<NUM_LIT:1>] = zero<EOL>J[:,<NUM_LIT:2>,<NUM_LIT:2>] = f<EOL>J[:,<NUM_LIT:2>,<NUM_LIT:3>] = -par*pma0*tau2*f2<EOL>J[:,<NUM_LIT:2>,<NUM_LIT:4>] = -par*pmd0*tau2*f2<EOL>J[:,<NUM_LIT:2>,<NUM_LIT:5>] = -par*w*tau*f2<EOL>J[:,<NUM_LIT:3>,<NUM_LIT:0>] = -pp0*pm02*tau*f3 - pr0*pma0*w*f3<EOL>J[:,<NUM_LIT:3>,<NUM_LIT:1>] = -pq0*pm02*tau*f3 - pr0*pmd0*w*f3<EOL>J[:,<NUM_LIT:3>,<NUM_LIT:2>] = zero<EOL>J[:,<NUM_LIT:3>,<NUM_LIT:3>] = pp0*w*f3 - two*pr0*pma0*tau*f3 - three*pma*pma0*tau2*f2<EOL>J[:,<NUM_LIT:3>,<NUM_LIT:4>] = pq0*w*f3 - two*pr0*pmd0*tau*f3 - three*pma*pmd0*tau2*f2<EOL>J[:,<NUM_LIT:3>,<NUM_LIT:5>] = ppmz*tau*f2<EOL>J[:,<NUM_LIT:4>,<NUM_LIT:0>] = -qp0*pm02*tau*f3 - qr0*pma0*w*f3<EOL>J[:,<NUM_LIT:4>,<NUM_LIT:1>] = -qq0*pm02*tau*f3 - qr0*pmd0*w*f3<EOL>J[:,<NUM_LIT:4>,<NUM_LIT:2>] = zero<EOL>J[:,<NUM_LIT:4>,<NUM_LIT:3>] = qp0*w*f3 - two*qr0*pma0*tau*f3 - three*pmd*pma0*tau2*f2<EOL>J[:,<NUM_LIT:4>,<NUM_LIT:4>] = qq0*w*f3 - two*qr0*pmd0*tau*f3 - three*pmd*pmd0*tau2*f2<EOL>J[:,<NUM_LIT:4>,<NUM_LIT:5>] = qpmz*tau*f2<EOL>J[:,<NUM_LIT:5>,<NUM_LIT:0>] = zero<EOL>J[:,<NUM_LIT:5>,<NUM_LIT:1>] = zero<EOL>J[:,<NUM_LIT:5>,<NUM_LIT:2>] = zero<EOL>J[:,<NUM_LIT:5>,<NUM_LIT:3>] = two*pma0*w*tau*f4<EOL>J[:,<NUM_LIT:5>,<NUM_LIT:4>] = two*pmd0*w*tau*f4<EOL>J[:,<NUM_LIT:5>,<NUM_LIT:5>] = (w**<NUM_LIT:2> - pm02*tau2)*f4<EOL>JT = zeros_like(J)<EOL>for i in range(J.shape[<NUM_LIT:0>]):<EOL><INDENT>JT[i] = J[i].T<EOL><DEDENT>if (c0.ndim==<NUM_LIT:2>):<EOL><INDENT>c = matmul(J,matmul(c0[newaxis,:,:],JT))<EOL><DEDENT>else:<EOL><INDENT>c = matmul(J,matmul(c0,JT))<EOL><DEDENT>return a, squeeze(c)<EOL>

Propagate the covariance matrix of the astrometric parameters and radial proper motion of a
source from epoch t0 to epoch t1.

Code based on the Hipparcos Fortran implementation by Lennart Lindegren.

Parameters
----------

a0 : array_like
    6-element vector: (phi, theta, parallax, muphistar, mutheta, vrad) in units of (radians,
    radians, mas, mas/yr, mas/yr, km/s). Shape of a should be (6,) or (6,N), with N the number of
    sources for which the astrometric parameters are provided.

c0 : array_like
    Covariance matrix stored in a 6x6 element array. This can be constructed from the columns
    listed in the Gaia catalogue. The units are [mas^2, mas^2/yr, mas^2/yr^2] for the various
    elements. Note that the elements in the 6th row and column should be:
    c[6,i]=c[i,6]=c[i,3]*vrad/auKmYearPerSec for i=1,..,5 and
    c[6,6]=c[3,3]*(vrad^2+vrad_error^2)/auKmYearPerSec^2+(parallax*vrad_error/auKmYearPerSec)^2

    Shape of c0 should be (6,6) or (N,6,6).

t0 : float
    Reference epoch (Julian years).

t1 : float
    New epoch (Julian years).

Returns
-------

Astrometric parameters, including the "radial proper motion" (NOT the radial velocity), and
covariance matrix at the new epoch as a 2D matrix with the new variances on the diagional and the
covariance in the off-diagonal elements.


def transformCartesianCoordinates(self, x, y, z):

xrot, yrot, zrot = dot(self.rotationMatrix,[x,y,z])<EOL>return xrot, yrot, zrot<EOL>

Rotates Cartesian coordinates from one reference system to another using the rotation matrix with
which the class was initialized. The inputs  can be scalars or 1-dimensional numpy arrays.

Parameters
----------

x - Value of X-coordinate in original reference system
y - Value of Y-coordinate in original reference system
z - Value of Z-coordinate in original reference system

Returns
-------

xrot - Value of X-coordinate after rotation
yrot - Value of Y-coordinate after rotation
zrot - Value of Z-coordinate after rotation


self.rotationMatrix=_rotationMatrixMap[desiredTransformation]<EOL>self.transformationStrings=_transformationStringMap[desiredTransformation]<EOL>

Class constructor/initializer. Sets the type of transformation to be used.

Parameters
----------

desiredTransformation - The kind of coordinate transformation that should be provided. For example
Transformations.GAL2ECL


def propagate_pos(self, phi, theta, parallax, muphistar, mutheta, vrad, t0, t1):

phi1, theta1, parallax1, muphistar1, mutheta1, vrad1 = self.epoch_prop_astrometry(phi, theta, parallax, muphistar, mutheta, vrad, t0, t1)<EOL>return phi1, theta1<EOL>

Propagate the position of a source from the reference epoch t0 to the new epoch t1.

Parameters
----------

phi : float
    Longitude at reference epoch (radians).
theta : float
    Latitude at reference epoch (radians).
parallax : float
    Parallax at the reference epoch (mas).
muphistar : float
    Proper motion in longitude (including cos(latitude) term) at reference epoch (mas/yr).
mutheta : float
    Proper motion in latitude at reference epoch (mas/yr).
vrad : float
    Radial velocity at reference epoch (km/s).
t0 : float
    Reference epoch (Julian years).
t1 : float
    New epoch (Julian years).

Returns
-------

Coordinates phi and theta at new epoch (in radians)


def transformSkyCoordinateErrors(self, phi, theta, sigPhiStar, sigTheta, rhoPhiTheta=<NUM_LIT:0>):

if isscalar(rhoPhiTheta) and not isscalar(sigTheta):<EOL><INDENT>rhoPhiTheta=zeros_like(sigTheta)+rhoPhiTheta<EOL><DEDENT>c, s = self._getJacobian(phi,theta)<EOL>cSqr = c*c<EOL>sSqr = s*s<EOL>covar = sigPhiStar*sigTheta*rhoPhiTheta<EOL>varPhiStar = sigPhiStar*sigPhiStar<EOL>varTheta = sigTheta*sigTheta<EOL>varPhiStarRot = cSqr*varPhiStar+sSqr*varTheta+<NUM_LIT>*covar*c*s<EOL>varThetaRot = sSqr*varPhiStar+cSqr*varTheta-<NUM_LIT>*covar*c*s<EOL>covarRot = (cSqr-sSqr)*covar+c*s*(varTheta-varPhiStar)<EOL>return sqrt(varPhiStarRot), sqrt(varThetaRot), covarRot/sqrt(varPhiStarRot*varThetaRot)<EOL>

Converts the sky coordinate errors from one reference system to another, including the covariance
term. Equations (1.5.4) and (1.5.20) from section 1.5 in the Hipparcos Explanatory Volume 1 are used.

Parameters
----------

phi         - The longitude-like angle of the position of the source (radians).
theta       - The latitude-like angle of the position of the source (radians).
sigPhiStar  - Standard error in the longitude-like angle of the position of the source (radians or
              sexagesimal units, including cos(latitude) term)
sigTheta    - Standard error in the latitude-like angle of the position of the source (radians or
              sexagesimal units)

Keywords (optional)
-------------------

rhoPhiTheta - Correlation coefficient of the position errors. Set to zero if this keyword is not
              provided.

Retuns
------

sigPhiRotStar  - The transformed standard error in the longitude-like angle (including
                 cos(latitude) factor)
sigThetaRot    - The transformed standard error in the latitude-like angle.
rhoPhiThetaRot - The transformed correlation coefficient.


def phaseSpaceToAstrometry(x, y, z, vx, vy, vz):

u, phi, theta = cartesianToSpherical(x, y, z)<EOL>parallax = _auMasParsec/u<EOL>p, q, r = normalTriad(phi, theta)<EOL>velocitiesArray=array([vx,vy,vz])<EOL>if  isscalar(u):<EOL><INDENT>muphistar=dot(p,velocitiesArray)*parallax/_auKmYearPerSec<EOL>mutheta=dot(q,velocitiesArray)*parallax/_auKmYearPerSec<EOL>vrad=dot(r,velocitiesArray)<EOL><DEDENT>else:<EOL><INDENT>muphistar=zeros_like(parallax)<EOL>mutheta=zeros_like(parallax)<EOL>vrad=zeros_like(parallax)<EOL>for i in range(parallax.size):<EOL><INDENT>muphistar[i]=dot(p[:,i],velocitiesArray[:,i])*parallax[i]/_auKmYearPerSec<EOL>mutheta[i]=dot(q[:,i],velocitiesArray[:,i])*parallax[i]/_auKmYearPerSec<EOL>vrad[i]=dot(r[:,i],velocitiesArray[:,i])<EOL><DEDENT><DEDENT>return phi, theta, parallax, muphistar, mutheta, vrad<EOL>

From the given phase space coordinates calculate the astrometric observables, including the radial
velocity, which here is seen as the sixth astrometric parameter. The phase space coordinates are
assumed to represent barycentric (i.e. centred on the Sun) positions and velocities.

This function has no mechanism to deal with units. The velocity units are always assumed to be km/s,
and the code is set up such that for positions in pc, the return units for the astrometry are radians,
milliarcsec, milliarcsec/year and km/s. For positions in kpc the return units are: radians,
microarcsec, microarcsec/year, and km/s.

NOTE that the doppler factor k=1/(1-vrad/c) is NOT used in the calculations. This is not a problem for
sources moving at typical velocities of Galactic stars.

Parameters
----------

x - The x component of the barycentric position vector (in pc or kpc).
y - The y component of the barycentric position vector (in pc or kpc).
z - The z component of the barycentric position vector (in pc or kpc).
vx - The x component of the barycentric velocity vector (in km/s).
vy - The y component of the barycentric velocity vector (in km/s).
vz - The z component of the barycentric velocity vector (in km/s).

Returns
-------

phi       - The longitude-like angle of the position of the source (radians).
theta     - The latitude-like angle of the position of the source (radians).
parallax  - The parallax of the source (in mas or muas, see above)
muphistar - The proper motion in the longitude-like angle, multiplied by cos(theta) (mas/yr or muas/yr,
see above)
mutheta   - The proper motion in the latitude-like angle (mas/yr or muas/yr, see above)
vrad      - The radial velocity (km/s)


if (axis=="<STR_LIT:x>" or axis=="<STR_LIT:X>"):<EOL><INDENT>return array([[<NUM_LIT:1.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>], [<NUM_LIT:0.0>, cos(rotationAngle), sin(rotationAngle)], [<NUM_LIT:0.0>,<EOL>-sin(rotationAngle), cos(rotationAngle)]])<EOL><DEDENT>elif (axis=="<STR_LIT:y>" or axis=="<STR_LIT:Y>"):<EOL><INDENT>return array([[cos(rotationAngle), <NUM_LIT:0.0>, -sin(rotationAngle)], [<NUM_LIT:0.0>, <NUM_LIT:1.0>, <NUM_LIT:0.0>], [sin(rotationAngle),<EOL><NUM_LIT:0.0>, cos(rotationAngle)]])<EOL><DEDENT>elif (axis=="<STR_LIT:z>" or axis=="<STR_LIT>"):<EOL><INDENT>return array([[cos(rotationAngle), sin(rotationAngle), <NUM_LIT:0.0>], [-sin(rotationAngle),<EOL>cos(rotationAngle), <NUM_LIT:0.0>], [<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>]])<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>"+axis+"<STR_LIT:!>")<EOL><DEDENT>

Construct an elementary rotation matrix describing a rotation around the x, y, or z-axis.

Parameters
----------

axis          - Axis around which to rotate ("x", "y", or "z")
rotationAngle - the rotation angle in radians

Returns
-------

The rotation matrix

Example usage
-------------

rotmat = elementaryRotationMatrix("y", pi/6.0)


def sphericalToCartesian(r, phi, theta):

ctheta=cos(theta)<EOL>x=r*cos(phi)*ctheta<EOL>y=r*sin(phi)*ctheta<EOL>z=r*sin(theta)<EOL>return x, y, z<EOL>

Convert spherical to Cartesian coordinates. The input can be scalars or 1-dimensional numpy arrays.
Note that the angle coordinates follow the astronomical convention of using elevation (declination,
latitude) rather than its complement (pi/2-elevation), where the latter is commonly used in the
mathematical treatment of spherical coordinates.

Parameters
----------

r     - length of input Cartesian vector.
phi   - longitude-like angle (e.g., right ascension, ecliptic longitude) in radians
theta - latitide-like angle (e.g., declination, ecliptic latitude) in radians

Returns
-------

The Cartesian vector components x, y, z


varDiag1 = rand(num)*<NUM_LIT>+<NUM_LIT:1.0><EOL>varDiag2 = rand(num)*<NUM_LIT>+<NUM_LIT:1.0><EOL>rotAngle = <NUM_LIT>*pi*rand(num)<EOL>sigma1 = zeros(num)<EOL>sigma2 = zeros(num)<EOL>rho12 = zeros(num)<EOL>for i in range(num): <EOL><INDENT>rotationMatrix=array([[cos(rotAngle[i]), sin(rotAngle[i])], [-sin(rotAngle[i]), cos(rotAngle[i])]])<EOL>covMatrix = dot(rotationMatrix,dot(diag([varDiag1[i],varDiag2[i]]),transpose(rotationMatrix)))<EOL>sigma1[i] = sqrt(covMatrix[<NUM_LIT:0>,<NUM_LIT:0>])<EOL>sigma2[i] = sqrt(covMatrix[<NUM_LIT:1>,<NUM_LIT:1>])<EOL>rho12[i] = covMatrix[<NUM_LIT:0>,<NUM_LIT:1>]/(sigma1[i]*sigma2[i])<EOL><DEDENT>return sigma1, sigma2, rho12<EOL>

Generate random covariance matrices through the transformation of diagonal positive definite
matrices.

Parameters
----------

num - Number of matrices to generate.

Returns
-------

sigma1 - Square root of variance of first variable.
sigma2 - Square root of variance of second variable.
rho12  - Correlation coefficient between errors on variables 1 and 2


if allclose(A, A.T, rtol=<NUM_LIT>, atol=<NUM_LIT>):<EOL><INDENT>try:<EOL><INDENT>cholesky(A)<EOL>return True<EOL><DEDENT>except LinAlgError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Check if matrix A is positive definite. Code from
https://stackoverflow.com/questions/16266720/find-out-if-matrix-is-positive-definite-with-numpy


z=calcZBpRp(G)<EOL>a = -<NUM_LIT>*power(vmini,<NUM_LIT:3>) + <NUM_LIT>*vmini*vmini - <NUM_LIT>*vmini + <NUM_LIT><EOL>b = -<NUM_LIT>*power(vmini,<NUM_LIT:3>) + <NUM_LIT>*vmini*vmini - <NUM_LIT>*vmini + <NUM_LIT><EOL>c = -<NUM_LIT>*power(vmini,<NUM_LIT:3>) + <NUM_LIT>*vmini*vmini - <NUM_LIT>*vmini - <NUM_LIT><EOL>return <NUM_LIT>*sqrt(power(<NUM_LIT>,a)*z*z+power(<NUM_LIT>,b)*z+power(<NUM_LIT>,c))<EOL>

Calculate the single-field-of-view-transit photometric standard error in the RP band as a function
of G and (V-I). Note: this refers to the integrated flux from the RP spectrophotometer. A margin of 20%
is included.

Parameters
----------

G     - Value(s) of G-band magnitude.
vmini - Value(s) of (V-I) colour.

Returns
-------

The RP band photometric standard error in units of magnitude.


Calculate the value for the parameter z in the formula for the BP and RP magnitude errors as a
function of G and (V-I).

Parameters
----------

G - Value of G-band magnitude.

Returns
-------

Value of z for BP/RP.


return _vradCalibrationFloor + _vradErrorBCoeff[spt]*exp(_vradErrorACoeff[spt]*(vmag-_vradMagnitudeZeroPoint))<EOL>

Calculate radial velocity error from V and the spectral type. The value of the error is an average over
the sky.

Parameters
----------

vmag - Value of V-band magnitude.
spt  - String representing the spectral type of the star.

Returns
-------

The radial velocity error in km/s.


def positionMinError(G, vmini, extension=<NUM_LIT:0.0>):

parallaxError = parallaxErrorSkyAvg(G, vmini, extension=extension)<EOL>return _astrometricErrorFactors['<STR_LIT>'].min()*parallaxError,_astrometricErrorFactors['<STR_LIT>'].min()*parallaxError<EOL>

Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.

NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ALSO ON THE ICRS.

Parameters
----------

G     - Value(s) of G-band magnitude.
vmini - Value(s) of (V-I) colour.

Keywords
--------

extension - Add this amount of years to the mission lifetime and scale the errors accordingly.

Returns
-------

The minimum error in alpha* and the error in delta, in that order, in micro-arcsecond.


return power((_nominalLifeTime+extension)/_nominalLifeTime, p)<EOL>

Calculate the factor by which to scale errors for a given Gaia mission extension.

Parameters
----------

extension - The mission extension in years (a negative extension can be used to make crude
performance predictions part-way through the mission lifetime).
p - The power by which the errors scale with time (error ~ t^p, p=-0.5 for parallax and celestial
position, and -1.5 for proper motion).

Returns
-------

The factor by which to scale the errors


def positionMaxError(G, vmini, extension=<NUM_LIT:0.0>):

parallaxError = parallaxErrorSkyAvg(G, vmini, extension)<EOL>return _astrometricErrorFactors['<STR_LIT>'].max()*parallaxError,_astrometricErrorFactors['<STR_LIT>'].max()*parallaxError<EOL>

Calculate the maximum position errors from G and (V-I). These correspond to the sky regions with the
largest astrometric errors.

NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ALSO ON THE ICRS.

Parameters
----------

G     - Value(s) of G-band magnitude.
vmini - Value(s) of (V-I) colour.

Keywords
--------

extension - Add this amount of years to the mission lifetime and scale the errors accordingly.

Returns
-------

The maximum error in alpha* and the error in delta, in that order, in micro-arcsecond.


def parallaxMaxError(G, vmini, extension=<NUM_LIT:0.0>):

errors = _astrometricErrorFactors["<STR_LIT>"].max()*parallaxErrorSkyAvg(G, vmini, extension=extension)<EOL>indices = (errors<_parallaxErrorMaxBright)<EOL>errors[indices]=_parallaxErrorMaxBright<EOL>return errors<EOL>

Calculate the maximum parallax error from G and (V-I). This correspond to the sky regions with the
largest astrometric errors.  At the bright end the parallax error is at least 14 muas due to the
gating scheme.

Parameters
----------

G     - Value(s) of G-band magnitude.
vmini - Value(s) of (V-I) colour.

Keywords
--------

extension - Add this amount of years to the mission lifetime and scale the errors accordingly.

Returns
-------

The maximum parallax error in micro-arcseconds.


def parallaxMinError(G, vmini, extension=<NUM_LIT:0.0>):

return _astrometricErrorFactors["<STR_LIT>"].min()*parallaxErrorSkyAvg(G, vmini, extension=extension)<EOL>

Calculate the minimum parallax error from G and (V-I). This correspond to the sky regions with the
smallest astrometric errors.  At the bright end the parallax error is at least 14 muas due to the
gating scheme.

Parameters
----------

G     - Value(s) of G-band magnitude.
vmini - Value(s) of (V-I) colour.

Keywords
--------

extension - Add this amount of years to the mission lifetime and scale the errors accordingly.

Returns
-------

The minimum parallax error in micro-arcseconds.


return angle/<NUM_LIT>*np.pi<EOL>

Convert from degrees to radians.

Parameters
----------

angle - angle in degrees

Returns
-------

Angle in radians.


parser = argparse.ArgumentParser(description="""<STR_LIT>""")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>args=vars(parser.parse_args())<EOL>return args<EOL>


Plot relative parallax errors as a function of distance for stars of a given spectral type.

Parameters
----------

args - command line arguments


parser = argparse.ArgumentParser(description="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", dest="<STR_LIT>", type=float, help="<STR_LIT>", default=<NUM_LIT:0.0>)<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>args=vars(parser.parse_args())<EOL>return args<EOL>


gmag=np.linspace(<NUM_LIT>,<NUM_LIT>,<NUM_LIT>)<EOL>vmini = args['<STR_LIT>']<EOL>vmag=gmag-gminvFromVmini(vmini)<EOL>if args['<STR_LIT>']:<EOL><INDENT>sigmaG = gMagnitudeErrorEoM(gmag)<EOL>sigmaGBp = bpMagnitudeErrorEoM(gmag, vmini)<EOL>sigmaGRp = rpMagnitudeErrorEoM(gmag, vmini)<EOL>yminmax = (<NUM_LIT:1.0>-<NUM_LIT:4>,<NUM_LIT:0.1>)<EOL><DEDENT>else:<EOL><INDENT>sigmaG = gMagnitudeError(gmag)<EOL>sigmaGBp = bpMagnitudeError(gmag, vmini)<EOL>sigmaGRp = rpMagnitudeError(gmag, vmini)<EOL>yminmax = (<NUM_LIT:1.0>-<NUM_LIT:4>,<NUM_LIT:1>)<EOL><DEDENT>fig=plt.figure(figsize=(<NUM_LIT:10>,<NUM_LIT>))<EOL>if (args['<STR_LIT>']):<EOL><INDENT>plt.semilogy(vmag, sigmaG, '<STR_LIT:k>', label='<STR_LIT>')<EOL>plt.semilogy(vmag, sigmaGBp, '<STR_LIT:b>', label='<STR_LIT>'+'<STR_LIT>'.format(vmini))<EOL>plt.semilogy(vmag, sigmaGRp, '<STR_LIT:r>', label='<STR_LIT>'+'<STR_LIT>'.format(vmini))<EOL>plt.xlim((<NUM_LIT:6>,<NUM_LIT:20>))<EOL>plt.legend(loc=<NUM_LIT:0>)<EOL>plt.xlabel('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>ax=fig.add_subplot(<NUM_LIT>)<EOL>plt.semilogy(gmag, sigmaG, '<STR_LIT:k>', label='<STR_LIT>')<EOL>plt.semilogy(gmag, sigmaGBp, '<STR_LIT:b>', label='<STR_LIT>'+'<STR_LIT>'.format(vmini))<EOL>plt.semilogy(gmag, sigmaGRp, '<STR_LIT:r>', label='<STR_LIT>'+'<STR_LIT>'.format(vmini))<EOL>plt.xlim((<NUM_LIT:6>,<NUM_LIT:20>))<EOL>plt.legend(loc=<NUM_LIT:0>)<EOL>plt.xlabel('<STR_LIT>')<EOL><DEDENT>plt.xticks(np.arange(<NUM_LIT:6>,<NUM_LIT:20>,<NUM_LIT:2>))<EOL>ax = plt.gca().yaxis <EOL>plt.grid(which='<STR_LIT>')<EOL>plt.ylabel('<STR_LIT>')<EOL>if args['<STR_LIT>']:<EOL><INDENT>plt.title('<STR_LIT>'.format(vmini), fontsize=<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>plt.title('<STR_LIT>'.format(vmini), fontsize=<NUM_LIT>)<EOL><DEDENT>basename = '<STR_LIT>'<EOL>if (args['<STR_LIT>']):<EOL><INDENT>plt.savefig(basename+'<STR_LIT>')<EOL><DEDENT>elif (args['<STR_LIT>']):<EOL><INDENT>plt.savefig(basename+'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plt.show()<EOL><DEDENT>

Make the plot with photometry performance predictions.

:argument args: command line arguments


def makePlot(gmag, pdf=False, png=False, rvs=False):

Make a plot of a Mv vs (V-I) colour magnitude diagram containing lines of constant distance for stars
at G=20. This will give an idea of the reach of Gaia.

Parameters
----------

args - command line arguments


parser = argparse.ArgumentParser(description="""<STR_LIT>""")<EOL>parser.add_argument("<STR_LIT>", help="<STR_LIT>", type=float)<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>args=vars(parser.parse_args())<EOL>return args<EOL>


gRvs=np.linspace(<NUM_LIT>,<NUM_LIT>,<NUM_LIT>)<EOL>spts=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>fig=plt.figure(figsize=(<NUM_LIT:10>,<NUM_LIT>))<EOL>deltaHue = <NUM_LIT>/(len(spts)-<NUM_LIT:1>)<EOL>hsv=np.zeros((<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:3>))<EOL>hsv[<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>]=<NUM_LIT:1.0><EOL>hsv[<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:2>]=<NUM_LIT><EOL>count=<NUM_LIT:0><EOL>for spt in spts:<EOL><INDENT>hsv[<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>]=(<NUM_LIT>-count*deltaHue)/<NUM_LIT><EOL>vmag = vminGrvsFromVmini(vminiFromSpt(spt)) + gRvs<EOL>vradErrors = vradErrorSkyAvg(vmag, spt)<EOL>plt.plot(vmag, vradErrors, '<STR_LIT:->', label=spt, color=hsv_to_rgb(hsv)[<NUM_LIT:0>,<NUM_LIT:0>,:])<EOL>count+=<NUM_LIT:1><EOL><DEDENT>plt.grid(which='<STR_LIT>')<EOL>plt.xlim(<NUM_LIT:9>,<NUM_LIT>)<EOL>plt.ylim(<NUM_LIT:0>,<NUM_LIT:20>)<EOL>plt.xticks(np.arange(<NUM_LIT:9>,<NUM_LIT>,<NUM_LIT:1>))<EOL>plt.yticks(np.arange(<NUM_LIT:0>,<NUM_LIT>,<NUM_LIT:5>))<EOL>plt.xlabel('<STR_LIT>')<EOL>plt.ylabel('<STR_LIT>')<EOL>leg=plt.legend(loc=<NUM_LIT:0>,  handlelength=<NUM_LIT>, labelspacing=<NUM_LIT>)<EOL>for t in leg.get_texts():<EOL><INDENT>t.set_fontsize(<NUM_LIT:12>)<EOL><DEDENT>if (args['<STR_LIT>']):<EOL><INDENT>plt.savefig('<STR_LIT>')<EOL><DEDENT>elif (args['<STR_LIT>']):<EOL><INDENT>plt.savefig('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plt.show()<EOL><DEDENT>

Make the plot with radial velocity performance predictions.

:argument args: command line arguments


parser = argparse.ArgumentParser(description="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>", help="<STR_LIT>")<EOL>args=vars(parser.parse_args())<EOL>return args<EOL>


gmag=np.linspace(<NUM_LIT>,<NUM_LIT>,<NUM_LIT>)<EOL>vminiB1V=vminiFromSpt('<STR_LIT>')<EOL>vminiG2V=vminiFromSpt('<STR_LIT>')<EOL>vminiM6V=vminiFromSpt('<STR_LIT>')<EOL>vmagB1V=gmag-gminvFromVmini(vminiB1V)<EOL>vmagG2V=gmag-gminvFromVmini(vminiG2V)<EOL>vmagM6V=gmag-gminvFromVmini(vminiM6V)<EOL>sigmualphaB1V, sigmudeltaB1V = properMotionErrorSkyAvg(gmag,vminiB1V)<EOL>sigmuB1V = np.sqrt(<NUM_LIT:0.5>*sigmualphaB1V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaB1V**<NUM_LIT:2>)<EOL>sigmualphaB1V, sigmudeltaB1V = properMotionMinError(gmag,vminiB1V)<EOL>sigmuB1Vmin = np.sqrt(<NUM_LIT:0.5>*sigmualphaB1V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaB1V**<NUM_LIT:2>)<EOL>sigmualphaB1V, sigmudeltaB1V = properMotionMaxError(gmag,vminiB1V)<EOL>sigmuB1Vmax = np.sqrt(<NUM_LIT:0.5>*sigmualphaB1V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaB1V**<NUM_LIT:2>)<EOL>sigmualphaG2V, sigmudeltaG2V = properMotionErrorSkyAvg(gmag,vminiG2V)<EOL>sigmuG2V = np.sqrt(<NUM_LIT:0.5>*sigmualphaG2V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaG2V**<NUM_LIT:2>)<EOL>sigmualphaG2V, sigmudeltaG2V = properMotionMinError(gmag,vminiG2V)<EOL>sigmuG2Vmin = np.sqrt(<NUM_LIT:0.5>*sigmualphaG2V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaG2V**<NUM_LIT:2>)<EOL>sigmualphaG2V, sigmudeltaG2V = properMotionMaxError(gmag,vminiG2V)<EOL>sigmuG2Vmax = np.sqrt(<NUM_LIT:0.5>*sigmualphaG2V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaG2V**<NUM_LIT:2>)<EOL>sigmualphaM6V, sigmudeltaM6V = properMotionErrorSkyAvg(gmag,vminiM6V)<EOL>sigmuM6V = np.sqrt(<NUM_LIT:0.5>*sigmualphaM6V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaM6V**<NUM_LIT:2>)<EOL>sigmualphaM6V, sigmudeltaM6V = properMotionMinError(gmag,vminiM6V)<EOL>sigmuM6Vmin = np.sqrt(<NUM_LIT:0.5>*sigmualphaM6V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaM6V**<NUM_LIT:2>)<EOL>sigmualphaM6V, sigmudeltaM6V = properMotionMaxError(gmag,vminiM6V)<EOL>sigmuM6Vmax = np.sqrt(<NUM_LIT:0.5>*sigmualphaM6V**<NUM_LIT:2>+<NUM_LIT:0.5>*sigmudeltaM6V**<NUM_LIT:2>)<EOL>fig=plt.figure(figsize=(<NUM_LIT:10>,<NUM_LIT>))<EOL>if (args['<STR_LIT>']):<EOL><INDENT>plt.semilogy(gmag, sigmuB1V, '<STR_LIT:b>', label='<STR_LIT>')<EOL>plt.semilogy(gmag, sigmuG2V, '<STR_LIT:g>', label='<STR_LIT>')<EOL>plt.semilogy(gmag, sigmuM6V, '<STR_LIT:r>', label='<STR_LIT>')<EOL>plt.xlim((<NUM_LIT:5>,<NUM_LIT:20>))<EOL>plt.ylim((<NUM_LIT:1>,<NUM_LIT>))<EOL>plt.legend(loc=<NUM_LIT:4>)<EOL><DEDENT>else:<EOL><INDENT>ax=fig.add_subplot(<NUM_LIT>)<EOL>plt.semilogy(vmagB1V, sigmuB1V, '<STR_LIT:b>', label='<STR_LIT>')<EOL>plt.semilogy(vmagM6V, sigmuM6V, '<STR_LIT:r>', label='<STR_LIT>')<EOL>plt.fill_between(vmagB1V, sigmuB1Vmin, sigmuB1Vmax, color='<STR_LIT:b>', alpha=<NUM_LIT>)<EOL>plt.fill_between(vmagM6V, sigmuM6Vmin, sigmuM6Vmax, color='<STR_LIT:r>', alpha=<NUM_LIT>)<EOL>plt.xlim((<NUM_LIT:5>,<NUM_LIT>))<EOL>plt.ylim((<NUM_LIT:1>,<NUM_LIT>))<EOL>plt.text(<NUM_LIT>,<NUM_LIT:100>,'<STR_LIT>',color='<STR_LIT:b>')<EOL>plt.text(<NUM_LIT>,<NUM_LIT:10>,'<STR_LIT>',color='<STR_LIT:r>')<EOL>plt.text(<NUM_LIT:7>,<NUM_LIT:11>,'<STR_LIT>', size=<NUM_LIT:12>, bbox=dict(boxstyle="<STR_LIT>",<EOL>ec=(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>),<EOL>fc=(<NUM_LIT:1.0>, <NUM_LIT:1.0>, <NUM_LIT:1.0>),<EOL>))<EOL>plt.text(<NUM_LIT>,<NUM_LIT:50>,'<STR_LIT>', rotation=<NUM_LIT>, size=<NUM_LIT:12>, bbox=dict(boxstyle="<STR_LIT>",<EOL>ec=(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>),<EOL>fc=(<NUM_LIT:1.0>, <NUM_LIT:1.0>, <NUM_LIT:1.0>),<EOL>))<EOL>ax.annotate('<STR_LIT>', xy=(<NUM_LIT>, <NUM_LIT>),  xycoords='<STR_LIT:data>',<EOL>xytext=(<NUM_LIT>,<NUM_LIT:30>), textcoords='<STR_LIT:data>', ha='<STR_LIT>', size='<STR_LIT>',<EOL>bbox=dict(boxstyle="<STR_LIT>",ec=(<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>),fc=(<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:1>)),<EOL>arrowprops=dict(facecolor='<STR_LIT>', shrink=<NUM_LIT>, width=<NUM_LIT:1>,<EOL>headwidth=<NUM_LIT:6>),<EOL>horizontalalignment='<STR_LIT:right>', verticalalignment='<STR_LIT>',<EOL>)<EOL>ax.annotate('<STR_LIT>', xy=(<NUM_LIT>, <NUM_LIT>),  xycoords='<STR_LIT:data>',<EOL>xytext=(<NUM_LIT>,<NUM_LIT>), textcoords='<STR_LIT:data>', ha='<STR_LIT>', size='<STR_LIT>',<EOL>arrowprops=dict(facecolor='<STR_LIT>', shrink=<NUM_LIT>, width=<NUM_LIT:1>,<EOL>headwidth=<NUM_LIT:6>),<EOL>horizontalalignment='<STR_LIT:right>', verticalalignment='<STR_LIT>',<EOL>)<EOL><DEDENT>plt.xticks(np.arange(<NUM_LIT:6>,<NUM_LIT>,<NUM_LIT:2>))<EOL>ax = plt.gca().yaxis <EOL>ax.set_major_formatter(matplotlib.ticker.ScalarFormatter())<EOL>plt.ticklabel_format(axis='<STR_LIT:y>',style='<STR_LIT>')<EOL>plt.grid(which='<STR_LIT>')<EOL>plt.xlabel('<STR_LIT>')<EOL>plt.ylabel('<STR_LIT>')<EOL>basename = '<STR_LIT>'<EOL>if (args['<STR_LIT>']):<EOL><INDENT>plt.savefig(basename+'<STR_LIT>')<EOL><DEDENT>elif (args['<STR_LIT>']):<EOL><INDENT>plt.savefig(basename+'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plt.show()<EOL><DEDENT>

Make the plot with proper motion performance predictions. The predictions are for the TOTAL proper
motion under the assumption of equal components mu_alpha* and mu_delta.

:argument args: command line arguments


parser = argparse.ArgumentParser(description="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", help="<STR_LIT>", type=float)<EOL>parser.add_argument("<STR_LIT>", help="<STR_LIT>", type=float)<EOL>args=vars(parser.parse_args())<EOL>return args<EOL>


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>def mlt(self, index, doc_type, id, body=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request(<EOL>'<STR_LIT:GET>', _make_path(index, doc_type, id, '<STR_LIT>'),<EOL>params=params, body=body)<EOL>raise gen.Return(data)<EOL>

Get documents that are "like" a specified document.
`<http://elasticsearch.org/guide/reference/api/more-like-this/>`_

:arg index: The name of the index
:arg doc_type: The type of the document (use `_all` to fetch the first
    document matching the ID across all types)
:arg id: The document ID
:arg body: A specific search request definition
:arg boost_terms: The boost factor
:arg max_doc_freq: The word occurrence frequency as count: words with
    higher occurrence in the corpus will be ignored
:arg max_query_terms: The maximum query terms to be included in the
    generated query
:arg max_word_len: The minimum length of the word: longer words will
    be ignored
:arg min_doc_freq: The word occurrence frequency as count: words with
    lower occurrence in the corpus will be ignored
:arg min_term_freq: The term frequency as percent: terms with lower
    occurrence in the source document will be ignored
:arg min_word_len: The minimum length of the word: shorter words will
    be ignored
:arg mlt_fields: Specific fields to perform the query against
:arg percent_terms_to_match: How many terms have to match in order to
    consider the document a match (default: 0.3)
:arg routing: Specific routing value
:arg search_from: The offset from which to return results
:arg search_indices: A comma-separated list of indices to perform the
    query against (default: the index containing the document)
:arg search_query_hint: The search query hint
:arg search_scroll: A scroll search request definition
:arg search_size: The number of documents to return (default: 10)
:arg search_source: A specific search request definition (instead of
    using the request body)
:arg search_type: Specific search type (eg. `dfs_then_fetch`, `count`,
    etc)
:arg search_types: A comma-separated list of types to perform the query
    against (default: the same type as the document)
:arg stop_words: A list of stop words to be ignored


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT:source>')<EOL>def count(self, index=None, doc_type=None, body=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request('<STR_LIT:POST>',<EOL>_make_path(index,<EOL>doc_type,<EOL>'<STR_LIT>'),<EOL>params=params, body=body)<EOL>raise gen.Return(data)<EOL>

Execute a query and get the number of matches for that query.
`<http://elasticsearch.org/guide/reference/api/count/>`_

:arg index: A comma-separated list of indices to restrict the results
:arg doc_type: A comma-separated list of types to restrict the results
:arg body: A query to restrict the results (optional)
:arg ignore_indices: When performed on multiple indices, allows to
    ignore `missing` ones (default: none)
:arg min_score: Include only documents with a specific `_score` value
    in the result
:arg preference: Specify the node or shard the operation should be
    performed on (default: random)
:arg routing: Specific routing value
:arg source: The URL-encoded query definition (instead of using the
    request body)


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT:q>', '<STR_LIT>', '<STR_LIT:source>')<EOL>def explain(self, index, doc_type, id, body=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request('<STR_LIT:GET>',<EOL>_make_path(index,<EOL>doc_type, id,<EOL>'<STR_LIT>'),<EOL>params=params, body=body)<EOL>raise gen.Return(data)<EOL>

The explain api computes a score explanation for a query and a specific
document. This can give useful feedback whether a document matches or
didn't match a specific query.
`<http://elasticsearch.org/guide/reference/api/explain/>`_

:arg index: The name of the index
:arg doc_type: The type of the document
:arg id: The document ID
:arg body: The query definition using the Query DSL
:arg _source: True or false to return the _source field or not, or a
    list of fields to return
:arg _source_exclude: A list of fields to exclude from the returned
    _source field
:arg _source_include: A list of fields to extract and return from the
    _source field
:arg analyze_wildcard: Specify whether wildcards and prefix queries in
    the query string query should be analyzed (default: false)
:arg analyzer: The analyzer for the query string query
:arg default_operator: The default operator for query string query (AND
    or OR), (default: OR)
:arg df: The default field for query string query (default: _all)
:arg fields: A comma-separated list of fields to return in the response
:arg lenient: Specify whether format-based query failures (such as
    providing text to a numeric field) should be ignored
:arg lowercase_expanded_terms: Specify whether query terms should be
    lowercased
:arg parent: The ID of the parent document
:arg preference: Specify the node or shard the operation should be
    performed on (default: random)
:arg q: Query in the Lucene query string syntax
:arg routing: Specific routing value
:arg source: The URL-encoded query definition (instead of using the
    request body)


try:<EOL><INDENT>self.transport.perform_request('<STR_LIT>', '<STR_LIT:/>', params=params)<EOL><DEDENT>except TransportError:<EOL><INDENT>raise gen.Return(False)<EOL><DEDENT>raise gen.Return(True)<EOL>

Returns True if the cluster is up, False otherwise.


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>')<EOL>def msearch(self, body, index=None, doc_type=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request('<STR_LIT:GET>',<EOL>_make_path(index,<EOL>doc_type,<EOL>'<STR_LIT>'),<EOL>params=params,<EOL>body=self._bulk_body(body))<EOL>raise gen.Return(data)<EOL>

Execute several search requests within the same API.
`<http://www.elasticsearch.org/guide/reference/api/multi-search/>`_

:arg body: The request definitions (metadata-search request definition
    pairs), separated by newlines
:arg index: A comma-separated list of index names to use as default
:arg doc_type: A comma-separated list of document types to use as default
:arg search_type: Search operation type


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT:version>', '<STR_LIT>')<EOL>def index(self, index, doc_type, body, id=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request(<EOL>'<STR_LIT>' if id else '<STR_LIT:POST>', _make_path(index, doc_type, id),<EOL>params=params, body=body)<EOL>raise gen.Return(data)<EOL>

Adds or updates a typed JSON document in a specific index, making it
searchable. `<http://elasticsearch.org/guide/reference/api/index_/>`_

:arg index: The name of the index
:arg doc_type: The type of the document
:arg body: The document
:arg id: Document ID
:arg consistency: Explicit write consistency setting for the operation
:arg op_type: Explicit operation type (default: index)
:arg parent: ID of the parent document
:arg percolate: Percolator queries to execute while indexing the doc
:arg refresh: Refresh the index after performing the operation
:arg replication: Specific replication type (default: sync)
:arg routing: Specific routing value
:arg timeout: Explicit operation timeout
:arg timestamp: Explicit timestamp for the document
:arg ttl: Expiration time for the document
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>def bulk(self, body, index=None, doc_type=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request('<STR_LIT:POST>',<EOL>_make_path(index,<EOL>doc_type,<EOL>'<STR_LIT>'),<EOL>params=params,<EOL>body=self._bulk_body(body))<EOL>raise gen.Return(data)<EOL>

Perform many index/delete operations in a single API call.
`<http://elasticsearch.org/guide/reference/api/bulk/>`_

See the :func:`~elasticsearch.helpers.bulk_index` for a more friendly
API.

:arg body: The operation definition and data (action-data pairs)
:arg index: Default index for items which don't provide one
:arg doc_type: Default document type for items which don't provide one
:arg consistency: Explicit write consistency setting for the operation
:arg refresh: Refresh the index after performing the operation
:arg replication: Explicitly set the replication type (efault: sync)


@gen.coroutine<EOL><INDENT>@query_params('<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>')<EOL>def get_mapping(self, index=None, doc_type=None, params=None):<DEDENT>

_, data = yield self.transport.perform_request('<STR_LIT:GET>',<EOL>_make_path(index,<EOL>'<STR_LIT>',<EOL>doc_type),<EOL>params=params)<EOL>raise gen.Return(data)<EOL>

Retrieve mapping definition of index or index/type.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html>`_
:arg index: A comma-separated list of index names
:arg doc_type: A comma-separated list of document types
:arg allow_no_indices: Whether to ignore if a wildcard indices
    expression resolves into no concrete indices. (This includes `_all`
    string or when no indices have been specified)
:arg expand_wildcards: Whether to expand wildcard expression to concrete
    indices that are open, closed or both., default 'open', valid
    choices are: 'open', 'closed', 'none', 'all'
:arg ignore_unavailable: Whether specified concrete indices should be
    ignored when unavailable (missing or closed)
:arg local: Return local information, do not retrieve the state from
    master node (default: false)


path = self._get_id_path('<STR_LIT>')<EOL>response = self._GET(path, kwargs)<EOL>self._set_attrs_to_values(response)<EOL>return response<EOL>

Get the recommendations for TV series for a specific TV series id.

Args:
    page: (optional) Minimum value of 1.  Expected value is an integer.
    language: (optional) ISO 639-1 code.

Returns:
    A dict respresentation of the JSON returned from the API.


path = self._get_id_path('<STR_LIT>')<EOL>payload = {<EOL>'<STR_LIT:value>': kwargs.pop('<STR_LIT:value>', None),<EOL>}<EOL>response = self._POST(path, kwargs, payload)<EOL>self._set_attrs_to_values(response)<EOL>return response<EOL>

This method lets users rate a TV show. A valid session id or guest
session id is required.

Args:
    session_id: see Authentication.
    guest_session_id: see Authentication.
    value: Rating value.

Returns:
    A dict respresentation of the JSON returned from the API.


path = self._get_series_id_season_number_path('<STR_LIT>')<EOL>response = self._GET(path, kwargs)<EOL>self._set_attrs_to_values(response)<EOL>return response<EOL>

Get the cast & crew credits for a TV season by season number.

Returns:
    A dict respresentation of the JSON returned from the API.


Get the list of translations that exist for a TV series. These
translations cascade down to the episode level.

Returns:
    A dict respresentation of the JSON returned from the API.


Get the images (posters and backdrops) for a TV series.

Args:
    language: (optional) ISO 639 code.
    include_image_language: (optional) Comma separated, a valid
                            ISO 69-1.

Returns:
    A dict respresentation of the JSON returned from the API.


Get the external ids that we have stored for a TV season by season
number.

Args:
    language: (optional) ISO 639 code.

Returns:
    A dict respresentation of the JSON returned from the API.


path = self._get_path('<STR_LIT>')<EOL>response = self._GET(path, kwargs)<EOL>self._set_attrs_to_values(response)<EOL>return response<EOL>

Get the list of TV shows that air today. Without a specified timezone,
this query defaults to EST (Eastern Time UTC-05:00).

Args:
    page: (optional) Minimum 1, maximum 1000.
    language: (optional) ISO 639 code.
    timezone: (optional) Valid value from the list of timezones.

Returns:
    A dict respresentation of the JSON returned from the API.


Search for collections by name.

Args:
    query: CGI escpaed string.
    page: (optional) Minimum value of 1. Expected value is an integer.
    language: (optional) ISO 639-1 code.

Returns:
    A dict respresentation of the JSON returned from the API.


Search the movie, tv show and person collections with a single query.

Args:
    query: CGI escpaed string.
    page: (optional) Minimum value of 1. Expected value is an integer.
    language: (optional) ISO 639-1 code.
    include_adult: (optional) Toggle the inclusion of adult titles.
                   Expected value is True or False.

Returns:
    A dict respresentation of the JSON returned from the API.


Search for movies by title.

Args:
    query: CGI escpaed string.
    page: (optional) Minimum value of 1. Expected value is an integer.
    language: (optional) ISO 639-1 code.
    include_adult: (optional) Toggle the inclusion of adult titles.
                   Expected value is True or False.
    year: (optional) Filter the results release dates to matches that
          include this value.
    primary_release_year: (optional) Filter the results so that only
                          the primary release dates have this value.
    search_type: (optional) By default, the search type is 'phrase'.
                 This is almost guaranteed the option you will want.
                 It's a great all purpose search type and by far the
                 most tuned for every day querying. For those wanting
                 more of an "autocomplete" type search, set this
                 option to 'ngram'.

Returns:
    A dict respresentation of the JSON returned from the API.