verb = environ['<STR_LIT>'].upper()<EOL>path = environ['<STR_LIT>'] or '<STR_LIT:/>'<EOL>if verb == '<STR_LIT>':<EOL><INDENT>methods = ['<STR_LIT>', verb, '<STR_LIT:GET>', '<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>methods = ['<STR_LIT>', verb, '<STR_LIT>']<EOL><DEDENT>for method in methods:<EOL><INDENT>if method in self.static and path in self.static[method]:<EOL><INDENT>target, getargs = self.static[method][path]<EOL>return target, getargs(path) if getargs else {}<EOL><DEDENT>elif method in self.dyna_regexes:<EOL><INDENT>for combined, rules in self.dyna_regexes[method]:<EOL><INDENT>match = combined(path)<EOL>if match:<EOL><INDENT>target, getargs = rules[match.lastindex - <NUM_LIT:1>]<EOL>return target, getargs(path) if getargs else {}<EOL><DEDENT><DEDENT><DEDENT><DEDENT>allowed = set([])<EOL>nocheck = set(methods)<EOL>for method in set(self.static) - nocheck:<EOL><INDENT>if path in self.static[method]:<EOL><INDENT>allowed.add(verb)<EOL><DEDENT><DEDENT>for method in set(self.dyna_regexes) - allowed - nocheck:<EOL><INDENT>for combined, rules in self.dyna_regexes[method]:<EOL><INDENT>match = combined(path)<EOL>if match:<EOL><INDENT>allowed.add(method)<EOL><DEDENT><DEDENT><DEDENT>if allowed:<EOL><INDENT>allow_header = "<STR_LIT:U+002C>".join(sorted(allowed))<EOL>raise HTTPError(<NUM_LIT>, "<STR_LIT>", Allow=allow_header)<EOL><DEDENT>raise HTTPError(<NUM_LIT>, "<STR_LIT>" + repr(path))<EOL>

Return a (target, url_args) tuple or raise HTTPError(400/404/405).


run(self, **kwargs)<EOL>

Calls :func:`run` with the same parameters.


self.dict.setdefault(key, []).append(value)<EOL>

Add a new value to the list of values for this key.


self.name = name<EOL>self.source = source.read() if hasattr(source, '<STR_LIT>') else source<EOL>self.filename = source.filename if hasattr(source, '<STR_LIT:filename>') else None<EOL>self.lookup = [os.path.abspath(x) for x in lookup] if lookup else []<EOL>self.encoding = encoding<EOL>self.settings = self.settings.copy()  <EOL>self.settings.update(settings)  <EOL>if not self.source and self.name:<EOL><INDENT>self.filename = self.search(self.name, self.lookup)<EOL>if not self.filename:<EOL><INDENT>raise TemplateError('<STR_LIT>' % repr(name))<EOL><DEDENT><DEDENT>if not self.source and not self.filename:<EOL><INDENT>raise TemplateError('<STR_LIT>')<EOL><DEDENT>self.prepare(**self.settings)<EOL>

Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.


@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def params(self):<DEDENT>

params = FormsDict()<EOL>for key, value in self.query.allitems():<EOL><INDENT>params[key] = value<EOL><DEDENT>for key, value in self.forms.allitems():<EOL><INDENT>params[key] = value<EOL><DEDENT>return params<EOL>

A :class:`FormsDict` with the combined values of :attr:`query` and
            :attr:`forms`. File uploads are stored in :attr:`files`.


return not sum(<NUM_LIT:0> if x == y else <NUM_LIT:1><EOL>for x, y in zip(a, b)) and len(a) == len(b)<EOL>

Compares two strings in a cryptographically safe way:
        Runtime is not affected by length of common prefix.


def wrapper(handler):<EOL><INDENT>self.error_handler[int(code)] = handler<EOL>return handler<EOL><DEDENT>return wrapper<EOL>

Decorator: Register an output handler for a HTTP error code


@classmethod<EOL><INDENT>def global_config(cls, key, *args):<DEDENT>

if args:<EOL><INDENT>cls.settings = cls.settings.copy()  <EOL>cls.settings[key] = args[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return cls.settings[key]<EOL><DEDENT>

This reads or sets the global settings stored in class.settings.


hdict = HeaderDict()<EOL>hdict.dict = self._headers<EOL>return hdict<EOL>

An instance of :class:`HeaderDict`, a case-insensitive dict-like
            view on the response headers.


raise HTTPError(code, text)<EOL>

Aborts execution and causes a HTTP error.


def open(self, name, mode='<STR_LIT:r>', *args, **kwargs):

fname = self.lookup(name)<EOL>if not fname: raise IOError("<STR_LIT>" % name)<EOL>return self.opener(fname, mode=mode, *args, **kwargs)<EOL>

Find a resource and return a file object, or raise IOError.


removed, remove = [], plugin<EOL>for i, plugin in list(enumerate(self.plugins))[::-<NUM_LIT:1>]:<EOL><INDENT>if remove is True or remove is plugin or remove is type(plugin)or getattr(plugin, '<STR_LIT:name>', True) == remove:<EOL><INDENT>removed.append(plugin)<EOL>del self.plugins[i]<EOL>if hasattr(plugin, '<STR_LIT>'): plugin.close()<EOL><DEDENT><DEDENT>if removed: self.reset()<EOL>return removed<EOL>

Uninstall plugins. Pass an instance to remove a specific plugin, a type
            object to remove all plugins that match that type, a string to remove
            all plugins with a matching ``name`` attribute or ``True`` to remove all
            plugins. Return the list of removed plugins.


def get_header(self, name, default=None):

return self.headers.get(name, default)<EOL>

Return the value of a request header, or a given default value.


return Request(self.environ.copy())<EOL>

Return a new :class:`Request` with a shallow :attr:`environ` copy.


if self.environ.get('<STR_LIT>'):<EOL><INDENT>raise KeyError('<STR_LIT>')<EOL><DEDENT>self.environ[key] = value<EOL>todelete = ()<EOL>if key == '<STR_LIT>':<EOL><INDENT>todelete = ('<STR_LIT:body>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif key == '<STR_LIT>':<EOL><INDENT>todelete = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif key.startswith('<STR_LIT>'):<EOL><INDENT>todelete = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>for key in todelete:<EOL><INDENT>self.environ.pop('<STR_LIT>' + key, None)<EOL><DEDENT>

Change an environ value and clear all caches that depend on it.


@functools.wraps(getattr(Bottle, name))<EOL>def wrapper(*a, **ka):<EOL><INDENT>return getattr(app(), name)(*a, **ka)<EOL><DEDENT>return wrapper<EOL>

Return a callable that relays calls to the current default app.


return self.urlparts.geturl()<EOL>

The full request URI including hostname and scheme. If your app
            lives behind a reverse proxy or load balancer and you get confusing
            results, make sure that the ``X-Forwarded-Host`` header is set
            correctly.


env = {}<EOL>stdout = []<EOL>for dictarg in args:<EOL><INDENT>env.update(dictarg)<EOL><DEDENT>env.update(kwargs)<EOL>self.execute(stdout, env)<EOL>return '<STR_LIT>'.join(stdout)<EOL>

Render the template using keyword arguments as local variables.


path = '<STR_LIT:/>' + func.__name__.replace('<STR_LIT>', '<STR_LIT:/>').lstrip('<STR_LIT:/>')<EOL>spec = getargspec(func)<EOL>argc = len(spec[<NUM_LIT:0>]) - len(spec[<NUM_LIT:3>] or [])<EOL>path += ('<STR_LIT>' * argc) % tuple(spec[<NUM_LIT:0>][:argc])<EOL>yield path<EOL>for arg in spec[<NUM_LIT:0>][argc:]:<EOL><INDENT>path += '<STR_LIT>' % arg<EOL>yield path<EOL><DEDENT>

Return a generator for routes that match the signature (name, args)
    of the func parameter. This may yield more than one route if the function
    takes optional keyword arguments. The output is best described by example::

        a()         -> '/a'
        b(x, y)     -> '/b/<x>/<y>'
        c(x, y=5)   -> '/c/<x>' and '/c/<x>/<y>'
        d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'


def path_shift(script_name, path_info, shift=<NUM_LIT:1>):

if shift == <NUM_LIT:0>: return script_name, path_info<EOL>pathlist = path_info.strip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>scriptlist = script_name.strip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>if pathlist and pathlist[<NUM_LIT:0>] == '<STR_LIT>': pathlist = []<EOL>if scriptlist and scriptlist[<NUM_LIT:0>] == '<STR_LIT>': scriptlist = []<EOL>if <NUM_LIT:0> < shift <= len(pathlist):<EOL><INDENT>moved = pathlist[:shift]<EOL>scriptlist = scriptlist + moved<EOL>pathlist = pathlist[shift:]<EOL><DEDENT>elif <NUM_LIT:0> > shift >= -len(scriptlist):<EOL><INDENT>moved = scriptlist[shift:]<EOL>pathlist = moved + pathlist<EOL>scriptlist = scriptlist[:shift]<EOL><DEDENT>else:<EOL><INDENT>empty = '<STR_LIT>' if shift < <NUM_LIT:0> else '<STR_LIT>'<EOL>raise AssertionError("<STR_LIT>" % empty)<EOL><DEDENT>new_script_name = '<STR_LIT:/>' + '<STR_LIT:/>'.join(scriptlist)<EOL>new_path_info = '<STR_LIT:/>' + '<STR_LIT:/>'.join(pathlist)<EOL>if path_info.endswith('<STR_LIT:/>') and pathlist: new_path_info += '<STR_LIT:/>'<EOL>return new_script_name, new_path_info<EOL>

Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.

        :return: The modified paths.
        :param script_name: The SCRIPT_NAME path.
        :param script_name: The PATH_INFO path.
        :param shift: The number of path fragments to shift. May be negative to
          change the shift direction. (default: 1)


func = self.callback<EOL>func = getattr(func, '<STR_LIT>' if py3k else '<STR_LIT>', func)<EOL>closure_attr = '<STR_LIT>' if py3k else '<STR_LIT>'<EOL>while hasattr(func, closure_attr) and getattr(func, closure_attr):<EOL><INDENT>attributes = getattr(func, closure_attr)<EOL>func = attributes[<NUM_LIT:0>].cell_contents<EOL>if not isinstance(func, FunctionType):<EOL><INDENT>func = filter(lambda x: isinstance(x, FunctionType),<EOL>map(lambda x: x.cell_contents, attributes))<EOL>func = list(func)[<NUM_LIT:0>]  <EOL><DEDENT><DEDENT>return func<EOL>

Return the callback. If the callback is a decorated function, try to
            recover the original function.


script_name = self.environ.get('<STR_LIT>', '<STR_LIT>').strip('<STR_LIT:/>')<EOL>return '<STR_LIT:/>' + script_name + '<STR_LIT:/>' if script_name else '<STR_LIT:/>'<EOL>

The initial portion of the URL's `path` that was removed by a higher
            level (server or routing middleware) before the application was
            called. This script path is returned with leading and tailing
            slashes.


clen = self.content_length<EOL>if clen > self.MEMFILE_MAX:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>if clen < <NUM_LIT:0>: clen = self.MEMFILE_MAX + <NUM_LIT:1><EOL>data = self.body.read(clen)<EOL>if len(data) > self.MEMFILE_MAX:  <EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>return data<EOL>

read body until content-length or MEMFILE_MAX into a string. Raise
            HTTPError(413) on requests that are to large.


def delete(self, path=None, method='<STR_LIT>', **options):

return self.route(path, method, **options)<EOL>

Equals :meth:`route` with a ``DELETE`` method parameter.


try:<EOL><INDENT>ts = email.utils.parsedate_tz(ims)<EOL>return time.mktime(ts[:<NUM_LIT:8>] + (<NUM_LIT:0>, )) - (ts[<NUM_LIT:9>] or <NUM_LIT:0>) - time.timezone<EOL><DEDENT>except (TypeError, ValueError, IndexError, OverflowError):<EOL><INDENT>return None<EOL><DEDENT>

Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.


if route is None: routes = self.routes<EOL>elif isinstance(route, Route): routes = [route]<EOL>else: routes = [self.routes[route]]<EOL>for route in routes:<EOL><INDENT>route.reset()<EOL><DEDENT>if DEBUG:<EOL><INDENT>for route in routes:<EOL><INDENT>route.prepare()<EOL><DEDENT><DEDENT>self.trigger_hook('<STR_LIT>')<EOL>

Reset all routes (force plugins to be re-applied) and clear all
            caches. If an ID or route object is given, only that specific route
            is affected.


tpl = args[<NUM_LIT:0>] if args else None<EOL>adapter = kwargs.pop('<STR_LIT>', SimpleTemplate)<EOL>lookup = kwargs.pop('<STR_LIT>', TEMPLATE_PATH)<EOL>tplid = (id(lookup), tpl)<EOL>if tplid not in TEMPLATES or DEBUG:<EOL><INDENT>settings = kwargs.pop('<STR_LIT>', {})<EOL>if isinstance(tpl, adapter):<EOL><INDENT>TEMPLATES[tplid] = tpl<EOL>if settings: TEMPLATES[tplid].prepare(**settings)<EOL><DEDENT>elif "<STR_LIT:\n>" in tpl or "<STR_LIT:{>" in tpl or "<STR_LIT:%>" in tpl or '<STR_LIT:$>' in tpl:<EOL><INDENT>TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)<EOL><DEDENT>else:<EOL><INDENT>TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)<EOL><DEDENT><DEDENT>if not TEMPLATES[tplid]:<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>' % tpl)<EOL><DEDENT>for dictarg in args[<NUM_LIT:1>:]:<EOL><INDENT>kwargs.update(dictarg)<EOL><DEDENT>return TEMPLATES[tplid].render(kwargs)<EOL>

Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).


def get_config(self, key, default=None):

for conf in (self.config, self.app.config):<EOL><INDENT>if key in conf: return conf[key]<EOL><DEDENT>return default<EOL>

Lookup a config field and return its value, first checking the
            route.config, then route.app.config.


default_app.push(self)<EOL>return self<EOL>

Use this application as default for all module-level shortcuts.


for plugin in self.plugins:<EOL><INDENT>if hasattr(plugin, '<STR_LIT>'): plugin.close()<EOL><DEDENT>

Close the application and all installed plugins.


def decorator(func):<EOL><INDENT>self.add_hook(name, func)<EOL>return func<EOL><DEDENT>return decorator<EOL>

Return a decorator that attaches a callback to a hook. See
            :meth:`add_hook` for details.


def getunicode(self, name, default=None, encoding=None):

try:<EOL><INDENT>return self._fix(self[name], encoding)<EOL><DEDENT>except (UnicodeError, KeyError):<EOL><INDENT>return default<EOL><DEDENT>

Return the value as a unicode string, or the default.


self.call<EOL>

Do all on-demand work immediately (useful for debugging).


@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def app(self):<DEDENT>

raise RuntimeError('<STR_LIT>')<EOL>

Bottle application handling this request.


return self[-<NUM_LIT:1>]<EOL>


@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def forms(self):<DEDENT>

forms = FormsDict()<EOL>for name, item in self.POST.allitems():<EOL><INDENT>if not isinstance(item, FileUpload):<EOL><INDENT>forms[name] = item<EOL><DEDENT><DEDENT>return forms<EOL>

Form values parsed from an `url-encoded` or `multipart/form-data`
            encoded POST or PUT request body. The result is returned as a
            :class:`FormsDict`. All keys and values are strings. File uploads
            are stored separately in :attr:`files`.


return '<STR_LIT>' % html_escape(string).replace('<STR_LIT:\n>', '<STR_LIT>').replace('<STR_LIT:\r>', '<STR_LIT>').replace('<STR_LIT:\t>', '<STR_LIT>')<EOL>

Escape and quote a string to be used as an HTTP attribute.


if '<STR_LIT:(>' not in p:<EOL><INDENT>return p<EOL><DEDENT>return re.sub(r'<STR_LIT>', lambda m: m.group(<NUM_LIT:0>) if<EOL>len(m.group(<NUM_LIT:1>)) % <NUM_LIT:2> else m.group(<NUM_LIT:1>) + '<STR_LIT>', p)<EOL>

Turn all capturing groups in a regular expression pattern into
        non-capturing groups.


msg = base64.b64encode(pickle.dumps(data, -<NUM_LIT:1>))<EOL>sig = base64.b64encode(hmac.new(tob(key), msg).digest())<EOL>return tob('<STR_LIT:!>') + sig + tob('<STR_LIT:?>') + msg<EOL>

Encode and sign a pickle-able object. Return a (byte) string


if hasattr(plugin, '<STR_LIT>'): plugin.setup(self)<EOL>if not callable(plugin) and not hasattr(plugin, '<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.plugins.append(plugin)<EOL>self.reset()<EOL>return plugin<EOL>

Add a plugin to the list of plugins and prepare it for being
            applied to all routes of this application. A plugin may be a simple
            decorator or an object that implements the :class:`Plugin` API.


return self.dict.get(key) or []<EOL>

Return a (possibly empty) list of values for a key.


def build(self, _name, *anons, **query):

builder = self.builder.get(_name)<EOL>if not builder:<EOL><INDENT>raise RouteBuildError("<STR_LIT>", _name)<EOL><DEDENT>try:<EOL><INDENT>for i, value in enumerate(anons):<EOL><INDENT>query['<STR_LIT>' % i] = value<EOL><DEDENT>url = '<STR_LIT>'.join([f(query.pop(n)) if n else f for (n, f) in builder])<EOL>return url if not query else url + '<STR_LIT:?>' + urlencode(query)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise RouteBuildError('<STR_LIT>' % _e().args[<NUM_LIT:0>])<EOL><DEDENT>

Build an URL by filling the wildcards in a rule.


raise NotImplementedError<EOL>

Run preparations (parsing, caching, ...).
        It should be possible to call this again to refresh a template or to
        update settings.


data = tob(data)<EOL>if cookie_is_encoded(data):<EOL><INDENT>sig, msg = data.split(tob('<STR_LIT:?>'), <NUM_LIT:1>)<EOL>if _lscmp(sig[<NUM_LIT:1>:], base64.b64encode(hmac.new(tob(key), msg).digest())):<EOL><INDENT>return pickle.loads(base64.b64decode(msg))<EOL><DEDENT><DEDENT>return None<EOL>

Verify and decode an encoded string. Return an object or None.


conf = ConfigParser()<EOL>conf.read(filename)<EOL>for section in conf.sections():<EOL><INDENT>for key, value in conf.items(section):<EOL><INDENT>if section not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>key = section + '<STR_LIT:.>' + key<EOL><DEDENT>self[key] = value<EOL><DEDENT><DEDENT>return self<EOL>

Load values from an ``*.ini`` style config file.

            If the config file contains sections, their names are used as
            namespaces for the values within. The two special sections
            ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).


self.__dict__.pop('<STR_LIT>', None)<EOL>

Forget any cached values. The next time :attr:`call` is accessed,
            all plugins are re-applied.


def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>result = func(*args, **kwargs)<EOL>if isinstance(result, (dict, DictMixin)):<EOL><INDENT>tplvars = defaults.copy()<EOL>tplvars.update(result)<EOL>return template(tpl_name, **tplvars)<EOL><DEDENT>elif result is None:<EOL><INDENT>return template(tpl_name, defaults)<EOL><DEDENT>return result<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>

Decorator: renders a template for a handler.
        The handler can control its behavior like that:

          - return a dict of template vars to fill out the template
          - return something other than a dict and the view decorator will not
            process the template, but return the handler result as is.
            This includes returning a HTTPResponse(dict) to get,
            for instance, JSON with autojson or other castfilters.


@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def json(self):<DEDENT>

ctype = self.environ.get('<STR_LIT>', '<STR_LIT>').lower().split('<STR_LIT:;>')[<NUM_LIT:0>]<EOL>if ctype == '<STR_LIT:application/json>':<EOL><INDENT>b = self._get_body_string()<EOL>if not b:<EOL><INDENT>return None<EOL><DEDENT>return json_loads(b)<EOL><DEDENT>return None<EOL>

If the ``Content-Type`` header is ``application/json``, this
            property holds the parsed content of the request body. Only requests
            smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
            exhaustion.


unique = set()<EOL>for p in reversed(self.app.plugins + self.plugins):<EOL><INDENT>if True in self.skiplist: break<EOL>name = getattr(p, '<STR_LIT:name>', False)<EOL>if name and (name in self.skiplist or name in unique): continue<EOL>if p in self.skiplist or type(p) in self.skiplist: continue<EOL>if name: unique.add(name)<EOL>yield p<EOL><DEDENT>


if not code:<EOL><INDENT>code = <NUM_LIT> if request.get('<STR_LIT>') == "<STR_LIT>" else <NUM_LIT><EOL><DEDENT>res = response.copy(cls=HTTPResponse)<EOL>res.status = code<EOL>res.body = "<STR_LIT>"<EOL>res.set_header('<STR_LIT>', urljoin(request.url, url))<EOL>raise res<EOL>

Aborts execution and causes a 303 or 302 redirect, depending on
        the HTTP protocol version.


return self.environ.get('<STR_LIT>', '<STR_LIT>').lower()<EOL>

The Content-Type header as a lowercase-string (default: empty).


scriptname = request.environ.get('<STR_LIT>', '<STR_LIT>').strip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>location = self.router.build(routename, **kargs).lstrip('<STR_LIT:/>')<EOL>return urljoin(urljoin('<STR_LIT:/>', scriptname), location)<EOL>

Return a string that matches a named route


def get(self, key, default=None, index=-<NUM_LIT:1>, type=None):

try:<EOL><INDENT>val = self.dict[key][index]<EOL>return type(val) if type else val<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return default<EOL>

Return the most recent value for a key.

            :param default: The default value to be returned if the key is not
                   present or the type conversion fails.
            :param index: An index for the list of available values.
            :param type: If defined, this callable is used to cast the value
                    into a specific type. Exception are suppressed and result in
                    the default value to be returned.


return '<STR_LIT>' in self.environ.get(<EOL>'<STR_LIT>', '<STR_LIT>').lower()<EOL>


if callable(path): path, callback = None, path<EOL>plugins = makelist(apply)<EOL>skiplist = makelist(skip)<EOL>def decorator(callback):<EOL><INDENT>if isinstance(callback, basestring): callback = load(callback)<EOL>for rule in makelist(path) or yieldroutes(callback):<EOL><INDENT>for verb in makelist(method):<EOL><INDENT>verb = verb.upper()<EOL>route = Route(self, rule, verb, callback,<EOL>name=name,<EOL>plugins=plugins,<EOL>skiplist=skiplist, **config)<EOL>self.add_route(route)<EOL><DEDENT><DEDENT>return callback<EOL><DEDENT>return decorator(callback) if callback else decorator<EOL>

A decorator to bind a function to a request URL. Example::

                @app.route('/hello/<name>')
                def hello(name):
                    return 'Hello %s' % name

            The ``:name`` part is a wildcard. See :class:`Router` for syntax
            details.

            :param path: Request path or a list of paths to listen to. If no
              path is specified, it is automatically generated from the
              signature of the function.
            :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
              methods to listen to. (default: `GET`)
            :param callback: An optional shortcut to avoid the decorator
              syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
            :param name: The name for this route. (default: None)
            :param apply: A decorator or plugin or a list of plugins. These are
              applied to the route callback in addition to installed plugins.
            :param skip: A list of plugins, plugin classes or names. Matching
              plugins are not installed to this route. ``True`` skips all.

            Any additional keyword arguments are stored as route-specific
            configuration and passed to plugins (see :meth:`Plugin.apply`).


yield '<STR_LIT>'<EOL>if filepath == '<STR_LIT:/>':<EOL><INDENT>filepath = '<STR_LIT>'<EOL><DEDENT>for name in FS.listdir(filepath):<EOL><INDENT>full_path = pathjoin(filepath, name)<EOL>if FS.isdir(full_path):<EOL><INDENT>full_path = full_path + '<STR_LIT:/>'<EOL><DEDENT>yield u'<STR_LIT>'.format(<EOL>cgi.escape(full_path))  <EOL><DEDENT>yield '<STR_LIT>'<EOL>

Generate directory listing HTML

Arguments:
    FS (FS): filesystem object to read files from
    filepath (str): path to generate directory listings for

Keyword Arguments:
    list_dir (callable: list[str]): list file names in a directory
    isdir (callable: bool): os.path.isdir

Yields:
    str: lines of an HTML table


log.debug('<STR_LIT>' % list(args))<EOL>def _pathjoin(*args, **kwargs):<EOL><INDENT>len_ = len(args) - <NUM_LIT:1><EOL>if len_ < <NUM_LIT:0>:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>elif len_ == <NUM_LIT:0>:<EOL><INDENT>if not isinstance(args, basestring):<EOL><INDENT>if hasattr(args, '<STR_LIT>'):<EOL><INDENT>_args = args<EOL>_args<EOL>args = args[<NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT>for i, arg in enumerate(args):<EOL><INDENT>if not i:<EOL><INDENT>yield arg.rstrip('<STR_LIT:/>')<EOL><DEDENT>elif i == len_:<EOL><INDENT>yield arg.lstrip('<STR_LIT:/>')<EOL><DEDENT>else:<EOL><INDENT>yield arg.strip('<STR_LIT:/>')<EOL><DEDENT><DEDENT><DEDENT>joined_path = u'<STR_LIT:/>'.join(_pathjoin(*args))<EOL>return sanitize_path(joined_path)<EOL>

Arguments:
    args (list): *args list of paths
        if len(args) == 1, args[0] is not a string, and args[0] is iterable,
        set args to args[0].

Basically::

    joined_path = u'/'.join(
        [args[0].rstrip('/')] +
        [a.strip('/') for a in args[1:-1]] +
        [args[-1].lstrip('/')])


if hasattr(self._bot, '<STR_LIT>'):<EOL><INDENT>user = self._bot.user_manager.get_by_username(username)<EOL>if user:<EOL><INDENT>return user<EOL><DEDENT>user = SlackUser.get_user(self._bot.sc, username)<EOL>self._bot.user_manager.set(user)<EOL>return user<EOL><DEDENT>return SlackUser.get_user(self._bot.sc, username)<EOL>

Utility function to query slack for a particular user

:param username: The username of the user to lookup
:return: SlackUser object or None


if isinstance(channel, SlackIM) or isinstance(channel, SlackUser):<EOL><INDENT>self._bot.send_im(channel, text)<EOL><DEDENT>elif isinstance(channel, SlackRoom):<EOL><INDENT>self._bot.send_message(channel, text)<EOL><DEDENT>elif isinstance(channel, basestring):<EOL><INDENT>if channel[<NUM_LIT:0>] == '<STR_LIT:@>':<EOL><INDENT>self._bot.send_im(channel[<NUM_LIT:1>:], text)<EOL><DEDENT>elif channel[<NUM_LIT:0>] == '<STR_LIT:#>':<EOL><INDENT>self._bot.send_message(channel[<NUM_LIT:1>:], text)<EOL><DEDENT>else:<EOL><INDENT>self._bot.send_message(channel, text)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._bot.send_message(channel, text)<EOL><DEDENT>

Used to send a message to the specified channel.

* channel - can be a channel or user
* text - message to send


return SlackChannel.get_channel(self._bot.sc, channel)<EOL>

Utility function to query slack for a particular channel

:param channel: The channel name or id of the channel to lookup
:return: SlackChannel object or None


def cmd(admin_only=False, acl='<STR_LIT:*>', aliases=None, while_ignored=False, *args, **kwargs):

def wrapper(func):<EOL><INDENT>func.is_cmd = True<EOL>func.is_subcmd = len(func.__name__.split('<STR_LIT:_>')) > <NUM_LIT:1><EOL>func.cmd_name = func.__name__.replace('<STR_LIT:_>', '<STR_LIT:U+0020>')<EOL>func.admin_only = admin_only<EOL>func.acl = acl<EOL>func.aliases = aliases<EOL>func.while_ignored = while_ignored<EOL>return func<EOL><DEDENT>return wrapper<EOL>

Decorator to mark plugin functions as commands in the form of !<cmd_name>

* admin_only - indicates only users in bot_admin are allowed to execute (only used if AuthManager is loaded)
* acl - indicates which ACL to perform permission checks against (only used if AuthManager is loaded)
* aliases - register function with additional commands (i.e. !alias1, !alias2, etc)
* while_ignored - allows a command to be run, even if channel has been !sleep


<EOL>if not self.is_setup:<EOL><INDENT>raise NotSetupError<EOL><DEDENT>self.webserver.start()<EOL>first_connect = True<EOL>try:<EOL><INDENT>while self.runnable:<EOL><INDENT>if self.reconnect_needed:<EOL><INDENT>if not self.sc.rtm_connect(with_team_state=start):<EOL><INDENT>return False<EOL><DEDENT>self.reconnect_needed = False<EOL>if first_connect:<EOL><INDENT>first_connect = False<EOL>self.plugins.connect()<EOL><DEDENT><DEDENT>try:<EOL><INDENT>events = self.sc.rtm_read()<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.log.exception('<STR_LIT>')<EOL>self.runnable = False<EOL>events = []<EOL><DEDENT>except:<EOL><INDENT>self.log.exception('<STR_LIT>')<EOL>self.reconnect_needed = True<EOL>events = []<EOL><DEDENT>for e in events:<EOL><INDENT>try:<EOL><INDENT>self._handle_event(e)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>self.runnable = False<EOL><DEDENT>except:<EOL><INDENT>self.log.exception('<STR_LIT>')<EOL><DEDENT><DEDENT>sleep(<NUM_LIT:0.1>)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>except:<EOL><INDENT>self.log.exception('<STR_LIT>')<EOL><DEDENT>

Connects to slack and enters the main loop.

* start - If True, rtm.start API is used. Else rtm.connect API is used

For more info, refer to
https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect


if self.webserver is not None:<EOL><INDENT>self.webserver.stop()<EOL><DEDENT>if not self.test_mode:<EOL><INDENT>self.plugins.save_state()<EOL><DEDENT>


def wrapper(func):<EOL><INDENT>if isinstance(kwargs['<STR_LIT>'], basestring):<EOL><INDENT>kwargs['<STR_LIT>'] = [kwargs['<STR_LIT>']]<EOL><DEDENT>func.is_eventhandler = True<EOL>func.events = kwargs['<STR_LIT>']<EOL>return func<EOL><DEDENT>return wrapper<EOL>

Decorator.  Marks a function as a receiver for the specified slack event(s).

* events - String or list of events to handle


if isinstance(user, SlackUser):<EOL><INDENT>user = user.id<EOL>channelid = self._find_im_channel(user)<EOL><DEDENT>else:<EOL><INDENT>channelid = user.id<EOL><DEDENT>self.send_message(channelid, text)<EOL>

Sends a message to a user as an IM

* user - The user to send to.  This can be a SlackUser object, a user id, or the username (without the @)
* text - String to send


if hasattr(message, '<STR_LIT>') and message.subtype in self.ignored_events:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

message_replied event is not truly a message event and does not have a message.text
don't process such events

commands may not be idempotent, so ignore message_changed events.


@cmd()<EOL><INDENT>def alert(self, msg, args):<DEDENT>

self.send_message(self.config['<STR_LIT>'], '<STR_LIT>')<EOL>return None<EOL>


@cmd()<EOL><INDENT>def shortsleep(self, msg, args):<DEDENT>

self.start_timer(<NUM_LIT:5>, self._sleep_func)<EOL>


@cmd()<EOL><INDENT>def shortsleep2(self, msg, args):<DEDENT>

self.start_timer(<NUM_LIT:5>, self._sleep_func2, msg.channel, '<STR_LIT:U+0020>'.join(args))<EOL>

Sleep for a bit, then echo the message back


@cmd()<EOL><INDENT>def xyzzy(self, msg, args):<DEDENT>

return "<STR_LIT>" % msg.user<EOL>


self.log.info("<STR_LIT>", user.id, user.username)<EOL>self.load_user_info(user)<EOL>self.log.info("<STR_LIT>", user.id, user.username)<EOL>self.load_user_rights(user)<EOL>self.log.info("<STR_LIT>", user.id, user.username)<EOL>self._add_user_to_cache(user)<EOL>return user<EOL>

Adds a user object to the user manager

user - a SlackUser object


if user.username in self.admins:<EOL><INDENT>user.is_admin = True<EOL><DEDENT>elif not hasattr(user, '<STR_LIT>'):<EOL><INDENT>user.is_admin = False<EOL><DEDENT>


<EOL>pass<EOL>

Loads additional user information and stores in user object


res = filter(lambda x: x.username == username, self.users.values())<EOL>if len(res) > <NUM_LIT:0>:<EOL><INDENT>return res[<NUM_LIT:0>]<EOL><DEDENT>return None<EOL>


self.log.info('<STR_LIT>', channel)<EOL>self._bot.dispatcher.ignore(channel)<EOL>self.send_message(channel, '<STR_LIT>')<EOL>

Causes the bot to ignore all messages from the channel.

        Usage:
        !sleep [channel name] - ignore the specified channel (or current if none specified)


@cmd()<EOL><INDENT>def whoami(self, msg, args):<DEDENT>

output = ["<STR_LIT>" % msg.user]<EOL>if hasattr(self._bot.dispatcher, '<STR_LIT>') and msg.user.is_admin is True:<EOL><INDENT>output.append("<STR_LIT>")<EOL><DEDENT>output.append("<STR_LIT>" % (self._bot.version, self._bot.commit))<EOL>return '<STR_LIT:\n>'.join(output)<EOL>

Prints information about the user and bot version.


def remove_user_from_acl(self, name, user):

if name not in self._acl:<EOL><INDENT>return False<EOL><DEDENT>if user in self._acl[name]['<STR_LIT>']:<EOL><INDENT>self._acl[name]['<STR_LIT>'].remove(user)<EOL><DEDENT>if user in self._acl[name]['<STR_LIT>']:<EOL><INDENT>self._acl[name]['<STR_LIT>'].remove(user)<EOL><DEDENT>return True<EOL>

Remove a user from the given acl (both allow and deny).


if name in self._acl:<EOL><INDENT>return False<EOL><DEDENT>self._acl[name] = {<EOL>'<STR_LIT>': [],<EOL>'<STR_LIT>': []<EOL>}<EOL>return True<EOL>


output = core.run("<STR_LIT>")<EOL>networks = {}<EOL>net_lines = [n.strip() for n in output.splitlines()[<NUM_LIT:2>:]]<EOL>for line in net_lines:<EOL><INDENT>if not line:<EOL><INDENT>continue<EOL><DEDENT>name, state, auto = line.split()<EOL>networks[name] = state == "<STR_LIT>"<EOL><DEDENT>return networks<EOL>

Return a dictionary of network name to active status bools.

        Sample virsh net-list output::

    Name                 State      Autostart
    -----------------------------------------
    default              active     yes
    juju-test            inactive   no
    foobar               inactive   no

    Parsing the above would return::
    {"default": True, "juju-test": False, "foobar": False}

    See: http://goo.gl/kXwfC


return (yield from self.handle_text(self.API.get('<STR_LIT>')))<EOL>


self.__modes = yield from self.get_modes()<EOL>return (yield from self.collect_labels(self.__modes))<EOL>

Get the label list of the supported modes.


return (yield from self.handle_long(self.API.get('<STR_LIT>')))<EOL>

Check when and if the device is going to sleep.


endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)<EOL>text = yield from endpoint.text(encoding='<STR_LIT:utf-8>')<EOL>doc = objectify.fromstring(text)<EOL>return doc.webfsapi.text<EOL>

Parse the fsapi endpoint from the device url.


status = yield from self.handle_int(self.API.get('<STR_LIT:status>'))<EOL>return self.PLAY_STATES.get(status)<EOL>


mute = (yield from self.handle_set(self.API.get('<STR_LIT>'), int(value)))<EOL>return bool(mute)<EOL>


power = (yield from self.handle_int(self.API.get('<STR_LIT>')))<EOL>return bool(power)<EOL>


return (yield from self.play_control(<NUM_LIT:4>))<EOL>


return (yield from self.handle_int(self.API.get('<STR_LIT>')))<EOL>


doc = yield from self.call('<STR_LIT>'+item+'<STR_LIT>', dict(<EOL>maxItems=<NUM_LIT:100>,<EOL>))<EOL>if doc is None:<EOL><INDENT>return []<EOL><DEDENT>if not doc.status == '<STR_LIT>':<EOL><INDENT>return []<EOL><DEDENT>ret = list()<EOL>for index, item in enumerate(list(doc.iterchildren('<STR_LIT>'))):<EOL><INDENT>temp = dict(band=index)<EOL>for field in list(item.iterchildren()):<EOL><INDENT>temp[field.get('<STR_LIT:name>')] = list(field.iterchildren()).pop()<EOL><DEDENT>ret.append(temp)<EOL><DEDENT>return ret<EOL>

Helper method for fetching a list(map) value.


@asyncio.coroutine<EOL><INDENT>def call(self, path, extra=None):<DEDENT>

try:<EOL><INDENT>if not self.__webfsapi:<EOL><INDENT>self.__webfsapi = yield from self.get_fsapi_endpoint()<EOL><DEDENT>if not self.sid:<EOL><INDENT>self.sid = yield from self.create_session()<EOL><DEDENT>if not isinstance(extra, dict):<EOL><INDENT>extra = dict()<EOL><DEDENT>params = dict(pin=self.pin, sid=self.sid)<EOL>params.update(**extra)<EOL>req_url = ('<STR_LIT>' % (self.__webfsapi, path))<EOL>result = yield from self.__session.get(req_url, params=params,<EOL>timeout = self.timeout)<EOL>if result.status == <NUM_LIT:200>:<EOL><INDENT>text = yield from result.text(encoding='<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>self.sid = yield from self.create_session()<EOL>params = dict(pin=self.pin, sid=self.sid)<EOL>params.update(**extra)<EOL>result = yield from self.__session.get(req_url, params=params,<EOL>timeout = self.timeout)<EOL>text = yield from result.text(encoding='<STR_LIT:utf-8>')<EOL><DEDENT>return objectify.fromstring(text)<EOL><DEDENT>except Exception as e:<EOL><INDENT>logging.info('<STR_LIT>' +traceback.format_exc())<EOL><DEDENT>return None<EOL>


return (yield from self.play_control(<NUM_LIT:2>))<EOL>


self.__equalisers = yield from self.get_equalisers()<EOL>return (yield from self.collect_labels(self.__equalisers))<EOL>


return (yield from self.handle_text(self.API.get('<STR_LIT:text>')))<EOL>

Get the text associated with the played media.


return (yield from self.handle_set(<EOL>self.API.get('<STR_LIT>'), value))<EOL>


return (yield from self.play_control(<NUM_LIT:3>))<EOL>


doc = yield from self.handle_get(item)<EOL>if doc is None:<EOL><INDENT>return None<EOL><DEDENT>return int(doc.value.u8.text) or None<EOL>

Helper method for fetching a integer value.


return (yield from self.handle_text(self.API.get('<STR_LIT:name>')))<EOL>


_options = kwargs<EOL>def decorator(f):<EOL><INDENT>LOG.debug("<STR_LIT>", f, _options)<EOL>if _options.get('<STR_LIT>', True):<EOL><INDENT>f.required_methods = getattr(f, '<STR_LIT>', set())<EOL>f.required_methods.add('<STR_LIT>')<EOL>f.provide_automatic_options = False<EOL><DEDENT>def wrapped_function(*args, **kwargs):<EOL><INDENT>options = get_cors_options(current_app, _options)<EOL>if options.get('<STR_LIT>') and request.method == '<STR_LIT>':<EOL><INDENT>resp = current_app.make_default_options_response()<EOL><DEDENT>else:<EOL><INDENT>resp = make_response(f(*args, **kwargs))<EOL><DEDENT>set_cors_headers(resp, options)<EOL>setattr(resp, FLASK_CORS_EVALUATED, True)<EOL>return resp<EOL><DEDENT>return update_wrapper(wrapped_function, f)<EOL><DEDENT>return decorator<EOL>

This function is the decorator which is used to wrap a Flask route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication which may be brute-forced, you
should add some degree of protection, such as Cross Site Forgery
Request protection.

:param origins:
    The origin, or list of origins to allow requests from.
    The origin(s) may be regular expressions, case-sensitive strings,
    or else an asterisk

    Default : '*'
:type origins: list, string or regex

:param methods:
    The method or list of methods which the allowed origins are allowed to
    access for non-simple requests.

    Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string

:param expose_headers:
    The header or list which are safe to expose to the API of a CORS API
    specification.

    Default : None
:type expose_headers: list or string

:param allow_headers:
    The header or list of header field names which can be used when this
    resource is accessed by allowed origins. The header(s) may be regular
    expressions, case-sensitive strings, or else an asterisk.

    Default : '*', allow all headers
:type allow_headers: list, string or regex

:param supports_credentials:
    Allows users to make authenticated requests. If true, injects the
    `Access-Control-Allow-Credentials` header in responses. This allows
    cookies and credentials to be submitted across domains.

    :note: This option cannot be used in conjuction with a '*' origin

    Default : False
:type supports_credentials: bool

:param max_age:
    The maximum time for which this CORS request maybe cached. This value
    is set as the `Access-Control-Max-Age` header.

    Default : None
:type max_age: timedelta, integer, string or None

:param send_wildcard: If True, and the origins parameter is `*`, a wildcard
    `Access-Control-Allow-Origin` header is sent, rather than the
    request's `Origin` header.

    Default : False
:type send_wildcard: bool

:param vary_header:
    If True, the header Vary: Origin will be returned as per the W3
    implementation guidelines.

    Setting this header when the `Access-Control-Allow-Origin` is
    dynamically generated (e.g. when there is more than one allowed
    origin, and an Origin than '*' is returned) informs CDNs and other
    caches that the CORS headers are dynamic, and cannot be cached.

    If False, the Vary header will never be injected or altered.

    Default : True
:type vary_header: bool

:param automatic_options:
    Only applies to the `cross_origin` decorator. If True, Flask-CORS will
    override Flask's default OPTIONS handling to return CORS headers for
    OPTIONS requests.

    Default : True
:type automatic_options: bool


options = DEFAULT_OPTIONS.copy()<EOL>options.update(get_app_kwarg_dict(appInstance))<EOL>if dicts:<EOL><INDENT>for d in dicts:<EOL><INDENT>options.update(d)<EOL><DEDENT><DEDENT>return serialize_options(options)<EOL>

Compute CORS options for an application by combining the DEFAULT_OPTIONS,
the app's configuration-specified options and any dictionaries passed. The
last specified option wins.


if isinstance(inst, string_types):<EOL><INDENT>return [inst]<EOL><DEDENT>elif not isinstance(inst, collections.Iterable):<EOL><INDENT>return [inst]<EOL><DEDENT>else:<EOL><INDENT>return inst<EOL><DEDENT>

Wraps scalars or string types as a list, or returns the iterable instance.


options = (opts or {}).copy()<EOL>for key in opts.keys():<EOL><INDENT>if key not in DEFAULT_OPTIONS:<EOL><INDENT>LOG.warning("<STR_LIT>", key)<EOL><DEDENT><DEDENT>options['<STR_LIT>'] = sanitize_regex_param(options.get('<STR_LIT>'))<EOL>options['<STR_LIT>'] = sanitize_regex_param(options.get('<STR_LIT>'))<EOL>if r'<STR_LIT>' in options['<STR_LIT>'] and options['<STR_LIT>'] and options['<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>serialize_option(options, '<STR_LIT>')<EOL>serialize_option(options, '<STR_LIT>', upper=True)<EOL>if isinstance(options.get('<STR_LIT>'), timedelta):<EOL><INDENT>options['<STR_LIT>'] = str(int(options['<STR_LIT>'].total_seconds()))<EOL><DEDENT>return options<EOL>

A helper method to serialize and processes the options dictionary.


return r'<STR_LIT>' if reg == r'<STR_LIT:*>' else reg<EOL>

Replace the invalid regex r'*' with the valid, wildcard regex r'/.*' to
enable the CORS app extension to have a more user friendly api.


<EOL>if hasattr(resp, FLASK_CORS_EVALUATED):<EOL><INDENT>LOG.debug('<STR_LIT>')<EOL>return resp<EOL><DEDENT>if (not isinstance(resp.headers, Headers)<EOL>and not isinstance(resp.headers, MultiDict)):<EOL><INDENT>resp.headers = MultiDict(resp.headers)<EOL><DEDENT>headers_to_set = get_cors_headers(options, request.headers, request.method)<EOL>LOG.debug('<STR_LIT>', str(headers_to_set))<EOL>for k, v in headers_to_set.items():<EOL><INDENT>resp.headers.add(k, v)<EOL><DEDENT>return resp<EOL>

Performs the actual evaluation of Flas-CORS options and actually
modifies the response object.

This function is used both in the decorator and the after_request
callback


if isinstance(maybe_regex, RegexObject):<EOL><INDENT>return re.match(maybe_regex, request_origin)<EOL><DEDENT>elif probably_regex(maybe_regex):<EOL><INDENT>return re.match(maybe_regex, request_origin, flags=re.IGNORECASE)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return request_origin.lower() == maybe_regex.lower()<EOL><DEDENT>except AttributeError:<EOL><INDENT>return request_origin == maybe_regex<EOL><DEDENT><DEDENT>

Safely attempts to match a pattern or string to a request origin.


return

Since the path '/' does not match the regular expression r'/api/*',
this route does not have CORS headers set.


return jsonify(success=True)<EOL>

Since the path matches the regular expression r'/api/*', this resource
automatically has CORS headers set.

Browsers will first make a preflight request to verify that the resource
allows cross-origin POSTs with a JSON Content-Type, which can be simulated
as:
$ curl --include -X OPTIONS http://127.0.0.1:5000/api/v1/users/create \
    --header Access-Control-Request-Method:POST \
    --header Access-Control-Request-Headers:Content-Type \
    --header Origin:www.examplesite.com
>> HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: POST, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Content-Length: 0
Server: Werkzeug/0.9.6 Python/2.7.9
Date: Sat, 31 Jan 2015 22:25:22 GMT

$ curl --include -X POST http://127.0.0.1:5000/api/v1/users/create \
    --header Content-Type:application/json \
    --header Origin:www.examplesite.com

>> HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 21
Access-Control-Allow-Origin: *
Server: Werkzeug/0.9.6 Python/2.7.9
Date: Sat, 31 Jan 2015 22:25:04 GMT

{
  "success": true
}


raise Exception("<STR_LIT>")<EOL>

Since the path matches the regular expression r'/api/*', this resource
automatically has CORS headers set.

Browsers will first make a preflight request to verify that the resource
allows cross-origin POSTs with a JSON Content-Type, which can be simulated
as:
$ curl --include -X OPTIONS http://127.0.0.1:5000/exception \
    --header Access-Control-Request-Method:POST \
    --header Access-Control-Request-Headers:Content-Type \
    --header Origin:www.examplesite.com
>> HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: POST, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Content-Length: 0
Server: Werkzeug/0.9.6 Python/2.7.9
Date: Sat, 31 Jan 2015 22:25:22 GMT


return jsonify(user="<STR_LIT>")<EOL>

Since the path matches the regular expression r'/api/*', this resource
automatically has CORS headers set. The expected result is as follows:

$ curl --include -X GET http://127.0.0.1:5000/api/v1/users/ \
    --header Origin:www.examplesite.com
HTTP/1.0 200 OK
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Origin: *
Content-Length: 21
Content-Type: application/json
Date: Sat, 09 Aug 2014 00:26:41 GMT
Server: Werkzeug/0.9.4 Python/2.7.8

{
    "success": true
}


return '''<STR_LIT>'''<EOL>


return jsonify(success=True)<EOL>


def extract_data_from_file(file_location: str, parser: Callable[[str], Any]=lambda data: data, separator: str=None)-> List[Any]:

with open(file_location, '<STR_LIT:r>') as file:<EOL><INDENT>contents = file.read()<EOL><DEDENT>if separator is not None:<EOL><INDENT>raw_data = contents.split(separator)<EOL><DEDENT>else:<EOL><INDENT>raw_data = [contents]<EOL><DEDENT>extracted = []<EOL>for item in raw_data:<EOL><INDENT>parsed = parser(item)<EOL>extracted.append(parsed)<EOL><DEDENT>return extracted<EOL>

Extracts data from the file at the given location, using the given parser.
:param file_location: the location of the file to read data from
:param parser: the parser to extract data from the file
:param separator: (optional) separator for data in the file
:return: the extracted data


blocked = True<EOL>def unblock(*args):<EOL><INDENT>nonlocal blocked<EOL>blocked = False<EOL><DEDENT>event_handler = FileSystemEventHandler()<EOL>event_handler.on_modified = unblock<EOL>source._observer.schedule(event_handler, source._directory_location, recursive=True)<EOL>temp_file_name = "<STR_LIT>" % block_until_synchronised_files_data_source_started.__name__<EOL>temp_file_path = os.path.join(source._directory_location, temp_file_name)<EOL>i = <NUM_LIT:0><EOL>while blocked:<EOL><INDENT>with open(temp_file_path, '<STR_LIT:a>') as file:<EOL><INDENT>file.write(str(i))<EOL><DEDENT>sleep(<NUM_LIT:10> / <NUM_LIT:1000>)<EOL>i += <NUM_LIT:1><EOL><DEDENT>

Blocks until the given synchronised files data source has started to notice changes in the file system (may be a few
milliseconds after it has been started).
:param source: the synchronised files data source that has been started


def _add_more_data_in_nested_directory(self, number_of_extra_files: int=<NUM_LIT:1>) -> Tuple[str, List[int]]:

nested_directory_path = os.path.join(self.temp_directory, "<STR_LIT>")<EOL>os.makedirs(nested_directory_path)<EOL>more_data = [i for i in range(<NUM_LIT:50>)]<EOL>write_data_to_files_in_temp_directory(more_data, number_of_extra_files, dir=nested_directory_path,<EOL>file_prefix=TestSynchronisedFilesDataSource._FILE_PREFIX)<EOL>return (nested_directory_path, more_data)<EOL>

Adds more data in a directory nested inside the temp directory.
:param number_of_extra_files: (optional) the number of files to put the new data in inside the nested directory
:return: a tuple where the first value is the path to the new nested directory and the second is the new data


def rename(self, key: Any, new_key: Any):

if new_key == key:<EOL><INDENT>return<EOL><DEDENT>required_locks = [self._key_locks[key], self._key_locks[new_key]]<EOL>ordered_required_locks = sorted(required_locks, key=lambda x: id(x))<EOL>for lock in ordered_required_locks:<EOL><INDENT>lock.acquire()<EOL><DEDENT>try:<EOL><INDENT>if key not in self._data:<EOL><INDENT>raise KeyError("<STR_LIT>" % key)<EOL><DEDENT>self._data[new_key] = self[key]<EOL>del self._data[key]<EOL><DEDENT>finally:<EOL><INDENT>for lock in required_locks:<EOL><INDENT>lock.release()<EOL><DEDENT><DEDENT>

Renames an item in this collection as a transaction.

Will override if new key name already exists.
:param key: the current name of the item
:param new_key: the new name that the item should have


self._data = dict(seq)<EOL>self._key_locks = ThreadSafeDefaultdict(Lock)<EOL>

Constructor.
:param seq: initial metadata items


def __init__(self, directory_location: str, data_type: type):

super().__init__(directory_location)<EOL>self._data_type = data_type<EOL>

Constructor.
:param directory_location: the location of the directory
:param data_type: the type of data that is loaded from files in the given directory


listenable = registration_event_listenable_map[type(registerable)]<EOL>event = RegistrationEvent(registerable, RegistrationEvent.Type.UNREGISTERED)<EOL>listenable.notify_listeners(event)<EOL>

Unregisters an object, notifying any listeners that may be interested in it.
:param registerable: the object to unregister


def _on_file_moved(self, event: FileSystemMovedEvent):

if not event.is_directory and self.is_data_file(event.src_path):<EOL><INDENT>delete_event = FileSystemEvent(event.src_path)<EOL>delete_event.event_type = EVENT_TYPE_DELETED<EOL>self._on_file_deleted(delete_event)<EOL>create_event = FileSystemEvent(event.dest_path)<EOL>create_event.event_type = EVENT_TYPE_CREATED<EOL>self._on_file_created(create_event)<EOL><DEDENT>

Called when a file in the monitored directory has been moved.

Breaks move down into a delete and a create (which it is sometimes detected as!).
:param event: the file system event


def _on_file_modified(self, event: FileSystemEvent):

if not event.is_directory and self.is_data_file(event.src_path):<EOL><INDENT>assert event.src_path in self._origin_mapped_data<EOL>self._origin_mapped_data[event.src_path] = self.no_error_extract_data_from_file(event.src_path)<EOL>self.notify_listeners(FileSystemChange.MODIFY)<EOL><DEDENT>

Called when a file in the monitored directory has been modified.
:param event: the file system event


with self._status_lock:<EOL><INDENT>if self._running:<EOL><INDENT>assert self._observer is not None<EOL>self._observer.stop()<EOL>self._running = False<EOL>self._origin_mapped_data = dict()<EOL><DEDENT><DEDENT>

Stops monitoring the predefined directory.


def _on_file_deleted(self, event: FileSystemEvent):

if not event.is_directory and self.is_data_file(event.src_path):<EOL><INDENT>assert event.src_path in self._origin_mapped_data<EOL>del(self._origin_mapped_data[event.src_path])<EOL>self.notify_listeners(FileSystemChange.DELETE)<EOL><DEDENT>

Called when a file in the monitored directory has been deleted.
:param event: the file system event


@abstractmethod<EOL><INDENT>def extract_data_from_file(self, file_path: str) -> Iterable[DataSourceType]:<DEDENT>

Extracts data from the file at the given file path.
:param file_path: the path to the file to extract data from
:return: the extracted data


def _create_client(base_url: str, tls: TLSConfig=False) -> Optional[APIClient]:

try:<EOL><INDENT>client = APIClient(base_url=base_url, tls=tls, version="<STR_LIT>")<EOL>return client if client.ping() else None<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>

Creates a Docker client with the given details.
:param base_url: the base URL of the Docker daemon
:param tls: the Docker daemon's TLS config (if any)
:return: the created client else None if unable to connect the client to the daemon


global _client<EOL>client = _client()<EOL>if client is None:<EOL><INDENT>docker_environment = kwargs_from_env(assert_hostname=False)<EOL>if "<STR_LIT>" in docker_environment:<EOL><INDENT>client = _create_client(docker_environment.get("<STR_LIT>"), docker_environment.get("<STR_LIT>"))<EOL>if client is None:<EOL><INDENT>raise ConnectionError(<EOL>"<STR_LIT>"<EOL>% docker_environment)<EOL><DEDENT>else:<EOL><INDENT>logging.info("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>client = _create_client("<STR_LIT>")<EOL>if client is not None:<EOL><INDENT>logging.info("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise ConnectionError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>_client = weakref.ref(client)<EOL><DEDENT>assert isinstance(client, APIClient)<EOL>return client<EOL>

Clients a Docker client.

Will raise a `ConnectionError` if the Docker daemon is not accessible.
:return: the Docker client


def create_temp_directory(self, **mkdtemp_kwargs) -> str:

kwargs = {**self.default_mkdtemp_kwargs, **mkdtemp_kwargs}<EOL>location = tempfile.mkdtemp(**kwargs)<EOL>self._temp_directories.add(location)<EOL>return location<EOL>

Creates a temp directory.
:param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp`
:return: the location of the temp directory


def __init__(self, default_mkdtemp_kwargs: dict=None, default_mkstemp_kwargs: dict=None):

self.default_mkdtemp_kwargs = default_mkdtemp_kwargs if default_mkdtemp_kwargs is not None else {}<EOL>self.default_mkstemp_kwargs = default_mkstemp_kwargs if default_mkstemp_kwargs is not None else {}<EOL>self._temp_directories = set()  <EOL>self._temp_files = set()    <EOL>atexit.register(self.tear_down)<EOL>

Constructor.
:param default_mkdtemp_kwargs:
:param default_mkstemp_kwargs:


def extract_version_number(string: str) -> str:

matched = _EXTRACT_VERSION_PATTERN.search(string)<EOL>if matched is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return matched.group().replace("<STR_LIT:_>", "<STR_LIT:.>")<EOL>

Extracts a version from a string in the form: `.*[0-9]+(_[0-9]+)*.*`, e.g. Irods4_1_9CompatibleController.

If the string contains multiple version numbers, the first (from left) is extracted.

Will raise a `ValueError` if there is no version number in the given string.
:param string: the string containing the version number
:return: the extracted version


def create_random_string(postfix: str= "<STR_LIT>", prefix: str="<STR_LIT>") -> str:

return "<STR_LIT>" % (prefix, uuid4(), postfix)<EOL>

Creates a random string.
:param postfix: optional postfix
:param prefix: optional prefix
:return: created string


free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<EOL>free_socket.bind(("<STR_LIT>", <NUM_LIT:0>))<EOL>free_socket.listen(<NUM_LIT:1>)<EOL>port = free_socket.getsockname()[<NUM_LIT:1>]<EOL>free_socket.close()<EOL>return port<EOL>

Gets a PORT that will (probably) be available on the machine.
It is possible that in-between the time in which the open PORT of found and when it is used, another process may
bind to it instead.
:return: the (probably) available PORT


self._lock = Lock(*args, **kwargs)<EOL>self._stat_lock = Lock()<EOL>self._waiting = <NUM_LIT:0><EOL>self._locked = False  <EOL>self._last_released = datetime.now()<EOL>


with self._stat_lock:<EOL><INDENT>self._waiting += <NUM_LIT:1><EOL><DEDENT>self._lock.acquire(*args, **kwargs)<EOL>with self._stat_lock:<EOL><INDENT>self._locked = True<EOL>self._waiting -= <NUM_LIT:1><EOL><DEDENT>


self._lock.release()<EOL>with self._stat_lock:<EOL><INDENT>self._locked = False<EOL>self._last_released = datetime.now()<EOL><DEDENT>


with self._stat_lock:<EOL><INDENT>return self._locked<EOL><DEDENT>


def __init__(self, target: _RegistrationTarget, event_type: Type):

self.target = target<EOL>self.event_type = event_type<EOL>

Constructor.
:param target: the object the event refers to
:param event_type: the type of update event


def remove_listener(self, listener: Callable[[_ListenableDataType], None]):

Removes a listener.
:param listener: the event listener to remove


if value == Priority.MIN_PRIORITY:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return value + <NUM_LIT:1><EOL>

Gets a lower priority value than that given.

Will raise a `ValueError` if already lowest priority value.
:param value: gets a lower priority value than this
:return: the lower priority value


if value == Priority.MAX_PRIORITY:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return value - <NUM_LIT:1><EOL>

Gets a higher priority value than that given.

Will raise a `ValueError` if already highest priority value.
:param value: gets a higher priority value than this
:return: the higher priority value


if isinstance(value, bool):<EOL><INDENT>if value:<EOL><INDENT>return '<STR_LIT:true>'<EOL><DEDENT>return '<STR_LIT:false>'<EOL><DEDENT>return value or arg<EOL>

Given a Python boolean value converts it to string representation so
    we can use it in HTML data attributes. If value is None use given default
    or '' if default is not provided.

    -----       ------
    Value       Output
    -----       ------
    True        "true"
    False       "false"
    None        arg


bits = token.split_contents()<EOL>tag_name = bits[<NUM_LIT:0>]<EOL>if len(bits) < <NUM_LIT:2>:<EOL><INDENT>raise TemplateSyntaxError("<STR_LIT>" %<EOL>tag_name)<EOL><DEDENT>args = []<EOL>kwargs = {}<EOL>bits = bits[<NUM_LIT:1>:]<EOL>if len(bits):<EOL><INDENT>for bit in bits:<EOL><INDENT>match = kwarg_re.match(bit)<EOL>if not match:<EOL><INDENT>raise TemplateSyntaxError("<STR_LIT>" %<EOL>tag_name)<EOL><DEDENT>name, value = match.groups()<EOL>if name:<EOL><INDENT>name = name.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>kwargs[name] = parser.compile_filter(value)<EOL><DEDENT>else:<EOL><INDENT>args.append(parser.compile_filter(value))<EOL><DEDENT><DEDENT><DEDENT>return SocialWidgetNode(args, kwargs)<EOL>

Renders the selected social widget. You can specify optional settings
    that will be passed  to widget template.

    Sample usage:
    {% social_widget_render widget_template ke1=val1 key2=val2 %}

    For example to render Twitter follow button you can use code like this:
    {% social_widget_render 'twitter/follow_button.html' username="ev" %}


def _subscribe_mock(self, signal_name, weak):

callback = mock.Mock()<EOL>decorator = self.model.subscribe(signal_name, weak)<EOL>return decorator(callback)<EOL>

Create a mock callback function and subscribe it to the specific
        signal on ``self.model``.


cmd = "<STR_LIT>".format(port)<EOL>if daemon:<EOL><INDENT>cmd += "<STR_LIT>"<EOL><DEDENT>run(cmd)<EOL>


version = '<STR_LIT>'<EOL>with open(fname, '<STR_LIT:r>') as fp:<EOL><INDENT>reg = re.compile(r'<STR_LIT>')<EOL>for line in fp:<EOL><INDENT>m = reg.match(line)<EOL>if m:<EOL><INDENT>version = m.group(<NUM_LIT:1>)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if not version:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return version<EOL>

Attempts to find the version number in the file names fname.
    Raises RuntimeError if not found.


if isinstance(value, list):<EOL><INDENT>return FrozenList(*value)<EOL><DEDENT>if isinstance(value, dict):<EOL><INDENT>return FrozenDict(**value)<EOL><DEDENT>return value<EOL>


def wrapper(cls):<EOL><INDENT>for label, ProxiedClass in six.iteritems(proxy_map):<EOL><INDENT>proxy = proxy_factory(cls, label, ProxiedClass, get_key)<EOL>setattr(cls, label, proxy)<EOL><DEDENT>return cls<EOL><DEDENT>return wrapper<EOL>

Class decorator factory; adds proxy class variables to target class.

    :param dict proxy_map: Mapping between class variable labels and proxied
        classes
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request


def proxy_factory(BaseSchema, label, ProxiedClass, get_key):

def local():<EOL><INDENT>key = get_key()<EOL>try:<EOL><INDENT>return proxies[BaseSchema][label][key]<EOL><DEDENT>except KeyError:<EOL><INDENT>proxies[BaseSchema][label][key] = ProxiedClass()<EOL>return proxies[BaseSchema][label][key]<EOL><DEDENT><DEDENT>return LocalProxy(local)<EOL>

Create a proxy to a class instance stored in ``proxies``.

    :param class BaseSchema: Base schema (e.g. ``StoredObject``)
    :param str label: Name of class variable to set
    :param class ProxiedClass: Class to get or create
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request


if value is None:<EOL><INDENT>return None<EOL><DEDENT>if isinstance(value, self.base_class):<EOL><INDENT>if not value._is_loaded:<EOL><INDENT>raise exceptions.DatabaseError('<STR_LIT>')<EOL><DEDENT>return value._primary_key<EOL><DEDENT>return self.base_class._to_primary_key(value)<EOL>

Return primary key; if value is StoredObject, verify
that it is loaded.


@classmethod<EOL><INDENT>def delegate(cls, method, conflict=None, *args, **kwargs):<DEDENT>

if cls.queue.active:<EOL><INDENT>action = WriteAction(method, *args, **kwargs)<EOL>if conflict:<EOL><INDENT>logger.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(action))<EOL><DEDENT>cls.queue.push(action)<EOL><DEDENT>else:<EOL><INDENT>method(*args, **kwargs)<EOL><DEDENT>

Execute or queue a database action. Variable positional and keyword
        arguments are passed to the provided method.

        :param function method: Method to execute or queue
        :param bool conflict: Potential conflict between cache_sandbox and backend,
            e.g., in the event of bulk updates or removes that bypass the
            cache_sandbox


@wraps(func)<EOL>def wrapped(this, *args, **kwargs):<EOL><INDENT>if '<STR_LIT>' in this.__dict__ and this._detached:<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL><DEDENT>return func(this, *args, **kwargs)<EOL><DEDENT>return wrapped<EOL>


@classmethod<EOL><INDENT>@has_storage<EOL>def remove_one(cls, which, rm=True):<DEDENT>

<EOL>obj = cls._which_to_obj(which)<EOL>rm_fwd_refs(obj)<EOL>rm_back_refs(obj)<EOL>cls._clear_caches(obj._storage_key)<EOL>if rm:<EOL><INDENT>cls.delegate(<EOL>cls._storage[<NUM_LIT:0>].remove,<EOL>False,<EOL>RawQuery(obj._primary_name, '<STR_LIT>', obj._storage_key)<EOL>)<EOL><DEDENT>obj._detached = True<EOL>

Remove an object, along with its references and back-references.
        Remove the object from the cache_sandbox and sets its _detached flag to True.

        :param which: Object selector: Query, StoredObject, or primary key
        :param rm: Remove data from backend


@classmethod<EOL><INDENT>@has_storage<EOL>@log_storage<EOL>def load(cls, key=None, data=None, _is_loaded=True):<DEDENT>

<EOL>signals.load.send(<EOL>cls,<EOL>key=key,<EOL>data=data,<EOL>)<EOL>if key is not None:<EOL><INDENT>key = cls._check_pk_type(key)<EOL>cached_object = cls._load_from_cache(key)<EOL>if cached_object is not None:<EOL><INDENT>return cached_object<EOL><DEDENT><DEDENT>if data is None:<EOL><INDENT>data = cls._storage[<NUM_LIT:0>].get(cls._primary_name, cls._pk_to_storage(key))<EOL><DEDENT>if data is None:<EOL><INDENT>return None<EOL><DEDENT>data = cls.from_storage(data)<EOL>if cls._version_of and '<STR_LIT>' in data and data['<STR_LIT>'] != cls._version:<EOL><INDENT>old_object = cls._version_of.load(data=data)<EOL>new_object = cls(_is_loaded=_is_loaded)<EOL>cls.migrate(old_object, new_object)<EOL>new_object._stored_key = new_object._primary_key<EOL>return new_object<EOL><DEDENT>ret = cls(_is_loaded=_is_loaded, **data)<EOL>ret._stored_key = ret._primary_key<EOL>return ret<EOL>


@classmethod<EOL><INDENT>def subscribe(cls, signal_name, weak=True):<DEDENT>

try:<EOL><INDENT>signal = getattr(signals, signal_name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(signal_name)<EOL>)<EOL><DEDENT>sender = None if cls._is_root else cls<EOL>return signal.connect_via(sender, weak)<EOL>

:param str signal_name: Name of signal to subscribe to; must be found
    in ``signals.py``.
:param bool weak: Create weak reference to callback
:returns: Decorator created by ``Signal::connect_via``
:raises: ValueError if signal is not found

Example usage: ::

    >>> @Schema.subscribe('before_save')
    ... def listener(cls, instance):
    ...     instance.value += 1


objs = cls.find(query)<EOL>for obj in objs:<EOL><INDENT>cls.remove_one(obj, rm=False)<EOL><DEDENT>cls.delegate(<EOL>cls._storage[<NUM_LIT:0>].remove,<EOL>False,<EOL>query<EOL>)<EOL>

Remove objects by query.

        :param query: Query object


@classmethod<EOL><INDENT>def migrate(cls, old, new, verbose=True, dry_run=False, rm_refs=True):<DEDENT>

if verbose:<EOL><INDENT>logging.basicConfig(format='<STR_LIT>',<EOL>level=logging.DEBUG)<EOL><DEDENT>deleted_fields = [field for field in old._fields if field not in new._fields]<EOL>added_fields = [field for field in new._fields if field not in old._fields]<EOL>logging.info('<STR_LIT>'.format(deleted_fields))<EOL>logging.info('<STR_LIT>'.format(added_fields))<EOL>if old._primary_name != new._primary_name:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(old_name=old._primary_name,<EOL>old_field=old._fields[old._primary_name],<EOL>new_name=new._primary_name,<EOL>new_field=new._fields[new._primary_name]))<EOL><DEDENT>for field in old._fields:<EOL><INDENT>if field not in cls._fields:<EOL><INDENT>if rm_refs:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(name=field,<EOL>field=old._fields[field]))<EOL>if not dry_run:<EOL><INDENT>rm_fwd_refs(old)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(name=field,<EOL>field=old._fields[field]))<EOL><DEDENT>continue<EOL><DEDENT>old_field_obj = old._fields[field]<EOL>new_field_obj = new._fields[field]<EOL>if old_field_obj != new_field_obj:<EOL><INDENT>if not old_field_obj._required and new_field_obj._required:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(name=field))<EOL><DEDENT>else:<EOL><INDENT>logging.info(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(name=field,<EOL>old_field=old_field_obj,<EOL>new_field=new_field_obj)<EOL>)<EOL><DEDENT>continue<EOL><DEDENT>if not dry_run:<EOL><INDENT>field_object = cls._fields[field]<EOL>field_object.__set__(<EOL>new,<EOL>getattr(old, field),<EOL>safe=True<EOL>)<EOL><DEDENT><DEDENT>if not dry_run:<EOL><INDENT>new.__backrefs = old.__backrefs<EOL><DEDENT>if not dry_run:<EOL><INDENT>cls._migrate(old, new)<EOL><DEDENT>

Migrate record to new schema.

        :param old: Record from original schema
        :param new: Record from new schema
        :param verbose: Print detailed info
        :param dry_run: Dry run; make no changes if true
        :param rm_refs: Remove references on deleted fields


def _optimistic_insert(self, primary_name, value, n=<NUM_LIT:5>):

while True:<EOL><INDENT>try:<EOL><INDENT>key = self._generate_random_id(n)<EOL>value[primary_name] = key<EOL>self.insert(primary_name, key, value)<EOL>break<EOL><DEDENT>except KeyExistsException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return key<EOL>

Attempt to insert with randomly generated key until insert
        is successful.

        :param str primary_name: The name of the primary key.
        :param dict value: The dictionary representation of the record.
        :param n: Number of characters in random key


alphabet = '<STR_LIT>'<EOL>return '<STR_LIT>'.join(random.sample(alphabet, n))<EOL>

Generated random alphanumeric key.

        :param n: Number of characters in random key


@abc.abstractmethod<EOL><INDENT>def get(self, primary_name, key):<DEDENT>

pass<EOL>

Get a single record.

        :param str primary_name: The name of the primary key.
        :param key: The value of the primary key.


@abc.abstractmethod<EOL><INDENT>def update(self, query, data):<DEDENT>

pass<EOL>

Update multiple records with new data.

        :param query: A query object.
        :param dict data: Dictionary of key:value pairs.


pass<EOL>


while self.pos < self.max_pos:<EOL><INDENT>match = self.find_match()<EOL>self.pos = match.end()<EOL><DEDENT>return self.root()<EOL>

Parse the given string data and sequentually update the current
        cursor position until the end is reached.

        Return the Root object if successful.


raise IgnoredMatchException<EOL>

Ignore lines that contain three dash symbols.


raise IgnoredMatchException<EOL>


def assert_command_id(self, request, target_id):<EOL>

<EOL>command_id = request.ams_header.command_id<EOL>command_id = struct.unpack('<STR_LIT>', command_id)[<NUM_LIT:0>]<EOL>self.assertEqual(command_id, target_id)<EOL>


cls.test_server = AdsTestServer(logging=True)<EOL>cls.test_server.start()<EOL>time.sleep(<NUM_LIT:1>)<EOL>


self.stop()<EOL>


def __exit__(self, exc_type, exc_value, traceback):<EOL>

self.close()<EOL>


if self._run:<EOL><INDENT>logger.info(<EOL>"<STR_LIT>".format(*self.client_address)<EOL>)<EOL>self._run = False<EOL><DEDENT>self.join()<EOL>


self._run = True<EOL>self.server.listen(<NUM_LIT:5>)<EOL>logger.info(<EOL>"<STR_LIT>".format(<EOL>self.ip_address or "<STR_LIT:localhost>", self.port<EOL>)<EOL>)<EOL>while self._run:<EOL><INDENT>ready, _, _ = select.select([self.server], [], [], <NUM_LIT:0.1>)<EOL>if ready:<EOL><INDENT>try:<EOL><INDENT>client, address = self.server.accept()<EOL><DEDENT>except:<EOL><INDENT>continue<EOL><DEDENT>logger.info("<STR_LIT>".format(*address))<EOL>client_thread = AdsClientConnection(<EOL>handler=self.handler, client=client, address=address, server=self<EOL>)<EOL>client_thread.daemon = True<EOL>client_thread.start()<EOL>self.clients.append(client_thread)<EOL><DEDENT><DEDENT>

Listen for incoming connections from clients.


data = request_bytes  <EOL>tcp_header = AmsTcpHeader(data[<NUM_LIT:2>:<NUM_LIT:6>])<EOL>ams_header = AmsHeader(<EOL>data[<NUM_LIT:6>:<NUM_LIT:12>],<EOL>data[<NUM_LIT:12>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT:20>],<EOL>data[<NUM_LIT:20>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT:30>],<EOL>data[<NUM_LIT:30>:<NUM_LIT>],<EOL>data[<NUM_LIT>:<NUM_LIT>],<EOL>data[<NUM_LIT>:],<EOL>)<EOL>return AmsPacket(tcp_header, ams_header)<EOL>

Unpack an AMS packet from binary data.

        :param bytes request_bytes: The raw request data
        :rtype AmsPacket:
        :return: AmsPacket with fields populated from the binary data


<EOL>command_id_bytes = request.ams_header.command_id<EOL>command_id = struct.unpack("<STR_LIT>", command_id_bytes)[<NUM_LIT:0>]<EOL>state = struct.unpack("<STR_LIT>", request.ams_header.state_flags)[<NUM_LIT:0>]<EOL>state = state | <NUM_LIT>  <EOL>state = struct.pack("<STR_LIT>", state)<EOL>def handle_read_device_info():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>major_version = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>minor_version = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>version_build = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>device_name = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>response_content = (<EOL>major_version + minor_version + version_build + device_name<EOL>)<EOL>return response_content<EOL><DEDENT>def handle_read():<EOL><INDENT>"""<STR_LIT>"""<EOL>data = request.ams_header.data<EOL>index_group = struct.unpack("<STR_LIT>", data[:<NUM_LIT:4>])[<NUM_LIT:0>]<EOL>index_offset = struct.unpack("<STR_LIT>", data[<NUM_LIT:4>:<NUM_LIT:8>])[<NUM_LIT:0>]<EOL>plc_datatype = struct.unpack("<STR_LIT>", data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>logger.info(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(index_group, index_offset, plc_datatype)<EOL>)<EOL>if index_group == constants.ADSIGRP_SYM_VALBYHND:<EOL><INDENT>response_value = self._named_data[index_offset].value<EOL><DEDENT>else:<EOL><INDENT>response_value = self._data[(index_group, index_offset)][:plc_datatype]<EOL><DEDENT>return struct.pack("<STR_LIT>", len(response_value)) + response_value<EOL><DEDENT>def handle_write():<EOL><INDENT>"""<STR_LIT>"""<EOL>data = request.ams_header.data<EOL>index_group = struct.unpack("<STR_LIT>", data[:<NUM_LIT:4>])[<NUM_LIT:0>]<EOL>index_offset = struct.unpack("<STR_LIT>", data[<NUM_LIT:4>:<NUM_LIT:8>])[<NUM_LIT:0>]<EOL>plc_datatype = struct.unpack("<STR_LIT>", data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>value = data[<NUM_LIT:12>:(<NUM_LIT:12> + plc_datatype)]<EOL>logger.info(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(index_group, index_offset, plc_datatype, value)<EOL>)<EOL>if index_group == constants.ADSIGRP_SYM_RELEASEHND:<EOL><INDENT>return b"<STR_LIT>"<EOL><DEDENT>elif index_group == constants.ADSIGRP_SYM_VALBYHND:<EOL><INDENT>self._named_data[index_offset].value = value<EOL>return b"<STR_LIT>"<EOL><DEDENT>self._data[(index_group, index_offset)] = value<EOL>return b"<STR_LIT>"<EOL><DEDENT>def handle_read_write():<EOL><INDENT>"""<STR_LIT>"""<EOL>data = request.ams_header.data<EOL>index_group = struct.unpack("<STR_LIT>", data[:<NUM_LIT:4>])[<NUM_LIT:0>]<EOL>index_offset = struct.unpack("<STR_LIT>", data[<NUM_LIT:4>:<NUM_LIT:8>])[<NUM_LIT:0>]<EOL>read_length = struct.unpack("<STR_LIT>", data[<NUM_LIT:8>:<NUM_LIT:12>])[<NUM_LIT:0>]<EOL>write_length = struct.unpack("<STR_LIT>", data[<NUM_LIT:12>:<NUM_LIT:16>])[<NUM_LIT:0>]<EOL>write_data = data[<NUM_LIT:16>:(<NUM_LIT:16> + write_length)]<EOL>logger.info(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(<EOL>index_group, index_offset, read_length, write_length, write_data<EOL>)<EOL>)<EOL>if index_group == constants.ADSIGRP_SYM_HNDBYNAME:<EOL><INDENT>var_name = write_data.decode()<EOL>names = [x.name for x in self._named_data]<EOL>try:<EOL><INDENT>handle = names.index(var_name)<EOL><DEDENT>except ValueError:<EOL><INDENT>self._named_data.append(PLCVariable(name=var_name, value=bytes(<NUM_LIT:16>)))<EOL>handle = len(self._named_data) - <NUM_LIT:1><EOL><DEDENT>read_data = struct.pack("<STR_LIT>", handle)<EOL><DEDENT>else:<EOL><INDENT>read_data = self._data[(index_group, index_offset)][:read_length]<EOL>self._data[(index_group, index_offset)] = write_data<EOL><DEDENT>return struct.pack("<STR_LIT>", len(read_data)) + read_data<EOL><DEDENT>def handle_read_state():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>ads_state = struct.pack("<STR_LIT>", constants.ADSSTATE_RUN)<EOL>device_state = struct.pack("<STR_LIT>", <NUM_LIT:0>)<EOL>return ads_state + device_state<EOL><DEDENT>def handle_writectrl():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>return b"<STR_LIT>"<EOL><DEDENT>def handle_add_devicenote():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>handle = ("<STR_LIT>" * <NUM_LIT:4>).encode("<STR_LIT:utf-8>")<EOL>return handle<EOL><DEDENT>def handle_delete_devicenote():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>return b"<STR_LIT>"<EOL><DEDENT>def handle_devicenote():<EOL><INDENT>"""<STR_LIT>"""<EOL>logger.info("<STR_LIT>")<EOL>return b"<STR_LIT>"<EOL><DEDENT>function_map = {<EOL>constants.ADSCOMMAND_READDEVICEINFO: handle_read_device_info,<EOL>constants.ADSCOMMAND_READ: handle_read,<EOL>constants.ADSCOMMAND_WRITE: handle_write,<EOL>constants.ADSCOMMAND_READWRITE: handle_read_write,<EOL>constants.ADSCOMMAND_READSTATE: handle_read_state,<EOL>constants.ADSCOMMAND_WRITECTRL: handle_writectrl,<EOL>constants.ADSCOMMAND_ADDDEVICENOTE: handle_add_devicenote,<EOL>constants.ADSCOMMAND_DELDEVICENOTE: handle_delete_devicenote,<EOL>constants.ADSCOMMAND_DEVICENOTE: handle_devicenote,<EOL>}<EOL>try:<EOL><INDENT>response_content = function_map[command_id]()<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.info("<STR_LIT>".format(hex(command_id)))<EOL>error_code = "<STR_LIT>".encode("<STR_LIT:utf-8>")<EOL>return AmsResponseData(state, error_code, "<STR_LIT>".encode("<STR_LIT:utf-8>"))<EOL><DEDENT>error_code = ("<STR_LIT:\x00>" * <NUM_LIT:4>).encode("<STR_LIT:utf-8>")<EOL>response_data = error_code + response_content<EOL>return AmsResponseData(state, request.ams_header.error_code, response_data)<EOL>

Handle incoming requests and create a response.


return c_int16 * n<EOL>


return c_short * n<EOL>


return c_float * n<EOL>


return c_double * n<EOL>


def read_by_name(self, data_name, plc_datatype, return_ctypes=False):<EOL>

if self._port:<EOL><INDENT>return adsSyncReadByNameEx(self._port, self._adr, data_name, plc_datatype, return_ctypes)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device from data name.

        :param string data_name: data name
        :param int plc_datatype: type of the data given to the PLC, according
            to PLCTYPE constants
            :return: value: **value**
        :param bool return_ctypes: return ctypes instead of python types if True
            (default: False)


if isinstance(ams_netid, str):<EOL><INDENT>ams_netid_st = _parse_ams_netid(ams_netid)<EOL><DEDENT>else:<EOL><INDENT>ams_netid_st = ams_netid<EOL><DEDENT>assert isinstance(ams_netid_st, SAmsNetId)<EOL>if linux:<EOL><INDENT>return adsSetLocalAddress(ams_netid_st)<EOL><DEDENT>else:<EOL><INDENT>raise ADSError(<EOL>text="<STR_LIT>"<EOL>)<EOL><DEDENT>

Set the local NetID (**Linux only**).

    :param str: new AmsNetID
    :rtype: None

    **Usage:**

        >>> import pyads
        >>> pyads.open_port()
        >>> pyads.set_local_address('0.0.0.0.1.1')


def notification_decorator(func):<EOL><INDENT>def func_wrapper(notification, data_name):<EOL><INDENT>contents = notification.contents<EOL>data = contents.data<EOL>data_size = contents.cbSampleSize<EOL>datatype_map = {<EOL>PLCTYPE_BOOL: "<STR_LIT>",<EOL>PLCTYPE_BYTE: "<STR_LIT>",<EOL>PLCTYPE_DINT: "<STR_LIT>",<EOL>PLCTYPE_DWORD: "<STR_LIT>",<EOL>PLCTYPE_INT: "<STR_LIT>",<EOL>PLCTYPE_LREAL: "<STR_LIT>",<EOL>PLCTYPE_REAL: "<STR_LIT>",<EOL>PLCTYPE_SINT: "<STR_LIT>",<EOL>PLCTYPE_UDINT: "<STR_LIT>",<EOL>PLCTYPE_UINT: "<STR_LIT>",<EOL>PLCTYPE_USINT: "<STR_LIT>",<EOL>PLCTYPE_WORD: "<STR_LIT>",<EOL>}  <EOL>if plc_datatype == PLCTYPE_STRING:<EOL><INDENT>dest = (c_ubyte * data_size)()<EOL>memmove(addressof(dest), addressof(data), data_size)<EOL>value = bytearray(dest).split(b"<STR_LIT>", <NUM_LIT:1>)[<NUM_LIT:0>].decode("<STR_LIT:utf-8>")<EOL><DEDENT>elif issubclass(plc_datatype, Structure):<EOL><INDENT>value = plc_datatype()<EOL>fit_size = min(data_size, sizeof(value))<EOL>memmove(addressof(value), addressof(data), fit_size)<EOL><DEDENT>elif plc_datatype not in datatype_map:<EOL><INDENT>value = data<EOL><DEDENT>else:<EOL><INDENT>value = struct.unpack(<EOL>datatype_map[plc_datatype], bytearray(data)[:data_size]<EOL>)[<NUM_LIT:0>]<EOL><DEDENT>dt = filetime_to_dt(contents.nTimeStamp)<EOL>return func(contents.hNotification, data_name, dt, value)<EOL><DEDENT>return func_wrapper<EOL><DEDENT>return notification_decorator<EOL>

Decorate a callback function.

        **Decorator**.

        A decorator that can be used for callback functions in order to
        convert the data of the NotificationHeader into the fitting
        Python type.

        :param plc_datatype: The PLC datatype that needs to be converted. This can
        be any basic PLC datatype or a `ctypes.Structure`.

        The callback functions need to be of the following type:

        >>> def callback(handle, name, timestamp, value)

        * `handle`: the notification handle
        * `name`: the variable name
        * `timestamp`: the timestamp as datetime value
        * `value`: the converted value of the variable

        **Usage**:

            >>> import pyads
            >>>
            >>> plc = pyads.Connection('172.18.3.25.1.1', 851)
            >>>
            >>>
            >>> @plc.notification(pyads.PLCTYPE_STRING)
            >>> def callback(handle, name, timestamp, value):
            >>>     print(handle, name, timestamp, value)
            >>>
            >>>
            >>> with plc:
            >>>    attr = pyads.NotificationAttrib(20,
            >>>                                    pyads.ADSTRANS_SERVERCYCLE)
            >>>    handles = plc.add_device_notification('GVL.test', attr,
            >>>                                          callback)
            >>>    while True:
            >>>        pass


if port is not None:<EOL><INDENT>return adsSyncSetTimeoutEx(port, ms)<EOL><DEDENT>


def write_control(self, ads_state, device_state, data, plc_datatype):<EOL>

if self._port is not None:<EOL><INDENT>return adsSyncWriteControlReqEx(<EOL>self._port, self._adr, ads_state, device_state, data, plc_datatype<EOL>)<EOL><DEDENT>

Change the ADS state and the machine-state of the ADS-server.

        :param int ads_state: new ADS-state, according to ADSTATE constants
        :param int device_state: new machine-state
        :param data: additional data
        :param int plc_datatype: datatype, according to PLCTYPE constants

        :note: Despite changing the ADS-state and the machine-state it is
            possible to send additional data to the ADS-server. For current
            ADS-devices additional data is not progressed.
            Every ADS-device is able to communicate its current state to other
            devices. There is a difference between the device-state and the
            state of the ADS-interface (AdsState). The possible states of an
            ADS-interface are defined in the ADS-specification.


def del_device_notification(adr, notification_handle, user_handle):<EOL>

if port is not None:<EOL><INDENT>return adsSyncDelDeviceNotificationReqEx(<EOL>port, adr, notification_handle, user_handle<EOL>)<EOL><DEDENT>

Remove a device notification.

    :param pyads.structs.AmsAddr adr: AMS Address associated with the routing
        entry which is to be removed from the router.
    :param notification_handle: address of the variable that contains
        the handle of the notification
    :param user_handle: user handle


def __exit__(self, _type, _val, _traceback):<EOL>

self.close()<EOL>


def add_device_notification(adr, data_name, attr, callback, user_handle=None):<EOL>

if port is not None:<EOL><INDENT>return adsSyncAddDeviceNotificationReqEx(<EOL>port, adr, data_name, attr, callback, user_handle<EOL>)<EOL><DEDENT>return None<EOL>

Add a device notification.

    :param pyads.structs.AmsAddr adr: AMS Address associated with the routing
        entry which is to be removed from the router.
    :param str data_name: PLC storage address
    :param pyads.structs.NotificationAttrib attr: object that contains
        all the attributes for the definition of a notification
    :param callback: callback function that gets executed on in the event
        of a notification

    :rtype: (int, int)
    :returns: notification handle, user handle

    Save the notification handle and the user handle on creating a
    notification if you want to be able to remove the notification
    later in your code.


self.open()<EOL>return self<EOL>


if self._port is not None:<EOL><INDENT>return adsSyncReadDeviceInfoReqEx(self._port, self._adr)<EOL><DEDENT>return None<EOL>

Read the name and the version number of the ADS-server.

        :rtype: string, AdsVersion
        :return: device name, version


if port is not None:<EOL><INDENT>return adsGetLocalAddressEx(port)<EOL><DEDENT>return None<EOL>

Return the local AMS-address and the port number.

    :rtype: AmsAddr


return adsDelRoute(adr.netIdStruct())<EOL>

Remove existing route from the AMS Router (Linux Only).

    :param pyads.structs.AmsAddr adr: AMS Address associated with the routing
        entry which is to be removed from the router.


return self._open<EOL>

Show the current connection state.

        :return: True if connection is open


global port<EOL>if port is not None:<EOL><INDENT>adsPortCloseEx(port)<EOL>port = None<EOL><DEDENT>

Close the connection to the TwinCAT message router.


if self._port is not None:<EOL><INDENT>return adsGetLocalAddressEx(self._port)<EOL><DEDENT>return None<EOL>

Return the local AMS-address and the port number.

        :rtype: AmsAddr


def read(self, index_group, index_offset, plc_datatype, return_ctypes=False):<EOL>

if self._port is not None:<EOL><INDENT>return adsSyncReadReqEx2(<EOL>self._port, self._adr, index_group, index_offset, plc_datatype, return_ctypes<EOL>)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device.

        :param int index_group: PLC storage area, according to the INDEXGROUP
            constants
        :param int index_offset: PLC storage address
        :param int plc_datatype: type of the data given to the PLC, according
            to PLCTYPE constants
            :return: value: **value**
        :param bool return_ctypes: return ctypes instead of python types if True
            (default: False)


if port is not None:<EOL><INDENT>return adsSyncReadWriteReqEx2(<EOL>port,<EOL>adr,<EOL>index_group,<EOL>index_offset,<EOL>plc_read_datatype,<EOL>value,<EOL>plc_write_datatype,<EOL>return_ctypes,<EOL>)<EOL><DEDENT>return None<EOL>

Read and write data synchronous from/to an ADS-device.

    :param AmsAddr adr: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type plc_read_datatype: type of the data given to the PLC to respond
            to, according to PLCTYPE constants
        :param value: value to write to the storage address of the PLC
    :param Type plc_write_datatype: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: PLCTYPE
    :return: value: **value**


def read_by_name(adr, data_name, plc_datatype, return_ctypes=False):<EOL>

if port is not None:<EOL><INDENT>return adsSyncReadByNameEx(port, adr, data_name, plc_datatype, return_ctypes)<EOL><DEDENT>return None<EOL>

Read data synchronous from an ADS-device from data name.

    :param AmsAddr adr: local or remote AmsAddr
    :param string data_name: data name
    :param int plc_datatype: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :return: value: **value**


return self._ams_addr.port<EOL>


return '<STR_LIT>'.format(self.netid, self.port)<EOL>


def __init__(self, netid=None, port=None):<EOL>

self._ams_addr = SAmsAddr()<EOL>if netid is not None:<EOL><INDENT>self.netid = netid<EOL><DEDENT>if port is not None:<EOL><INDENT>self.port = port<EOL><DEDENT>

Create a new AmsAddr object by a given netid and port.

        :param netid: NetId of an ADS device
        :param port: port of an ADS device


return self._attrib.cbLength<EOL>


return ('<STR_LIT>'<EOL>.format(self.length, self.trans_mode, self.max_delay,<EOL>self.cycle_time))<EOL>


def __init__(self, length, trans_mode=ADSTRANS_SERVERONCHA,<EOL>max_delay=<NUM_LIT>, cycle_time=<NUM_LIT>):<EOL>

self._attrib = SAdsNotificationAttrib()<EOL>if length:<EOL><INDENT>self._attrib.cbLength = length<EOL><DEDENT>if trans_mode:<EOL><INDENT>self._attrib.nTransMode = trans_mode<EOL><DEDENT>if max_delay:<EOL><INDENT>self._attrib.nMaxDelay = int(max_delay * <NUM_LIT>)<EOL><DEDENT>if cycle_time:<EOL><INDENT>self._attrib.nCycleTime = int(cycle_time * <NUM_LIT>)<EOL><DEDENT>

Create a new NotificationAttrib object.

        :param int length: length of the data
        :param int trans_mode: transmission mode
        :param float max_delay: maximum delay in ms
        :param float cycle_time: cycle time in ms


return self._ams_addr.netId<EOL>


return self._attrib<EOL>


return self.netid + "<STR_LIT>" + str(self._ams_addr.port)<EOL>

Textual representation of the AMS address.

        :rtype: string
        :return:  textual representation of the AMS adress


def adsSyncWriteByNameEx(port, address, data_name, value, data_type):<EOL>

<EOL>handle = adsSyncReadWriteReqEx2(<EOL>port,<EOL>address,<EOL>ADSIGRP_SYM_HNDBYNAME,<EOL><NUM_LIT>,<EOL>PLCTYPE_UDINT,<EOL>data_name,<EOL>PLCTYPE_STRING,<EOL>)<EOL>adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)<EOL>adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, <NUM_LIT:0>, handle, PLCTYPE_UDINT)<EOL>

Send data synchronous to an ADS-device from data name.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param string data_name: PLC storage address
    :param value: value to write to the storage address of the PLC
    :param Type data_type: type of the data given to the PLC,
        according to PLCTYPE constants


def adsSyncWriteControlReqEx(<EOL>port, address, ads_state, device_state, data, plc_data_type<EOL>):<EOL>

sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>ads_state_c = ctypes.c_ulong(ads_state)<EOL>device_state_c = ctypes.c_ulong(device_state)<EOL>if plc_data_type == PLCTYPE_STRING:<EOL><INDENT>data = ctypes.c_char_p(data.encode("<STR_LIT:utf-8>"))<EOL>data_pointer = data<EOL>data_length = len(data_pointer.value) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>data = plc_data_type(data)<EOL>data_pointer = ctypes.pointer(data)<EOL>data_length = ctypes.sizeof(data)<EOL><DEDENT>error_code = sync_write_control_request(<EOL>port,<EOL>ams_address_pointer,<EOL>ads_state_c,<EOL>device_state_c,<EOL>data_length,<EOL>data_pointer,<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>

Change the ADS state and the machine-state of the ADS-server.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr adr: local or remote AmsAddr
    :param int ads_state: new ADS-state, according to ADSTATE constants
    :param int device_state: new machine-state
    :param data: additional data
    :param int plc_data_type: plc datatype, according to PLCTYPE constants


delete_route = _adsDLL.AdsDelRoute<EOL>delete_route(net_id)<EOL>

Remove existing route from the AMS Router.

    :param pyads.structs.SAmsNetId net_id: net id associated with the routing
        entry which is to be removed from the router.


port_open_ex = _adsDLL.AdsPortOpenEx<EOL>port_open_ex.restype = ctypes.c_long<EOL>port = port_open_ex()<EOL>if port == <NUM_LIT:0>:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>return port<EOL>

Connect to the TwinCAT message router.

    :rtype: int
    :return: port number


def adsSyncReadReqEx2(<EOL>port, address, index_group, index_offset, data_type, return_ctypes=False<EOL>):<EOL>

sync_read_request = _adsDLL.AdsSyncReadReqEx2<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>index_group_c = ctypes.c_ulong(index_group)<EOL>index_offset_c = ctypes.c_ulong(index_offset)<EOL>if data_type == PLCTYPE_STRING:<EOL><INDENT>data = (STRING_BUFFER * PLCTYPE_STRING)()<EOL><DEDENT>else:<EOL><INDENT>data = data_type()<EOL><DEDENT>data_pointer = ctypes.pointer(data)<EOL>data_length = ctypes.c_ulong(ctypes.sizeof(data))<EOL>bytes_read = ctypes.c_ulong()<EOL>bytes_read_pointer = ctypes.pointer(bytes_read)<EOL>error_code = sync_read_request(<EOL>port,<EOL>ams_address_pointer,<EOL>index_group_c,<EOL>index_offset_c,<EOL>data_length,<EOL>data_pointer,<EOL>bytes_read_pointer,<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(<EOL>data_length.value, bytes_read.value<EOL>)<EOL>)<EOL><DEDENT>if return_ctypes:<EOL><INDENT>return data<EOL><DEDENT>if data_type == PLCTYPE_STRING:<EOL><INDENT>return data.value.decode("<STR_LIT:utf-8>")<EOL><DEDENT>if type(data_type).__name__ == "<STR_LIT>":<EOL><INDENT>return [i for i in data]<EOL><DEDENT>if hasattr(data, "<STR_LIT:value>"):<EOL><INDENT>return data.value<EOL><DEDENT>return data<EOL>

Read data synchronous from an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: data_type
    :return: value: **value**


def adsSyncAddDeviceNotificationReqEx(<EOL>port, adr, data_name, pNoteAttrib, callback, user_handle=None<EOL>):<EOL>

global callback_store<EOL>if NOTEFUNC is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx<EOL>pAmsAddr = ctypes.pointer(adr.amsAddrStruct())<EOL>hnl = adsSyncReadWriteReqEx2(<EOL>port, adr, ADSIGRP_SYM_HNDBYNAME, <NUM_LIT>, PLCTYPE_UDINT, data_name, PLCTYPE_STRING<EOL>)<EOL>nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)<EOL>nIndexOffset = ctypes.c_ulong(hnl)<EOL>attrib = pNoteAttrib.notificationAttribStruct()<EOL>pNotification = ctypes.c_ulong()<EOL>nHUser = ctypes.c_ulong(hnl)<EOL>if user_handle is not None:<EOL><INDENT>nHUser = ctypes.c_ulong(user_handle)<EOL><DEDENT>adsSyncAddDeviceNotificationReqFct.argtypes = [<EOL>ctypes.c_ulong,<EOL>ctypes.POINTER(SAmsAddr),<EOL>ctypes.c_ulong,<EOL>ctypes.c_ulong,<EOL>ctypes.POINTER(SAdsNotificationAttrib),<EOL>NOTEFUNC,<EOL>ctypes.c_ulong,<EOL>ctypes.POINTER(ctypes.c_ulong),<EOL>]<EOL>adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long<EOL>def wrapper(addr, notification, user):<EOL><INDENT>return callback(notification, data_name)<EOL><DEDENT>c_callback = NOTEFUNC(wrapper)<EOL>err_code = adsSyncAddDeviceNotificationReqFct(<EOL>port,<EOL>pAmsAddr,<EOL>nIndexGroup,<EOL>nIndexOffset,<EOL>ctypes.byref(attrib),<EOL>c_callback,<EOL>nHUser,<EOL>ctypes.byref(pNotification),<EOL>)<EOL>if err_code:<EOL><INDENT>raise ADSError(err_code)<EOL><DEDENT>callback_store[pNotification.value] = c_callback<EOL>return (pNotification.value, hnl)<EOL>

Add a device notification.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr adr: local or remote AmsAddr
    :param string data_name: PLC storage address
    :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes
    :param callback: Callback function to handle notification
    :param user_handle: User Handle
    :rtype: (int, int)
    :returns: notification handle, user handle


def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):<EOL>

<EOL>handle = adsSyncReadWriteReqEx2(<EOL>port,<EOL>address,<EOL>ADSIGRP_SYM_HNDBYNAME,<EOL><NUM_LIT>,<EOL>PLCTYPE_UDINT,<EOL>data_name,<EOL>PLCTYPE_STRING,<EOL>)<EOL>value = adsSyncReadReqEx2(<EOL>port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes<EOL>)<EOL>adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, <NUM_LIT:0>, handle, PLCTYPE_UDINT)<EOL>return value<EOL>

Read data synchronous from an ADS-device from data name.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param string data_name: data name
    :param Type data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :param bool return_ctypes: return ctypes instead of python types if True
        (default: False)
    :rtype: data_type
    :return: value: **value**


get_local_address_ex = _adsDLL.AdsGetLocalAddressEx<EOL>ams_address_struct = SAmsAddr()<EOL>error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>local_ams_address = AmsAddr()<EOL>local_ams_address._ams_addr = ams_address_struct<EOL>return local_ams_address<EOL>

Return the local AMS-address and the port number.

    :rtype: pyads.structs.AmsAddr
    :return: AMS-address


port_close_ex = _adsDLL.AdsPortCloseEx<EOL>port_close_ex.restype = ctypes.c_long<EOL>error_code = port_close_ex(port)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>


@wraps(fn)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>if platform_is_windows():  <EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return fn(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>

Raise a runtime error if on Win32 systems.

    Decorator.

    Decorator for functions that interact with the router for the Linux
    implementation of the ADS library.

    Unlike the Windows implementation which uses a separate router daemon,
    the Linux library manages AMS routing in-process. As such, routing must be
    configured programatically via. the provided API. These endpoints are
    invalid on Win32 systems, so an exception will be raised.


def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):<EOL>

sync_write_request = _adsDLL.AdsSyncWriteReqEx<EOL>ams_address_pointer = ctypes.pointer(address.amsAddrStruct())<EOL>index_group_c = ctypes.c_ulong(index_group)<EOL>index_offset_c = ctypes.c_ulong(index_offset)<EOL>if plc_data_type == PLCTYPE_STRING:<EOL><INDENT>data = ctypes.c_char_p(value.encode("<STR_LIT:utf-8>"))<EOL>data_pointer = data  <EOL>data_length = len(data_pointer.value) + <NUM_LIT:1>  <EOL><DEDENT>else:<EOL><INDENT>if type(plc_data_type).__name__ == "<STR_LIT>":<EOL><INDENT>data = plc_data_type(*value)<EOL><DEDENT>else:<EOL><INDENT>data = plc_data_type(value)<EOL><DEDENT>data_pointer = ctypes.pointer(data)<EOL>data_length = ctypes.sizeof(data)<EOL><DEDENT>error_code = sync_write_request(<EOL>port,<EOL>ams_address_pointer,<EOL>index_group_c,<EOL>index_offset_c,<EOL>data_length,<EOL>data_pointer,<EOL>)<EOL>if error_code:<EOL><INDENT>raise ADSError(error_code)<EOL><DEDENT>

Send data synchronous to an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int indexGroup: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param value: value to write to the storage address of the PLC
    :param int plc_data_type: type of the data given to the PLC,
        according to PLCTYPE constants


return "<STR_LIT>"<EOL>


return ZERO<EOL>

Return offset of localtime from UTC time.


def render_tag(self, context, name, nodelist):

<EOL>settings = self.setting_model.objects.filter(name=name).as_dict()<EOL>try:<EOL><INDENT>value = settings[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>value = settings[name] = nodelist.render(context)<EOL><DEDENT>return value<EOL>


if default is None:<EOL><INDENT>settings = self.setting_model.objects.as_dict()<EOL><DEDENT>else:<EOL><INDENT>settings = self.setting_model.objects.as_dict(default=default)<EOL><DEDENT>return settings<EOL>


<EOL>if self.empty_cache:<EOL><INDENT>self.refresh()<EOL><DEDENT>with transaction.atomic():<EOL><INDENT>self.model.objects.filter(name=key).delete()<EOL>self.model.objects.create(name=key, value=value)<EOL><DEDENT>super(SettingDict, self).__setitem__(key, value)<EOL>

Tries to delete and then creates a setting, in case the value type has
changed. Otherwise, we would need to get, update (if same type), or
delete and create (if not same type).