payload = '<STR_LIT>'<EOL>msg = str(MSG_TYPES[data['<STR_LIT:type>']])<EOL>if msg in ['<STR_LIT:0>', '<STR_LIT:1>']:<EOL><INDENT>msg += '<STR_LIT>' + data['<STR_LIT>']<EOL>if '<STR_LIT>' in data and data['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>msg += '<STR_LIT::>' + data['<STR_LIT>']<EOL><DEDENT><DEDENT>elif msg == '<STR_LIT:2>':<EOL><INDENT>msg += '<STR_LIT>'<EOL><DEDENT>elif msg in ['<STR_LIT:3>', '<STR_LIT:4>', '<STR_LIT:5>']:<EOL><INDENT>if msg == '<STR_LIT:3>':<EOL><INDENT>payload = data['<STR_LIT:data>']<EOL><DEDENT>if msg == '<STR_LIT:4>':<EOL><INDENT>payload = json_dumps(data['<STR_LIT:data>'])<EOL><DEDENT>if msg == '<STR_LIT:5>':<EOL><INDENT>d = {}<EOL>d['<STR_LIT:name>'] = data['<STR_LIT:name>']<EOL>if '<STR_LIT:args>' in data and data['<STR_LIT:args>'] != []:<EOL><INDENT>d['<STR_LIT:args>'] = data['<STR_LIT:args>']<EOL><DEDENT>payload = json_dumps(d)<EOL><DEDENT>if '<STR_LIT:id>' in data:<EOL><INDENT>msg += '<STR_LIT::>' + str(data['<STR_LIT:id>'])<EOL>if data['<STR_LIT>'] == '<STR_LIT:data>':<EOL><INDENT>msg += '<STR_LIT:+>'<EOL><DEDENT>msg += '<STR_LIT::>'<EOL><DEDENT>else:<EOL><INDENT>msg += '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in data:<EOL><INDENT>data['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if payload != '<STR_LIT>':<EOL><INDENT>msg += data['<STR_LIT>'] + '<STR_LIT::>' + payload<EOL><DEDENT>else:<EOL><INDENT>msg += data['<STR_LIT>']<EOL><DEDENT><DEDENT>elif msg == '<STR_LIT>':<EOL><INDENT>msg += '<STR_LIT>' + data.get('<STR_LIT>', '<STR_LIT>') + '<STR_LIT::>' + str(data['<STR_LIT>'])<EOL>if '<STR_LIT:args>' in data and data['<STR_LIT:args>'] != []:<EOL><INDENT>msg += '<STR_LIT:+>' + json_dumps(data['<STR_LIT:args>'])<EOL><DEDENT><DEDENT>elif msg == '<STR_LIT>':<EOL><INDENT>msg += '<STR_LIT>'<EOL>if '<STR_LIT>' in data and data['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>msg += str(ERROR_REASONS[data['<STR_LIT>']])<EOL><DEDENT>if '<STR_LIT>' in data and data['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>msg += '<STR_LIT:+>' + str(ERROR_ADVICES[data['<STR_LIT>']])<EOL><DEDENT>msg += data['<STR_LIT>']<EOL><DEDENT>elif msg == '<STR_LIT>':<EOL><INDENT>msg += '<STR_LIT>'<EOL><DEDENT>return msg<EOL>

Encode an attribute dict into a byte string.


return key in self.active_ns<EOL>

Verifies if the namespace is active (was initialized)


self.ack_counter += <NUM_LIT:1><EOL>return self.ack_counter<EOL>

This retrieves the next value for the 'id' field when sending
        an 'event' or 'message' or 'json' that asks the remote client
        to 'ack' back, so that we trigger the local callback.


self.namespaces = namespaces<EOL>

This is a mapping (dict) of the different '/namespaces' to their
        BaseNamespace object derivative.

        This is called by socketio_manage().


self.request = request<EOL>

Saves the request object for future use by the different Namespaces.

        This is called by socketio_manage().


self.environ = environ<EOL>

Save the WSGI environ, for future use.

        This is called by socketio_manage().


if namespace in self.active_ns:<EOL><INDENT>del self.active_ns[namespace]<EOL><DEDENT>if len(self.active_ns) == <NUM_LIT:0> and self.connected:<EOL><INDENT>self.kill(detach=True)<EOL><DEDENT>

This removes a Namespace object from the socket.

        This is usually called by
        :meth:`~socketio.namespace.BaseNamespace.disconnect`.


return self.client_queue.get(**kwargs)<EOL>

Grab a message to send it to the browser


return self.active_ns[key]<EOL>

This will get the nested Namespace using its '/chat' reference.

        Using this, you can go from one Namespace to the other (to emit, add
        ACLs, etc..) with:

          adminnamespace.socket['/chat'].add_acl_method('kick-ban')


self.put_client_msg(packet.encode(pkt, self.json_dumps))<EOL>

Low-level interface to queue a packet on the wire (encoded as wire
        protocol


return self.state == self.STATE_CONNECTED<EOL>

Returns whether the state is CONNECTED or not.


Writes to the client's pipe, to end up in the browser


client_queue = self.client_queue<EOL>msgs = [client_queue.get(**kwargs)]<EOL>while client_queue.qsize():<EOL><INDENT>msgs.append(client_queue.get())<EOL><DEDENT>return msgs<EOL>

Get multiple messages, in case we're going through the various
        XHR-polling methods, on which we can pack more than one message if the
        rate is high, and encode the payload for the HTTP channel.


job = gevent.spawn(self._watcher)<EOL>return job<EOL>

This one is not waited for with joinall(socket.jobs), as it
        is an external watcher, to clean up when everything is done.


def serve_paste(app, global_conf, **kw):

serve(app, **kw)<EOL>return <NUM_LIT:0><EOL>

pserve / paster serve / waitress replacement / integration

    You can pass as parameters:

    transports = websockets, xhr-multipart, xhr-longpolling, etc...
    policy_server = True


self.sockets = {}<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>print("<STR_LIT>")<EOL>self.resource = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.resource = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>self.transports = kwargs.pop('<STR_LIT>', None)<EOL>if kwargs.pop('<STR_LIT>', True):<EOL><INDENT>try:<EOL><INDENT>address = args[<NUM_LIT:0>][<NUM_LIT:0>]<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>address = args[<NUM_LIT:0>].address[<NUM_LIT:0>]<EOL><DEDENT>except AttributeError:<EOL><INDENT>address = args[<NUM_LIT:0>].cfg_addr[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>policylistener = kwargs.pop('<STR_LIT>', (address, <NUM_LIT>))<EOL>self.policy_server = FlashPolicyServer(policylistener)<EOL><DEDENT>else:<EOL><INDENT>self.policy_server = None<EOL><DEDENT>self.config = {<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>}<EOL>for f in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if f in kwargs:<EOL><INDENT>self.config[f] = int(kwargs.pop(f))<EOL><DEDENT><DEDENT>if not '<STR_LIT>' in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = SocketIOHandler<EOL><DEDENT>if not '<STR_LIT>' in kwargs:<EOL><INDENT>self.ws_handler_class = WebSocketHandler<EOL><DEDENT>else:<EOL><INDENT>self.ws_handler_class = kwargs.pop('<STR_LIT>')<EOL><DEDENT>log_file = kwargs.pop('<STR_LIT>', None)<EOL>if log_file:<EOL><INDENT>kwargs['<STR_LIT>'] = open(log_file, '<STR_LIT:a>')<EOL><DEDENT>super(SocketIOServer, self).__init__(*args, **kwargs)<EOL>

This is just like the standard WSGIServer __init__, except with a
        few additional ``kwargs``:

        :param resource: The URL which has to be identified as a
            socket.io request.  Defaults to the /socket.io/ URL.

        :param transports: Optional list of transports to allow. List of
            strings, each string should be one of
            handler.SocketIOHandler.handler_types.

        :param policy_server: Boolean describing whether or not to use the
            Flash policy server.  Default True.

        :param policy_listener: A tuple containing (host, port) for the
            policy server.  This is optional and used only if policy server
            is set to true.  The default value is 0.0.0.0:843

        :param heartbeat_interval: int The timeout for the server, we
            should receive a heartbeat from the client within this
            interval. This should be less than the
            ``heartbeat_timeout``.

        :param heartbeat_timeout: int The timeout for the client when
            it should send a new heartbeat to the server. This value
            is sent to the client after a successful handshake.

        :param close_timeout: int The timeout for the client, when it
            closes the connection it still X amounts of seconds to do
            re open of the connection. This value is sent to the
            client after a successful handshake.

        :param log_file: str The file in which you want the PyWSGI
            server to write its access log.  If not specified, it
            is sent to `stderr` (with gevent 0.13).


socket = self.sockets.get(sessid)<EOL>if sessid and not socket:<EOL><INDENT>return None  <EOL><DEDENT>if socket is None:<EOL><INDENT>socket = Socket(self, self.config)<EOL>self.sockets[socket.sessid] = socket<EOL><DEDENT>else:<EOL><INDENT>socket.incr_hits()<EOL><DEDENT>return socket<EOL>

Return an existing or new client Socket.


def get_messages_payload(self, socket, timeout=None):

try:<EOL><INDENT>msgs = socket.get_multiple_client_msgs(timeout=timeout)<EOL>data = self.encode_payload(msgs)<EOL><DEDENT>except Empty:<EOL><INDENT>data = "<STR_LIT>"<EOL><DEDENT>return data<EOL>

This will fetch the messages from the Socket's queue, and if
        there are many messes, pack multiple messages in one payload and return


if not messages or messages[<NUM_LIT:0>] is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if len(messages) == <NUM_LIT:1>:<EOL><INDENT>return messages[<NUM_LIT:0>].encode('<STR_LIT:utf-8>')<EOL><DEDENT>payload = u'<STR_LIT>'.join([(u'<STR_LIT>' % (len(p), p))<EOL>for p in messages if p is not None])<EOL>return payload.encode('<STR_LIT:utf-8>')<EOL>

Encode list of messages. Expects messages to be unicode.

        ``messages`` - List of raw messages to encode, if necessary


def __init__(self, handler, config, **kwargs):

self.content_type = ("<STR_LIT:Content-Type>", "<STR_LIT>")<EOL>self.headers = [<EOL>("<STR_LIT>", "<STR_LIT:*>"),<EOL>("<STR_LIT>", "<STR_LIT:true>"),<EOL>("<STR_LIT>", "<STR_LIT>"),<EOL>("<STR_LIT>", "<STR_LIT>"),<EOL>]<EOL>self.handler = handler<EOL>self.config = config<EOL>

Base transport class.

        :param config: dict Should contain the config keys, like
          ``heartbeat_interval``, ``heartbeat_timeout`` and
          ``close_timeout``.


def socketio_manage(environ, namespaces, request=None, error_handler=None,<EOL>json_loads=None, json_dumps=None):

Main SocketIO management function, call from within your Framework of
    choice's view.

    The ``environ`` variable is the WSGI ``environ``.  It is used to extract
    Socket object from the underlying server (as the 'socketio' key), and will
    be attached to both the ``Socket`` and ``Namespace`` objects.

    The ``namespaces`` parameter is a dictionary of the namespace string
    representation as key, and the BaseNamespace namespace class descendant as
    a value.  The empty string ('') namespace is the global namespace.  You can
    use Socket.GLOBAL_NS to be more explicit. So it would look like:

    .. code-block:: python

      namespaces={'': GlobalNamespace,
                  '/chat': ChatNamespace}

    The ``request`` object is not required, but will probably be useful to pass
    framework-specific things into your Socket and Namespace functions. It will
    simply be attached to the Socket and Namespace object (accessible through
    ``self.request`` in both cases), and it is not accessed in any case by the
    ``gevent-socketio`` library.

    Pass in an ``error_handler`` if you want to override the default
    error_handler (which is :func:`socketio.virtsocket.default_error_handler`.
    The callable you pass in should have the same signature as the default
    error handler.

    The ``json_loads`` and ``json_dumps`` are overrides for the default
    ``json.loads`` and ``json.dumps`` function calls.  Override these at
    the top-most level here.  This will affect all sockets created by this
    socketio manager, and all namespaces inside.

    This function will block the current "view" or "controller" in your
    framework to do the recv/send on the socket, and dispatch incoming messages
    to your namespaces.

    This is a simple example using Pyramid:

    .. code-block:: python

      def my_view(request):
          socketio_manage(request.environ, {'': GlobalNamespace}, request)

    NOTE: You must understand that this function is going to be called
    *only once* per socket opening, *even though* you are using a long
    polling mechanism.  The subsequent calls (for long polling) will
    be hooked directly at the server-level, to interact with the
    active ``Socket`` instance.  This means you will *not* get access
    to the future ``request`` or ``environ`` objects.  This is of
    particular importance regarding sessions (like Beaker).  The
    session will be opened once at the opening of the Socket, and not
    closed until the socket is closed.  You are responsible for
    opening and closing the cookie-based session yourself if you want
    to keep its data in sync with the rest of your GET/POST calls.


path = self.environ.get('<STR_LIT>')<EOL>if not path.lstrip('<STR_LIT:/>').startswith(self.server.resource + '<STR_LIT:/>'):<EOL><INDENT>return super(SocketIOHandler, self).handle_one_response()<EOL><DEDENT>self.status = None<EOL>self.headers_sent = False<EOL>self.result = None<EOL>self.response_length = <NUM_LIT:0><EOL>self.response_use_chunked = False<EOL>request_method = self.environ.get("<STR_LIT>")<EOL>request_tokens = self.RE_REQUEST_URL.match(path)<EOL>handshake_tokens = self.RE_HANDSHAKE_URL.match(path)<EOL>disconnect_tokens = self.RE_DISCONNECT_URL.match(path)<EOL>if handshake_tokens:<EOL><INDENT>return self._do_handshake(handshake_tokens.groupdict())<EOL><DEDENT>elif disconnect_tokens:<EOL><INDENT>tokens = disconnect_tokens.groupdict()<EOL><DEDENT>elif request_tokens:<EOL><INDENT>tokens = request_tokens.groupdict()<EOL><DEDENT>else:<EOL><INDENT>return super(SocketIOHandler, self).handle_one_response()<EOL><DEDENT>sessid = tokens["<STR_LIT>"]<EOL>socket = self.server.get_socket(sessid)<EOL>if not socket:<EOL><INDENT>self.handle_bad_request()<EOL>return []  <EOL><DEDENT>if self.environ['<STR_LIT>'].startswith('<STR_LIT>'):<EOL><INDENT>socket.disconnect()<EOL>self.handle_disconnect_request()<EOL>return []<EOL><DEDENT>transport = self.handler_types.get(tokens["<STR_LIT>"])<EOL>old_class = None<EOL>if issubclass(transport, (transports.WebsocketTransport,<EOL>transports.FlashSocketTransport)):<EOL><INDENT>old_class = self.__class__<EOL>self.__class__ = self.server.ws_handler_class<EOL>self.prevent_wsgi_call = True  <EOL>self.handle_one_response()  <EOL><DEDENT>self.environ['<STR_LIT>'] = socket<EOL>self.transport = transport(self, self.config)<EOL>self.transport.do_exchange(socket, request_method)<EOL>if not socket.connection_established:<EOL><INDENT>socket.connection_established = True<EOL>socket.state = socket.STATE_CONNECTED<EOL>socket._spawn_heartbeat()<EOL>socket._spawn_watcher()<EOL>try:<EOL><INDENT>if socket.wsgi_app_greenlet is None:<EOL><INDENT>start_response = lambda status, headers, exc=None: None<EOL>socket.wsgi_app_greenlet = gevent.spawn(self.application,<EOL>self.environ,<EOL>start_response)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.handle_error(*sys.exc_info())<EOL><DEDENT><DEDENT>if tokens['<STR_LIT>'] in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>gevent.joinall(socket.jobs)<EOL><DEDENT>if old_class:<EOL><INDENT>self.__class__ = old_class<EOL><DEDENT>if hasattr(self, '<STR_LIT>') and self.websocket:<EOL><INDENT>if hasattr(self.websocket, '<STR_LIT>'):<EOL><INDENT>del self.websocket.environ<EOL><DEDENT>del self.websocket<EOL><DEDENT>if self.environ:<EOL><INDENT>del self.environ<EOL><DEDENT>

This function deals with *ONE INCOMING REQUEST* from the web.

        It will wire and exchange message to the queues for long-polling
        methods, otherwise, will stay alive for websockets.


pass<EOL>

This is called right after ``__init__``, on the initial
        creation of a namespace so you may handle any setup job you
        need.

        Namespaces are created only when some packets arrive that ask
        for the namespace.  They are not created altogether when a new
        :class:`~socketio.virtsocket.Socket` connection is established,
        so you can have many many namespaces assigned (when calling
        :func:`~socketio.socketio_manage`) without clogging the
        memory.

        If you override this method, you probably want to initialize
        the variables you're going to use in the events handled by this
        namespace, setup ACLs, etc..

        This method is called on all base classes following the _`method resolution order <http://docs.python.org/library/stdtypes.html?highlight=mro#class.__mro__>`
        so you don't need to call super() to initialize the mixins or
        other derived classes.


def error(self, error_name, error_message, msg_id=None, quiet=False):

self.socket.error(error_name, error_message, endpoint=self.ns_name,<EOL>msg_id=msg_id, quiet=quiet)<EOL>

Use this to use the configured ``error_handler`` yield an
        error message to your application.

        :param error_name: is a short string, to associate messages to recovery
                           methods
        :param error_message: is some human-readable text, describing the error
        :param msg_id: is used to associate with a request
        :param quiet: specific to error_handlers. The default doesn't send a
                      message to the user, but shows a debug message on the
                      developer console.


def call_method(self, method_name, packet, *args):

method = getattr(self, method_name, None)<EOL>if method is None:<EOL><INDENT>self.error('<STR_LIT>',<EOL>'<STR_LIT>' % method_name)<EOL>return<EOL><DEDENT>specs = inspect.getargspec(method)<EOL>func_args = specs.args<EOL>if not len(func_args) or func_args[<NUM_LIT:0>] != '<STR_LIT>':<EOL><INDENT>self.error("<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>method = self.exception_handler_decorator(method)<EOL><DEDENT>if len(func_args) == <NUM_LIT:2> and func_args[<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>return method(packet)<EOL><DEDENT>else:<EOL><INDENT>return method(*args)<EOL><DEDENT>

This function is used to implement the two behaviors on dispatched
        ``on_*()`` and ``recv_*()`` method calls.

        Those are the two behaviors:

        * If there is only one parameter on the dispatched method and
          it is named ``packet``, then pass in the packet dict as the
          sole parameter.

        * Otherwise, pass in the arguments as specified by the
          different ``recv_*()`` methods args specs, or the
          :meth:`process_event` documentation.

        This method will also consider the
        ``exception_handler_decorator``.  See Namespace documentation
        for details and examples.


if self.allowed_methods is None:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>)<EOL><DEDENT>self.allowed_methods.remove(method_name)<EOL>

ACL system: ensure the user will not have access to that method.


if isinstance(self.allowed_methods, set):<EOL><INDENT>self.allowed_methods.add(method_name)<EOL><DEDENT>else:<EOL><INDENT>self.allowed_methods = set([method_name])<EOL><DEDENT>

ACL system: make the method_name accessible to the current socket


def send(self, message, json=False, callback=None):

pkt = dict(type="<STR_LIT:message>", data=message, endpoint=self.ns_name)<EOL>if json:<EOL><INDENT>pkt['<STR_LIT:type>'] = "<STR_LIT>"<EOL><DEDENT>if callback:<EOL><INDENT>pkt['<STR_LIT>'] = True<EOL>pkt['<STR_LIT:id>'] = msgid = self.socket._get_next_msgid()<EOL>self.socket._save_ack_callback(msgid, callback)<EOL><DEDENT>self.socket.send_packet(pkt)<EOL>

Use send to send a simple string message.

        If ``json`` is True, the message will be encoded as a JSON object
        on the wire, and decoded on the other side.

        This is mostly for backwards compatibility.  ``emit()`` is more fun.

        :param callback: This is a callback function that will be
                         called automatically by the client upon
                         reception.  It does not verify that the
                         listener over there was completed with
                         success.  It just tells you that the browser
                         got a hold of the packet.
        :type callback: callable


self.allowed_methods = self.get_initial_acl()<EOL>

Resets ACL to its initial value (calling
        :meth:`get_initial_acl`` and applying that again).


return None<EOL>

ACL system: If you define this function, you must return
        all the 'event' names that you want your User (the established
        virtual Socket) to have access to.

        If you do not define this function, the user will have free
        access to all of the ``on_*()`` and ``recv_*()`` functions,
        etc.. methods.

        Return something like: ``set(['recv_connect', 'on_public_method'])``

        You can later modify this list dynamically (inside
        ``on_connect()`` for example) using:

        .. code-block:: python

           self.add_acl_method('on_secure_method')

        ``self.request`` is available in here, if you're already ready to
        do some auth. check.

        The ACLs are checked by the :meth:`process_packet` and/or
        :meth:`process_event` default implementations, before calling
        the class's methods.

        **Beware**, returning ``None`` leaves the namespace completely
        accessible.

        The methods that are open are stored in the ``allowed_methods``
        attribute of the ``Namespace`` instance.


packet_type = packet['<STR_LIT:type>']<EOL>if packet_type == '<STR_LIT>':<EOL><INDENT>return self.process_event(packet)<EOL><DEDENT>elif packet_type == '<STR_LIT:message>':<EOL><INDENT>return self.call_method_with_acl('<STR_LIT>', packet,<EOL>packet['<STR_LIT:data>'])<EOL><DEDENT>elif packet_type == '<STR_LIT>':<EOL><INDENT>return self.call_method_with_acl('<STR_LIT>', packet,<EOL>packet['<STR_LIT:data>'])<EOL><DEDENT>elif packet_type == '<STR_LIT>':<EOL><INDENT>self.socket.send_packet(packet)<EOL>return self.call_method_with_acl('<STR_LIT>', packet)<EOL><DEDENT>elif packet_type == '<STR_LIT:error>':<EOL><INDENT>return self.call_method_with_acl('<STR_LIT>', packet)<EOL><DEDENT>elif packet_type == '<STR_LIT>':<EOL><INDENT>callback = self.socket._pop_ack_callback(packet['<STR_LIT>'])<EOL>if not callback:<EOL><INDENT>print("<STR_LIT>" % packet['<STR_LIT>'])<EOL>return<EOL><DEDENT>return callback(*(packet['<STR_LIT:args>']))<EOL><DEDENT>elif packet_type == '<STR_LIT>':<EOL><INDENT>return self.call_method_with_acl('<STR_LIT>', packet)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>", packet)<EOL><DEDENT>

If you override this, NONE of the functions in this class
        will be called.  It is responsible for dispatching to
        :meth:`process_event` (which in turn calls ``on_*()`` and
        ``recv_*()`` methods).

        If the packet arrived here, it is because it belongs to this endpoint.

        For each packet arriving, the only possible path of execution, that is,
        the only methods that *can* be called are the following:

        * recv_connect()
        * recv_message()
        * recv_json()
        * recv_error()
        * recv_disconnect()
        * on_*()


def call_method_with_acl(self, method_name, packet, *args):

if not self.is_method_allowed(method_name):<EOL><INDENT>self.error('<STR_LIT>',<EOL>'<STR_LIT>' % method_name)<EOL>return<EOL><DEDENT>return self.call_method(method_name, packet, *args)<EOL>

You should always use this function to call the methods,
        as it checks if the user is allowed according to the ACLs.

        If you override :meth:`process_packet` or
        :meth:`process_event`, you should definitely want to use this
        instead of ``getattr(self, 'my_method')()``


if not silent:<EOL><INDENT>packet = {"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": self.ns_name}<EOL>self.socket.send_packet(packet)<EOL><DEDENT>try:<EOL><INDENT>self.socket.remove_namespace(self.ns_name)<EOL><DEDENT>finally:<EOL><INDENT>self.kill_local_jobs()<EOL><DEDENT>

Send a 'disconnect' packet, so that the user knows it has been
        disconnected (booted actually).  This will trigger an onDisconnect()
        call on the client side.

        Over here, we will kill all ``spawn``ed processes and remove the
        namespace from the Socket object.

        :param silent: do not actually send the packet (if they asked for a
                       disconnect for example), but just kill all jobs spawned
                       by this Namespace, and remove it from the Socket.


<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>fn = self.exception_handler_decorator(fn)<EOL><DEDENT>new = gevent.spawn(fn, *args, **kwargs)<EOL>self.jobs.append(new)<EOL>return new<EOL>

Spawn a new process, attached to this Namespace.

        It will be monitored by the "watcher" process in the Socket. If the
        socket disconnects, all these greenlets are going to be killed, after
        calling BaseNamespace.disconnect()

        This method uses the ``exception_handler_decorator``.  See
        Namespace documentation for more information.


gevent.killall(self.jobs)<EOL>self.jobs = []<EOL>

Kills all the jobs spawned with BaseNamespace.spawn() on a namespace
        object.

        This will be called automatically if the ``watcher`` process detects
        that the Socket was closed.


args = packet['<STR_LIT:args>']<EOL>name = packet['<STR_LIT:name>']<EOL>if not allowed_event_name_regex.match(name):<EOL><INDENT>self.error("<STR_LIT>",<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>method_name = '<STR_LIT>' + name.replace('<STR_LIT:U+0020>', '<STR_LIT:_>')<EOL>return self.call_method_with_acl(method_name, packet, *args)<EOL>

This function dispatches ``event`` messages to the correct
        functions. You should override this method only if you are not
        satisfied with the automatic dispatching to
        ``on_``-prefixed methods.  You could then implement your own dispatch.
        See the source code for inspiration.

        There are two ways to deal with callbacks from the client side
        (meaning, the browser has a callback waiting for data that this
        server will be sending back):

        The first one is simply to return an object.  If the incoming
        packet requested has an 'ack' field set, meaning the browser is
        waiting for callback data, it will automatically be packaged
        and sent, associated with the 'ackId' from the browser. The
        return value must be a *sequence* of elements, that will be
        mapped to the positional parameters of the callback function
        on the browser side.

        If you want to *know* that you're dealing with a packet
        that requires a return value, you can do those things manually
        by inspecting the ``ack`` and ``id`` keys from the ``packet``
        object.  Your callback will behave specially if the name of
        the argument to your method is ``packet``.  It will fill it
        with the unprocessed ``packet`` object for your inspection,
        like this:

        .. code-block:: python

          def on_my_callback(self, packet):
              if 'ack' in packet:
                  self.emit('go_back', 'param1', id=packet['id'])


def report(self, linenumber, filename, severity, message, rulename, char):

if self._print_filename is not None:<EOL><INDENT>print("<STR_LIT>" + self._print_filename)<EOL>self._print_filename = None<EOL><DEDENT>if severity in (WARNING, ERROR):<EOL><INDENT>self.counts[severity] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self.counts["<STR_LIT>"] += <NUM_LIT:1><EOL><DEDENT>print(self.args.format.format(linenumber=linenumber, filename=filename,<EOL>severity=severity, message=message.encode('<STR_LIT:utf-8>'),<EOL>rulename=rulename, char=char))<EOL>


def report(self, obj, message, linenum, char_offset=<NUM_LIT:0>):

self.controller.report(linenumber=linenum, filename=obj.path,<EOL>severity=self.severity, message=message,<EOL>rulename = self.__class__.__name__,<EOL>char=char_offset)<EOL>


for table in self.tables:<EOL><INDENT>if isinstance(table, VariableTable):<EOL><INDENT>for statement in table.rows:<EOL><INDENT>if statement[<NUM_LIT:0>] != "<STR_LIT>":<EOL><INDENT>yield statement<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Generator which returns all of the statements in all of the variables tables


for table in self.tables:<EOL><INDENT>if isinstance(table, SettingTable):<EOL><INDENT>for statement in table.statements:<EOL><INDENT>yield statement<EOL><DEDENT><DEDENT><DEDENT>

Generator which returns all of the statements in all of the settings tables


requested = types if len(types) > <NUM_LIT:0> else [SuiteFile, ResourceFile, SuiteFolder, Testcase, Keyword]<EOL>for thing in self.robot_files:<EOL><INDENT>if thing.__class__ in requested:<EOL><INDENT>yield thing<EOL><DEDENT>if isinstance(thing, SuiteFolder):<EOL><INDENT>for child in thing.walk():<EOL><INDENT>if child.__class__ in requested:<EOL><INDENT>yield child<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for child in thing.walk(*types):<EOL><INDENT>yield child<EOL><DEDENT><DEDENT><DEDENT>

Iterator which visits all suites and suite files,
yielding test cases and keywords


robot_tables = [table for table in self.tables if not isinstance(table, UnknownTable)]<EOL>if len(robot_tables) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>for table in self.tables:<EOL><INDENT>if isinstance(table, TestcaseTable):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Return 'suite' or 'resource' or None

        This will return 'suite' if a testcase table is found;
        It will return 'resource' if at least one robot table
        is found. If no tables are found it will return None


for table in self.tables:<EOL><INDENT>print("<STR_LIT>" % table.name)<EOL>table.dump()<EOL><DEDENT>


for table in self.tables:<EOL><INDENT>if isinstance(table, KeywordTable):<EOL><INDENT>for keyword in table.keywords:<EOL><INDENT>yield keyword<EOL><DEDENT><DEDENT><DEDENT>

Generator which returns all keywords in the suite


<EOL>if len(self.rows) == <NUM_LIT:0>:<EOL><INDENT>return []<EOL><DEDENT>current_statement = Statement(self.rows[<NUM_LIT:0>])<EOL>current_statement.startline = self.rows[<NUM_LIT:0>].linenumber<EOL>current_statement.endline = self.rows[<NUM_LIT:0>].linenumber<EOL>statements = []<EOL>for row in self.rows[<NUM_LIT:1>:]:<EOL><INDENT>if len(row) > <NUM_LIT:0> and row[<NUM_LIT:0>] == "<STR_LIT>":<EOL><INDENT>current_statement += row[<NUM_LIT:1>:]<EOL>current_statement.endline = row.linenumber<EOL><DEDENT>else:<EOL><INDENT>if len(current_statement) > <NUM_LIT:0>:<EOL><INDENT>statements.append(current_statement)<EOL><DEDENT>current_statement = Statement(row)<EOL>current_statement.startline = row.linenumber<EOL>current_statement.endline = row.linenumber<EOL><DEDENT><DEDENT>if len(current_statement) > <NUM_LIT:0>:<EOL><INDENT>statements.append(current_statement)<EOL><DEDENT>while (len(statements[-<NUM_LIT:1>]) == <NUM_LIT:0> or <EOL>((len(statements[-<NUM_LIT:1>]) == <NUM_LIT:1>) and len(statements[-<NUM_LIT:1>][<NUM_LIT:0>]) == <NUM_LIT:0>)):<EOL><INDENT>statements.pop()<EOL><DEDENT>return statements<EOL>

Return a list of statements

        This is done by joining together any rows that
        have continuations


for table in self.parent.tables:<EOL><INDENT>if isinstance(table, SettingTable):<EOL><INDENT>for row in table.rows:<EOL><INDENT>if row[<NUM_LIT:0>].lower() == "<STR_LIT>":<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return False<EOL>

Return True if the test is part of a suite that uses a Test Template


for cell in self[:]:<EOL><INDENT>if cell == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if cell.lstrip().startswith("<STR_LIT:#>"):<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return False<EOL>

Return True if the first non-empty cell starts with "#


self.__init__(settings=settings if settings is not None else SETTINGS)<EOL>

Reinitializes the Algolia engine and its client.
        :param settings: settings to use instead of the default django.conf.settings.algolia


def __pre_delete_receiver(self, instance, **kwargs):

logger.debug('<STR_LIT>', instance.__class__)<EOL>self.delete_record(instance)<EOL>

Signal handler for when a registered model has been deleted.


return model in self.__registered_models<EOL>

Checks whether the given models is registered with Algolia engine


def reindex_all(self, model, batch_size=<NUM_LIT:1000>):

adapter = self.get_adapter(model)<EOL>return adapter.reindex_all(batch_size)<EOL>

Reindex all the records.

By default, this method use Model.objects.all() but you can implement
a method `get_queryset` in your subclass. This can be used to optimize
the performance (for example with select_related or prefetch_related).


model = instance.__class__<EOL>return self.get_adapter(model)<EOL>

Returns the adapter associated with the given instance.


batch_size = options.get('<STR_LIT>', None)<EOL>if not batch_size:<EOL><INDENT>batch_size = <NUM_LIT:1000><EOL><DEDENT>self.stdout.write('<STR_LIT>')<EOL>for model in get_registered_model():<EOL><INDENT>if options.get('<STR_LIT>', None) and not (model.__name__ in<EOL>options['<STR_LIT>']):<EOL><INDENT>continue<EOL><DEDENT>counts = reindex_all(model, batch_size=batch_size)<EOL>self.stdout.write('<STR_LIT>'.format(model.__name__, counts))<EOL><DEDENT>


self.stdout.write('<STR_LIT>')<EOL>for model in get_registered_model():<EOL><INDENT>if options.get('<STR_LIT>', None) and not (model.__name__ in<EOL>options['<STR_LIT>']):<EOL><INDENT>continue<EOL><DEDENT>clear_index(model)<EOL>self.stdout.write('<STR_LIT>'.format(model.__name__))<EOL><DEDENT>


def raw_search(self, query='<STR_LIT>', params=None):

if params is None:<EOL><INDENT>params = {}<EOL><DEDENT>try:<EOL><INDENT>return self.__index.search(query, params)<EOL><DEDENT>except AlgoliaException as e:<EOL><INDENT>if DEBUG:<EOL><INDENT>raise e<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', self.index_name, e)<EOL><DEDENT><DEDENT>

Performs a search query and returns the parsed JSON.


try:<EOL><INDENT>self.__index.clear_index()<EOL>logger.info('<STR_LIT>', self.index_name)<EOL><DEDENT>except AlgoliaException as e:<EOL><INDENT>if DEBUG:<EOL><INDENT>raise e<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', self.model, e)<EOL><DEDENT><DEDENT>


objectID = self.objectID(instance)<EOL>try:<EOL><INDENT>self.__index.delete_object(objectID)<EOL>logger.info('<STR_LIT>', objectID, self.model)<EOL><DEDENT>except AlgoliaException as e:<EOL><INDENT>if DEBUG:<EOL><INDENT>raise e<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', objectID,<EOL>self.model, e)<EOL><DEDENT><DEDENT>


if set(geolocation) != {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>raise AlgoliaIndexError(<EOL>'<STR_LIT>'.format(<EOL>geolocation<EOL>)<EOL>)<EOL><DEDENT>

Make sure we have the proper geolocation format.


def get_raw_record(self, instance, update_fields=None):

tmp = {'<STR_LIT>': self.objectID(instance)}<EOL>if update_fields:<EOL><INDENT>if isinstance(update_fields, str):<EOL><INDENT>update_fields = (update_fields,)<EOL><DEDENT>for elt in update_fields:<EOL><INDENT>key = self.__translate_fields.get(elt, None)<EOL>if key:<EOL><INDENT>tmp[key] = self.__named_fields[key](instance)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for key, value in self.__named_fields.items():<EOL><INDENT>tmp[key] = value(instance)<EOL><DEDENT>if self.geo_field:<EOL><INDENT>loc = self.geo_field(instance)<EOL>if isinstance(loc, tuple):<EOL><INDENT>tmp['<STR_LIT>'] = {'<STR_LIT>': loc[<NUM_LIT:0>], '<STR_LIT>': loc[<NUM_LIT:1>]}<EOL><DEDENT>elif isinstance(loc, dict):<EOL><INDENT>self._validate_geolocation(loc)<EOL>tmp['<STR_LIT>'] = loc<EOL><DEDENT>elif isinstance(loc, list):<EOL><INDENT>[self._validate_geolocation(geo) for geo in loc]<EOL>tmp['<STR_LIT>'] = loc<EOL><DEDENT><DEDENT>if self.tags:<EOL><INDENT>if callable(self.tags):<EOL><INDENT>tmp['<STR_LIT>'] = self.tags(instance)<EOL><DEDENT>if not isinstance(tmp['<STR_LIT>'], list):<EOL><INDENT>tmp['<STR_LIT>'] = list(tmp['<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT>logger.debug('<STR_LIT>', tmp['<STR_LIT>'], self.model)<EOL>return tmp<EOL>

Gets the raw record.

If `update_fields` is set, the raw record will be build with only
the objectID and the given fields. Also, `_geoloc` and `_tags` will
not be included.


return self.should_index is not None<EOL>

Return True if this AlgoliaIndex has a should_index method or attribute


if self._should_index_is_method:<EOL><INDENT>is_method = inspect.ismethod(self.should_index)<EOL>try:<EOL><INDENT>count_args = len(inspect.signature(self.should_index).parameters)<EOL><DEDENT>except AttributeError:<EOL><INDENT>count_args = len(inspect.getargspec(self.should_index).args)<EOL><DEDENT>if is_method or count_args is <NUM_LIT:1>:<EOL><INDENT>return self.should_index(instance)<EOL><DEDENT>else:<EOL><INDENT>return self.should_index()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>attr_type = type(self.should_index)<EOL>if attr_type is DeferredAttribute:<EOL><INDENT>attr_value = self.should_index.__get__(instance, None)<EOL><DEDENT>elif attr_type is str:<EOL><INDENT>attr_value = getattr(instance, self.should_index)<EOL><DEDENT>elif attr_type is property:<EOL><INDENT>attr_value = self.should_index.__get__(instance)<EOL><DEDENT>else:<EOL><INDENT>raise AlgoliaIndexError('<STR_LIT>'.format(<EOL>self.should_index))<EOL><DEDENT>if type(attr_value) is not bool:<EOL><INDENT>raise AlgoliaIndexError("<STR_LIT>" % (<EOL>instance.__class__.__name__, self.should_index))<EOL><DEDENT>return attr_value<EOL><DEDENT>

Return True if according to should_index the object should be indexed.


def update_records(self, qs, batch_size=<NUM_LIT:1000>, **kwargs):

tmp = {}<EOL>for key, value in kwargs.items():<EOL><INDENT>name = self.__translate_fields.get(key, None)<EOL>if name:<EOL><INDENT>tmp[name] = value<EOL><DEDENT><DEDENT>batch = []<EOL>objectsIDs = qs.only(self.custom_objectID).values_list(<EOL>self.custom_objectID, flat=True)<EOL>for elt in objectsIDs:<EOL><INDENT>tmp['<STR_LIT>'] = elt<EOL>batch.append(dict(tmp))<EOL>if len(batch) >= batch_size:<EOL><INDENT>self.__index.partial_update_objects(batch)<EOL>batch = []<EOL><DEDENT><DEDENT>if len(batch) > <NUM_LIT:0>:<EOL><INDENT>self.__index.partial_update_objects(batch)<EOL><DEDENT>

Updates multiple records.

This method is optimized for speed. It takes a QuerySet and the same
arguments as QuerySet.update(). Optionnaly, you can specify the size
of the batch send to Algolia with batch_size (default to 1000).

>>> from algoliasearch_django import update_records
>>> qs = MyModel.objects.filter(myField=False)
>>> update_records(MyModel, qs, myField=True)
>>> qs.update(myField=True)


@classmethod<EOL><INDENT>def auto_client(cls, host, server, ca_path=None, ca_contents=None,<EOL>cert_path=None, cert_contents=None, key_path=None,<EOL>key_contents=None):<DEDENT>

<EOL>client = {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": True<EOL>}<EOL>port = server.get('<STR_LIT:port>') or <NUM_LIT><EOL>client['<STR_LIT>'] = [{'<STR_LIT:host>': host, '<STR_LIT:port>': port}]<EOL>if server.get('<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>client['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>client['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' in server or '<STR_LIT>' in server:<EOL><INDENT>client['<STR_LIT>'] = True<EOL><DEDENT>if '<STR_LIT>' not in server or not server['<STR_LIT>']:<EOL><INDENT>client['<STR_LIT>'] = False<EOL><DEDENT>ns_cert_type = {None: '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>client['<STR_LIT>'] = ns_cert_type[server.get('<STR_LIT>')]<EOL>remote_cert_tls = {None: '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>client['<STR_LIT>'] = remote_cert_tls[server.get('<STR_LIT>')]<EOL>copy_keys = ['<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:key>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT:user>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:float>', '<STR_LIT>', '<STR_LIT>']<EOL>for key in copy_keys:<EOL><INDENT>if key in server:<EOL><INDENT>client[key] = server[key]<EOL><DEDENT><DEDENT>files = cls._auto_client_files(client, ca_path, ca_contents,<EOL>cert_path, cert_contents,<EOL>key_path, key_contents)<EOL>return {<EOL>'<STR_LIT>': [client],<EOL>'<STR_LIT>': files<EOL>}<EOL>

Returns a configuration dictionary representing an OpenVPN client configuration
that is compatible with the passed server configuration.

:param host: remote VPN server
:param server: dictionary representing a single OpenVPN server configuration
:param ca_path: optional string representing path to CA, will consequently add
                a file in the resulting configuration dictionary
:param ca_contents: optional string representing contents of CA file
:param cert_path: optional string representing path to certificate, will consequently add
                a file in the resulting configuration dictionary
:param cert_contents: optional string representing contents of cert file
:param key_path: optional string representing path to key, will consequently add
                a file in the resulting configuration dictionary
:param key_contents: optional string representing contents of key file
:returns: dictionary representing a single OpenVPN client configuration


@classmethod<EOL><INDENT>def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None,<EOL>cert_contents=None, key_path=None, key_contents=None):<DEDENT>

files = []<EOL>if ca_path and ca_contents:<EOL><INDENT>client['<STR_LIT>'] = ca_path<EOL>files.append(dict(path=ca_path,<EOL>contents=ca_contents,<EOL>mode=DEFAULT_FILE_MODE))<EOL><DEDENT>if cert_path and cert_contents:<EOL><INDENT>client['<STR_LIT>'] = cert_path<EOL>files.append(dict(path=cert_path,<EOL>contents=cert_contents,<EOL>mode=DEFAULT_FILE_MODE))<EOL><DEDENT>if key_path and key_contents:<EOL><INDENT>client['<STR_LIT:key>'] = key_path<EOL>files.append(dict(path=key_path,<EOL>contents=key_contents,<EOL>mode=DEFAULT_FILE_MODE,))<EOL><DEDENT>return files<EOL>

returns a list of NetJSON extra files for automatically generated clients
produces side effects in ``client`` dictionary


text = self.render(files=False)<EOL>vpn_instances = vpn_pattern.split(text)<EOL>if '<STR_LIT>' in vpn_instances:<EOL><INDENT>vpn_instances.remove('<STR_LIT>')<EOL><DEDENT>for vpn in vpn_instances:<EOL><INDENT>lines = vpn.split('<STR_LIT:\n>')<EOL>vpn_name = lines[<NUM_LIT:0>]<EOL>text_contents = '<STR_LIT:\n>'.join(lines[<NUM_LIT:2>:])<EOL>if text_contents.endswith('<STR_LIT>'):<EOL><INDENT>text_contents = text_contents[<NUM_LIT:0>:-<NUM_LIT:1>]<EOL><DEDENT>self._add_file(tar=tar,<EOL>name='<STR_LIT>'.format(vpn_name, config_suffix),<EOL>contents=text_contents)<EOL><DEDENT>

Adds configuration files to tarfile instance.

:param tar: tarfile instance
:returns: None


return output<EOL>

Performs cleanup of output (indentation, new lines)

:param output: string representation of the client configuration


return str(cls.__name__).replace('<STR_LIT>', '<STR_LIT>').lower()<EOL>

Returns the name of the render class without its prefix


output = '<STR_LIT>'<EOL>files = self.config.get('<STR_LIT>', [])<EOL>if files:<EOL><INDENT>output += '<STR_LIT>'.format(self.FILE_SECTION_DELIMITER)<EOL><DEDENT>for f in files:<EOL><INDENT>mode = f.get('<STR_LIT>', DEFAULT_FILE_MODE)<EOL>file_output = '<STR_LIT>''<STR_LIT>''<STR_LIT>'.format(f['<STR_LIT:path>'], mode, f['<STR_LIT>'])<EOL>output += file_output<EOL><DEDENT>return output<EOL>

Renders additional files specified in ``self.config['files']``


self.validate()<EOL>self.intermediate_data = OrderedDict()<EOL>for converter_class in self.converters:<EOL><INDENT>if not converter_class.should_run_forward(self.config):<EOL><INDENT>continue<EOL><DEDENT>converter = converter_class(self)<EOL>value = converter.to_intermediate()<EOL>if value and isinstance(value, (tuple, list)):  <EOL><INDENT>value = OrderedDict(value)<EOL><DEDENT>if value:<EOL><INDENT>self.intermediate_data = merge_config(self.intermediate_data,<EOL>value,<EOL>list_identifiers=['<STR_LIT>'])<EOL><DEDENT><DEDENT>

Converts the NetJSON configuration dictionary (self.config)
to the intermediate data structure (self.intermediate_data) that will
be then used by the renderer class to generate the router configuration


tar_bytes = BytesIO()<EOL>tar = tarfile.open(fileobj=tar_bytes, mode='<STR_LIT:w>')<EOL>self._generate_contents(tar)<EOL>self._process_files(tar)<EOL>tar.close()<EOL>tar_bytes.seek(<NUM_LIT:0>)  <EOL>gzip_bytes = BytesIO()<EOL>gz = gzip.GzipFile(fileobj=gzip_bytes, mode='<STR_LIT:wb>', mtime=<NUM_LIT:0>)<EOL>gz.write(tar_bytes.getvalue())<EOL>gz.close()<EOL>gzip_bytes.seek(<NUM_LIT:0>)  <EOL>return gzip_bytes<EOL>

Returns a ``BytesIO`` instance representing an in-memory tar.gz archive
containing the native router configuration.

:returns: in-memory tar.gz archive, instance of ``BytesIO``


<EOL>for file_item in self.config.get('<STR_LIT>', []):<EOL><INDENT>path = file_item['<STR_LIT:path>']<EOL>if path.startswith('<STR_LIT:/>'):<EOL><INDENT>path = path[<NUM_LIT:1>:]<EOL><DEDENT>self._add_file(tar=tar,<EOL>name=path,<EOL>contents=file_item['<STR_LIT>'],<EOL>mode=file_item.get('<STR_LIT>', DEFAULT_FILE_MODE))<EOL><DEDENT>

Adds files specified in self.config['files'] to tarfile instance.

:param tar: tarfile instance
:returns: None


if isinstance(config, six.string_types):<EOL><INDENT>try:<EOL><INDENT>config = json.loads(config)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not isinstance(config, dict):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return config<EOL>


def _merge_config(self, config, templates):

if not templates:<EOL><INDENT>return config<EOL><DEDENT>if not isinstance(templates, list):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>result = {}<EOL>config_list = templates + [config]<EOL>for merging in config_list:<EOL><INDENT>result = merge_config(result, self._load(merging), self.list_identifiers)<EOL><DEDENT>return result<EOL>


def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):

byte_contents = BytesIO(contents.encode('<STR_LIT:utf8>'))<EOL>info = tarfile.TarInfo(name=name)<EOL>info.size = len(contents)<EOL>info.mtime = <NUM_LIT:0><EOL>info.type = tarfile.REGTYPE<EOL>info.mode = int(mode, <NUM_LIT:8>)  <EOL>tar.addfile(tarinfo=info, fileobj=byte_contents)<EOL>

Adds a single file in tarfile instance.

:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representing file mode, defaults to 644
:returns: None


self.validate()<EOL>if self.intermediate_data is None:<EOL><INDENT>self.to_intermediate()<EOL><DEDENT>renderers = getattr(self, '<STR_LIT>', None) or [self.renderer]<EOL>output = '<STR_LIT>'<EOL>for renderer_class in renderers:<EOL><INDENT>renderer = renderer_class(self)<EOL>output += renderer.render()<EOL>del renderer<EOL><DEDENT>if files:<EOL><INDENT>files_output = self._render_files()<EOL>if files_output:<EOL><INDENT>output += files_output.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT><DEDENT>return output<EOL>

Converts the configuration dictionary into the corresponding configuration format

:param files: whether to include "additional files" in the output or not;
              defaults to ``True``
:returns: string with output


if not hasattr(self, '<STR_LIT>') or not self.parser:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>parser = self.parser(native)<EOL>self.intermediate_data = parser.intermediate_data<EOL>del parser<EOL>self.to_netjson()<EOL>

Parses a native configuration and converts
it to a NetJSON configuration dictionary


def json(self, validate=True, *args, **kwargs):

if validate:<EOL><INDENT>self.validate()<EOL><DEDENT>config = deepcopy(self.config)<EOL>config.update({'<STR_LIT:type>': '<STR_LIT>'})<EOL>return json.dumps(config, *args, **kwargs)<EOL>

returns a string formatted as **NetJSON DeviceConfiguration**;
performs validation before returning output;

``*args`` and ``*kwargs`` will be passed to ``json.dumps``;

:returns: string


result = OrderedDict()<EOL>intermediate_data = list(self.intermediate_data[self.intermediate_key])<EOL>for index, block in enumerate(intermediate_data):<EOL><INDENT>if self.should_skip_block(block):<EOL><INDENT>continue<EOL><DEDENT>if remove_block:<EOL><INDENT>self.intermediate_data[self.intermediate_key].remove(block)<EOL><DEDENT>result = self.to_netjson_loop(block, result, index + <NUM_LIT:1>)<EOL><DEDENT>return result<EOL>

Converts the intermediate data structure (``self.intermediate_datra``)
to a NetJSON configuration dictionary (``self.config``)


def to_intermediate_loop(self, block, result, index=None):

raise NotImplementedError()<EOL>

Utility method called in the loop of ``to_intermediate``


for radio in self.config.get('<STR_LIT>', []):<EOL><INDENT>radio.setdefault('<STR_LIT>', False)<EOL><DEDENT>

OpenWisp 1.x requires the following explicit entry
in the radio sections of /uci/wireless.conf:
    option disabled '0'


<EOL>context = dict(tc_options=self.config.get('<STR_LIT>', []))<EOL>contents = self._render_template('<STR_LIT>', context)<EOL>self.config.setdefault('<STR_LIT>', [])  <EOL>self._add_unique_file({<EOL>"<STR_LIT:path>": "<STR_LIT>",<EOL>"<STR_LIT>": contents,<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>})<EOL>

generates tc_script.sh and adds it to included files


config = self.config<EOL>l2vpn = []<EOL>for vpn in self.config.get('<STR_LIT>', []):<EOL><INDENT>if vpn.get('<STR_LIT>') != '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>tap = vpn.copy()<EOL>l2vpn.append(tap)<EOL><DEDENT>bridges = []<EOL>for interface in self.config.get('<STR_LIT>', []):<EOL><INDENT>if interface['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>bridge = interface.copy()<EOL>if bridge.get('<STR_LIT>'):<EOL><INDENT>bridge['<STR_LIT>'] = interface['<STR_LIT>'][<NUM_LIT:0>].get('<STR_LIT>')<EOL>bridge['<STR_LIT>'] = interface['<STR_LIT>'][<NUM_LIT:0>].get('<STR_LIT:address>')<EOL><DEDENT>bridges.append(bridge)<EOL><DEDENT>cron = False<EOL>for _file in config.get('<STR_LIT>', []):<EOL><INDENT>path = _file['<STR_LIT:path>']<EOL>if path.startswith('<STR_LIT>') or path.startswith('<STR_LIT>'):<EOL><INDENT>cron = True<EOL>break<EOL><DEDENT><DEDENT>return dict(hostname=config['<STR_LIT>']['<STR_LIT>'],  <EOL>l2vpn=l2vpn,<EOL>bridges=bridges,<EOL>radios=config.get('<STR_LIT>', []),  <EOL>cron=cron)<EOL>

returns the template context for install.sh and uninstall.sh


contents = self._render_template('<STR_LIT>', context)<EOL>self.config.setdefault('<STR_LIT>', [])  <EOL>self._add_unique_file({<EOL>"<STR_LIT:path>": "<STR_LIT>",<EOL>"<STR_LIT>": contents,<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>})<EOL>

generates install.sh and adds it to included files


return True<EOL>


def __intermediate_proto(self, interface, address):

<EOL>address_proto = address.pop('<STR_LIT>', '<STR_LIT>')<EOL>if '<STR_LIT>' not in interface:<EOL><INDENT>return address_proto<EOL><DEDENT>else:<EOL><INDENT>return interface.pop('<STR_LIT>')<EOL><DEDENT>


def __intermediate_dns_servers(self, uci, address):

<EOL>if '<STR_LIT>' in uci:<EOL><INDENT>return uci['<STR_LIT>']<EOL><DEDENT>if address['<STR_LIT>'] in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:none>']:<EOL><INDENT>return None<EOL><DEDENT>dns = self.netjson.get('<STR_LIT>', None)<EOL>if dns:<EOL><INDENT>return '<STR_LIT:U+0020>'.join(dns)<EOL><DEDENT>


def __intermediate_interface(self, interface, uci_name):

interface.update({<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': uci_name,<EOL>'<STR_LIT>': interface.pop('<STR_LIT:name>')<EOL>})<EOL>if '<STR_LIT>' in interface:<EOL><INDENT>del interface['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in interface:<EOL><INDENT>if interface.get('<STR_LIT:type>') != '<STR_LIT>':<EOL><INDENT>interface['<STR_LIT>'] = interface['<STR_LIT>']<EOL><DEDENT>del interface['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in interface:<EOL><INDENT>interface['<STR_LIT>'] = interface['<STR_LIT>']<EOL>del interface['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in interface:<EOL><INDENT>interface['<STR_LIT>'] = not interface['<STR_LIT>']<EOL>del interface['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in interface:<EOL><INDENT>del interface['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in interface:<EOL><INDENT>del interface['<STR_LIT>']<EOL><DEDENT>return interface<EOL>

converts NetJSON interface to
UCI intermediate data structure


def __intermediate_bridge(self, interface, i):

<EOL>if interface['<STR_LIT:type>'] == '<STR_LIT>' and i < <NUM_LIT:2>:<EOL><INDENT>bridge_members = '<STR_LIT:U+0020>'.join(interface.pop('<STR_LIT>'))<EOL>if bridge_members:<EOL><INDENT>interface['<STR_LIT>'] = bridge_members<EOL><DEDENT>else:<EOL><INDENT>interface['<STR_LIT>'] = True<EOL>del interface['<STR_LIT>']<EOL><DEDENT><DEDENT>elif interface['<STR_LIT:type>'] == '<STR_LIT>' and i >= <NUM_LIT:2>:<EOL><INDENT>if '<STR_LIT>' not in interface['<STR_LIT>']:<EOL><INDENT>interface['<STR_LIT>'] = '<STR_LIT>'.format(**interface)<EOL><DEDENT>for attr in ['<STR_LIT:type>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if attr in interface:<EOL><INDENT>del interface[attr]<EOL><DEDENT><DEDENT><DEDENT>elif interface['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>del interface['<STR_LIT:type>']<EOL><DEDENT>return interface<EOL>

converts NetJSON bridge to
UCI intermediate data structure


protocol = radio['<STR_LIT>']<EOL>if protocol in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return protocol[<NUM_LIT:4>:]<EOL><DEDENT>if radio['<STR_LIT>'] is <NUM_LIT:0>:<EOL><INDENT>return radio.get('<STR_LIT>')<EOL><DEDENT>elif radio['<STR_LIT>'] <= <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>

possible return values are: 11a, 11b, 11g


uci = self.render(files=False)<EOL>packages = packages_pattern.split(uci)<EOL>if '<STR_LIT>' in packages:<EOL><INDENT>packages.remove('<STR_LIT>')<EOL><DEDENT>for package in packages:<EOL><INDENT>lines = package.split('<STR_LIT:\n>')<EOL>package_name = lines[<NUM_LIT:0>]<EOL>text_contents = '<STR_LIT:\n>'.join(lines[<NUM_LIT:2>:])<EOL>self._add_file(tar=tar,<EOL>name='<STR_LIT>'.format(config_path, package_name),<EOL>contents=text_contents)<EOL><DEDENT>

Adds configuration files to tarfile instance.

:param tar: tarfile instance
:returns: None


def merge_config(template, config, list_identifiers=None):

result = template.copy()<EOL>for key, value in config.items():<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>node = result.get(key, OrderedDict())<EOL>result[key] = merge_config(node, value)<EOL><DEDENT>elif isinstance(value, list) and isinstance(result.get(key), list):<EOL><INDENT>result[key] = merge_list(result[key], value, list_identifiers)<EOL><DEDENT>else:<EOL><INDENT>result[key] = value<EOL><DEDENT><DEDENT>return result<EOL>

Merges ``config`` on top of ``template``.

Conflicting keys are handled in the following way:

* simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
  overwrite the ones in ``template``
* values of type ``list`` in both ``config`` and ``template`` will be
  merged using to the ``merge_list`` function
* values of type ``dict`` will be merged recursively

:param template: template ``dict``
:param config: config ``dict``
:param list_identifiers: ``list`` or ``None``
:returns: merged ``dict``


error_list = []<EOL>for value, error in zip(e.validator_value, e.context):<EOL><INDENT>error_list.append((value, error.message))<EOL>if error.context:<EOL><INDENT>error_list += _list_errors(error)<EOL><DEDENT><DEDENT>return error_list<EOL>

Returns a list of violated schema fragments and related error messages
:param e: ``jsonschema.exceptions.ValidationError`` instance


requirements = []<EOL>for line in open('<STR_LIT>').readlines():<EOL><INDENT>if line.startswith('<STR_LIT:#>') or line == '<STR_LIT>' or line.startswith('<STR_LIT:http>') or line.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>requirements.append(line.replace('<STR_LIT:\n>', '<STR_LIT>'))<EOL><DEDENT>if sys.version_info.major < <NUM_LIT:3>:<EOL><INDENT>requirements.append('<STR_LIT>')<EOL><DEDENT>return requirements<EOL>

parse requirements.txt, ignore links, exclude comments


if (a != b) == out:<EOL><INDENT>return fault == <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return fault == <NUM_LIT:1><EOL><DEDENT>

Returns True if XOR(a, b) == out and fault == 0 or XOR(a, b) != out and fault == 1.


<EOL>return _irreducible_components(constraint.configurations, constraint.variables)<EOL>

Determine the sets of variables that are irreducible.

    Let V(C) denote the variables of constraint C. For a configuration x, let x|A denote the
    restriction of the configuration to the variables of A. Constraint C is reducible if there
    is a partition of V(C) into nonempty subsets A and B, and two constraints C_A and C_B, with
    V(C_A) = A and C_B V(C_B) = B, such that a configuration x is feasible in C if and only if x|A
    is feasible in C_A and x|B is feasible in C_B. A constraint is irreducible if it is not
    reducible.

    Args:
        constraint (:obj:`.Constraint`):
            Constraint to attempt to reduce.

    Returns:
        list[tuple]: List of tuples in which each tuple is a set of variables that is irreducible.

    Examples:
        This example reduces a constraint, created by specifying its valid configurations, to two
        constraints. The original constraint, that valid configurations for a,b,c are 0,0,1 and
        1,1,1, can be represented by two reduced constraints, for example, (c=1) & (a=b). For
        comparison, an attempt to reduce a constraint representing an AND gate fails to find a
        valid reduction.

        >>> import dwavebinarycsp
        >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0, 1), (1, 1, 1)],
        ...                                                       ['a', 'b', 'c'], dwavebinarycsp.BINARY)
        >>> dwavebinarycsp.irreducible_components(const)
        [('c',), ('a', 'b')]
        >>> const_and = dwavebinarycsp.Constraint.from_configurations([(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)],
        ...                                                           ['a', 'b', 'c'], dwavebinarycsp.BINARY)
        >>> dwavebinarycsp.irreducible_components(const_and)
        [('a', 'b', 'c')]


variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configs = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>)])<EOL><DEDENT>else:<EOL><INDENT>configs = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>)])<EOL><DEDENT>def func(augend, addend, sum_, carry):<EOL><INDENT>total = (augend > <NUM_LIT:0>) + (addend > <NUM_LIT:0>)<EOL>if total == <NUM_LIT:0>:<EOL><INDENT>return (sum_ <= <NUM_LIT:0>) and (carry <= <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:1>:<EOL><INDENT>return (sum_ > <NUM_LIT:0>) and (carry <= <NUM_LIT:0>)<EOL><DEDENT>elif total == <NUM_LIT:2>:<EOL><INDENT>return (sum_ <= <NUM_LIT:0>) and (carry > <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return Constraint(func, configs, variables, vartype=vartype, name=name)<EOL>

Half adder.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,
            where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant
            outputs.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='HALF_ADDER'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of a Boolean half adder.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.halfadder_gate(['a', 'b', 'total', 'carry'], name='HA1'))
        >>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})
        True


@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def and_gate(variables, vartype=dimod.BINARY, name='<STR_LIT>'):

variables = tuple(variables)<EOL>if vartype is dimod.BINARY:<EOL><INDENT>configurations = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)])<EOL>def func(in1, in2, out): return (in1 and in2) == out<EOL><DEDENT>else:<EOL><INDENT>configurations = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>)])<EOL>def func(in1, in2, out): return ((in1 > <NUM_LIT:0>) and (in2 > <NUM_LIT:0>)) == (out > <NUM_LIT:0>)<EOL><DEDENT>return Constraint(func, configurations, variables, vartype=vartype, name=name)<EOL>

AND gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='AND'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an AND gate.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.gates as gates
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c'], name='AND1'))
        >>> csp.check({'a': 1, 'b': 0, 'c': 0})
        True


@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def sat2in4(pos, neg=tuple(), vartype=dimod.BINARY, name='<STR_LIT>'):

pos = tuple(pos)<EOL>neg = tuple(neg)<EOL>variables = pos + neg<EOL>if len(variables) != <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if neg and (len(neg) < <NUM_LIT:4>):<EOL><INDENT>const = sat2in4(pos=variables, vartype=vartype)  <EOL>for v in neg:<EOL><INDENT>const.flip_variable(v)<EOL>const.name = name  <EOL><DEDENT>return const<EOL><DEDENT>if vartype is dimod.BINARY:<EOL><INDENT>configurations = frozenset([(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>)])<EOL><DEDENT>else:<EOL><INDENT>configurations = frozenset([(-<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>),<EOL>(-<NUM_LIT:1>, +<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, -<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>(+<NUM_LIT:1>, +<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>)])<EOL><DEDENT>def func(a, b, c, d):<EOL><INDENT>if a == b:<EOL><INDENT>return (b != c) and (c == d)<EOL><DEDENT>elif a == c:<EOL><INDENT>return b == d<EOL><DEDENT>else:<EOL><INDENT>return a == d<EOL><DEDENT><DEDENT>return Constraint(func, configurations, variables, vartype=vartype, name=name)<EOL>

Two-in-four (2-in-4) satisfiability.

    Args:
        pos (iterable):
            Variable labels, as an iterable, for non-negated variables of the constraint.
            Exactly four variables are specified by `pos` and `neg` together.
        neg (tuple):
            Variable labels, as an iterable, for negated variables of the constraint.
            Exactly four variables are specified by `pos` and `neg` together.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='2-in-4'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that satisfy a two-in-four satisfiability problem.

    Examples:
        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories.constraint.sat as sat
        >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
        >>> csp.add_constraint(sat.sat2in4(['w', 'x', 'y', 'z'], vartype='BINARY', name='sat1'))
        >>> csp.check({'w': 1, 'x': 1, 'y': 0, 'z': 0})
        True


def random_2in4sat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):

if num_variables < <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if num_clauses > <NUM_LIT:16> * _nchoosek(num_variables, <NUM_LIT:4>):  <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>csp = ConstraintSatisfactionProblem(vartype)<EOL>variables = list(range(num_variables))<EOL>constraints = set()<EOL>if satisfiable:<EOL><INDENT>values = tuple(vartype.value)<EOL>planted_solution = {v: choice(values) for v in variables}<EOL>configurations = [(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>), (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>), (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>),<EOL>(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>), (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>), (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>)]<EOL>while len(constraints) < num_clauses:<EOL><INDENT>constraint_variables = sorted(sample(variables, <NUM_LIT:4>))<EOL>config = choice(configurations)<EOL>pos = tuple(v for idx, v in enumerate(constraint_variables) if config[idx] == (planted_solution[v] > <NUM_LIT:0>))<EOL>neg = tuple(v for idx, v in enumerate(constraint_variables) if config[idx] != (planted_solution[v] > <NUM_LIT:0>))<EOL>const = sat2in4(pos=pos, neg=neg, vartype=vartype)<EOL>assert const.check(planted_solution)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while len(constraints) < num_clauses:<EOL><INDENT>constraint_variables = sorted(sample(variables, <NUM_LIT:4>))<EOL>pos = tuple(v for v in constraint_variables if random() > <NUM_LIT>)<EOL>neg = tuple(v for v in constraint_variables if v not in pos)<EOL>const = sat2in4(pos=pos, neg=neg, vartype=vartype)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>for const in constraints:<EOL><INDENT>csp.add_constraint(const)<EOL><DEDENT>for v in variables:<EOL><INDENT>csp.add_variable(v)<EOL><DEDENT>return csp<EOL>

Random two-in-four (2-in-4) constraint satisfaction problem.

    Args:
        num_variables (integer): Number of variables (at least four).
        num_clauses (integer): Number of constraints that together constitute the
            constraint satisfaction problem.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables
        are assigned values that satisfy a two-in-four satisfiability problem.

    Examples:
        This example creates a CSP with 6 variables and two random constraints and checks
        whether a particular assignment of variables satisifies it.

        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories as sat
        >>> csp = sat.random_2in4sat(6, 2)
        >>> csp.constraints    # doctest: +SKIP
        [Constraint.from_configurations(frozenset({(1, 0, 1, 0), (1, 0, 0, 1), (1, 1, 1, 1), (0, 1, 1, 0), (0, 0, 0, 0),
         (0, 1, 0, 1)}), (2, 4, 0, 1), Vartype.BINARY, name='2-in-4'),
         Constraint.from_configurations(frozenset({(1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0), (0, 0, 0, 1),
         (0, 1, 0, 0), (0, 0, 1, 0)}), (1, 2, 4, 5), Vartype.BINARY, name='2-in-4')]
        >>> csp.check({0: 1, 1: 0, 2: 1, 3: 1, 4: 0, 5: 0})       # doctest: +SKIP
        True


def random_xorsat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):

if num_variables < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if num_clauses > <NUM_LIT:8> * _nchoosek(num_variables, <NUM_LIT:3>):  <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>csp = ConstraintSatisfactionProblem(vartype)<EOL>variables = list(range(num_variables))<EOL>constraints = set()<EOL>if satisfiable:<EOL><INDENT>values = tuple(vartype.value)<EOL>planted_solution = {v: choice(values) for v in variables}<EOL>configurations = [(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>), (<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>), (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>)]<EOL>while len(constraints) < num_clauses:<EOL><INDENT>x, y, z = sample(variables, <NUM_LIT:3>)<EOL>if y > x:<EOL><INDENT>x, y = y, x<EOL><DEDENT>const = xor_gate([x, y, z], vartype=vartype)<EOL>config = choice(configurations)<EOL>for idx, v in enumerate(const.variables):<EOL><INDENT>if config[idx] != (planted_solution[v] > <NUM_LIT:0>):<EOL><INDENT>const.flip_variable(v)<EOL><DEDENT><DEDENT>assert const.check(planted_solution)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while len(constraints) < num_clauses:<EOL><INDENT>x, y, z = sample(variables, <NUM_LIT:3>)<EOL>if y > x:<EOL><INDENT>x, y = y, x<EOL><DEDENT>const = xor_gate([x, y, z], vartype=vartype)<EOL>for idx, v in enumerate(const.variables):<EOL><INDENT>if random() > <NUM_LIT>:<EOL><INDENT>const.flip_variable(v)<EOL><DEDENT><DEDENT>assert const.check(planted_solution)<EOL>constraints.add(const)<EOL><DEDENT><DEDENT>for const in constraints:<EOL><INDENT>csp.add_constraint(const)<EOL><DEDENT>for v in variables:<EOL><INDENT>csp.add_variable(v)<EOL><DEDENT>return csp<EOL>

Random XOR constraint satisfaction problem.

    Args:
        num_variables (integer): Number of variables (at least three).
        num_clauses (integer): Number of constraints that together constitute the
            constraint satisfaction problem.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        satisfiable (bool, optional, default=True): True if the CSP can be satisfied.

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables
        are assigned values that satisfy a XOR satisfiability problem.

    Examples:
        This example creates a CSP with 5 variables and two random constraints and checks
        whether a particular assignment of variables satisifies it.

        >>> import dwavebinarycsp
        >>> import dwavebinarycsp.factories as sat
        >>> csp = sat.random_xorsat(5, 2)
        >>> csp.constraints    # doctest: +SKIP
        [Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),
         Vartype.BINARY, name='XOR (0 flipped)'),
         Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),
         Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]
        >>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1})       # doctest: +SKIP
        True


if nbit < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>num_multiplier_bits = num_multiplicand_bits = nbit<EOL>csp = ConstraintSatisfactionProblem(vartype)<EOL>a = {i: '<STR_LIT>' % i for i in range(nbit)}<EOL>b = {j: '<STR_LIT>' % j for j in range(nbit)}<EOL>p = {k: '<STR_LIT>' % k for k in range(nbit + nbit)}<EOL>AND = defaultdict(dict)  <EOL>SUM = defaultdict(dict)  <EOL>CARRY = defaultdict(dict)  <EOL>for i in range(num_multiplier_bits):<EOL><INDENT>for j in range(num_multiplicand_bits):<EOL><INDENT>ai = a[i]<EOL>bj = b[j]<EOL>if i == <NUM_LIT:0> and j == <NUM_LIT:0>:<EOL><INDENT>andij = AND[i][j] = p[<NUM_LIT:0>]<EOL>gate = and_gate([ai, bj, andij], vartype=vartype, name='<STR_LIT>' % (ai, bj, andij))<EOL>csp.add_constraint(gate)<EOL>continue<EOL><DEDENT>andij = AND[i][j] = '<STR_LIT>' % (i, j)<EOL>gate = and_gate([ai, bj, andij], vartype=vartype, name='<STR_LIT>' % (ai, bj, andij))<EOL>csp.add_constraint(gate)<EOL>inputs = [andij]<EOL>if i - <NUM_LIT:1> in CARRY and j in CARRY[i - <NUM_LIT:1>]:<EOL><INDENT>inputs.append(CARRY[i - <NUM_LIT:1>][j])<EOL><DEDENT>if i - <NUM_LIT:1> in SUM and j + <NUM_LIT:1> in SUM[i - <NUM_LIT:1>]:<EOL><INDENT>inputs.append(SUM[i - <NUM_LIT:1>][j + <NUM_LIT:1>])<EOL><DEDENT>if len(inputs) == <NUM_LIT:1>:<EOL><INDENT>SUM[i][j] = andij<EOL><DEDENT>elif len(inputs) == <NUM_LIT:2>:<EOL><INDENT>if j == <NUM_LIT:0>:<EOL><INDENT>sumij = SUM[i][j] = p[i]<EOL><DEDENT>else:<EOL><INDENT>sumij = SUM[i][j] = '<STR_LIT>' % (i, j)<EOL><DEDENT>carryij = CARRY[i][j] = '<STR_LIT>' % (i, j)<EOL>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumij, carryij)<EOL>gate = halfadder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumij, carryij], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL><DEDENT>else:<EOL><INDENT>assert len(inputs) == <NUM_LIT:3>, '<STR_LIT>'<EOL>if j == <NUM_LIT:0>:<EOL><INDENT>sumij = SUM[i][j] = p[i]<EOL><DEDENT>else:<EOL><INDENT>sumij = SUM[i][j] = '<STR_LIT>' % (i, j)<EOL><DEDENT>carryij = CARRY[i][j] = '<STR_LIT>' % (i, j)<EOL>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumij, carryij)<EOL>gate = fulladder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumij, carryij], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL><DEDENT><DEDENT><DEDENT>for col in range(nbit - <NUM_LIT:1>):<EOL><INDENT>inputs = [CARRY[nbit - <NUM_LIT:1>][col], SUM[nbit - <NUM_LIT:1>][col + <NUM_LIT:1>]]<EOL>if col == <NUM_LIT:0>:<EOL><INDENT>sumout = p[nbit + col]<EOL>carryout = CARRY[nbit][col] = '<STR_LIT>' % (nbit, col)<EOL>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumout, carryout)<EOL>gate = halfadder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], sumout, carryout], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL>continue<EOL><DEDENT>inputs.append(CARRY[nbit][col - <NUM_LIT:1>])<EOL>sumout = p[nbit + col]<EOL>if col < nbit - <NUM_LIT:2>:<EOL><INDENT>carryout = CARRY[nbit][col] = '<STR_LIT>' % (nbit, col)<EOL><DEDENT>else:<EOL><INDENT>carryout = p[<NUM_LIT:2> * nbit - <NUM_LIT:1>]<EOL><DEDENT>name = '<STR_LIT>' % (inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumout, carryout)<EOL>gate = fulladder_gate([inputs[<NUM_LIT:0>], inputs[<NUM_LIT:1>], inputs[<NUM_LIT:2>], sumout, carryout], vartype=vartype, name=name)<EOL>csp.add_constraint(gate)<EOL><DEDENT>return csp<EOL>

Multiplication circuit constraint satisfaction problem.

    A constraint satisfaction problem that represents the binary multiplication :math:`ab=p`,
    where the multiplicands are binary variables of length `nbit`; for example,
    :math:`a_0 + 2a_1 + 4a_2 +... +2^ma_{nbit}`.

    The square below shows a graphic representation of the circuit::

      ________________________________________________________________________________
      |                                         and20         and10         and00    |
      |                                           |             |             |      |
      |                           and21         add11──and11  add01──and01    |      |
      |                             |┌───────────┘|┌───────────┘|             |      |
      |             and22         add12──and12  add02──and02    |             |      |
      |               |┌───────────┘|┌───────────┘|             |             |      |
      |             add13─────────add03           |             |             |      |
      |  ┌───────────┘|             |             |             |             |      |
      | p5            p4            p3            p2            p1            p0     |
      --------------------------------------------------------------------------------

    Args:
        nbit (int): Number of bits in the multiplicands.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}

    Returns:
        CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when variables
        :math:`a,b,p` are assigned values that correctly solve binary multiplication :math:`ab=p`.

    Examples:
        This example creates a multiplication circuit CSP that multiplies two 3-bit numbers,
        which is then formulated as a binary quadratic model (BQM). It fixes the multiplacands
        as :math:`a=5, b=6` (:math:`101` and :math:`110`) and uses a simulated annealing sampler
        to find the product, :math:`p=30` (:math:`111100`).

        >>> import dwavebinarycsp
        >>> from dwavebinarycsp.factories.csp.circuits import multiplication_circuit
        >>> import neal
        >>> csp = multiplication_circuit(3)
        >>> bqm = dwavebinarycsp.stitch(csp)
        >>> bqm.fix_variable('a0', 1); bqm.fix_variable('a1', 0); bqm.fix_variable('a2', 1)
        >>> bqm.fix_variable('b0', 1); bqm.fix_variable('b1', 1); bqm.fix_variable('b2', 0)
        >>> sampler = neal.SimulatedAnnealingSampler()
        >>> response = sampler.sample(bqm)
        >>> p = next(response.samples(n=1, sorted_by='energy'))
        >>> print(p['p0'], p['p1'], p['p2'], p['p3'], p['p4'], p['p5'])    # doctest: +SKIP
        1 1 1 1 0 0


<EOL>variables = set(variables)<EOL>if not variables.issubset(self.variables):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>idxs = [i for i, v in enumerate(self.variables) if v in variables]<EOL>configurations = frozenset(tuple(config[i] for i in idxs) for config in self.configurations)<EOL>variables = tuple(self.variables[i] for i in idxs)<EOL>return self.from_configurations(configurations, variables, self.vartype)<EOL>

Create a new constraint that is the projection onto a subset of the variables.

        Args:
            variables (iterable):
                Subset of the constraint's variables.

        Returns:
            :obj:`.Constraint`: A new constraint over a subset of the variables.

        Examples:

            >>> import dwavebinarycsp
            ...
            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0), (0, 1)],
            ...                                                       ['a', 'b'],
            ...                                                       dwavebinarycsp.BINARY)
            >>> proj = const.projection(['a'])
            >>> proj.variables
            ['a']
            >>> proj.configurations
            {(0,)}


return self.variables.__len__()<EOL>


variables = self.variables<EOL>try:<EOL><INDENT>idx = variables.index(v)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(v))<EOL><DEDENT>if value not in self.vartype.value:<EOL><INDENT>raise ValueError("<STR_LIT>".format(self.vartype.value, value))<EOL><DEDENT>configurations = frozenset(config[:idx] + config[idx + <NUM_LIT:1>:]  <EOL>for config in self.configurations<EOL>if config[idx] == value)<EOL>if not configurations:<EOL><INDENT>raise UnsatError("<STR_LIT>".format(v, value))<EOL><DEDENT>variables = variables[:idx] + variables[idx + <NUM_LIT:1>:]<EOL>self.configurations = configurations<EOL>self.variables = variables<EOL>def func(*args): return args in configurations<EOL>self.func = func<EOL>self.name = '<STR_LIT>'.format(self.name, v, value)<EOL>

Fix the value of a variable and remove it from the constraint.

        Args:
            v (variable):
                Variable in the constraint to be set to a constant value.

            val (int):
                Value assigned to the variable. Values must match the :class:`.Vartype` of the
                constraint.

        Examples:
            This example creates a constraint that :math:`a \\ne b` on binary variables,
            fixes variable a to 0, and tests two candidate solutions.

            >>> import dwavebinarycsp
            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> const.fix_variable('a', 0)
            >>> const.check({'b': 1})
            True
            >>> const.check({'b': 0})
            False


@classmethod<EOL><INDENT>@dimod.decorators.vartype_argument('<STR_LIT>')<EOL>def from_func(cls, func, variables, vartype, name=None):<DEDENT>

variables = tuple(variables)<EOL>configurations = frozenset(config<EOL>for config in itertools.product(vartype.value, repeat=len(variables))<EOL>if func(*config))<EOL>return cls(func, configurations, variables, vartype, name)<EOL>

Construct a constraint from a validation function.

        Args:
            func (function):
                Function that evaluates True when the variables satisfy the constraint.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:
            This example creates a constraint that binary variables `a` and `b`
            are not equal.

            >>> import dwavebinarycsp
            >>> import operator
            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')
            >>> print(const.name)
            Constraint
            >>> (0, 1) in const.configurations
            True

            This example creates a constraint that :math:`out = NOT(x)`
            for spin variables.

            >>> import dwavebinarycsp
            >>> def not_(y, x):  # y=NOT(x) for spin variables
            ...     return (y == -x)
            ...
            >>> const = dwavebinarycsp.Constraint.from_func(
            ...               not_,
            ...               ['out', 'in'],
            ...               {1, -1},
            ...               name='not_spin')
            >>> print(const.name)
            not_spin
            >>> (1, -1) in const.configurations
            True


return all(constraint.check(solution) for constraint in self.constraints)<EOL>

Check that a solution satisfies all of the constraints.

        Args:
            solution (container):
                An assignment of values for the variables in the constraint satisfaction problem.

        Returns:
            bool: True if the solution satisfies all of the constraints; False otherwise.

        Examples:
            This example creates a binary-valued constraint satisfaction problem, adds
            two logic gates implementing Boolean constraints, :math:`c = a \wedge b`
            and :math:`d = a \oplus c`, and verifies that the combined problem is satisfied
            for a given assignment.

            >>> import dwavebinarycsp
            >>> import dwavebinarycsp.factories.constraint.gates as gates
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate
            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate
            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})
            True


self.variables[v]<EOL>

Add a variable.

        Args:
            v (variable):
                Variable in the constraint satisfaction problem. May be of any type that
                can be a dict key.

        Examples:
            This example adds two variables, one of which is already used in a constraint
            of the constraint satisfaction problem.

            >>> import dwavebinarycsp
            >>> import operator
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> csp.add_constraint(operator.eq, ['a', 'b'])
            >>> csp.add_variable('a')  # does nothing, already added as part of the constraint
            >>> csp.add_variable('c')
            >>> csp.check({'a': -1, 'b': -1, 'c': 1})
            True
            >>> csp.check({'a': -1, 'b': -1, 'c': -1})
            True


def add_constraint(self, constraint, variables=tuple()):

if isinstance(constraint, Constraint):<EOL><INDENT>if variables and (tuple(variables) != constraint.variables):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif isinstance(constraint, Callable):<EOL><INDENT>constraint = Constraint.from_func(constraint, variables, self.vartype)<EOL><DEDENT>elif isinstance(constraint, Iterable):<EOL><INDENT>constraint = Constraint.from_configurations(constraint, variables, self.vartype)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.constraints.append(constraint)<EOL>for v in constraint.variables:<EOL><INDENT>self.variables[v].append(constraint)<EOL><DEDENT>

Add a constraint.

        Args:
            constraint (function/iterable/:obj:`.Constraint`):
                Constraint definition in one of the supported formats:

                1. Function, with input arguments matching the order and
                   :attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`
                   argument, that evaluates True when the constraint is satisfied.
                2. List explicitly specifying each allowed configuration as a tuple.
                3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.

            variables(iterable):
                Variables associated with the constraint. Not required when `constraint` is
                a :obj:`.Constraint` object.

        Examples:
            This example defines a function that evaluates True when the constraint is satisfied.
            The function's input arguments match the order and type of the `variables` argument.

            >>> import dwavebinarycsp
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> def all_equal(a, b, c):  # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN
            ...     return (a == b) and (b == c)
            >>> csp.add_constraint(all_equal, ['a', 'b', 'c'])
            >>> csp.check({'a': 0, 'b': 0, 'c': 0})
            True
            >>> csp.check({'a': 0, 'b': 0, 'c': 1})
            False

            This example explicitly lists allowed configurations.

            >>> import dwavebinarycsp
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> eq_configurations = {(-1, -1), (1, 1)}
            >>> csp.add_constraint(eq_configurations, ['v0', 'v1'])
            >>> csp.check({'v0': -1, 'v1': +1})
            False
            >>> csp.check({'v0': -1, 'v1': -1})
            True

            This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.

            >>> import dwavebinarycsp
            >>> import dwavebinarycsp.factories.constraint.gates as gates
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
            >>> csp.add_constraint(gates.and_gate(['a', 'b', 'c']))  # add an AND gate
            >>> csp.add_constraint(gates.xor_gate(['a', 'c', 'd']))  # add an XOR gate
            >>> csp.check({'a': 1, 'b': 0, 'c': 0, 'd': 1})
            True


if v not in self.variables:<EOL><INDENT>raise ValueError("<STR_LIT>".format(v))<EOL><DEDENT>for constraint in self.variables[v]:<EOL><INDENT>constraint.fix_variable(v, value)<EOL><DEDENT>del self.variables[v]<EOL>

Fix the value of a variable and remove it from the constraint satisfaction problem.

        Args:
            v (variable):
                Variable to be fixed in the constraint satisfaction problem.

            value (int):
                Value assigned to the variable. Values must match the
                :attr:`~.ConstraintSatisfactionProblem.vartype` of the constraint
                satisfaction problem.

        Examples:
            This example creates a spin-valued constraint satisfaction problem, adds two constraints,
            :math:`a = b` and :math:`b \\ne c`, and fixes variable b to +1.

            >>> import dwavebinarycsp
            >>> import operator
            >>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
            >>> csp.add_constraint(operator.eq, ['a', 'b'])
            >>> csp.add_constraint(operator.ne, ['b', 'c'])
            >>> csp.check({'a': +1, 'b': +1, 'c': -1})
            True
            >>> csp.check({'a': -1, 'b': -1, 'c': +1})
            True
            >>> csp.fix_variable('b', +1)
            >>> csp.check({'a': +1, 'b': +1, 'c': -1})  # 'b' is ignored
            True
            >>> csp.check({'a': -1, 'b': -1, 'c': +1})
            False
            >>> csp.check({'a': +1, 'c': -1})
            True
            >>> csp.check({'a': -1, 'c': +1})
            False


configurations = constraint.configurations<EOL>num_configurations = len(configurations)<EOL>bqm = dimod.BinaryQuadraticModel.empty(constraint.vartype)<EOL>if num_configurations == <NUM_LIT:1>:<EOL><INDENT>val, = next(iter(configurations))<EOL>v, = constraint.variables<EOL>bqm.add_variable(v, -<NUM_LIT:1> if val > <NUM_LIT:0> else +<NUM_LIT:1>, vartype=dimod.SPIN)<EOL><DEDENT>else:<EOL><INDENT>bqm.add_variables_from((v, <NUM_LIT:0.0>) for v in constraint.variables)<EOL><DEDENT>return bqm<EOL>

create a bqm for a constraint with only one variable

    bqm will have exactly classical gap 2.


return list(self._results.keys())<EOL>

Returns a list of strings to represent the options for the poll, in
        the order they were given when the poll was created.


return list(self._results.items())[index]<EOL>

Returns a tuple containing a string representing the option and an
        int which specify the current votes for that option.

        :param int index: The index of the wanted option in the options list.


def submit_poll(self, poll, *, request_policy=None):

if poll.id is not None:<EOL><INDENT>raise ExistingPoll()<EOL><DEDENT>options = poll.options<EOL>data = {<EOL>'<STR_LIT:title>': poll.title,<EOL>'<STR_LIT>': options,<EOL>'<STR_LIT>': poll.multi,<EOL>'<STR_LIT>': poll.dupcheck,<EOL>'<STR_LIT>': poll.captcha<EOL>}<EOL>return self._http_client.post(self._POLLS,<EOL>data=data,<EOL>request_policy=request_policy,<EOL>cls=strawpoll.Poll)<EOL>

Submits a poll on strawpoll.

        :param poll: The poll to submit.
        :type poll: :class:`Poll`
        :param request_policy: Overrides :attr:`API.requests_policy` for that \
        request.
        :type request_policy: Optional[:class:`RequestsPolicy`]

        :raises ExistingPoll: This poll instance has already been submitted.
        :raises HTTPException: The submission failed.

        :returns: The given poll updated with the data sent back from the submission.
        :rtype: :class:`Poll`

        .. note::
            Only polls that have a non empty title and between 2 and 30 options
            can be submitted.


return hmac.new(<EOL>self._secret, request.data, hashlib.sha1).hexdigest() if self._secret else None<EOL>

Return message digest if a secret key was provided


usage = "<STR_LIT>"<EOL>parser = optparse.OptionParser(usage=usage)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store_true>", dest="<STR_LIT>", default=False,<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store>", type="<STR_LIT:string>", dest="<STR_LIT>",<EOL>default='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store>", type="<STR_LIT:string>", dest="<STR_LIT>",<EOL>default='<STR_LIT>',<EOL>help=("<STR_LIT>" +<EOL>"<STR_LIT>"))<EOL>(options, args) = parser.parse_args()<EOL>if options.verbose:<EOL><INDENT>log_level = logging.DEBUG<EOL><DEDENT>else:<EOL><INDENT>log_level = logging.INFO<EOL><DEDENT>logging.basicConfig(level=log_level,<EOL>format="<STR_LIT>")<EOL>curdir = os.getcwd()<EOL>testbinary = os.path.join(curdir, '<STR_LIT>', '<STR_LIT:test>')<EOL>if not os.path.exists(testbinary):<EOL><INDENT>raise RuntimeError("<STR_LIT>" % testbinary)<EOL><DEDENT>coveragebinary = os.path.join(curdir, '<STR_LIT>', '<STR_LIT>')<EOL>if not os.path.exists(coveragebinary):<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>coveragebinary = '<STR_LIT>'<EOL><DEDENT>logger.info("<STR_LIT>")<EOL>parts = [coveragebinary, '<STR_LIT>', testbinary]<EOL>if options.test_args:<EOL><INDENT>parts.append(options.test_args)<EOL><DEDENT>system("<STR_LIT:U+0020>".join(parts))<EOL>logger.debug("<STR_LIT>")<EOL>if options.output_dir:<EOL><INDENT>coverage_dir = options.output_dir<EOL>open_in_browser = False<EOL><DEDENT>else:<EOL><INDENT>coverage_dir = '<STR_LIT>'  <EOL>open_in_browser = True<EOL><DEDENT>system("<STR_LIT>" % (coveragebinary, coverage_dir))<EOL>logger.info("<STR_LIT>", coverage_dir)<EOL>if open_in_browser:<EOL><INDENT>index_file = os.path.abspath(<EOL>os.path.join(coverage_dir, '<STR_LIT>'))<EOL>logger.debug("<STR_LIT>", index_file)<EOL>webbrowser.open('<STR_LIT>' + index_file)<EOL>logger.info("<STR_LIT>")<EOL><DEDENT>

Create coverage reports and open them in the browser.


logger.debug("<STR_LIT>", command)<EOL>p = subprocess.Popen(command,<EOL>shell=True,<EOL>stdin=subprocess.PIPE,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>close_fds=MUST_CLOSE_FDS)<EOL>stdoutdata, stderrdata = p.communicate(input=input)<EOL>result = stdoutdata + stderrdata<EOL>if p.returncode:<EOL><INDENT>logger.error("<STR_LIT>",<EOL>command)<EOL>logger.error("<STR_LIT>", p.returncode)<EOL>logger.error("<STR_LIT>")<EOL>logger.error(result)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>logger.info(result)<EOL>

commands.getoutput() replacement that also works on windows.

    Code mostly copied from zc.buildout.


context.log.debug(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% scenario.name)<EOL>

Add an entry to the debug log after scenario was finished


context.log.debug(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% scenario.name)<EOL>context.params = {}<EOL>context.exception = None<EOL>context.result = None<EOL>

Add entry to the debug log befere starting the scenario


return quote(string.encode('<STR_LIT:utf8>'), safe='<STR_LIT>')<EOL>

Percent encode a string as ASCII so that it is a valid part of a URI

    :param string: str
    :returns: ASCII string


if not string or not re.match('<STR_LIT>' + PARTS[part] + '<STR_LIT>', string):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(part, PARTS[part]))<EOL><DEDENT>

Raise an exception if string doesn't match a part's regex

    :param string: str
    :param part: a key in the PARTS dict
    :raises: ValueError, TypeError


try:<EOL><INDENT>parse_hub_key(value)<EOL>return True<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>return False<EOL><DEDENT>

Test if a value could be a hub key
    :param value: the value to test if it is a hub key
    :returns: True if it is a hub key


def generate_hub_key(resolver_id, hub_id, repository_id, entity_type, entity_id=None):

parsed = urlparse(resolver_id)<EOL>if not parsed.scheme:<EOL><INDENT>parsed = parsed._replace(scheme=PROTOCOL, netloc=idna_encode(parsed.path.lower()), path=u'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>parsed = parsed._replace(netloc=idna_encode(parsed.netloc.lower()))<EOL><DEDENT>resolver_id = urlunparse(parsed)<EOL>hub_id = url_quote(hub_id.lower())<EOL>if not entity_id:<EOL><INDENT>entity_id = str(uuid.uuid4()).replace('<STR_LIT:->', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>match_part(entity_id, '<STR_LIT>')<EOL><DEDENT>match_part(resolver_id, '<STR_LIT>')<EOL>match_part(hub_id, '<STR_LIT>')<EOL>match_part(repository_id, '<STR_LIT>')<EOL>match_part(entity_type, '<STR_LIT>')<EOL>hub_key = SEPARATOR.join(<EOL>[resolver_id, SCHEMA, hub_id, repository_id, entity_type, entity_id])<EOL>return hub_key<EOL>

Create and return an array of hub keys
    :param resolver_id: the service that can resolve this key
    :param hub_id: the unique id of the hub
    :param repository_id: the type of id that the provider recognises
    :param entity_type: the type of the entity to which the key refers.
    :param entity_id: ID of entity (UUID)
    :returns: a hub key
    :raises:
    :AttributeError: if a parameter has a bad value
    :TypeError: if a parameter has a bad value
    :ValueError: if a parameter has a bad value


def press_key(self, key, mode=<NUM_LIT:0>):

if isinstance(key, str):<EOL><INDENT>assert key in KEYS, '<STR_LIT>'.format(key)<EOL>key = KEYS[key]<EOL><DEDENT>_LOGGER.info('<STR_LIT>', self.__get_key_name(key))<EOL>return self.rq('<STR_LIT>', OrderedDict([('<STR_LIT:key>', key), ('<STR_LIT>', mode)]))<EOL>

modes:
    0 -> simple press
    1 -> long press
    2 -> release after long press


if isinstance(obj, dict):<EOL><INDENT>for k, v in obj.items():<EOL><INDENT>if v is referent:<EOL><INDENT>return "<STR_LIT>" % k<EOL><DEDENT><DEDENT><DEDENT>for k in dir(obj) + ['<STR_LIT>']:<EOL><INDENT>if getattr(obj, k, None) is referent:<EOL><INDENT>return "<STR_LIT>" % k<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Return the dict key or attribute name of obj which refers to
        referent.


objtype = type(obj)<EOL>typename = str(objtype.__module__) + "<STR_LIT:.>" + objtype.__name__<EOL>prettytype = typename.replace("<STR_LIT>", "<STR_LIT>")<EOL>name = getattr(obj, "<STR_LIT>", "<STR_LIT>")<EOL>if name:<EOL><INDENT>prettytype = "<STR_LIT>" % (prettytype, name)<EOL><DEDENT>key = "<STR_LIT>"<EOL>if referent:<EOL><INDENT>key = self.get_refkey(obj, referent)<EOL><DEDENT>url = reverse('<STR_LIT>', args=(<EOL>typename,<EOL>id(obj)<EOL>))<EOL>return ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>% (url, id(obj), prettytype, key, get_repr(obj, <NUM_LIT:100>))<EOL>)<EOL>

Return an HTML tree block describing the given object.


def print_tree(self, maxresults=<NUM_LIT:100>, maxdepth=None):

self.ignore_caller()<EOL>for trail in self.walk(maxresults, maxdepth):<EOL><INDENT>print(trail)<EOL><DEDENT>if self.stops:<EOL><INDENT>print("<STR_LIT>" % self.stops)<EOL><DEDENT>

Walk the object tree, pretty-printing each branch.


def walk(self, maxresults=<NUM_LIT:100>, maxdepth=None):

self.stops = <NUM_LIT:0><EOL>self.seen = {}<EOL>self.ignore(self, self.__dict__, self.seen, self._ignore)<EOL>self.ignore_caller()<EOL>self.maxdepth = maxdepth<EOL>count = <NUM_LIT:0><EOL>for result in self._gen(self.obj):<EOL><INDENT>yield result<EOL>count += <NUM_LIT:1><EOL>if maxresults and count >= maxresults:<EOL><INDENT>yield <NUM_LIT:0>, <NUM_LIT:0>, "<STR_LIT>"<EOL>return<EOL><DEDENT><DEDENT>

Walk the object tree, showing circular referents.