def _extractall(self, path="<STR_LIT:.>", members=None):

import copy<EOL>import operator<EOL>from tarfile import ExtractError<EOL>directories = []<EOL>if members is None:<EOL><INDENT>members = self<EOL><DEDENT>for tarinfo in members:<EOL><INDENT>if tarinfo.isdir():<EOL><INDENT>directories.append(tarinfo)<EOL>tarinfo = copy.copy(tarinfo)<EOL>tarinfo.mode = <NUM_LIT> <EOL><DEDENT>self.extract(tarinfo, path)<EOL><DEDENT>if sys.version_info < (<NUM_LIT:2>, <NUM_LIT:4>):<EOL><INDENT>def sorter(dir1, dir2):<EOL><INDENT>return cmp(dir1.name, dir2.name)<EOL><DEDENT>directories.sort(sorter)<EOL>directories.reverse()<EOL><DEDENT>else:<EOL><INDENT>directories.sort(key=operator.attrgetter('<STR_LIT:name>'), reverse=True)<EOL><DEDENT>for tarinfo in directories:<EOL><INDENT>dirpath = os.path.join(path, tarinfo.name)<EOL>try:<EOL><INDENT>self.chown(tarinfo, dirpath)<EOL>self.utime(tarinfo, dirpath)<EOL>self.chmod(tarinfo, dirpath)<EOL><DEDENT>except ExtractError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if self.errorlevel > <NUM_LIT:1>:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % e)<EOL><DEDENT><DEDENT><DEDENT>

Extract all members from the archive to the current working
       directory and set owner, modification time and permissions on
       directories afterwards. `path' specifies a different directory
       to extract to. `members' is optional and must be a subset of the
       list returned by getmembers().


tarball = download_setuptools()<EOL>_install(tarball)<EOL>

Install or upgrade setuptools and EasyInstall


if context:<EOL><INDENT>texts = context.xpath('<STR_LIT>').extract()<EOL>text = str(texts).lower()<EOL>if len(texts) > <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>elif '<STR_LIT>' in text:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>elif '<STR_LIT>' not in text:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>elif '<STR_LIT>' in text:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif '<STR_LIT>' in text:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT><DEDENT>return <NUM_LIT:3><EOL>

The likelihood that the context is a "member".


def make_url(symbol, start_date='<STR_LIT>', end_date='<STR_LIT>'):

return '<STR_LIT>'% (symbol, end_date, start_date)<EOL>

A URL that lists all 10-Q and 10-K filings of a company.


def _adjust_delay(self, slot, response):

if response.status in self.retry_http_codes:<EOL><INDENT>new_delay = max(slot.delay, <NUM_LIT:1>) * <NUM_LIT:4><EOL>new_delay = max(new_delay, self.mindelay)<EOL>new_delay = min(new_delay, self.maxdelay)<EOL>slot.delay = new_delay<EOL>self.stats.inc_value('<STR_LIT>')<EOL><DEDENT>elif response.status == <NUM_LIT:200>:<EOL><INDENT>new_delay = max(slot.delay / <NUM_LIT:2>, self.mindelay)<EOL>if new_delay < <NUM_LIT>:<EOL><INDENT>new_delay = <NUM_LIT:0><EOL><DEDENT>slot.delay = new_delay<EOL><DEDENT>


loader = ReportItemLoader(response=response)<EOL>item = loader.load_item()<EOL>if '<STR_LIT>' in item:<EOL><INDENT>doc_type = item['<STR_LIT>']<EOL>if doc_type in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return item<EOL><DEDENT><DEDENT>return None<EOL>


async def _try_catch_coro(emitter, event, listener, coro):

try:<EOL><INDENT>await coro<EOL><DEDENT>except Exception as exc:<EOL><INDENT>if event == emitter.LISTENER_ERROR_EVENT:<EOL><INDENT>raise<EOL><DEDENT>emitter.emit(emitter.LISTENER_ERROR_EVENT, event, listener, exc)<EOL><DEDENT>

Coroutine wrapper to catch errors after async scheduling.

    Args:
        emitter (EventEmitter): The event emitter that is attempting to
            call a listener.
        event (str): The event that triggered the emitter.
        listener (async def): The async def that was used to generate the coro.
        coro (coroutine): The coroutine that should be tried.

    If an exception is caught the function will use the emitter to emit the
    failure event. If, however, the current event _is_ the failure event then
    the method reraises. The reraised exception may show in debug mode for the
    event loop but is otherwise silently dropped.


self._loop = loop or asyncio.get_event_loop()<EOL>self._listeners = collections.defaultdict(list)<EOL>self._once = collections.defaultdict(list)<EOL>self._max_listeners = self.DEFAULT_MAX_LISTENERS<EOL>

Initialize the emitter with an event loop.


if self.count(event) > self.max_listeners:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'.format(event),<EOL>ResourceWarning,<EOL>)<EOL><DEDENT>

Check if the listener limit is hit and warn if needed.


def add_listener(self, event, listener):

self.emit('<STR_LIT>', event, listener)<EOL>self._listeners[event].append(listener)<EOL>self._check_limit(event)<EOL>return self<EOL>

Bind a listener to a particular event.

        Args:
            event (str): The name of the event to listen for. This may be any
                string value.
            listener (def or async def): The callback to execute when the event
                fires. This may be a sync or async function.


self.emit('<STR_LIT>', event, listener)<EOL>self._once[event].append(listener)<EOL>self._check_limit(event)<EOL>return self<EOL>

Add a listener that is only called once.


def remove_listener(self, event, listener):

with contextlib.suppress(ValueError):<EOL><INDENT>self._listeners[event].remove(listener)<EOL>return True<EOL><DEDENT>with contextlib.suppress(ValueError):<EOL><INDENT>self._once[event].remove(listener)<EOL>return True<EOL><DEDENT>return False<EOL>

Remove a listener from the emitter.

        Args:
            event (str): The event name on which the listener is bound.
            listener: A reference to the same object given to add_listener.

        Returns:
            bool: True if a listener was removed else False.

        This method only removes one listener at a time. If a listener is
        attached multiple times then this method must be called repeatedly.
        Additionally, this method removes listeners first from the those
        registered with 'on' or 'add_listener'. If none are found it continue
        to remove afterwards from those added with 'once'.


if event is None:<EOL><INDENT>self._listeners = collections.defaultdict(list)<EOL>self._once = collections.defaultdict(list)<EOL><DEDENT>else:<EOL><INDENT>del self._listeners[event]<EOL>del self._once[event]<EOL><DEDENT>

Remove all listeners, or those of the specified *event*.

        It's not a good idea to remove listeners that were added elsewhere in
        the code, especially when it's on an emitter that you didn't create
        (e.g. sockets or file streams).


return self._max_listeners<EOL>

Get the max number of listeners before warning.


self._max_listeners = value<EOL>

Set the max number of listeners before warning.


return self._listeners[event][:] + self._once[event][:]<EOL>

Get an iterable of all listeners for the given event.

        Args:
            event (str): The name of the event for which to generate an
                iterable of listeners.

        The resulting iterable contains all listeners regardless of whether
        they were registered with 'on'/'add_listener' or 'once'.


def _dispatch_coroutine(self, event, listener, *args, **kwargs):

try:<EOL><INDENT>coro = listener(*args, **kwargs)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>if event == self.LISTENER_ERROR_EVENT:<EOL><INDENT>raise<EOL><DEDENT>return self.emit(self.LISTENER_ERROR_EVENT, event, listener, exc)<EOL><DEDENT>asyncio.ensure_future(<EOL>_try_catch_coro(self, event, listener, coro),<EOL>loop=self._loop,<EOL>)<EOL>

Schedule a coroutine for execution.

        Args:
            event (str): The name of the event that triggered this call.
            listener (async def): The async def that needs to be executed.
            *args: Any number of positional arguments.
            **kwargs: Any number of keyword arguments.

        The values of *args and **kwargs are passed, unaltered, to the async
        def when generating the coro. If there is an exception generating the
        coro, such as the wrong number of arguments, the emitter's error event
        is triggered. If the triggering event _is_ the emitter's error event
        then the exception is reraised. The reraised exception may show in
        debug mode for the event loop but is otherwise silently dropped.


def _dispatch_function(self, event, listener, *args, **kwargs):

try:<EOL><INDENT>return listener(*args, **kwargs)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>if event == self.LISTENER_ERROR_EVENT:<EOL><INDENT>raise<EOL><DEDENT>return self.emit(self.LISTENER_ERROR_EVENT, event, listener, exc)<EOL><DEDENT>

Execute a sync function.

        Args:
            event (str): The name of the event that triggered this call.
            listener (def): The def that needs to be executed.
            *args: Any number of positional arguments.
            **kwargs: Any number of keyword arguments.

        The values of *args and **kwargs are passed, unaltered, to the def
        when exceuting. If there is an exception executing the def, such as the
        wrong number of arguments, the emitter's error event is triggered. If
        the triggering event _is_ the emitter's error event then the exception
        is reraised. The reraised exception may show in debug mode for the
        event loop but is otherwise silently dropped.


def _dispatch(self, event, listener, *args, **kwargs):

if (<EOL>asyncio.iscoroutinefunction(listener) or<EOL>isinstance(listener, functools.partial) and<EOL>asyncio.iscoroutinefunction(listener.func)<EOL>):<EOL><INDENT>return self._dispatch_coroutine(event, listener, *args, **kwargs)<EOL><DEDENT>return self._dispatch_function(event, listener, *args, **kwargs)<EOL>

Dispatch an event to a listener.

        Args:
            event (str): The name of the event that triggered this call.
            listener (def or async def): The listener to trigger.
            *args: Any number of positional arguments.
            **kwargs: Any number of keyword arguments.

        This method inspects the listener. If it is a def it dispatches the
        listener to a method that will execute that def. If it is an async def
        it dispatches it to a method that will schedule the resulting coro with
        the event loop.


listeners = self._listeners[event]<EOL>listeners = itertools.chain(listeners, self._once[event])<EOL>self._once[event] = []<EOL>for listener in listeners:<EOL><INDENT>self._loop.call_soon(<EOL>functools.partial(<EOL>self._dispatch,<EOL>event,<EOL>listener,<EOL>*args,<EOL>**kwargs,<EOL>)<EOL>)<EOL><DEDENT>return self<EOL>

Call each listener for the event with the given arguments.

        Args:
            event (str): The event to trigger listeners on.
            *args: Any number of positional arguments.
            **kwargs: Any number of keyword arguments.

        This method passes all arguments other than the event name directly
        to the listeners. If a listener raises an exception for any reason the
        'listener-error', or current value of LISTENER_ERROR_EVENT, is emitted.
        Listeners to this event are given the event name, listener object, and
        the exception raised. If an error listener fails it does so silently.

        All event listeners are fired in a deferred way so this method returns
        immediately. The calling coro must yield at some point for the event
        to propagate to the listeners.


return len(self._listeners[event]) + len(self._once[event])<EOL>

Get the number of listeners for the event.

        Args:
            event (str): The event for which to count all listeners.

        The resulting count is a combination of listeners added using
        'on'/'add_listener' and 'once'.


self._emitter = emitter<EOL>self._event = event<EOL>self._emitter.on(event, self._push)<EOL>self._data = collections.deque()<EOL>self._future = None<EOL>

Initialize the iterator with an emitter and event to fire on.


self._data.append((args, kwargs))<EOL>if self._future is not None:<EOL><INDENT>future, self._future = self._future, None<EOL>future.set_result(True)<EOL><DEDENT>

Push new data into the buffer. Resume looping if paused.


if self._data:<EOL><INDENT>return self._data.popleft()<EOL><DEDENT>self._future = asyncio.Future()<EOL>await self._future<EOL>return self._data.popleft()<EOL>

Fetch the next set of values. Wait for new values if empty.


self._emitter = emitter<EOL>self._event = event<EOL>

Initialize the iterable with an emitter and target event.


return EventIterator(self._emitter, self._event)<EOL>


if not thread.isAlive():<EOL><INDENT>return<EOL><DEDENT>exc = ctypes.py_object(SystemExit)<EOL>res = ctypes.pythonapi.PyThreadState_SetAsyncExc(<EOL>ctypes.c_long(thread.ident), exc)<EOL>if res == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif res > <NUM_LIT:1>:<EOL><INDENT>ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)<EOL>raise SystemError("<STR_LIT>")<EOL><DEDENT>

Terminates a python thread from another thread.

    :param thread: a threading.Thread instance


def bracket_split(source, brackets=('<STR_LIT>', '<STR_LIT:{}>', '<STR_LIT>'), strip=False):

starts = [e[<NUM_LIT:0>] for e in brackets]<EOL>in_bracket = <NUM_LIT:0><EOL>n = <NUM_LIT:0><EOL>last = <NUM_LIT:0><EOL>while n < len(source):<EOL><INDENT>e = source[n]<EOL>if not in_bracket and e in starts:<EOL><INDENT>in_bracket = <NUM_LIT:1><EOL>start = n<EOL>b_start, b_end = brackets[starts.index(e)]<EOL><DEDENT>elif in_bracket:<EOL><INDENT>if e == b_start:<EOL><INDENT>in_bracket += <NUM_LIT:1><EOL><DEDENT>elif e == b_end:<EOL><INDENT>in_bracket -= <NUM_LIT:1><EOL>if not in_bracket:<EOL><INDENT>if source[last:start]:<EOL><INDENT>yield source[last:start]<EOL><DEDENT>last = n + <NUM_LIT:1><EOL>yield source[start + strip:n + <NUM_LIT:1> - strip]<EOL><DEDENT><DEDENT><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>if source[last:]:<EOL><INDENT>yield source[last:]<EOL><DEDENT>

DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)


def pass_bracket(source, start, bracket='<STR_LIT>'):

e = bracket_split(source[start:], [bracket], False)<EOL>try:<EOL><INDENT>cand = next(e)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return None, None<EOL><DEDENT>if not cand.strip():  <EOL><INDENT>try:<EOL><INDENT>res = next(e)<EOL>return res, start + len(cand) + len(res)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return None, None<EOL><DEDENT><DEDENT>elif cand[-<NUM_LIT:1>] == bracket[<NUM_LIT:1>]:<EOL><INDENT>return cand, start + len(cand)<EOL><DEDENT>else:<EOL><INDENT>return None, None<EOL><DEDENT>

Returns content of brackets with brackets and first pos after brackets
     if source[start] is followed by some optional white space and brackets.
     Otherwise None


def except_token(source, start, token, throw=True):

start = pass_white(source, start)<EOL>if start < len(source) and source[start] == token:<EOL><INDENT>return start + <NUM_LIT:1><EOL><DEDENT>if throw:<EOL><INDENT>raise SyntaxError('<STR_LIT>' % token)<EOL><DEDENT>return None<EOL>

Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw
    otherwise returns None


def except_keyword(source, start, keyword):

start = pass_white(source, start)<EOL>kl = len(keyword)  <EOL>if kl + start > len(source):<EOL><INDENT>return None<EOL><DEDENT>if source[start:start + kl] != keyword:<EOL><INDENT>return None<EOL><DEDENT>if kl + start < len(source) and source[start + kl] in IDENTIFIER_PART:<EOL><INDENT>return None<EOL><DEDENT>return start + kl<EOL>

Returns position after keyword if found else None
        Note: skips white space


def parse_identifier(source, start, throw=True):

start = pass_white(source, start)<EOL>end = start<EOL>if not end < len(source):<EOL><INDENT>if throw:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>return None<EOL><DEDENT>if source[end] not in IDENTIFIER_START:<EOL><INDENT>if throw:<EOL><INDENT>raise SyntaxError('<STR_LIT>' % source[end])<EOL><DEDENT>return None<EOL><DEDENT>end += <NUM_LIT:1><EOL>while end < len(source) and source[end] in IDENTIFIER_PART:<EOL><INDENT>end += <NUM_LIT:1><EOL><DEDENT>if not is_valid_lval(source[start:end]):<EOL><INDENT>if throw:<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>' % source[start:end])<EOL><DEDENT>return None<EOL><DEDENT>return source[start:end], end<EOL>

passes white space from start and returns first identifier,
       if identifier invalid and throw raises SyntaxError otherwise returns None


parsed_len = <NUM_LIT:0><EOL>last = <NUM_LIT:0><EOL>splits = []<EOL>for e in bracket_split(args, brackets=['<STR_LIT>', '<STR_LIT>', '<STR_LIT:{}>']):<EOL><INDENT>if e[<NUM_LIT:0>] not in {'<STR_LIT:(>', '<STR_LIT:[>', '<STR_LIT:{>'}:<EOL><INDENT>for i, char in enumerate(e):<EOL><INDENT>if char == sep:<EOL><INDENT>splits.append(args[last:parsed_len + i])<EOL>last = parsed_len + i + <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>parsed_len += len(e)<EOL><DEDENT>splits.append(args[last:])<EOL>return splits<EOL>

used to split JS args (it is not that simple as it seems because
       sep can be inside brackets).

       pass args *without* brackets!

       Used also to parse array and object elements, and more


n = <NUM_LIT:0><EOL>text = text.replace('<STR_LIT>', '<STR_LIT>').replace(<EOL>'<STR_LIT>', '<STR_LIT>')  <EOL>spotted = False  <EOL>last = <NUM_LIT:0><EOL>while n < len(text):<EOL><INDENT>e = text[n]<EOL>if e == '<STR_LIT:+>' or e == '<STR_LIT:->':<EOL><INDENT>if spotted:<EOL><INDENT>yield text[last:n].replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>yield e<EOL>last = n + <NUM_LIT:1><EOL>spotted = False<EOL><DEDENT><DEDENT>elif e == '<STR_LIT:/>' or e == '<STR_LIT:*>' or e == '<STR_LIT:%>':<EOL><INDENT>spotted = False<EOL><DEDENT>elif e != '<STR_LIT:U+0020>':<EOL><INDENT>spotted = True<EOL><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>yield text[last:n].replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>

Specialized function splitting text at add/sub operators.
    Operands are *not* translated. Example result ['op1', '+', 'op2', '-', 'op3']


lis.sort(key=lambda x: len(x), reverse=True)<EOL>last = <NUM_LIT:0><EOL>n = <NUM_LIT:0><EOL>text_len = len(text)<EOL>while n < text_len:<EOL><INDENT>if any(text[:n].endswith(e)<EOL>for e in not_before):  <EOL><INDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>for e in lis:<EOL><INDENT>s = len(e)<EOL>if s + n > text_len:<EOL><INDENT>continue<EOL><DEDENT>if validitate and not validitate(e, text[:n], text[n + s:]):<EOL><INDENT>continue<EOL><DEDENT>if any(text[n + s:].startswith(e)<EOL>for e in not_after):  <EOL><INDENT>n += <NUM_LIT:1><EOL>break<EOL><DEDENT>if e == text[n:n + s]:<EOL><INDENT>yield text[last:n] if not translate else translate(<EOL>text[last:n])<EOL>yield e<EOL>n += s<EOL>last = n<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>yield text[last:n] if not translate else translate(text[last:n])<EOL>


def split_at_single(text, sep, not_before=[], not_after=[]):

n = <NUM_LIT:0><EOL>lt, s = len(text), len(sep)<EOL>last = <NUM_LIT:0><EOL>while n < lt:<EOL><INDENT>if not s + n > lt:<EOL><INDENT>if sep == text[n:n + s]:<EOL><INDENT>if any(text[last:n].endswith(e) for e in not_before):<EOL><INDENT>pass<EOL><DEDENT>elif any(text[n + s:].startswith(e) for e in not_after):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>yield text[last:n]<EOL>last = n + s<EOL>n += s - <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>yield text[last:]<EOL>

Works like text.split(sep) but separated fragments
    cant end with not_before or start with not_after


start = pass_white(source, start)<EOL>if not start < len(source):  <EOL><INDENT>return None, start<EOL><DEDENT>if any(startswith_keyword(source[start:], e) for e in {'<STR_LIT>', '<STR_LIT:default>'}):<EOL><INDENT>return None, start<EOL><DEDENT>rest = source[start:]<EOL>for key, meth in KEYWORD_METHODS.items(<EOL>):  <EOL><INDENT>if rest.startswith(key):<EOL><INDENT>if len(key) == len(rest) or rest[len(key)] not in IDENTIFIER_PART:<EOL><INDENT>return meth(source, start)<EOL><DEDENT><DEDENT><DEDENT>if rest[<NUM_LIT:0>] == '<STR_LIT:{>':  <EOL><INDENT>return do_block(source, start)<EOL><DEDENT>cand = parse_identifier(source, start, False)<EOL>if cand is not None:  <EOL><INDENT>label, cand_start = cand<EOL>cand_start = pass_white(source, cand_start)<EOL>if source[cand_start] == '<STR_LIT::>':<EOL><INDENT>return do_label(source, start)<EOL><DEDENT><DEDENT>return do_expression(source, start)<EOL>

returns none if not found other functions that begin with 'do_' raise
    also this do_ type function passes white space


global TO_REGISTER<EOL>TO_REGISTER = []<EOL>return do_block('<STR_LIT>' % source, <NUM_LIT:0>)[<NUM_LIT:0>], TO_REGISTER<EOL>

Source cant have arrays, object, constant or function literals.
       Returns PySource and variables to register


<EOL>no_const, constants = remove_constants(js)<EOL>no_obj, objects, obj_count = remove_objects(no_const)<EOL>no_arr, arrays, arr_count = remove_arrays(no_obj)<EOL>reset_inline_count()<EOL>no_func, hoisted, inline = remove_functions(no_arr)<EOL>py_seed, to_register = translate_flow(no_func)<EOL>top += '<STR_LIT>' % str(to_register + list(hoisted.keys()))<EOL>defs = '<STR_LIT>'<EOL>for nested_name, nested_info in hoisted.items():<EOL><INDENT>nested_block, nested_args = nested_info<EOL>new_code = translate_func('<STR_LIT>', nested_block,<EOL>nested_args)<EOL>new_code += '<STR_LIT>' % repr(nested_name)<EOL>defs += new_code + '<STR_LIT>' % repr(<EOL>nested_name)<EOL><DEDENT>for nested_name, nested_info in inline.items():<EOL><INDENT>nested_block, nested_args = nested_info<EOL>new_code = translate_func(nested_name, nested_block, nested_args)<EOL>py_seed = inject_before_lval(py_seed,<EOL>nested_name.split('<STR_LIT:@>')[<NUM_LIT:0>], new_code)<EOL><DEDENT>py_seed = defs + py_seed<EOL>for arr_lval, arr_code in arrays.items():<EOL><INDENT>translation, obj_count, arr_count = translate_array(<EOL>arr_code, arr_lval, obj_count, arr_count)<EOL>py_seed = inject_before_lval(py_seed, arr_lval, translation)<EOL><DEDENT>for obj_lval, obj_code in objects.items():<EOL><INDENT>translation, obj_count, arr_count = translate_object(<EOL>obj_code, obj_lval, obj_count, arr_count)<EOL>py_seed = inject_before_lval(py_seed, obj_lval, translation)<EOL><DEDENT>py_code = recover_constants(py_seed, constants)<EOL>return top + py_code<EOL>

js has to be a javascript source code.
       returns equivalent python code.


inline = name.startswith('<STR_LIT>')<EOL>real_name = '<STR_LIT>'<EOL>if inline:<EOL><INDENT>name, real_name = name.split('<STR_LIT:@>')<EOL><DEDENT>arglist = '<STR_LIT:U+002CU+0020>'.join(args) + '<STR_LIT:U+002CU+0020>' if args else '<STR_LIT>'<EOL>code = '<STR_LIT>' % (name, arglist)<EOL>scope = "<STR_LIT>"  <EOL>for arg in args:<EOL><INDENT>scope += '<STR_LIT>' % (repr(arg), arg)<EOL><DEDENT>if real_name:<EOL><INDENT>scope += '<STR_LIT>' % (repr(real_name), name)<EOL><DEDENT>code += indent('<STR_LIT>' % scope)<EOL>block, nested_hoisted, nested_inline = remove_functions(block)<EOL>py_code, to_register = translate_flow(block)<EOL>to_register += list(nested_hoisted.keys())<EOL>if to_register:<EOL><INDENT>code += indent('<STR_LIT>' % str(to_register))<EOL><DEDENT>for nested_name, info in nested_hoisted.items():<EOL><INDENT>nested_block, nested_args = info<EOL>new_code = translate_func('<STR_LIT>', nested_block,<EOL>nested_args)<EOL>code += indent(new_code)<EOL>code += indent(<EOL>'<STR_LIT>' % repr(nested_name))<EOL>code += indent(<EOL>'<STR_LIT>' % repr(nested_name))<EOL><DEDENT>for nested_name, info in nested_inline.items():<EOL><INDENT>nested_block, nested_args = info<EOL>new_code = translate_func(nested_name, nested_block, nested_args)<EOL>py_code = inject_before_lval(py_code,<EOL>nested_name.split('<STR_LIT:@>')[<NUM_LIT:0>], new_code)<EOL><DEDENT>if py_code.strip():<EOL><INDENT>code += indent(py_code)<EOL><DEDENT>return code<EOL>

Translates functions and all nested functions to Python code.
       name -  name of that function (global functions will be available under var while
            inline will be available directly under this name )
       block - code of the function (*with* brackets {} )
       args - arguments that this function takes


if n.strip():<EOL><INDENT>return False<EOL><DEDENT>last = last.strip()<EOL>markers = {<EOL>'<STR_LIT:)>',<EOL>'<STR_LIT:;>',<EOL>}<EOL>if not last or last[-<NUM_LIT:1>] in markers:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>


if is_empty_object(n, last):<EOL><INDENT>return True<EOL><DEDENT>if not n.strip():<EOL><INDENT>return False<EOL><DEDENT>if len(argsplit(n, '<STR_LIT:;>')) > <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>cands = argsplit(n, '<STR_LIT:U+002C>')<EOL>if not cands[-<NUM_LIT:1>].strip():<EOL><INDENT>return True  <EOL><DEDENT>for cand in cands:<EOL><INDENT>cand = cand.strip()<EOL>kv = argsplit(cand, '<STR_LIT::>')<EOL>if len(<EOL>kv<EOL>) > <NUM_LIT:2>:  <EOL><INDENT>kv = kv[<NUM_LIT:0>], '<STR_LIT::>'.join(kv[<NUM_LIT:1>:])<EOL><DEDENT>if len(kv) == <NUM_LIT:2>:<EOL><INDENT>k, v = kv<EOL>if not is_lval(k.strip()):<EOL><INDENT>return False<EOL><DEDENT>v = v.strip()<EOL>if v.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>if v[<NUM_LIT:0>] == '<STR_LIT:{>':  <EOL><INDENT>return False<EOL><DEDENT>for e in KEYWORD_METHODS:<EOL><INDENT>if v.startswith(e) and len(e) < len(v) and v[len(<EOL>e)] not in IDENTIFIER_PART:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>elif not (cand.startswith('<STR_LIT>') or cand.startswith('<STR_LIT>')):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

n may be the inside of block or object.
       last is the code before object


replacements = {}  <EOL>br = bracket_split(code, ['<STR_LIT:{}>', '<STR_LIT>'])<EOL>res = '<STR_LIT>'<EOL>last = '<STR_LIT>'<EOL>for e in br:<EOL><INDENT>if e[<NUM_LIT:0>] == '<STR_LIT:{>':<EOL><INDENT>n, temp_rep, cand_count = remove_objects(e[<NUM_LIT:1>:-<NUM_LIT:1>], count)<EOL>if is_object(n, last):<EOL><INDENT>res += '<STR_LIT:U+0020>' + OBJECT_LVAL % count<EOL>replacements[OBJECT_LVAL % count] = e<EOL>count += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>res += '<STR_LIT>' % n<EOL>count = cand_count<EOL>replacements.update(temp_rep)<EOL><DEDENT><DEDENT>elif e[<NUM_LIT:0>] == '<STR_LIT:[>':<EOL><INDENT>if is_array(last):<EOL><INDENT>res += e  <EOL><DEDENT>else:  <EOL><INDENT>n, rep, count = remove_objects(e[<NUM_LIT:1>:-<NUM_LIT:1>], count)<EOL>res += '<STR_LIT>' % n<EOL>replacements.update(rep)<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>res += e<EOL><DEDENT>last = e  <EOL><DEDENT>return res, replacements, count<EOL>

This function replaces objects with OBJECTS_LVALS, returns new code, replacement dict and count.
        count arg is the number that should be added to the LVAL of the first replaced object


res = '<STR_LIT>'<EOL>last = '<STR_LIT>'<EOL>replacements = {}<EOL>for e in bracket_split(code, ['<STR_LIT>']):<EOL><INDENT>if e[<NUM_LIT:0>] == '<STR_LIT:[>':<EOL><INDENT>if is_array(last):<EOL><INDENT>name = ARRAY_LVAL % count<EOL>res += '<STR_LIT:U+0020>' + name<EOL>replacements[name] = e<EOL>count += <NUM_LIT:1><EOL><DEDENT>else:  <EOL><INDENT>cand, new_replacements, count = remove_arrays(e[<NUM_LIT:1>:-<NUM_LIT:1>], count)<EOL>res += '<STR_LIT>' % cand<EOL>replacements.update(new_replacements)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>res += e<EOL><DEDENT>last = e<EOL><DEDENT>return res, replacements, count<EOL>

removes arrays and replaces them with ARRAY_LVALS
       returns new code and replacement dict
       *NOTE* has to be called AFTER remove objects


def translate_array(array, lval, obj_count=<NUM_LIT:1>, arr_count=<NUM_LIT:1>):

array = array[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>array, obj_rep, obj_count = remove_objects(array, obj_count)<EOL>array, arr_rep, arr_count = remove_arrays(array, arr_count)<EOL>array, hoisted, inline = functions.remove_functions(array, all_inline=True)<EOL>assert not hoisted<EOL>arr = []<EOL>for e in argsplit(array, '<STR_LIT:U+002C>'):<EOL><INDENT>e = exp_translator(e.replace('<STR_LIT:\n>', '<STR_LIT>'))<EOL>arr.append(e if e else '<STR_LIT:None>')<EOL><DEDENT>arr = '<STR_LIT>' % (lval, '<STR_LIT:U+002C>'.join(arr))<EOL>for nested_name, nested_info in inline.items():<EOL><INDENT>nested_block, nested_args = nested_info<EOL>new_def = FUNC_TRANSLATOR(nested_name, nested_block, nested_args)<EOL>arr = new_def + arr<EOL><DEDENT>for lval, obj in obj_rep.items():<EOL><INDENT>new_def, obj_count, arr_count = translate_object(<EOL>obj, lval, obj_count, arr_count)<EOL>arr = new_def + arr<EOL><DEDENT>for lval, obj in arr_rep.items():<EOL><INDENT>new_def, obj_count, arr_count = translate_array(<EOL>obj, lval, obj_count, arr_count)<EOL>arr = new_def + arr<EOL><DEDENT>return arr, obj_count, arr_count<EOL>

array has to be any js array for example [1,2,3]
       lval has to be name of this array.
       Returns python code that adds lval to the PY scope it should be put before lval


markers = '<STR_LIT>'<EOL>k = <NUM_LIT:0><EOL>while True:<EOL><INDENT>k += <NUM_LIT:1><EOL>if n - k < <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT>char = source[n - k]<EOL>if char in markers:<EOL><INDENT>return True<EOL><DEDENT>if char != '<STR_LIT:U+0020>' and char != '<STR_LIT:\n>':<EOL><INDENT>break<EOL><DEDENT><DEDENT>return False<EOL>

returns True if regexp starts at n else returns False
      checks whether it is not a division


while start < len(source) and source[start] in charset:<EOL><INDENT>start += <NUM_LIT:1><EOL><DEDENT>return start<EOL>

Returns a first index>=start of chat not in charset


if not source[start] in {'<STR_LIT:e>', '<STR_LIT:E>'}:<EOL><INDENT>if source[start] in IDENTIFIER_PART:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>return start<EOL><DEDENT>start += <NUM_LIT:1><EOL>if source[start] in {'<STR_LIT:->', '<STR_LIT:+>'}:<EOL><INDENT>start += <NUM_LIT:1><EOL><DEDENT>FOUND = False<EOL>while source[start] in NUMS:<EOL><INDENT>FOUND = True<EOL>start += <NUM_LIT:1><EOL><DEDENT>if not FOUND or source[start] in IDENTIFIER_PART:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>return start<EOL>

returns end of exponential, raises SyntaxError if failed


source = '<STR_LIT:U+0020>' + source + '<STR_LIT:\n>'<EOL>comments = []<EOL>inside_comment, single_comment = False, False<EOL>inside_single, inside_double = False, False<EOL>inside_regexp = False<EOL>regexp_class_count = <NUM_LIT:0><EOL>n = <NUM_LIT:0><EOL>while n < len(source):<EOL><INDENT>char = source[n]<EOL>if char == '<STR_LIT:">' and not (inside_comment or inside_single<EOL>or inside_regexp):<EOL><INDENT>if not _is_cancelled(source, n):<EOL><INDENT>if inside_double:<EOL><INDENT>inside_double[<NUM_LIT:1>] = n + <NUM_LIT:1><EOL>comments.append(inside_double)<EOL>inside_double = False<EOL><DEDENT>else:<EOL><INDENT>inside_double = [n, None, <NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT>elif char == "<STR_LIT:'>" and not (inside_comment or inside_double<EOL>or inside_regexp):<EOL><INDENT>if not _is_cancelled(source, n):<EOL><INDENT>if inside_single:<EOL><INDENT>inside_single[<NUM_LIT:1>] = n + <NUM_LIT:1><EOL>comments.append(inside_single)<EOL>inside_single = False<EOL><DEDENT>else:<EOL><INDENT>inside_single = [n, None, <NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT>elif (inside_single or inside_double):<EOL><INDENT>if char in LINE_TERMINATOR:<EOL><INDENT>if _is_cancelled(source, n):<EOL><INDENT>if char == CR and source[n + <NUM_LIT:1>] == LF:<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>else:<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if inside_comment:<EOL><INDENT>if single_comment:<EOL><INDENT>if char in LINE_TERMINATOR:<EOL><INDENT>inside_comment[<NUM_LIT:1>] = n<EOL>comments.append(inside_comment)<EOL>inside_comment = False<EOL>single_comment = False<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>if char == '<STR_LIT:/>' and source[n - <NUM_LIT:1>] == '<STR_LIT:*>':<EOL><INDENT>inside_comment[<NUM_LIT:1>] = n + <NUM_LIT:1><EOL>comments.append(inside_comment)<EOL>inside_comment = False<EOL><DEDENT><DEDENT><DEDENT>elif inside_regexp:<EOL><INDENT>if not quiting_regexp:<EOL><INDENT>if char in LINE_TERMINATOR:<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if _is_cancelled(source, n):<EOL><INDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>if char == '<STR_LIT:[>':<EOL><INDENT>regexp_class_count += <NUM_LIT:1><EOL><DEDENT>elif char == '<STR_LIT:]>':<EOL><INDENT>regexp_class_count = max(regexp_class_count - <NUM_LIT:1>, <NUM_LIT:0>)<EOL><DEDENT>elif char == '<STR_LIT:/>' and not regexp_class_count:<EOL><INDENT>quiting_regexp = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if char not in IDENTIFIER_START:<EOL><INDENT>inside_regexp[<NUM_LIT:1>] = n<EOL>comments.append(inside_regexp)<EOL>inside_regexp = False<EOL><DEDENT><DEDENT><DEDENT>elif char == '<STR_LIT:/>' and source[n - <NUM_LIT:1>] == '<STR_LIT:/>':<EOL><INDENT>single_comment = True<EOL>inside_comment = [n - <NUM_LIT:1>, None, <NUM_LIT:1>]<EOL><DEDENT>elif char == '<STR_LIT:*>' and source[n - <NUM_LIT:1>] == '<STR_LIT:/>':<EOL><INDENT>inside_comment = [n - <NUM_LIT:1>, None, <NUM_LIT:1>]<EOL><DEDENT>elif char == '<STR_LIT:/>' and source[n + <NUM_LIT:1>] not in ('<STR_LIT:/>', '<STR_LIT:*>'):<EOL><INDENT>if not _ensure_regexp(source, n):  <EOL><INDENT>n += <NUM_LIT:1><EOL>continue  <EOL><DEDENT>quiting_regexp = False<EOL>inside_regexp = [n, None, <NUM_LIT:2>]<EOL><DEDENT>elif not (inside_comment or inside_regexp):<EOL><INDENT>if (char in NUMS and<EOL>source[n - <NUM_LIT:1>] not in IDENTIFIER_PART) or char == '<STR_LIT:.>':<EOL><INDENT>if char == '<STR_LIT:.>':<EOL><INDENT>k = parse_num(source, n + <NUM_LIT:1>, NUMS)<EOL>if k == n + <NUM_LIT:1>:  <EOL><INDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>k = parse_exponent(source, k)<EOL><DEDENT>elif char == '<STR_LIT:0>' and source[n + <NUM_LIT:1>] in {<EOL>'<STR_LIT:x>', '<STR_LIT:X>'<EOL>}:  <EOL><INDENT>k = parse_num(source, n + <NUM_LIT:2>, HEX)<EOL>if k == n + <NUM_LIT:2> or source[k] in IDENTIFIER_PART:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>k = parse_num(source, n + <NUM_LIT:1>, NUMS)<EOL>if source[k] == '<STR_LIT:.>':<EOL><INDENT>k = parse_num(source, k + <NUM_LIT:1>, NUMS)<EOL><DEDENT>k = parse_exponent(source, k)<EOL><DEDENT>comments.append((n, k, <NUM_LIT:3>))<EOL>n = k<EOL>continue<EOL><DEDENT><DEDENT><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>res = '<STR_LIT>'<EOL>start = <NUM_LIT:0><EOL>count = <NUM_LIT:0><EOL>constants = {}<EOL>for end, next_start, typ in comments:<EOL><INDENT>res += source[start:end]<EOL>start = next_start<EOL>if typ == <NUM_LIT:0>:  <EOL><INDENT>name = StringName<EOL><DEDENT>elif typ == <NUM_LIT:1>:  <EOL><INDENT>continue<EOL><DEDENT>elif typ == <NUM_LIT:2>:  <EOL><INDENT>name = RegExpName<EOL><DEDENT>elif typ == <NUM_LIT:3>:  <EOL><INDENT>name = NumberName<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError()<EOL><DEDENT>res += '<STR_LIT:U+0020>' + name % count + '<STR_LIT:U+0020>'<EOL>constants[name % count] = source[end:next_start]<EOL>count += <NUM_LIT:1><EOL><DEDENT>res += source[start:]<EOL>for e in WHITE:<EOL><INDENT>res = res.replace(e, '<STR_LIT:U+0020>')<EOL><DEDENT>res = res.replace(CR + LF, '<STR_LIT:\n>')<EOL>for e in LINE_TERMINATOR:<EOL><INDENT>res = res.replace(e, '<STR_LIT:\n>')<EOL><DEDENT>return res.strip(), constants<EOL>

Replaces Strings and Regexp literals in the source code with
       identifiers and *removes comments*. Identifier is of the format:

       PyJsStringConst(String const number)_ - for Strings
       PyJsRegExpConst(RegExp const number)_ - for RegExps

       Returns dict which relates identifier and replaced constant.

       Removes single line and multiline comments from JavaScript source code
       Pseudo comments (inside strings) will not be removed.

       For example this line:
       var x = "/*PSEUDO COMMENT*/ TEXT //ANOTHER PSEUDO COMMENT"
       will be unaltered


for identifier, value in replacements.items():<EOL><INDENT>if identifier.startswith('<STR_LIT>'):<EOL><INDENT>py_source = py_source.replace(identifier,<EOL>'<STR_LIT>' % repr(value))<EOL><DEDENT>elif identifier.startswith('<STR_LIT>'):<EOL><INDENT>py_source = py_source.replace(<EOL>identifier, '<STR_LIT>' % unify_string_literals(value))<EOL><DEDENT>else:<EOL><INDENT>py_source = py_source.replace(identifier, '<STR_LIT>' % value)<EOL><DEDENT><DEDENT>return py_source<EOL>

Converts identifiers representing Js constants to the PyJs constants
    PyJsNumberConst_1_ which has the true value of 5 will be converted to PyJsNumber(5)


n = <NUM_LIT:0><EOL>res = '<STR_LIT>'<EOL>limit = len(js_string)<EOL>while n < limit:<EOL><INDENT>char = js_string[n]<EOL>if char == '<STR_LIT:\\>':<EOL><INDENT>new, n = do_escape(js_string, n)<EOL>res += new<EOL><DEDENT>else:<EOL><INDENT>res += char<EOL>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>return res<EOL>

this function parses the string just like javascript
       for example literal '\d' in JavaScript would be interpreted
       as 'd' - backslash would be ignored and in Pyhon this
       would be interpreted as '\\d' This function fixes this problem.


if not n + <NUM_LIT:1> < len(source):<EOL><INDENT>return '<STR_LIT>'  <EOL><DEDENT>if source[n + <NUM_LIT:1>] in LINE_TERMINATOR:<EOL><INDENT>if source[n + <NUM_LIT:1>] == CR and n + <NUM_LIT:2> < len(source) and source[n + <NUM_LIT:2>] == LF:<EOL><INDENT>return source[n:n + <NUM_LIT:3>], n + <NUM_LIT:3><EOL><DEDENT>return source[n:n + <NUM_LIT:2>], n + <NUM_LIT:2><EOL><DEDENT>if source[n + <NUM_LIT:1>] in ESCAPE_CHARS:<EOL><INDENT>return source[n:n + <NUM_LIT:2>], n + <NUM_LIT:2><EOL><DEDENT>if source[n + <NUM_LIT:1>] in {'<STR_LIT:x>', '<STR_LIT:u>'}:<EOL><INDENT>char, length = ('<STR_LIT:u>', <NUM_LIT:4>) if source[n + <NUM_LIT:1>] == '<STR_LIT:u>' else ('<STR_LIT:x>', <NUM_LIT:2>)<EOL>n += <NUM_LIT:2><EOL>end = parse_num(source, n, HEX)<EOL>if end - n < length:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>return source[n - <NUM_LIT:2>:n + length], n + length<EOL><DEDENT>if source[n + <NUM_LIT:1>] in OCTAL:<EOL><INDENT>n += <NUM_LIT:1><EOL>end = parse_num(source, n, OCTAL)<EOL>end = min(end, n + <NUM_LIT:3>)  <EOL>max_num = <NUM_LIT:255><EOL>num = <NUM_LIT:0><EOL>len_parsed = <NUM_LIT:0><EOL>for e in source[n:end]:<EOL><INDENT>cand = <NUM_LIT:8> * num + int(e)<EOL>if cand > max_num:<EOL><INDENT>break<EOL><DEDENT>num = cand<EOL>len_parsed += <NUM_LIT:1><EOL><DEDENT>return '<STR_LIT:\\>' + hex(num)[<NUM_LIT:1>:], n + len_parsed<EOL><DEDENT>return source[n + <NUM_LIT:1>], n + <NUM_LIT:2><EOL>

Its actually quite complicated to cover every case :)
       http://www.javascriptkit.com/jsref/escapesequence.shtml


it = reversed(lis)<EOL>res = trans(next(it))<EOL>for e in it:<EOL><INDENT>e = trans(e)<EOL>res = op(e, res)<EOL><DEDENT>return res<EOL>

performs this operation on a list from *right to left*
        op must take 2 args
        a,b,c  => op(a, op(b, c))


it = iter(lis)<EOL>res = trans(next(it))<EOL>for e in it:<EOL><INDENT>e = trans(e)<EOL>res = op(res, e)<EOL><DEDENT>return res<EOL>

performs this operation on a list from *left to right*
        op must take 2 args
        a,b,c  => op(op(a, b), c)


if not self.code:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>new = bracket_replace(self.code)<EOL>cand = new.split('<STR_LIT:U+002C>')  <EOL>if len(cand) > <NUM_LIT:1>:  <EOL><INDENT>return self.lr(cand, js_comma)<EOL><DEDENT>if '<STR_LIT:?>' in new:<EOL><INDENT>cond_ind = new.find('<STR_LIT:?>')<EOL>tenary_start = <NUM_LIT:0><EOL>for ass in re.finditer(ASSIGNMENT_MATCH, new):<EOL><INDENT>cand = ass.span()[<NUM_LIT:1>]<EOL>if cand < cond_ind:<EOL><INDENT>tenary_start = cand<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>actual_tenary = new[tenary_start:]<EOL>spl = '<STR_LIT>'.join(split_at_any(new, ['<STR_LIT::>', '<STR_LIT:?>'], translate=trans))<EOL>tenary_translation = transform_crap(spl)<EOL>assignment = new[:tenary_start] + '<STR_LIT>'<EOL>return trans(assignment).replace('<STR_LIT>',<EOL>tenary_translation)<EOL><DEDENT>cand = list(split_at_single(new, '<STR_LIT:=>', ['<STR_LIT:!>', '<STR_LIT:=>', '<STR_LIT:<>', '<STR_LIT:>>'], ['<STR_LIT:=>']))<EOL>if len(cand) > <NUM_LIT:1>:  <EOL><INDENT>it = reversed(cand)<EOL>res = trans(next(it))<EOL>for e in it:<EOL><INDENT>e = e.strip()<EOL>if not e:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>op = '<STR_LIT>'<EOL>if e[-<NUM_LIT:2>:] in OP_METHODS:<EOL><INDENT>op = '<STR_LIT:U+002C>' + e[-<NUM_LIT:2>:].__repr__()<EOL>e = e[:-<NUM_LIT:2>]<EOL><DEDENT>elif e[-<NUM_LIT:1>:] in OP_METHODS:<EOL><INDENT>op = '<STR_LIT:U+002C>' + e[-<NUM_LIT:1>].__repr__()<EOL>e = e[:-<NUM_LIT:1>]<EOL><DEDENT>e = trans(e)<EOL>c = list(bracket_split(e, ['<STR_LIT>']))<EOL>beg, arglist = '<STR_LIT>'.join(c[:-<NUM_LIT:1>]).strip(), c[-<NUM_LIT:1>].strip(<EOL>)  <EOL>if beg[-<NUM_LIT:4>:] != '<STR_LIT>':<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>beg = beg[<NUM_LIT:0>:-<NUM_LIT:3>] + '<STR_LIT>'<EOL>arglist = arglist[<NUM_LIT:0>:-<NUM_LIT:1>] + '<STR_LIT:U+002CU+0020>' + res + op + '<STR_LIT:)>'<EOL>res = beg + arglist<EOL><DEDENT>return res<EOL><DEDENT>order = [OR, AND, BOR, BXOR, BAND, EQS, COMPS, BSHIFTS, ADDS, MULTS]<EOL>dangerous = ['<STR_LIT:<>', '<STR_LIT:>>']<EOL>for typ in order:<EOL><INDENT>if '<STR_LIT:+>' in typ:<EOL><INDENT>cand = list(split_add_ops(new))<EOL><DEDENT>else:<EOL><INDENT>cand = list(<EOL>split_at_any(<EOL>new,<EOL>list(typ.keys()),<EOL>False,<EOL>dangerous,<EOL>dangerous,<EOL>validitate=comb_validitator))<EOL><DEDENT>if not len(cand) > <NUM_LIT:1>:<EOL><INDENT>continue<EOL><DEDENT>n = <NUM_LIT:1><EOL>res = trans(cand[<NUM_LIT:0>])<EOL>if not res:<EOL><INDENT>raise SyntaxError("<STR_LIT>")<EOL><DEDENT>while n < len(cand):<EOL><INDENT>e = cand[n]<EOL>if not e:<EOL><INDENT>raise SyntaxError("<STR_LIT>")<EOL><DEDENT>if n % <NUM_LIT:2>:<EOL><INDENT>op = typ[e]<EOL><DEDENT>else:<EOL><INDENT>res = op(res, trans(e))<EOL><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>return res<EOL><DEDENT>cand = list(<EOL>split_at_any(<EOL>new, list(UNARY.keys()), False, validitate=unary_validitator))<EOL>if len(cand) > <NUM_LIT:1>:  <EOL><INDENT>if '<STR_LIT>' in cand or '<STR_LIT>' in cand:  <EOL><INDENT>if '<STR_LIT>' in cand:<EOL><INDENT>op = '<STR_LIT>'<EOL>meths = js_post_dec, js_pre_dec<EOL><DEDENT>else:<EOL><INDENT>op = '<STR_LIT>'<EOL>meths = js_post_inc, js_pre_inc<EOL><DEDENT>pos = cand.index(op)<EOL>if cand[pos - <NUM_LIT:1>].strip():  <EOL><INDENT>a = cand[pos - <NUM_LIT:1>]<EOL>meth = meths[<NUM_LIT:0>]<EOL><DEDENT>elif cand[pos + <NUM_LIT:1>].strip():  <EOL><INDENT>a = cand[pos + <NUM_LIT:1>]<EOL>meth = meths[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>if cand[pos + <NUM_LIT:2>:]:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>operand = meth(trans(a))<EOL>cand = cand[:pos - <NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>operand = trans(cand[-<NUM_LIT:1>])<EOL>del cand[-<NUM_LIT:1>]<EOL><DEDENT>for i, e in enumerate(reversed(cand)):<EOL><INDENT>if i % <NUM_LIT:2>:<EOL><INDENT>if e.strip():<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>operand = UNARY[e](operand)<EOL><DEDENT><DEDENT>return operand<EOL><DEDENT>if new[<NUM_LIT:0>] == '<STR_LIT:@>' or new[<NUM_LIT:0>] == '<STR_LIT:#>':<EOL><INDENT>if len(<EOL>list(bracket_split(new, ('<STR_LIT>', '<STR_LIT>')))<EOL>) == <NUM_LIT:1>:  <EOL><INDENT>assert new in REPL<EOL>if new[<NUM_LIT:0>] == '<STR_LIT:#>':<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>')<EOL><DEDENT>return '<STR_LIT:(>' + trans(REPL[new][<NUM_LIT:1>:-<NUM_LIT:1>]) + '<STR_LIT:)>'<EOL><DEDENT><DEDENT>it = bracket_split(new, ('<STR_LIT>', '<STR_LIT>'))<EOL>res = []<EOL>for e in it:<EOL><INDENT>if e[<NUM_LIT:0>] != '<STR_LIT:#>' and e[<NUM_LIT:0>] != '<STR_LIT:@>':<EOL><INDENT>res += [x.strip() for x in e.split('<STR_LIT:.>')]<EOL><DEDENT>else:<EOL><INDENT>res += [e.strip()]<EOL><DEDENT><DEDENT>res = [x for x in res if x]<EOL>if is_internal(res[<NUM_LIT:0>]):<EOL><INDENT>out = res[<NUM_LIT:0>]<EOL><DEDENT>elif res[<NUM_LIT:0>][<NUM_LIT:0>] in {'<STR_LIT:#>', '<STR_LIT:@>'}:<EOL><INDENT>out = '<STR_LIT:(>' + trans(REPL[res[<NUM_LIT:0>]][<NUM_LIT:1>:-<NUM_LIT:1>]) + '<STR_LIT:)>'<EOL><DEDENT>elif is_valid_lval(<EOL>res[<NUM_LIT:0>]) or res[<NUM_LIT:0>] in {'<STR_LIT>', '<STR_LIT:false>', '<STR_LIT:true>', '<STR_LIT:null>'}:<EOL><INDENT>out = '<STR_LIT>' + res[<NUM_LIT:0>].__repr__() + '<STR_LIT:)>'<EOL><DEDENT>else:<EOL><INDENT>if is_reserved(res[<NUM_LIT:0>]):<EOL><INDENT>raise SyntaxError('<STR_LIT>' % res[<NUM_LIT:0>])<EOL><DEDENT>raise SyntaxError('<STR_LIT>' % res[<NUM_LIT:0>])<EOL><DEDENT>if len(res) == <NUM_LIT:1>:<EOL><INDENT>return out<EOL><DEDENT>n = <NUM_LIT:1><EOL>while n < len(res):  <EOL><INDENT>e = res[n]<EOL>if e[<NUM_LIT:0>] == '<STR_LIT:@>':  <EOL><INDENT>out += trans_args(REPL[e])<EOL>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>args = False  <EOL>if n + <NUM_LIT:1> < len(res) and res[n + <NUM_LIT:1>][<NUM_LIT:0>] == '<STR_LIT:@>':  <EOL><INDENT>args = trans_args(REPL[res[n + <NUM_LIT:1>]])[<NUM_LIT:1>:]<EOL>if args != '<STR_LIT:)>':<EOL><INDENT>args = '<STR_LIT:U+002C>' + args<EOL><DEDENT><DEDENT>if e[<NUM_LIT:0>] == '<STR_LIT:#>':<EOL><INDENT>prop = trans(REPL[e][<NUM_LIT:1>:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>if not is_lval(e):<EOL><INDENT>raise SyntaxError('<STR_LIT>' % e)<EOL><DEDENT>prop = e.__repr__()<EOL><DEDENT>if args:  <EOL><INDENT>n += <NUM_LIT:1><EOL>out += '<STR_LIT>' + prop + args<EOL><DEDENT>else:  <EOL><INDENT>out += '<STR_LIT>' + prop + '<STR_LIT:)>'<EOL><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>return out<EOL>

Translates outer operation and calls translate on inner operation.
           Returns fully translated code.


global INLINE_COUNT<EOL>inline = {}<EOL>hoisted = {}<EOL>n = <NUM_LIT:0><EOL>limit = len(source) - <NUM_LIT:9>  <EOL>res = '<STR_LIT>'<EOL>last = <NUM_LIT:0><EOL>while n < limit:<EOL><INDENT>if n and source[n - <NUM_LIT:1>] in IDENTIFIER_PART:<EOL><INDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>if source[n:n + <NUM_LIT:8>] == '<STR_LIT>' and source[n +<EOL><NUM_LIT:8>] not in IDENTIFIER_PART:<EOL><INDENT>if source[:n].rstrip().endswith(<EOL>'<STR_LIT:.>'):  <EOL><INDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>if source[n + <NUM_LIT:8>:].lstrip().startswith(<EOL>'<STR_LIT::>'):  <EOL><INDENT>n += <NUM_LIT:1><EOL>continue<EOL><DEDENT>entered = n<EOL>res += source[last:n]<EOL>name = '<STR_LIT>'<EOL>n = pass_white(source, n + <NUM_LIT:8>)<EOL>if source[n] in IDENTIFIER_START:  <EOL><INDENT>name, n = parse_identifier(source, n)<EOL><DEDENT>args, n = pass_bracket(source, n, '<STR_LIT>')<EOL>if not args:<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>args = args.strip('<STR_LIT>')<EOL>args = tuple(parse_identifier(e, <NUM_LIT:0>)[<NUM_LIT:0>]<EOL>for e in argsplit(args)) if args else ()<EOL>if len(args) - len(set(args)):<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>block, n = pass_bracket(source, n, '<STR_LIT:{}>')<EOL>if not block:<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>')<EOL><DEDENT>mixed = False  <EOL>if name and not all_inline:<EOL><INDENT>before = source[:entered].rstrip()<EOL>if any(endswith_keyword(before, e) for e in PRE_EXP_STARTS):<EOL><INDENT>mixed = True<EOL><DEDENT>elif before and before[-<NUM_LIT:1>] not in PRE_ALLOWED and not before[<EOL>-<NUM_LIT:2>:] in INCREMENTS:<EOL><INDENT>mixed = True<EOL><DEDENT>else:<EOL><INDENT>hoisted[name] = block, args<EOL><DEDENT><DEDENT>if not name or mixed or all_inline:  <EOL><INDENT>INLINE_COUNT += <NUM_LIT:1><EOL>iname = INLINE_NAME % INLINE_COUNT  <EOL>res += '<STR_LIT:U+0020>' + iname<EOL>inline['<STR_LIT>' % (<EOL>iname, name<EOL>)] = block, args  <EOL><DEDENT>last = n<EOL><DEDENT>else:<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>res += source[last:]<EOL>return res, hoisted, inline<EOL>

removes functions and returns new source, and 2 dicts.
        first dict with removed hoisted(global) functions and second with replaced inline functions


if not t:<EOL><INDENT>return False<EOL><DEDENT>i = iter(t)<EOL>if i.next() not in IDENTIFIER_START:<EOL><INDENT>return False<EOL><DEDENT>return all(e in IDENTIFIER_PART for e in i)<EOL>

Does not chceck whether t is not resticted or internal


if not is_internal(t) and is_lval(t) and t not in RESERVED_NAMES:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Checks whether t is valid JS identifier name (no keyword like var, function, if etc)
    Also returns false on internal


with codecs.open(path_as_local(path), "<STR_LIT:r>", "<STR_LIT:utf-8>") as f:<EOL><INDENT>js = f.read()<EOL><DEDENT>e = EvalJs()<EOL>e.execute(js)<EOL>var = e.context['<STR_LIT>']<EOL>globals[lib_name] = var.to_python()<EOL>

Imports from javascript source file.
      globals is your globals()


js = get_file_contents(input_path)<EOL>py_code = translate_js(js)<EOL>lib_name = os.path.basename(output_path).split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>head = '<STR_LIT>' % repr(<EOL>lib_name)<EOL>tail = '<STR_LIT>' % lib_name<EOL>out = head + py_code + tail<EOL>write_file_contents(output_path, out)<EOL>

Translates input JS file to python and saves the it to the output path.
It appends some convenience code at the end so that it is easy to import JS objects.

For example we have a file 'example.js' with:   var a = function(x) {return x}
translate_file('example.js', 'example.py')

Now example.py can be easily importend and used:
>>> from example import example
>>> example.a(30)
30


if context is None:<EOL><INDENT>context = EvalJs()<EOL><DEDENT>if not isinstance(context, EvalJs):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>eval_value = context.eval(get_file_contents(path_or_file))<EOL>return eval_value, context<EOL>

Context must be EvalJS object. Runs given path as a JS program. Returns (eval_value, context).


e = EvalJs()<EOL>return e.eval(js)<EOL>

Just like javascript eval. Translates javascript to python,
       executes and returns python object.
       js is javascript source code

       EXAMPLE:
        >>> import js2py
        >>> add = js2py.eval_js('function add(a, b) {return a + b}')
        >>> add(1, 2) + 3
        6
        >>> add('1', 2, 3)
        u'12'
        >>> add.constructor
        function Function() { [python code] }

       NOTE: For Js Number, String, Boolean and other base types returns appropriate python BUILTIN type.
       For Js functions and objects, returns Python wrapper - basically behaves like normal python object.
       If you really want to convert object to python dict you can use to_dict method.


return eval_js(js6_to_js5(js))<EOL>

Just like eval_js but with experimental support for js6 via babel.


return translate_js(js6_to_js5(js))<EOL>

Just like translate_js but with experimental support for js6 via babel.


def execute(self, js=None, use_compilation_plan=False):

try:<EOL><INDENT>cache = self.__dict__['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>cache = self.__dict__['<STR_LIT>'] = {}<EOL><DEDENT>hashkey = hashlib.md5(js.encode('<STR_LIT:utf-8>')).digest()<EOL>try:<EOL><INDENT>compiled = cache[hashkey]<EOL><DEDENT>except KeyError:<EOL><INDENT>code = translate_js(<EOL>js, '<STR_LIT>', use_compilation_plan=use_compilation_plan)<EOL>compiled = cache[hashkey] = compile(code, '<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT>exec (compiled, self._context)<EOL>

executes javascript js in current context

        During initial execute() the converted js is cached for re-use. That means next time you
        run the same javascript snippet you save many instructions needed to parse and convert the
        js code to python code.

        This cache causes minor overhead (a cache dicts is updated) but the Js=>Py conversion process
        is typically expensive compared to actually running the generated python code.

        Note that the cache is just a dict, it has no expiration or cleanup so when running this
        in automated situations with vast amounts of snippets it might increase memory usage.


def eval(self, expression, use_compilation_plan=False):

code = '<STR_LIT>' % json.dumps(expression)<EOL>self.execute(code, use_compilation_plan=use_compilation_plan)<EOL>return self['<STR_LIT>']<EOL>

evaluates expression in current context and returns its value


code = translate_js(js, '<STR_LIT>')<EOL>filename = '<STR_LIT>' + os.sep + '<STR_LIT:_>' + hashlib.md5(<EOL>code.encode("<STR_LIT:utf-8>")).hexdigest() + '<STR_LIT>'<EOL>try:<EOL><INDENT>with open(filename, mode='<STR_LIT:w>') as f:<EOL><INDENT>f.write(code)<EOL><DEDENT>with open(filename, "<STR_LIT:r>") as f:<EOL><INDENT>pyCode = compile(f.read(), filename, '<STR_LIT>')<EOL>exec(pyCode, self._context)<EOL><DEDENT><DEDENT>except Exception as err:<EOL><INDENT>raise err<EOL><DEDENT>finally:<EOL><INDENT>os.remove(filename)<EOL>try:<EOL><INDENT>os.remove(filename + '<STR_LIT:c>')<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

executes javascript js in current context
        as opposed to the (faster) self.execute method, you can use your regular debugger
        to set breakpoints and inspect the generated python code


code = '<STR_LIT>' % json.dumps(expression)<EOL>self.execute_debug(code)<EOL>return self['<STR_LIT>']<EOL>

evaluates expression in current context and returns its value
        as opposed to the (faster) self.execute method, you can use your regular debugger
        to set breakpoints and inspect the generated python code


while True:<EOL><INDENT>if six.PY2:<EOL><INDENT>code = raw_input('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>code = input('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>print(self.eval(code))<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>break<EOL><DEDENT>except Exception as e:<EOL><INDENT>import traceback<EOL>if DEBUG:<EOL><INDENT>sys.stderr.write(traceback.format_exc())<EOL><DEDENT>else:<EOL><INDENT>sys.stderr.write('<STR_LIT>' + str(e) + '<STR_LIT:\n>')<EOL><DEDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>

starts to interact (starts interactive console) Something like code.InteractiveConsole


px = to_primitive(self, '<STR_LIT>')<EOL>py = to_primitive(other, '<STR_LIT>')<EOL>if not self_first:  <EOL><INDENT>px, py = py, px<EOL><DEDENT>if not (Type(px) == '<STR_LIT>' and Type(py) == '<STR_LIT>'):<EOL><INDENT>px, py = to_number(px), to_number(py)<EOL>if is_nan(px) or is_nan(py):<EOL><INDENT>return None  <EOL><DEDENT>return px < py  <EOL><DEDENT>else:<EOL><INDENT>return px < py<EOL><DEDENT>

self<other if self_first else other<self.
       Returns the result of the question: is self smaller than other?
       in case self_first is false it returns the answer of:
                                           is other smaller than self.
       result is PyJs type: bool or undefined


tx, ty = Type(self), Type(other)<EOL>if tx == ty:<EOL><INDENT>if tx == '<STR_LIT>' or tx == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>if tx == '<STR_LIT>' or tx == '<STR_LIT>' or tx == '<STR_LIT>':<EOL><INDENT>return self == other<EOL><DEDENT>return self is other  <EOL><DEDENT>elif (tx == '<STR_LIT>' and ty == '<STR_LIT>') or (ty == '<STR_LIT>'<EOL>and tx == '<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>elif tx == '<STR_LIT>' and ty == '<STR_LIT>':<EOL><INDENT>return abstract_equality_op(self, to_number(other))<EOL><DEDENT>elif tx == '<STR_LIT>' and ty == '<STR_LIT>':<EOL><INDENT>return abstract_equality_op(to_number(self), other)<EOL><DEDENT>elif tx == '<STR_LIT>':<EOL><INDENT>return abstract_equality_op(to_number(self), other)<EOL><DEDENT>elif ty == '<STR_LIT>':<EOL><INDENT>return abstract_equality_op(self, to_number(other))<EOL><DEDENT>elif (tx == '<STR_LIT>' or tx == '<STR_LIT>') and is_object(other):<EOL><INDENT>return abstract_equality_op(self, to_primitive(other))<EOL><DEDENT>elif (ty == '<STR_LIT>' or ty == '<STR_LIT>') and is_object(self):<EOL><INDENT>return abstract_equality_op(to_primitive(self), other)<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

returns the result of JS == compare.
       result is PyJs type: bool


if not hasattr(other, '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>return other.has_instance(self)<EOL>


if not is_object(other):<EOL><INDENT>raise MakeError(<EOL>'<STR_LIT>',<EOL>"<STR_LIT>")<EOL><DEDENT>return other.has_property(to_string(self))<EOL>


arr = self.NewArray(len(py_arr))<EOL>arr._init(py_arr)<EOL>return arr<EOL>

note py_arr elems are NOT converted to PyJs types!


obj = self.NewObject()<EOL>for k, v in py_obj.items():<EOL><INDENT>obj.put(unicode(k), v)<EOL><DEDENT>return obj<EOL>

note py_obj items are NOT converted to PyJs types!


def replacement_template(rep, source, span, npar):

n = <NUM_LIT:0><EOL>res = '<STR_LIT>'<EOL>while n < len(rep) - <NUM_LIT:1>:<EOL><INDENT>char = rep[n]<EOL>if char == '<STR_LIT:$>':<EOL><INDENT>if rep[n + <NUM_LIT:1>] == '<STR_LIT:$>':<EOL><INDENT>res += '<STR_LIT:$>'<EOL>n += <NUM_LIT:2><EOL>continue<EOL><DEDENT>elif rep[n + <NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>res += source[:span[<NUM_LIT:0>]]<EOL>n += <NUM_LIT:2><EOL>continue<EOL><DEDENT>elif rep[n + <NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>res += source[span[<NUM_LIT:1>]:]<EOL>n += <NUM_LIT:2><EOL>continue<EOL><DEDENT>elif rep[n + <NUM_LIT:1>] in DIGS:<EOL><INDENT>dig = rep[n + <NUM_LIT:1>]<EOL>if n + <NUM_LIT:2> < len(rep) and rep[n + <NUM_LIT:2>] in DIGS:<EOL><INDENT>dig += rep[n + <NUM_LIT:2>]<EOL><DEDENT>num = int(dig)<EOL>if not num or num > len(npar):<EOL><INDENT>res += '<STR_LIT:$>' + dig<EOL><DEDENT>else:<EOL><INDENT>res += npar[num - <NUM_LIT:1>] if npar[num - <NUM_LIT:1>] else '<STR_LIT>'<EOL><DEDENT>n += <NUM_LIT:1> + len(dig)<EOL>continue<EOL><DEDENT><DEDENT>res += char<EOL>n += <NUM_LIT:1><EOL><DEDENT>if n < len(rep):<EOL><INDENT>res += rep[-<NUM_LIT:1>]<EOL><DEDENT>return res<EOL>

Takes the replacement template and some info about the match and returns filled template


raise MakeError('<STR_LIT>', '<STR_LIT>' % self.Class)<EOL>

Generally not a constructor, raise an error


return self.pat.match(string, int(pos))<EOL>


def __init__(self, scope, space, parent=None):

self.space = space<EOL>self.prototype = parent<EOL>if type(scope) is not dict:<EOL><INDENT>assert parent is not None, '<STR_LIT>'<EOL>self.own = scope<EOL>self.is_with_scope = True<EOL><DEDENT>else:<EOL><INDENT>self.is_with_scope = False<EOL><DEDENT>if parent is None:<EOL><INDENT>self.own = {}<EOL>for k, v in six.iteritems(scope):<EOL><INDENT>self.define_own_property(<EOL>k, {<EOL>'<STR_LIT:value>': v,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False<EOL>}, False)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.own = scope  <EOL><DEDENT>self.par = super(Scope, self)<EOL>self.stack = []<EOL>


for var in vars:<EOL><INDENT>self.register(var)<EOL><DEDENT>


if self.is_native:<EOL><INDENT>_args = SpaceTuple(<EOL>args<EOL>)  <EOL>_args.space = self.space<EOL>return self.code(<EOL>this, _args<EOL>)  <EOL><DEDENT>else:<EOL><INDENT>return self.space.exe._call(self, this,<EOL>args)<EOL><DEDENT>

Dont use this method from inside bytecode to call other bytecode.


if type(self) in (UNDEFINED_TYPE, NULL_TYPE):<EOL><INDENT>raise MakeError('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT>


def pad(num, n=<NUM_LIT:2>, sign=False):

s = unicode(abs(num))<EOL>if len(s) < n:<EOL><INDENT>s = '<STR_LIT:0>' * (n - len(s)) + s<EOL><DEDENT>if not sign:<EOL><INDENT>return s<EOL><DEDENT>if num >= <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT:+>' + s<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT:->' + s<EOL><DEDENT>

returns n digit string representation of the num


if isinstance(what, basestring):<EOL><INDENT>return self.exe.emit(what, *args)<EOL><DEDENT>elif isinstance(what, list):<EOL><INDENT>self._emit_statement_list(what)<EOL><DEDENT>else:<EOL><INDENT>return getattr(self, what['<STR_LIT:type>'])(**what)<EOL><DEDENT>

what can be either name of the op, or node, or a list of statements.


self.tape.append(OP_CODES[op_code](*args))<EOL>

Adds op_code with specified args to tape


self.label_locs = {} if self.label_locs is None else self.label_locs<EOL>loc = start_loc<EOL>while loc < len(self.tape):<EOL><INDENT>if type(self.tape[loc]) == LABEL:<EOL><INDENT>self.label_locs[self.tape[loc].num] = loc<EOL>del self.tape[loc]<EOL>continue<EOL><DEDENT>loc += <NUM_LIT:1><EOL><DEDENT>self.compiled = True<EOL>

Records locations of labels and compiles the code


assert not func.is_native<EOL>old_contexts = self.contexts<EOL>old_return_locs = self.return_locs<EOL>old_curr_ctx = self.current_ctx<EOL>self.contexts = [FakeCtx()]<EOL>self.return_locs = [len(self.tape)]  <EOL>my_ctx = func._generate_my_context(this, args)<EOL>self.current_ctx = my_ctx<EOL>ret = self.run(my_ctx, starting_loc=self.label_locs[func.code])<EOL>self.current_ctx = old_curr_ctx<EOL>self.contexts = old_contexts<EOL>self.return_locs = old_return_locs<EOL>return ret<EOL>

Calls a bytecode function func
            NOTE:  use !ONLY! when calling functions from native methods!


def execute_fragment_under_context(self, ctx, start_label, end_label):

old_curr_ctx = self.current_ctx<EOL>self.ctx_depth += <NUM_LIT:1><EOL>old_stack_len = len(ctx.stack)<EOL>old_ret_len = len(self.return_locs)<EOL>old_ctx_len = len(self.contexts)<EOL>try:<EOL><INDENT>self.current_ctx = ctx<EOL>return self._execute_fragment_under_context(<EOL>ctx, start_label, end_label)<EOL><DEDENT>except JsException as err:<EOL><INDENT>if self.debug_mode:<EOL><INDENT>self._on_fragment_exit("<STR_LIT>")<EOL><DEDENT>del ctx.stack[old_stack_len:]<EOL>del self.return_locs[old_ret_len:]<EOL>del self.contexts[old_ctx_len :]<EOL>return undefined, <NUM_LIT:3>, err<EOL><DEDENT>finally:<EOL><INDENT>self.ctx_depth -= <NUM_LIT:1><EOL>self.current_ctx = old_curr_ctx<EOL>assert old_stack_len == len(ctx.stack)<EOL><DEDENT>

just like run but returns if moved outside of the specified fragment
            # 4 different exectution results
            # 0=normal, 1=return, 2=jump_outside, 3=errors
            # execute_fragment_under_context returns:
            # (return_value, typ, return_value/jump_loc/py_error)
            # IMPARTANT: It is guaranteed that the length of the ctx.stack is unchanged.


if literal_or_identifier['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return literal_or_identifier['<STR_LIT:name>']<EOL><DEDENT>elif literal_or_identifier['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>k = literal_or_identifier['<STR_LIT:value>']<EOL>if isinstance(k, float):<EOL><INDENT>return unicode(float_repr(k))<EOL><DEDENT>elif '<STR_LIT>' in literal_or_identifier:<EOL><INDENT>return compose_regex(k)<EOL><DEDENT>elif isinstance(k, bool):<EOL><INDENT>return u'<STR_LIT:true>' if k else u'<STR_LIT:false>'<EOL><DEDENT>elif k is None:<EOL><INDENT>return u'<STR_LIT:null>'<EOL><DEDENT>else:<EOL><INDENT>return unicode(k)<EOL><DEDENT><DEDENT>

returns string representation of this object


return [this.get(str(e)) for e in xrange(len(this))]<EOL>


return JsToPyException(ERRORS[name](Js(message)))<EOL>

Returns PyJsException with PyJsError inside


if isinstance(val, PyJs):<EOL><INDENT>return val<EOL><DEDENT>elif val is None:<EOL><INDENT>return undefined<EOL><DEDENT>elif isinstance(val, basestring):<EOL><INDENT>return PyJsString(val, StringPrototype)<EOL><DEDENT>elif isinstance(val, bool):<EOL><INDENT>return true if val else false<EOL><DEDENT>elif isinstance(val, float) or isinstance(val, int) or isinstance(<EOL>val, long) or (NUMPY_AVAILABLE and isinstance(<EOL>val,<EOL>(numpy.int8, numpy.uint8, numpy.int16, numpy.uint16,<EOL>numpy.int32, numpy.uint32, numpy.float32, numpy.float64))):<EOL><INDENT>if val in NUM_BANK:<EOL><INDENT>return NUM_BANK[val]<EOL><DEDENT>return PyJsNumber(float(val), NumberPrototype)<EOL><DEDENT>elif isinstance(val, FunctionType):<EOL><INDENT>return PyJsFunction(val, FunctionPrototype)<EOL><DEDENT>elif isinstance(val, dict):  <EOL><INDENT>temp = PyJsObject({}, ObjectPrototype)<EOL>for k, v in six.iteritems(val):<EOL><INDENT>temp.put(Js(k), Js(v))<EOL><DEDENT>return temp<EOL><DEDENT>elif isinstance(val, (list, tuple)):  <EOL><INDENT>return PyJsArray(val, ArrayPrototype)<EOL><DEDENT>elif isinstance(val, JsObjectWrapper):<EOL><INDENT>return val.__dict__['<STR_LIT>']<EOL><DEDENT>elif NUMPY_AVAILABLE and isinstance(val, numpy.ndarray):<EOL><INDENT>if val.dtype == numpy.int8:<EOL><INDENT>return PyJsInt8Array(val, Int8ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.uint8 and not Clamped:<EOL><INDENT>return PyJsUint8Array(val, Uint8ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.uint8 and Clamped:<EOL><INDENT>return PyJsUint8ClampedArray(val, Uint8ClampedArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.int16:<EOL><INDENT>return PyJsInt16Array(val, Int16ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.uint16:<EOL><INDENT>return PyJsUint16Array(val, Uint16ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.int32:<EOL><INDENT>return PyJsInt32Array(val, Int32ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.uint32:<EOL><INDENT>return PyJsUint16Array(val, Uint32ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.float32:<EOL><INDENT>return PyJsFloat32Array(val, Float32ArrayPrototype)<EOL><DEDENT>elif val.dtype == numpy.float64:<EOL><INDENT>return PyJsFloat64Array(val, Float64ArrayPrototype)<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>return py_wrap(val)<EOL><DEDENT>


tx, ty = Type(a), Type(b)<EOL>if tx != ty:<EOL><INDENT>return false<EOL><DEDENT>if tx == '<STR_LIT>' or tx == '<STR_LIT>':<EOL><INDENT>return true<EOL><DEDENT>if a.is_primitive():  <EOL><INDENT>return Js(a.value == b.value)<EOL><DEDENT>if a.Class == b.Class == '<STR_LIT>':<EOL><INDENT>return Js(a.obj == b.obj)<EOL><DEDENT>return Js(a is b)<EOL>


return PyJsStrictEq(a, b).neg()<EOL>


return a.pyjs_bshift(b)<EOL>


def __init__(self, value=None, prototype=None, extensible=False):

<EOL>self.value = value<EOL>self.extensible = extensible<EOL>self.prototype = prototype<EOL>self.own = {}<EOL>self.buff = None<EOL>

Constructor for Number String and Boolean


if self.Class == '<STR_LIT>' or self.Class == '<STR_LIT>':<EOL><INDENT>raise MakeError('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT>if not isinstance(prop, basestring):<EOL><INDENT>prop = prop.to_string().value<EOL><DEDENT>if NUMPY_AVAILABLE and prop.isdigit():<EOL><INDENT>if self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.int8(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.uint8(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>if val < Js(numpy.uint8(<NUM_LIT:0>)):<EOL><INDENT>val = Js(numpy.uint8(<NUM_LIT:0>))<EOL><DEDENT>elif val > Js(numpy.uint8(<NUM_LIT:255>)):<EOL><INDENT>val = Js(numpy.uint8(<NUM_LIT:255>))<EOL><DEDENT>else:<EOL><INDENT>val = Js(numpy.uint8(val.to_number().value))<EOL><DEDENT><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.int16(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.uint16(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.int32(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.uint32(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.float32(val.to_number().value))<EOL><DEDENT>elif self.Class == '<STR_LIT>':<EOL><INDENT>val = Js(numpy.float64(val.to_number().value))<EOL><DEDENT>if isinstance(self.buff, numpy.ndarray):<EOL><INDENT>self.buff[int(prop)] = int(val.to_number().value)<EOL><DEDENT><DEDENT>if op is not None:<EOL><INDENT>val = getattr(self.get(prop), OP_METHODS[op])(val)<EOL><DEDENT>if not self.can_put(prop):<EOL><INDENT>return val<EOL><DEDENT>own_desc = self.get_own_property(prop)<EOL>if is_data_descriptor(own_desc):<EOL><INDENT>if self.Class in [<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>]:<EOL><INDENT>self.define_own_property(prop, {'<STR_LIT:value>': val})<EOL><DEDENT>else:<EOL><INDENT>self.own[prop]['<STR_LIT:value>'] = val<EOL><DEDENT>return val<EOL><DEDENT>desc = self.get_property(prop)<EOL>if is_accessor_descriptor(desc):<EOL><INDENT>desc['<STR_LIT>'].call(self, (val, ))<EOL><DEDENT>else:<EOL><INDENT>new = {<EOL>'<STR_LIT:value>': val,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': True<EOL>}<EOL>if self.Class in [<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>]:<EOL><INDENT>self.define_own_property(prop, new)<EOL><DEDENT>else:<EOL><INDENT>self.own[prop] = new<EOL><DEDENT><DEDENT>return val<EOL>

Just like in js: self.prop op= val
           for example when op is '+' it will be self.prop+=val
           op can be either None for simple assignment or one of:
           * / % + - << >> & ^ |


if self.Class in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise MakeError('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT>


def abstract_relational_comparison(self, other, self_first=True):

px = self.to_primitive('<STR_LIT>')<EOL>py = other.to_primitive('<STR_LIT>')<EOL>if not self_first:  <EOL><INDENT>px, py = py, px<EOL><DEDENT>if not (px.Class == '<STR_LIT>' and py.Class == '<STR_LIT>'):<EOL><INDENT>px, py = px.to_number(), py.to_number()<EOL>if px.is_nan() or py.is_nan():<EOL><INDENT>return undefined<EOL><DEDENT>return Js(px.value < py.value)  <EOL><DEDENT>else:<EOL><INDENT>return Js(px.value < py.value)<EOL><DEDENT>

self<other if self_first else other<self.
           Returns the result of the question: is self smaller than other?
           in case self_first is false it returns the answer of:
                                               is other smaller than self.
           result is PyJs type: bool or undefined


tx, ty = self.TYPE, other.TYPE<EOL>if tx == ty:<EOL><INDENT>if tx == '<STR_LIT>' or tx == '<STR_LIT>':<EOL><INDENT>return true<EOL><DEDENT>if tx == '<STR_LIT>' or tx == '<STR_LIT>' or tx == '<STR_LIT>':<EOL><INDENT>return Js(self.value == other.value)<EOL><DEDENT>return Js(self is other)  <EOL><DEDENT>elif (tx == '<STR_LIT>' and ty == '<STR_LIT>') or (ty == '<STR_LIT>'<EOL>and tx == '<STR_LIT>'):<EOL><INDENT>return true<EOL><DEDENT>elif tx == '<STR_LIT>' and ty == '<STR_LIT>':<EOL><INDENT>return self.abstract_equality_comparison(other.to_number())<EOL><DEDENT>elif tx == '<STR_LIT>' and ty == '<STR_LIT>':<EOL><INDENT>return self.to_number().abstract_equality_comparison(other)<EOL><DEDENT>elif tx == '<STR_LIT>':<EOL><INDENT>return self.to_number().abstract_equality_comparison(other)<EOL><DEDENT>elif ty == '<STR_LIT>':<EOL><INDENT>return self.abstract_equality_comparison(other.to_number())<EOL><DEDENT>elif (tx == '<STR_LIT>' or tx == '<STR_LIT>') and other.is_object():<EOL><INDENT>return self.abstract_equality_comparison(other.to_primitive())<EOL><DEDENT>elif (ty == '<STR_LIT>' or ty == '<STR_LIT>') and self.is_object():<EOL><INDENT>return self.to_primitive().abstract_equality_comparison(other)<EOL><DEDENT>else:<EOL><INDENT>return false<EOL><DEDENT>

returns the result of JS == compare.
           result is PyJs type: bool


if not hasattr(other, '<STR_LIT>'):<EOL><INDENT>return false<EOL><DEDENT>return other.has_instance(self)<EOL>


if not self.is_callable():<EOL><INDENT>raise MakeError('<STR_LIT>',<EOL>'<STR_LIT>' % self.typeof())<EOL><DEDENT>return self.call(self.GlobalObject, args)<EOL>

Call a property prop as a function (this will be global object).

        NOTE: dont pass this and arguments here, these will be added
        automatically!


raise MakeError('<STR_LIT>', '<STR_LIT>' % self.Class)<EOL>


if not isinstance(prop, basestring):<EOL><INDENT>prop = prop.to_string().value<EOL><DEDENT>cand = self.get(prop)<EOL>if not cand.is_callable():<EOL><INDENT>raise MakeError('<STR_LIT>',<EOL>'<STR_LIT>' % cand.typeof())<EOL><DEDENT>return cand.call(self, args)<EOL>

Call a property prop as a method (this will be self).

        NOTE: dont pass this and arguments here, these will be added
        automatically!


return to_python(self)<EOL>

returns equivalent python object.
         for example if this object is javascript array then this method will return equivalent python array


return self.to_python()<EOL>


def __init__(self, scope, closure=None):

self.prototype = closure<EOL>if closure is None:<EOL><INDENT>self.own = {}<EOL>for k, v in six.iteritems(scope):<EOL><INDENT>self.define_own_property(<EOL>k, {<EOL>'<STR_LIT:value>': v,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False<EOL>})<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.own = scope<EOL><DEDENT>


for lval in lvals:<EOL><INDENT>self.register(lval)<EOL><DEDENT>


if self.own.get('<STR_LIT:name>'):<EOL><INDENT>self.func_name = name<EOL>self.own['<STR_LIT:name>']['<STR_LIT:value>'] = Js(name)<EOL><DEDENT>


if not hasattr(args, '<STR_LIT>'):  <EOL><INDENT>args = (args, )<EOL><DEDENT>args = tuple(Js(e) for e in args)  <EOL>arguments = PyJsArguments(<EOL>args, self)  <EOL>arglen = self.argcount  <EOL>if len(args) > arglen:<EOL><INDENT>args = args[<NUM_LIT:0>:arglen]<EOL><DEDENT>elif len(args) < arglen:<EOL><INDENT>args += (undefined, ) * (arglen - len(args))<EOL><DEDENT>args += this, arguments  <EOL>try:<EOL><INDENT>return Js(self.code(*args))<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>raise<EOL><DEDENT>except RuntimeError as e:  <EOL><INDENT>raise MakeError(<EOL>'<STR_LIT>', e.message if<EOL>not isinstance(e, NotImplementedError) else '<STR_LIT>')<EOL><DEDENT>

Calls this function and returns a result
        (converted to PyJs type so func can return python types)

        this must be a PyJs object and args must be a python tuple of PyJs objects.

        arguments object is passed automatically and will be equal to Js(args)
        (tuple converted to arguments object).You dont need to worry about number
        of arguments you provide if you supply less then missing ones will be set
        to undefined (but not present in arguments object).
        And if you supply too much then excess will not be passed
        (but they will be present in arguments object).


def __init__(self, value=None, prototype=None):

if not isinstance(value, basestring):<EOL><INDENT>raise TypeError  <EOL><DEDENT>self.value = value<EOL>self.prototype = prototype<EOL>self.own = {}<EOL>self.own['<STR_LIT>'] = {<EOL>'<STR_LIT:value>': Js(len(value)),<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False<EOL>}<EOL>if len(value) == <NUM_LIT:1>:<EOL><INDENT>CHAR_BANK[value] = self<EOL><DEDENT>


return self.pat.match(string, pos)<EOL>


fcode = six.get_function_code(func)<EOL>fargs = fcode.co_varnames[fcode.co_argcount - <NUM_LIT:2>:fcode.co_argcount]<EOL>if fargs == ('<STR_LIT>', '<STR_LIT>') or fargs == ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return func<EOL><DEDENT>code = append_arguments(six.get_function_code(func), ('<STR_LIT>', '<STR_LIT>'))<EOL>return types.FunctionType(<EOL>code,<EOL>six.get_function_globals(func),<EOL>func.__name__,<EOL>closure=six.get_function_closure(func))<EOL>

Use this function when unsure whether func takes this and arguments as its last 2 args.
       It will append 2 args if it does not.


return '<STR_LIT>'<EOL>


def translate_js(js, HEADER=DEFAULT_HEADER, use_compilation_plan=False):

if use_compilation_plan and not '<STR_LIT>' in js and not '<STR_LIT>' in js:<EOL><INDENT>return translate_js_with_compilation_plan(js, HEADER=HEADER)<EOL><DEDENT>parser = pyjsparser.PyJsParser()<EOL>parsed = parser.parse(js)  <EOL>translating_nodes.clean_stacks()<EOL>return HEADER + translating_nodes.trans(<EOL>parsed)<EOL>

js has to be a javascript source code.
       returns equivalent python code.


match_increaser_str, match_increaser_num, compilation_plan = get_compilation_plan(<EOL>js)<EOL>cp_hash = hashlib.md5(compilation_plan.encode('<STR_LIT:utf-8>')).digest()<EOL>try:<EOL><INDENT>python_code = cache[cp_hash]['<STR_LIT>']<EOL><DEDENT>except:<EOL><INDENT>parser = pyjsparser.PyJsParser()<EOL>parsed = parser.parse(compilation_plan)  <EOL>translating_nodes.clean_stacks()<EOL>python_code = translating_nodes.trans(<EOL>parsed)  <EOL>cache[cp_hash] = {<EOL>'<STR_LIT>': compilation_plan,<EOL>'<STR_LIT>': python_code,<EOL>}<EOL><DEDENT>python_code = match_increaser_str.wrap_up(python_code)<EOL>python_code = match_increaser_num.wrap_up(python_code)<EOL>return HEADER + python_code<EOL>

js has to be a javascript source code.
       returns equivalent python code.

       compile plans only work with the following restrictions:
       - only enabled for oneliner expressions
       - when there are comments in the js code string substitution is disabled
       - when there nested escaped quotes string substitution is disabled, so

       cacheable:
       Q1 == 1 && name == 'harry'

       not cacheable:
       Q1 == 1 && name == 'harry' // some comment

       not cacheable:
       Q1 == 1 && name == 'o\'Reilly'

       not cacheable:
       Q1 == 1 && name /* some comment */ == 'o\'Reilly'


return translate_js(js, HEADER)<EOL>

js has to be a javascript source code.
       returns equivalent python code.

       Equivalent to translate_js


if literal_or_identifier['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return literal_or_identifier['<STR_LIT:name>']<EOL><DEDENT>elif literal_or_identifier['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>k = literal_or_identifier['<STR_LIT:value>']<EOL>if isinstance(k, float):<EOL><INDENT>return unicode(float_repr(k))<EOL><DEDENT>elif '<STR_LIT>' in literal_or_identifier:<EOL><INDENT>return compose_regex(k)<EOL><DEDENT>elif isinstance(k, bool):<EOL><INDENT>return '<STR_LIT:true>' if k else '<STR_LIT:false>'<EOL><DEDENT>elif k is None:<EOL><INDENT>return '<STR_LIT:null>'<EOL><DEDENT>else:<EOL><INDENT>return unicode(k)<EOL><DEDENT><DEDENT>


try:<EOL><INDENT>node = globals().get(ele['<STR_LIT:type>'])<EOL>if not node:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' % ele['<STR_LIT:type>'])<EOL><DEDENT>if standard:<EOL><INDENT>node = node.__dict__[<EOL>'<STR_LIT>'] if '<STR_LIT>' in node.__dict__ else node<EOL><DEDENT>return node(**ele)<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>

Translates esprima syntax tree to python by delegating to appropriate translating node


def f(standard=False, **args):<EOL><INDENT>insert_pos = len(<EOL>inline_stack.names<EOL>)  <EOL>res = func(**args)<EOL>if len(res) > LINE_LEN_LIMIT:<EOL><INDENT>name = inline_stack.require('<STR_LIT>')<EOL>inline_stack.names.pop()<EOL>inline_stack.names.insert(insert_pos, name)<EOL>res = '<STR_LIT>' % (name, res)<EOL>inline_stack.define(name, res)<EOL>return name + '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return res<EOL><DEDENT><DEDENT>f.__dict__['<STR_LIT>'] = func<EOL>return f<EOL>

Decorator limiting resulting line length in order to avoid python parser stack overflow -
      If expression longer than LINE_LEN_LIMIT characters then it will be moved to upper line
     USE ONLY ON EXPRESSIONS!!!


p = PyJsParser()<EOL>return p.parse(javascript_code)<EOL>

Returns syntax tree of javascript_code.

    Syntax tree has the same structure as syntax tree produced by esprima.js

       Same as PyJsParser().parse  For your convenience :)


return {'<STR_LIT:type>': '<STR_LIT>', '<STR_LIT>': self.parseDisjunction()}<EOL>

Perform sctring escape - for regexp literals


parsed_len = <NUM_LIT:0><EOL>last = <NUM_LIT:0><EOL>splits = []<EOL>for e in bracket_split(args, brackets=['<STR_LIT>', '<STR_LIT>', '<STR_LIT:{}>']):<EOL><INDENT>if e[<NUM_LIT:0>] not in ('<STR_LIT:(>', '<STR_LIT:[>', '<STR_LIT:{>'):<EOL><INDENT>for i, char in enumerate(e):<EOL><INDENT>if char == sep:<EOL><INDENT>splits.append(args[last:parsed_len + i])<EOL>last = parsed_len + i + <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>parsed_len += len(e)<EOL><DEDENT>splits.append(args[last:])<EOL>return splits<EOL>

used to split JS args (it is not that simple as it seems because
       sep can be inside brackets).

       pass args *without* brackets!

       Used also to parse array and object elements, and more


def bracket_split(source, brackets=('<STR_LIT>', '<STR_LIT:{}>', '<STR_LIT>'), strip=False):

starts = [e[<NUM_LIT:0>] for e in brackets]<EOL>in_bracket = <NUM_LIT:0><EOL>n = <NUM_LIT:0><EOL>last = <NUM_LIT:0><EOL>while n < len(source):<EOL><INDENT>e = source[n]<EOL>if not in_bracket and e in starts:<EOL><INDENT>in_bracket = <NUM_LIT:1><EOL>start = n<EOL>b_start, b_end = brackets[starts.index(e)]<EOL><DEDENT>elif in_bracket:<EOL><INDENT>if e == b_start:<EOL><INDENT>in_bracket += <NUM_LIT:1><EOL><DEDENT>elif e == b_end:<EOL><INDENT>in_bracket -= <NUM_LIT:1><EOL>if not in_bracket:<EOL><INDENT>if source[last:start]:<EOL><INDENT>yield source[last:start]<EOL><DEDENT>last = n + <NUM_LIT:1><EOL>yield source[start + strip:n + <NUM_LIT:1> - strip]<EOL><DEDENT><DEDENT><DEDENT>n += <NUM_LIT:1><EOL><DEDENT>if source[last:]:<EOL><INDENT>yield source[last:]<EOL><DEDENT>

DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)


return {}<EOL>


socketio_manage(request.environ, namespaces=nsmap, request=request)<EOL>return {}<EOL>

The view that will launch the socketio listener


ret = os.system("<STR_LIT>")<EOL>self.emit("<STR_LIT>", ret)<EOL>


def simple_route(config, name, url, fn):

config.add_route(name, url)<EOL>config.add_view(fn, route_name=name,<EOL>renderer="<STR_LIT>" % name)<EOL>

Function to simplify creating routes in pyramid
        Takes the pyramid configuration, name of the route, url, and view
        function


self.socket.rooms.add(self._get_room_name(room))<EOL>

Lets a user join a room on a specific Namespace.


self.socket.rooms.remove(self._get_room_name(room))<EOL>

Lets a user leave a room on a specific Namespace.


def emit_to_room(self, event, args, room):

pkt = dict(type="<STR_LIT>",<EOL>name=event,<EOL>args=args,<EOL>endpoint=self.ns_name)<EOL>room_name = self._get_room_name(room)<EOL>for sessid, socket in self.socket.server.sockets.iteritems():<EOL><INDENT>if not hasattr(socket, '<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>if room_name in socket.rooms:<EOL><INDENT>socket.send_packet(pkt)<EOL><DEDENT><DEDENT>

This is sent to all in the room (in this particular Namespace)


Function to simplify creating routes in pyramid
Takes the pyramid configuration, name of the route, url, and view
function.


context = {"<STR_LIT>": ChatRoom.objects.all()}<EOL>return render(request, template, context)<EOL>


def room(request, slug, template="<STR_LIT>"):

context = {"<STR_LIT>": get_object_or_404(ChatRoom, slug=slug)}<EOL>return render(request, template, context)<EOL>


name = request.POST.get("<STR_LIT:name>")<EOL>if name:<EOL><INDENT>room, created = ChatRoom.objects.get_or_create(name=name)<EOL>return redirect(room)<EOL><DEDENT>return redirect(rooms)<EOL>

Handles post from the "Add room" form on the homepage, and
redirects to the new room.


def get_handler(self, *args, **options):

handler = WSGIHandler()<EOL>try:<EOL><INDENT>from django.contrib.staticfiles.handlers import StaticFilesHandler<EOL><DEDENT>except ImportError:<EOL><INDENT>return handler<EOL><DEDENT>use_static_handler = options.get('<STR_LIT>', True)<EOL>insecure_serving = options.get('<STR_LIT>', False)<EOL>if (settings.DEBUG and use_static_handler or<EOL>(use_static_handler and insecure_serving)):<EOL><INDENT>handler = StaticFilesHandler(handler)<EOL><DEDENT>return handler<EOL>

Returns the django.contrib.staticfiles handler.


context = {"<STR_LIT>": ChatRoom.query.all()}<EOL>return render_template('<STR_LIT>', **context)<EOL>


context = {"<STR_LIT>": get_object_or_404(ChatRoom, slug=slug)}<EOL>return render_template('<STR_LIT>', **context)<EOL>


name = request.form.get("<STR_LIT:name>")<EOL>if name:<EOL><INDENT>room, created = get_or_create(ChatRoom, name=name)<EOL>return redirect(url_for('<STR_LIT>', slug=room.slug))<EOL><DEDENT>return redirect(url_for('<STR_LIT>'))<EOL>


self.session['<STR_LIT>'].add(self._get_room_name(room))<EOL>


self.session['<STR_LIT>'].remove(self._get_room_name(room))<EOL>


def emit_to_room(self, room, event, *args):

pkt = dict(type="<STR_LIT>",<EOL>name=event,<EOL>args=args,<EOL>endpoint=self.ns_name)<EOL>room_name = self._get_room_name(room)<EOL>for sessid, socket in six.iteritems(self.socket.server.sockets):<EOL><INDENT>if '<STR_LIT>' not in socket.session:<EOL><INDENT>continue<EOL><DEDENT>if room_name in socket.session['<STR_LIT>'] and self.socket != socket:<EOL><INDENT>socket.send_packet(pkt)<EOL><DEDENT><DEDENT>


def broadcast_event(self, event, *args):

pkt = dict(type="<STR_LIT>",<EOL>name=event,<EOL>args=args,<EOL>endpoint=self.ns_name)<EOL>for sessid, socket in six.iteritems(self.socket.server.sockets):<EOL><INDENT>socket.send_packet(pkt)<EOL><DEDENT>

This is sent to all in the sockets in this particular Namespace,
including itself.


def broadcast_event_not_me(self, event, *args):

pkt = dict(type="<STR_LIT>",<EOL>name=event,<EOL>args=args,<EOL>endpoint=self.ns_name)<EOL>for sessid, socket in six.iteritems(self.socket.server.sockets):<EOL><INDENT>if socket is not self.socket:<EOL><INDENT>socket.send_packet(pkt)<EOL><DEDENT><DEDENT>

This is sent to all in the sockets in this particular Namespace,
except itself.


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.


decoded_msg = {}<EOL>try:<EOL><INDENT>rawstr = rawstr.decode('<STR_LIT:utf-8>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>split_data = rawstr.split("<STR_LIT::>", <NUM_LIT:3>)<EOL>msg_type = split_data[<NUM_LIT:0>]<EOL>msg_id = split_data[<NUM_LIT:1>]<EOL>endpoint = split_data[<NUM_LIT:2>]<EOL>data = '<STR_LIT>'<EOL>if msg_id != '<STR_LIT>':<EOL><INDENT>if "<STR_LIT:+>" in msg_id:<EOL><INDENT>msg_id = msg_id.split('<STR_LIT:+>')[<NUM_LIT:0>]<EOL>decoded_msg['<STR_LIT:id>'] = int(msg_id)<EOL>decoded_msg['<STR_LIT>'] = '<STR_LIT:data>'<EOL><DEDENT>else:<EOL><INDENT>decoded_msg['<STR_LIT:id>'] = int(msg_id)<EOL>decoded_msg['<STR_LIT>'] = True<EOL><DEDENT><DEDENT>msg_type_id = int(msg_type)<EOL>if msg_type_id in MSG_VALUES:<EOL><INDENT>decoded_msg['<STR_LIT:type>'] = MSG_VALUES[int(msg_type)]<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % msg_type)<EOL><DEDENT>decoded_msg['<STR_LIT>'] = endpoint<EOL>if len(split_data) > <NUM_LIT:3>:<EOL><INDENT>data = split_data[<NUM_LIT:3>]<EOL><DEDENT>if msg_type == "<STR_LIT:0>":  <EOL><INDENT>pass<EOL><DEDENT>elif msg_type == "<STR_LIT:1>":  <EOL><INDENT>decoded_msg['<STR_LIT>'] = data<EOL><DEDENT>elif msg_type == "<STR_LIT:2>":  <EOL><INDENT>pass<EOL><DEDENT>elif msg_type == "<STR_LIT:3>":  <EOL><INDENT>decoded_msg['<STR_LIT:data>'] = data<EOL><DEDENT>elif msg_type == "<STR_LIT:4>":  <EOL><INDENT>decoded_msg['<STR_LIT:data>'] = json_loads(data)<EOL><DEDENT>elif msg_type == "<STR_LIT:5>":  <EOL><INDENT>try:<EOL><INDENT>data = json_loads(data)<EOL><DEDENT>except ValueError:<EOL><INDENT>print("<STR_LIT>", data)<EOL>decoded_msg['<STR_LIT:args>'] = []<EOL><DEDENT>else:<EOL><INDENT>decoded_msg['<STR_LIT:name>'] = data.pop('<STR_LIT:name>')<EOL>if '<STR_LIT:args>' in data:<EOL><INDENT>decoded_msg['<STR_LIT:args>'] = data['<STR_LIT:args>']<EOL><DEDENT>else:<EOL><INDENT>decoded_msg['<STR_LIT:args>'] = []<EOL><DEDENT><DEDENT><DEDENT>elif msg_type == "<STR_LIT>":  <EOL><INDENT>if '<STR_LIT:+>' in data:<EOL><INDENT>ackId, data = data.split('<STR_LIT:+>')<EOL>decoded_msg['<STR_LIT>'] = int(ackId)<EOL>decoded_msg['<STR_LIT:args>'] = json_loads(data)<EOL><DEDENT>else:<EOL><INDENT>decoded_msg['<STR_LIT>'] = int(data)<EOL>decoded_msg['<STR_LIT:args>'] = []<EOL><DEDENT><DEDENT>elif msg_type == "<STR_LIT>":  <EOL><INDENT>if '<STR_LIT:+>' in data:<EOL><INDENT>reason, advice = data.split('<STR_LIT:+>')<EOL>decoded_msg['<STR_LIT>'] = REASONS_VALUES[int(reason)]<EOL>decoded_msg['<STR_LIT>'] = ADVICES_VALUES[int(advice)]<EOL><DEDENT>else:<EOL><INDENT>decoded_msg['<STR_LIT>'] = '<STR_LIT>'<EOL>if data != '<STR_LIT>':<EOL><INDENT>decoded_msg['<STR_LIT>'] = REASONS_VALUES[int(data)]<EOL><DEDENT>else:<EOL><INDENT>decoded_msg['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>elif msg_type == "<STR_LIT>":  <EOL><INDENT>pass<EOL><DEDENT>return decoded_msg<EOL>

Decode a rawstr packet arriving from the socket into a dict.


global LOADING_SOCKETIO<EOL>if LOADING_SOCKETIO:<EOL><INDENT>return<EOL><DEDENT>LOADING_SOCKETIO = True<EOL>import imp<EOL>from django.conf import settings<EOL>for app in settings.INSTALLED_APPS:<EOL><INDENT>try:<EOL><INDENT>app_path = import_module(app).__path__<EOL><DEDENT>except AttributeError:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>imp.find_module('<STR_LIT>', app_path)<EOL><DEDENT>except ImportError:<EOL><INDENT>continue<EOL><DEDENT>import_module("<STR_LIT>" % app)<EOL><DEDENT>LOADING_SOCKETIO = False<EOL>

Auto-discover INSTALLED_APPS sockets.py modules and fail silently when
not present. NOTE: socketio_autodiscover was inspired/copied from
django.contrib.admin autodiscover


def default_error_handler(socket, error_name, error_message, endpoint,<EOL>msg_id, quiet):

pkt = dict(type='<STR_LIT>', name='<STR_LIT:error>',<EOL>args=[error_name, error_message],<EOL>endpoint=endpoint)<EOL>if msg_id:<EOL><INDENT>pkt['<STR_LIT:id>'] = msg_id<EOL><DEDENT>if not quiet:<EOL><INDENT>socket.send_packet(pkt)<EOL><DEDENT>log.error(u"<STR_LIT>".format(<EOL>error_name, error_message, endpoint, msg_id<EOL>))<EOL>

This is the default error handler, you can override this when
    calling :func:`socketio.socketio_manage`.

    It basically sends an event through the socket with the 'error' name.

    See documentation for :meth:`Socket.error`.

    :param quiet: if quiet, this handler will not send a packet to the
                  user, but only log for the server developer.


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().


self.error_handler = error_handler<EOL>

Changes the default error_handler function to the one specified

        This is called by socketio_manage().


self.json_loads = json_loads<EOL>

Change the default JSON decoder.

        This should be a callable that accepts a single string, and returns
        a well-formed object.


self.json_dumps = json_dumps<EOL>


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.


def _save_ack_callback(self, msgid, callback):

if msgid in self.ack_callbacks:<EOL><INDENT>return False<EOL><DEDENT>self.ack_callbacks[msgid] = callback<EOL>

Keep a reference of the callback on this socket.


if msgid not in self.ack_callbacks:<EOL><INDENT>return None<EOL><DEDENT>return self.ack_callbacks.pop(msgid)<EOL>

Fetch the callback for a given msgid, if it exists, otherwise,
        return None


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')


return key in self.active_ns<EOL>

Verifies if the namespace is active (was initialized)


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

Returns whether the state is CONNECTED or not.


self.timeout.set()<EOL>

This makes the heart beat for another X seconds.  Call this when
        you get a heartbeat packet in.

        This clear the heartbeat disconnect timeout (resets for X seconds).


<EOL>self.ack_callbacks = {}<EOL>if self.connected:<EOL><INDENT>self.state = self.STATE_DISCONNECTING<EOL>self.server_queue.put_nowait(None)<EOL>self.client_queue.put_nowait(None)<EOL>if len(self.active_ns) > <NUM_LIT:0>:<EOL><INDENT>log.debug("<STR_LIT>" % self)<EOL>self.disconnect()<EOL><DEDENT><DEDENT>if detach:<EOL><INDENT>self.detach()<EOL><DEDENT>gevent.killall(self.jobs)<EOL>

This function must/will be called when a socket is to be completely
        shut down, closed by connection timeout, connection error or explicit
        disconnection from the client.

        It will call all of the Namespace's
        :meth:`~socketio.namespace.BaseNamespace.disconnect` methods
        so that you can shut-down things properly.


log.debug("<STR_LIT>" % self)<EOL>if self.sessid in self.server.sockets:<EOL><INDENT>self.server.sockets.pop(self.sessid)<EOL><DEDENT>

Detach this socket from the server. This should be done in
        conjunction with kill(), once all the jobs are dead, detach the
        socket for garbage collection.


self.heartbeat()<EOL>self.server_queue.put_nowait(msg)<EOL>

Writes to the server's pipe, to end up in in the Namespaces


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


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

Grab a message to send it to the browser


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

Grab a message, to process it by the server and dispatch calls


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.


def error(self, error_name, error_message, endpoint=None, msg_id=None,<EOL>quiet=False):

handler = self.error_handler<EOL>return handler(<EOL>self, error_name, error_message, endpoint, msg_id, quiet)<EOL>

Send an error to the user, using the custom or default
        ErrorHandler configured on the [TODO: Revise this] Socket/Handler
        object.

        :param error_name: is a simple string, for easy association on
                           the client side

        :param error_message: is a human readable message, the user
                              will eventually see

        :param endpoint: set this if you have a message specific to an
                         end point

        :param msg_id: set this if your error is relative to a
                       specific message

        :param quiet: way to make the error handler quiet. Specific to
                      the handler.  The default handler will only log,
                      with quiet.


for ns_name, ns in list(six.iteritems(self.active_ns)):<EOL><INDENT>ns.recv_disconnect()<EOL><DEDENT>

Calling this method will call the
        :meth:`~socketio.namespace.BaseNamespace.disconnect` method on
        all the active Namespaces that were open, killing all their
        jobs and sending 'disconnect' packets for each of them.

        Normally, the Global namespace (endpoint = '') has special meaning,
        as it represents the whole connection,

        :param silent: when True, pass on the ``silent`` flag to the Namespace
                       :meth:`~socketio.namespace.BaseNamespace.disconnect`
                       calls.


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`.


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


log.debug("<STR_LIT>" % fn.__name__)<EOL>job = gevent.spawn(fn, *args, **kwargs)<EOL>self.jobs.append(job)<EOL>return job<EOL>

Spawn a new Greenlet, attached to this Socket instance.

        It will be monitored by the "watcher" method