text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Esprima: Regex Collector Demo</title>

<link rel="stylesheet" type="text/css" href="../assets/codemirror/codemirror.css"/>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>

← Home

Code

Documentation

Issues

Regular Expression Collector uncovers all your secrets

Note: Only regular expression literals and objects created with RegExp are considered.

Type ECMAScript code:

<textarea id="code" autofocus="autofocus" cols="70" rows="15" spellcheck="false">
var letterRE = new RegExp('[a-zA-Z]', 'g'),
    digitRE = RegExp('[0-9]');

// This is from json2.js.

if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
    .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
    .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
}
</textarea>

The above code editor is based on CodeMirror.

Using Esprima version .

Esprima is created by
Ariya Hidayat. Follow @ariyahidayat on Twitter.

<textarea id="test"></textarea>

redpajama_set_name: RedPajamaGithub


text:
typedef enum
{
    MQ_WAIT_NONE,		// don't wait
    MQ_WAIT_RECEIVED,	// wait until the consumer thread has received the message
    MQ_WAIT_PROCESSED	// wait until the consumer thread has processed the message
} ovrMQWait;

#define MAX_MESSAGE_PARMS	8
#define MAX_MESSAGES		1024

typedef struct
{
    int			Id;
    ovrMQWait	Wait;
    long long	Parms[MAX_MESSAGE_PARMS];
} ovrMessage;

static void ovrMessage_Init( ovrMessage * message, const int id, const ovrMQWait wait )
{
    message->Id = id;
    message->Wait = wait;
    memset( message->Parms, 0, sizeof( message->Parms ) );
}

static void		ovrMessage_SetPointerParm( ovrMessage * message, int index, void * ptr ) { *(void **)&message->Parms[index] = ptr; }
static void *	ovrMessage_GetPointerParm( ovrMessage * message, int index ) { return *(void **)&message->Parms[index]; }
static void		ovrMessage_SetIntegerParm( ovrMessage * message, int index, int value ) { message->Parms[index] = value; }
static int		ovrMessage_GetIntegerParm( ovrMessage * message, int index ) { return (int)message->Parms[index]; }
static void		ovrMessage_SetFloatParm( ovrMessage * message, int index, float value ) { *(float *)&message->Parms[index] = value; }
static float	ovrMessage_GetFloatParm( ovrMessage * message, int index ) { return *(float *)&message->Parms[index]; }

// Cyclic queue with messages.
typedef struct
{
    ovrMessage	 		Messages[MAX_MESSAGES];
    volatile int		Head;	// dequeue at the head
    volatile int		Tail;	// enqueue at the tail
    ovrMQWait			Wait;
    volatile bool		EnabledFlag;
    volatile bool		PostedFlag;
    volatile bool		ReceivedFlag;
    volatile bool		ProcessedFlag;
    pthread_mutex_t		Mutex;
    pthread_cond_t		PostedCondition;
    pthread_cond_t		ReceivedCondition;
    pthread_cond_t		ProcessedCondition;
} ovrMessageQueue;

static void ovrMessageQueue_Create( ovrMessageQueue * messageQueue )
{
    messageQueue->Head = 0;
    messageQueue->Tail = 0;
    messageQueue->Wait = MQ_WAIT_NONE;
    messageQueue->EnabledFlag = false;
    messageQueue->PostedFlag = false;
    messageQueue->ReceivedFlag = false;
    messageQueue->ProcessedFlag = false;

    pthread_mutexattr_t	attr;
    pthread_mutexattr_init( &attr );
    pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
    pthread_mutex_init( &messageQueue->Mutex, &attr );
    pthread_mutexattr_destroy( &attr );
    pthread_cond_init( &messageQueue->PostedCondition, NULL );
    pthread_cond_init( &messageQueue->ReceivedCondition, NULL );
    pthread_cond_init( &messageQueue->ProcessedCondition, NULL );
}

static void ovrMessageQueue_Destroy( ovrMessageQueue * messageQueue )
{
    pthread_mutex_destroy( &messageQueue->Mutex );
    pthread_cond_destroy( &messageQueue->PostedCondition );
    pthread_cond_destroy( &messageQueue->ReceivedCondition );
    pthread_cond_destroy( &messageQueue->ProcessedCondition );
}

static void ovrMessageQueue_Enable( ovrMessageQueue * messageQueue, const bool set )
{
    messageQueue->EnabledFlag = set;
}

static void ovrMessageQueue_PostMessage( ovrMessageQueue * messageQueue, const ovrMessage * message )
{
    if ( !messageQueue->EnabledFlag )
    {
        return;
    }
    while ( messageQueue->Tail - messageQueue->Head >= MAX_MESSAGES )
    {
        usleep( 1000 );
    }
    pthread_mutex_lock( &messageQueue->Mutex );
    messageQueue->Messages[messageQueue->Tail & ( MAX_MESSAGES - 1 )] = *message;
    messageQueue->Tail++;
    messageQueue->PostedFlag = true;
    pthread_cond_broadcast( &messageQueue->PostedCondition );
    if ( message->Wait == MQ_WAIT_RECEIVED )
    {
        while ( !messageQueue->ReceivedFlag )
        {
            pthread_cond_wait( &messageQueue->ReceivedCondition, &messageQueue->Mutex );
        }
        messageQueue->ReceivedFlag = false;
    }
    else if ( message->Wait == MQ_WAIT_PROCESSED )
    {
        while ( !messageQueue->ProcessedFlag )
        {
            pthread_cond_wait( &messageQueue->ProcessedCondition, &messageQueue->Mutex );
        }
        messageQueue->ProcessedFlag = false;
    }
    pthread_mutex_unlock( &messageQueue->Mutex );
}

static void ovrMessageQueue_SleepUntilMessage( ovrMessageQueue * messageQueue )
{
    if ( messageQueue->Wait == MQ_WAIT_PROCESSED )
    {
        messageQueue->ProcessedFlag = true;
        pthread_cond_broadcast( &messageQueue->ProcessedCondition );
        messageQueue->Wait = MQ_WAIT_NONE;
    }
    pthread_mutex_lock( &messageQueue->Mutex );
    if ( messageQueue->Tail > messageQueue->Head )
    {
        pthread_mutex_unlock( &messageQueue->Mutex );
        return;
    }
    while ( !messageQueue->PostedFlag )
    {
        pthread_cond_wait( &messageQueue->PostedCondition, &messageQueue->Mutex );
    }
    messageQueue->PostedFlag = false;
    pthread_mutex_unlock( &messageQueue->Mutex );
}

static bool ovrMessageQueue_GetNextMessage( ovrMessageQueue * messageQueue, ovrMessage * message, bool waitForMessages )
{
    if ( messageQueue->Wait == MQ_WAIT_PROCESSED )
    {
        messageQueue->ProcessedFlag = true;
        pthread_cond_broadcast( &messageQueue->ProcessedCondition );
        messageQueue->Wait = MQ_WAIT_NONE;
    }
    if ( waitForMessages )
    {
        ovrMessageQueue_SleepUntilMessage( messageQueue );
    }
    pthread_mutex_lock( &messageQueue->Mutex );
    if ( messageQueue->Tail <= messageQueue->Head )
    {
        pthread_mutex_unlock( &messageQueue->Mutex );
        return false;
    }
    *message = messageQueue->Messages[messageQueue->Head & ( MAX_MESSAGES - 1 )];
    messageQueue->Head++;
    pthread_mutex_unlock( &messageQueue->Mutex );
    if ( message->Wait == MQ_WAIT_RECEIVED )
    {
        messageQueue->ReceivedFlag = true;
        pthread_cond_broadcast( &messageQueue->ReceivedCondition );
    }
    else if ( message->Wait == MQ_WAIT_PROCESSED )
    {
        messageQueue->Wait = MQ_WAIT_PROCESSED;
    }
    return true;
}

// ================================================================================================
// Oculus Mobile SDK EGL library
// ================================================================================================
#if !defined( EGL_OPENGL_ES3_BIT_KHR )
#define EGL_OPENGL_ES3_BIT_KHR		0x0040
#endif

static const char * EglErrorString( const EGLint error )
{
    switch ( error )
    {
        case EGL_SUCCESS:				return "EGL_SUCCESS";
        case EGL_NOT_INITIALIZED:		return "EGL_NOT_INITIALIZED";
        case EGL_BAD_ACCESS:			return "EGL_BAD_ACCESS";
        case EGL_BAD_ALLOC:				return "EGL_BAD_ALLOC";
        case EGL_BAD_ATTRIBUTE:			return "EGL_BAD_ATTRIBUTE";
        case EGL_BAD_CONTEXT:			return "EGL_BAD_CONTEXT";
        case EGL_BAD_CONFIG:			return "EGL_BAD_CONFIG";
        case EGL_BAD_CURRENT_SURFACE:	return "EGL_BAD_CURRENT_SURFACE";
        case EGL_BAD_DISPLAY:			return "EGL_BAD_DISPLAY";
        case EGL_BAD_SURFACE:			return "EGL_BAD_SURFACE";
        case EGL_BAD_MATCH:				return "EGL_BAD_MATCH";
        case EGL_BAD_PARAMETER:			return "EGL_BAD_PARAMETER";
        case EGL_BAD_NATIVE_PIXMAP:		return "EGL_BAD_NATIVE_PIXMAP";
        case EGL_BAD_NATIVE_WINDOW:		return "EGL_BAD_NATIVE_WINDOW";
        case EGL_CONTEXT_LOST:			return "EGL_CONTEXT_LOST";
        default:						return "unknown";
    }
}

static const char * GlFrameBufferStatusString( GLenum status )
{
    switch ( status )
    {
        case GL_FRAMEBUFFER_UNDEFINED:						return "GL_FRAMEBUFFER_UNDEFINED";
        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:			return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:	return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
        case GL_FRAMEBUFFER_UNSUPPORTED:					return "GL_FRAMEBUFFER_UNSUPPORTED";
        case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:			return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE";
        default:											return "unknown";
    }
}

#ifdef CHECK_GL_ERRORS

static const char * GlErrorString( GLenum error )
{
    switch ( error )
    {
        case GL_NO_ERROR:						return "GL_NO_ERROR";
        case GL_INVALID_ENUM:					return "GL_INVALID_ENUM";
        case GL_INVALID_VALUE:					return "GL_INVALID_VALUE";
        case GL_INVALID_OPERATION:				return "GL_INVALID_OPERATION";
        case GL_INVALID_FRAMEBUFFER_OPERATION:	return "GL_INVALID_FRAMEBUFFER_OPERATION";
        case GL_OUT_OF_MEMORY:					return "GL_OUT_OF_MEMORY";
        default: return "unknown";
    }
}

static void GLCheckErrors()
{
    for ( int i = 0; i < 10; i++ )
    {
        const GLenum error = glGetError();
        if ( error == GL_NO_ERROR )
        {
            break;
        }
        ALOGE( "GL error: %s", GlErrorString( error ) );
    }
}

#define GL( func )		func; GLCheckErrors();

#else // CHECK_GL_ERRORS

#define GL( func )		func;

#endif // CHECK_GL_ERRORS

typedef struct
{
    EGLint		MajorVersion;
    EGLint		MinorVersion;
    EGLDisplay	Display;
    EGLConfig	Config;
    EGLSurface	TinySurface;
    EGLSurface	MainSurface;
    EGLContext	Context;
} ovrEgl;

static void ovrEgl_Clear( ovrEgl * egl )
{
    egl->MajorVersion = 0;
    egl->MinorVersion = 0;
    egl->Display = 0;
    egl->Config = 0;
    egl->TinySurface = EGL_NO_SURFACE;
    egl->MainSurface = EGL_NO_SURFACE;
    egl->Context = EGL_NO_CONTEXT;
}

static void ovrEgl_CreateContext( ovrEgl * egl, const ovrEgl * shareEgl )
{
    if ( egl->Display != 0 )
    {
        return;
    }

    egl->Display = eglGetDisplay( EGL_DEFAULT_DISPLAY );
    LOG_MESSAGE( "        eglInitialize( Display, &MajorVersion, &MinorVersion )" );
    eglInitialize( egl->Display, &egl->MajorVersion, &egl->MinorVersion );
    // Do NOT use eglChooseConfig, because the Android EGL code pushes in multisample
    // flags in eglChooseConfig if the user has selected the "force 4x MSAA" option in
    // settings, and that is completely wasted for our warp target.
    const int MAX_CONFIGS = 1024;
    EGLConfig configs[MAX_CONFIGS];
    EGLint numConfigs = 0;
    if ( eglGetConfigs( egl->Display, configs, MAX_CONFIGS, &numConfigs ) == EGL_FALSE )
    {
        LOG_ERROR( "        eglGetConfigs() failed: %s", EglErrorString( eglGetError() ) );
        return;
    }
    const EGLint configAttribs[] =
    {
        EGL_ALPHA_SIZE, 8, // need alpha for the multi-pass timewarp compositor
        EGL_BLUE_SIZE,  8,
        EGL_GREEN_SIZE, 8,
        EGL_RED_SIZE,   8,
        EGL_DEPTH_SIZE, 0,
        EGL_SAMPLES,	0,
        EGL_NONE
    };
    egl->Config = 0;
    for ( int i = 0; i < numConfigs; i++ )
    {
        EGLint value = 0;

        eglGetConfigAttrib( egl->Display, configs[i], EGL_RENDERABLE_TYPE, &value );
        if ( ( value & EGL_OPENGL_ES3_BIT_KHR ) != EGL_OPENGL_ES3_BIT_KHR )
        {
            continue;
        }

        // The pbuffer config also needs to be compatible with normal window rendering
        // so it can share textures with the window context.
        eglGetConfigAttrib( egl->Display, configs[i], EGL_SURFACE_TYPE, &value );
        if ( ( value & ( EGL_WINDOW_BIT | EGL_PBUFFER_BIT ) ) != ( EGL_WINDOW_BIT | EGL_PBUFFER_BIT ) )
        {
            continue;
        }

        int	j = 0;
        for ( ; configAttribs[j] != EGL_NONE; j += 2 )
        {
            eglGetConfigAttrib( egl->Display, configs[i], configAttribs[j], &value );
            if ( value != configAttribs[j + 1] )
            {
                break;
            }
        }
        if ( configAttribs[j] == EGL_NONE )
        {
            egl->Config = configs[i];
            break;
        }
    }
    if ( egl->Config == 0 )
    {
        LOG_ERROR( "        eglChooseConfig() failed: %s", EglErrorString( eglGetError() ) );
        return;
    }
    EGLint contextAttribs[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, 3,
        EGL_NONE
    };
    LOG_MESSAGE( "        Context = eglCreateContext( Display, Config, EGL_NO_CONTEXT, contextAttribs )" );
    egl->Context = eglCreateContext( egl->Display, egl->Config, ( shareEgl != NULL ) ? shareEgl->Context : EGL_NO_CONTEXT, contextAttribs );
    if ( egl->Context == EGL_NO_CONTEXT )
    {
        LOG_ERROR( "        eglCreateContext() failed: %s", EglErrorString( eglGetError() ) );
        return;
    }
    const EGLint surfaceAttribs[] =
    {
        EGL_WIDTH, 16,
        EGL_HEIGHT, 16,
        EGL_NONE
    };
    LOG_MESSAGE( "        TinySurface = eglCreatePbufferSurface( Display, Config, surfaceAttribs )" );
    egl->TinySurface = eglCreatePbufferSurface( egl->Display, egl->Config, surfaceAttribs );
    if ( egl->TinySurface == EGL_NO_SURFACE )
    {
        LOG_ERROR( "        eglCreatePbufferSurface() failed: %s", EglErrorString( eglGetError() ) );
        eglDestroyContext( egl->Display, egl->Context );
        egl->Context = EGL_NO_CONTEXT;
        return;
    }
    LOG_MESSAGE( "        eglMakeCurrent( Display, TinySurface, TinySurface, Context )" );
    if ( eglMakeCurrent( egl->Display, egl->TinySurface, egl->TinySurface, egl->Context ) == EGL_FALSE )
    {
        LOG_ERROR( "        eglMakeCurrent() failed: %s", EglErrorString( eglGetError() ) );
        eglDestroySurface( egl->Display, egl->TinySurface );
        eglDestroyContext( egl->Display, egl->Context );
        egl->Context = EGL_NO_CONTEXT;
        return;
    }
}

static void ovrEgl_DestroyContext( ovrEgl * egl )
{
    if ( egl->Display != 0 )
    {
        LOG_ERROR( "        eglMakeCurrent( Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT )" );
        if ( eglMakeCurrent( egl->Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT ) == EGL_FALSE )
        {
            LOG_ERROR( "        eglMakeCurrent() failed: %s", EglErrorString( eglGetError() ) );
        }
    }
    if ( egl->Context != EGL_NO_CONTEXT )
    {
        LOG_ERROR( "        eglDestroyContext( Display, Context )" );
        if ( eglDestroyContext( egl->Display, egl->Context ) == EGL_FALSE )
        {
            LOG_ERROR( "        eglDestroyContext() failed: %s", EglErrorString( eglGetError() ) );
        }
        egl->Context = EGL_NO_CONTEXT;
    }
    if ( egl->TinySurface != EGL_NO_SURFACE )
    {
        LOG_ERROR( "        eglDestroySurface( Display, TinySurface )" );
        if ( eglDestroySurface( egl->Display, egl->TinySurface ) == EGL_FALSE )
        {
            LOG_ERROR( "        eglDestroySurface() failed: %s", EglErrorString( eglGetError() ) );
        }
        egl->TinySurface = EGL_NO_SURFACE;
    }
    if ( egl->Display != 0 )
    {
        LOG_ERROR( "        eglTerminate( Display )" );
        if ( eglTerminate( egl->Display ) == EGL_FALSE )
        {
            LOG_ERROR( "        eglTerminate() failed: %s", EglErrorString( eglGetError() ) );
        }
        egl->Display = 0;
    }
}

static void ovrEgl_CreateSurface( ovrEgl * egl, ANativeWindow * nativeWindow )
{
    if ( egl->MainSurface != EGL_NO_SURFACE )
    {
        return;
    }
    LOG_MESSAGE( "        MainSurface = eglCreateWindowSurface( Display, Config, nativeWindow, attribs )" );
    const EGLint surfaceAttribs[] = { EGL_NONE };
    egl->MainSurface = eglCreateWindowSurface( egl->Display, egl->Config, nativeWindow, surfaceAttribs );
    if ( egl->MainSurface == EGL_NO_SURFACE )
    {
        LOG_ERROR( "        eglCreateWindowSurface() failed: %s", EglErrorString( eglGetError() ) );
        return;
    }
#if EXPLICIT_GL_OBJECTS == 0
    LOG_MESSAGE( "        eglMakeCurrent( display, MainSurface, MainSurface, Context )" );
    if ( eglMakeCurrent( egl->Display, egl->MainSurface, egl->MainSurface, egl->Context ) == EGL_FALSE )
    {
        LOG_ERROR( "        eglMakeCurrent() failed: %s", EglErrorString( eglGetError() ) );
        return;
    }
#endif
}

static void ovrEgl_DestroySurface( ovrEgl * egl )
{
#if EXPLICIT_GL_OBJECTS == 0
    if ( egl->Context != EGL_NO_CONTEXT )
    {
        LOG_MESSAGE( "        eglMakeCurrent( display, TinySurface, TinySurface, Context )" );
        if ( eglMakeCurrent( egl->Display, egl->TinySurface, egl->TinySurface, egl->Context ) == EGL_FALSE )
        {
            LOG_ERROR( "        eglMakeCurrent() failed: %s", EglErrorString( eglGetError() ) );
        }
    }
#endif
    if ( egl->MainSurface != EGL_NO_SURFACE )
    {
        LOG_MESSAGE( "        eglDestroySurface( Display, MainSurface )" );
        if ( eglDestroySurface( egl->Display, egl->MainSurface ) == EGL_FALSE )
        {
            LOG_ERROR( "        eglDestroySurface() failed: %s", EglErrorString( eglGetError() ) );
        }
        egl->MainSurface = EGL_NO_SURFACE;
    }
}

// ================================================================================================
// OculudMobileSDKHeadTracking
// ================================================================================================
class OculusMobileSDKHeadTracking
{
private:
    static const int CPU_LEVEL = 2;
    static const int GPU_LEVEL = 3;

    enum MessageTypes
    {
        MESSAGE_START,
        MESSAGE_RESUME,
        MESSAGE_PAUSE,
        MESSAGE_STOP,
        MESSAGE_SURFACE_CREATED,
        MESSAGE_SURFACE_DESTROYED
    };

    pthread_t thread;
    JavaVM* javaVM;
    jobject activityJObject;
    jobject oculusMobileSDKHeadTrackingJObject;
    jobject dataJObject;
    jclass oculusMobileSDKHeadTrackingJClass;
    jclass dataJClass;
    jmethodID headTrackingStartedMethodID;
    jmethodID headTrackingErrorMethodID;
    jfieldID dataTimeStampFieldID;
    jfieldID dataOrientationXFieldID;
    jfieldID dataOrientationYFieldID;
    jfieldID dataOrientationZFieldID;
    jfieldID dataOrientationWFieldID;
    jfieldID dataLinearVelocityXFieldID;
    jfieldID dataLinearVelocityYFieldID;
    jfieldID dataLinearVelocityZFieldID;
    jfieldID dataAngularVelocityXFieldID;
    jfieldID dataAngularVelocityYFieldID;
    jfieldID dataAngularVelocityZFieldID;
    jfieldID dataLinearAccelerationXFieldID;
    jfieldID dataLinearAccelerationYFieldID;
    jfieldID dataLinearAccelerationZFieldID;
    jfieldID dataAngularAccelerationXFieldID;
    jfieldID dataAngularAccelerationYFieldID;
    jfieldID dataAngularAccelerationZFieldID;
    jfieldID dataMountedFieldID;
    jfieldID dataDockedFieldID;
    ovrMobile* ovr;
    long long frameIndex;
    ANativeWindow* nativeWindow;
    ovrMessageQueue messageQueue;
    bool destroyed;
    bool resumed;
    bool started;
    ovrEgl egl;
    ovrJava java;

    void handleVRModeChanges()
    {
        if (nativeWindow != NULL && egl.MainSurface == EGL_NO_SURFACE )
        {
            ovrEgl_CreateSurface(&egl, nativeWindow);
        }

        if (resumed != false && nativeWindow != NULL )
        {
            if ( ovr == NULL )
            {
                ovrModeParms parms = vrapi_DefaultModeParms( &java );

#if EXPLICIT_GL_OBJECTS == 1
                parms.Display = (size_t)egl.Display;
                parms.WindowSurface = (size_t)egl.MainSurface;
                parms.ShareContext = (size_t)egl.Context;
#else
                LOG_MESSAGE( "        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) );
#endif

                ovr = vrapi_EnterVrMode( &parms );

                LOG_MESSAGE( "        vrapi_EnterVrMode()" );

#if EXPLICIT_GL_OBJECTS == 0
                LOG_MESSAGE( "        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) );
#endif
                if (!started)
                {
                    started = true;
                    const ovrHeadModelParms headModelParms = vrapi_DefaultHeadModelParms();

                    float eyeX = vrapi_GetSystemPropertyFloat(&java, VRAPI_SYS_PROP_SUGGESTED_EYE_FOV_DEGREES_X);
                    float eyeY = vrapi_GetSystemPropertyFloat(&java, VRAPI_SYS_PROP_SUGGESTED_EYE_FOV_DEGREES_Y);
                    float interpupillaryDistance = headModelParms.InterpupillaryDistance;

                    LOG_MESSAGE("JUDAX: mounted = %d", vrapi_GetSystemStatusInt(&java, VRAPI_SYS_STATUS_MOUNTED));
                    LOG_MESSAGE("JUDAX: docked = %d", vrapi_GetSystemStatusInt(&java, VRAPI_SYS_STATUS_DOCKED));

                    java.Env->CallVoidMethod(oculusMobileSDKHeadTrackingJObject, headTrackingStartedMethodID, eyeX, eyeY, interpupillaryDistance);
                }
            }
        }
        else
        {
            if ( ovr != NULL )
            {
                LOG_MESSAGE( "        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) );

                vrapi_LeaveVrMode( ovr );
                ovr = NULL;

                LOG_MESSAGE( "        vrapi_LeaveVrMode()" );
                LOG_MESSAGE( "        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) );
            }
        }

        if ( nativeWindow == NULL && egl.MainSurface != EGL_NO_SURFACE )
        {
            ovrEgl_DestroySurface( &egl );
        }
    }

    void threadFunction()
    {
        java.Vm = javaVM;
        java.Vm->AttachCurrentThread(&java.Env, NULL);
        java.ActivityObject = activityJObject;

        SystemActivities_Init( &java );

        const ovrInitParms initParms = vrapi_DefaultInitParms(&java);
        int32_t initResult = vrapi_Initialize(&initParms);
        if (initResult != VRAPI_INITIALIZE_SUCCESS)
        {
            char const * msg = initResult == VRAPI_INITIALIZE_PERMISSIONS_ERROR ?
            "Thread priority security exception. Make sure the APK is signed." :
            "VrApi initialization error.";

            java.Env->CallVoidMethod(oculusMobileSDKHeadTrackingJObject, headTrackingErrorMethodID, java.Env->NewStringUTF(msg));

            SystemActivities_DisplayError(&java, SYSTEM_ACTIVITIES_FATAL_ERROR_OSIG, __FILE__, msg);
        }

        ovrEgl_CreateContext( &egl, NULL );

        ovrPerformanceParms perfParms = vrapi_DefaultPerformanceParms();
        perfParms.CpuLevel = CPU_LEVEL;
        perfParms.GpuLevel = GPU_LEVEL;
        perfParms.MainThreadTid = gettid();

        LOG_MESSAGE("OculusMobileSDKHeadTracking thread running...");

        frameIndex = 0;

        const ovrHeadModelParms headModelParms = vrapi_DefaultHeadModelParms();

        for (destroyed = false; !destroyed ;)
        {
            for ( ; ; )
            {
                ovrMessage message;
                const bool waitForMessages = !destroyed;
                if (!ovrMessageQueue_GetNextMessage(&messageQueue, &message, waitForMessages))
                {
                    break;
                }

                LOG_MESSAGE("Message received. message.Id = %d", message.Id);

                switch (message.Id)
                {
                    case MESSAGE_START:
                        break;
                    case MESSAGE_RESUME:
                        resumed = true;
                        break;
                    case MESSAGE_PAUSE:
                        resumed = false;
                        break;
                    case MESSAGE_STOP:
                        destroyed = true;
                        break;
                    case MESSAGE_SURFACE_CREATED:
                        break;
                    case MESSAGE_SURFACE_DESTROYED:
                        break;
                }

                handleVRModeChanges();
            }
        }

        if (ovr != NULL)
        {
            vrapi_LeaveVrMode(ovr);
            ovr = NULL;
        }

        ovrEgl_DestroyContext( &egl );

        vrapi_Shutdown();

        SystemActivities_Shutdown( &java );

        java.Vm->DetachCurrentThread();

        started = false;

        LOG_MESSAGE("OculusMobileSDKHeadTracking thread stopped!");
    }

    static void* threadFunctionStatic(void* data)
    {
        OculusMobileSDKHeadTracking* _this = (OculusMobileSDKHeadTracking*)data;
        _this->threadFunction();
        return NULL;
    }

public:
    OculusMobileSDKHeadTracking(): javaVM(NULL), resumed(false), destroyed(false), started(false), ovr(NULL), frameIndex(0), nativeWindow(NULL)
    {
        ovrEgl_Clear(&egl);
    }

    void start(JNIEnv* jniEnv, jobject activityJObject, jobject oculusMobileSDKHeadTrackingJObject, jobject dataJObject)
    {
        jniEnv->GetJavaVM(&javaVM);
        // Keep some references alive
        this->activityJObject = jniEnv->NewGlobalRef(activityJObject);
        this->oculusMobileSDKHeadTrackingJObject = jniEnv->NewGlobalRef(oculusMobileSDKHeadTrackingJObject);
        this->dataJObject = jniEnv->NewGlobalRef(dataJObject);

        // Cache some JNI methods and classes
        oculusMobileSDKHeadTrackingJClass = jniEnv->GetObjectClass(oculusMobileSDKHeadTrackingJObject);
        headTrackingStartedMethodID = jniEnv->GetMethodID(oculusMobileSDKHeadTrackingJClass, "headTrackingStartedFromNative", "(FFF)V");
        headTrackingErrorMethodID = jniEnv->GetMethodID(oculusMobileSDKHeadTrackingJClass, "headTrackingErrorFromNative", "(Ljava/lang/String;)V");

        // Cache OculudMobileSDKHeadTrackingData properties
        dataJClass = jniEnv->GetObjectClass(dataJObject);
        dataTimeStampFieldID = jniEnv->GetFieldID(dataJClass, "timeStamp", "D");
        dataOrientationXFieldID = jniEnv->GetFieldID(dataJClass, "orientationX", "F");
        dataOrientationYFieldID = jniEnv->GetFieldID(dataJClass, "orientationY", "F");
        dataOrientationZFieldID = jniEnv->GetFieldID(dataJClass, "orientationZ", "F");
        dataOrientationWFieldID = jniEnv->GetFieldID(dataJClass, "orientationW", "F");
        dataLinearVelocityXFieldID = jniEnv->GetFieldID(dataJClass, "linearVelocityX", "F");
        dataLinearVelocityYFieldID = jniEnv->GetFieldID(dataJClass, "linearVelocityY", "F");
        dataLinearVelocityZFieldID = jniEnv->GetFieldID(dataJClass, "linearVelocityZ", "F");
        dataAngularVelocityXFieldID = jniEnv->GetFieldID(dataJClass, "angularVelocityX", "F");
        dataAngularVelocityYFieldID = jniEnv->GetFieldID(dataJClass, "angularVelocityY", "F");
        dataAngularVelocityZFieldID = jniEnv->GetFieldID(dataJClass, "angularVelocityZ", "F");
        dataLinearAccelerationXFieldID = jniEnv->GetFieldID(dataJClass, "linearAccelerationX", "F");
        dataLinearAccelerationYFieldID = jniEnv->GetFieldID(dataJClass, "linearAccelerationY", "F");
        dataLinearAccelerationZFieldID = jniEnv->GetFieldID(dataJClass, "linearAccelerationZ", "F");
        dataAngularAccelerationXFieldID = jniEnv->GetFieldID(dataJClass, "angularAccelerationX", "F");
        dataAngularAccelerationYFieldID = jniEnv->GetFieldID(dataJClass, "angularAccelerationY", "F");
        dataAngularAccelerationZFieldID = jniEnv->GetFieldID(dataJClass, "angularAccelerationZ", "F");
        dataMountedFieldID = jniEnv->GetFieldID(dataJClass, "mounted", "I");
        dataDockedFieldID = jniEnv->GetFieldID(dataJClass, "docked", "I");

        ovrMessageQueue_Create(&messageQueue);

        const int createErr = pthread_create( &thread, NULL, threadFunctionStatic, this);
        if ( createErr != 0 )
        {
            jniEnv->CallVoidMethod(oculusMobileSDKHeadTrackingJObject, headTrackingErrorMethodID, java.Env->NewStringUTF("Could not create native head tracking thread."));
            LOG_ERROR("pthread_create returned %i", createErr);
        }

        // Post MESSAGE_START
        ovrMessageQueue_Enable(&messageQueue, true);
        ovrMessage message;
        ovrMessage_Init(&message, MESSAGE_START, MQ_WAIT_PROCESSED);
        ovrMessageQueue_PostMessage(&messageQueue, &message);
    }

    void resume()
    {
        // Post MESSAGE_RESUME
        ovrMessage message;
        ovrMessage_Init(&message, MESSAGE_RESUME, MQ_WAIT_PROCESSED);
        ovrMessageQueue_PostMessage(&messageQueue, &message);
    }

    void pause()
    {
        // Post MESSAGE_PAUSE
        ovrMessage message;
        ovrMessage_Init( &message, MESSAGE_PAUSE, MQ_WAIT_PROCESSED );
        ovrMessageQueue_PostMessage( &messageQueue, &message );
    }

    void stop(JNIEnv* jniEnv)
    {
        // Post MESSAGE_STOP
        ovrMessage message;
        ovrMessage_Init(&message, MESSAGE_STOP, MQ_WAIT_PROCESSED);
        ovrMessageQueue_PostMessage(&messageQueue, &message);
        ovrMessageQueue_Enable(&messageQueue, false);

        // Wait for the thread and free resources
        pthread_join(thread, NULL);

        // Free some references
        jniEnv->DeleteGlobalRef(activityJObject);
        jniEnv->DeleteGlobalRef(oculusMobileSDKHeadTrackingJObject);
        jniEnv->DeleteGlobalRef(dataJObject);

        ovrMessageQueue_Destroy(&messageQueue);
    }

    inline void setNativeWindow(ANativeWindow* nativeWindow)
    {
        // Is the new nativeWindow is different from the current one?
        if ( this->nativeWindow != nativeWindow )
        {
            if (this->nativeWindow != NULL)
            {
                // There is a current native window so post MESSAGE_ON_SURFACE_DESTROYED
                ovrMessage message;
                ovrMessage_Init( &message, MESSAGE_SURFACE_DESTROYED, MQ_WAIT_PROCESSED );
                ovrMessageQueue_PostMessage(&messageQueue, &message);
                ANativeWindow_release(this->nativeWindow);
                this->nativeWindow = NULL;
            }
            if (nativeWindow != NULL)
            {
                // A new native window has been provided so post MESSAGE_ON_SURFACE_CREATED
                this->nativeWindow = nativeWindow;
                ovrMessage message;
                ovrMessage_Init(&message, MESSAGE_SURFACE_CREATED, MQ_WAIT_PROCESSED);
                ovrMessageQueue_PostMessage(&messageQueue, &message);
            }
        }
        else if ( nativeWindow != NULL )
        {
            // Both the curent native window and the new one are the same (and not NULL). Release the new one (acquired outside of this call)
            ANativeWindow_release(nativeWindow);
        }
    }

    void getData(JNIEnv* jniEnv)
    {
        frameIndex++;
        const ovrHeadModelParms headModelParms = vrapi_DefaultHeadModelParms();
        const double predictedDisplayTime = vrapi_GetPredictedDisplayTime(ovr, frameIndex);
        const ovrTracking baseTracking = vrapi_GetPredictedTracking(ovr, predictedDisplayTime);
        const ovrTracking tracking = vrapi_ApplyHeadModel(&headModelParms, &baseTracking);

        // ==============================================
        // THIS CODE IS JUST FOR REFERENCE PURPOSES! BEGIN
        //            // Position and orientation together.
        //            typedef struct ovrPosef_
        //            {
        //                ovrQuatf	Orientation;
        //                ovrVector3f	Position;
        //            } ovrPosef;
        //            typedef struct ovrRigidBodyPosef_
        //            {
        //                ovrPosef	Pose;
        //                ovrVector3f	AngularVelocity;
        //                ovrVector3f	LinearVelocity;
        //                ovrVector3f	AngularAcceleration;
        //                ovrVector3f	LinearAcceleration;
        //                double		TimeInSeconds;			// Absolute time of this pose.
        //                double		PredictionInSeconds;	// Seconds this pose was predicted ahead.
        //            } ovrRigidBodyPosef;
        //
        //            // Bit flags describing the current status of sensor tracking.
        //            typedef enum
        //            {
        //                VRAPI_TRACKING_STATUS_ORIENTATION_TRACKED	= 0x0001,	// Orientation is currently tracked.
        //                VRAPI_TRACKING_STATUS_POSITION_TRACKED		= 0x0002,	// Position is currently tracked.
        //                VRAPI_TRACKING_STATUS_HMD_CONNECTED			= 0x0080	// HMD is available & connected.
        //            } ovrTrackingStatus;
        //
        //            // Tracking state at a given absolute time.
        //            typedef struct ovrTracking_
        //            {
        //                // Sensor status described by ovrTrackingStatus flags.
        //                unsigned int		Status;
        //                // Predicted head configuration at the requested absolute time.
        //                // The pose describes the head orientation and center eye position.
        //                ovrRigidBodyPosef	HeadPose;
        //            } ovrTracking;
        // THIS CODE IS JUST FOR REFERENCE PURPOSES! END
        // ==============================================

        jniEnv->SetDoubleField(dataJObject, dataTimeStampFieldID, tracking.HeadPose.TimeInSeconds);
        jniEnv->SetFloatField(dataJObject, dataOrientationXFieldID, tracking.HeadPose.Pose.Orientation.x);
        jniEnv->SetFloatField(dataJObject, dataOrientationYFieldID, tracking.HeadPose.Pose.Orientation.y);
        jniEnv->SetFloatField(dataJObject, dataOrientationZFieldID, tracking.HeadPose.Pose.Orientation.z);
        jniEnv->SetFloatField(dataJObject, dataOrientationWFieldID, tracking.HeadPose.Pose.Orientation.w);
        jniEnv->SetFloatField(dataJObject, dataLinearVelocityXFieldID, tracking.HeadPose.LinearVelocity.x);
        jniEnv->SetFloatField(dataJObject, dataLinearVelocityYFieldID, tracking.HeadPose.LinearVelocity.y);
        jniEnv->SetFloatField(dataJObject, dataLinearVelocityZFieldID, tracking.HeadPose.LinearVelocity.z);
        jniEnv->SetFloatField(dataJObject, dataLinearAccelerationXFieldID, tracking.HeadPose.LinearAcceleration.x);
        jniEnv->SetFloatField(dataJObject, dataLinearAccelerationYFieldID, tracking.HeadPose.LinearAcceleration.y);
        jniEnv->SetFloatField(dataJObject, dataLinearAccelerationZFieldID, tracking.HeadPose.LinearAcceleration.z);
        jniEnv->SetFloatField(dataJObject, dataAngularVelocityXFieldID, tracking.HeadPose.AngularVelocity.x);
        jniEnv->SetFloatField(dataJObject, dataAngularVelocityYFieldID, tracking.HeadPose.AngularVelocity.y);
        jniEnv->SetFloatField(dataJObject, dataAngularVelocityZFieldID, tracking.HeadPose.AngularVelocity.z);
        jniEnv->SetFloatField(dataJObject, dataAngularAccelerationXFieldID, tracking.HeadPose.AngularAcceleration.x);
        jniEnv->SetFloatField(dataJObject, dataAngularAccelerationYFieldID, tracking.HeadPose.AngularAcceleration.y);
        jniEnv->SetFloatField(dataJObject, dataAngularAccelerationZFieldID, tracking.HeadPose.AngularAcceleration.z);
        jniEnv->SetIntField(dataJObject, dataMountedFieldID, vrapi_GetSystemStatusInt(&java, VRAPI_SYS_STATUS_MOUNTED));
        jniEnv->SetIntField(dataJObject, dataDockedFieldID, vrapi_GetSystemStatusInt(&java, VRAPI_SYS_STATUS_DOCKED));
    }
};

extern "C"
{
    // Activity life cycle
    JNIEXPORT jlong JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeStart(JNIEnv* jniEnv, jobject obj, jobject activityJObject, jobject oculusMobileSDKHeadTrackingJObject, jobject dataJObject)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = new OculusMobileSDKHeadTracking();
        oculusMobileSDKHeadTracking->start(jniEnv, activityJObject, oculusMobileSDKHeadTrackingJObject, dataJObject);
        return (jlong)((size_t)oculusMobileSDKHeadTracking);

        return 0;
    }

    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeResume(JNIEnv* jniEnv, jobject obj, jlong objectPtr)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);

        oculusMobileSDKHeadTracking->resume();
    }

    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativePause(JNIEnv* jniEnv, jobject obj, jlong objectPtr)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);

        oculusMobileSDKHeadTracking->pause();
    }

    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeStop(JNIEnv* jniEnv, jobject obj, jlong objectPtr)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);
        oculusMobileSDKHeadTracking->stop(jniEnv);
        delete oculusMobileSDKHeadTracking;
        oculusMobileSDKHeadTracking = 0;
    }

    // Surface life cycle
    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeSurfaceCreated(JNIEnv* jniEnv, jobject obj, jlong objectPtr, jobject surfaceJObject)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);

        ANativeWindow * newNativeWindow = ANativeWindow_fromSurface(jniEnv, surfaceJObject);
        if (ANativeWindow_getWidth(newNativeWindow) < ANativeWindow_getHeight(newNativeWindow))
        {
            // An app that is relaunched after pressing the home button gets an initial surface with
            // the wrong orientation even though android:screenOrientation="landscape" is set in the
            // manifest. The choreographer callback will also never be called for this surface because
            // the surface is immediately replaced with a new surface with the correct orientation.
            LOG_ERROR("Surface not in landscape mode!");
        }

        oculusMobileSDKHeadTracking->setNativeWindow(newNativeWindow);
    }

    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeSurfaceChanged(JNIEnv* jniEnv, jobject obj, jlong objectPtr, jobject surfaceJObject)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);

        ANativeWindow* newNativeWindow = ANativeWindow_fromSurface(jniEnv, surfaceJObject);
        if (ANativeWindow_getWidth(newNativeWindow) < ANativeWindow_getHeight(newNativeWindow))
        {
            // An app that is relaunched after pressing the home button gets an initial surface with
            // the wrong orientation even though android:screenOrientation="landscape" is set in the
            // manifest. The choreographer callback will also never be called for this surface because
            // the surface is immediately replaced with a new surface with the correct orientation.
            LOG_ERROR("Surface not in landscape mode!");
        }

        oculusMobileSDKHeadTracking->setNativeWindow(newNativeWindow);
    }

    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeSurfaceDestroyed(JNIEnv* jniEnv, jobject obj, jlong objectPtr)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);

        oculusMobileSDKHeadTracking->setNativeWindow(NULL);
    }

    JNIEXPORT void JNICALL Java_com_judax_oculusmobilesdkheadtracking_OculusMobileSDKHeadTracking_nativeGetData(JNIEnv* jniEnv, jobject obj, jlong objectPtr)
    {
        OculusMobileSDKHeadTracking* oculusMobileSDKHeadTracking = (OculusMobileSDKHeadTracking*)((size_t)objectPtr);

        oculusMobileSDKHeadTracking->getData(jniEnv);
    }

}


text:
EPM.Tutorial = function (game) {

	this.music = null;
	this.playButton = null;

};

EPM.Tutorial.prototype = {

	create: function () {

		this.stage.backgroundColor = 0xEEEEEE;

		this.add_aimated_tutorial_text("WELCOME TO EUROPEAN PARLIAMENT MADNESS 2 !",100,100,500)

		this.add_aimated_tutorial_text("- Turn two blue cards by clicking on them \n\n- If they look the same you get +1 hitpoints and +10 of score\n\n- If they don't you loose 1 hitpoints\n\n- The game ends when you have no hit points\n\n- That being said , try to make the best score\n\n- Memorizing the parliament members' faces helps !",100,150,500)

		this.playButton = new LabelButton(this,360, 550,150,50,10, 'PLAY !',{
			font: "30px Courier",
			fill: "#0000FF",
			align: "left"
		},this.startGame,this);

		this.muteButton = new MuteButton(this,750, 10);

		this.backButton = new SmallButton(this,10, 10,50, 'BACK',{
			font: "14px Courier",
			fill: "#0000FF",
			align: "left"
		},this.backToMenu,this);

		slideFadeIn(this, this.playButton,'right',200);

	},

	add_aimated_tutorial_text:function(text,x,y,delay){

		var tutorial_text_1 = this.add.text(x,y, text, {
			font: "20px Courier",
			fill: "#000000",
			align: "left"
		});

		slideFadeIn(this, tutorial_text_1,'left',200);

	},

	update: function () {

		//	Do some nice funky main menu effect here

	},

    backToMenu: function (pointer) {

		this.playButton.destroy();
		this.muteButton.destroy();
		this.backButton.destroy();

        this.state.start('MainMenu');

    },

	startGame: function (pointer) {

		//	Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing)
		//this.music.stop();

		//	And start the actual game
		this.state.start('Game');

	}

};


text:
.. _dojo/removeClass:

================
dojo.removeClass
================

.. contents ::
   :depth: 2

*Deprecated*, see :ref:`dojo/dom-class::remove() <dojo/dom-class#remove>` instead.


text:
layout:     post
title:      To view this page, you need to login to the proxy server.
date:       2015-12-15
summary:    Stuck behind a NTLM based proxy server in a windows only corporate environment on a MacBook? Here's how you can make the best out of a bad situation.
categories: xamarin corporate soe ntlm proxy internet cntlm
---

If you have ever been in the unfortunate situation whereby you are using a Macbook/OSX device within a Windows centric environment and are forced to use a proxy server then the words above and the image below will potentially send shivers down your spine.

![To view this page, you need to login to the proxy server.](/images/osx-ntlm-proxy-auth.png)

What's the big deal you ask? Surely it's just a matter of entering in your username (```domain\username```) and password. Two minutes later (if your lucky) that damn prompt will come back regardless if you selected "Remember this password in my Keychain" and clicking "Cancel" is about the worst possible thing you can do.....

![To view this page, you need to login to the proxy server.](/images/osx-ntlm-proxy-auth-loop.png)

Luckily, thanks to the magic powers of open-source software there's a solution!

    # brew install cntlm

Next step is to generate a encrypted `NTLMv2` hash which will be used instead storing your password in plain text.

    # cntlm -H -c /usr/local/etc/cntlm.conf

    Password:
    PassLM          4CnopeEACnope43F5nope60C
    PassNT          4CnopeEACnope43F5nope60C
    PassNTLMv2      4CnopeEACnope43F5nope60C

Edit the configuration file at ```/usr/local/etc/cntlm.conf```:

    Domain          $domainname
    Username        $username

    PassNTLMv2      $passNTLMv2
    Auth            NTLMv2

    # upstream proxy server hostname and port (hostname:port)
    Proxy           proxy.example.com:8080

    # destinations which are not routed to the upstream proxy server.
    NoProxy         localhost, 127.0.0.*, 10.*, 192.168.*

    # which TCP port to bind on
    Listen          3128

    # bind to all network interfaces (yes) or bind to loopback (no)
    Gateway         yes

    # ACL of addresses allowed to connect through the proxy
    Allow           127.0.0.1

Replace `$username`, `$passNTLMv2`,`$domain` and configure the `NoProxy` and `Proxy` stanza's as appropriate.

Configure `cntlm` to launch automatically by creating `~/Library/LaunchAgents/cntlm.daemon.plist` with the following contents:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <key>Label</key>
      <string>cntlm.daemon</string>
      <key>ProgramArguments</key>
      <array>
          <string>/usr/local/bin/cntlm</string>
      </array>
      <key>KeepAlive</key>
      <false/>
      <key>RunAtLoad</key>
      <true/>
      <key>StandardErrorPath</key>
      <string>/dev/null</string>
      <key>StandardOutPath</key>
      <string>/dev/null</string>
    </dict>
    </plist>

Start the daemon:

    # cntlm

Configure OSX to use the proxy server that is now running at ```localhost:3128```

In 31 days or whenever you windows password chasnges/expires you will need to re-run the `cntlm -H` command, update the configuration file with the new `PassNTLMv2` hash and then restart the daemon.


text:
package org.sagebionetworks.repo.model.dbo.auth;

import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.*;

import java.util.List;
import java.util.UUID;

import org.sagebionetworks.ids.IdGenerator;
import org.sagebionetworks.ids.IdType;
import org.sagebionetworks.repo.transactions.WriteTransactionReadCommitted;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class DBOAuthenticationReceiptDAOImpl implements AuthenticationReceiptDAO{
	public static final Long EXPIRATION_PERIOD = 3*24*60*60*1000L;

	private static final String SQL_SELECT = "SELECT "+COL_AUTHENTICATION_RECEIPT_ID
			+" FROM "+TABLE_AUTHENTICATION_RECEIPT
			+" WHERE "+COL_AUTHENTICATION_RECEIPT_USER_ID+" = ?"
			+" AND "+COL_AUTHENTICATION_RECEIPT_RECEIPT+" = ?";
	private static final String SQL_INSERT = "INSERT INTO "+TABLE_AUTHENTICATION_RECEIPT+"( "
			+COL_AUTHENTICATION_RECEIPT_ID+", "
			+COL_AUTHENTICATION_RECEIPT_USER_ID+", "
			+COL_AUTHENTICATION_RECEIPT_RECEIPT+", "
			+COL_AUTHENTICATION_RECEIPT_EXPIRATION+") VALUES (?,?,?,?)";
	private static final String SQL_UPDATE = "UPDATE "+TABLE_AUTHENTICATION_RECEIPT
			+" SET "+COL_AUTHENTICATION_RECEIPT_RECEIPT+" = ?, "
			+COL_AUTHENTICATION_RECEIPT_EXPIRATION+" = ?"
			+" WHERE "+COL_AUTHENTICATION_RECEIPT_USER_ID+" = ?"
			+" AND "+COL_AUTHENTICATION_RECEIPT_RECEIPT+" = ?";
	private static final String SQL_COUNT = "SELECT COUNT(*)"
			+" FROM "+TABLE_AUTHENTICATION_RECEIPT
			+" WHERE "+COL_AUTHENTICATION_RECEIPT_USER_ID+" = ?";
	private static final String SQL_DELETE_EXPIRED = "DELETE"
			+" FROM "+TABLE_AUTHENTICATION_RECEIPT
			+" WHERE "+COL_AUTHENTICATION_RECEIPT_USER_ID+" = ?"
			+" AND "+COL_AUTHENTICATION_RECEIPT_EXPIRATION+" < ?";
	private static final String SQL_TRUNCATE = "TRUNCATE "+TABLE_AUTHENTICATION_RECEIPT;

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private IdGenerator idGenerator;

	@Override
	public boolean isValidReceipt(long userId, String receipt) {
		List<String> results = jdbcTemplate.queryForList(SQL_SELECT, String.class, userId, receipt);
		return results.size() == 1;
	}

	@WriteTransactionReadCommitted
	@Override
	public String createNewReceipt(long userId) {
		Long id = idGenerator.generateNewId(IdType.AUTHENTICATION_RECEIPT_ID);
		String receipt = UUID.randomUUID().toString();
		jdbcTemplate.update(SQL_INSERT, id, userId, receipt, System.currentTimeMillis()+EXPIRATION_PERIOD);
		return receipt;
	}

	@WriteTransactionReadCommitted
	@Override
	public String replaceReceipt(long userId, String oldReceipt) {
		String receipt = UUID.randomUUID().toString();
		jdbcTemplate.update(SQL_UPDATE, receipt, System.currentTimeMillis()+EXPIRATION_PERIOD, userId, oldReceipt);
		return receipt;
	}

	@Override
	public long countReceipts(long userId) {
		return jdbcTemplate.queryForObject(SQL_COUNT, Long.class, userId);
	}

	@WriteTransactionReadCommitted
	@Override
	public void deleteExpiredReceipts(long userId, long expirationTime) {
		jdbcTemplate.update(SQL_DELETE_EXPIRED, userId, expirationTime);
	}

	@WriteTransactionReadCommitted
	@Override
	public void truncateAll() {
		jdbcTemplate.update(SQL_TRUNCATE);
	}
}


text:
#pragma once

#include <zk/config.hpp>

#ifdef GTEST_API_
#   error "GTest was included externally -- you MUST include <zk/tests/test.hpp> first"
#endif

// Before including GTest, tell it not to define the various generically-named macros (which clash with other common
// names).
#define GTEST_DONT_DEFINE_ASSERT_EQ 1
#define GTEST_DONT_DEFINE_ASSERT_NE 1
#define GTEST_DONT_DEFINE_ASSERT_LE 1
#define GTEST_DONT_DEFINE_ASSERT_LT 1
#define GTEST_DONT_DEFINE_ASSERT_GE 1
#define GTEST_DONT_DEFINE_ASSERT_GT 1
#define GTEST_DONT_DEFINE_TEST      1
#define GTEST_DONT_DEFINE_FAIL      1
#define GTEST_DONT_DEFINE_SUCCEED   1

#include <gtest/gtest.h>

// Maybe some day this will be defined
#ifndef GTEST_TEST_F
#   define GTEST_TEST_F TEST_F
#endif

namespace zk::test
{

/** \def CHECK
 *  Check a condition and abort the test in failure if it does not hold. When performing binary comparisons, prefer to
 *  use the check macros which accept two arguments (\c CHECK_EQ, \c CHECK_LT, etc), as these will print out the values
 *  in failure cases.
 *
 *  \example
 *  \code
 *  CHECK(something) << "Something isn't right!";
 *  \endcode
**/
#define CHECK(cond)       GTEST_TEST_BOOLEAN_(cond,     #cond, false, true,  GTEST_FATAL_FAILURE_)
#define CHECK_TRUE(cond)  GTEST_TEST_BOOLEAN_(!!(cond), #cond, false, true,  GTEST_FATAL_FAILURE_)
#define CHECK_FALSE(cond) GTEST_TEST_BOOLEAN_(!(cond),  #cond, true,  false, GTEST_FATAL_FAILURE_)
#define CHECK_EQ          GTEST_ASSERT_EQ
#define CHECK_NE          GTEST_ASSERT_NE
#define CHECK_LT          GTEST_ASSERT_LT
#define CHECK_LE          GTEST_ASSERT_LE
#define CHECK_GT          GTEST_ASSERT_GT
#define CHECK_GE          GTEST_ASSERT_GE
#define CHECK_SUCCESS     GTEST_SUCCEED
#define CHECK_FAIL        GTEST_FAIL

using test_fixture = ::testing::Test;

namespace detail
{

template <typename TException>
struct check_throws_info
{
    ptr<const char> filename;
    std::size_t     line_no;

    explicit check_throws_info(ptr<const char> filename, std::size_t line_no) :
            filename(filename),
            line_no(line_no)
    { }

    friend std::ostream& operator<<(std::ostream& os, const check_throws_info& info)
    {
        return os << info.filename << ':' << info.line_no;
    }
};

template <typename TException, typename FAction>
void operator+(const check_throws_info<TException>& info, FAction&& action)
{
    try
    {
        std::forward<FAction>(action)();
        CHECK_FAIL() << "At " << info << ": Action was supposed to throw, but it did not"; // LCOV_EXCL_LINE
    }
    catch (const TException&)
    {
        CHECK_SUCCESS() << "Successfully threw expected error";
    }
}

/** \def CHECK_THROWS
 *  Ensure that a block of code throws an exception of type \a ex.
 *
 *  \code
 *  CHECK_THROWS(std::logic_error)
 *  {
 *      throw std::logic_error("Some issue");
 *  }; // <- note the ';'
 *  \endcode
**/
#define CHECK_THROWS(ex)                                                                                \
    ::zk::test::detail::check_throws_info<ex>(__FILE__, __LINE__) + [&] ()

}

}


text:
package io.vertx.example.core.net.stream;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;
import io.vertx.core.streams.ReadStream;
import io.vertx.core.streams.WriteStream;

import java.util.Objects;

/*
 *  @author Emad Alblueshi
 */

public class BatchStream implements ReadStream<Batch>, WriteStream<Batch> {

  private final RecordParser recordParser;
  private final WriteStream<Buffer> writeStream;
  private int size = -1;
  private Handler<Throwable> exceptionHandler;

  public BatchStream(ReadStream<Buffer> rs, WriteStream<Buffer> ws) {
    Objects.requireNonNull(rs, "ReadStream");
    Objects.requireNonNull(ws, "WriteStream");
    recordParser = RecordParser.newFixed(4, rs);
    writeStream = ws;
    // Propagate exceptions to the current stream
    recordParser.exceptionHandler(throwable -> {
      if (exceptionHandler != null) {
        exceptionHandler.handle(throwable);
      }
    });
    writeStream.exceptionHandler(throwable -> {
      if (exceptionHandler != null) {
        exceptionHandler.handle(throwable);
      }
    });
  }

  @Override
  public BatchStream exceptionHandler(Handler<Throwable> handler) {
    exceptionHandler = handler;
    return this;
  }

  @Override
  public Future<Void> write(Batch batch) {
    if (batch == null) {
      return Future.failedFuture(new NullPointerException());
    }
    Buffer protocol = Buffer.buffer();
    protocol.appendInt(0);
    protocol.appendByte((byte) batch.getType());
    protocol.appendBuffer(batch.getRaw());
    protocol.setInt(0, protocol.length() - 4);
    return writeStream.write(protocol);
  }

  @Override
  public void write(Batch batch, Handler<AsyncResult<Void>> handler) {
    if (batch == null) {
      NullPointerException err = new NullPointerException();
      if (exceptionHandler != null) {
        exceptionHandler.handle(err);
      }
      if (handler != null) {
        handler.handle(Future.failedFuture(err));
      }
    } else {
      Buffer protocol = Buffer.buffer();
      protocol.appendInt(0);
      protocol.appendByte((byte) batch.getType());
      protocol.appendBuffer(batch.getRaw());
      protocol.setInt(0, protocol.length() - 4);
      writeStream.write(protocol, handler);
    }
  }

  @Override
  public Future<Void> end() {
    return writeStream.end();
  }

  @Override
  public void end(Handler<AsyncResult<Void>> handler) {
    writeStream.end(handler);
  }

  @Override
  public BatchStream setWriteQueueMaxSize(int maxSize) {
    writeStream.setWriteQueueMaxSize(maxSize);
    return this;
  }

  @Override
  public boolean writeQueueFull() {
    return writeStream.writeQueueFull();
  }

  @Override
  public BatchStream drainHandler(Handler<Void> handler) {
    writeStream.drainHandler(handler);
    return this;
  }

  @Override
  public BatchStream handler(Handler<Batch> handler) {
    if (handler == null) {
      recordParser.handler(null);
      recordParser.exceptionHandler(null);
      recordParser.endHandler(null);
      return this;
    }
    recordParser.handler(buffer -> {
      try {
        // Message size mode
        if (size == -1) {
          size = buffer.getInt(0);
          recordParser.fixedSizeMode(size);
          // Message body mode
        } else {
          size = -1;
          recordParser.fixedSizeMode(4);
          // Batch message type
          final char type = (char) buffer.getByte(0);
          // Batch message data (Buffer)
          final Buffer payload = buffer.getBuffer(1, buffer.length());
          switch (type) {
            // JsonObject
            case 'O': {
              handler.handle(new Batch(payload.toJsonObject()));
              break;
            }
            // JsonArray
            case 'A': {
              handler.handle(new Batch(payload.toJsonArray()));
              break;
            }
            // Buffer
            case 'B': {
              handler.handle(new Batch(payload));
              break;
            } // Invalid
            default: {
              if (exceptionHandler != null) {
                exceptionHandler.handle(new IllegalStateException("Invalid message " + type));
              }
            }
          }
        }
      } catch (Throwable throwable) {
        if (exceptionHandler != null) {
          exceptionHandler.handle(throwable);
        }
      }
    });
    return this;
  }

  @Override
  public BatchStream pause() {
    recordParser.pause();
    return this;
  }

  @Override
  public BatchStream fetch(long l) {
    recordParser.fetch(l);
    return this;
  }

  @Override
  public BatchStream resume() {
    recordParser.resume();
    return this;
  }

  @Override
  public BatchStream endHandler(Handler<Void> endHandler) {
    recordParser.endHandler(endHandler);
    return this;
  }
}


text:
using Cosmos.Logging.Extensions.NodaTime.Core;
using NodaTime;
using NodaTime.Text;

namespace Cosmos.Logging.Extensions.NodaTime {
    internal sealed class LocalDateDestructureResolveRule : NodaTimeDestructureResolveRule<LocalDate> {
        protected override IPattern<LocalDate> Pattern => LocalDatePattern.Iso;

        public LocalDateDestructureResolveRule() : base(CreateIsoValidator(x => x.Calendar)) { }
    }
}


text:
//#define LOG_NDEBUG 0
#define LOG_TAG "MarlinDrmFactory"
#include <utils/Log.h>

#include <MarlinConstants.h>
#include "MarlinDrmFactory.h"
#include "MarlinCDMSingleton.h"
#include "MarlinDrmPlugin.h"
#include "utils/Errors.h"

namespace marlindrm {

bool MarlinDrmFactory::isCryptoSchemeSupported(const uint8_t uuid[16]) {
    bool ret = true;
    if (memcmp(uuid, marlincdm::MBB_UUID, 16)
            && memcmp(uuid, marlincdm::MS3_UUID, 16)){
        ALOGD("Do not supported UUID: %s", uuid);
        ret = false;
    }
    return ret;
}

bool MarlinDrmFactory::isContentTypeSupported(const String8 &mimeType) {
    return mimeType == "video/mp4";
}

status_t MarlinDrmFactory::createDrmPlugin(const uint8_t uuid[16],
                                           android::DrmPlugin** plugin) {
    if (!isCryptoSchemeSupported(uuid)) {
        ALOGD("Do not supported UUID: %s", uuid);
        *plugin = NULL;
        return android::BAD_VALUE;
    }

    *plugin = new MarlinDrmPlugin(getCDM(uuid));
    return android::OK;
}

} // namespace marlindrm


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

  Copyright 2003 - 2020 The eFaps Team

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

-->
<ui-form xmlns="http://www.efaps.org/xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>c323eded-3d30-44c5-8776-0162019d02d0</uuid>
    <file-application>eFapsApp-Print</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Print_PrintNodeWhoamiForm</name>
        <field name="response">
            <property name="ModeCreate">EDITABLE</property>
            <property name="ModeEdit">EDITABLE</property>
            <property name="ModeSearch">EDITABLE</property>
            <property name="UIType">SNIPPLET</property>
            <trigger program="org.efaps.esjp.print.printnode.PrintNodeService"
                method="whoami"
                name="Print_PrintNodeWhoamiForm.response.UI_FIELD_VALUE"
                event="UI_FIELD_VALUE">
            </trigger>
        </field>
    </definition>
</ui-form>


text:
const keystone = require('keystone');
// const moment = require('moment');
const RSVP = keystone.list('RSVP');
const Meetup = keystone.list('Meetup');

exports = module.exports = function (req, res) {
	const view = new keystone.View(req, res);
	const locals = res.locals;

	locals.section = 'meetups';
	locals.page.title = 'Meetups - UTA CSEC';

	view.query('upcomingMeetup', Meetup.model.findOne().where('state', 'active').sort('-startDate'), 'talks[who]');
	view.query('pastMeetups', Meetup.model.find().where('state', 'past').sort('-startDate'), 'talks[who]');

	view.on('render', function (next) {
		if (!req.user || !locals.upcomingMeetup) return next();

		RSVP.model.findOne()
			.where('who', req.user._id)
			.where('meetup', locals.upcomingMeetup)
			.exec(function (err, rsvp) {
				locals.rsvpStatus = { rsvped: !!rsvp, attending: !!(rsvp && rsvp.attending), };

				return next();
        });
	});

	view.render('site/meetups');
};


text:
require "hbc/source/path_base"

module Hbc
  module Source
    class PathSlashRequired < PathBase
      def self.me?(query)
        path = path_for_query(query)
        path.to_s.include?("/") && path.exist?
      end
    end
  end
end


text:
package org.apache.sis.internal.jaxb.metadata;

import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import org.opengis.metadata.Identifier;
import org.opengis.referencing.ReferenceIdentifier;
import org.apache.sis.metadata.iso.DefaultIdentifier;
import org.apache.sis.metadata.iso.ImmutableIdentifier;
import org.apache.sis.internal.jaxb.gco.PropertyType;

/**
 * JAXB adapter mapping implementing class to the GeoAPI interface. See
 * package documentation for more information about JAXB and interface.
 *
 * @author  Cédric Briançon (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @since   0.3
 * @version 0.7
 * @module
 */
public final class MD_Identifier extends PropertyType<MD_Identifier, Identifier> {
    /**
     * Empty constructor for JAXB only.
     */
    public MD_Identifier() {
    }

    /**
     * Returns the GeoAPI interface which is bound by this adapter.
     * This method is indirectly invoked by the private constructor
     * below, so it shall not depend on the state of this object.
     *
     * @return {@code Identifier.class}
     */
    @Override
    protected Class<Identifier> getBoundType() {
        return Identifier.class;
    }

    /**
     * Constructor for the {@link #wrap} method only.
     */
    private MD_Identifier(final Identifier metadata) {
        super(metadata);
    }

    /**
     * Invoked by {@link PropertyType} at marshalling time for wrapping the given metadata value
     * in a {@code <gmd:MD_Identifier>} XML element.
     *
     * @param  metadata The metadata element to marshall.
     * @return A {@code PropertyType} wrapping the given the metadata element.
     */
    @Override
    protected MD_Identifier wrap(final Identifier metadata) {
        return new MD_Identifier(metadata);
    }

    /**
     * Invoked by JAXB at marshalling time for getting the actual metadata to write
     * inside the {@code <gmd:MD_Identifier>} or {@code RS_Identifier} XML element.
     * This is the value or a copy of the value given in argument to the {@code wrap} method.
     *
     * @return The metadata to be marshalled.
     */
    @XmlElementRefs({
        @XmlElementRef(type = DefaultIdentifier.class),
        @XmlElementRef(type = ImmutableIdentifier.class)
    })
    @SuppressWarnings("deprecation")
    public Identifier getElement() {
        if (metadata instanceof ImmutableIdentifier) {
            return (ImmutableIdentifier) metadata;
        }
        if (metadata instanceof ReferenceIdentifier) {
            return ImmutableIdentifier.castOrCopy(metadata);
        }
        return DefaultIdentifier.castOrCopy(metadata);
    }

    /**
     * Invoked by JAXB at unmarshalling time for storing the result temporarily.
     *
     * @param metadata The unmarshalled metadata.
     */
    public void setElement(final Identifier metadata) {
        this.metadata = metadata;
    }
}


text:
workspace( "GUCEF_exe_FileReplacer" )

  platforms( { "ALL" } )

  location( "projects\premake5\targets" )

  --
  -- Includes for all modules in the solution:
  --

filter "ALL"
  include( "platform/gucefCORE" )
  include( "platform/gucefMT" )
  include( "tools/FileReplacer" )


text:
var titleToNumber = function(s) {
    var map = {},
    result = 0;
    for (var j = 0; j != 26; j++){
        map[String.fromCharCode(j + 65)] = j + 1;  // populate object keys with alphabet, and add number value
    }

    s.split('').forEach(function(currentVal,i,arr){
        result += map[currentVal] * (Math.pow(26,arr.length - 1 - i ) );
    })
    return result;
};


text:
Widgets are named with `Observable` prefix.
(e.g. `ListView` → `ObservableListView`)
You can handle these widgets with `Scrollable` interface.

| Widget | Since | Note |
|:------:|:-----:| ---- |
| ListView | v1.0.0 | - |
| ScrollView | v1.0.0 | - |
| WebView | v1.0.0 | - |
| RecyclerView | v1.1.0 | It's supported but RecyclerView provides scroll states and position with [OnScrollListener](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.OnScrollListener.html). You should use it if you don't have any reason. |
| GridView | v1.2.0 | - |


text:
var App = require('app');

require('controllers/wizard/step5_controller');

App.ManageJournalNodeWizardStep1Controller = Em.Controller.extend(App.BlueprintMixin, App.AssignMasterComponents, {

  name: "manageJournalNodeWizardStep1Controller",

  useServerValidation: false,

  mastersToShow: ['JOURNALNODE'],

  showInstalledMastersFirst: true,

  JOURNALNODES_COUNT_MINIMUM: 3, // TODO get this from stack

  nextButtonCheckTrigger: true,

  /**
   * On initial rendering, load equivalent number of existing JournalNodes to masterToShow
   * @param masterComponents
   */
  renderComponents: function (masterComponents) {
    //check if we are restoring components assignment by checking existing of JOURNALNODE component in array
    var restoringComponents = masterComponents.someProperty('component_name', 'JOURNALNODE');
    masterComponents = restoringComponents ? masterComponents : masterComponents.concat(this.generateJournalNodeComponents());
    this._super(masterComponents);
    this.updateJournalNodeInfo();
    this.showHideJournalNodesAddRemoveControl();
    this.toggleProperty('nextButtonCheckTrigger');
  },

  /**
   * Create JOURNALNODE components to add them to masters array
   */
  generateJournalNodeComponents: function () {
    var journalNodes = [];
    App.HostComponent.find().filterProperty('componentName', 'JOURNALNODE').forEach(function (jn) {
      var jnComponent = this.createComponentInstallationObject(Em.Object.create({
        serviceName: jn.get('service.serviceName'),
        componentName: jn.get('componentName')
      }), jn.get('hostName'));
      jnComponent.isInstalled = true;
      journalNodes.push(jnComponent);
    }, this);
    return journalNodes;
  },

  /**
   * Override of method from App.AssignMasterComponents
   * Added to satisfy the requirement that maximum number of new JournalNodes to be added
   * should be 1 less that total of the existing JournalNodes
   * @returns {number}
   */
  getMaxNumberOfMasters: function () {
    const defaultLimitation = this._super('JOURNALNODE'),
      installedJournalNodesCount = App.HostComponent.find().filterProperty('componentName', 'JOURNALNODE').length;
    return Math.min(defaultLimitation, installedJournalNodesCount * 2 - 1);
  },

  /**
   * Enable/Disable show/hide operation for each JournalNode
   */
  showHideJournalNodesAddRemoveControl: function () {
    var masterComponents = this.get('selectedServicesMasters');
    var jns = masterComponents.filterProperty('component_name', 'JOURNALNODE');
    var maxNumMasters = this.getMaxNumberOfMasters('JOURNALNODE');
    var showRemoveControl = jns.get('length') > this.get('JOURNALNODES_COUNT_MINIMUM');
    var showAddControl = jns.get('length') < maxNumMasters;
    jns.forEach(function (item) {
      item.set('showAddControl', false);
      item.set('showRemoveControl', showRemoveControl);
    });
    jns.set('lastObject.showAddControl', showAddControl);
  }.observes('hostNameCheckTrigger'),

  /**
   * Mark existing JournalNodes 'isInstalled' and 'showCurrentPrefix'
   */
  updateJournalNodeInfo: function () {
    var jns = this.get('selectedServicesMasters').filterProperty('component_name', 'JOURNALNODE');
    var hosts = App.HostComponent.find().filterProperty('componentName', 'JOURNALNODE').mapProperty('hostName');
    hosts.forEach(function (host) {
      var jn = jns.findProperty('selectedHost', host);
      if (jn) {
        jn.set('isInstalled', true);
        jn.set('showCurrentPrefix', true);
      }
    });
  }.observes('hostNameCheckTrigger'),

  /**
   * Callback after load controller data (hosts, host components etc)
   * @method loadStepCallback
   */
  loadStepCallback: function (components, self) {
    self.renderComponents(components);

    self.get('addableComponents').forEach(function (componentName) {
      self.updateComponent(componentName);
    }, self);
    self.set('isRecommendationsLoaded', true);
  },

  /**
   * Next button is disabled when there is any change to the original JournalNode hosts
   */
  nextButtonDisabled: function () {
    var currentHosts = this.get('selectedServicesMasters').filterProperty('component_name', 'JOURNALNODE').mapProperty('selectedHost');
    var originalHosts = App.HostComponent.find().filterProperty('componentName', 'JOURNALNODE').mapProperty('hostName');
    return currentHosts.sort().join() === originalHosts.sort().join();
  }.property('hostNameCheckTrigger', 'nextButtonCheckTrigger')

});


text:
@implementation JIRIssueFieldsWatches

@synthesize isWatching;
@synthesize selfUrl;
@synthesize watchCount;

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:[NSNumber numberWithBool:self.isWatching] forKey:@"isWatching"];
    [encoder encodeObject:self.selfUrl forKey:@"selfUrl"];
    [encoder encodeObject:self.watchCount forKey:@"watchCount"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if ((self = [super init])) {
        self.isWatching = [(NSNumber *)[decoder decodeObjectForKey:@"isWatching"] boolValue];
        self.selfUrl = [decoder decodeObjectForKey:@"selfUrl"];
        self.watchCount = [decoder decodeObjectForKey:@"watchCount"];
    }
    return self;
}

+ (JIRIssueFieldsWatches *)instanceFromDictionary:(NSDictionary *)aDictionary
{

    JIRIssueFieldsWatches *instance = [[JIRIssueFieldsWatches alloc] init];
    [instance setAttributesFromDictionary:aDictionary];
    return instance;

}

- (void)setAttributesFromDictionary:(NSDictionary *)aDictionary
{

    if (![aDictionary isKindOfClass:[NSDictionary class]]) {
        return;
    }

    [self setValuesForKeysWithDictionary:aDictionary];

}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{

    if ([key isEqualToString:@"self"]) {
        [self setValue:value forKey:@"selfUrl"];
    } else {
        [super setValue:value forUndefinedKey:key];
    }

}

- (NSDictionary *)dictionaryRepresentation
{

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    [dictionary setObject:[NSNumber numberWithBool:self.isWatching] forKey:@"isWatching"];

    if (self.selfUrl) {
        [dictionary setObject:self.selfUrl forKey:@"selfUrl"];
    }

    if (self.watchCount) {
        [dictionary setObject:self.watchCount forKey:@"watchCount"];
    }

    return dictionary;

}

@end


text:
Qordoba's SDK enables agile, intelligent internationalization for native iOS applications. Benefits of localizing via an SDK versus file-based methods include:

* Improved QA for your app, in less time
* Live renderings of your screens for your marketing and localization teams (no code required)
* Easy, dynamic maintenance of content in your app (without re-submitting to the App Store)
* Happy, engaged international users (since we all know when an app has not been well-localized)

### Installation

To use the SDK, you'll need the following:

* Xcode version 7.0 or later
* A sandbox key, production key & application ID from the Qordoba web application

**1. Install via CocoaPods:**

[![Version](https://img.shields.io/cocoapods/v/Qordoba-iOS-SDK.svg?style=flat)](http://cocoapods.org/pods/Qordoba-iOS-SDK)
[![License](https://img.shields.io/cocoapods/l/Qordoba-iOS-SDK.svg?style=flat)](http://cocoapods.org/pods/Qordoba-iOS-SDK)
[![Platform](https://img.shields.io/cocoapods/p/Qordoba-iOS-SDK.svg?style=flat)](http://cocoapods.org/pods/Qordoba-iOS-SDK)

**2. Install manually:**

Detailed manual installation instructions are available at https://developers.qordoba.com/ios

### Feedback

Your feedback will help us shape the future of this product! For questions, comments, suggestions or feedback, please message us at support@qordoba.com.

### Legal

This SDK is available under the Apache license (please see separate License file). Other usage is covered by Qordoba's [terms of service](http://www.qordoba.com/terms.html).


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

<meta name="description" content="Status">

<meta name="keywords" content="solr"/>

<meta property="og:title" content="Better balancer and more for Apache Solr">
<meta property="og:type" content="article">
<meta property="og:url" content="http://sysadm.cz/2016/05/22/Better-balancer-for-solr//">
<meta property="og:image" content="http://sysadm.cz">
<meta property="og:description" content="Status">
<meta property="og:site_name" content="sysadm.cz">
<meta property="og:locale" content="">

  <meta property="article:published_time" content="2016-05-22T00:00:00+02:00">
  <meta property="article:author" content="">

    <meta property="og:see_also" content="http://sysadm.cz/2016/04/08/One-more-step-to-autodeploy/">

    <meta property="og:see_also" content="http://sysadm.cz/2016/02/16/Azkaban-eboshi/">

    <meta property="og:see_also" content="http://sysadm.cz/2016/01/07/Inconsistency-jmx-hbck/">

<meta property="fb:admins" content="">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Better balancer and more for Apache Solr · sysadm.cz

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/lanyon.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

the pages with experience one of the bigdata admin

    Home
    About
    Tags
    Feed
    Latest posts

		   22 May 2016 »

		   Better balancer and more for Apache Solr

		   08 Apr 2016 »

		   One more step to autodeploy

		   16 Feb 2016 »

		   Azkaban workflow manager + eboshi

		   07 Jan 2016 »

		   Corrupt blocks in HDFS?

		   05 Dec 2015 »

		   Upgrade OpsCenter to version 5.2.2

		   24 Nov 2015 »

		   Welcome to my new page

            sysadm.cz

Better balancer and more for Apache Solr

  22 May 2016

Our team have some Apache Solr servers.

We had states and pillars in this format.

state-launcher.sls

clusterlauncher:
  pkg.installed:
    - name:
      - szn-email-job: {{ pillar['szn-email-job'] }}
      - szn-email-activity: {{ pillar['szn-email-activity'] }}
      - szn-fulltext-generator: {{ pillar['szn-fulltext-generator'] }}
      - szn-fulltext-dump: {{ pillar['szn-fulltext-dump'] }}
    - refresh: True

pillar-cluster.sls

szn-email-job: 0.1.0
szn-email-activity: 0.0.17
szn-fulltext-generator: 0.1.21
szn-fulltext-dump: 0.0.3

We made adjustments to our states and pillars. What we want know about package? We want to know where to install package, his version and config file. So we chose this format for our new pillars.

new-pillar-cluster.sls

#there is two ways for define package for install
# 1)
#   package-name: 0.0.1
#
# 2)
#   package-name:
#     version: 0.0.1
#    [conf-src: salt://path/to/conf]
#    [conf-dst: /path/to/conf/on/server]
pkgs:
  - clusterlauncher\d+\.ng\.seznam\.cz:
    szn-email-job: 0.1.0
    szn-email-activity:
      version: 0.0.17
      conf-src: salt://conf/szn-email-activity/
      conf-dst: /www/szn-email-activity/conf/
    szn-fulltext-generator: 0.1.21
    szn-fulltext-dump:
      version: 0.0.3
      conf-src: salt://conf/szn-fulltext-dump/config.xml
      conf-dst: /www/szn-fulltext-dump/conf/config.xml

You will se that is optionally if we use conf or not. Plus we can copy one file or directory (if conf-dst last char is "/"). After this we must deploy state for installation packages and copy configs. But there was problem. Jinja can`t work with regex. Really! So we had to add workaround via salt module.

my_re.py

import re

def match(pattern, st, flags=0):
  return re.match(pattern, st, flags)

Ok. After this we can finaly deploy states. We wrote two states:

pkg-regex-install.sls

{% if pillar['pkgs'] is defined %}

regex-install:
  pkg.installed:
    - pkgs:
#### we can`t have empty list of pkgs for install (when for loop is empty) ####
      - apt
{% for regex, pkgs in salt['pillar.get']('pkgs', {}).iteritems() %}
  {% if salt['my_re.match'](regex, grains['fqdn']) != None %}
    {% for pkg, metadata in pkgs.iteritems() %}
      {% if 'version' in metadata %}
      - {{ pkg }}: {{ metadata['version'] }}
      {% else %}
      - {{ pkg }}: {{ metadata }}
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}
    - refresh: True

{% endif %}

config-regex.sls

{% if pillar['pkgs'] is defined %}

{% for regex, pkgs in salt['pillar.get']('pkgs', {}).iteritems() %}
  {% if salt['my_re.match'](regex, grains['fqdn']) != None %}
    {% for pkg, metadata in pkgs.iteritems() %}
      {% if 'conf-dst' in metadata %}
{{ metadata['conf-dst'] }}:
        {% if metadata['conf-dst'][-1] == "/" %}
  file.recurse:
        {% else %}
  file.managed:
        {% endif %}
    - source: {{ metadata['conf-src'] }}
    - template: jinja
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}

{% endif %}

Now when we want to add some package we edit only one file. Plus deployers can themself send merge request with his changes in config or version. Then sysadmin only check changes and run state.highstate on salt master to server.

Related Posts

            One more step to autodeploy
            08 Apr 2016

            Azkaban workflow manager + eboshi
            16 Feb 2016

            Corrupt blocks in HDFS?
            07 Jan 2016


text:
layout: single
title: ROS MiniImu Calibration and Sensor Fusion
sidebar:
  nav: "sidenav"
---

## Overview
This is a [ROS] package developed to calibrate and fuse the orientation data provided by an Polulu MiniImu v9.

The ROS MiniImu Calibration and Sensor Fusion Packages are tested under ROS Indigo and Ubuntu 14.04.

**Affiliation: Advancements for Robotics in Rescue Applications, AR2A**

## Travis Build Status
[![Build Status](https://travis-ci.org/AR2A/imu-minimu-arduino.svg?branch=master)](https://travis-ci.org/AR2A/imu-minimu-arduino)

## Installation

### Dependencies

This software is built on the Robotic Operating System ([ROS]), which needs to be [installed](http://wiki.ros.org) first. Additionaly, the ROS MiniImu Calibration and Sensor Fusion depends on following software:

- [arduino toolchain](https://www.arduino.cc) (simple programming environment for education pcbs)

- [rosserial](https://github.com/ros-drivers/rosserial) (wrapper to transmit ros messages over a serial port)

        sudo apt-get install ros-indigo-rosserial-arduino
        sudo apt-get install ros-indigo-rosserial

- [Boost](http://www.boost.org) (general purpose c++ library),

        sudo apt-get install libboost-dev

- [armadillo](http://arma.sourceforge.net/) (c++ linear algebra library),

        sudo apt-get install liblapack-dev
        sudo apt-get install libblas-dev
        sudo apt-get install libarmadillo-dev

### Building

To use the packages in your project, clone the latest version of this repository to the source folder of your catkin workspace.
Make sure that all dependencies listed above are installed before executing catkin_make.

        cd ~/catkin_ws/src
        git clone https://github.com/AR2A/imu-minimu-arduino.git
        cd ..
        catkin_make

## Basic Usage

### Downloading the firmware to the arduino

In order for the download to work modify the file "avr_imu/firmware/CMakeLists.txt" to suit your setup.

        cmake_minimum_required(VERSION 2.8.3)

        include_directories(ros_lib arduino_libs)

        generate_arduino_firmware(avr_imu
        	SRCS avr_imu.cpp arduino_libs/L3G/L3G.cpp arduino_libs/LSM303/LSM303.cpp ros_lib/time.cpp
        	BOARD mega2560
        	PORT /dev/ttyACM0
        )

Most likely the variables BOARD and PORT have to be modified.

Afterwards you download the firmware by issuing the following commands inside your catkin workspace.

        catkin_make avr_imu_firmware_avr_imu
        catkin_make avr_imu_firmware_avr_imu-upload

### Visualizing data with [rviz]

For debugging purposes it can be useful to visualize the orientation within [rviz]. To do so install the imu_tools package which contains the [rviz_imu_plugin](http://wiki.ros.org/rviz_imu_plugin) package.

        sudo apt-get install ros-indigo-imu-tools

## Nodes

### Node: avr_imu

This is the rosserial node running on the arduino board. The node reads the data from the imu over the spi interface and issues a message containing this data in a 50 Hz cycle.

#### Subscribed Topics

*None*

#### Published Topics

* **`/imu/data_raw`** ([sensor_msgs/Imu])

    The raw register data of the imu (accelerometer and gyroscope).

* **`/imu/magnetic_field`** ([sensor_msgs/MagneticField])

	The raw register data of the imu (magnetometer).

#### Services

*None*

#### Parameters

*None*

### Node: calib_imu(experimental)

This node executes a step by step calibration process to compensate the alignement and scaling of the imu data (as well as hard and soft ironing effects on the magnetometer data). When the calibration finishes the calculated data is stored inside the ros execution path (typical ~/.ros).

#### Subscribed Topics

* **`/imu/data_raw`** ([sensor_msgs/Imu])

    The raw register data of the imu (accelerometer and gyroscope).

* **`/imu/magnetic_field`** ([sensor_msgs/MagneticField])

	The raw register data of the imu (magnetometer).

#### Published Topics

*None*

#### Services

*None*

#### Parameters

*None*

### Node: process_imu_data

This node processes the senor fusion with an extended kalman filter

The node is roughly designed after the findings of the following paper:

> David Jurman, Marko Jankovec, Roman Kamnik, Marko Topic, "[Calibration and data fusion solution for the miniature
attitude and heading reference system](http://www.sciencedirect.com/science/article/pii/S0924424707003834)", in Sensors and Actuators A: Physical, Volume 138, 2007.

#### Subscribed Topics

* **`/imu/data_raw`** ([sensor_msgs/Imu])

    The raw register data of the imu (accelerometer and gyroscope).

* **`/imu/magnetic_field`** ([sensor_msgs/MagneticField])

	The raw register data of the imu (magnetometer).

#### Published Topics

* **`/imu/data`** ([sensor_msgs/Imu])

    The fused orientation data.

#### Services

*None*

#### Parameters

*None*

## Bugs & Feature Requests

Please report bugs and request features using the [Issue Tracker](https://github.com/AR2A/imu-minimu-arduino/issues).

[ROS]: http://www.ros.org
[rviz]: http://wiki.ros.org/rviz
[avr_imu/Imu]: https://github.com/AR2A/imu-minimu-arduino/blob/master/avr_imu/msg/Imu.msg
[sensor_msgs/Imu]: http://docs.ros.org/api/sensor_msgs/html/msg/Imu.html
[sensor_msgs/MagneticField]: http://docs.ros.org/api/sensor_msgs/html/msg/MagneticField.html
[std_msgs/Empty]: http://docs.ros.org/api/std_msgs/html/msg/Empty.html


text:
#ifndef POLYGRAPH__PGL_MULTIRANGESYM_H
#define POLYGRAPH__PGL_MULTIRANGESYM_H

#include "xstd/String.h"
#include "pgl/RangeSym.h"

class MultiRangeSym: public RangeSym {
	public:
		typedef bool (MultiRangeSym::*FactorFunc)(double &rf) const;

	public:
		static const String TheType;

	public:
		MultiRangeSym();
		MultiRangeSym(const String &aType, PglRec *aRec);

		virtual bool isA(const String &type) const;

		RndDistr *first_range_start_absolute() const;
		RndDistr *first_range_start_relative() const;
		RndDistr *range_length_absolute() const;
		RndDistr *range_length_relative() const;
                RndDistr *range_count() const;

	protected:
		virtual SynSym *dupe(const String &dType) const;
};

#endif


text:
package twitter4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import java.util.Map;

/**
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @since Twitter4J 2.2.4
 */
public class LazyHttpClientImpl extends HttpClientImpl {
    private static final long serialVersionUID = 7325894890960046422L;
    private final HttpClient client;

    public LazyHttpClientImpl(HttpClientConfiguration conf) {
        client = new AlternativeHttpClientImpl(conf);
    }

    @Override
    public HttpResponse handleRequest(HttpRequest req) throws TwitterException {
        return new LazyHttpResponseImpl(client, req);
    }

}

class LazyHttpResponseImpl extends HttpResponse {
    private HttpClient client;
    private HttpRequest req;
    private HttpResponse actualResponse = null;

    LazyHttpResponseImpl(HttpClient client, HttpRequest req) {
        this.client = client;
        this.req = req;
    }

    @Override
    public Map<String, List<String>> getResponseHeaderFields() {
        ensure();
        return actualResponse.getResponseHeaderFields();
    }

    @Override
    public void disconnect() throws IOException {
        ensure();
        actualResponse.disconnect();
    }

    public int getStatusCode() {
        ensure();
        return actualResponse.getStatusCode();
    }

    public String getResponseHeader(String name) {
        ensure();
        return actualResponse.getResponseHeader(name);
    }

    public InputStream asStream() {
        ensure();
        return actualResponse.asStream();
    }

    public String asString() throws TwitterException {
        ensure();
        return actualResponse.asString();
    }

    public JSONObject asJSONObject() throws TwitterException {
        ensure();
        return actualResponse.asJSONObject();
    }

    public JSONArray asJSONArray() throws TwitterException {
        ensure();
        return actualResponse.asJSONArray();
    }

    public Reader asReader() {
        ensure();
        return actualResponse.asReader();
    }

    private void ensure() {
        if (actualResponse == null) {
            try {
                actualResponse = client.request(req);
            } catch (TwitterException e) {
                throw new TwitterRuntimeException(e);
            }
        }
    }
}


text:
.PHONY: test fuzz

test:
	go test -coverprofile=profile.out -coverpkg=github.com/yuin/goldmark,github.com/yuin/goldmark/ast,github.com/yuin/goldmark/extension,github.com/yuin/goldmark/extension/ast,github.com/yuin/goldmark/parser,github.com/yuin/goldmark/renderer,github.com/yuin/goldmark/renderer/html,github.com/yuin/goldmark/text,github.com/yuin/goldmark/util ./...

cov: test
	go tool cover -html=profile.out

fuzz:
	cd ./fuzz && go test -fuzz=Fuzz