# Path: sio/workers/util.py
# def first_entry_point(group, name=None):
#     def __init__(self):
#     def elapsed(self):
# def s2ms(seconds):
# def ms2s(miliseconds):
# def ceil_ms2s(miliseconds):
#     def __init__(self, fname):
#     def __enter__(self):
#     def __exit__(self, exc_type, exc_value, traceback):
# def rmtree(path):
#     def remove_readonly(fn, path, excinfo):
# def tempcwd(path=None):
#     def __init__(self, inner_directory=None):
#     def __enter__(self):
#     def __exit__(self, exc_type, exc_value, traceback):
# def path_join_abs(base, subpath):
# def replace_invalid_UTF(a_string):
#     def default(self, obj):
# def json_dumps(obj, **kwargs):
# def decode_fields(fields):
#     def _decode_decorator(func):
#         def _wrapper(*args, **kwargs):
# def null_ctx_manager():
#     def dummy():
#     def __init__(cls, class_name, bases, new_attrs):
#     def __classinit__(cls):
#     def __classinit__(cls):
#         def find_superclass(cls):
# class PerfTimer(object):
# class Writable(object):
# class TemporaryCwd(object):
# class CompatibleJSONEncoder(json.JSONEncoder):
# class ClassInitMeta(type):
# class ClassInitBase(six.with_metaclass(ClassInitMeta, object)):
# class RegisteredSubclassesBase(ClassInitBase):
# 
# Path: sio/workers/elf_loader_patch.py
# EXT = '.old_elf_loader'
# def _get_unpatched_name(path):
# def _patch_elf_loader(path):
# 
# Path: sio/workers/sandbox.py
# def get_sandbox(name):
#     """Constructs a :class:`Sandbox` with the given ``name``.
# 
#     If a :class:`Sandbox` instance for the given ``name`` is already
#     created, returns that instance.
# 
#     Only this function should be used to creating or getting
#     :class:`Sandbox` instances.
#     """
#     return Sandbox._instance(name)
# 
# Path: sio/workers/util.py
# def ceil_ms2s(miliseconds):
#     """Returns first integer count of seconds not less that ``miliseconds``.
# 
#     >>> ceil_ms2s(1000)
#     1
#     >>> ceil_ms2s(1001)
#     2
#     """
#     return int((miliseconds + 999) / 1000)
# 
# def decode_fields(fields):
#     def _decode_decorator(func):
#         def _wrapper(*args, **kwargs):
#             result_dict = func(*args, **kwargs)
#             for field in fields:
#                 if not isinstance(result_dict[field], six.string_types):
#                     result_dict[field] = result_dict[field].decode()
#             return result_dict
# 
#         return _wrapper
# 
#     return _decode_decorator
# 
# def ms2s(miliseconds):
#     """Converts ``miliseconds`` to seconds and returns float.
# 
#     >>> '%.2f' % ms2s(1190)
#     '1.19'
#     """
#     return miliseconds / 1000.0
# 
# def s2ms(seconds):
#     """Converts ``seconds`` to miliseconds
# 
#     >>> s2ms(1.95)
#     1950
#     """
#     return int(1000 * seconds)
# 
# def path_join_abs(base, subpath):
#     """Joins two absolute paths making ``subpath`` relative to ``base``.
# 
#     >>> import os.path
#     >>> os.path.join('/usr', '/bin/sh')
#     '/bin/sh'
# 
#     >>> path_join_abs('/usr', '/bin/sh')
#     '/usr/bin/sh'
#     """
#     return os.path.join(base, subpath.strip(os.sep))
# 
# def null_ctx_manager():
#     def dummy():
#         yield
# 
#     return contextmanager(dummy)()
# 
# def tempcwd(path=None):
#     # Someone might call tempcwd twice, i.e. tempcwd(tempcwd('something'))
#     # Do nothing in this case.
#     if path is not None and os.path.isabs(path):
#         return path
#     d = threadlocal_dir.tmpdir
#     if path:
#         return os.path.join(d, path)
#     else:
#         return d


import os
import subprocess
import tempfile
import signal
import logging
import re
import sys
import traceback
import six
from threading import Timer
from os import path
from sio.workers import util, elf_loader_patch
from sio.workers.sandbox import get_sandbox
from sio.workers.util import (
    ceil_ms2s,
    decode_fields,
    ms2s,
    s2ms,
    path_join_abs,
    null_ctx_manager,
    tempcwd,
)
from six.moves import map
        120: 'OLE',
        121: 'RV',
        124: 'MLE',
        125: 'TLE',
    }

    def __init__(self, sandbox_name):
        super(_SIOSupervisedExecutor, self).__init__(sandbox_name)

    def _supervisor_result_to_code(self, result):
        return self._supervisor_codes.get(int(result), 'RE')

    @decode_fields(['result_string'])
    def _execute(self, command, **kwargs):
        env = kwargs.get('env')
        env.update(
            {
                'MEM_LIMIT': kwargs['mem_limit'] or 64 * 2 ** 10,
                'TIME_LIMIT': kwargs['time_limit'] or 30000,
                'OUT_LIMIT': kwargs['output_limit'] or 50 * 2 ** 20,
            }
        )

        if kwargs['real_time_limit']:
            env['HARD_LIMIT'] = 1 + ceil_ms2s(kwargs['real_time_limit'])
        elif kwargs['time_limit'] and kwargs['real_time_limit'] is None:
            env['HARD_LIMIT'] = 1 + ceil_ms2s(64 * kwargs['time_limit'])

        if 'HARD_LIMIT' in env:
            # Limiting outside supervisor

# Path: sio/workers/util.py
# def first_entry_point(group, name=None):
#     def __init__(self):
#     def elapsed(self):
# def s2ms(seconds):
# def ms2s(miliseconds):
# def ceil_ms2s(miliseconds):
#     def __init__(self, fname):
#     def __enter__(self):
#     def __exit__(self, exc_type, exc_value, traceback):
# def rmtree(path):
#     def remove_readonly(fn, path, excinfo):
# def tempcwd(path=None):
#     def __init__(self, inner_directory=None):
#     def __enter__(self):
#     def __exit__(self, exc_type, exc_value, traceback):
# def path_join_abs(base, subpath):
# def replace_invalid_UTF(a_string):
#     def default(self, obj):
# def json_dumps(obj, **kwargs):
# def decode_fields(fields):
#     def _decode_decorator(func):
#         def _wrapper(*args, **kwargs):
# def null_ctx_manager():
#     def dummy():
#     def __init__(cls, class_name, bases, new_attrs):
#     def __classinit__(cls):
#     def __classinit__(cls):
#         def find_superclass(cls):
# class PerfTimer(object):
# class Writable(object):
# class TemporaryCwd(object):
# class CompatibleJSONEncoder(json.JSONEncoder):
# class ClassInitMeta(type):
# class ClassInitBase(six.with_metaclass(ClassInitMeta, object)):
# class RegisteredSubclassesBase(ClassInitBase):
# 
# Path: sio/workers/elf_loader_patch.py
# EXT = '.old_elf_loader'
# def _get_unpatched_name(path):
# def _patch_elf_loader(path):
# 
# Path: sio/workers/sandbox.py
# def get_sandbox(name):
#     """Constructs a :class:`Sandbox` with the given ``name``.
# 
#     If a :class:`Sandbox` instance for the given ``name`` is already
#     created, returns that instance.
# 
#     Only this function should be used to creating or getting
#     :class:`Sandbox` instances.
#     """
#     return Sandbox._instance(name)
# 
# Path: sio/workers/util.py
# def ceil_ms2s(miliseconds):
#     """Returns first integer count of seconds not less that ``miliseconds``.
# 
#     >>> ceil_ms2s(1000)
#     1
#     >>> ceil_ms2s(1001)
#     2
#     """
#     return int((miliseconds + 999) / 1000)
# 
# def decode_fields(fields):
#     def _decode_decorator(func):
#         def _wrapper(*args, **kwargs):
#             result_dict = func(*args, **kwargs)
#             for field in fields:
#                 if not isinstance(result_dict[field], six.string_types):
#                     result_dict[field] = result_dict[field].decode()
#             return result_dict
# 
#         return _wrapper
# 
#     return _decode_decorator
# 
# def ms2s(miliseconds):
#     """Converts ``miliseconds`` to seconds and returns float.
# 
#     >>> '%.2f' % ms2s(1190)
#     '1.19'
#     """
#     return miliseconds / 1000.0
# 
# def s2ms(seconds):
#     """Converts ``seconds`` to miliseconds
# 
#     >>> s2ms(1.95)
#     1950
#     """
#     return int(1000 * seconds)
# 
# def path_join_abs(base, subpath):
#     """Joins two absolute paths making ``subpath`` relative to ``base``.
# 
#     >>> import os.path
#     >>> os.path.join('/usr', '/bin/sh')
#     '/bin/sh'
# 
#     >>> path_join_abs('/usr', '/bin/sh')
#     '/usr/bin/sh'
#     """
#     return os.path.join(base, subpath.strip(os.sep))
# 
# def null_ctx_manager():
#     def dummy():
#         yield
# 
#     return contextmanager(dummy)()
# 
# def tempcwd(path=None):
#     # Someone might call tempcwd twice, i.e. tempcwd(tempcwd('something'))
#     # Do nothing in this case.
#     if path is not None and os.path.isabs(path):
#         return path
#     d = threadlocal_dir.tmpdir
#     if path:
#         return os.path.join(d, path)
#     else:
#         return d


# Path: sio/workers/executors.py
import os
import subprocess
import tempfile
import signal
import logging
import re
import sys
import traceback
import six
from threading import Timer
from os import path
from sio.workers import util, elf_loader_patch
from sio.workers.sandbox import get_sandbox
from sio.workers.util import (
    ceil_ms2s,
    decode_fields,
    ms2s,
    s2ms,
    path_join_abs,
    null_ctx_manager,
    tempcwd,
)
from six.moves import map

        120: 'OLE',
        121: 'RV',
        124: 'MLE',
        125: 'TLE',
    }

    def __init__(self, sandbox_name):
        super(_SIOSupervisedExecutor, self).__init__(sandbox_name)

    def _supervisor_result_to_code(self, result):
        return self._supervisor_codes.get(int(result), 'RE')

    @decode_fields(['result_string'])
    def _execute(self, command, **kwargs):
        env = kwargs.get('env')
        env.update(
            {
                'MEM_LIMIT': kwargs['mem_limit'] or 64 * 2 ** 10,
                'TIME_LIMIT': kwargs['time_limit'] or 30000,
                'OUT_LIMIT': kwargs['output_limit'] or 50 * 2 ** 20,
            }
        )

        if kwargs['real_time_limit']:
            env['HARD_LIMIT'] = 1 + ceil_ms2s(kwargs['real_time_limit'])
        elif kwargs['time_limit'] and kwargs['real_time_limit'] is None:
            env['HARD_LIMIT'] = 1 + ceil_ms2s(64 * kwargs['time_limit'])

        if 'HARD_LIMIT' in env:
            # Limiting outside supervisor

            kwargs['real_time_limit'] = 2 * s2ms(env['HARD_LIMIT'])