text:
from rsqueakvm import constants, error, wrapper
from rsqueakvm.model.compiled_methods import W_CompiledMethod
from rsqueakvm.model.pointers import W_PointersObject
from rsqueakvm.model.block_closure import W_BlockClosure
from rsqueakvm.storage import AbstractStrategy, ShadowMixin

from rpython.rlib import jit, objectmodel, unroll
from rpython.rlib.objectmodel import import_from_mixin, always_inline
from rpython.rlib.rarithmetic import r_uint, intmask

@objectmodel.specialize.call_location()
def fresh_virtualizable(x):
    return jit.hint(x, access_directly=True, fresh_virtualizable=True)

class ContextState(object):
    _attrs_ = ["name", "i"]
    _immutable_fields_ = ["name", "i"]
    states = []
    def __init__(self, name):
        self.name = name
        self.i = len(self.states)
        self.states.append(self)
    def __str__(self):
        return self.name
    def __repr__(self):
        return self.name
    def num(self):
        return self.i
InactiveContext = ContextState("InactiveContext")
ActiveContext = ContextState("ActiveContext")
DirtyContext = ContextState("DirtyContext")

class ExtraContextAttributes(object):
    _attrs_ = [
        # Cache for allInstances
        'instances_w',
        # Fallback for failed primitives
        '_s_fallback',
        # From block-context
        '_w_home', '_initialip', '_eargc']

    def __init__(self):
        self.instances_w = None
        self._s_fallback = None
        self._w_home = None
        self._initialip = 0
        self._eargc = 0

state_mask     = r_uint(0b00111111111111111111111111111111)
stackptr_mask  = r_uint(0b11000000001111111111111111111111)
pc_mask        = r_uint(0b11111111110000000000000000000000)
returned_pc    = 0b00000000001111111111111111111111
state_shift    = 30
stackptr_shift = 22
pc_shift       = 0

class ContextPartShadow(AbstractStrategy):
    """
    This Shadow handles the entire object storage on its own, ignoring the _storage
    field in W_PointersObject. The w_self parameter in fetch/store/size etc. is ignored,
    and the own_fetch/own_store/own_size methods from ShadowMixin should be used instead.
    This shadow can exist without a W_PointersObject.
    In order to integrate well with the RPython toolchain (virtualizables and jit), this
    class actually represents one of two classes, determined by the is_block_context switch.
    """
    repr_classname = "ContextPartShadow"

    import_from_mixin(ShadowMixin)

    _attrs_ = ['_w_self', '_w_self_size',
               '_state_stackptr_pc',
               # Core context data
               '_s_sender', '_temps_and_stack',
               # MethodContext data
               'blockmethod',
               'closure', '_w_receiver', '_w_method',
               # Extra data
               'extra_data'
               ]

    _virtualizable_ = [
        "_w_self", "_w_self_size",
        '_state_stackptr_pc',
        '_s_sender', "_temps_and_stack[*]",
        'blockmethod',
        'closure', '_w_receiver', '_w_method',
        'extra_data'
    ]

    # ______________________________________________________________________
    # Initialization

    @jit.unroll_safe
    def __init__(self, space, w_self, size, w_class):
        self = fresh_virtualizable(self)
        AbstractStrategy.__init__(self, space, w_self, size, w_class)

        self._state_stackptr_pc = r_uint(0)
        self._s_sender = jit.vref_None
        if w_self is not None:
            self._w_self_size = w_self.size()
        else:
            self._w_self_size = size
        self._w_self = w_self
        self.set_state(InactiveContext)
        self.store_pc(0)

        # From MethodContext
        self.blockmethod = None
        self.closure = None
        self._w_method = None
        self._w_receiver = None
        # Extra data
        self.extra_data = None

    def _initialize_storage(self, w_self, initial_size):
        # The context object holds all of its storage itself.
        self.set_storage(w_self, None)

    @jit.unroll_safe
    def _convert_storage_from(self, w_self, previous_strategy):
        size = previous_strategy.size(w_self)
        # Some fields have to be initialized before the rest,
        # to ensure correct initialization.
        if self.pure_is_block_context():
            assert len(self.privileged_block_fields) == 1
            self.store(w_self, self.privileged_block_fields[0],
                       previous_strategy.fetch(w_self, self.privileged_block_fields[0]))
        else:
            assert len(self.privileged_method_fields) == 2
            self.store(w_self, self.privileged_method_fields[0],
                       previous_strategy.fetch(w_self, self.privileged_method_fields[0]))
            self.store(w_self, self.privileged_method_fields[1],
                       previous_strategy.fetch(w_self, self.privileged_method_fields[1]))

        # Now the temp size will be known.
        self.init_temps_and_stack()

        # After this, convert the rest of the fields.
        for n0 in range(size):
            if not self.is_privileged_index(n0):
                self.store(w_self, n0, previous_strategy.fetch(w_self, n0))

        # Finally, we can remove the storage that was there previously
        self._initialize_storage(w_self, size)

    privileged_block_fields = (constants.BLKCTX_HOME_INDEX,)
    privileged_method_fields = (constants.MTHDCTX_METHOD, constants.MTHDCTX_CLOSURE_OR_NIL)

    def is_privileged_index(self, n0):
        if self.pure_is_block_context():
            assert len(self.privileged_block_fields) == 1
            return n0 == self.privileged_block_fields[0]
        else:
            assert len(self.privileged_method_fields) == 2
            # we use | instead of || to generate only one guard
            return (n0 == self.privileged_method_fields[0]) | (n0 == self.privileged_method_fields[1])

    def get_extra_data(self):
        if self.extra_data is None:
            self.extra_data = ExtraContextAttributes()
        return self.extra_data

    def get_fallback(self):
        if self.extra_data is None:
            return None
        else:
            return self.extra_data._s_fallback

    @always_inline
    def _get_state_stackptr_pc(self):
        return jit.promote(self._state_stackptr_pc)

    @always_inline
    def get_state(self):
        return ContextState.states[intmask((self._get_state_stackptr_pc() & ~state_mask) >> state_shift)]

    @always_inline
    def set_state(self, t):
        self._state_stackptr_pc = (self._get_state_stackptr_pc() & state_mask) | (r_uint(t.num()) << state_shift)
        assert self.get_state() == t

    # ______________________________________________________________________
    # Accessing object fields

    def pure_is_block_context(self):
        if self.space.uses_block_contexts.is_set():
            return self.space.w_BlockContext.is_same_object(self.w_class)
        else:
            return False

    def size(self, ignored_w_self):
        return self._w_self_size

    def fetch(self, ignored_w_self, n0):
        if self.pure_is_block_context():
            return self.fetch_block_context(n0)
        else:
            return self.fetch_method_context(n0)

    def fetch_context_part(self, n0):
        if n0 == constants.CTXPART_SENDER_INDEX:
            return self.w_sender()
        if n0 == constants.CTXPART_PC_INDEX:
            return self.wrap_pc()
        if n0 == constants.CTXPART_STACKP_INDEX:
            return self.wrap_stackpointer()
        if self.stackstart() <= n0 < self.external_stackpointer():
            temp_i = self.stackdepth() - (n0-self.stackstart()) - 1
            assert temp_i >= 0, "trying to access temp out of range"
            return self.peek(temp_i)
        if self.external_stackpointer() <= n0 < self.stackend():
            return self.space.w_nil
        else:
            # XXX later should store tail out of known context part as well
            raise error.WrapperException("Index in context out of bounds")

    def store(self, ignored_w_self, n0, w_value):
        if self.pure_is_block_context():
            return self.store_block_context(n0, w_value)
        else:
            return self.store_method_context(n0, w_value)

    def store_context_part(self, n0, w_value):
        if n0 == constants.CTXPART_SENDER_INDEX:
            assert isinstance(w_value, W_PointersObject), "trying to store non-pointer sender"
            if w_value.is_nil(self.space):
                self.remove_s_sender()
                if self.get_state() is ActiveContext:
                    self.set_state(DirtyContext)
            else:
                self.store_s_sender(w_value.as_context_get_shadow(self.space))
            return
        if n0 == constants.CTXPART_PC_INDEX:
            return self.store_unwrap_pc(w_value)
        if n0 == constants.CTXPART_STACKP_INDEX:
            return self.unwrap_store_stackpointer(w_value)
        if self.stackstart() <= n0 < self.external_stackpointer():  # XXX can be simplified?
            temp_i = self.stackdepth() - (n0-self.stackstart()) - 1
            assert temp_i >= 0, "trying to store temp out of range"
            return self.set_top(w_value, temp_i)
        if self.external_stackpointer() <= n0 < self.stackend():
            return
        else:
            # XXX later should store tail out of known context part as well
            raise error.WrapperException("Index in context out of bounds")

    # === Sender ===

    def remove_s_sender(self):
        self._s_sender = jit.vref_None

    def has_s_sender(self):
        return self._s_sender is not jit.vref_None

    def store_s_sender(self, s_sender):
        assert s_sender is not None, "trying to store None s_sender"
        self._s_sender = jit.non_virtual_ref(s_sender)
        if self.get_state() is ActiveContext:
            self.set_state(DirtyContext)

    def enter_virtual_frame(self, s_sender):
        self.set_state(ActiveContext)
        if self.has_s_sender() or s_sender is None:
            return jit.vref_None
        else:
            self._s_sender = jit.virtual_ref(s_sender)
            return self._s_sender

    def leave_virtual_frame(self, vref, ref):
        self.set_state(InactiveContext)
        if vref is not jit.vref_None:
            jit.virtual_ref_finish(vref, ref)
            if vref is self._s_sender:
                # If this frame was not manipulated, _s_sender is still our
                # initial vref. If the frame was manipulated (or has no sender)
                # _s_sender is already a non_virtual_ref.
                self._s_sender = jit.non_virtual_ref(ref)

    def w_sender(self):
        sender = self.s_sender()
        if sender is None:
            return self.space.w_nil
        return sender.w_self()

    def s_sender(self):
        return self._s_sender()

    # === Stack Pointer ===

    def unwrap_store_stackpointer(self, w_sp1):
        # the stackpointer in the W_PointersObject starts counting at the
        # tempframe start
        # Stackpointer from smalltalk world == stacksize in python world
        self.store_stackpointer(self.space.unwrap_int(w_sp1))

    @jit.unroll_safe
    def store_stackpointer(self, size):
        depth = self.stackdepth()
        if size < depth:
            assert size >= 0, "trying to store negative stackpointer"
            self.pop_n(depth - size)
        else:
            for i in range(depth, size):
                self.push(self.space.w_nil)

    def stackdepth(self):
        return self.stack_ptr()

    @always_inline
    def stack_ptr(self):
        return intmask((self._get_state_stackptr_pc() & ~stackptr_mask) >> stackptr_shift)

    @always_inline
    def store_stack_ptr(self, ptr):
        assert ptr >= 0
        assert ptr < 256
        self._state_stackptr_pc = (self._get_state_stackptr_pc() & stackptr_mask) | (r_uint(ptr) << stackptr_shift)
        assert self.stack_ptr() == ptr

    def wrap_stackpointer(self):
        return self.space.wrap_smallint_unsafe(self.stackdepth())

    # === Program Counter ===

    def store_unwrap_pc(self, w_pc):
        if w_pc.is_nil(self.space):
            self.store_pc(returned_pc)
        else:
            pc = self.space.unwrap_int(w_pc)
            pc -= self.w_method().bytecodeoffset()
            pc -= 1
            self.store_pc(pc)

    def wrap_pc(self):
        pc = self.pc()
        if pc == returned_pc:
            return self.space.w_nil
        else:
            pc += 1
            pc += self.w_method().bytecodeoffset()
            return self.space.wrap_smallint_unsafe(pc)

    @always_inline
    def pc(self):
        return intmask((self._get_state_stackptr_pc() & ~pc_mask) >> pc_shift)

    @always_inline
    def store_pc(self, newpc):
        assert newpc >= 0, "trying to store pc < 0"
        assert newpc <= returned_pc, "trying to store pc > returned_pc"
        self._state_stackptr_pc = (self._get_state_stackptr_pc() & pc_mask) | (r_uint(newpc) << pc_shift)
        assert self.pc() == newpc

    # ______________________________________________________________________
    # Specialized accessors
    #
    # These methods have different versions depending on whether the receiver
    # is a BlockContext or MethodContext. The call is forwarded to a specialized
    # version, like a manual kind of inheritance.

    def s_home(self):
        if self.pure_is_block_context():
            return self.s_home_block_context()
        else:
            return self.s_home_method_context()

    def stackstart(self):
        if self.pure_is_block_context():
            return self.stackstart_block_context()
        else:
            return self.stackstart_method_context()

    def w_receiver(self):
        if self.pure_is_block_context():
            return self.w_receiver_block_context()
        else:
            return self.w_receiver_method_context()

    def w_method(self):
        if self.pure_is_block_context():
            return self.w_method_block_context()
        else:
            return self.w_method_method_context()

    def tempsize(self):
        if self.pure_is_block_context():
            return self.tempsize_block_context()
        else:
            return self.tempsize_method_context()

    def is_closure_context(self):
        if self.pure_is_block_context():
            return self.is_closure_context_block_context()
        else:
            return self.is_closure_context_method_context()

    def is_BlockClosure_ensure(self):
        if self.pure_is_block_context():
            return False
        else:
            # Primitive 198 is a marker used in BlockClosure >> ensure:
            return self.w_method().primitive() == 198

    def home_is_self(self):
        if self.pure_is_block_context():
            return self.home_is_self_block_context()
        else:
            return self.home_is_self_method_context()

    # ______________________________________________________________________
    # Temporary Variables
    #
    # Every context has it's own stack. BlockContexts share their temps with
    # their home contexts. MethodContexts created from a BlockClosure get their
    # temps copied from the closure upon activation. Changes are not propagated back;
    # this is handled by the compiler by allocating an extra Array for temps.

    def gettemp(self, index):
        if self.pure_is_block_context():
            return self.gettemp_block_context(index)
        else:
            return self.gettemp_method_context(index)

    def settemp(self, index, w_value):
        if self.pure_is_block_context():
            return self.settemp_block_context(index, w_value)
        else:
            return self.settemp_method_context(index, w_value)

    # === Other properties of Contexts ===

    def mark_returned(self):
        self.store_pc(returned_pc)
        self.remove_s_sender()

    def is_returned(self):
        return self.pc() == returned_pc and (not self.has_s_sender())

    def external_stackpointer(self):
        return self.stackdepth() + self.stackstart()

    def stackend(self):
        # XXX this is incorrect when there is subclassing
        return self._w_self_size

    def fetch_next_bytecode(self):
        pc = jit.promote(self.pc())
        assert pc < returned_pc, "fetching bytecode on returned method"
        self.store_pc(pc + 1)
        return self.fetch_bytecode(pc)

    def fetch_bytecode(self, pc):
        bytecode = self.w_method().fetch_bytecode(pc)
        return ord(bytecode)

    # ______________________________________________________________________
    # Stack Manipulation

    def stacksize(self):
        return self.stackend() - self.stackstart()

    def full_stacksize(self):
        if not self.pure_is_block_context():
            # Magic numbers... Takes care of cases where reflective
            # code writes more than actual stack size
            method = self.w_method()
            assert isinstance(method, W_CompiledMethod), "context method is not a W_CompiledMethod"
            stacksize = method.compute_frame_size()
        else:
            # TODO why not use method.compute_frame_size for BlockContext too?
            stacksize = self.stacksize()  # no temps
        return stacksize

    def init_temps_and_stack(self):
        self = fresh_virtualizable(self)
        stacksize = self.full_stacksize()
        self._temps_and_stack = [None] * stacksize
        tempsize = self.tempsize()
        self.store_stack_ptr(tempsize)  # we point after the last element

    def stack_get(self, index0):
        assert index0 >= 0, "trying to stack_get negative index"
        return self._temps_and_stack[index0] or self.space.w_nil

    def stack_put(self, index0, w_val):
        assert w_val is not None, "trying to put None on the stack"
        assert index0 >= 0, "trying to stack_put at negative index"
        self._temps_and_stack[index0] = w_val

    @objectmodel.not_rpython # this is only for testing.
    def stack(self):
        return self._temps_and_stack[self.tempsize():self.stack_ptr()]

    def pop(self):
        # HACK HACK HACK (3 times)
        # Popping the empty stack is actually an error, but this sometimes
        # happens in strange code paths. So, there's typically only the receiver
        # at bottom, under the stack, or among the temps that could be around there,
        # so just hard return the receiver.
        #assert self.stack_ptr() > self.tempsize()
        ptr = jit.promote(self.stack_ptr()) - 1
        if ptr < 0:
            ret = self.w_receiver()
            ptr = 0
        else:
            ret = self.stack_get(ptr)
        #
        # HACK HACK HACK HACK HACK (5 times)
        # We really would like to nil out the popp'ed value, but there are
        # methods (yes, ContextPart>>contextOn:do:, I am looking at you!) that
        # do a pop and access the stack afterwards. Or better said, do a pop on
        # the empty stack and would hence nil out a temp. We cannot let this
        # happen.
        # Problem: how do we tell the GC to collect outside self.stack_ptr()?
        #  self.stack_put(ptr, self.space.w_nil)
        assert ptr >= 0, "stack pointer got negative in pop"
        self.store_stack_ptr(ptr)
        return ret

    def push(self, w_v):
        ptr = jit.promote(self.stack_ptr())
        self.stack_put(ptr, w_v)
        self.store_stack_ptr(ptr + 1)

    @jit.unroll_safe
    def push_all(self, lst):
        for elt in lst:
            self.push(elt)

    def top(self):
        return self.peek(0)

    def set_top(self, value, position=0):
        ptr = self.stack_ptr() - position - 1
        self.stack_put(ptr, value)

    def peek(self, idx):
        ptr = jit.promote(self.stack_ptr()) - idx - 1
        return self.stack_get(ptr)

    @jit.unroll_safe
    def peek_n(self, n):
        result = [self.peek(i) for i in range(n - 1, -1, -1)]
        return result

    @jit.unroll_safe
    def pop_n(self, n):
        jit.promote(self.stack_ptr())
        while n > 0:
            n -= 1
            assert self.stack_ptr() >= 1, "stack pointer reduced to < 1 in pop_n"
            self.store_stack_ptr(self.stack_ptr() - 1)
            self.stack_put(self.stack_ptr(), self.space.w_nil)

    @jit.unroll_safe
    def pop_and_return_n(self, n):
        result = [self.peek(i) for i in range(n - 1, -1, -1)]
        self.pop_n(n)
        return result

    # ______________________________________________________________________
    # Primitive support

    def store_instances_array(self, w_class, match_w):
        # used for primitives 77 & 78
        if self.get_extra_data().instances_w is None:
            self.get_extra_data().instances_w = {}
        self.get_extra_data().instances_w[w_class] = match_w

    def instances_array(self, w_class):
        if self.get_extra_data().instances_w is None:
            return None
        else:
            return self.get_extra_data().instances_w.get(w_class, None)

    # ______________________________________________________________________
    # Printing

    def w_arguments(self):
        if self.pure_is_block_context():
            return self.w_arguments_block_context()
        else:
            return self.w_arguments_method_context()

    def method_str(self):
        if self.pure_is_block_context():
            return self.method_str_block_context()
        else:
            return self.method_str_method_context()

    def argument_strings(self):
        return [w_arg.as_repr_string() for w_arg in self.w_arguments()]

    def __str__(self):
        retval = self.short_str()
        retval += "\n%s" % self.w_method().bytecode_string(markBytecode=self.pc() + 1)
        retval += "\nArgs:----------------"
        argcount = self.w_method().argsize
        j = 0
        for w_obj in self._temps_and_stack[:self.stack_ptr()]:
            w_obj = self.space.w_nil if w_obj is None else w_obj
            if j == argcount:
                retval += "\nTemps:---------------"
            if j == self.tempsize():
                retval += "\nStack:---------------"
            retval += "\n  %0.2i: %s" % (j, w_obj.as_repr_string())
            j += 1
        retval += "\n---------------------"
        return retval

    def short_str(self):
        arg_strings = self.argument_strings()
        if len(arg_strings) > 0:
            args = " , ".join(arg_strings)
            args = " (%d arg(s): %s)" % (len(arg_strings), args)
        else:
            args = ""
        return '%s [pc: %d] (rcvr: %s)%s' % (
            self.method_str(),
            self.pc() + 1,
            self.w_receiver().as_repr_string(),
            args
        )

    def print_stack(self, method=True):
        return self.print_padded_stack(method)[1]

    def print_padded_stack(self, method):
        padding = ret_str = ''
        if self.has_s_sender():
            padding, ret_str = self.s_sender().print_padded_stack(method)
        if method:
            desc = self.method_str()
        else:
            desc = self.short_str()
        return padding + ' ', '%s\n%s%s' % (ret_str, padding, desc)

    def exitFromHeadlessExecution(self, selector="", w_message=None):
        if not objectmodel.we_are_translated():
            if getattr(self.space, "testing", False):
                return  # During Testing
            do_exit = True
            import pdb; pdb.set_trace()
            if not do_exit: # during debugging, we can change do_exit and go on
                return
        print "== Receiver: %s" % self.w_receiver().as_repr_string()
        if isinstance(w_message, W_PointersObject):
            fields = w_message.fetch_all(self.space)
            if len(fields) >= 1:
                print "== Selector: %s" % fields[0].selector_string()
            if len(fields) >= 2:
                w_args = fields[1]
                if isinstance(w_args, W_PointersObject):
                    arg_strings = [w_arg.selector_string() for w_arg in w_args.fetch_all(self.space)]
                    if len(arg_strings) > 0:
                        print "== Arguments: %s" % ', '.join(arg_strings)
        print "== Smalltalk Stack:%s" % self.print_stack()
        if selector == "":
            selector = self.w_method().lookup_selector
        raise error.Exit("Unhandled %s in headless mode." % selector)

class __extend__(ContextPartShadow):
    # Extensions for --- BlockContextShadow ---

    # === Initialization ===

    @staticmethod
    def build_block_context(space, s_home, argcnt, pc):
        size = s_home.own_size() - s_home.tempsize()
        w_self = W_PointersObject(space, space.w_BlockContext, size)

        ctx = ContextPartShadow(space, w_self, size, space.w_BlockContext)
        ctx.store_expected_argument_count(argcnt)
        ctx.store_w_home(s_home.w_self())
        ctx.store_initialip(pc)
        ctx.store_pc(pc)
        w_self.store_strategy(ctx)
        ctx.init_temps_and_stack()
        return ctx

    # === Implemented accessors ===

    def s_home_block_context(self):
        return self.get_extra_data()._w_home.as_context_get_shadow(self.space)

    def stackstart_block_context(self):
        return constants.BLKCTX_STACK_START

    def tempsize_block_context(self):
        # A blockcontext doesn't have any temps
        return 0

    def w_receiver_block_context(self):
        return self.s_home().w_receiver()

    def w_method_block_context(self):
        retval = self.s_home().w_method()
        assert isinstance(retval, W_CompiledMethod), "block context method is no W_CompiledMethod"
        return retval

    def is_closure_context_block_context(self):
        return True

    def home_is_self_block_context(self):
        return False

    # === Temporary variables ===

    def gettemp_block_context(self, index):
        return self.s_home().gettemp(index)

    def settemp_block_context(self, index, w_value):
        self.s_home().settemp(index, w_value)

    # === Accessing object fields ===

    def fetch_block_context(self, n0):
        if n0 == constants.BLKCTX_HOME_INDEX:
            return self.get_extra_data()._w_home
        if n0 == constants.BLKCTX_INITIAL_IP_INDEX:
            return self.wrap_initialip()
        if n0 == constants.BLKCTX_BLOCK_ARGUMENT_COUNT_INDEX:
            return self.wrap_eargc()
        else:
            return self.fetch_context_part(n0)

    def store_block_context(self, n0, w_value):
        if n0 == constants.BLKCTX_HOME_INDEX:
            return self.store_w_home(w_value)
        if n0 == constants.BLKCTX_INITIAL_IP_INDEX:
            return self.unwrap_store_initialip(w_value)
        if n0 == constants.BLKCTX_BLOCK_ARGUMENT_COUNT_INDEX:
            return self.unwrap_store_eargc(w_value)
        else:
            return self.store_context_part(n0, w_value)

    def store_w_home(self, w_home):
        assert isinstance(w_home, W_PointersObject), "trying to store non-pointer w_home"
        self.get_extra_data()._w_home = w_home

    def unwrap_store_initialip(self, w_value):
        initialip = self.space.unwrap_int(w_value)
        initialip -= 1 + self.w_method().literalsize
        self.store_initialip(initialip)

    def store_initialip(self, initialip):
        self.get_extra_data()._initialip = initialip

    def wrap_initialip(self):
        initialip = self.initialip()
        initialip += 1 + self.w_method().literalsize
        return self.space.wrap_smallint_unsafe(initialip)

    def reset_pc(self):
        self.store_pc(self.initialip())

    def initialip(self):
        return self.get_extra_data()._initialip

    def unwrap_store_eargc(self, w_value):
        self.store_expected_argument_count(self.space.unwrap_int(w_value))

    def wrap_eargc(self):
        return self.space.wrap_smallint_unsafe(self.expected_argument_count())

    def expected_argument_count(self):
        return self.get_extra_data()._eargc

    def store_expected_argument_count(self, argc):
        self.get_extra_data()._eargc = argc

    # === Stack Manipulation ===

    def reset_stack(self):
        self.pop_n(self.stackdepth())

    # === Printing ===

    def w_arguments_block_context(self):
        return []

    def method_str_block_context(self):
        return '[] in %s' % self.w_method().get_identifier_string()

class __extend__(ContextPartShadow):
    # Extensions for --- MethodContextShadow ---

    # === Initialization ===

    @staticmethod
    def build_method_context(space, w_method, w_receiver, arguments=[],
                             closure=None, s_fallback=None):
        w_method = jit.promote(w_method)
        size = w_method.compute_frame_size() + constants.MTHDCTX_TEMP_FRAME_START

        ctx = ContextPartShadow(space, None, size, space.w_MethodContext)
        if s_fallback is not None:
            ctx.get_extra_data()._s_fallback = s_fallback
        ctx.store_w_receiver(w_receiver)
        ctx.store_w_method(w_method)
        ctx.closure = closure
        ctx.init_temps_and_stack()
        ctx.initialize_temps(space, arguments)
        return ctx

    @jit.unroll_safe
    def initialize_temps(self, space, arguments):
        argc = len(arguments)
        for i0 in range(argc):
            w_arg = arguments[i0]
            if isinstance(w_arg, W_BlockClosure) and self.blockmethod is None:
                # If our first argument is a block, we use its home method to
                # distinguish the context from others that receive a different
                # block argument to the same method (e.g. so that all the
                # collection methods are specialized based on where the block
                # that was passed in came from
                self.blockmethod = w_arg.w_method()
            self.settemp(i0, w_arg)
        closure = self.closure
        if closure:
            startpc = jit.promote(closure.startpc())
            pc = startpc - self.w_method().bytecodeoffset() - 1
            self.store_pc(pc)
            for i0 in range(closure.varsize()):
                w_obj = closure.at0(space, i0)
                if isinstance(w_obj, W_BlockClosure) and self.blockmethod is None:
                    # for some methods (see Collection>>do: or detect:ifNone:)
                    # the user code passes in a block, and the block closure
                    # captures that block and is then called in a loop. So if we
                    # activate the block passed in from detect:ifNone: in the
                    # loop, we really want to specialize on the first temp of
                    # that block, which represents the block passed in from user
                    # code into detect:ifNone:
                    self.blockmethod = w_obj.w_method()
                self.settemp(i0+argc, w_obj)

    # === Accessing object fields ===

    def fetch_method_context(self, n0):
        if n0 == constants.MTHDCTX_METHOD:
            return self.w_method()
        if n0 == constants.MTHDCTX_CLOSURE_OR_NIL:
            if self.closure:
                return self.closure
            else:
                return self.space.w_nil
        if n0 == constants.MTHDCTX_RECEIVER:
            return self.w_receiver()
        temp_i = n0-constants.MTHDCTX_TEMP_FRAME_START
        if (0 <= temp_i < self.tempsize()):
            return self.gettemp(temp_i)
        else:
            return self.fetch_context_part(n0)

    def store_method_context(self, n0, w_value):
        if n0 == constants.MTHDCTX_METHOD:
            return self.store_w_method(w_value)
        if n0 == constants.MTHDCTX_CLOSURE_OR_NIL:
            if w_value.is_nil(self.space):
                self.closure = None
            else:
                if not isinstance(w_value, W_BlockClosure):
                    raise error.PrimitiveFailedError
                self.closure = w_value
            return
        if n0 == constants.MTHDCTX_RECEIVER:
            self.store_w_receiver(w_value)
            return
        temp_i = n0-constants.MTHDCTX_TEMP_FRAME_START
        if (0 <= temp_i < self.tempsize()):
            return self.settemp(temp_i, w_value)
        else:
            return self.store_context_part(n0, w_value)

    def store_w_receiver(self, w_receiver):
        self._w_receiver = w_receiver

    # === Implemented Accessors ===

    def s_home_method_context(self):
        if self.is_closure_context():
            # this is a context for a blockClosure
            w_outerContext = self.closure.w_outerContext()
            assert isinstance(w_outerContext, W_PointersObject), "outer context is no pointers object"
            s_outerContext = w_outerContext.as_context_get_shadow(self.space)
            # XXX check whether we can actually return from that context
            if s_outerContext.is_returned():
                raise error.BlockCannotReturnError()
            return s_outerContext.s_home()
        else:
            return self

    def stackstart_method_context(self):
        return constants.MTHDCTX_TEMP_FRAME_START

    def store_w_method(self, w_method):
        assert isinstance(w_method, W_CompiledMethod), "trying to store method that is not a W_CompiledMethod"
        self._w_method = w_method

    def w_receiver_method_context(self):
        return self._w_receiver

    def w_method_method_context(self):
        retval = self._w_method
        assert isinstance(retval, W_CompiledMethod), "method context method is not a W_CompiledMethod"
        return retval

    def tempsize_method_context(self):
        if not self.is_closure_context():
            return self.w_method().tempsize()
        else:
            return self.closure.tempsize()

    def is_closure_context_method_context(self):
        return self.closure is not None

    def home_is_self_method_context(self):
        return not self.is_closure_context()

    # ______________________________________________________________________
    # Marriage of MethodContextShadows with PointerObjects only when required

    def w_self(self):
        if self._w_self is not None:
            return self._w_self
        else:
            space = self.space
            w_self = W_PointersObject(space, space.w_MethodContext, self._w_self_size)
            w_self.store_strategy(self)
            self._w_self = w_self
            return w_self

    # === Temporary variables ===

    def gettemp_method_context(self, index0):
        return self.stack_get(index0)

    def settemp_method_context(self, index0, w_value):
        self.stack_put(index0, w_value)

    # === Printing ===

    def w_arguments_method_context(self):
        argcount = self.w_method().argsize
        return [self.stack_get(i) for i in range(argcount)]

    def method_str_method_context(self):
        block = '[] in ' if self.is_closure_context() else ''
        return '%s%s' % (block, self.w_method().get_identifier_string())

ContextPartShadow.instantiate_type = ContextPartShadow


text:
//
// IQUIViewController+Additions.h
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <UIKit/UIViewController.h>

@class NSLayoutConstraint;

@interface UIViewController (Additions)

/**
 This method is provided to override by viewController's if the library lifts a viewController which you doesn't want to lift . This may happen if you have implemented side menu feature in your app and the library try to lift the side menu controller. Overriding this method in side menu class to return correct controller should fix the problem.
*/
-(nullable UIViewController*)parentIQContainerViewController;

/**
 Top/Bottom Layout constraint which help library to manage keyboardTextField distance

 @deprecated    Due to change in core-logic of handling distance between textField and keyboard distance, this layout contraint tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview.
*/
@property(nullable, nonatomic, strong) IBOutlet NSLayoutConstraint *IQLayoutGuideConstraint __attribute__((deprecated("Due to change in core-logic of handling distance between textField and keyboard distance, this layout contraint tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview.")));

@end

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <string name="app_name">ArduWrap_sample</string>
</resources>


text:
--Create the Select Proc
CREATE PROCEDURE [dbo].[app_SurveyQuestion_GetByID] @QID INT
AS
SELECT *
FROM [SurveyQuestion]
WHERE QID = @QID


text:
<!DOCTYPE html>

	<title>UI Integration with Cards</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

	<link rel="stylesheet" href="./css/index.css">
	<link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">
	<link rel="icon" type="image/x-icon" href="images/favicon.ico">

UI Integration with Cards

The new way for developers, key users, and end users to create and
					share
					business content in an easy, declarative, and consistent way.

					Open Card Explorer

Declarative

Based on JSON schema. Design-time and runtime tooling support. Portable to any device and host
						environment.
						Rich feature set.

Consistent

SAP Fiori design language and customer theming. Accessible. All enterprise product
						standards included.

Easy To Consume

UI5, Custom Element and Web Component support. Included JSON-based data consumption. Configurable
						styling.
						Speech and bot support.

Easy card integration in just two steps...

1

Define a cards manifest.json file

										With the manifest.json you define the cards header and content.
										You can use static data to be displayed, or define a request object for your
										data endpoint.
										Translations for static texts on the card, such as the title and subtitle, can
										be provided in separate files.

{
  "sap.card": {
    "type": "Object",
    "header": {
      "icon": {
        "src": "../images/Sabine_Mayer.png"
      },
      "title": "Sabine Mayer",
      "subTitle": "Executive Assistant"
    },
    "content": {
      "groups": [
        {
          "title": "Contact Details",
          "items": [
            {
              "label": "Mobile",
              "value": "+001 6101 34869-0",
              "actions": [
                {
                  "type": "Navigation",
                  "parameters": {
                    "url": "tel:+001 6101 34869-0"
                  }
                }
              ]
            },
            {
              "label": "Phone",
              "value": "+001 4231 5424 0231",
              "actions": [
                {
                  "type": "Navigation",
                  "parameters": {
                    "url": "tel:+001 4231 5424 0231"
                  }
                }
              ]
            },
            {
              "label": "Email",
              "value": "sabine@cardadventure.com",
              "actions": [
                {
                  "type": "Navigation",
                  "parameters": {
                    "url": "mailto:sabine@cardadventure.com"
                  }
                }
              ]
            }
          ]
        },
        {
          "title": "Company Details",
          "items": [
            {
              "label": "Direct Manager",
              "value": "Michael Adams",
              "icon": {
                "src": "../images/Michael_Adams.png"
              }
            },
            {
              "label": "Phone",
              "value": "+001 4242 4242 0873",
              "actions": [
                {
                  "type": "Navigation",
                  "parameters": {
                    "url": "tel:+001 4242 4242 0873"
                  }
                }
              ]
            },
            {
              "label": "Email",
              "value": "madams@cardadventure.com",
              "actions": [
                {
                  "type": "Navigation",
                  "parameters": {
                    "url": "mailto:madams@cardadventure.com"
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  }
}

2

Consume the card in your site

										To enable any html page to consume cards, just use

										<ui-integration-card> tag which will be served from the provided
										minimalistic sap-ui-integration.js bundle.

<html>
  <head>
    <script
      id="sap-ui-bootstrap"
      src="https://ui5.sap.com/resources/sap-ui-integration.js"
      data-sap-ui-compatVersion="edge">
    </script>
  </head>
  <body>
    ...
    <ui-integration-card
       manifest="../manifest.json">
    </ui-integration-card>
  </body>
</html>

Done

								Launch your page and see the result.

							<ui-integration-card style="text-align: left;"
								manifest="./manifests/objectcard.manifest.json"></ui-integration-card>

Get the insights

Learn. Explore. Design. Integrate.

								Card Explorer

Get involved

Explore the source code and samples. Contribute. Report
								issues.

							OpenUI5
								Project

						Framework Compatibility

UI Integration Cards are framework-agnostic and can run with arbitrary HTML framework or page

						Browser Compatibility

UI Integration Cards are supported on all modern browsers out of the box

Community

						Twitter
						YouTube
						Slack Channel
						GitHub

Docs

						Documentation
						Explorer
						FAQ

Legal & Privacy

						Legal Disclosure
						Privacy

Contact Us

						Report Issue
						Contact Us


text:
using System;

namespace Cassandra.Serialization
{
    /// <summary>
    /// Serializer that handles any protocol version.
    /// </summary>
    internal interface IGenericSerializer
    {
        object Deserialize(ProtocolVersion version, byte[] buffer, int offset, int length, ColumnTypeCode typeCode, IColumnInfo typeInfo);

        byte[] Serialize(ProtocolVersion version, object value);

        Type GetClrType(ColumnTypeCode typeCode, IColumnInfo typeInfo);

        Type GetClrTypeForGraph(ColumnTypeCode typeCode, IColumnInfo typeInfo);

        Type GetClrTypeForCustom(IColumnInfo typeInfo);

        ColumnTypeCode GetCqlType(Type type, out IColumnInfo typeInfo);

        /// <summary>
        /// Performs a lightweight validation to determine if the source type and target type matches.
        /// It isn't more strict to support miscellaneous uses of the driver, like direct inputs of blobs and all that. (backward compatibility)
        /// </summary>
        bool IsAssignableFrom(CqlColumn column, object value);

        UdtMap GetUdtMapByName(string name);

        UdtMap GetUdtMapByType(Type type);
    }
}


text:
@interface SQUMidiDeviceController : NSObject {
	MIDIClientRef _client;
	MIDIEndpointRef _endpoint;
}

@end


text:
package io.permazen.kv.fdb;

import com.apple.foundationdb.KeyValue;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.Range;
import com.apple.foundationdb.ReadTransaction;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.async.AsyncIterator;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
import com.google.common.primitives.Bytes;

import io.permazen.kv.KVPair;
import io.permazen.kv.KVStore;
import io.permazen.util.ByteUtil;
import io.permazen.util.CloseableIterator;

import java.util.concurrent.ExecutionException;

import javax.annotation.concurrent.ThreadSafe;

/**
 * A {@link KVStore} view of a FoundationDB {@link Transaction}.
 */
@ThreadSafe
public class FoundationKVStore implements KVStore {

    private static final byte[] MIN_KEY = ByteUtil.EMPTY;                   // minimum possible key (inclusive)
    private static final byte[] MAX_KEY = new byte[] { (byte)0xff };        // maximum possible key (exclusive)

    private final Transaction tx;
    private final byte[] keyPrefix;

    /**
     * Constructor.
     *
     * @param tx FDB transaction; note, caller is responsible for closing this
     * @param keyPrefix key prefix, or null for none
     */
    public FoundationKVStore(Transaction tx, byte[] keyPrefix) {
        Preconditions.checkArgument(tx != null, "null tx");
        this.tx = tx;
        this.keyPrefix = keyPrefix != null ? keyPrefix.clone() : null;
    }

    /**
     * Get the underlying {@link Transaction} associated with this instance.
     *
     * @return the associated transaction
     */
    public Transaction getTransaction() {
        return this.tx;
    }

    /**
     * Get the key prefix associated with this instance, if any.
     *
     * @return the associated key prefix, or null for none
     */
    public byte[] getKeyPrefix() {
        return this.keyPrefix != null ? this.keyPrefix.clone() : null;
    }

// KVStore

    @Override
    public byte[] get(byte[] key) {
        Preconditions.checkArgument(key.length == 0 || key[0] != (byte)0xff, "key starts with 0xff");
        try {
            return this.tx.get(this.addPrefix(key)).get();
        } catch (ExecutionException e) {
            throw e.getCause() instanceof RuntimeException ? (RuntimeException)e.getCause() : new RuntimeException(e.getCause());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public KVPair getAtLeast(byte[] minKey, byte[] maxKey) {
        if (minKey != null && minKey.length > 0 && minKey[0] == (byte)0xff)
            return null;
        return this.getFirstInRange(minKey, maxKey, false);
    }

    @Override
    public KVPair getAtMost(byte[] maxKey, byte[] minKey) {
        if (maxKey != null && maxKey.length > 0 && maxKey[0] == (byte)0xff)
            maxKey = null;
        return this.getFirstInRange(minKey, maxKey, true);
    }

    @Override
    public CloseableIterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse) {
        if (minKey != null && minKey.length > 0 && minKey[0] == (byte)0xff)
            minKey = MAX_KEY;
        if (maxKey != null && maxKey.length > 0 && maxKey[0] == (byte)0xff)
            maxKey = null;
        Preconditions.checkArgument(minKey == null || maxKey == null || ByteUtil.compare(minKey, maxKey) <= 0, "minKey > maxKey");
        final AsyncIterator<KeyValue> i = this.tx.getRange(
          this.addPrefix(minKey, maxKey), ReadTransaction.ROW_LIMIT_UNLIMITED, reverse).iterator();
        return CloseableIterator.wrap(
          Iterators.transform(i, kv -> new KVPair(this.removePrefix(kv.getKey()), kv.getValue())),
          i instanceof AutoCloseable ? (AutoCloseable)i : (AutoCloseable)i::cancel);
    }

    private KVPair getFirstInRange(byte[] minKey, byte[] maxKey, boolean reverse) {
        final AsyncIterator<KeyValue> i = this.tx.getRange(
          this.addPrefix(minKey, maxKey), ReadTransaction.ROW_LIMIT_UNLIMITED /* 1? */, reverse).iterator();
        try {
            if (!i.hasNext())
                return null;
            final KeyValue kv = i.next();
            return new KVPair(this.removePrefix(kv.getKey()), kv.getValue());
        } finally {
            i.cancel();
        }
    }

    @Override
    public void put(byte[] key, byte[] value) {
        Preconditions.checkArgument(key.length == 0 || key[0] != (byte)0xff, "key starts with 0xff");
        this.tx.set(this.addPrefix(key), value);
    }

    @Override
    public void remove(byte[] key) {
        Preconditions.checkArgument(key.length == 0 || key[0] != (byte)0xff, "key starts with 0xff");
        this.tx.clear(this.addPrefix(key));
    }

    @Override
    public void removeRange(byte[] minKey, byte[] maxKey) {
        if (minKey != null && minKey.length > 0 && minKey[0] == (byte)0xff)
            return;
        if (maxKey != null && maxKey.length > 0 && maxKey[0] == (byte)0xff)
            maxKey = null;
        Preconditions.checkArgument(minKey == null || maxKey == null || ByteUtil.compare(minKey, maxKey) <= 0, "minKey > maxKey");
        this.tx.clear(this.addPrefix(minKey, maxKey));
    }

    @Override
    public byte[] encodeCounter(long value) {
        return FoundationKVDatabase.encodeCounter(value);
    }

    @Override
    public long decodeCounter(byte[] bytes) {
        return FoundationKVDatabase.decodeCounter(bytes);
    }

    @Override
    public void adjustCounter(byte[] key, long amount) {
        this.tx.mutate(MutationType.ADD, this.addPrefix(key), this.encodeCounter(amount));
    }

// Key prefixing

    byte[] addPrefix(byte[] key) {
        return this.keyPrefix != null ? Bytes.concat(this.keyPrefix, key) : key;
    }

    Range addPrefix(byte[] minKey, byte[] maxKey) {
        if (this.keyPrefix == null && maxKey != null && maxKey.length > 1 && maxKey[0] == (byte)0xff)
            maxKey = MAX_KEY;
        return new Range(this.addPrefix(minKey != null ? minKey : MIN_KEY), this.addPrefix(maxKey != null ? maxKey : MAX_KEY));
    }

    byte[] removePrefix(byte[] key) {
        if (this.keyPrefix == null)
            return key;
        if (!ByteUtil.isPrefixOf(this.keyPrefix, key)) {
            throw new IllegalArgumentException("read key " + ByteUtil.toString(key) + " not having "
              + ByteUtil.toString(this.keyPrefix) + " as a prefix");
        }
        final byte[] stripped = new byte[key.length - this.keyPrefix.length];
        System.arraycopy(key, this.keyPrefix.length, stripped, 0, stripped.length);
        return stripped;
    }
}


text:
package liquibase.database.structure.type;

public class UUIDType extends DataType {
    public UUIDType() {
        super("CHAR(36)",0,0);
    }

    public UUIDType(String dataTypeName) {
        super(dataTypeName,0,0);
    }
}


text:
/********************************************************************************/
/* Copyright (c) 2004                                                           */
/* Daniel Sleator, David Temperley, and John Lafferty                           */
/* All rights reserved                                                          */
/*                                                                              */
/* Use of the link grammar parsing system is subject to the terms of the        */
/* license set forth in the LICENSE file included with this software,           */
/* and also available at http://www.link.cs.cmu.edu/link/license.html           */
/* This license allows free redistribution and use in source and binary         */
/* forms, with or without modification, subject to certain conditions.          */
/*                                                                              */
/********************************************************************************/

#include "link-includes.h"

int contains_underbar(char * s) {
    /* Returns TRUE if the string contains an underbar character.
     */
    while(*s != '\0') {
	if (*s == '_') return TRUE;
	s++;
    }
    return FALSE;
}

int is_idiom_string(char * s) {
    /* Returns FALSE if it is not a correctly formed idiom string.
       correct such string:
       () contains no "."
       () non-empty strings separated by _
       */
    char * t;
    for (t=s; *t != '\0'; t++) {
	if (*t == '.') {
	    return FALSE;
	}
    }
    if ((s[0] == '_') || (s[strlen(s)-1] == '_')) {
	return FALSE;
    }
    for (t=s; *t != '\0'; t++) {
	if ((*t == '_') && (*(t+1) == '_')) {
	    return FALSE;
	}
    }
    return TRUE;
}

int is_number(char *s) {
    /* return TRUE if the string s is a sequence of digits. */
    while(*s != '\0') {
	if (!isdigit((int)*s)) return FALSE;
	s++;
    }
    return TRUE;
}

int numberfy(char * s) {
    /* if the string contains a single ".", and ends in ".Ix" where
       x is a number, return x.  Return -1 if not of this form.
       */
    for (; (*s != '\0') && (*s != '.'); s++)
      ;
    if (*s++ != '.') return -1;
    if (*s++ != 'I') return -1;
    if (!is_number(s)) return -1;
    return atoi(s);
}

int max_postfix_found(Dict_node * d) {
    /* Look for words that end in ".Ix" where x is a number.
       Return the largest x found.
       */
    int i, j;
    i = 0;
    while(d != NULL) {
	j = numberfy(d->string);
	if (j > i) i = j;
	d = d->right;
    }
    return i;
}

char * build_idiom_word_name(Dictionary dict, char * s) {
    /* Allocates string space and returns a pointer to it.
       In this string is placed the idiomized name of the given string s.
       This is the same as s, but with a postfix of ".Ix", where x is an
       appropriate number.  x is the minimum number that distinguishes
       this word from others in the dictionary.
       */
    char * new_s, * x, *id;
    int count, sz;

    count = max_postfix_found(dictionary_lookup(dict, s))+1;

    sz = strlen(s)+10;
    new_s = x = (char *) xalloc(sz); /* fails if > 10**10 idioms */
    while((*s != '\0') && (*s != '.')) {
	*x = *s;
	x++;
	s++;
    }
    sprintf(x,".I%d",count);

    id = string_set_add(new_s, dict->string_set);
    xfree(new_s, sz);
    return id;
}

Dict_node * make_idiom_Dict_nodes(Dictionary dict, char * string) {
    /* Tear the idiom string apart.
       Destroys the string s, but does not free it.
       Put the parts into a list of Dict_nodes (connected by their right pointers)
       Sets the string fields of these Dict_nodes pointing to the
       fragments of the string s.  Later these will be replaced by
       correct names (with .Ix suffixes).
       The list is reversed from the way they occur in the string.
       A pointer to this list is returned.
       */
    Dict_node * dn, * dn_new;
    char * t, *s, *p;
    int more, sz;
    dn = NULL;

    sz = strlen(string)+1;
    p = s = xalloc(sz);
    strcpy(s, string);

    while (*s != '\0') {
	t = s;
    	while((*s != '\0') && (*s != '_')) s++;
	if (*s == '_') {
	    more = TRUE;
	    *s = '\0';
	} else {
	    more = FALSE;
	}
	dn_new = (Dict_node *) xalloc(sizeof (Dict_node));
	dn_new->right = dn;
	dn = dn_new;
	dn->string = string_set_add(t, dict->string_set);
	dn->file = NULL;
	if (more) s++;
    }

    xfree(p, sz);
    return dn;
}

static char current_name[] = "AAAAAAAA";
#define CN_size (sizeof(current_name)-1)

void increment_current_name(void) {
    int i, carry;
    i = CN_size-1;
    carry = 1;
    while (carry == 1) {
	current_name[i]++;
	if (current_name[i] == 'Z'+1) {
	    current_name[i] = 'A';
	    carry = 1;
	} else {
	    carry = 0;
	}
	i--;
    }
}

char * generate_id_connector(Dictionary dict) {
    /* generate a new connector name
       obtained from the current_name
       allocate string space for it.
       return a pointer to it.
     */
    int i, sz;
    char * t, * s, *id;

    for (i=0; current_name[i] == 'A'; i++)
      ;
    /* i is now the number of characters of current_name to skip */
    sz = CN_size - i + 2 + 1 + 1;
    s = t = (char *) xalloc(sz);
    *t++ = 'I';
    *t++ = 'D';
    for (; i < CN_size; i++ ) {
	*t++ = current_name[i] ;
    }
    *t++ = '\0';
    id = string_set_add(s, dict->string_set);
    xfree(s, sz);
    return id;
}

void insert_idiom(Dictionary dict, Dict_node * dn) {
    /* Takes as input a pointer to a Dict_node.
       The string of this Dict_node is an idiom string.
       This string is torn apart, and its components are inserted into the
       dictionary as special idiom words (ending in .I*, where * is a number).
       The expression of this Dict_node (its node field) has already been
       read and constructed.  This will be used to construct the special idiom
       expressions.
       The given dict node is freed.  The string is also freed.
       */
    Exp * nc, * no, * n1;
    E_list *ell, *elr;
    char * s;
    int s_length;
    Dict_node * dn_list, * xdn, * start_dn_list;

    no = dn->exp;
    s = dn->string;
    s_length = strlen(s);

    if (!is_idiom_string(s)) {
	printf("*** Word \"%s\" on line %d is not",s, dict->line_number);
	printf(" a correctly formed idiom string.\n");
	printf("    This word will be ignored\n");
	/* xfree((char *)s, s_length+1);  strings are handled now by string_set */
	xfree((char *)dn, sizeof (Dict_node));
	return;
    }

    dn_list = start_dn_list = make_idiom_Dict_nodes(dict, s);
    xfree((char *)dn, sizeof (Dict_node));

    if (dn_list->right == NULL) {
      error("Idiom string with only one connector -- should have been caught");
    }

    /* first make the nodes for the base word of the idiom (last word) */
    /* note that the last word of the idiom is first in our list */

    /* ----- this code just sets up the node fields of the dn_list ----*/
    nc = Exp_create(dict);
    nc->u.string = generate_id_connector(dict);
    nc->dir = '-';
    nc->multi = FALSE;
    nc->type = CONNECTOR_type;
    nc->cost = 0;

    n1 = Exp_create(dict);
    n1->u.l = ell = (E_list *) xalloc(sizeof(E_list));
    ell->next = elr = (E_list *) xalloc(sizeof(E_list));
    elr->next = NULL;
    ell->e = nc;
    elr->e = no;
    n1->type = AND_type;
    n1->cost = 0;

    dn_list->exp = n1;

    dn_list = dn_list->right;

    while(dn_list->right != NULL) {
	/* generate the expression for a middle idiom word */

	n1 = Exp_create(dict);
	n1->u.string = NULL;
	n1->type = AND_type;
	n1->cost = 0;
	n1->u.l = ell = (E_list *) xalloc(sizeof(E_list));
	ell->next = elr = (E_list *) xalloc(sizeof(E_list));
	elr->next = NULL;

	nc = Exp_create(dict);
	nc->u.string = generate_id_connector(dict);
	nc->dir = '+';
	nc->multi = FALSE;
	nc->type = CONNECTOR_type;
	nc->cost = 0;
	elr->e = nc;

	increment_current_name();

	nc = Exp_create(dict);
	nc->u.string = generate_id_connector(dict);
	nc->dir = '-';
	nc->multi = FALSE;
	nc->type = CONNECTOR_type;
	nc->cost = 0;

	ell->e = nc;

	dn_list->exp = n1;

	dn_list = dn_list->right;
    }
    /* now generate the last one */

    nc = Exp_create(dict);
    nc->u.string = generate_id_connector(dict);
    nc->dir = '+';
    nc->multi = FALSE;
    nc->type = CONNECTOR_type;
    nc->cost = 0;

    dn_list->exp = nc;

    increment_current_name();

    /* ---- end of the code alluded to above ---- */

    /* now its time to insert them into the dictionary */

    dn_list = start_dn_list;

    while (dn_list != NULL) {
	xdn = dn_list->right;
	dn_list->left = dn_list->right = NULL;
        dn_list->string = build_idiom_word_name(dict, dn_list->string);
	dict->root = insert_dict(dict, dict->root, dn_list);
	dict->num_entries++;
	dn_list = xdn;
    }
    /* xfree((char *)s, s_length+1); strings are handled by string_set */
}

int is_idiom_word(char * s) {
    /* returns TRUE if this is a word ending in ".Ix", where x is a number. */
    return (numberfy(s) != -1) ;
}

/*
  int only_idiom_words(Dict_node * dn) {
  returns TRUE if the list of words contains only words that are
  idiom words.  This is useful, because under this condition you want
   to be able to insert the word anyway, as long as it doesn't match
   exactly.

    while(dn != NULL) {
	if (!is_idiom_word(dn->string)) return FALSE;
	dn = dn->right;
    }
    return TRUE;
}
*/


text:
class EmailRetrievalService
  def initialize(user)
    @user = user
    @gmail = Gmail.connect(:xoauth2, user.email, user.oauth_token)
  end

  def retrieve_emails(partner)
    emails = @gmail.inbox.emails(from: partner.email).last(10)
    save_emails(partner, emails)
    emails
  end

  def save_emails(partner, emails)
    emails.each do |email|
      new_email = Email.new(user_id: @user.id, partner_id: partner.id)
      new_email.update(subject: email.subject, text: clean_email_text(email), sent_at: email.date)
    end
  end

  def clean_email_text(email)
    body = email.text_part ? email.text_part.body.raw_source : email.body.decoded
    text = ActionView::Base.full_sanitizer.sanitize(body)
    only_text = remove_image(text)
    shortened_text = shorten_text(only_text)
    cleaned_headers = remove_headings(shortened_text)
    cleaned_spaces = remove_spaces(cleaned_headers)
    cleaned_text = remove_numbers(cleaned_spaces)
    return RbLibText.tokens(cleaned_text).join(" ")
  end

  def remove_image(text)
    text =~ /Content-Type: image\/jpeg/ ? '' : text
  end

  def shorten_text(text)
    text.truncate(200000)
  end

  def remove_headings(text)
    text.gsub(/.*Content-Transfer-Encoding/,'').gsub(/.*Content-Type.*[uUtTfF]-8/,'').gsub(/ application\/pdf.*/,'').gsub(/Content-Disposition.*/,'')
  end

  def remove_spaces(text)
    text.gsub(/\\n/,'')
  end

  def remove_numbers(text)
    text.gsub(/--.?\d*/,'')
  end

end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Vila</tipo><logradouro>Olga</logradouro><bairro>Esplanada</bairro><cidade>Caratinga</cidade><uf>MG</uf><cep>35300242</cep></feed>


text:
<resources>
    <string name="app_name">EMA</string>
    <string name="title_activity_take_photo">TakePhotoActivity</string>

    <string name="action_settings">Configurações</string>
    <string name="title_activity_create_text">CreateTextActivity</string>

    <string name="save">Salvar</string>
    <string name="saved">Salvo</string>
    <string name="cancel">Cancelar</string>
    <string name="turnOn">Ligar</string>
    <string name="turnOff">Desligar</string>
    <string name="sound">Som</string>
    <string name="ok">OK</string>
    <string name="you">Você</string>
    <string name="made">fez</string>
    <string name="points">ponto(s)</string>
    <string name="noWordsMessage">Este usuário não possui atividade cadastrada. Por favor Contate o Administrador</string>
    <string name="NeedUserWords">Precisa de usuário(s) e palavra(s)</string>
    <string name="title_activity_receive_text">ReceivTextActivity</string>
    <string name="playedActivities">Atividades jogadas</string>
    <string name="highestPointing">Pontuação mais alta</string>
    <string name="lowestPointing">Pontuação mais baixa</string>
    <string name="Points">Ponto(s)</string>
    <string name="Choose_an_user">Escolha um usuário</string>

    <string name="title_activity_menu">EMA</string>

    <!-- Menu -->
    <string name="messages">Palavras</string>
    <string name="title_activity_photo_intent">PhotoIntentActivity</string>
    <string name="menu">Menu</string>
    <!-- Camera -->
    <string name="newPhoto">Nova Foto</string>
    <string name="Photo">Foto</string>
    <string name="cannot">Não pode</string>
    <string name="album_name">MeuABCAlbum</string>

    <string name="speech_toggle_on">Falar</string>
    <string name="speech_toggle_off">Falar</string>

    <string name="add">Adicionar</string>
    <string name="edit">Editar</string>
    <string name="delete">Remover</string>
    <string name="start_speaking">Start</string>
    <!--<string name="stop_speaking">Parar fala</string>-->
    <string name="title_activity_drag_and_drop">DragAndDropActivity</string>

    <string name="hello_world">Hello world!</string>

    <string name="next">próximo</string>
    <string name="information">informações</string>
    <string name="clear"><</string>
    <string name="try_again">Tente novamente...</string>
    <string name="wrong">Errou</string>
    <string name="build_the_words">Construa a palavra</string>
    <string name="correct">Correto!</string>
    <string name="play">Jogar</string>
    <string name="finish">Terminar</string>
    <string name="deleteWord">Excluir Palavra</string>

    <string name="image">Imagem</string>
    <string name="newWord">Adicionar palavra</string>

    <string name="name">Nome</string>
    <string name="users">Usuários</string>
    <string name="settings">Configurações</string>
    <string name="newUser">Novo Usuário</string>
    <string name="deleteUsers">Remover Usuário(s)</string>
    <string name="updateData">Editar dados</string>
    <string name="goBack">Voltar</string>
    <string name="words">Palavras</string>
    <string name="Word">Palavra</string>
    <string name="wordAudio">Audio da palavra</string>
    <string name="onlyOneToEdit">Marque somente um usuário para editar</string>
    <string name="checkOneToEdit">Escolha um usuário para editar</string>
    <string name="dataAnalysis">Análise de dados</string>
    <string name="wasCreated">foi criado(a).</string>
    <string name="wasUpdated">foi atualizado.</string>

    <string name="noData">Sem dados.</string>

    <string name="level">Dificuldade</string>
    <string name="levelEasy">Fácil</string>
    <string name="levelIntermediate">Intermediário</string>
    <string name="levelHard">Difícil</string>

    <string name="language">Idioma</string>
    <string name="portuguese">Português</string>
    <string name="english">Inglês</string>

    <string name="password">Senha</string>
    <string name="activities">Atividades</string>

    <string name="checkDataTyped">Verifique os dados digitados</string>
    <string name="areYouSure">Tem certeza?</string>

    <string name="login">Entrar</string>
    <string name="logout">   Sair   </string>

    <string name="stats">  Estatísticas  </string>
    <!-- Colors -->
    <color name="white">#FFFFFF</color>
    <color name="blue">#1887C7</color>
    <color name="red">#E60E0E</color>
    <color name="green">#83BF25</color>
    <color name="black">#000000</color>
    <color name="gray">#E0E0E0</color>

    <string name="title_activity_build_challenges">BuildChallengesActivity</string>
    <string name="title_activity_play_challenges">PlayChallengesActivity</string>
    <string name="title_activity_scrabble">ScrabbleActivity</string>
    <string name="title_activity_abc">ABCActivity</string>
    <string name="title_activity_profiles">ProfilesActivity</string>
    <string name="title_activity_data_analysis">DataAnalysisActivity</string>
    <string name="title_activity_user">UserActivity</string>
    <string name="title_activity_initial_loading">InitialLoadingActivity</string>
    <string name="title_activity_admin_form">AdminFormActivity</string>
    <string name="title_activity_stats">StatsActivity</string>
    <string name="deleteUser">Remover Usuário</string>
    <string name="updateUser">Atualizar Usuário</string>
    <string name="showWord">Mostrar palavra</string>
    <string name="Yes">Sim</string>
    <string name="No">Não</string>
    <string name="ChooseAnotherNameAdm">Escolha outro nome, este é o nome do administrador.</string>
    <string name="ChooseAnotherName">Escolha outro nome.</string>
    <string name="imageOf">Imagem de </string>
    <string name="logo">Logo</string>
    <string name="comma">,</string>
    <string name="keySpace">          </string>
    <string name="erase">apagar</string>
    <string name="zero">0</string>
    <string name="rotate">girar</string>
    <string name="blank"></string>
    <string name="tutorial_admin_form1">Bem Vindo!</string>
    <string name="tutorial_admin_form2">Primeiro defina os dados do usuário administrador</string>
    <string name="tutorial_admin_form3">Defina o nome do usuário. Exemplo: admin</string>
    <string name="tutorial_admin_form4">Defina a senha do usuário. utilize mais de 6 caracteres</string>
    <string name="tutorial_admin_form5">Adicione um email para recuperar a senha de Administrador se necessário.</string>
    <string name="tutorial_admin_form6">Então clique em salvar.</string>
    <string name="noStats">Sem estatísticas no momento.</string>
    <string name="Email">Email</string>
    <string name="anEmailWillbeSend">Um email será enviado.</string>
    <string name="title_activity_new_admin_password">NewAdminPassword</string>
    <string name="ConfirmPassword">Confirmar Senha</string>
    <string name="newPassword">Nova Senha</string>
    <string name="ChangingPassword">Mudando Senha</string>
    <string name="YourNewPasswordIs">Sua nova senha é</string>
    <string name="invalidEmail">E-mail inválido.</string>
    <string name="passwordWithLessThan6">Senha com menos de 6 caracteres.</string>
    <string name="DifferentPasswords">Senhas Diferentes.</string>
</resources>


text:
//Problem 8. Maximal sum
//Write a program that finds the sequence of maximal sum in given array.
//Example:
//input 	                                       result
//2, 3, -6, -1, 2, -1, 6, 4, -8, 8 	              2, -1, 6, 4
//Can you do it with only one loop (with single scan through the elements of the array)?

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] arr = Console.ReadLine().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
        int[] nums = new int[arr.Length];
        //string[] letters = new string[input.Length];
        for (int i = 0; i < arr.Length; i++)
        {
            nums[i] = int.Parse(arr[i]);
        }
        int sum = 0;
        int bestSum = 0;
        int startIndex = new int();
        int endIndex = new int();
        // One scan
        for (int i = 0; i < nums.Length; i++)
        {
            for (int j = i; j < nums.Length; j++)
            {
                sum += nums[j];
                if (sum > bestSum)
                {
                    startIndex = i;
                    endIndex = j;
                    bestSum = sum;
                }
            }
            sum = 0;
        }
        // Printing
        for (int i = startIndex; i <= endIndex; i++)
        {
            Console.Write(nums[i] + " ");
        }
        Console.WriteLine();
        Console.Write("SUM: " + bestSum);
        Console.ReadLine();
    }
}


text:
@interface RNHawk : NSObject<RCTBridgeModule>

@end


text:
import django
from django.db.models.sql import compiler
from django.utils.six.moves import zip_longest

class SQLCompiler(compiler.SQLCompiler):
    def resolve_columns(self, row, fields=()):
        values = []
        index_extra_select = len(self.query.extra_select)
        bool_fields = ("BooleanField", "NullBooleanField")
        for value, field in zip_longest(row[index_extra_select:], fields):
            if (field and field.get_internal_type() in bool_fields and
                    value in (0, 1)):
                value = bool(value)
            values.append(value)
        return row[:index_extra_select] + tuple(values)

    def as_subquery_condition(self, alias, columns, qn):
        # Django 1.6
        qn2 = self.connection.ops.quote_name
        sql, params = self.as_sql()
        column_list = ', '.join(
            ['%s.%s' % (qn(alias), qn2(column)) for column in columns])
        return '({0}) IN ({1})'.format(column_list, sql), params

class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
    pass

class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
    pass

class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
    pass

class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
    pass

class SQLDateCompiler(compiler.SQLDateCompiler, SQLCompiler):
    pass

if django.VERSION >= (1, 6):
    class SQLDateTimeCompiler(compiler.SQLDateTimeCompiler, SQLCompiler):
        # Django 1.6
        pass


text:
package models;

import com.fasterxml.jackson.annotation.JsonView;
import views.SchoolViews;

/**
 * Created by aserafin on 26/11/15.
 */

public class School {
    @JsonView(SchoolViews.Base.class)
    public Integer id;

    @JsonView(SchoolViews.Base.class)
    public String name;

    @JsonView(SchoolViews.Full.class)
    public String address;

    @JsonView(SchoolViews.Full.class)
    public String postCode;

    @JsonView(SchoolViews.Full.class)
    public String post;

    @JsonView(SchoolViews.Full.class)
    public String city;

    @JsonView(SchoolViews.Full.class)
    public String regon;

    @JsonView(SchoolViews.Full.class)
    public String schoolType;

    @JsonView(SchoolViews.Full.class)
    public String ownershipType;

    @JsonView(SchoolViews.Full.class)
    public String email;

    @JsonView(SchoolViews.Full.class)
    public String phone;

    @JsonView(SchoolViews.Full.class)
    public String rspo;

    @JsonView(SchoolViews.Location.class)
    public Double latitude;

    @JsonView(SchoolViews.Location.class)
    public Double longitude;

    @JsonView(SchoolViews.Full.class)
    public Double stars;

    public String addressForGeolocation() {
        return String.format("%s %s %s %s", name, address, postCode, city);
    }
}


text:
import math
import numpy as np
from geometry_msgs.msg import Point, Pose, PoseStamped, Quaternion
from std_msgs.msg import ColorRGBA
import visualization_msgs.msg
import rospy
import tf.transformations as tft

def wait_for_time():
    """Wait for simulated time to begin.
    """
    while rospy.Time().now().to_sec() == 0:
        pass

def cosd(degs):
    return math.cos(degs * math.pi / 180)

def sind(degs):
    return math.sin(degs * math.pi / 180)

def axis_marker(pose_stamped):
    marker = visualization_msgs.msg.Marker()
    marker.ns = 'axes'
    marker.header = pose_stamped.header
    marker.pose = pose_stamped.pose
    marker.type = visualization_msgs.msg.Marker.LINE_LIST
    marker.scale.x = 0.1

    marker.points.append(Point(0, 0, 0))
    marker.colors.append(ColorRGBA(0.8, 0, 0, 1))
    marker.points.append(Point(1, 0, 0))
    marker.colors.append(ColorRGBA(0.8, 0, 0, 1))

    marker.points.append(Point(0, 0, 0))
    marker.colors.append(ColorRGBA(0, 0.8, 0, 1))
    marker.points.append(Point(0, 1, 0))
    marker.colors.append(ColorRGBA(0, 0.8, 0, 1))

    marker.points.append(Point(0, 0, 0))
    marker.colors.append(ColorRGBA(0, 0, 0.8, 1))
    marker.points.append(Point(0, 0, 1))
    marker.colors.append(ColorRGBA(0, 0, 0.8, 1))

    return marker

def transform_to_pose(matrix):
    pose = Pose()
    pose.position.x = matrix[0, 3]
    pose.position.y = matrix[1, 3]
    pose.position.z = matrix[2, 3]
    x, y, z, w = tft.quaternion_from_matrix(matrix)
    pose.orientation.x = x
    pose.orientation.y = y
    pose.orientation.z = z
    pose.orientation.w = w
    return pose

def pose_to_transform(pose):
    q = pose.orientation
    matrix = tft.quaternion_matrix([q.x, q.y, q.z, q.w])
    matrix[0, 3] = pose.position.x
    matrix[1, 3] = pose.position.y
    matrix[2, 3] = pose.position.z
    return matrix

def arrow_marker(point):
    marker = visualization_msgs.msg.Marker()
    marker.ns = 'arrow'
    marker.type = visualization_msgs.msg.Marker.ARROW
    marker.header.frame_id = 'frame_a'
    marker.points.append(Point(0, 0, 0))
    marker.points.append(point)
    marker.scale.x = 0.1
    marker.scale.y = 0.15
    marker.color.r = 1
    marker.color.g = 1
    marker.color.a = 1
    return marker

def main():
    rospy.init_node('transformation_demo')
    wait_for_time()
    viz_pub = rospy.Publisher(
        'visualization_marker', visualization_msgs.msg.Marker, queue_size=1)
    rospy.sleep(0.5)
    b_in_a = np.array([
        [cosd(45), -sind(45), 0, 0],
        [sind(45), cosd(45), 0, 0],
        [0, 0, 1, 0.5],
        [0, 0, 0, 1]
    ])
    ps = PoseStamped()
    ps.header.frame_id = 'frame_a'
    ps.pose = transform_to_pose(b_in_a)
    viz_pub.publish(axis_marker(ps))

    point_in_b = np.array([1, 0, 0, 1])
    point_in_a = np.dot(b_in_a, point_in_b)
    rospy.loginfo(point_in_b)
    rospy.loginfo(point_in_a)
    point = Point(point_in_a[0], point_in_a[1], point_in_a[2])
    viz_pub.publish(arrow_marker(point))

def main2():
    rospy.init_node('transformation_demo')
    wait_for_time()
    viz_pub = rospy.Publisher(
        'visualization_marker', visualization_msgs.msg.Marker, queue_size=1)
    rospy.sleep(0.5)

    obj_pose_in_base = Pose(Point(0.6, -0.1, 0.7), Quaternion(0, 0, 0.38268343, 0.92387953))
    obj_mat_in_base = pose_to_transform(obj_pose_in_base)

    pregrasp_pose_in_obj = Pose()
    pregrasp_pose_in_obj.position.x = -0.1
    pregrasp_pose_in_obj.orientation.w = 1
    pregrasp_mat_in_obj = pose_to_transform(pregrasp_pose_in_obj)

    pregrasp_mat_in_base = np.dot(obj_mat_in_base, pregrasp_mat_in_obj)
    pregrasp_pose = transform_to_pose(pregrasp_mat_in_base)

    ps1 = PoseStamped()
    ps1.header.frame_id = 'frame_a'
    ps1.pose = obj_pose_in_base

    ps2 = PoseStamped()
    ps2.header.frame_id = 'frame_a'
    ps2.pose = pregrasp_pose

    viz_pub.publish(axis_marker(ps1))
    marker2 = axis_marker(ps2)
    marker2.id = 1
    viz_pub.publish(marker2)

if __name__ == '__main__':
    main2()


text:
using System;
using Foundation;
using UIKit;
using System.CodeDom.Compiler;
using HomeKit;

namespace HomeKitIntro
{
	public partial class AvailableTableViewController : UITableViewController
	{
		#region Computed Properties
		/// <summary>
		/// Returns the delegate of the current running application
		/// </summary>
		/// <value>The this app.</value>
		public AppDelegate ThisApp {
			get { return (AppDelegate)UIApplication.SharedApplication.Delegate; }
		}

		/// <summary>
		/// Gets the data source.
		/// </summary>
		/// <value>The data source.</value>
		public AvailableTableSource DataSource {
			get { return (AvailableTableSource)TableView.Source; }
		}

		/// <summary>
		/// Gets or sets the index of the accessory being edited.
		/// </summary>
		/// <value>The index of the accessory.</value>
		public int AccessoryIndex { get; set; }

		/// <summary>
		/// Gets or sets the accessory browser.
		/// </summary>
		/// <value>The accessory browser.</value>
		public HMAccessoryBrowser AccessoryBrowser { get; set; }
		#endregion

		#region Constructors
		public AvailableTableViewController (IntPtr handle) : base (handle)
		{
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Reloads the data.
		/// </summary>
		public void ReloadData() {

			// Ask the table to redisplay its information
			TableView.ReloadData ();
		}
		#endregion

		#region Override Methods
		/// <Docs>Called after the object has been loaded from the nib file. Overriders must call base.AwakeFromNib().</Docs>
		/// <summary>
		/// Awakes from nib.
		/// </summary>
		public override void AwakeFromNib ()
		{
			base.AwakeFromNib ();

			// Create a new accessory browser
			AccessoryBrowser = new HMAccessoryBrowser ();

			// Wireup changes
			AccessoryBrowser.DidFindNewAccessory += (sender, e) => {
				// Update display
				ReloadData();
			};

			AccessoryBrowser.DidRemoveNewAccessory += (sender, e) => {
				// Update display
				ReloadData();

				// Inform the rest of the UI that it needs to refresh
				ThisApp.RaiseUpdateGUI();
			};
		}

		/// <summary>
		/// Views the did load.
		/// </summary>
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Register the tableview's datasource
			TableView.Source = new AvailableTableSource (this);

		}

		/// <summary>
		/// Views the will appear.
		/// </summary>
		/// <param name="animated">If set to <c>true</c> animated.</param>
		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);

			// Ask the browser to start searching for new items
			AccessoryBrowser.StartSearchingForNewAccessories ();
		}

		public override void ViewWillDisappear (bool animated)
		{
			base.ViewWillDisappear (animated);

			// Ask the accessory browser to stop seraching for new accessories
			AccessoryBrowser.StopSearchingForNewAccessories ();
		}
		#endregion
	}
}


text:
package cz.zcu.kiv.jop.annotation.generator.bool;

import java.lang.annotation.Annotation;

/**
 * Implementation of annotation {@link RandomBoolean}.
 *
 * @author Mr.FrAnTA
 */
public class RandomBooleanImpl implements RandomBoolean {

  /** The value of parameter probability. */
  private final double probability;

  /**
   * Constructs the annotation.
   *
   * @param probability probability of annotation.
   */
  public RandomBooleanImpl(double probability) {
    this.probability = probability;
  }

  /**
   * Returns type of annotation (this class).
   *
   * @return type of annotation.
   */
  public Class<? extends Annotation> annotationType() {
    return getClass();
  }

  /**
   * @return The value of parameter probability.
   */
  public double probability() {
    return probability;
  }

}


text:
package org.arquillian.cube.await;

import org.arquillian.cube.docker.DockerClientExecutor;

import com.github.dockerjava.api.command.CreateContainerResponse;

public class NativeAwaitStrategy implements AwaitStrategy {

    public static final String TAG = "native";

    private DockerClientExecutor dockerClientExecutor;
    private CreateContainerResponse createContainerResponse;

    public NativeAwaitStrategy(DockerClientExecutor dockerClientExecutor, CreateContainerResponse createContainerResponse) {
        this.dockerClientExecutor = dockerClientExecutor;
        this.createContainerResponse = createContainerResponse;
    }

    @Override
    public boolean await() {

        if (this.dockerClientExecutor.waitContainer(this.createContainerResponse) == 0) {
            return true;
        } else {
            return false;
        }
    }

}


text:
import _Object$getPrototypeOf from 'babel-runtime/core-js/object/get-prototype-of';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import PropTypes from 'prop-types';
import { Component } from 'react';
import defaultHeaderRenderer from './defaultHeaderRenderer';
import defaultCellRenderer from './defaultCellRenderer';
import defaultCellDataGetter from './defaultCellDataGetter';

/**
 * Describes the header and cell contents of a table column.
 */

var Column = function (_Component) {
  _inherits(Column, _Component);

  function Column() {
    _classCallCheck(this, Column);

    return _possibleConstructorReturn(this, (Column.__proto__ || _Object$getPrototypeOf(Column)).apply(this, arguments));
  }

  return Column;
}(Component);

Column.defaultProps = {
  cellDataGetter: defaultCellDataGetter,
  cellRenderer: defaultCellRenderer,
  flexGrow: 0,
  flexShrink: 1,
  headerRenderer: defaultHeaderRenderer,
  style: {}
};
export default Column;
process.env.NODE_ENV !== "production" ? Column.propTypes = {
  /** Optional aria-label value to set on the column header */
  'aria-label': PropTypes.string,

  /**
   * Callback responsible for returning a cell's data, given its :dataKey
   * ({ columnData: any, dataKey: string, rowData: any }): any
   */
  cellDataGetter: PropTypes.func,

  /**
   * Callback responsible for rendering a cell's contents.
   * ({ cellData: any, columnData: any, dataKey: string, rowData: any, rowIndex: number }): node
   */
  cellRenderer: PropTypes.func,

  /** Optional CSS class to apply to cell */
  className: PropTypes.string,

  /** Optional additional data passed to this column's :cellDataGetter */
  columnData: PropTypes.object,

  /** Uniquely identifies the row-data attribute correspnding to this cell */
  dataKey: PropTypes.any.isRequired,

  /** If sort is enabled for the table at large, disable it for this column */
  disableSort: PropTypes.bool,

  /** Flex grow style; defaults to 0 */
  flexGrow: PropTypes.number,

  /** Flex shrink style; defaults to 1 */
  flexShrink: PropTypes.number,

  /** Optional CSS class to apply to this column's header */
  headerClassName: PropTypes.string,

  /**
   * Optional callback responsible for rendering a column header contents.
   * ({ columnData: object, dataKey: string, disableSort: boolean, label: string, sortBy: string, sortDirection: string }): PropTypes.node
   */
  headerRenderer: PropTypes.func.isRequired,

  /** Optional id to set on the column header */
  id: PropTypes.string,

  /** Header label for this column */
  label: PropTypes.string,

  /** Maximum width of column; this property will only be used if :flexGrow is > 0. */
  maxWidth: PropTypes.number,

  /** Minimum width of column. */
  minWidth: PropTypes.number,

  /** Optional inline style to apply to cell */
  style: PropTypes.object,

  /** Flex basis (width) for this column; This value can grow or shrink based on :flexGrow and :flexShrink properties. */
  width: PropTypes.number.isRequired
} : void 0;


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
using System.Linq;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults
{
    internal class ObjectList : AbstractObjectList<LibraryManager>
    {
        private readonly IList<AbstractTreeItem> _items;

        public ObjectList(IList<AbstractTreeItem> items, LibraryManager manager)
            : base(manager)
        {
            _items = items;
        }

        protected override bool CanGoToSource(uint index, VSOBJGOTOSRCTYPE srcType)
        {
            var item = _items[(int)index];

            switch (srcType)
            {
                case VSOBJGOTOSRCTYPE.GS_ANY:
                    return true;

                case VSOBJGOTOSRCTYPE.GS_DEFINITION:
                    return item.CanGoToDefinition();

                case VSOBJGOTOSRCTYPE.GS_REFERENCE:
                    return item.CanGoToReference();
            }

            return false;
        }

        protected override bool TryGetCategoryField(uint index, int category, out uint categoryField)
        {
            if (category == (int)LIB_CATEGORY.LC_LISTTYPE)
            {
                categoryField = (uint)_LIB_LISTTYPE.LLT_HIERARCHY;
                return true;
            }
            else
            {
                categoryField = 0;
                return false;
            }
        }

        protected override void GetDisplayData(uint index, ref VSTREEDISPLAYDATA data)
        {
            var item = _items[(int)index];
            data.Image = item.GlyphIndex;
            data.SelectedImage = item.GlyphIndex;
            data.State |= (uint)_VSTREEDISPLAYSTATE.TDS_FORCESELECT;

            if (item.UseGrayText)
            {
                data.State |= (uint)_VSTREEDISPLAYSTATE.TDS_GRAYTEXT;
            }

            data.ForceSelectStart = item.DisplaySelectionStart;
            data.ForceSelectLength = item.DisplaySelectionLength;
        }

        protected override bool GetExpandable(uint index, uint listTypeExcluded)
        {
            var item = _items[(int)index];
            return (item?.Children?.Any() == true);
        }

        protected override uint GetItemCount()
        {
            return (uint)_items.Count;
        }

        protected override IVsSimpleObjectList2 GetList(uint index, uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch)
        {
            var item = _items[(int)index];
            return (item?.Children?.Any() == true) ? new ObjectList(item.Children, LibraryManager) : null;
        }

        protected override string GetText(uint index, VSTREETEXTOPTIONS tto)
        {
            var item = _items[(int)index];
            switch (tto)
            {
                case VSTREETEXTOPTIONS.TTO_DISPLAYTEXT:
                    return item.DisplayText;

                case VSTREETEXTOPTIONS.TTO_SORTTEXT:
                    return index.ToString("D5");
            }

            return string.Empty;
        }

        protected override string GetTipText(uint index, VSTREETOOLTIPTYPE eTipType)
        {
            var item = _items[(int)index];
            return item.DisplayText;
        }

        protected override int GoToSource(uint index, VSOBJGOTOSRCTYPE srcType)
        {
            if (index >= _items.Count)
            {
                return VSConstants.E_INVALIDARG;
            }

            var item = _items[(int)index];
            return item.GoToSource();
        }

        protected override uint GetUpdateCounter()
        {
            return 0;
        }
    }
}


text:
package com.interface21.samples.countries.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.interface21.beans.BeanWrapper;
import com.interface21.beans.BeanWrapperImpl;
import com.interface21.beans.BeansException;
import com.interface21.context.ApplicationContext;
import com.interface21.context.ApplicationContextAware;
import com.interface21.context.ApplicationContextException;
import com.interface21.samples.countries.dao.IDaoCountry;
import com.interface21.web.servlet.HandlerInterceptor;

/**
 * An interceptor that tell the views about the possibility of a copy
 * of the countries to a database.
 * @author Jean-Pierre Pawlak
 */
public class CopyInterceptor implements HandlerInterceptor, ApplicationContextAware {

	protected final Log logger = LogFactory.getLog(getClass());

	private Boolean copyAvailable;

	/**
	 * Set copyAvailable to True if the countriesController
	 * has a secondDao declared and if this one is of a DATABASE type.
	 * Otherwise copyAvailable is set to False.
	 *
	 * @see com.interface21.context.ApplicationContextAware#setApplicationContext(com.interface21.context.ApplicationContext)
	 */
	public void setApplicationContext(ApplicationContext ctx)
		throws ApplicationContextException {
		Object o = ctx.getBean("countriesController");
		if (null == o) {
			copyAvailable = Boolean.FALSE;
		} else {
			BeanWrapper bw = new BeanWrapperImpl(o);
			Object dao;
			try {
				dao = bw.getPropertyValue("secondDaoCountry");
				bw = new BeanWrapperImpl(dao);
				if (IDaoCountry.DATABASE.equals(bw.getPropertyValue("type"))) {
					copyAvailable = Boolean.TRUE;
				} else {
					copyAvailable = Boolean.FALSE;
				}
			} catch (BeansException e) {
				copyAvailable = Boolean.FALSE;
			}
		}
		if (copyAvailable.booleanValue()) {
			logger.info("The countriesController has a valid secondDao. Copy to the database is available.");
		} else {
			logger.info("The countriesController has no valid secondDao. Copy to the database is not available.");
		}
	}

	/**
	 * Makes the copyAvailable value available to views.
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		request.setAttribute("copyAvailable", copyAvailable);
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
	}

}


text:
IPython Integration
===================

Dask.distributed integrates with IPython in three ways:

1.  You can launch a Dask.distributed cluster from an IPyParallel_ cluster
2.  You can launch IPython kernels from Dask Workers and Schedulers to assist
    with debugging
3.  They both support the common concurrent.futures_ interface

.. _IPyParallel: https://ipyparallel.readthedocs.io/en/latest/
.. _concurrent.futures: https://docs.python.org/3/library/concurrent.futures.html

Launch Dask from IPyParallel
----------------------------

IPyParallel is IPython's distributed computing framework that allows you to
easily manage many IPython engines on different computers.

An IPyParallel ``Client`` can launch a ``dask.distributed`` Scheduler and
Workers on those IPython engines, effectively launching a full dask.distributed
system.

This is possible with the Client.become_dask_ method::

   $ ipcluster start

.. code-block:: python

   >>> from ipyparallel import Client
   >>> c = Client()  # connect to IPyParallel cluster

   >>> e = c.become_dask()  # start dask on top of IPyParallel
   >>> e
   <Client: scheduler="127.0.0.1:59683" processes=8 cores=8>

.. _Client.become_dask: https://ipyparallel.readthedocs.io/en/latest/api/ipyparallel.html#ipyparallel.Client.become_dask

Launch IPython within Dask Workers
----------------------------------

It is sometimes convenient to inspect the ``Worker`` or ``Scheduler`` process
interactively.  Fortunately IPython gives us a way to launch interactive
sessions within Python processes.  This is available through the following
methods:

.. currentmodule:: distributed.client

.. autosummary::
   Client.start_ipython_workers
   Client.start_ipython_scheduler

These methods start IPython kernels running in a separate thread within the
specified Worker or Schedulers.  These kernels are accessible either through
IPython magics or a QT-Console.

Example with IPython Magics
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

   >>> e.start_ipython_scheduler()
   >>> %scheduler scheduler.processing
   {'127.0.0.1:3595': ['inc-1', 'inc-2'],
    '127.0.0.1:53589': ['inc-2', 'add-5']}

   >>> info = e.start_ipython_workers()
   >>> %remote info['127.0.0.1:3595'] worker.active
   {'inc-1', 'inc-2'}

Example with qt-console
~~~~~~~~~~~~~~~~~~~~~~~

You can also open up a full interactive `IPython qt-console`_ on the scheduler
or each of the workers:

.. code-block:: python

   >>> e.start_ipython_scheduler(qtconsole=True)
   >>> e.start_ipython_workers(qtconsole=True)

.. _`IPython qt-console`: https://ipython.org/ipython-doc/3/interactive/qtconsole.html


text:
import IECore
import Gaffer

class test( Gaffer.Application ) :

	def __init__( self ) :

		Gaffer.Application.__init__( self )

		self.parameters().addParameters(

			[
				IECore.StringParameter(
					name = "testCase",
					description = "The name of a specific test case to run. If unspecified then all test cases are run.",
					defaultValue = "",
				),

				IECore.IntParameter(
					name = "repeat",
					description = "The number of times to repeat the tests.",
					defaultValue = 1,
				),
			]

		)

		self.parameters().userData()["parser"] = IECore.CompoundObject(
			{
				"flagless" : IECore.StringVectorData( [ "testCase" ] )
			}
		)

	def _run( self, args ) :

		import unittest

		testSuite = unittest.TestSuite()
		if args["testCase"].value :

			testCase = unittest.defaultTestLoader.loadTestsFromName( args["testCase"].value )
			testSuite.addTest( testCase )

		else :

			import GafferTest
			import GafferUITest
			import GafferSceneTest
			import GafferImageTest
			import GafferImageUITest

			for module in ( GafferTest, GafferUITest, GafferSceneTest, GafferImageTest, GafferImageUITest ) :

				moduleTestSuite = unittest.defaultTestLoader.loadTestsFromModule( module )
				testSuite.addTest( moduleTestSuite )

		for i in range( 0, args["repeat"].value ) :
			testRunner = unittest.TextTestRunner( verbosity=2 )
			testResult = testRunner.run( testSuite )
			if not testResult.wasSuccessful() :
				return 1

		return 0

IECore.registerRunTimeTyped( test )