text:
#include "util.h"
#include "ThreadReferenceImpl.h"
#include "eventHandler.h"
#include "threadControl.h"
#include "inStream.h"
#include "outStream.h"
#include "FrameID.h"

static jboolean
name(PacketInputStream *in, PacketOutputStream *out)
{
    JNIEnv *env;
    jthread thread;

    env = getEnv();

    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    WITH_LOCAL_REFS(env, 1) {

        jvmtiThreadInfo info;
        jvmtiError error;

        (void)memset(&info, 0, sizeof(info));

        error = JVMTI_FUNC_PTR(gdata->jvmti,GetThreadInfo)
                                (gdata->jvmti, thread, &info);

        if (error != JVMTI_ERROR_NONE) {
            outStream_setError(out, map2jdwpError(error));
        } else {
            (void)outStream_writeString(out, info.name);
        }

        if ( info.name != NULL )
            jvmtiDeallocate(info.name);

    } END_WITH_LOCAL_REFS(env);

    return JNI_TRUE;
}

static jboolean
suspend(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }
    error = threadControl_suspendThread(thread, JNI_FALSE);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
    }
    return JNI_TRUE;
}

static jboolean
resume(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    /* true means it is okay to unblock the commandLoop thread */
    error = threadControl_resumeThread(thread, JNI_TRUE);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
    }
    return JNI_TRUE;
}

static jboolean
status(PacketInputStream *in, PacketOutputStream *out)
{
    jdwpThreadStatus threadStatus;
    jint statusFlags;
    jvmtiError error;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    error = threadControl_applicationThreadStatus(thread, &threadStatus,
                                                          &statusFlags);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
        return JNI_TRUE;
    }
    (void)outStream_writeInt(out, threadStatus);
    (void)outStream_writeInt(out, statusFlags);
    return JNI_TRUE;
}

static jboolean
threadGroup(PacketInputStream *in, PacketOutputStream *out)
{
    JNIEnv *env;
    jthread thread;

    env = getEnv();

    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    WITH_LOCAL_REFS(env, 1) {

        jvmtiThreadInfo info;
        jvmtiError error;

        (void)memset(&info, 0, sizeof(info));

        error = JVMTI_FUNC_PTR(gdata->jvmti,GetThreadInfo)
                                (gdata->jvmti, thread, &info);

        if (error != JVMTI_ERROR_NONE) {
            outStream_setError(out, map2jdwpError(error));
        } else {
            (void)outStream_writeObjectRef(env, out, info.thread_group);
        }

        if ( info.name!=NULL )
            jvmtiDeallocate(info.name);

    } END_WITH_LOCAL_REFS(env);

    return JNI_TRUE;
}

static jboolean
validateSuspendedThread(PacketOutputStream *out, jthread thread)
{
    jvmtiError error;
    jint count;

    error = threadControl_suspendCount(thread, &count);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
        return JNI_FALSE;
    }

    if (count == 0) {
        outStream_setError(out, JDWP_ERROR(THREAD_NOT_SUSPENDED));
        return JNI_FALSE;
    }

    return JNI_TRUE;
}

static jboolean
frames(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    FrameNumber fnum;
    jint count;
    JNIEnv *env;
    jthread thread;
    jint startIndex;
    jint length;

    env = getEnv();

    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }
    startIndex = inStream_readInt(in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }
    length = inStream_readInt(in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    if (!validateSuspendedThread(out, thread)) {
        return JNI_TRUE;
    }

    error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameCount)
                        (gdata->jvmti, thread, &count);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
        return JNI_TRUE;
    }

    if (length == -1) {
        length = count - startIndex;
    }

    if (length == 0) {
        (void)outStream_writeInt(out, 0);
        return JNI_TRUE;
    }

    if ((startIndex < 0) || (startIndex > count - 1)) {
        outStream_setError(out, JDWP_ERROR(INVALID_INDEX));
        return JNI_TRUE;
    }

    if ((length < 0) || (length + startIndex > count)) {
        outStream_setError(out, JDWP_ERROR(INVALID_LENGTH));
        return JNI_TRUE;
    }

    (void)outStream_writeInt(out, length);

    for(fnum = startIndex ; fnum < startIndex+length ; fnum++ ) {

        WITH_LOCAL_REFS(env, 1) {

            jclass clazz;
            jmethodID method;
            jlocation location;

            /* Get location info */
            error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameLocation)
                (gdata->jvmti, thread, fnum, &method, &location);
            if (error == JVMTI_ERROR_OPAQUE_FRAME) {
                clazz = NULL;
                location = -1L;
                error = JVMTI_ERROR_NONE;
            } else if ( error == JVMTI_ERROR_NONE ) {
                error = methodClass(method, &clazz);
                if ( error == JVMTI_ERROR_NONE ) {
                    FrameID frame;
                    frame = createFrameID(thread, fnum);
                    (void)outStream_writeFrameID(out, frame);
                    writeCodeLocation(out, clazz, method, location);
                }
            }

        } END_WITH_LOCAL_REFS(env);

        if (error != JVMTI_ERROR_NONE)
            break;

    }

    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
    }
    return JNI_TRUE;
}

static jboolean
getFrameCount(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    jint count;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    if (!validateSuspendedThread(out, thread)) {
        return JNI_TRUE;
    }

    error = JVMTI_FUNC_PTR(gdata->jvmti,GetFrameCount)
                        (gdata->jvmti, thread, &count);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
        return JNI_TRUE;
    }
    (void)outStream_writeInt(out, count);

    return JNI_TRUE;
}

static jboolean
ownedMonitors(PacketInputStream *in, PacketOutputStream *out)
{
    JNIEnv *env;
    jthread thread;

    env = getEnv();

    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    if (!validateSuspendedThread(out, thread)) {
        return JNI_TRUE;
    }

    WITH_LOCAL_REFS(env, 1) {

        jvmtiError error;
        jint count = 0;
        jobject *monitors = NULL;

        error = JVMTI_FUNC_PTR(gdata->jvmti,GetOwnedMonitorInfo)
                                (gdata->jvmti, thread, &count, &monitors);
        if (error != JVMTI_ERROR_NONE) {
            outStream_setError(out, map2jdwpError(error));
        } else {
            int i;
            (void)outStream_writeInt(out, count);
            for (i = 0; i < count; i++) {
                jobject monitor = monitors[i];
                (void)outStream_writeByte(out, specificTypeKey(env, monitor));
                (void)outStream_writeObjectRef(env, out, monitor);
            }
        }
        if (monitors != NULL)
            jvmtiDeallocate(monitors);

    } END_WITH_LOCAL_REFS(env);

    return JNI_TRUE;
}

static jboolean
currentContendedMonitor(PacketInputStream *in, PacketOutputStream *out)
{
    JNIEnv *env;
    jthread thread;

    env = getEnv();

    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (thread == NULL || threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    if (!validateSuspendedThread(out, thread)) {
        return JNI_TRUE;
    }

    WITH_LOCAL_REFS(env, 1) {

        jobject monitor;
        jvmtiError error;

        error = JVMTI_FUNC_PTR(gdata->jvmti,GetCurrentContendedMonitor)
                                (gdata->jvmti, thread, &monitor);

        if (error != JVMTI_ERROR_NONE) {
            outStream_setError(out, map2jdwpError(error));
        } else {
            (void)outStream_writeByte(out, specificTypeKey(env, monitor));
            (void)outStream_writeObjectRef(env, out, monitor);
        }

    } END_WITH_LOCAL_REFS(env);

    return JNI_TRUE;
}

static jboolean
stop(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    jthread thread;
    jobject throwable;
    JNIEnv *env;

    env = getEnv();
    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }
    throwable = inStream_readObjectRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    error = threadControl_stop(thread, throwable);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
    }
    return JNI_TRUE;
}

static jboolean
interrupt(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    error = threadControl_interrupt(thread);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
    }
    return JNI_TRUE;
}

static jboolean
suspendCount(PacketInputStream *in, PacketOutputStream *out)
{
    jvmtiError error;
    jint count;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    error = threadControl_suspendCount(thread, &count);
    if (error != JVMTI_ERROR_NONE) {
        outStream_setError(out, map2jdwpError(error));
        return JNI_TRUE;
    }

    (void)outStream_writeInt(out, count);
    return JNI_TRUE;
}

static jboolean
ownedMonitorsWithStackDepth(PacketInputStream *in, PacketOutputStream *out)
{
    JNIEnv *env;
    jthread thread;

    thread = inStream_readThreadRef(getEnv(), in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (thread == NULL || threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    if (!validateSuspendedThread(out, thread)) {
        return JNI_TRUE;
    }

    env = getEnv();

    WITH_LOCAL_REFS(env, 1) {

        jvmtiError error = JVMTI_ERROR_NONE;
        jint count = 0;
        jvmtiMonitorStackDepthInfo *monitors=NULL;

        error = JVMTI_FUNC_PTR(gdata->jvmti,GetOwnedMonitorStackDepthInfo)
                                (gdata->jvmti, thread, &count, &monitors);

        if (error != JVMTI_ERROR_NONE) {
            outStream_setError(out, map2jdwpError(error));
        } else {
            int i;
            (void)outStream_writeInt(out, count);
            for (i = 0; i < count; i++) {
                jobject monitor = monitors[i].monitor;
                (void)outStream_writeByte(out, specificTypeKey(env, monitor));
                (void)outStream_writeObjectRef(getEnv(), out, monitor);
                (void)outStream_writeInt(out,monitors[i].stack_depth);
            }
        }
        if (monitors != NULL) {
            jvmtiDeallocate(monitors);
        }

    } END_WITH_LOCAL_REFS(env);

    return JNI_TRUE;
}

static jboolean
forceEarlyReturn(PacketInputStream *in, PacketOutputStream *out)
{
    JNIEnv *env;
    jthread thread;
    jvalue value;
    jbyte typeKey;
    jvmtiError error;

    env = getEnv();
    thread = inStream_readThreadRef(env, in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (threadControl_isDebugThread(thread)) {
        outStream_setError(out, JDWP_ERROR(INVALID_THREAD));
        return JNI_TRUE;
    }

    typeKey = inStream_readByte(in);
    if (inStream_error(in)) {
        return JNI_TRUE;
    }

    if (isObjectTag(typeKey)) {
        value.l = inStream_readObjectRef(env, in);
        error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnObject)
                        (gdata->jvmti, thread, value.l);
    } else {
        switch (typeKey) {
            case JDWP_TAG(VOID):
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnVoid)
                                (gdata->jvmti, thread);
                break;
            case JDWP_TAG(BYTE):
                value.b = inStream_readByte(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnInt)
                                (gdata->jvmti, thread, value.b);
                break;

            case JDWP_TAG(CHAR):
                value.c = inStream_readChar(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnInt)
                                (gdata->jvmti, thread, value.c);
                break;

            case JDWP_TAG(FLOAT):
                value.f = inStream_readFloat(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnFloat)
                                (gdata->jvmti, thread, value.f);
                break;

            case JDWP_TAG(DOUBLE):
                value.d = inStream_readDouble(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnDouble)
                                (gdata->jvmti, thread, value.d);
                break;

            case JDWP_TAG(INT):
                value.i = inStream_readInt(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnInt)
                                (gdata->jvmti, thread, value.i);
                break;

            case JDWP_TAG(LONG):
                value.j = inStream_readLong(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnLong)
                                (gdata->jvmti, thread, value.j);
                break;

            case JDWP_TAG(SHORT):
                value.s = inStream_readShort(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnInt)
                                (gdata->jvmti, thread, value.s);
                break;

            case JDWP_TAG(BOOLEAN):
                value.z = inStream_readBoolean(in);
                error = JVMTI_FUNC_PTR(gdata->jvmti,ForceEarlyReturnInt)
                                (gdata->jvmti, thread, value.z);
                break;

            default:
                error =  AGENT_ERROR_INVALID_TAG;
                break;
        }
    }
    {
      jdwpError serror = map2jdwpError(error);
      if (serror != JDWP_ERROR(NONE)) {
        outStream_setError(out, serror);
      }
    }
    return JNI_TRUE;
}

void *ThreadReference_Cmds[] = { (void *)14,
    (void *)name,
    (void *)suspend,
    (void *)resume,
    (void *)status,
    (void *)threadGroup,
    (void *)frames,
    (void *)getFrameCount,
    (void *)ownedMonitors,
    (void *)currentContendedMonitor,
    (void *)stop,
    (void *)interrupt,
    (void *)suspendCount,
    (void *)ownedMonitorsWithStackDepth,
    (void *)forceEarlyReturn
    };


text:
OverrideAudit ChangeLog
=======================

Version 2.2.5 (2022-06-06)
--------------------------

  * Update the hover popup that displays package information
    to make it clearer that the commands that are implemented
    in the Default package are available in all plugin hosts
    and not just the one that it natively runs in.

  * Include extra hover popups on different parts of the
    various reports that are available to help explain what is
    being seen, such as the different package types and the
    text that marks different types of overrides.

  NOTE: This is the last version of OverrideAudit that will
        be released for Sublime Text 3. With this release the
        minimum required version of Sublime Text will be 4
        in order to allow OverrideAudit to take advantage of
        newer features in the application.

Version 2.2.4 (2021-10-12)
--------------------------

  * Resolve an issue with the Open Resource command, which
    did not allow you to open unknown override files. This
    makes various workflows problematic.

    The fix comes courtesy of Keith Hall.

Version 2.2.3 (2021-07-13)
--------------------------

  * Correct the version of the User package Python interpreter
    in newer builds of Sublime.

  * Fix context sensitive commands throwing errors if they are
    invoked from the tab context menu.

Version 2.2.2 (2020-10-20)
--------------------------
  * Previously, when creating or refreshing a report, the cursor
    would be left at the bottom of the view, which can cause some
    unwanted scroll on cursor move.

    Report creation and refreshing now puts the cursor at the top
    of the buffer, similar to the behaviour of opening a file.

  * Fix an issue where attempting to Diff a package that has no
    sublime-package file or no unpacked files might cause an error.

  * All reports now use a custom context menu that display only
    OverrideAudit commands, so that working in them for users
    that use the context menu is nicer.

  * Added a new option to Override reports to allow for
    skipping overrides that are unchanged from appearing
    in reports.

  * Added in a new option to Package Diff reports to allow for
    skipping overrides that are unchanged from appearing in
    reports.

  * Fix the context menu in tabs potentially displaying errors in
    the console if the tab prior to an override tab was an image or
    HTML sheet, which throws off the view index calculation.

Version 2.2.1 (2020-02-26)
--------------------------
  * The `Open Resource` command was incorrectly hiding
    packages that are not represented by a `sublime-package`
    file.

    This made it impossible to open a package resource from
    a purely unpacked package (such as the `User` package).
    This is now resolved.

Version 2.2.0 (2020-01-21)
--------------------------
  * Include a new command to open a resource for viewing, which
    works the same as the PackageResourceViewer command of the
    same name. This is functionally somewhat similar to the built
    in `View Package File` command, but prompts you for the file
    in a different manner; overrides are also annotated in the
    list.

  * For packages that contain plugins, the hover popup on reports
    now indicates what version of Python the plugins in that
    package are running in. This provides an indication of that
    package containing a plugin while also allowing for the
    inclusion of newer versions of Python being supported in
    Sublime in the future.

  * Fix a problem where some commands did not reload on package
    update properly. This is not a particularly big deal (and
    restarting Sublime would resolve the issue anyway).

Version 2.1.1 (2019-11-05)
--------------------------
  * Fix an issue with the new `mini_diff_underlying` setting in
    which if an override was open when you quit Sublime, on
    restart the incremental diff indicators would not properly
    track the underlying package file.

Version 2.1.0 (2019-09-15)
--------------------------
  * New command to create an override or promote a view opened
    by `View Package File` to a potential new override. Both are
    available from the main menu and the command palette as
    appropriate, as well as package name context menus.

  * New setting `mini_diff_underlying` (default: `true`) that
    sets the mini diff functionality in override edit views to
    diff against the underlying package file instead of the file
    on disk. Requires `mini_diff` to be enabled in your user
    preferences.

  * New command to revert an existing override. This replaces
    the file with a freshly unpacked version of the underlying
    file. The new setting `confirm_revert` controls whether the
    user gets asked to confirm this action before it is carried
    out.

  * Loose files in an unpacked package that don't correspond to
    any files in an associated `sublime-package` file are now
    shown in override reports and bulk diffs annotated with `[?]`
    to indicate that their status is unknown. The new setting
    `ignore_unknown_overrides` controls if this feature is enabled
    or not and can be used to filter the list of unknown overrides
    as needed.

  * Include hover popups for packages in reports. The popup gives
    more detailed package information, displays some help
    information on click, and can trigger some commands as well.
    This is currently a work in progress.

  * Fix a bug in bulk diff context menu items in reports; they
    would appear disabled instead of hiding themselves. They're
    now also smarter about when they enable themselves.

  * Fix a bug in which a package was only considered a dependency
    if it was an unpacked package. The package control bootstrap
    package 0_package_control_loader is an example of a dependency
    that is packed, so detection has been altered to check if any
    package is a dependency instead.

  * Fix an issue where the temporary files created when an external
    diff is performed might have different line endings than the
    source file originally had.

Version 2.0.0 (2019-03-14)
--------------------------
  * Massive internal refactoring has been done to make it easier
    to add in new commands and functionality. The primary target
    of the refactor was in taking a few commands which were
    overloaded and took an "action" parameter to select how they
    worked and splitting them out into distinct commands.

    This change will make it easier to add in new functionality
    but it does mean that many commands have been renamed to
    more descriptive names.

    The full list of changes is:

      override_audit_diff_override
        -> override_audit_diff_single

      override_audit_diff_package
        -> override_audit_diff_report

      override_audit_context_override
        -> override_audit_toggle_override
        -> override_audit_diff_override
        -> override_audit_edit_override
        -> override_audit_delete_override
        -> override_audit_freshen_override

      override_audit_context_package
        -> override_audit_diff_package
        -> override_audit_freshen_package

      override_audit_context_report
        -> override_audit_refresh_report

  * Enhanced all of the commands available via the context menu:

      - Commands are now always visible unless you provide an
        argument telling them to hide themselves when they do
        not apply; this allows you to add these commands to other
        menus and control visibily.

      - Commands will be visible but disabled when the underlying
        package or override they are supposed to work with does
        not exist. For an override this means a file does not
        exist, while for a package it means that the unpacked
        folder is missing.

      - The default captions for disabled commands is slightly
        different when the appropriate context information is not
        available to tell you what exactly they will do (e.g.
        "Diff Override" instead of telling you what override will
        be diffed)

  * The package report table frame was updated, because the lack
    of `+` characters is really hard to unsee once it's pointed
    out.

Version 1.2.2 (2019-03-13)
--------------------------
  * Last public version of OverrideAudit version 1.x. This version is
    functionally identical to the previous version, but is here to point
    out that no further releases in this series are planned.

Version 1.2.1 (2019-02-15)
--------------------------
  * Support using
    [Sublimerge Pro](https://packagecontrol.io/packages/Sublimerge%20Pro) or
    [Sublimerge 3](https://packagecontrol.io/packages/Sublimerge%203)
    as the external diff tool by setting `external_diff` to the
    string `"sublimerge"`.

  * Improve detection of an invalid `external_diff` setting that could
    lead to the command being enabled when it should not be.

  * Log to the console when the tempoary files created during an
    external diff are removed

Version 1.2.0 (2019-02-10)
--------------------------
  * Implement the ability to open an override diff in an external diff
    tool via the `external_diff` setting. This command is available
    from the command palette and the context menu of override diff
    views.

Version 1.1.2 (2019-01-21)
-------------------------
  * Fix a bug in save_on_diff handling whereby the buffer might
    visually appear unsaved in some circumstances even though the file
    was actually saved.

  * Fix a bug introduced in 1.1.0 while fixing #24 which caused text
    in reports telling you that there are no overrides to be treated
    as an override.

  * Improve detection of packages that are dependency packages that
    are still under development so that they appear as appropriate in
    package reports (#25).

  * Include links to the online documentation in the settings menu
    and the command palette instead of opening the README file, since
    they contain the same information but one is hyperlinked and laid
    out better than the other one.

Version 1.1.1 (2017-05-01)
--------------------------
  * Remove a debug print statement that slipped through during some
    last minute code testing prior to the last release.

Version 1.1.0 (2017-04-28)
--------------------------

  * Implement the ability to "freshen" a single expired override or
    all within a package (#15) via a context menu option
  * Implement the ability to show the diff header even if a diff is
    empty (#18) controlled via `diff_empty_hdr` option
  * Fix a problem with overrides starting with a period not being
    correctly recognized as an override (#24).
  * Fix a file case issue on Windows/MacOS where opening an override
    from a package folder with an incorrect case would not enable
    the commands to edit or diff the override.
  * Performance enhancements for some package operations for users
    with a large number of installed packages.

Version 1.0.1 (2017-04-10)
--------------------------

  * Fix mixed path separators in diff output, delete confirmations and
    diff tab headers so they are always forward slashes (unix-style)
    to visually conform with how Sublime represents package path
    fragments internally (#14).

  * The Package Report, Override Report and and Bulk Diff Reports now
    have word wrap turned off by default.

  * Enhanced the checks performed at file load and save so to more
    correctly determine if a file is actually an override or not when
    enabling integration with OverrideAudit Edit/Diff functionality.

  * Rename the "Swap Diff/Override View" command to "Swap Diff/Edit
    View" in the command palette and change the associated text used
    in Diff tab titles.

  * Add a configuration option `save_on_diff` (defaults to false) to
    control if the contents of an edited override should be persisted
    to disk before performing a diff on it.

Version 1.0.0 (2017-04-03)
--------------------------

  * Initial release

redpajama_set_name: RedPajamaGithub


text:
package container

import (
	"fmt"
	"github.com/bunbunjp/gotop/dataservice/memory"
	"github.com/gizak/termui"
	"math"
)

// MemoryHistoryContainer メモリ使用率利用履歴表示用コンテナ
type MemoryHistoryContainer struct {
	lineChart *termui.LineChart
}

// Initialize # Container Interface
func (m *MemoryHistoryContainer) Initialize() {

}

// UpdateRender # Container Interface
func (m *MemoryHistoryContainer) UpdateRender() {
	data := memory.GetInstance()

	startline := int(math.Max(0, float64(len(data.VirtualUsedHistory)-m.lineChart.Width)))
	m.lineChart.Data = data.VirtualUsedHistory[startline:]
}

// CreateUI # Container Interface
func (m *MemoryHistoryContainer) CreateUI() termui.GridBufferer {
	m.lineChart = termui.NewLineChart()
	m.lineChart.BorderLabel = fmt.Sprintf("memory usage history")
	m.lineChart.Width = termui.TermWidth() / 2
	m.lineChart.Height = 10
	m.lineChart.AxesColor = termui.ColorWhite
	m.lineChart.LineColor = termui.ColorGreen | termui.AttrBold
	m.lineChart.DotStyle = '+'
	m.lineChart.Mode = "dot"

	return m.lineChart
}


text:
from typing import Any, Mapping, Optional, Sequence, Union, cast

from bs4 import BeautifulSoup as Soup
from requests import Request, Session
from typing_extensions import Literal

__all__ = ('DownloadMixin', 'download_page')

def download_page(
        sess: Session,
        url: str,
        data: Any = None,
        method: Literal['get', 'post'] = 'get',
        headers: Optional[Mapping[str, str]] = None,
        params: Optional[Mapping[str, str]] = None,
        return_json: bool = False,
        json: Any = None) -> Union[str, Sequence[Any], Mapping[str, Any]]:
    if headers:
        sess.headers.update(headers)
    req = Request(method.upper(), url, data=data, params=params, json=json)
    prepped = sess.prepare_request(req)  # type: ignore[no-untyped-call]
    del prepped.headers['accept-encoding']
    r = sess.send(prepped)  # type: ignore[no-untyped-call]
    r.raise_for_status()
    if not return_json:
        return r.text.strip()
    return cast(Mapping[str, Any], r.json())

class DownloadMixin:  # pylint: disable=too-few-public-methods
    _sess: Session

    def _download_page(
            self,
            url: str,
            data: Any = None,
            method: Literal['get', 'post'] = 'get',
            headers: Optional[Mapping[str, str]] = None,
            params: Optional[Mapping[str, str]] = None,
            return_json: bool = False,
            json: Any = None) -> Union[str, Sequence[Any], Mapping[str, Any]]:
        return download_page(self._sess, url, data, method, headers, params,
                             return_json, json)

    def _download_page_soup(self, *args: Any, **kwargs: Any) -> Soup:
        return Soup(cast(str, self._download_page(*args, **kwargs)),
                    kwargs.pop('parser', 'html5lib'))


text:
#ifndef PPP_H_
#define PPP_H_

#include <stdbool.h>
#include "Callback.h"
#include "FileHandle.h"
#include "NetStackMemoryManager.h"

class PPP {
public:

    /** Return the default on-board PPP
     *
     * Returns the default on-board PPP - this will be target-specific, and
     * may not be available on all targets.
     */
    static PPP &get_default_instance();

    virtual ~PPP() {};

    /**
     * Callback to be registered with PPP interface and to be called for received packets
     *
     * @param buf  Received data
     */
    //typedef void (*ppp_link_input_fn)(void *data, net_stack_mem_buf_t *buf);
    typedef mbed::Callback<void (net_stack_mem_buf_t *buf)> ppp_link_input_cb_t;

    /**
     * Callback to be registered with PPP interface and to be called for link status changes
     *
     * @param  up   Link status
     */
    //typedef void (*ppp_link_state_change_fn)(void *data, bool up);
    typedef mbed::Callback<void (bool up)> ppp_link_state_change_cb_t;

    /**
     * Return maximum transmission unit
     *
     * @return     MTU in bytes
     */
    virtual uint32_t get_mtu_size() = 0;

    /**
     * Gets memory buffer alignment preference
     *
     * Gets preferred memory buffer alignment of the cellular device.
     * @return         Memory alignment requirement in bytes
     */
    virtual uint32_t get_align_preference() const = 0;

    /**
     * Return interface name
     *
     * @param name Pointer to where the name should be written
     * @param size Maximum number of characters to copy
     */
    virtual void get_ifname(char *name, uint8_t size) const = 0;

    /**
     * Sends the packet over the link
     *
     * That cannot be called from an interrupt context.
     *
     * @param buf  Packet to be sent
     * @return     True if the packet was sent, false otherwise
     */
    virtual bool link_out(net_stack_mem_buf_t *buf, nsapi_ip_stack_t ip_stack) = 0;

    /**
     * Initializes the PPP
     *
     * @return True on success, False in case of an error.
     */
    virtual bool power_up() = 0;

    /**
     * Deinitializes the PPP
     *
     */
    virtual void power_down() = 0;

    /**
     * Sets a callback that needs to be called for packets received for that interface
     *
     * @param input_cb Function to be register as a callback
     */
    virtual void set_link_input_cb(ppp_link_input_cb_t input_cb) = 0;

    /**
     * Sets a callback that needs to be called on link status changes for given interface
     *
     * @param state_cb Function to be register as a callback
     */
    virtual void set_link_state_cb(ppp_link_state_change_cb_t state_cb) = 0;

    /** Sets memory manager that is used to handle memory buffers
     *
     * @param mem_mngr Pointer to memory manager
     */
    virtual void set_memory_manager(NetStackMemoryManager &mem_mngr) = 0;

    /** Sets file stream used to communicate with modem
     *
     * @param stream Pointer to file handle
     */
    virtual void set_stream(mbed::FileHandle *stream) = 0;

    /** Sets IP protocol versions of IP stack
     *
     * @param ip_stack IP protocol version
     */
    virtual void set_ip_stack(nsapi_ip_stack_t ip_stack) = 0;

    /** Sets user name and password for PPP protocol
     *
     * @param uname    User name
     * @param password Password
     */
    virtual void set_credentials(const char *uname, const char *password) = 0;

    /** Gets local IP address
     *
     * @param version IP address version
     * @return        IP address
     */
    virtual const nsapi_addr_t *get_ip_address(nsapi_version_t version) = 0;

    /** Get the local network mask.
     *
     *  @return         Local network mask or null if no network mask has been received.
     */
    virtual const nsapi_addr_t *get_netmask() = 0;

    /** Get the local gateway.
     *
     *  @return         Local gateway or null if no network mask has been received.
     */
    virtual const nsapi_addr_t *get_gateway() = 0;

    /** Gets DNS server address
     *
     * @param index Server index
     */
    virtual const nsapi_addr_t *get_dns_server(uint8_t index) = 0;
};

#endif /* PPP_H_ */


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 35: 104 (1937)

#### Original name
Uraecium derridicola Cummins, 1937

### Remarks
null


text:
'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

const InputStream = require('./InputStream');
const {IterationNode} = require('./nodes');
const MatchResult = require('./MatchResult');
const common = require('./common');
const errors = require('./errors');
const util = require('./util');

// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------

const globalActionStack = [];

const hasOwnProperty = (x, prop) => Object.prototype.hasOwnProperty.call(x, prop);

// ----------------- Wrappers -----------------

// Wrappers decorate CST nodes with all of the functionality (i.e., operations and attributes)
// provided by a Semantics (see below). `Wrapper` is the abstract superclass of all wrappers. A
// `Wrapper` must have `_node` and `_semantics` instance variables, which refer to the CST node and
// Semantics (resp.) for which it was created, and a `_childWrappers` instance variable which is
// used to cache the wrapper instances that are created for its child nodes. Setting these instance
// variables is the responsibility of the constructor of each Semantics-specific subclass of
// `Wrapper`.
class Wrapper {
  constructor(node, sourceInterval, baseInterval) {
    this._node = node;
    this.source = sourceInterval;

    // The interval that the childOffsets of `node` are relative to. It should be the source
    // of the closest Nonterminal node.
    this._baseInterval = baseInterval;

    if (node.isNonterminal()) {
      common.assert(sourceInterval === baseInterval);
    }
    this._childWrappers = [];
  }

  toString() {
    return '[semantics wrapper for ' + this._node.grammar.name + ']';
  }

  _forgetMemoizedResultFor(attributeName) {
    // Remove the memoized attribute from the cstNode and all its children.
    delete this._node[this._semantics.attributeKeys[attributeName]];
    this.children.forEach(child => {
      child._forgetMemoizedResultFor(attributeName);
    });
  }

  // Returns the wrapper of the specified child node. Child wrappers are created lazily and
  // cached in the parent wrapper's `_childWrappers` instance variable.
  child(idx) {
    if (!(0 <= idx && idx < this._node.numChildren())) {
      // TODO: Consider throwing an exception here.
      return undefined;
    }
    let childWrapper = this._childWrappers[idx];
    if (!childWrapper) {
      const childNode = this._node.childAt(idx);
      const offset = this._node.childOffsets[idx];

      const source = this._baseInterval.subInterval(offset, childNode.matchLength);
      const base = childNode.isNonterminal() ? source : this._baseInterval;
      childWrapper = this._childWrappers[idx] = this._semantics.wrap(childNode, source, base);
    }
    return childWrapper;
  }

  // Returns an array containing the wrappers of all of the children of the node associated
  // with this wrapper.
  _children() {
    // Force the creation of all child wrappers
    for (let idx = 0; idx < this._node.numChildren(); idx++) {
      this.child(idx);
    }
    return this._childWrappers;
  }

  // Returns `true` if the CST node associated with this wrapper corresponds to an iteration
  // expression, i.e., a Kleene-*, Kleene-+, or an optional. Returns `false` otherwise.
  isIteration() {
    return this._node.isIteration();
  }

  // Returns `true` if the CST node associated with this wrapper is a terminal node, `false`
  // otherwise.
  isTerminal() {
    return this._node.isTerminal();
  }

  // Returns `true` if the CST node associated with this wrapper is a nonterminal node, `false`
  // otherwise.
  isNonterminal() {
    return this._node.isNonterminal();
  }

  // Returns `true` if the CST node associated with this wrapper is a nonterminal node
  // corresponding to a syntactic rule, `false` otherwise.
  isSyntactic() {
    return this.isNonterminal() && this._node.isSyntactic();
  }

  // Returns `true` if the CST node associated with this wrapper is a nonterminal node
  // corresponding to a lexical rule, `false` otherwise.
  isLexical() {
    return this.isNonterminal() && this._node.isLexical();
  }

  // Returns `true` if the CST node associated with this wrapper is an iterator node
  // having either one or no child (? operator), `false` otherwise.
  // Otherwise, throws an exception.
  isOptional() {
    return this._node.isOptional();
  }

  // Create a new _iter wrapper in the same semantics as this wrapper.
  iteration(optChildWrappers) {
    const childWrappers = optChildWrappers || [];

    const childNodes = childWrappers.map(c => c._node);
    const iter = new IterationNode(childNodes, [], -1, false);

    const wrapper = this._semantics.wrap(iter, null, null);
    wrapper._childWrappers = childWrappers;
    return wrapper;
  }

  // Returns an array containing the children of this CST node.
  get children() {
    return this._children();
  }

  // Returns the name of grammar rule that created this CST node.
  get ctorName() {
    return this._node.ctorName;
  }

  // TODO: Remove this eventually (deprecated in v0.12).
  get interval() {
    throw new Error('The `interval` property is deprecated -- use `source` instead');
  }

  // Returns the number of children of this CST node.
  get numChildren() {
    return this._node.numChildren();
  }

  // Returns the contents of the input stream consumed by this CST node.
  get sourceString() {
    return this.source.contents;
  }
}

// ----------------- Semantics -----------------

// A Semantics is a container for a family of Operations and Attributes for a given grammar.
// Semantics enable modularity (different clients of a grammar can create their set of operations
// and attributes in isolation) and extensibility even when operations and attributes are mutually-
// recursive. This constructor should not be called directly except from
// `Semantics.createSemantics`. The normal ways to create a Semantics, given a grammar 'g', are
// `g.createSemantics()` and `g.extendSemantics(parentSemantics)`.
function Semantics(grammar, superSemantics) {
  const self = this;
  this.grammar = grammar;
  this.checkedActionDicts = false;

  // Constructor for wrapper instances, which are passed as the arguments to the semantic actions
  // of an operation or attribute. Operations and attributes require double dispatch: the semantic
  // action is chosen based on both the node's type and the semantics. Wrappers ensure that
  // the `execute` method is called with the correct (most specific) semantics object as an
  // argument.
  this.Wrapper = class extends (superSemantics ? superSemantics.Wrapper : Wrapper) {
    constructor(node, sourceInterval, baseInterval) {
      super(node, sourceInterval, baseInterval);
      self.checkActionDictsIfHaventAlready();
      this._semantics = self;
    }
  };

  this.super = superSemantics;
  if (superSemantics) {
    if (!(grammar.equals(this.super.grammar) || grammar._inheritsFrom(this.super.grammar))) {
      throw new Error(
          "Cannot extend a semantics for grammar '" +
          this.super.grammar.name +
          "' for use with grammar '" +
          grammar.name +
          "' (not a sub-grammar)"
      );
    }
    this.operations = Object.create(this.super.operations);
    this.attributes = Object.create(this.super.attributes);
    this.attributeKeys = Object.create(null);

    // Assign unique symbols for each of the attributes inherited from the super-semantics so that
    // they are memoized independently.
    // eslint-disable-next-line guard-for-in
    for (const attributeName in this.attributes) {
      Object.defineProperty(this.attributeKeys, attributeName, {
        value: util.uniqueId(attributeName),
      });
    }
  } else {
    this.operations = Object.create(null);
    this.attributes = Object.create(null);
    this.attributeKeys = Object.create(null);
  }
}

Semantics.prototype.toString = function() {
  return '[semantics for ' + this.grammar.name + ']';
};

Semantics.prototype.checkActionDictsIfHaventAlready = function() {
  if (!this.checkedActionDicts) {
    this.checkActionDicts();
    this.checkedActionDicts = true;
  }
};

// Checks that the action dictionaries for all operations and attributes in this semantics,
// including the ones that were inherited from the super-semantics, agree with the grammar.
// Throws an exception if one or more of them doesn't.
Semantics.prototype.checkActionDicts = function() {
  let name;
  // eslint-disable-next-line guard-for-in
  for (name in this.operations) {
    this.operations[name].checkActionDict(this.grammar);
  }
  // eslint-disable-next-line guard-for-in
  for (name in this.attributes) {
    this.attributes[name].checkActionDict(this.grammar);
  }
};

Semantics.prototype.toRecipe = function(semanticsOnly) {
  function hasSuperSemantics(s) {
    return s.super !== Semantics.BuiltInSemantics._getSemantics();
  }

  let str = '(function(g) {\n';
  if (hasSuperSemantics(this)) {
    str += '  var semantics = ' + this.super.toRecipe(true) + '(g';

    const superSemanticsGrammar = this.super.grammar;
    let relatedGrammar = this.grammar;
    while (relatedGrammar !== superSemanticsGrammar) {
      str += '.superGrammar';
      relatedGrammar = relatedGrammar.superGrammar;
    }

    str += ');\n';
    str += '  return g.extendSemantics(semantics)';
  } else {
    str += '  return g.createSemantics()';
  }
  ['Operation', 'Attribute'].forEach(type => {
    const semanticOperations = this[type.toLowerCase() + 's'];
    Object.keys(semanticOperations).forEach(name => {
      const {actionDict, formals, builtInDefault} = semanticOperations[name];

      let signature = name;
      if (formals.length > 0) {
        signature += '(' + formals.join(', ') + ')';
      }

      let method;
      if (hasSuperSemantics(this) && this.super[type.toLowerCase() + 's'][name]) {
        method = 'extend' + type;
      } else {
        method = 'add' + type;
      }
      str += '\n    .' + method + '(' + JSON.stringify(signature) + ', {';

      const srcArray = [];
      Object.keys(actionDict).forEach(actionName => {
        if (actionDict[actionName] !== builtInDefault) {
          let source = actionDict[actionName].toString().trim();

          // Convert method shorthand to plain old function syntax.
          // https://github.com/harc/ohm/issues/263
          source = source.replace(/^.*\(/, 'function(');

          srcArray.push('\n      ' + JSON.stringify(actionName) + ': ' + source);
        }
      });
      str += srcArray.join(',') + '\n    })';
    });
  });
  str += ';\n  })';

  if (!semanticsOnly) {
    str =
      '(function() {\n' +
      '  var grammar = this.fromRecipe(' +
      this.grammar.toRecipe() +
      ');\n' +
      '  var semantics = ' +
      str +
      '(grammar);\n' +
      '  return semantics;\n' +
      '});\n';
  }

  return str;
};

function parseSignature(signature, type) {
  if (!Semantics.prototypeGrammar) {
    // The Operations and Attributes grammar won't be available while Ohm is loading,
    // but we can get away the following simplification b/c none of the operations
    // that are used while loading take arguments.
    common.assert(signature.indexOf('(') === -1);
    return {
      name: signature,
      formals: [],
    };
  }

  const r = Semantics.prototypeGrammar.match(
      signature,
    type === 'operation' ? 'OperationSignature' : 'AttributeSignature'
  );
  if (r.failed()) {
    throw new Error(r.message);
  }

  return Semantics.prototypeGrammarSemantics(r).parse();
}

function newDefaultAction(type, name, doIt) {
  return function(...children) {
    const thisThing = this._semantics.operations[name] || this._semantics.attributes[name];
    const args = thisThing.formals.map(formal => this.args[formal]);

    if (!this.isIteration() && children.length === 1) {
      // This CST node corresponds to a non-terminal in the grammar (e.g., AddExpr). The fact that
      // we got here means that this action dictionary doesn't have an action for this particular
      // non-terminal or a generic `_nonterminal` action.
      // As a convenience, if this node only has one child, we just return the result of applying
      // this operation / attribute to the child node.
      return doIt.apply(children[0], args);
    } else {
      // Otherwise, we throw an exception to let the programmer know that we don't know what
      // to do with this node.
      throw errors.missingSemanticAction(this.ctorName, name, type, globalActionStack);
    }
  };
}

Semantics.prototype.addOperationOrAttribute = function(type, signature, actionDict) {
  const typePlural = type + 's';

  const parsedNameAndFormalArgs = parseSignature(signature, type);
  const {name} = parsedNameAndFormalArgs;
  const {formals} = parsedNameAndFormalArgs;

  // TODO: check that there are no duplicate formal arguments

  this.assertNewName(name, type);

  // Create the action dictionary for this operation / attribute that contains a `_default` action
  // which defines the default behavior of iteration, terminal, and non-terminal nodes...
  const builtInDefault = newDefaultAction(type, name, doIt);
  const realActionDict = {_default: builtInDefault};
  // ... and add in the actions supplied by the programmer, which may override some or all of the
  // default ones.
  Object.keys(actionDict).forEach(name => {
    realActionDict[name] = actionDict[name];
  });

  const entry =
    type === 'operation' ?
      new Operation(name, formals, realActionDict, builtInDefault) :
      new Attribute(name, realActionDict, builtInDefault);

  // The following check is not strictly necessary (it will happen later anyway) but it's better to
  // catch errors early.
  entry.checkActionDict(this.grammar);

  this[typePlural][name] = entry;

  function doIt(...args) {
    // Dispatch to most specific version of this operation / attribute -- it may have been
    // overridden by a sub-semantics.
    const thisThing = this._semantics[typePlural][name];

    // Check that the caller passed the correct number of arguments.
    if (arguments.length !== thisThing.formals.length) {
      throw new Error(
          'Invalid number of arguments passed to ' +
          name +
          ' ' +
          type +
          ' (expected ' +
          thisThing.formals.length +
          ', got ' +
          arguments.length +
          ')'
      );
    }

    // Create an "arguments object" from the arguments that were passed to this
    // operation / attribute.
    const argsObj = Object.create(null);
    for (const [idx, val] of Object.entries(args)) {
      const formal = thisThing.formals[idx];
      argsObj[formal] = val;
    }

    const oldArgs = this.args;
    this.args = argsObj;
    const ans = thisThing.execute(this._semantics, this);
    this.args = oldArgs;
    return ans;
  }

  if (type === 'operation') {
    this.Wrapper.prototype[name] = doIt;
    this.Wrapper.prototype[name].toString = function() {
      return '[' + name + ' operation]';
    };
  } else {
    Object.defineProperty(this.Wrapper.prototype, name, {
      get: doIt,
      configurable: true, // So the property can be deleted.
    });
    Object.defineProperty(this.attributeKeys, name, {
      value: util.uniqueId(name),
    });
  }
};

Semantics.prototype.extendOperationOrAttribute = function(type, name, actionDict) {
  const typePlural = type + 's';

  // Make sure that `name` really is just a name, i.e., that it doesn't also contain formals.
  parseSignature(name, 'attribute');

  if (!(this.super && name in this.super[typePlural])) {
    throw new Error(
        'Cannot extend ' +
        type +
        " '" +
        name +
        "': did not inherit an " +
        type +
        ' with that name'
    );
  }
  if (hasOwnProperty(this[typePlural], name)) {
    throw new Error('Cannot extend ' + type + " '" + name + "' again");
  }

  // Create a new operation / attribute whose actionDict delegates to the super operation /
  // attribute's actionDict, and which has all the keys from `inheritedActionDict`.
  const inheritedFormals = this[typePlural][name].formals;
  const inheritedActionDict = this[typePlural][name].actionDict;
  const newActionDict = Object.create(inheritedActionDict);
  Object.keys(actionDict).forEach(name => {
    newActionDict[name] = actionDict[name];
  });

  this[typePlural][name] =
    type === 'operation' ?
      new Operation(name, inheritedFormals, newActionDict) :
      new Attribute(name, newActionDict);

  // The following check is not strictly necessary (it will happen later anyway) but it's better to
  // catch errors early.
  this[typePlural][name].checkActionDict(this.grammar);
};

Semantics.prototype.assertNewName = function(name, type) {
  if (hasOwnProperty(Wrapper.prototype, name)) {
    throw new Error('Cannot add ' + type + " '" + name + "': that's a reserved name");
  }
  if (name in this.operations) {
    throw new Error(
        'Cannot add ' + type + " '" + name + "': an operation with that name already exists"
    );
  }
  if (name in this.attributes) {
    throw new Error(
        'Cannot add ' + type + " '" + name + "': an attribute with that name already exists"
    );
  }
};

// Returns a wrapper for the given CST `node` in this semantics.
// If `node` is already a wrapper, returns `node` itself.  // TODO: why is this needed?
Semantics.prototype.wrap = function(node, source, optBaseInterval) {
  const baseInterval = optBaseInterval || source;
  return node instanceof this.Wrapper ? node : new this.Wrapper(node, source, baseInterval);
};

// Creates a new Semantics instance for `grammar`, inheriting operations and attributes from
// `optSuperSemantics`, if it is specified. Returns a function that acts as a proxy for the new
// Semantics instance. When that function is invoked with a CST node as an argument, it returns
// a wrapper for that node which gives access to the operations and attributes provided by this
// semantics.
Semantics.createSemantics = function(grammar, optSuperSemantics) {
  const s = new Semantics(
      grammar,
    optSuperSemantics !== undefined ?
      optSuperSemantics :
      Semantics.BuiltInSemantics._getSemantics()
  );

  // To enable clients to invoke a semantics like a function, return a function that acts as a proxy
  // for `s`, which is the real `Semantics` instance.
  const proxy = function ASemantics(matchResult) {
    if (!(matchResult instanceof MatchResult)) {
      throw new TypeError(
          'Semantics expected a MatchResult, but got ' +
          common.unexpectedObjToString(matchResult)
      );
    }
    if (matchResult.failed()) {
      throw new TypeError('cannot apply Semantics to ' + matchResult.toString());
    }

    const cst = matchResult._cst;
    if (cst.grammar !== grammar) {
      throw new Error(
          "Cannot use a MatchResult from grammar '" +
          cst.grammar.name +
          "' with a semantics for '" +
          grammar.name +
          "'"
      );
    }
    const inputStream = new InputStream(matchResult.input);
    return s.wrap(cst, inputStream.interval(matchResult._cstOffset, matchResult.input.length));
  };

  // Forward public methods from the proxy to the semantics instance.
  proxy.addOperation = function(signature, actionDict) {
    s.addOperationOrAttribute('operation', signature, actionDict);
    return proxy;
  };
  proxy.extendOperation = function(name, actionDict) {
    s.extendOperationOrAttribute('operation', name, actionDict);
    return proxy;
  };
  proxy.addAttribute = function(name, actionDict) {
    s.addOperationOrAttribute('attribute', name, actionDict);
    return proxy;
  };
  proxy.extendAttribute = function(name, actionDict) {
    s.extendOperationOrAttribute('attribute', name, actionDict);
    return proxy;
  };
  proxy._getActionDict = function(operationOrAttributeName) {
    const action =
      s.operations[operationOrAttributeName] || s.attributes[operationOrAttributeName];
    if (!action) {
      throw new Error(
          '"' +
          operationOrAttributeName +
          '" is not a valid operation or attribute ' +
          'name in this semantics for "' +
          grammar.name +
          '"'
      );
    }
    return action.actionDict;
  };
  proxy._remove = function(operationOrAttributeName) {
    let semantic;
    if (operationOrAttributeName in s.operations) {
      semantic = s.operations[operationOrAttributeName];
      delete s.operations[operationOrAttributeName];
    } else if (operationOrAttributeName in s.attributes) {
      semantic = s.attributes[operationOrAttributeName];
      delete s.attributes[operationOrAttributeName];
    }
    delete s.Wrapper.prototype[operationOrAttributeName];
    return semantic;
  };
  proxy.getOperationNames = function() {
    return Object.keys(s.operations);
  };
  proxy.getAttributeNames = function() {
    return Object.keys(s.attributes);
  };
  proxy.getGrammar = function() {
    return s.grammar;
  };
  proxy.toRecipe = function(semanticsOnly) {
    return s.toRecipe(semanticsOnly);
  };

  // Make the proxy's toString() work.
  proxy.toString = s.toString.bind(s);

  // Returns the semantics for the proxy.
  proxy._getSemantics = function() {
    return s;
  };

  return proxy;
};

// ----------------- Operation -----------------

// An Operation represents a function to be applied to a concrete syntax tree (CST) -- it's very
// similar to a Visitor (http://en.wikipedia.org/wiki/Visitor_pattern). An operation is executed by
// recursively walking the CST, and at each node, invoking the matching semantic action from
// `actionDict`. See `Operation.prototype.execute` for details of how a CST node's matching semantic
// action is found.
class Operation {
  constructor(name, formals, actionDict, builtInDefault) {
    this.name = name;
    this.formals = formals;
    this.actionDict = actionDict;
    this.builtInDefault = builtInDefault;
  }

  checkActionDict(grammar) {
    grammar._checkTopDownActionDict(this.typeName, this.name, this.actionDict);
  }

  // Execute this operation on the CST node associated with `nodeWrapper` in the context of the
  // given Semantics instance.
  execute(semantics, nodeWrapper) {
    try {
      // Look for a semantic action whose name matches the node's constructor name, which is either
      // the name of a rule in the grammar, or '_terminal' (for a terminal node), or '_iter' (for an
      // iteration node).
      const {ctorName} = nodeWrapper._node;
      let actionFn = this.actionDict[ctorName];
      if (actionFn) {
        globalActionStack.push([this, ctorName]);
        return actionFn.apply(nodeWrapper, nodeWrapper._children());
      }

      // The action dictionary does not contain a semantic action for this specific type of node.
      // If this is a nonterminal node and the programmer has provided a `_nonterminal` semantic
      // action, we invoke it:
      if (nodeWrapper.isNonterminal()) {
        actionFn = this.actionDict._nonterminal;
        if (actionFn) {
          globalActionStack.push([this, '_nonterminal', ctorName]);
          return actionFn.apply(nodeWrapper, nodeWrapper._children());
        }
      }

      // Otherwise, we invoke the '_default' semantic action.
      globalActionStack.push([this, 'default action', ctorName]);
      return this.actionDict._default.apply(nodeWrapper, nodeWrapper._children());
    } finally {
      globalActionStack.pop();
    }
  }
}

Operation.prototype.typeName = 'operation';

// ----------------- Attribute -----------------

// Attributes are Operations whose results are memoized. This means that, for any given semantics,
// the semantic action for a CST node will be invoked no more than once.
class Attribute extends Operation {
  constructor(name, actionDict, builtInDefault) {
    super(name, [], actionDict, builtInDefault);
  }

  execute(semantics, nodeWrapper) {
    const node = nodeWrapper._node;
    const key = semantics.attributeKeys[this.name];
    if (!hasOwnProperty(node, key)) {
      // The following is a super-send -- isn't JS beautiful? :/
      node[key] = Operation.prototype.execute.call(this, semantics, nodeWrapper);
    }
    return node[key];
  }
}

Attribute.prototype.typeName = 'attribute';

// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------

module.exports = Semantics;


text:
layout: post
title: Using R language in Python
date: 2017-12-21
categories: blog
tags: [R, Python, conda]
header-img: img/top.png    #这篇文章标题背景图片
---

Some packages are only available in R environment.

This post will introduce how to use R in Python.

###- INSTALLING PYTHON AND R
Both Python and R can be managed through the Anaconda platform, which is available for Linux, OSX and Windows. The default installation includes Python, and R can easily be installed later. The 64bit Python3 installer is a suitable download choice for most people.

After Anaconda has been installed on your system, you can use the command line conda package manager or the GUI-driven anaconda-navigator to install Python packages, R, and R libraries. For comprehensive instructions on both of these, refer to the official documentation. Brief step-by-step instructions to get up and running with conda follow.

####PYTHON
When the **Anaconda** installation has finished, Python is accessible by running python in a terminal (on Windows, you might have to run the Anaconda specific command prompt to access Python).

Anaconda also includes graphical interfaces for interacting with Python, which can be invoked by running **spyder** or **jupyter-notebook** from the command line.

To install a new python package from the Anaconda repositories, simply run **conda install < package name >** in a terminal. You can also use the pip package manager, but it will be easier to keep track of packages by sticking to one installation method.

####R
R can be installed via **conda install -c r r-essentials**, which bundles R with some of its most frequently used libraries (for a minimal R setup, substitute r or r-base for r-essentials).

-c r specifies that this package will be fetched from the R-channel in the Anaconda repositories.

After the installation completes, R can be invoked from the command line by typing R.

Like with Python, the jupyter-notebook can be used with R, simply launch the notebook and click **New >> R** (technically made possible via the r-irkernel and r-irdisplay packages in the r-essentials bundle).

Another GUI-driven editor for R can be installed via **conda install -c r rstudio**, and launched by typing rstudio at the command prompt.

To install a new R package, simply type **conda install -c r < package name >**.

All R package names are prefixed with **r-**.

You can also use the standard **install.packages() within R**, but it will be easier to keep track of packages by sticking to one installation method.


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

<TITLE>
Serialized Form (ZooKeeper 3.3.5 API)
</TITLE>

<META NAME="date" CONTENT="2012-03-15">

<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

Serialized Form

Package org.apache.zookeeper

Class org.apache.zookeeper.KeeperException extends Exception implements Serializable

Serialized Fields

code

KeeperException.Code code

path

String path

Class org.apache.zookeeper.KeeperException.APIErrorException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.AuthFailedException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.BadArgumentsException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.BadVersionException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.ConnectionLossException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.DataInconsistencyException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.InvalidACLException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.InvalidCallbackException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.MarshallingErrorException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.NoAuthException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.NoChildrenForEphemeralsException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.NodeExistsException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.NoNodeException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.NotEmptyException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.OperationTimeoutException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.RuntimeInconsistencyException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.SessionExpiredException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.SessionMovedException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.SystemErrorException extends KeeperException implements Serializable

Class org.apache.zookeeper.KeeperException.UnimplementedException extends KeeperException implements Serializable

Package org.apache.zookeeper.server

Class org.apache.zookeeper.server.RequestProcessor.RequestProcessorException extends Exception implements Serializable

Class org.apache.zookeeper.server.ZooKeeperServer.MissingSessionException extends IOException implements Serializable

serialVersionUID: 7467414635467261007L

Package org.apache.zookeeper.server.quorum

Class org.apache.zookeeper.server.quorum.Leader.XidRolloverException extends Exception implements Serializable

Class org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException extends Exception implements Serializable

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012 The Apache Software Foundation


text:
#nullable disable

using System.ComponentModel.DataAnnotations;

namespace Amazon.Ssm;

public sealed class CancelCommandRequest : ISsmRequest
{
    [Required]
    public string CommandId { get; set; }

    // If empty, cancels all
    public string[] InstanceIds { get; set; }
}


text:
import factScanDataService from './fact-scan-data.service';
import getDataForComparison from './get-data-for-comparison.factory';
import getModuleOptions from './get-module-options.factory';
import resolveEmptyVersions from './resolve-empty-versions.factory';
import shared from '../../shared/main';

export default
    angular.module('systemTracking.dataServices', [shared.name])
        .factory('getModuleOptions', getModuleOptions)
        .factory('getDataForComparison', getDataForComparison)
        .factory('resolveEmptyVersions', resolveEmptyVersions)
        .service('factScanDataService', factScanDataService);


text:
namespace app { namespace Uno { namespace Collections { struct List__int4; } } }

namespace app {
namespace Uno {
namespace Collections {

struct List1_Enumerator__int4;

struct List1_Enumerator__int4__uType : ::uStructType
{
    ::app::Uno::Collections::IEnumerator__int4 __interface_0;
    ::app::Uno::IDisposable __interface_1;
    ::app::Uno::Collections::IEnumerator __interface_2;
};

List1_Enumerator__int4__uType* List1_Enumerator__int4__typeof();

void List1_Enumerator__int4___ObjInit(List1_Enumerator__int4* __this, ::app::Uno::Collections::List__int4* source);
void List1_Enumerator__int4__Dispose(List1_Enumerator__int4* __this);
::app::Uno::Int4 List1_Enumerator__int4__get_Current(List1_Enumerator__int4* __this);
bool List1_Enumerator__int4__MoveNext(List1_Enumerator__int4* __this);
List1_Enumerator__int4 List1_Enumerator__int4__New_1(::uStatic* __this, ::app::Uno::Collections::List__int4* source);
void List1_Enumerator__int4__Uno_Collections_IEnumerator_Reset(List1_Enumerator__int4* __this);

struct List1_Enumerator__int4
{
    ::uStrong< ::app::Uno::Collections::List__int4*> _source;
    int _version;
    int _iterator;
    ::app::Uno::Int4 _current;

    void _ObjInit(::app::Uno::Collections::List__int4* source) { List1_Enumerator__int4___ObjInit(this, source); }
    void Dispose() { List1_Enumerator__int4__Dispose(this); }
    ::app::Uno::Int4 Current() { return List1_Enumerator__int4__get_Current(this); }
    bool MoveNext() { return List1_Enumerator__int4__MoveNext(this); }
};

}}}

#endif


text:
package hudson.plugins.jira.pipeline;

import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;

import hudson.plugins.jira.JiraSession;
import hudson.plugins.jira.JiraSite;
import hudson.plugins.jira.Messages;
import hudson.plugins.jira.model.JiraIssueField;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;

import com.atlassian.jira.rest.client.api.RestClientException;
import com.google.common.collect.Lists;

import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.jira.selector.AbstractIssueSelector;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import jenkins.tasks.SimpleBuildStep;

/**
 * Issue custom fields updater
 *
 * @author Dmitry Frolov tekillaz.dev@gmail.com
 *
 */
public class IssueFieldUpdateStep extends Builder implements SimpleBuildStep {

    private AbstractIssueSelector issueSelector;

    public AbstractIssueSelector getIssueSelector() {
        return this.issueSelector;
    }

    @DataBoundSetter
    public void setIssueSelector(AbstractIssueSelector issueSelector) {
        this.issueSelector = issueSelector;
    }

    public String fieldId;

    public String getFieldId() {
        return this.fieldId;
    }

    @DataBoundSetter
    public void setFieldId(String fieldId) {
        this.fieldId = fieldId;
    }

    public String fieldValue;

    public String getFieldValue() {
        return this.fieldValue;
    }

    @DataBoundSetter
    public void setFieldValue(String fieldValue) {
        this.fieldValue = fieldValue;
    }

    @DataBoundConstructor
    public IssueFieldUpdateStep(AbstractIssueSelector issueSelector, String fieldId, String fieldValue) {
        this.issueSelector = issueSelector;
        this.fieldId = fieldId;
        this.fieldValue = fieldValue;
    }

    public String prepareFieldId(String fieldId) {
        String prepared = fieldId;
        if (!prepared.startsWith("customfield_"))
            prepared = "customfield_" + prepared;
        return prepared;
    }

    @Override
    public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener)
            throws InterruptedException, IOException {
        PrintStream logger = listener.getLogger();

        AbstractIssueSelector selector = issueSelector;
        if (selector == null) {
            logger.println("[JIRA][IssueFieldUpdateStep] No issue selector found!");
            throw new IOException("[JIRA][IssueFieldUpdateStep] No issue selector found!");
        }

        JiraSite site = JiraSite.get(run.getParent());
        if (site == null) {
            logger.println(Messages.NoJiraSite());
            run.setResult(Result.FAILURE);
            return;
        }

        JiraSession session = null;
        try {
            session = site.getSession();
        } catch (IOException e) {
            listener.getLogger().println(Messages.FailedToConnect());
            e.printStackTrace(listener.getLogger());
        }
        if (session == null) {
            logger.println(Messages.NoRemoteAccess());
            run.setResult(Result.FAILURE);
            return;
        }

        Set<String> issues = selector.findIssueIds(run, site, listener);
        if (issues.isEmpty()) {
            logger.println("[JIRA][IssueFieldUpdateStep] Issue list is empty!");
            return;
        }

        List<JiraIssueField> fields = Lists.newArrayList();
        fields.add(new JiraIssueField(prepareFieldId(fieldId), fieldValue));

        for (String issue : issues) {
            submitFields(session, issue, fields, logger);
        }
    }

    public void submitFields(JiraSession session, String issueId, List<JiraIssueField> fields, PrintStream logger) {
        try {
            session.addFields(issueId, fields);
        } catch (RestClientException e) {

            if (e.getStatusCode().or(0).equals(404)) {
                logger.println(issueId + " - JIRA issue not found");
            }

            if (e.getStatusCode().or(0).equals(403)) {
                logger.println(issueId
                        + " - Jenkins JIRA user does not have permissions to comment on this issue");
            }

            if (e.getStatusCode().or(0).equals(401)) {
                logger.println(
                        issueId + " - Jenkins JIRA authentication problem");
            }

            logger.println(Messages.FailedToUpdateIssue(issueId));
            logger.println(e.getLocalizedMessage());
        }
    }

    @Override
    public DescriptorImpl getDescriptor() {
        return (DescriptorImpl) super.getDescriptor();
    }

    @Extension
    public static class DescriptorImpl extends BuildStepDescriptor<Builder> {

        public FormValidation doCheckField_id(@QueryParameter String value) throws IOException, ServletException {
            if (Util.fixNull(value).trim().length() == 0)
                return FormValidation.warning(Messages.JiraIssueFieldUpdater_NoIssueFieldID());
            if (!value.matches("\\d+"))
                return FormValidation.error(Messages.JiraIssueFieldUpdater_NotAtIssueFieldID());
            return FormValidation.ok();
        }

        @Override
        public boolean isApplicable(Class<? extends AbstractProject> jobType) {
            return true;
        }

        @Override
        public String getDisplayName() {
            return Messages.JiraIssueFieldUpdater_DisplayName();
        }
    }

}


text:
@class NSDate;

__attribute__((visibility("hidden")))
@interface BRStreamingMediaHost : BRSyncingMediaHost
{
    NSDate *_lastAccessedDate;
}

+ (id)streamingMediaHostWithHostInfo:(id)arg1;
- (void)dealloc;
- (id)init;

@end


text:
from charms.reactive import when, when_not, set_state

@when_not('pintostack.installed')
def install_pintostack():
    # Do your setup here.
    #
    # If your charm has other dependencies before it can install,
    # add those as @when() clauses above., or as additional @when()
    # decorated handlers below
    #
    # See the following for information about reactive charms:
    #
    #  * https://jujucharms.com/docs/devel/developer-getting-started
    #  * https://github.com/juju-solutions/layer-basic#overview
    #
    set_state('pintostack.installed')


text:
package org.jf.dexlib2.dexbacked;

import com.google.common.io.ByteStreams;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.OatFile.SymbolTable.Symbol;
import org.jf.dexlib2.dexbacked.raw.HeaderItem;
import org.jf.util.AbstractForwardSequentialList;

import javax.annotation.Nonnull;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;

public class OatFile extends BaseDexBuffer {
    private static final byte[] ELF_MAGIC = new byte[] { 0x7f, 'E', 'L', 'F' };
    private static final byte[] OAT_MAGIC = new byte[] { 'o', 'a', 't', '\n' };
    private static final int MIN_ELF_HEADER_SIZE = 52;

    // These are the "known working" versions that I have manually inspected the source for.
    // Later version may or may not work, depending on what changed.
    private static final int MIN_OAT_VERSION = 56;
    private static final int MAX_OAT_VERSION = 71;

    public static final int UNSUPPORTED = 0;
    public static final int SUPPORTED = 1;
    public static final int UNKNOWN = 2;

    private final boolean is64bit;
    @Nonnull private final OatHeader oatHeader;
    @Nonnull private final Opcodes opcodes;

    public OatFile(@Nonnull byte[] buf) {
        super(buf);

        if (buf.length < MIN_ELF_HEADER_SIZE) {
            throw new NotAnOatFileException();
        }

        verifyMagic(buf);

        if (buf[4] == 1) {
            is64bit = false;
        } else if (buf[4] == 2) {
            is64bit = true;
        } else {
            throw new InvalidOatFileException(String.format("Invalid word-size value: %x", buf[5]));
        }

        OatHeader oatHeader = null;
        SymbolTable symbolTable = getSymbolTable();
        for (Symbol symbol: symbolTable.getSymbols()) {
            if (symbol.getName().equals("oatdata")) {
                oatHeader = new OatHeader(symbol.getFileOffset());
                break;
            }
        }

        if (oatHeader == null) {
            throw new InvalidOatFileException("Oat file has no oatdata symbol");
        }
        this.oatHeader = oatHeader;

        if (!oatHeader.isValid()) {
            throw new InvalidOatFileException("Invalid oat magic value");
        }

        this.opcodes = Opcodes.forArtVersion(oatHeader.getVersion());
    }

    private static void verifyMagic(byte[] buf) {
        for (int i = 0; i < ELF_MAGIC.length; i++) {
            if (buf[i] != ELF_MAGIC[i]) {
                throw new NotAnOatFileException();
            }
        }
    }

    public static OatFile fromInputStream(@Nonnull InputStream is)
            throws IOException {
        if (!is.markSupported()) {
            throw new IllegalArgumentException("InputStream must support mark");
        }
        is.mark(4);
        byte[] partialHeader = new byte[4];
        try {
            ByteStreams.readFully(is, partialHeader);
        } catch (EOFException ex) {
            throw new NotAnOatFileException();
        } finally {
            is.reset();
        }

        verifyMagic(partialHeader);

        is.reset();

        byte[] buf = ByteStreams.toByteArray(is);
        return new OatFile(buf);
    }

    public int getOatVersion() {
        return oatHeader.getVersion();
    }

    public int isSupportedVersion() {
        int version = getOatVersion();
        if (version < MIN_OAT_VERSION) {
            return UNSUPPORTED;
        }
        if (version <= MAX_OAT_VERSION) {
            return SUPPORTED;
        }
        return UNKNOWN;
    }

    @Nonnull
    public List<OatDexFile> getDexFiles() {
        return new AbstractForwardSequentialList<OatDexFile>() {
            @Override public int size() {
                return oatHeader.getDexFileCount();
            }

            @Nonnull @Override public Iterator<OatDexFile> iterator() {
                return new Iterator<OatDexFile>() {
                    int index = 0;
                    int offset = oatHeader.getDexListStart();

                    @Override public boolean hasNext() {
                        return index < size();
                    }

                    @Override public OatDexFile next() {
                        int filenameLength = readSmallUint(offset);
                        offset += 4;

                        // TODO: what is the correct character encoding?
                        String filename = new String(buf, offset, filenameLength, Charset.forName("US-ASCII"));
                        offset += filenameLength;

                        offset += 4; // checksum

                        int dexOffset = readSmallUint(offset) + oatHeader.offset;
                        offset += 4;

                        int classCount = readSmallUint(dexOffset + HeaderItem.CLASS_COUNT_OFFSET);
                        offset += 4 * classCount;

                        index++;

                        return new OatDexFile(dexOffset, filename);
                    }

                    @Override public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    public class OatDexFile extends DexBackedDexFile {
        @Nonnull public final String filename;

        public OatDexFile(int offset, @Nonnull String filename) {
            super(opcodes, OatFile.this.buf, offset);
            this.filename = filename;
        }

        public int getOatVersion() {
            return OatFile.this.getOatVersion();
        }

        @Override public boolean hasOdexOpcodes() {
            return true;
        }
    }

    private class OatHeader {
        private final int offset;

        public OatHeader(int offset) {
            this.offset = offset;
        }

        public boolean isValid() {
            for (int i=0; i<OAT_MAGIC.length; i++) {
                if (buf[offset + i] != OAT_MAGIC[i]) {
                    return false;
                }
            }

            for (int i=4; i<7; i++) {
                if (buf[offset + i] < '0' || buf[offset + i] > '9') {
                    return false;
                }
            }

            return buf[offset + 7] == 0;
        }

        public int getVersion() {
            return Integer.valueOf(new String(buf, offset + 4, 3));
        }

        public int getDexFileCount() {
            return readSmallUint(offset + 20);
        }

        public int getKeyValueStoreSize() {
            int version = getVersion();
            if (version < 56) {
                throw new IllegalStateException("Unsupported oat version");
            }
            int fieldOffset = 17 * 4;
            return readSmallUint(offset + fieldOffset);
        }

        public int getHeaderSize() {
            int version = getVersion();
             if (version >= 56) {
                return 18*4 + getKeyValueStoreSize();
            } else {
                throw new IllegalStateException("Unsupported oat version");
            }

        }

        public int getDexListStart() {
            return offset + getHeaderSize();
        }
    }

    @Nonnull
    private List<SectionHeader> getSections() {
        final int offset;
        final int entrySize;
        final int entryCount;
        if (is64bit) {
            offset = readLongAsSmallUint(40);
            entrySize = readUshort(58);
            entryCount = readUshort(60);
        } else {
            offset = readSmallUint(32);
            entrySize = readUshort(46);
            entryCount = readUshort(48);
        }

        if (offset + (entrySize * entryCount) > buf.length) {
            throw new InvalidOatFileException("The ELF section headers extend past the end of the file");
        }

        return new AbstractList<SectionHeader>() {
            @Override public SectionHeader get(int index) {
                if (index < 0 || index >= entryCount) {
                    throw new IndexOutOfBoundsException();
                }
                if (is64bit) {
                    return new SectionHeader64Bit(offset + (index * entrySize));
                } else {
                    return new SectionHeader32Bit(offset + (index * entrySize));
                }
            }

            @Override public int size() {
                return entryCount;
            }
        };
    }

    @Nonnull
    private SymbolTable getSymbolTable() {
        for (SectionHeader header: getSections()) {
            if (header.getType() == SectionHeader.TYPE_DYNAMIC_SYMBOL_TABLE) {
                return new SymbolTable(header);
            }
        }
        throw new InvalidOatFileException("Oat file has no symbol table");
    }

    @Nonnull
    private StringTable getSectionNameStringTable() {
        int index = readUshort(50);
        if (index == 0) {
            throw new InvalidOatFileException("There is no section name string table");
        }

        try {
            return new StringTable(getSections().get(index));
        } catch (IndexOutOfBoundsException ex) {
            throw new InvalidOatFileException("The section index for the section name string table is invalid");
        }
    }

    private abstract class SectionHeader {
        protected final int offset;
        public static final int TYPE_DYNAMIC_SYMBOL_TABLE = 11;
        public SectionHeader(int offset) { this.offset = offset; }
        @Nonnull public String getName() { return getSectionNameStringTable().getString(readSmallUint(offset)); }
        public int getType() { return readInt(offset + 4); }
        public abstract long getAddress();
        public abstract int getOffset();
        public abstract int getSize();
        public abstract int getLink();
        public abstract int getEntrySize();
    }

    private class SectionHeader32Bit extends SectionHeader {
        public SectionHeader32Bit(int offset) { super(offset); }
        @Override public long getAddress() { return readInt(offset + 12) & 0xFFFFFFFFL; }
        @Override public int getOffset() { return readSmallUint(offset + 16); }
        @Override public int getSize() { return readSmallUint(offset + 20); }
        @Override public int getLink() { return readSmallUint(offset + 24); }
        @Override public int getEntrySize() { return readSmallUint(offset + 36); }
    }

    private class SectionHeader64Bit extends SectionHeader {
        public SectionHeader64Bit(int offset) { super(offset); }
        @Override public long getAddress() { return readLong(offset + 16); }
        @Override public int getOffset() { return readLongAsSmallUint(offset + 24); }
        @Override public int getSize() { return readLongAsSmallUint(offset + 32); }
        @Override public int getLink() { return readSmallUint(offset + 40); }
        @Override public int getEntrySize() { return readLongAsSmallUint(offset + 56); }
    }

    class SymbolTable {
        @Nonnull private final StringTable stringTable;
        private final int offset;
        private final int entryCount;
        private final int entrySize;

        public SymbolTable(@Nonnull SectionHeader header) {
            try {
                this.stringTable = new StringTable(getSections().get(header.getLink()));
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidOatFileException("String table section index is invalid");
            }
            this.offset = header.getOffset();
            this.entrySize = header.getEntrySize();
            this.entryCount = header.getSize() / entrySize;

            if (offset + entryCount * entrySize > buf.length) {
                throw new InvalidOatFileException("Symbol table extends past end of file");
            }
        }

        @Nonnull
        public List<Symbol> getSymbols() {
            return new AbstractList<Symbol>() {
                @Override public Symbol get(int index) {
                    if (index < 0 || index >= entryCount) {
                        throw new IndexOutOfBoundsException();
                    }
                    if (is64bit) {
                        return new Symbol64(offset + index * entrySize);
                    } else {
                        return new Symbol32(offset + index * entrySize);
                    }
                }

                @Override public int size() {
                    return entryCount;
                }
            };
        }

        public abstract class Symbol {
            protected final int offset;
            public Symbol(int offset) { this.offset = offset; }
            @Nonnull public abstract String getName();
            public abstract long getValue();
            public abstract int getSize();
            public abstract int getSectionIndex();

            public int getFileOffset() {
                SectionHeader sectionHeader;
                try {
                    sectionHeader = getSections().get(getSectionIndex());
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidOatFileException("Section index for symbol is out of bounds");
                }

                long sectionAddress = sectionHeader.getAddress();
                int sectionOffset = sectionHeader.getOffset();
                int sectionSize = sectionHeader.getSize();

                long symbolAddress = getValue();

                if (symbolAddress < sectionAddress || symbolAddress >= sectionAddress + sectionSize) {
                    throw new InvalidOatFileException("symbol address lies outside it's associated section");
                }

                long fileOffset = (sectionOffset + (getValue() - sectionAddress));
                assert fileOffset <= Integer.MAX_VALUE;
                return (int)fileOffset;
            }
        }

        public class Symbol32 extends Symbol {
            public Symbol32(int offset) { super(offset); }

            @Nonnull
            public String getName() { return stringTable.getString(readSmallUint(offset)); }
            public long getValue() { return readSmallUint(offset + 4); }
            public int getSize() { return readSmallUint(offset + 8); }
            public int getSectionIndex() { return readUshort(offset + 14); }
        }

        public class Symbol64 extends Symbol {
            public Symbol64(int offset) { super(offset); }

            @Nonnull
            public String getName() { return stringTable.getString(readSmallUint(offset)); }
            public long getValue() { return readLong(offset + 8); }
            public int getSize() { return readLongAsSmallUint(offset + 16); }
            public int getSectionIndex() { return readUshort(offset + 6); }
        }
    }

    private class StringTable {
        private final int offset;
        private final int size;

        public StringTable(@Nonnull SectionHeader header) {
            this.offset = header.getOffset();
            this.size = header.getSize();

            if (offset + size > buf.length) {
                throw new InvalidOatFileException("String table extends past end of file");
            }
        }

        @Nonnull
        public String getString(int index) {
            if (index >= size) {
                throw new InvalidOatFileException("String index is out of bounds");
            }

            int start = offset + index;
            int end = start;
            while (buf[end] != 0) {
                end++;
                if (end >= offset + size) {
                    throw new InvalidOatFileException("String extends past end of string table");
                }
            }

            return new String(buf, start, end-start, Charset.forName("US-ASCII"));
        }

    }

    public static class InvalidOatFileException extends RuntimeException {
        public InvalidOatFileException(String message) {
            super(message);
        }
    }

    public static class NotAnOatFileException extends RuntimeException {
        public NotAnOatFileException() {}
    }
}


text:
package com.greenpepper.extensions.ognl;

import java.util.ArrayList;
import java.util.List;

import com.greenpepper.util.NameUtils;
import com.greenpepper.util.StringUtil;

/**
 * Build an ordered expressions list to resolve at OGNL execution.
 */
public class OgnlResolution
{
    private String expression;
    private String format;

    public OgnlResolution( String expression )
    {
        if (StringUtil.isBlank( expression )) throw new IllegalArgumentException( "No expression to resolve" );

        this.expression = expression;
    }

    public List<String> expressionsListToResolve()
    {
        String[] parts = expression.trim().split( "\\s+" );
        List<String> expressionsList = new ArrayList<String>();

        withDots( expressionsList, parts );
        noDots( expressionsList, parts );
        asIs( expressionsList, parts );

        return expressionsList;
    }

    public List<String> expressionsListToResolve( String format )
    {
        this.format = format;

        return expressionsListToResolve();
    }

    private void withDots( List<String> expressionsList, String[] parts )
    {
        boolean[] dots = new boolean[parts.length - 1];

        placeDots( expressionsList, parts, dots, 0 );
    }

    private void placeDots( List<String> expressionsList, String[] parts, boolean[] dots, int from )
    {
        for (int i = from; i < dots.length; i++)
        {
            dots[i] = true;

            placeDots( expressionsList, parts, dots, i + 1 );

            addExpression( expressionsList, parts, dots );

            dots[i] = false;
        }
    }

    private void noDots( List<String> expressionsList, String[] parts )
    {
        boolean[] dots = new boolean[parts.length - 1];

        addExpression( expressionsList, parts, dots );
    }

    private void asIs( List<String> expressionsList, String[] parts )
    {
        String addExpression = "";

        for (int i = 0; i < parts.length; i++)
        {
            addExpression += parts[i] + " ";
        }

        addToList( expressionsList, addExpression );
    }

    private void addExpression( List<String> expressionsList, String[] parts, boolean[] dots )
    {
        String addExpression = "";
        String identifier = "";

        for (int i = 0; i < parts.length; i++)
        {
            if (startAsAnIdentifier( parts[i] ))
            {
                identifier += parts[i] + " ";

                if (identifierComplete( parts, dots, i ))
                {
                    addExpression += NameUtils.toLowerCamelCase( identifier );
                    addExpression += (insertDot( parts, dots, i ) ? "." : " ");

                    identifier = "";
                }
            }
            else
            {
                addExpression += parts[i];
                addExpression += (insertDot( parts, dots, i ) ? "." : " ");
            }
        }

        addToList( expressionsList, addExpression );
    }

    private void addToList( List<String> expressionsList, String addExpression )
    {
        addExpression = addExpression.trim();

        if (format != null)
        {
            addExpression = String.format( format, addExpression );
        }

        if (!StringUtil.isEmpty( addExpression ) && !expressionsList.contains( addExpression ))
        {
            expressionsList.add( addExpression );
        }
    }

    private boolean startAsAnIdentifier( String token )
    {
        return Character.isJavaIdentifierStart( token.codePointAt( 0 ) );
    }

    private boolean identifierComplete( String[] parts, boolean[] dots, int index )
    {
        /*
         * The identifier is complete if:
         *    - It's the last token or
         *    - The next token does not start as a valid Java identifier or
         *    - A dot is to be insert after identifier.
         */
        return index == parts.length - 1 ||
               !Character.isJavaIdentifierStart( firstChar( parts[index + 1] ) ) ||
               insertDot( parts, dots, index );
    }

    private int firstChar( String s )
    {
        return s.codePointAt( 0 );
    }

    private boolean insertDot( String[] parts, boolean[] dots, int index )
    {
        /*
         * A dot is to be inserted if:
         *    - It's not the last token and
         *    - Indication to actually try to insert it and
         *    - The next token start as a valid Java identifier.
         */
        return index < parts.length - 1 && dots[index] && Character.isJavaIdentifierStart( firstChar( parts[index + 1] ) );
    }
}