text:
/*
    Little Smalltalk version 4

    Written by Tim Budd, Oregon State University, July 1994

        budd@cs.orst.edu

    bytecode interpreter module

    given a process object, execute bytecodes in a tight loop.

    performs subroutine calls for
    a) garbage collection
        b) finding a non-cached method
        c) executing a primitive
    d) creating an integer

    otherwise simply loops until time slice has ended

    Modified by Kyle Hayes for 64-bit systems.
*/

#include <stdio.h>
#include <string.h> /* For bzero() */
#include <stdint.h>
#include "globals.h"
#include "image.h"
#include "interp.h"
#include "memory.h"
#include "prim.h"
#include "err.h"

/* method cache */

typedef struct {
    struct object *name;
    struct object *class;
    struct object *method;
} method_cache_entry;

#define METHOD_CACHE_SIZE (703)

extern method_cache_entry cache[METHOD_CACHE_SIZE];

/*
    method cache for speeding method lookup
*/

method_cache_entry cache[METHOD_CACHE_SIZE];

int64_t cache_hit = 0;
int64_t cache_miss = 0;

/* flush dynamic methods when GC occurs */
void flushCache(void)
{
    int i;

    for (i = 0; i < METHOD_CACHE_SIZE; i++) {
        cache[i].name = 0;  /* force refill */
    }
}

/*
 * Debugging
 */

#ifdef TRACE
static void indent(struct object *ctx)
{
    static int oldlev = 0;
    int lev = 0, x;

    while (ctx && (ctx != nilObject)) {
        lev += 1;
        putchar(' ');
        ctx = ctx->data[previousContextInContext];
    }

    /*
     * This lets you use your editor's brace matching to
     * match up opening and closing indentation levels.
     */
    if (lev < oldlev) {
        for (x = lev; x < oldlev; ++x) {
            putchar('}');
        }
    } else if (lev > oldlev) {
        for (x = oldlev; x < lev; ++x) {
            putchar('{');
        }
    }

    oldlev = lev;
}

#define PC (bytePointer-1)
#define DBG0(msg) if (debugging) {indent(context); fprintf(stderr, "%d: %s\n", PC, msg);}
#define DBG1(msg, arg) if (debugging) {indent(context); \
        fprintf(stderr, "%d: %s %d\n", PC, msg, arg);}
#define DBGS(msg, cl, sel) \
    if (debugging) { \
        indent(context); \
        fprintf(stderr, "%d: %s %.*s %.*s\n", PC, msg, SIZE(cl), (char *)bytePtr(cl), SIZE(sel), (char*)bytePtr(sel)); }
#else
#define DBG0(msg)
#define DBG1(msg, arg)
#define DBGS(msg, cl, sel)
#endif

/*
    method lookup routine, used when cache miss occurs
*/

static int symbolcomp(struct object *left, struct object *right)
{
    int leftsize = SIZE(left);
    int rightsize = SIZE(right);
    int minsize = leftsize;
    int i;

    if (rightsize < minsize) {
        minsize = rightsize;
    }
    for (i = 0; i < minsize; i++) {
        if (bytePtr(left)[i] != bytePtr(right)[i]) {
            return bytePtr(left)[i]-bytePtr(right)[i];
        }
    }
    return leftsize - rightsize;
}

static struct object *lookupMethod(struct object *selector, struct object *class)
{
    struct object *dict, *keys, *vals, *val;
    int low, high, mid;

    if(!selector || selector == nilObject) {
        info("lookupMethod(): selector is NULL or nil!");
        return NULL;
    }

    if(!class || class == nilObject) {
        info("lookupMethod(): lookup called with selector %.*s on NULL/nil class object!", SIZE(selector), bytePtr(selector));
        return NULL;
    }

    /*
     * Scan upward through the class hierarchy
     */
    for ( ; class != nilObject; class = class->data[parentClassInClass]) {
        info("looking up #%.*s in class %.*s.", SIZE(selector), (char*)bytePtr(selector), SIZE(class->data[nameInClass]), (char*)bytePtr(class->data[nameInClass]));
        /*
         * Consider the Dictionary of methods for this Class
         */
        dict = class->data[methodsInClass];
        keys = dict->data[0];
        low = 0;
        high = SIZE(keys);

        /*
         * Do a binary search through its keys, which are
         * Symbol's.
         */
        while (low < high) {
            mid = (low + high) / 2;
            val = keys->data[mid];

            /*
             * If we find the selector, return the
             * method object.
             */
            if (val == selector) {
                vals = dict->data[1];
                return(vals->data[mid]);
            }

            /*
             * Otherwise continue the binary search
             */
            if (symbolcomp(selector, val) < 0) {
                high = mid;
            } else {
                low = mid+1;
            }
        }
    }

    /*
     * Sorry, couldn't find a method
     */
    return NULL;
}

/*
 * bulkReplace()
 *  Implement replaceFrom:to:with:startingAt: as a primitive
 *
 * Return 1 if we couldn't do it, 0 on success.  This routine has
 * distinct code paths for plain old byte type arrays, and for
 * arrays of object pointers; the latter must handle the special
 * case of static pointers.  It looks hairy (and it is), but it's
 * still much faster than executing the block move in Smalltalk
 * VM opcodes.
 */
static int bulkReplace(struct object *dest, struct object *start,
                       struct object *stop, struct object *src,
                       struct object *repStart)
{
    int irepStart, istart, istop, count;

    /*
     * We only handle simple 31-bit integer indices.  Map the
     * values onto 0-based C array type values.
     */
    if (!IS_SMALLINT(repStart) || !IS_SMALLINT(start) ||
        !IS_SMALLINT(stop)) {
        return(1);
    }
    irepStart = integerValue(repStart)-1;
    istart = integerValue(start)-1;
    istop = integerValue(stop)-1;
    count = (istop-istart) + 1;

    /*
     * Defend against goofy negative indices.
     */
    if ((irepStart < 0) || (istart < 0) || (istop < 0) || (count < 1)) {
        return(1);
    }

    /*
     * Range check
     */
    if ((SIZE(dest) < (uint32_t)istop) || (SIZE(src) < (uint32_t)(irepStart + count))) {
        return(1);
    }

    /*
     * If both source and dest are binary, do a bcopy()
     */
    if (IS_BINOBJ(src) && IS_BINOBJ(dest)) {
        /*
         * Do it.
         */
        bcopy(bytePtr(src) + irepStart, bytePtr(dest) + istart, (size_t)count);
        return(0);
    }

    /*
     * If not both regular storage, fail
     */
    if (IS_BINOBJ(src) || IS_BINOBJ(dest)) {
        return(1);
    }

    /*
     * If we're fiddling pointers between static and dynamic memory,
     * let the VM-based implementation deal with it.
     */
    if (isDynamicMemory(src) != isDynamicMemory(dest)) {
        return(1);
    }

    /*
     * Copy object pointer fields
     */
    bcopy(&src->data[irepStart], &dest->data[istart], (size_t)(BytesPerWord * count));
    return(0);
}

/* Code locations are extracted as VAL's */
#define VAL (bp[bytePointer] | (bp[bytePointer+1] << 8))
#define VALSIZE 2

int execute(struct object *aProcess, int ticks)
{
    int low, high, x, stackTop, bytePointer;
    struct object *context, *method, *arguments, *temporaries,
            *instanceVariables, *literals, *stack,
            *returnedValue = nilObject, *messageSelector,
             *receiverClass, *op;
    uint8_t *bp;
    int64_t l;
    int64_t *i64p;

    /* push process, so as to save it */
    rootStack[rootTop++] = aProcess;

    /* get current context information */
    context = aProcess->data[contextInProcess];

    method = context->data[methodInContext];

    /* load byte pointer */
    bp = (uint8_t *)bytePtr(method->data[byteCodesInMethod]);
    bytePointer = integerValue(context->data[bytePointerInContext]);

    /* load stack */
    stack = context->data[stackInContext];
    stackTop = integerValue(context->data[stackTopInContext]);

    /* everything else can wait, as maybe won't be needed at all */
    temporaries = instanceVariables = arguments = literals = 0;

    for (;;) {
        /*
         * If we're running against a CPU tick count, stop execution
         * when we expire the given number of ticks.
         */
        if (ticks && (--ticks == 0)) {
            aProcess = rootStack[--rootTop];
            aProcess->data[contextInProcess] = context;
            aProcess->data[resultInProcess] = returnedValue;
            context->data[bytePointerInContext] = newInteger(bytePointer);
            context->data[stackTopInContext] = newInteger(stackTop);
            return(ReturnTimeExpired);
        }

        /* Otherwise decode the instruction */
        low = (high = bp[bytePointer++] ) & 0x0F;
        high >>= 4;
        if (high == Extended) {
            high = low;
            low = bp[bytePointer++] ;
        }

        /* And dispatch */
        switch (high) {

        case PushInstance:
            DBG1("PushInstance", low);
            if (! arguments) {
                arguments = context->data[argumentsInContext];
            }
            if (! instanceVariables)
                instanceVariables =
                    arguments->data[receiverInArguments];
            stack->data[stackTop++] = instanceVariables->data[low];
            break;

        case PushArgument:
            DBG1("PushArgument", low);
            if (! arguments) {
                arguments = context->data[argumentsInContext];
            }
            stack->data[stackTop++] = arguments->data[low];
            break;

        case PushTemporary:
            DBG1("PushTemporary", low);
            if (! temporaries) {
                temporaries = context->data[temporariesInContext];
            }
            stack->data[stackTop++] = temporaries->data[low];
            break;

        case PushLiteral:
            DBG1("PushLiteral", low);
            if (! literals) {
                literals = method->data[literalsInMethod];
            }
            stack->data[stackTop++] = literals->data[low];
            break;

        case PushConstant:
            DBG1("PushConstant", low);
            switch(low) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                stack->data[stackTop++] = newInteger(low);
                break;
            case nilConst:
                stack->data[stackTop++] = nilObject;
                break;
            case trueConst:
                stack->data[stackTop++] = trueObject;
                break;
            case falseConst:
                stack->data[stackTop++] = falseObject;
                break;
            default:
                error("unknown push constant %d", low);
            }
            break;

        case PushBlock:
            DBG0("PushBlock");
            /* create a block object */
            /* low is arg location */
            /* next byte is goto value */
            high = VAL;
            bytePointer += VALSIZE;
            rootStack[rootTop++] = context;
            op = rootStack[rootTop++] = gcalloc(x = integerValue(method->data[stackSizeInMethod]));
            op->class = ArrayClass;
            bzero(bytePtr(op), (size_t)(x * BytesPerWord));
            returnedValue = gcalloc(blockSize);
            returnedValue->class = BlockClass;
            returnedValue->data[bytePointerInContext] =
                returnedValue->data[stackTopInBlock] =
                    returnedValue->data[previousContextInBlock] = NULL;
            returnedValue->data[bytePointerInBlock] =
                newInteger(bytePointer);
            returnedValue->data[argumentLocationInBlock] = newInteger(low);
            returnedValue->data[stackInBlock] = rootStack[--rootTop];
            context = rootStack[--rootTop];
            if (CLASS(context) == BlockClass) {
                returnedValue->data[creatingContextInBlock] =
                    context->data[creatingContextInBlock];
            } else {
                returnedValue->data[creatingContextInBlock] = context;
            }
            method = returnedValue->data[methodInBlock] =
                         context->data[methodInBlock];
            arguments = returnedValue->data[argumentsInBlock] =
                            context->data[argumentsInBlock];
            temporaries = returnedValue->data[temporariesInBlock] =
                              context->data[temporariesInBlock];
            stack = context->data[stackInContext];
            bp = bytePtr(method->data[byteCodesInMethod]);
            stack->data[stackTop++] = returnedValue;
            /* zero these out just in case GC occurred */
            literals = instanceVariables = 0;
            bytePointer = high;
            break;

        case AssignInstance:
            DBG1("AssignInstance", low);
            if (!arguments)  {
                arguments = context->data[argumentsInContext];
            }
            if (!instanceVariables) {
                instanceVariables =
                    arguments->data[receiverInArguments];
                /* don't pop stack, leave result there */
            }
            instanceVariables->data[low] = stack->data[stackTop-1];

            /*
             * If changing a static area, need to add to roots
             */
            if (!isDynamicMemory(instanceVariables)
                && isDynamicMemory(stack->data[stackTop-1])) {
                addStaticRoot(&instanceVariables->data[low]);
            }
            break;

        case AssignTemporary:
            DBG1("AssignTemporary", low);
            if (! temporaries) {
                temporaries = context->data[temporariesInContext];
            }
            temporaries->data[low] = stack->data[stackTop-1];
            break;

        case MarkArguments:
            DBG1("MarkArguments", low);
            rootStack[rootTop++] = context;
            arguments = gcalloc(low);
            arguments->class = ArrayClass;
            if (context != rootStack[--rootTop]) { /* gc has occurred */
                /* reload context */
                instanceVariables = temporaries = literals = 0;
                context = rootStack[rootTop];
                method = context->data[methodInContext];
                bp = bytePtr(method->data[byteCodesInMethod]);
                stack = context->data[stackInContext];
            }
            /* now load new argument array */
            while (low > 0) {
                arguments->data[--low] = stack->data[--stackTop];
            }
            stack->data[stackTop++] = arguments;
            arguments = 0;
            break;

        case SendMessage:
            if (! literals) {
                literals = method->data[literalsInMethod];
            }
            messageSelector = literals->data[low];
            arguments = stack->data[--stackTop];

findMethodFromSymbol:
            receiverClass = CLASS(arguments->data[receiverInArguments]);
            DBGS("SendMessage", receiverClass->data[nameInClass], messageSelector);
checkCache:
            low = (int)((((uintptr_t) messageSelector) +
                         ((uintptr_t) receiverClass)) % (uintptr_t)METHOD_CACHE_SIZE);
            if ((cache[low].name == messageSelector) &&
                (cache[low].class == receiverClass)) {
                method = cache[low].method;
                cache_hit++;
            } else {
                cache_miss++;
                method = lookupMethod(messageSelector, receiverClass);
                if (!method) {
                    if (messageSelector == badMethodSym) {
                        backTrace(context);
                        error("doesNotUnderstand: missing");
                    }
                    op = gcalloc(2);
                    op->class = ArrayClass;
                    op->data[receiverInArguments] = arguments->data[receiverInArguments];
                    op->data[1] = messageSelector;
                    arguments = op;
                    messageSelector = badMethodSym;
                    goto findMethodFromSymbol;
                }
                cache[low].name = messageSelector;
                cache[low].class = receiverClass;
                cache[low].method = method;
            }

            /* see if we can optimize tail call */
            if (bp[bytePointer] == (DoSpecial * 16 + StackReturn)) {
                high = 1;
            } else if (bp[bytePointer] ==
                       (DoSpecial * 16 + BlockReturn)) {
                high = 2;
            } else {
                high = 0;
            }

            /* build temporaries for new context */
            rootStack[rootTop++] = arguments;
            rootStack[rootTop++] = method;
            rootStack[rootTop++] = context;
            low = integerValue(method->data[temporarySizeInMethod]);
            op = rootStack[rootTop++] =
                     gcalloc(x = integerValue(method->data[stackSizeInMethod]));
            op->class = ArrayClass;
            bzero(bytePtr(op), (size_t)(x * BytesPerWord));
            if (low > 0) {
                int i;

                temporaries = gcalloc(low);
                temporaries->class = ArrayClass;
                for (i = 0; i < low; i++) {
                    temporaries->data[i] = nilObject;
                }
                rootStack[rootTop++] = temporaries; /* temporaries */
            } else {
                rootStack[rootTop++] = NULL;    /* why bother */
            }
            context = rootStack[rootTop-3];
            context->data[stackTopInContext] = newInteger(stackTop);
            context->data[bytePointerInContext] = newInteger(bytePointer);

            /* now go off and build the new context */
            context = gcalloc(contextSize);
            context->class = ContextClass;
            temporaries = context->data[temporariesInContext] = rootStack[--rootTop];
            stack = context->data[stackInContext] = rootStack[--rootTop];
            stack->class = ArrayClass;
            context->data[stackTopInContext] = newInteger(0);
            stackTop = 0;
            context->data[previousContextInContext] = rootStack[--rootTop];
            if (high == 1) {
                context->data[previousContextInContext] =
                    context->data[previousContextInContext]->
                    data[previousContextInContext];
            } else if (high == 2) {
                context->data[previousContextInContext] =
                    context->data[previousContextInContext]->
                    data[creatingContextInBlock]->
                    data[previousContextInContext];
            }
            method = context->data[methodInContext] = rootStack[--rootTop];
            arguments = context->data[argumentsInContext]
                        = rootStack[--rootTop];
            instanceVariables = literals = 0;
            context->data[bytePointerInContext] = newInteger(0);
            bytePointer = 0;
            bp = (uint8_t *) (method->data[byteCodesInMethod]->data);
            /* now go execute new method */
            break;

        case SendUnary: /* optimize certain unary messages */
            DBG1("SendUnary", low);
            returnedValue = stack->data[--stackTop];
            switch(low) {
            case 0: /* isNil */
                if (returnedValue == nilObject) {
                    returnedValue = trueObject;
                } else {
                    returnedValue = falseObject;
                }
                break;
            case 1: /* notNil */
                if (returnedValue == nilObject) {
                    returnedValue = falseObject;
                } else {
                    returnedValue = trueObject;
                }
                break;
            default:
                error("unimplemented SendUnary %d", low);
            }
            stack->data[stackTop++] = returnedValue;
            break;

        case SendBinary:    /* optimize certain binary messages */
            DBG1("SendBinary", low);
            if (IS_SMALLINT(stack->data[stackTop-1])
                && IS_SMALLINT(stack->data[stackTop-2])) {
                int i, j;
                j = integerValue(stack->data[--stackTop]);
                i = integerValue(stack->data[--stackTop]);
                /* can only do operations that won't */
                /* trigger garbage collection */
                switch(low) {
                case 0: /* < */
                    if (i < j) {
                        returnedValue = trueObject;
                    } else {
                        returnedValue = falseObject;
                    }
                    break;
                case 1: /* <= */
                    if (i <= j) {
                        returnedValue = trueObject;
                    } else {
                        returnedValue = falseObject;
                    }
                    break;
                case 2: /* + */
                    /* no possibility of garbage col */
                    returnedValue = newInteger(i+j);
                    break;
                }
                stack->data[stackTop++] = returnedValue;
                break;
            }

            /* not integers, do as message send */
            rootStack[rootTop++] = context;
            arguments = gcalloc(2);
            arguments->class = ArrayClass;
            if (context != rootStack[--rootTop]) { /* gc has occurred */
                /* reload context */
                instanceVariables = temporaries = literals = 0;
                context = rootStack[rootTop];
                method = context->data[methodInContext];
                bp = bytePtr(method->data[byteCodesInMethod]);
                stack = context->data[stackInContext];
            }

            /* now load new argument array */
            arguments->data[1] = stack->data[--stackTop];
            arguments->data[0] = stack->data[--stackTop];
            /* now go send message */
            messageSelector = binaryMessages[low];
            goto findMethodFromSymbol;

            /*
            * Pull two integers of the required class as arguments from stack
            */
#define GET_HIGH_LOW() \
    op = stack->data[--stackTop]; \
    if (!IS_SMALLINT(op)) { \
        stackTop -= 1; \
        goto failPrimitive; \
    } \
    low = integerValue(op); \
    op = stack->data[--stackTop]; \
    if (!IS_SMALLINT(op)) { \
        goto failPrimitive; \
    } \
    high = integerValue(op);

        case DoPrimitive:
            /* low is argument count */
            /* next byte is primitive number */
            high = bp[bytePointer++];
            DBG1("DoPrimitive", high);
            rootStack[rootTop++] = context;
            switch (high) {
            case 1:     /* object identity */
                returnedValue = stack->data[--stackTop];
                if (returnedValue == stack->data[--stackTop]) {
                    returnedValue = trueObject;
                } else {
                    returnedValue = falseObject;
                }
                break;

            case 2:     /* object class */
                returnedValue = stack->data[--stackTop];
                returnedValue = CLASS(returnedValue);
                break;

            case 3: /* print a single character */
                low = integerValue(stack->data[--stackTop]);
                putchar(low); /* fflush(stdout); */
                returnedValue = nilObject;
                break;

            case 4: /* object size */
                returnedValue = stack->data[--stackTop];
                if (IS_SMALLINT(returnedValue)) {
                    high  = 0;
                } else {
                    high = SIZE(returnedValue);
                }
                returnedValue = newInteger(high);
                break;

            case 5:     /* Array at put */
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    stackTop -= 2;
                    goto failPrimitive;
                }
                low = integerValue(op)-1;
                returnedValue = stack->data[--stackTop];
                /* Bounds check */
                if ((low < 0) || (low >= (int)SIZE(returnedValue))) {
                    stackTop -= 1;
                    goto failPrimitive;
                }

                returnedValue->data[low]= stack->data[--stackTop];
                /*
                 * If putting a non-static pointer
                 * into an array in static memory,
                 * register it for GC.
                 */
                if (!isDynamicMemory(returnedValue) && isDynamicMemory(stack->data[stackTop])) {
                    addStaticRoot(&returnedValue->data[low]);
                }
                break;

            case 6:     /* new process execute */
                low = integerValue(stack->data[--stackTop]);
                op = stack->data[--stackTop];
                low = execute(op, low);

                /* return value as a SmallInt */
                returnedValue = newInteger(low);
                break;

            case 7:     /* new object allocation */
                low = integerValue(stack->data[--stackTop]);
                rootStack[rootTop++] = stack->data[--stackTop];
                returnedValue = gcalloc(low);
                returnedValue->class = rootStack[--rootTop];
                while (low > 0) {
                    returnedValue->data[--low] = nilObject;
                }
                break;

            case 8: /* block invocation */
                /* low holds number of arguments */
                returnedValue = stack->data[--stackTop];
                /* put arguments in place */
                high = integerValue(returnedValue->data[argumentLocationInBlock]);
                temporaries = returnedValue->data[temporariesInBlock];
                low -= 2;
                x = (temporaries ? ((int)SIZE(temporaries) - high) : 0);
                if (low >= x) {
                    stackTop -= (low+1);
                    goto failPrimitive;
                }
                while (low >= 0) {
                    temporaries->data[high + low] =
                        stack->data[--stackTop];
                    low--;
                }
                returnedValue->data[previousContextInBlock] =
                    context->data[previousContextInContext];
                context = returnedValue;
                arguments = instanceVariables =
                                literals = 0;
                stack = context->data[stackInContext];
                stackTop = 0;
                method = context->data[methodInBlock];
                bp = bytePtr(method->data[byteCodesInMethod]);
                bytePointer = integerValue(
                                  context->data[bytePointerInBlock]);
                --rootTop;
                goto endPrimitive;

            case 9:     /* read char from input */
                low = getchar();
                if (low == EOF) {
                    returnedValue = nilObject;
                } else {
                    returnedValue = newInteger(low);
                }
                break;

            case 10:    /* small integer addition */
                GET_HIGH_LOW();
                x = high + low;
                if (((high > 0) && (low > 0) && (x < high)) ||
                    ((high < 0) && (low < 0) && (x > high))) {
                    /* overflow... do it with 64 bits */
                    returnedValue = newLInteger(
                                        (int64_t)high + (int64_t)low);
                } else {
                    if (!FITS_SMALLINT(x)) {
                        returnedValue = newLInteger(x);
                    } else {
                        returnedValue = newInteger(x);
                    }
                }
                break;

            case 11:    /* small integer division */
                GET_HIGH_LOW();
                if (low == 0) {
                    goto failPrimitive;
                }
                high /= low;
                returnedValue = newInteger(high);
                break;

            case 12:    /* small integer remainder */
                GET_HIGH_LOW();
                if (low == 0) {
                    goto failPrimitive;
                }
                high %= low;
                returnedValue = newInteger(high);
                break;

            case 13:    /* small integer less than */
                GET_HIGH_LOW();
                if (high < low) {
                    returnedValue = trueObject;
                } else {
                    returnedValue = falseObject;
                }
                break;

            case 14:    /* small integer equality */
                GET_HIGH_LOW();
                if (high == low) {
                    returnedValue = trueObject;
                } else {
                    returnedValue = falseObject;
                }
                break;

            case 15:    /* small integer multiplication */
                GET_HIGH_LOW();
                x = high*low;
                if ((low == 0) || (x/low == high)) {
                    if (!FITS_SMALLINT(x)) {
                        returnedValue = newLInteger(x);
                    } else {
                        returnedValue = newInteger(x);
                    }
                } else {
                    /* overflow... do it with 64 bits */
                    returnedValue = newLInteger(
                                        (int64_t)high * (int64_t)low);
                }
                break;

            case 16:    /* small integer subtraction */
                GET_HIGH_LOW();
                x = high - low;
                if ((low > 0) && (high < 0) && (x > high)) {
                    returnedValue = newLInteger(
                                        (int64_t)high - (int64_t)low);
                } else {
                    if (!FITS_SMALLINT(x)) {
                        returnedValue = newLInteger(x);
                    } else {
                        returnedValue = newInteger(x);
                    }
                }
                break;

            case 18:    /* turn on debugging */
                debugging = 1;
                returnedValue = nilObject;
                break;

            case 19:    /* error trap -- halt execution */
                --rootTop; /* pop context */
                aProcess = rootStack[--rootTop];
                aProcess->data[contextInProcess] = context;
                return(ReturnError);

            case 20:    /* byteArray allocation */
                low = integerValue(stack->data[--stackTop]);
                rootStack[rootTop++] = stack->data[--stackTop];
                returnedValue = gcialloc(low);
                returnedValue->class = rootStack[--rootTop];
                bzero(bytePtr(returnedValue), (size_t)low);
                break;

            case 21:    /* string at */
                low = integerValue(stack->data[--stackTop])-1;
                returnedValue = stack->data[--stackTop];
                if ((low < 0) || (low >= (int)SIZE(returnedValue))) {
                    goto failPrimitive;
                }
                low = bytePtr(returnedValue)[low];
                returnedValue = newInteger(low);
                break;

            case 22:    /* string at put */
                low = integerValue(stack->data[--stackTop])-1;
                returnedValue = stack->data[--stackTop];
                if ((low < 0) || (low >= (int)SIZE(returnedValue))) {
                    stackTop -= 1;
                    goto failPrimitive;
                }
                bytePtr(returnedValue)[low] = (uint8_t)(uint32_t)integerValue(stack->data[--stackTop]);
                break;

            case 23:    /* string clone */
                rootStack[rootTop++] = stack->data[--stackTop];
                rootStack[rootTop++] = returnedValue
                                       = stack->data[--stackTop];
                low = SIZE(returnedValue);
                returnedValue = gcialloc(low);
                messageSelector = rootStack[--rootTop];
                while (low-- > 0)
                    bytePtr(returnedValue)[low] =
                        bytePtr(messageSelector)[low];
                returnedValue->class = rootStack[--rootTop];
                break;

            case 24:    /* array at */
                low = integerValue(stack->data[--stackTop])-1;
                returnedValue = stack->data[--stackTop];
                if ((low < 0) || (low >= (int)SIZE(returnedValue))) {
                    goto failPrimitive;
                }
                returnedValue = returnedValue->data[low];
                break;
#undef GET_HIGH_LOW

            case 25:    /* Integer division */
            case 26:    /* Integer remainder */
            case 27:    /* Integer addition */
            case 28:    /* Integer multiplication */
            case 29:    /* Integer subtraction */
            case 30:    /* Integer less than */
            case 31:    /* Integer equality */
                op = stack->data[--stackTop];
                if (CLASS(op) != IntegerClass) {
                    stackTop -= 1;
                    goto failPrimitive;
                }
                returnedValue = stack->data[--stackTop];
                if (CLASS(returnedValue) != IntegerClass) {
                    goto failPrimitive;
                }
                returnedValue = do_Integer(high,
                                           returnedValue, op);
                if (returnedValue == NULL) {
                    goto failPrimitive;
                }
                break;

            case 32:    /* Integer allocation */
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    goto failPrimitive;
                }
                returnedValue = newLInteger(integerValue(op));
                break;

            case 33:    /* Low order of Integer -> SmallInt */
                op = stack->data[--stackTop];
                i64p = (int64_t *)bytePtr(op);
                l = *i64p;
                x = (int)l;
                if (!FITS_SMALLINT(x)) {
                    goto failPrimitive;
                }
                returnedValue = newInteger(x);
                break;

            case 34:    /* Flush method cache */
                flushCache();
                break;

            case 35:    /* Bulk object exchange */
                op = stack->data[--stackTop];
                if (op->class != ArrayClass) {
                    goto failPrimitive;
                }
                returnedValue = stack->data[--stackTop];
                if (returnedValue->class != ArrayClass) {
                    goto failPrimitive;
                }
                if (SIZE(op) != SIZE(returnedValue)) {
                    goto failPrimitive;
                }
                exchangeObjects(op, returnedValue, SIZE(op));
                break;

            case 36:    /* bitOr: */
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    --stackTop;
                    goto failPrimitive;
                }
                high = integerValue(op);
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    goto failPrimitive;
                }
                returnedValue = newInteger(integerValue(op) | high);
                break;

            case 37:    /* bitAnd: */
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    --stackTop;
                    goto failPrimitive;
                }
                high = integerValue(op);
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    goto failPrimitive;
                }
                returnedValue = newInteger(integerValue(op) & high);
                break;

            case 38:    /* replaceFrom:... */
                returnedValue = stack->data[--stackTop];
                /* compiler is getting cranky.  Original code in comments:
                 *
                 *  if (bulkReplace(returnedValue,
                    stack->data[--stackTop],
                    stack->data[--stackTop],
                    stack->data[--stackTop],
                    stack->data[--stackTop])) {
                        goto failPrimitive;
                    }

                    It complains that the operation of -- may be undefined.  This seems
                    like it should be a fully defined operation, but prefix subtraction
                    may be compiled out in some optimization settings and hoisted above the
                    block for the function arguments?  Not sure.

                    At any rate, the code below replaces this.
                 */
                stackTop -= 4;
                if (bulkReplace(returnedValue,
                                stack->data[stackTop+3],
                                stack->data[stackTop+2],
                                stack->data[stackTop+1],
                                stack->data[stackTop])) {
                    goto failPrimitive;
                }
                break;

            case 39:    /* bitShift: */
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    --stackTop;
                    goto failPrimitive;
                }
                low = integerValue(op);
                op = stack->data[--stackTop];
                if (!IS_SMALLINT(op)) {
                    goto failPrimitive;
                }
                high = integerValue(op);
                if (low < 0) {
                    /* Negative means shift right */
                    low = high >> (-low);
                } else {
                    /* Shift left--catch overflow */
                    low = high << low;
                    if (high > low) {
                        goto failPrimitive;
                    }
                }
                returnedValue = newInteger(low);
                break;

            case 40:    /* Truncate Integer -> SmallInt */
                op = stack->data[--stackTop];
                i64p = (int64_t *)bytePtr(op);
                l = *i64p;
                x = (int)l;
                returnedValue = newInteger(x);
                break;

            default:
                /* pop arguments, try primitive */
                rootStack[rootTop++] = stack;
                arguments = gcalloc(low);
                arguments->class = ArrayClass;
                stack = rootStack[--rootTop];
                while (low > 0) {
                    arguments->data[--low] =
                        stack->data[--stackTop];
                }
                {
                    int failed;

                    returnedValue = primitive(high, arguments, &failed);
                    if (failed) {
                        goto failPrimitive;
                    }
                }
                arguments = 0;
                break;
            }

            /*
             * Restore our context pointer and
             * force a stack return due to successful
             * primitive.
             */
            context = rootStack[--rootTop];
            goto doReturn;

failPrimitive:
            /*
             * Since we're continuing execution from a failed
             * primitive, re-fetch context if a GC had occurred
             * during the failed execution.  Supply a return value
             * for the failed primitive.
             */
            returnedValue = nilObject;
            if (context != rootStack[--rootTop]) {
                context = rootStack[rootTop];
                method = context->data[methodInContext];
                stack = context->data[stackInContext];
                bp = bytePtr(method->data[byteCodesInMethod]);
                arguments = temporaries = literals = instanceVariables = 0;
            }
            stack->data[stackTop++] = nilObject;

endPrimitive:
            /*
             * Done with primitive, continue execution loop
             */
            break;

        case DoSpecial:
            DBG1("DoSpecial", low);
            switch(low) {
            case SelfReturn:
                if (! arguments) {
                    arguments = context->data[argumentsInContext];
                }
                returnedValue = arguments->data[receiverInArguments];
                goto doReturn;

            case StackReturn:
                returnedValue = stack->data[--stackTop];

doReturn:
                context = context->data[previousContextInContext];
doReturn2:
                if ((context == 0) || (context == nilObject)) {
                    aProcess = rootStack[--rootTop];
                    aProcess->data[contextInProcess] = context;
                    aProcess->data[resultInProcess] = returnedValue;
                    return(ReturnReturned);
                }

                arguments = instanceVariables = literals = temporaries = 0;

                stack = context->data[stackInContext];
                stackTop = integerValue(context->data[stackTopInContext]);
                stack->data[stackTop++] = returnedValue;
                method = context->data[methodInContext];
                bp = bytePtr(method->data[byteCodesInMethod]);
                bytePointer = integerValue(context->data[bytePointerInContext]);
                break;

            case BlockReturn:
                returnedValue = stack->data[--stackTop];
                context = context->data[creatingContextInBlock]
                          ->data[previousContextInContext];
                goto doReturn2;

            case Duplicate:
                returnedValue = stack->data[stackTop-1];
                stack->data[stackTop++] = returnedValue;
                break;

            case PopTop:
                stackTop--;
                break;

            case Branch:
                low = VAL;
                bytePointer = low;
                break;

            case BranchIfTrue:
                low = VAL;
                returnedValue = stack->data[--stackTop];
                if (returnedValue == trueObject) {
                    bytePointer = low;
                } else {
                    bytePointer += VALSIZE;
                }
                break;

            case BranchIfFalse:
                low = VAL;
                returnedValue = stack->data[--stackTop];
                if (returnedValue == falseObject) {
                    bytePointer = low;
                } else {
                    bytePointer += VALSIZE;
                }
                break;

            case SendToSuper:
                /* next byte has literal selector number */
                low = bp[bytePointer++];
                if (! literals) {
                    literals = method->data[literalsInMethod];
                }
                messageSelector = literals->data[low];
                receiverClass =
                    method->data[classInMethod]
                    ->data[parentClassInClass];
                arguments = stack->data[--stackTop];
                goto checkCache;

            case Breakpoint:
                /* Back up on top of the breaking location */
                bytePointer -= 1;

                /* Return to our master process */
                aProcess = rootStack[--rootTop];
                aProcess->data[contextInProcess] = context;
                aProcess->data[resultInProcess] = returnedValue;
                context->data[bytePointerInContext] =
                    newInteger(bytePointer);
                context->data[stackTopInContext] = newInteger(stackTop);
                return(ReturnBreak);

            default:
                error("invalid doSpecial %d!", low);
                break;
            }
            break;

        default:
            error("invalid bytecode %d!", high);
            break;
        }
    }
}


text:
package net.mobctrl.activity;

import net.mobctrl.treerecyclerview.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.github.nuptboyzhb.lib.SuperSwipeRefreshLayout;

/**
 * @Author Zheng Haibo
 * @PersonalWebsite http://www.mobctrl.net
 * @Description
 */
public class ScrollViewActivity extends Activity {

    private SuperSwipeRefreshLayout swipeRefreshLayout;

    private ProgressBar progressBar;

    private TextView textView;

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrollview);
        swipeRefreshLayout = (SuperSwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        View child = LayoutInflater.from(swipeRefreshLayout.getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) child.findViewById(R.id.pb_view);
        textView = (TextView) child.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) child.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        swipeRefreshLayout.setHeaderView(child);
        swipeRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        textView.setText("正在刷新");
                        imageView.setVisibility(View.GONE);
                        progressBar.setVisibility(View.VISIBLE);
                        System.out.println("debug:onRefresh");
                        new Handler().postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                swipeRefreshLayout.setRefreshing(false);
                                progressBar.setVisibility(View.GONE);
                                System.out.println("debug:stopRefresh");
                            }
                        }, 2000);
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        System.out.println("debug:distance = " + distance);
                        //myAdapter.updateHeaderHeight(distance);
                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        textView.setText(enable ? "松开刷新" : "下拉刷新");
                        imageView.setVisibility(View.VISIBLE);
                        imageView.setRotation(enable ? 180 : 0);
                    }
                });

    }
}

redpajama_set_name: RedPajamaGithub


text:
describe Nightfury::Metric::Value do
  it "should get a value by delegating to redis" do
    value_metric = Nightfury::Metric::Value.new(:tickets_count)
    flexmock(value_metric.redis).should_receive(:get).with('tickets_count').once
    value_metric.get
  end

  it "should set a value by delegating to redis" do
    value_metric = Nightfury::Metric::Value.new(:tickets_count)
    flexmock(value_metric.redis).should_receive(:set).with('tickets_count', 1).once
    value_metric.set(1)
  end

  it "should increment a value by delegating to redis" do
    value_metric = Nightfury::Metric::Value.new(:tickets_count)
    flexmock(value_metric.redis).should_receive(:incrby).with('tickets_count', 1).once
    value_metric.incr
  end

  it "should decrement a value by delegating to redis" do
    value_metric = Nightfury::Metric::Value.new(:tickets_count)
    flexmock(value_metric.redis).should_receive(:decrby).with('tickets_count', 2).once
    value_metric.decr(2)
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.commons.math3.linear.RealVector.Entry (Commons Math 3.2 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.commons.math3.linear.RealVector.Entry

Packages that use RealVector.Entry

org.apache.commons.math3.linear
Linear algebra support.

Uses of RealVector.Entry in org.apache.commons.math3.linear

Subclasses of RealVector.Entry in org.apache.commons.math3.linear

protected  class
OpenMapRealVector.OpenMapEntry

          Deprecated. Implementation of Entry optimized for OpenMap.

Methods in org.apache.commons.math3.linear that return RealVector.Entry

 RealVector.Entry
RealVector.SparseEntryIterator.next()

          Deprecated.

 RealVector.Entry
OpenMapRealVector.OpenMapSparseIterator.next()

Methods in org.apache.commons.math3.linear that return types with arguments of type RealVector.Entry

 Iterator<RealVector.Entry>
RealVector.iterator()

          Generic dense iterator.

 Iterator<RealVector.Entry>
RealVector.sparseIterator()

          Deprecated. As of 3.1, this method is deprecated, because its interface
 is too confusing (see
 JIRA MATH-875).
 This method will be completely removed in 4.0.

 Iterator<RealVector.Entry>
OpenMapRealVector.sparseIterator()

          Deprecated. Create a sparse iterator over the vector, which may omit some entries.

Methods in org.apache.commons.math3.linear with parameters of type RealVector.Entry

protected  void
RealVector.SparseEntryIterator.advance(RealVector.Entry e)

          Deprecated. Advance an entry up to the next nonzero one.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2003-2013 The Apache Software Foundation. All Rights Reserved.


text:
@(user: models.User)(form: play.data.Form[views.forms.VideoForm])(id: Long)(catMap: java.util.Map[String, Boolean])(publicAccessMap: java.util.Map[String, Boolean])

@*
    Display a form, that allows editing metadata of a video
    VideoForm with a multiple fields:
        @title - title of the video
        @description - description of the video
        @categories - categories, video belongs to
        @publicaccess - whether video is public or not
    Expected input:
        @user - currently logged-in user
        @form - VideoForm with mentioned fields
        @id - id of the video, that is being edited
        @catMap - 'category name' to 'selected' (bool) map
        @publicAccessMap - {'Yes'/'No'} string to 'selected' (bool) map
*@

@import bootstrap3._

@stylesheets = {
    <link rel="stylesheet" href="@routes.Assets.at("stylesheets/admin.css")" />
    <link rel="stylesheet" href="@routes.Assets.at("stylesheets/chosen.min.css")" />
}

@javascripts = {

}

@main("Your Video Management Page - Careers From Here")(stylesheets)(javascripts)(user) {

Edit video metadata

            @helper.form(action = routes.UserController.postVideo(id)) {
                <fieldset>
                    @text(form("title"),
                        label = "Title")
                    @textarea(form("description"),
                        label = "Description",
                        help = "Provide brief summary of the video.")
                    @select(form("categories"),
                        label = "Categories",
                        isMultiple = true,
                        optionMap = catMap)
                    @select(form("publicaccess"),
                        isMultiple = false,
                        optionMap = publicAccessMap,
                        label = "Public Access")

                            <button id="submit" type="submit" value="Submit" class="btn btn-primary">Submit</button>

                </fieldset>
            }

}


text:
function fvcBubbleChart() {
  var diameter = 800,
      format = d3.format(",d"),
      color = d3.scale.category20c();

  function chart(selection) {
    selection.each(function(data) {
      var svg = d3.select(this).selectAll("svg").data([data]);

      var bubble = d3.layout.pack()
          .sort(null)
          .size([diameter, diameter])
          .padding(1.5);

      svg.enter().append("svg")
          .attr("class", "bubble");

      svg.attr("width", diameter)
          .attr("height", diameter);
      var bdata = bubble.nodes({children: data})
          .filter(function(d) { return !d.children; });
      var nodes = svg.selectAll("g.node")
        .data(bdata, function(d) { return d.key; });

      var gEnter = nodes.enter().append("g")
          .attr("class", "node");
          //.attr("transform", function(d) { console.log(d); return "translate(" + d.x + "," + d.y + ")"; });
      gEnter.append("title");
      gEnter.append("circle")
            .style("fill", function(d) { return color(d.key); });
      gEnter.append("text")
          .attr("dy", ".3em")
          .style("text-anchor", "middle");

      nodes.exit().select("circle").transition().duration(500).attr("r", function(d) { return 0; }).remove();
      nodes.exit().remove();
      nodes.transition()
        .duration(1000)
          .attr("transform", function(d) { return "translate(" + (d.x) + "," + d.y + ")"; })
        .select("circle")
          .transition()
          .duration(500).attr("r", function(d) { return d.r; });
      nodes.select("title").text(function(d) { return d.key + ": " + format(d.value); });
      //nodes.select("circle").attr("r", function(d) { return d.r; });
      nodes.select("text").text(function(d) {return d.key.substring(0, d.r / 3); });
    });
  }

  chart.diameter = function(_) {
    if (!arguments.length) return diameter;
    diameter = _;
    return chart;
  };

  return chart;
}

function trans(d) {
  return "translate(" + d.x + "," + d.y + ")";
}

function fvcPieChart() {
  var width = 500,
      height = 500,
      r      = 200,
      minSlice = 0.007,
      xValue = function(d) { return d.key; },
      yValue = function(d) { return +d.value; };

  function chart(selection) {
    selection.each(function(data) {
      // Convert data to standard representation greedily;
      // this is needed for nondeterministic accessors.
      data = data.map(function(d, i) {
        return [xValue.call(data, d, i), yValue.call(data, d, i)];
      });

      var total = d3.sum(data, function(d) { return d[1]; });
      var otherTotal = 0;

      // Add anything less than minSlice to "other"
      data = data.filter(function(d) {
        var bigEnough = d[1]/total >= minSlice;
        if (!bigEnough) {
          otherTotal += d[1];
        }
        return bigEnough;
      });

      data.push(["other", otherTotal]);

      var svg = d3.select(this).selectAll("svg").data([data]);

      var color = d3.scale.category20c();

      svg.enter()
        .append("svg")
        .append("g");
      svg.attr("width", width);
      svg.attr("height", height);

      var g = svg.select("g")
          .attr("transform", "translate(" + width/2 + "," + height/2 + ")");
      //var r = Math.min(width, height) / 2;

      var arc = d3.svg.arc()
          .outerRadius(r - 10)
          .innerRadius(0);

      var pie = d3.layout.pie()
          .sort(null)
          .value(function(d) { return d[1]; });

      var pieData = pie(data);

      g.selectAll(".arc").remove();
      var arcs = g.selectAll(".arc")
          .data(pieData);

      arcs.enter().append("g")
          .attr("class", "arc");

      arcs.append("path")
          .attr("d", arc)
          .style("fill", function(d) { return color(d.data[0]); });

      g.selectAll("line").remove();

      var lines = g.selectAll("line").data(pieData);
      lines.enter().append("line")
        .attr("x1", 0)
        .attr("x2", 0)
        .attr("y1", -r-3)
        .attr("y2", -r-8)
        .attr("stroke", "gray")
        .attr("transform", function(d) {
          return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
        });

      var textOffset = 14;
      arcs.append("text")
        .attr("transform", function(d) {
              var centroid = arc.centroid(d),
                  x = centroid[0],
                  y = centroid[1];
          return "translate(" + 2.3*x  + "," + 2.3*y + ")"; })
        .attr("dy", ".35em")
        .style("text-anchor", "middle")
        .text(function(d) { return d.data[0]; });

   });
  }

  chart.width = function(_) {
    if (!arguments.length) return width;
    width = _;
    return chart;
  };

  chart.height = function(_) {
    if (!arguments.length) return height;
    height = _;
    return chart;
  };

  chart.r = function(_) {
    if (!arguments.length) return r;
    r = _;
    return chart;
  };

  chart.minSlice = function(_) {
    if (!arguments.length) return minSlice;
    minSlice = _;
    return chart;
  };

  chart.x = function(_) {
    if (!arguments.length) return xValue;
    xValue = _;
    return chart;
  };

  chart.y = function(_) {
    if (!arguments.length) return yValue;
    yValue = _;
    return chart;
  };

  return chart;
}


text:
using BlueSheep.Common.Data;
using BlueSheep.Common.Data.D2o;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlueSheep.Common.Types
{
    public class Spell
    {
        public Spell(int id, int level, int position)
        {
            Id = id;
            Level = level;
            Position = position;
        }

        public int Id { get; private set; }
        public int Level { get; internal set; }
        public int Position { get; private set; }

        public string GetName()
        {
            //GameDataFileAccessor access = new GameDataFileAccessor();
            //BlueSheep.Common.Data.DataCenter.Fight.Spell spell = (BlueSheep.Common.Data.DataCenter.Fight.Spell)access.GetObject("Spells",Id);
            DataClass spell = GameData.GetDataObject(D2oFileEnum.Spells, Id);
            return I18N.GetText((int)spell.Fields["nameId"]);
        }
    }
}


text:
package com.github.TKnudsen.DMandML.data.cluster;

import java.util.List;

import com.github.TKnudsen.ComplexDataObject.data.interfaces.IDObject;
import com.github.TKnudsen.ComplexDataObject.data.interfaces.ISelfDescription;

public interface IClusteringResult<T, C extends ICluster<T>> extends IDObject, ISelfDescription, Iterable<C> {

	boolean containsCluster(C c);

	List<C> getClusters();

	/**
	 * retrieves the index of the cluster, if a given object is assigned to one of
	 * the clusters.
	 *
	 * @deprecated this should never be necessary. try to avoid and use cluster
	 *             objects instead
	 * @param object the query object
	 * @return -1 if not assigned. else the cluster index w.r.t. the index of the
	 *         internal cluster list.
	 */
	int getClusterIndex(T object);

	/**
	 * Retrieves the cluster for a given object. Returns null if object was not
	 * subject to the clustering routine, though.
	 *
	 * @param object the query object
	 * @return the cluster of the query object
	 */
	C getCluster(T object);

	/**
	 * Retrieves the cluster for a given object. If getClusterMapping is null (if
	 * object was not part of the clustering routine) AND
	 * retrievNearestWhenUnassigned is set true, the method retrieves the nearest
	 * cluster for the object.
	 *
	 * @param object the query feature vector object
	 * @return the cluster that is retrieved for the feature vector object, if any
	 */
	C retrieveCluster(T object);

	int size();

	int hashCode();

	boolean equals(Object obj);

}


text:
#ifndef _ASILens_H_
#define _ASILens_H_

#include "ASIPeripheralBase.h"
#include "../../MMDevice/MMDevice.h"
#include "../../MMDevice/DeviceBase.h"

class CLens : public ASIPeripheralBase<CStageBase, CLens>
{
public:
   CLens(const char* name);
   ~CLens() { }

   // Device API
   // ----------
   int Initialize();
   bool Busy();

   // Lens API
   // -----------
   int Stop();
   int Home();

   // the step size is the programming unit for dimensions and is integer
   // see http://micro-manager.3463995.n2.nabble.com/what-are-quot-steps-quot-for-stages-td7580724.html
   double GetStepSize() {return stepSizeUm_;}
   int GetPositionSteps(long& steps);
   int SetPositionSteps(long steps);
   int SetPositionUm(double pos);
   int GetPositionUm(double& pos);
   int SetRelativePositionUm(double d);
   int GetLimits(double& min, double& max);
   int SetOrigin();

   bool IsContinuousFocusDrive() const { return false; }  // todo figure out what this means and if it's accurate

   int IsStageSequenceable(bool& isSequenceable) const { isSequenceable = ttl_trigger_enabled_; return DEVICE_OK; }
   int GetStageSequenceMaxLength(long& nrEvents) const { nrEvents = ring_buffer_capacity_; return DEVICE_OK; }

   // special firmware required for sequence (TTL triggering)
   int StartStageSequence();
   int StopStageSequence();
   int ClearStageSequence();
   int AddToStageSequence(double position);
   int SendStageSequence();

   // action interface
   // ----------------
   int OnSaveCardSettings     (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnRefreshProperties    (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnLowerLim             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnUpperLim             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnLensMode            (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnJoystickFastSpeed    (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnJoystickSlowSpeed    (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnJoystickMirror       (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnJoystickSelect       (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnWheelFastSpeed       (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnWheelSlowSpeed       (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnWheelMirror          (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnMotorControl         (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnAxisPolarity         (MM::PropertyBase* pProp, MM::ActionType eAct);
   // single axis properties
   int OnSAAmplitude          (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAOffset             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAPeriod             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAMode               (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAPattern            (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAAdvanced           (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAClkSrc             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAClkPol             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSATTLOut             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSATTLPol             (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnSAPatternByte        (MM::PropertyBase* pProp, MM::ActionType eAct);
   // ring buffer properties
   int OnRBDelayBetweenPoints (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnRBMode               (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnRBTrigger            (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnRBRunning            (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnUseSequence          (MM::PropertyBase* pProp, MM::ActionType eAct);
   //Others
   int OnVector				  (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnTTLin				  (MM::PropertyBase* pProp, MM::ActionType eAct);
   int OnTTLout			      (MM::PropertyBase* pProp, MM::ActionType eAct);

private:
   double unitMult_;
   double stepSizeUm_;
   string axisLetter_;
   bool ring_buffer_supported_;
   long ring_buffer_capacity_;
   bool ttl_trigger_supported_;
   bool ttl_trigger_enabled_;
   std::vector<double> sequence_;

   // private helper functions
   int OnSaveJoystickSettings();
};

#endif //_ASIPiezo_H_


text:
using System;
using System.Globalization;
using Put.io.Core.Common;
using Put.io.Core.Extensions;

namespace Put.io.Core.Models
{
    public class Transfer : ViewModelBase
    {

        #region Properties
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name == value) return;

                _name = value;
                OnPropertyChanged();
            }
        }

        private int _transferID;
        public int TransferID
        {
            get { return _transferID; }
            set
            {
                if (_transferID == value) return;

                _transferID = value;
                OnPropertyChanged();
            }
        }

        private long _size;
        public long Size
        {
            get { return _size; }
            set
            {
                if (_size == value) return;

                _size = value;
                OnPropertyChanged();
            }
        }

        private int _percentComplete;
        public int PercentComplete
        {
            get { return _percentComplete; }
            set
            {
                if (_percentComplete == value) return;

                _percentComplete = value;
                OnPropertyChanged();
            }
        }

        private StatusType _status;
        public StatusType Status
        {
            get { return _status; }
            set
            {
                if (_status == value) return;

                _status = value;
                OnPropertyChanged();
            }
        }

        private int _timeRemaining;
        public int TimeRemaining
        {
            get { return _timeRemaining; }
            set
            {
                if (_timeRemaining == value) return;

                _timeRemaining = value;
                OnPropertyChanged();
            }
        }

        private int _downSpeed;
        public int DownSpeed
        {
            get { return _downSpeed; }
            set
            {
                if (_downSpeed == value) return;

                _downSpeed = value;
                OnPropertyChanged();
            }
        }
        #endregion
    }
}


text:
<button
    color="primary"
    mat-button
    mat-raised-button
    mat-icon-button
    class="adf-create-attachment"
    [adf-upload]="true"
    [mode]="['click']"
    [multiple]="true"
    (upload-files)="onFileUpload($event)">
    <mat-icon>add</mat-icon>
</button>


text:
package iotools

import (
	"io"
)

// CountingWriter is an io.Writer that counts the number of bytes that are
// written.
type CountingWriter struct {
	io.Writer // The underlying io.Writer.

	// Count is the number of bytes that have been written.
	Count int64

	singleByteBuf [1]byte
}

var _ io.Writer = (*CountingWriter)(nil)

// Write implements io.Writer.
func (c *CountingWriter) Write(buf []byte) (int, error) {
	amount, err := c.Writer.Write(buf)
	c.Count += int64(amount)
	return amount, err
}

// WriteByte implements io.ByteWriter.
func (c *CountingWriter) WriteByte(b byte) error {
	// If our underlying Writer is a ByteWriter, use its WriteByte directly.
	if bw, ok := c.Writer.(io.ByteWriter); ok {
		if err := bw.WriteByte(b); err != nil {
			return err
		}
		c.Count++
		return nil
	}

	c.singleByteBuf[0] = b
	_, err := c.Write(c.singleByteBuf[:])
	return err
}


text:
    #ifdef __STRICT_ANSI__
    #undef __STRICT_ANSI__
    #endif
#endif

#include "../structures/point3d.h"
#include "../structures/boundingbox.h"
#include "../structures/pointerless_octree.h"
#include "test_helpers.h"

#include <vector>
#include <iterator>
#include "gtest/gtest.h"

using std::vector;
using std::array;

class PointerlessOctreeTest : public OctreeTest {};

TEST_F(PointerlessOctreeTest, DefaultConstructor) {
    PointerlessOctree<std::vector<ValuePoint<int>>::iterator, ExamplePointExtractor<int>> o;
    EXPECT_EQ(o.size(), 0);
}

TEST_F(PointerlessOctreeTest, DefaultConstructorMaxDepthSmall) {
    PointerlessOctree<std::vector<ValuePoint<int>>::iterator, ExamplePointExtractor<int>, 16, 3> o;
    EXPECT_EQ(o.size(), 0);
}

TEST_F(PointerlessOctreeTest, DefaultConstructorMaxPerNodeLarge) {
    PointerlessOctree<std::vector<ValuePoint<int>>::iterator, ExamplePointExtractor<int>, 100> o;
    EXPECT_EQ(o.size(), 0);
}

TEST_F(PointerlessOctreeTest, IteratorConstructor) {
    PointerlessOctree<std::vector<ValuePoint<int>>::iterator, ExamplePointExtractor<int>> o(data.begin(), data.end());
    EXPECT_EQ(o.size(), 100);
}

TEST_F(PointerlessOctreeTest, IteratorConstructorMaxDepthSmall) {
    PointerlessOctree<std::vector<ValuePoint<int>>::iterator, ExamplePointExtractor<int>, 16, 3> o(data.begin(), data.end());
    EXPECT_EQ(o.size(), 100);
}

TEST_F(PointerlessOctreeTest, IteratorConstructorMaxPerNodeLarge) {
    PointerlessOctree<std::vector<ValuePoint<int>>::iterator, ExamplePointExtractor<int>, 100> o(data.begin(), data.end());
    EXPECT_EQ(o.size(), 100);
}

TEST_F(PointerlessOctreeTest, BoxSearchNotPresent) {
    PointerlessOctree<vector<ValuePoint<int>>::const_iterator, ExamplePointExtractor<int>> o(data.cbegin(), data.cend());
    vector<vector<ValuePoint<int>>::const_iterator> outputValues;
    auto outputIterator = back_inserter(outputValues);
    BoundingBox box{{-5, -5, -5}, {-10, -10, -10}};
    EXPECT_FALSE(o.search(box, outputIterator));
}

TEST_F(PointerlessOctreeTest, BoxSearchPresent) {
    PointerlessOctree<vector<ValuePoint<int>>::const_iterator, ExamplePointExtractor<int>> o(data.cbegin(), data.cend());
    vector<vector<ValuePoint<int>>::const_iterator> outputValues;
    auto outputIterator = back_inserter(outputValues);
    BoundingBox box{{5, 5, 5}, {10, 10, 10}};

    vector<vector<ValuePoint<int>>::const_iterator> expectedValues;
    for (auto it = data.cbegin(); it != data.cend(); ++it) {
        if (box.contains(ExamplePointExtractor<int>()(*it))) {
            expectedValues.push_back(it);
        }
    }
    EXPECT_TRUE(o.search(box, outputIterator));
    EXPECT_EQ(expectedValues, outputValues);
}

TEST_F(PointerlessOctreeTest, BoxSearchAll) {
    PointerlessOctree<vector<ValuePoint<int>>::const_iterator, ExamplePointExtractor<int>> o(data.cbegin(), data.cend());
    vector<vector<ValuePoint<int>>::const_iterator> outputValues;
    auto outputIterator = back_inserter(outputValues);

    vector<vector<ValuePoint<int>>::const_iterator> expectedValues;
    for (auto it = data.cbegin(); it != data.cend(); ++it) {
        if (allBox.contains(ExamplePointExtractor<int>()(*it))) {
            expectedValues.push_back(it);
        }
    }

    // Verify that all of the values are in the box
    EXPECT_EQ(data.size(), expectedValues.size());

    // Verify that something was found
    EXPECT_TRUE(o.search(allBox, outputIterator));

    // Verify that we got as many things out as we wanted to
    EXPECT_EQ(outputValues.size(), expectedValues.size());

    // Verify that each element is the same
    for (size_t index = 0; index < std::min(expectedValues.size(), outputValues.size()); ++index) {
        EXPECT_EQ(outputValues[index], expectedValues[index]) << "At index: " << index;
    }
}


text:
utility-categories
==================

Various utility categories that I find useful.  I will add categories as I find new usecases.

It does the following things so far:
* Configurable shadows for UIViews without too much repetitive CALayer stuff.
* Create bold and italic versions of a font.
* Enable font scaling for multi-line UILabels. (largest font that fits.)
* Allows font and color manipulation on mutable attributed strings (ios 6 style)


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/securitycenter/v1/access.proto

package com.google.cloud.securitycenter.v1;

/**
 *
 *
 *

 * Represents a geographical location for a given access.
 *

 *
 * Protobuf type {@code google.cloud.securitycenter.v1.Geolocation}
 */
public final class Geolocation extends com.google.protobuf.GeneratedMessageV3
    implements
    // @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1.Geolocation)
    GeolocationOrBuilder {
  private static final long serialVersionUID = 0L;
  // Use Geolocation.newBuilder() to construct.
  private Geolocation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }

  private Geolocation() {
    regionCode_ = "";
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
    return new Geolocation();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
    return this.unknownFields;
  }

  public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
    return com.google.cloud.securitycenter.v1.AccessProto
        .internal_static_google_cloud_securitycenter_v1_Geolocation_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.cloud.securitycenter.v1.AccessProto
        .internal_static_google_cloud_securitycenter_v1_Geolocation_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.cloud.securitycenter.v1.Geolocation.class,
            com.google.cloud.securitycenter.v1.Geolocation.Builder.class);
  }

  public static final int REGION_CODE_FIELD_NUMBER = 1;
  private volatile java.lang.Object regionCode_;
  /**
   *
   *
   *

   * A CLDR.
   *

   *
   * string region_code = 1;
   *
   * @return The regionCode.
   */
  @java.lang.Override
  public java.lang.String getRegionCode() {
    java.lang.Object ref = regionCode_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      regionCode_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * A CLDR.
   *

   *
   * string region_code = 1;
   *
   * @return The bytes for regionCode.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString getRegionCodeBytes() {
    java.lang.Object ref = regionCode_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      regionCode_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  private byte memoizedIsInitialized = -1;

  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(regionCode_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 1, regionCode_);
    }
    getUnknownFields().writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(regionCode_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, regionCode_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof com.google.cloud.securitycenter.v1.Geolocation)) {
      return super.equals(obj);
    }
    com.google.cloud.securitycenter.v1.Geolocation other =
        (com.google.cloud.securitycenter.v1.Geolocation) obj;

    if (!getRegionCode().equals(other.getRegionCode())) return false;
    if (!getUnknownFields().equals(other.getUnknownFields())) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + REGION_CODE_FIELD_NUMBER;
    hash = (53 * hash) + getRegionCode().hashCode();
    hash = (29 * hash) + getUnknownFields().hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseDelimitedFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseDelimitedFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      com.google.protobuf.CodedInputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.securitycenter.v1.Geolocation parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() {
    return newBuilder();
  }

  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

  public static Builder newBuilder(com.google.cloud.securitycenter.v1.Geolocation prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }

  @java.lang.Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *
   *
   *

   * Represents a geographical location for a given access.
   *

   *
   * Protobuf type {@code google.cloud.securitycenter.v1.Geolocation}
   */
  public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
      implements
      // @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1.Geolocation)
      com.google.cloud.securitycenter.v1.GeolocationOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
      return com.google.cloud.securitycenter.v1.AccessProto
          .internal_static_google_cloud_securitycenter_v1_Geolocation_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.cloud.securitycenter.v1.AccessProto
          .internal_static_google_cloud_securitycenter_v1_Geolocation_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.cloud.securitycenter.v1.Geolocation.class,
              com.google.cloud.securitycenter.v1.Geolocation.Builder.class);
    }

    // Construct using com.google.cloud.securitycenter.v1.Geolocation.newBuilder()
    private Builder() {}

    private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);
    }

    @java.lang.Override
    public Builder clear() {
      super.clear();
      regionCode_ = "";

      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
      return com.google.cloud.securitycenter.v1.AccessProto
          .internal_static_google_cloud_securitycenter_v1_Geolocation_descriptor;
    }

    @java.lang.Override
    public com.google.cloud.securitycenter.v1.Geolocation getDefaultInstanceForType() {
      return com.google.cloud.securitycenter.v1.Geolocation.getDefaultInstance();
    }

    @java.lang.Override
    public com.google.cloud.securitycenter.v1.Geolocation build() {
      com.google.cloud.securitycenter.v1.Geolocation result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @java.lang.Override
    public com.google.cloud.securitycenter.v1.Geolocation buildPartial() {
      com.google.cloud.securitycenter.v1.Geolocation result =
          new com.google.cloud.securitycenter.v1.Geolocation(this);
      result.regionCode_ = regionCode_;
      onBuilt();
      return result;
    }

    @java.lang.Override
    public Builder clone() {
      return super.clone();
    }

    @java.lang.Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return super.setField(field, value);
    }

    @java.lang.Override
    public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
      return super.clearField(field);
    }

    @java.lang.Override
    public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return super.clearOneof(oneof);
    }

    @java.lang.Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
      return super.setRepeatedField(field, index, value);
    }

    @java.lang.Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return super.addRepeatedField(field, value);
    }

    @java.lang.Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof com.google.cloud.securitycenter.v1.Geolocation) {
        return mergeFrom((com.google.cloud.securitycenter.v1.Geolocation) other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(com.google.cloud.securitycenter.v1.Geolocation other) {
      if (other == com.google.cloud.securitycenter.v1.Geolocation.getDefaultInstance()) return this;
      if (!other.getRegionCode().isEmpty()) {
        regionCode_ = other.regionCode_;
        onChanged();
      }
      this.mergeUnknownFields(other.getUnknownFields());
      onChanged();
      return this;
    }

    @java.lang.Override
    public final boolean isInitialized() {
      return true;
    }

    @java.lang.Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      if (extensionRegistry == null) {
        throw new java.lang.NullPointerException();
      }
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            case 10:
              {
                regionCode_ = input.readStringRequireUtf8();

                break;
              } // case 10
            default:
              {
                if (!super.parseUnknownField(input, extensionRegistry, tag)) {
                  done = true; // was an endgroup tag
                }
                break;
              } // default:
          } // switch (tag)
        } // while (!done)
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.unwrapIOException();
      } finally {
        onChanged();
      } // finally
      return this;
    }

    private java.lang.Object regionCode_ = "";
    /**
     *
     *
     *

     * A CLDR.
     *

     *
     * string region_code = 1;
     *
     * @return The regionCode.
     */
    public java.lang.String getRegionCode() {
      java.lang.Object ref = regionCode_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        regionCode_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     *
     *
     *

     * A CLDR.
     *

     *
     * string region_code = 1;
     *
     * @return The bytes for regionCode.
     */
    public com.google.protobuf.ByteString getRegionCodeBytes() {
      java.lang.Object ref = regionCode_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
        regionCode_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *
     *
     *

     * A CLDR.
     *

     *
     * string region_code = 1;
     *
     * @param value The regionCode to set.
     * @return This builder for chaining.
     */
    public Builder setRegionCode(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }

      regionCode_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * A CLDR.
     *

     *
     * string region_code = 1;
     *
     * @return This builder for chaining.
     */
    public Builder clearRegionCode() {

      regionCode_ = getDefaultInstance().getRegionCode();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * A CLDR.
     *

     *
     * string region_code = 1;
     *
     * @param value The bytes for regionCode to set.
     * @return This builder for chaining.
     */
    public Builder setRegionCodeBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);

      regionCode_ = value;
      onChanged();
      return this;
    }

    @java.lang.Override
    public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

    @java.lang.Override
    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:google.cloud.securitycenter.v1.Geolocation)
  }

  // @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Geolocation)
  private static final com.google.cloud.securitycenter.v1.Geolocation DEFAULT_INSTANCE;

  static {
    DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v1.Geolocation();
  }

  public static com.google.cloud.securitycenter.v1.Geolocation getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<Geolocation> PARSER =
      new com.google.protobuf.AbstractParser<Geolocation>() {
        @java.lang.Override
        public Geolocation parsePartialFrom(
            com.google.protobuf.CodedInputStream input,
            com.google.protobuf.ExtensionRegistryLite extensionRegistry)
            throws com.google.protobuf.InvalidProtocolBufferException {
          Builder builder = newBuilder();
          try {
            builder.mergeFrom(input, extensionRegistry);
          } catch (com.google.protobuf.InvalidProtocolBufferException e) {
            throw e.setUnfinishedMessage(builder.buildPartial());
          } catch (com.google.protobuf.UninitializedMessageException e) {
            throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
          } catch (java.io.IOException e) {
            throw new com.google.protobuf.InvalidProtocolBufferException(e)
                .setUnfinishedMessage(builder.buildPartial());
          }
          return builder.buildPartial();
        }
      };

  public static com.google.protobuf.Parser<Geolocation> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<Geolocation> getParserForType() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.cloud.securitycenter.v1.Geolocation getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }
}


text:
package spring.condition;

public class MagicBean {

}


text:
require "spec_helper"
require "openc_bot"
require "openc_bot/helpers/alpha_search"

module ModuleThatIncludesAlphaSearch
  extend OpencBot
  extend OpencBot::Helpers::AlphaSearch
end

describe "a module that includes AlphaSearch" do
  before do
    allow(ModuleThatIncludesAlphaSearch).to receive(:sqlite_magic_connection)
      .and_return(test_database_connection)
  end

  after do
    remove_test_database
  end

  it "includes register_methods" do
    expect(ModuleThatIncludesAlphaSearch).to respond_to(:registry_url)
  end

  describe "#letters_and_numbers" do
    it "returns an array of all letters and numbers" do
      expect(ModuleThatIncludesAlphaSearch.letters_and_numbers).to eq(("A".."Z").to_a + ("0".."9").to_a)
    end
  end

  describe "numbers_of_chars_in_search" do
    context "and no NUMBER_OF_CHARS_IN_SEARCH constant" do
      it "returns 1" do
        expect(ModuleThatIncludesAlphaSearch.numbers_of_chars_in_search).to eq(1)
      end
    end

    context "and has NUMBER_OF_CHARS_IN_SEARCH constant" do
      it "returns NUMBER_OF_CHARS_IN_SEARCH" do
        stub_const("ModuleThatIncludesAlphaSearch::NUMBER_OF_CHARS_IN_SEARCH", 4)
        expect(ModuleThatIncludesAlphaSearch.numbers_of_chars_in_search).to eq(ModuleThatIncludesAlphaSearch::NUMBER_OF_CHARS_IN_SEARCH)
      end
    end
  end

  describe "#alpha_terms" do
    before do
      @letters_and_numbers = %w[A B 1 2]
      allow(ModuleThatIncludesAlphaSearch).to receive(:letters_and_numbers).and_return(@letters_and_numbers)
    end

    it "returns array of letters_and_numbers based on numbers_of_chars_in_search" do
      expect(ModuleThatIncludesAlphaSearch.alpha_terms).to eq(@letters_and_numbers)
      expect(ModuleThatIncludesAlphaSearch).to receive(:numbers_of_chars_in_search).and_return(2)
      expect(ModuleThatIncludesAlphaSearch.alpha_terms)
        .to eq(@letters_and_numbers.repeated_permutation(2).collect(&:join))
    end

    context "and starting character given" do
      it "starts array from given character" do
        expect(ModuleThatIncludesAlphaSearch.alpha_terms("B")).to eq(@letters_and_numbers[1..-1])
        allow(ModuleThatIncludesAlphaSearch).to receive(:numbers_of_chars_in_search).and_return(2)
        expect(ModuleThatIncludesAlphaSearch.alpha_terms("1B"))
          .to eq(%w[1B 11 12 2A 2B 21 22])
      end

      it "starts array from beginning if no such character" do
        expect(ModuleThatIncludesAlphaSearch.alpha_terms("X")).to eq(@letters_and_numbers)
        allow(ModuleThatIncludesAlphaSearch).to receive(:numbers_of_chars_in_search).and_return(2)
        expect(ModuleThatIncludesAlphaSearch.alpha_terms("C"))
          .to eq(@letters_and_numbers.repeated_permutation(2).collect(&:join))
      end
    end
  end

  describe "each_search_term" do
    before do
      allow(ModuleThatIncludesAlphaSearch).to receive(:alpha_terms).with("B").and_return(%w[C D])
    end

    it "iterates through alpha_terms and yield them" do
      yielded_data = []
      ModuleThatIncludesAlphaSearch.each_search_term("B") { |t| yielded_data << "#{t}#{t}" }
      expect(yielded_data).to eq(%w[CC DD])
    end

    context "and no block given" do
      it "returns alpha_terms" do
        expect(ModuleThatIncludesAlphaSearch.each_search_term("B")).to eq(%w[C D])
      end
    end
  end

  describe "#fetch_data_via_alpha_search" do
    before do
      @alpha_terms = %w[A1 B2 XX YY]
      allow(ModuleThatIncludesAlphaSearch).to receive(:create_new_company)
      allow(ModuleThatIncludesAlphaSearch).to receive(:save_entity)
      allow(ModuleThatIncludesAlphaSearch).to receive(:alpha_terms).and_return(@alpha_terms)
      allow(ModuleThatIncludesAlphaSearch).to receive(:search_for_entities_for_term).and_yield(nil)
    end

    it "search_for_entities_for_terms for each term in alpha_terms" do
      @alpha_terms.each do |term|
        expect(ModuleThatIncludesAlphaSearch).to receive(:search_for_entities_for_term).with(term, anything).and_yield(nil)
      end
      ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search
    end

    it "processes entity data yielded by search_for_entities_for_term" do
      @alpha_terms.each do |term|
        allow(ModuleThatIncludesAlphaSearch).to receive(:search_for_entities_for_term).with(term, anything).and_yield(:datum_1).and_yield(:datum_2)
      end
      expect(ModuleThatIncludesAlphaSearch).to receive(:save_entity).with(:datum_1)
      expect(ModuleThatIncludesAlphaSearch).to receive(:save_entity).with(:datum_2)

      ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search
    end

    it "starts from saved starting term" do
      ModuleThatIncludesAlphaSearch.save_var("starting_term", "B2")
      expect(ModuleThatIncludesAlphaSearch).to receive(:alpha_terms).with("B2").and_return(@alpha_terms)

      ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search
    end

    it "passes options to search_for_entities_for_term" do
      expect(ModuleThatIncludesAlphaSearch).to receive(:search_for_entities_for_term).with(anything, foo: "bar").and_yield(nil)

      ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search(foo: "bar")
    end

    context "and explicit starting_term passed in as option" do
      it "starts from given starting term" do
        ModuleThatIncludesAlphaSearch.save_var("starting_term", "B2")
        expect(ModuleThatIncludesAlphaSearch).to receive(:alpha_terms).with("XX").and_return(@alpha_terms)

        ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search(starting_term: "XX")
      end
    end

    context "and search gets to end of alpha_terms" do
      it "flushes starting_term record" do
        ModuleThatIncludesAlphaSearch.save_var("starting_term", "B2")

        ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search
        expect(ModuleThatIncludesAlphaSearch.get_var("starting_term")).to be_nil
      end
    end

    context "and search finishes before getting to end of alpha_terms" do
      it "stores term where it was working on where there was problem" do
        expect(ModuleThatIncludesAlphaSearch).to receive(:search_for_entities_for_term)
          .with(@alpha_terms.first, anything).and_yield(nil)

        expect(ModuleThatIncludesAlphaSearch).to receive(:search_for_entities_for_term)
          .with(@alpha_terms[1], anything).and_raise("Something has gone wrong")

        expect { ModuleThatIncludesAlphaSearch.fetch_data_via_alpha_search }.to raise_error(RuntimeError, "Something has gone wrong")
        expect(ModuleThatIncludesAlphaSearch.get_var("starting_term")).to eq(@alpha_terms[1])
      end
    end
  end

  describe "#search_for_entities_for_term" do
    it "raises exception" do
      expect { ModuleThatIncludesAlphaSearch.search_for_entities_for_term("foo") }.to raise_error(/method has not been implemented/)
    end
  end
end


text:
namespace System.Runtime.InteropServices
{

#if CONFIG_COM_INTEROP && CONFIG_FRAMEWORK_2_0

public sealed class BStrWrapper
{
	// Internal state.
	private String value;

	// Constructors.
	public BStrWrapper(String value)
			{
				this.value = value;
			}

	// Get the wrapped dispatch object value.
	public String WrappedObject
			{
				get
				{
					return value;
				}
			}

}; // class BStrWrapper

#endif // CONFIG_COM_INTEROP && CONFIG_FRAMEWORK_2_0

}; // namespace System.Runtime.InteropServices


text:
@interface PodsDummy_MRGLaunchImageViewController : NSObject
@end
@implementation PodsDummy_MRGLaunchImageViewController
@end