text:
/*
    This example demonstrates the use of CUDA/OpenGL interoperability
    to post-process an image of a 3D scene generated in OpenGL.

    The basic steps are:
    1 - render the scene to the framebuffer
    2 - map the color texture so that its memory is accessible from CUDA
    4 - run CUDA to process the image, writing to memory
        a- either mapped from a second PBO
        b- or allocated through CUDA
    6 - copy result
        a- from the PBO to a texture with glTexSubImage2D()
        b- or map the target texture and do a cuda memory copy
    7 - display the texture with a fullscreen quad

    The example also provides two solutions for the format of the image:
      - RGBA16F : more bytes involved but easier to handle because
        compatible with regular fragment shader
      - RGBA8UI : 32bytes, but the teapot color must be scaled by 255 (so we needed GLSL code)
    How about RGBA8?  The CUDA driver does not have consistent interoperability with this format.
    Older GPUs may not store data the same way compared with newer GPUs, resulting in a swap of R and B components
    On older HW, this will need workarounds.

    Press space to toggle the CUDA processing on/off.
    Press 'a' to toggle animation.
    Press '+' and '-' to increment and decrement blur radius
*/

// this mode is "old fashion" : use glTexSubImage2D() to update the final result
// commenting it will make the sample use the other way :
// map a texture in CUDA and blit the result into it
#define USE_TEXSUBIMAGE2D

#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#  define WINDOWS_LEAN_AND_MEAN
#  define NOMINMAX
#  include <windows.h>
#pragma warning(disable:4996)
#endif

// OpenGL Graphics includes
#include <GL/glew.h>
#if defined(__APPLE__) || defined(MACOSX)
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#include <GLUT/glut.h>
// Sorry for Apple : unsigned int sampler is not available to you, yet...
// Let's switch to the use of PBO and glTexSubImage
#define USE_TEXSUBIMAGE2D
#else
#include <GL/freeglut.h>
#endif

// CUDA includes
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>

// CUDA utilities and system includes
#include <helper_cuda.h>
#include <helper_cuda_gl.h>

#include <helper_functions.h>
#include <rendercheck_gl.h>

// Shared Library Test Functions
#define MAX_EPSILON 10
#define REFRESH_DELAY     10 //ms

const char *sSDKname = "postProcessGL";

unsigned int g_TotalErrors = 0;

// CheckFBO/BackBuffer class objects
CheckRender *g_CheckRender = NULL;

////////////////////////////////////////////////////////////////////////////////
// constants / global variables
unsigned int window_width = 512;
unsigned int window_height = 512;
unsigned int image_width = 512;
unsigned int image_height = 512;
int iGLUTWindowHandle = 0;          // handle to the GLUT window

// pbo and fbo variables
#ifdef USE_TEXSUBIMAGE2D
GLuint pbo_dest;
struct cudaGraphicsResource *cuda_pbo_dest_resource;
#else
unsigned int *cuda_dest_resource;
GLuint shDrawTex;  // draws a texture
struct cudaGraphicsResource *cuda_tex_result_resource;
#endif

GLuint fbo_source;
struct cudaGraphicsResource *cuda_tex_screen_resource;

unsigned int size_tex_data;
unsigned int num_texels;
unsigned int num_values;

// (offscreen) render target fbo variables
GLuint framebuffer;     // to bind the proper targets
GLuint depth_buffer;    // for proper depth test while rendering the scene
GLuint tex_screen;      // where we render the image
GLuint tex_cudaResult;  // where we will copy the CUDA result

float rotate[3];

char *ref_file       = NULL;
bool enable_cuda     = true;
bool animate         = true;
int  blur_radius     = 8;
int  max_blur_radius = 16;

int   *pArgc = NULL;
char **pArgv = NULL;

// Timer
static int fpsCount = 0;
static int fpsLimit = 1;
StopWatchInterface *timer = NULL;

#ifndef USE_TEXTURE_RGBA8UI
#   pragma message("Note: Using Texture fmt GL_RGBA16F_ARB")
#else
// NOTE: the current issue with regular RGBA8 internal format of textures
// is that HW stores them as BGRA8. Therefore CUDA will see BGRA where users
// expected RGBA8. To prevent this issue, the driver team decided to prevent this to happen
// instead, use RGBA8UI which required the additional work of scaling the fragment shader
// output from 0-1 to 0-255. This is why we have some GLSL code, in this case
#   pragma message("Note: Using Texture RGBA8UI + GLSL for teapot rendering")
#endif
GLuint shDrawPot;  // colors the teapot

////////////////////////////////////////////////////////////////////////////////
extern "C" void
launch_cudaProcess(dim3 grid, dim3 block, int sbytes,
                   cudaArray *g_data, unsigned int *g_odata,
                   int imgw, int imgh, int tilew,
                   int radius, float threshold, float highlight);

// Forward declarations
void runStdProgram(int argc, char **argv);
void FreeResource();
void Cleanup(int iExitCode);

// GL functionality
bool initCUDA(int argc, char **argv, bool bUseGL);
bool initGL(int *argc, char **argv);

#ifdef USE_TEXSUBIMAGE2D
void createPBO(GLuint *pbo, struct cudaGraphicsResource **pbo_resource);
void deletePBO(GLuint *pbo);
#endif

void createTextureDst(GLuint *tex_cudaResult, unsigned int size_x, unsigned int size_y);
void createTextureSrc(GLuint *tex_screen, unsigned int size_x, unsigned int size_y);
void deleteTexture(GLuint *tex);
void createDepthBuffer(GLuint *depth, unsigned int size_x, unsigned int size_y);
void deleteDepthBuffer(GLuint *depth);
void createFramebuffer(GLuint *fbo, GLuint color, GLuint depth);
void deleteFramebuffer(GLuint *fbo);

// rendering callbacks
void display();
void idle();
void keyboard(unsigned char key, int x, int y);
void reshape(int w, int h);
void mainMenu(int i);

////////////////////////////////////////////////////////////////////////////////
//! Run the Cuda part of the computation
////////////////////////////////////////////////////////////////////////////////
void process(int width, int height, int radius)
{
    cudaArray *in_array;
    unsigned int *out_data;

#ifdef USE_TEXSUBIMAGE2D
    checkCudaErrors(cudaGraphicsMapResources(1, &cuda_pbo_dest_resource, 0));
    size_t num_bytes;
    checkCudaErrors(cudaGraphicsResourceGetMappedPointer((void **)&out_data, &num_bytes,
                                                         cuda_pbo_dest_resource));
    //printf("CUDA mapped pointer of pbo_out: May access %ld bytes, expected %d\n", num_bytes, size_tex_data);
#else
    out_data = cuda_dest_resource;
#endif

    // map buffer objects to get CUDA device pointers
    checkCudaErrors(cudaGraphicsMapResources(1, &cuda_tex_screen_resource, 0));
    //printf("Mapping tex_in\n");
    checkCudaErrors(cudaGraphicsSubResourceGetMappedArray(&in_array, cuda_tex_screen_resource, 0, 0));

    // calculate grid size
    dim3 block(16, 16, 1);
    //dim3 block(16, 16, 1);
    dim3 grid(width / block.x, height / block.y, 1);
    int sbytes = (block.x+(2*radius))*(block.y+(2*radius))*sizeof(unsigned int);

    // execute CUDA kernel
    launch_cudaProcess(grid, block, sbytes,
                       in_array, out_data, width, height,
                       block.x+(2*radius), radius, 0.8f, 4.0f);

    checkCudaErrors(cudaGraphicsUnmapResources(1, &cuda_tex_screen_resource, 0));
#ifdef USE_TEXSUBIMAGE2D
    checkCudaErrors(cudaGraphicsUnmapResources(1, &cuda_pbo_dest_resource, 0));
#endif
}

#ifdef USE_TEXSUBIMAGE2D
////////////////////////////////////////////////////////////////////////////////
//! Create PBO
////////////////////////////////////////////////////////////////////////////////
void
createPBO(GLuint *pbo, struct cudaGraphicsResource **pbo_resource)
{
    // set up vertex data parameter
    num_texels = image_width * image_height;
    num_values = num_texels * 4;
    size_tex_data = sizeof(GLubyte) * num_values;
    void *data = malloc(size_tex_data);

    // create buffer object
    glGenBuffers(1, pbo);
    glBindBuffer(GL_ARRAY_BUFFER, *pbo);
    glBufferData(GL_ARRAY_BUFFER, size_tex_data, data, GL_DYNAMIC_DRAW);
    free(data);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // register this buffer object with CUDA
    checkCudaErrors(cudaGraphicsGLRegisterBuffer(pbo_resource, *pbo, cudaGraphicsMapFlagsNone));

    SDK_CHECK_ERROR_GL();
}

void
deletePBO(GLuint *pbo)
{
    glDeleteBuffers(1, pbo);
    SDK_CHECK_ERROR_GL();
    *pbo = 0;
}
#endif

const GLenum fbo_targets[] =
{
    GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT,
    GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT
};

#ifndef USE_TEXSUBIMAGE2D
static const char *glsl_drawtex_vertshader_src =
    "void main(void)\n"
    "{\n"
    "	gl_Position = gl_Vertex;\n"
    "	gl_TexCoord[0].xy = gl_MultiTexCoord0.xy;\n"
    "}\n";

static const char *glsl_drawtex_fragshader_src =
    "#version 130\n"
    "uniform usampler2D texImage;\n"
    "void main()\n"
    "{\n"
    "   vec4 c = texture(texImage, gl_TexCoord[0].xy);\n"
    "	gl_FragColor = c / 255.0;\n"
    "}\n";
#endif

static const char *glsl_drawpot_fragshader_src =
    //WARNING: seems like the gl_FragColor doesn't want to output >1 colors...
    //you need version 1.3 so you can define a uvec4 output...
    //but MacOSX complains about not supporting 1.3 !!
    // for now, the mode where we use RGBA8UI may not work properly for Apple : only RGBA16F works (default)
#if defined(__APPLE__) || defined(MACOSX)
    "void main()\n"
    "{"
    "  gl_FragColor = vec4(gl_Color * 255.0);\n"
    "}\n";
#else
    "#version 130\n"
    "in vec4 inColor;\n"
    "out uvec4 FragColor;\n"
    "void main()\n"
    "{"
    "  FragColor = uvec4(inColor.xyz * 255.0, 255.0);\n"
    "}\n";
#endif

////////////////////////////////////////////////////////////////////////////////
//! render a simple 3D scene
////////////////////////////////////////////////////////////////////////////////
void renderScene(bool colorScale)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (colorScale)
    {
        glUseProgram(shDrawPot);
        glBindFragDataLocationEXT(shDrawPot, 0, "FragColor");
        SDK_CHECK_ERROR_GL();
    }

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0, 0.0, -3.0);
    glRotatef(rotate[0], 1.0, 0.0, 0.0);
    glRotatef(rotate[1], 0.0, 1.0, 0.0);
    glRotatef(rotate[2], 0.0, 0.0, 1.0);

    glViewport(0, 0, 512, 512);

    glEnable(GL_LIGHTING);
    glEnable(GL_DEPTH_TEST);

    glutSolidTeapot(1.0);

    if (colorScale)
    {
        glUseProgram(0);
    }

    SDK_CHECK_ERROR_GL();
}

// copy image and process using CUDA
void processImage()
{
    // run the Cuda kernel
    process(image_width, image_height, blur_radius);

    // CUDA generated data in cuda memory or in a mapped PBO made of BGRA 8 bits
    // 2 solutions, here :
    // - use glTexSubImage2D(), there is the potential to loose performance in possible hidden conversion
    // - map the texture and blit the result thanks to CUDA API
#ifdef USE_TEXSUBIMAGE2D
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo_dest);

    glBindTexture(GL_TEXTURE_2D, tex_cudaResult);
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
                    image_width, image_height,
                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    SDK_CHECK_ERROR_GL();
    glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, 0);
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
#else
    // We want to copy cuda_dest_resource data to the texture
    // map buffer objects to get CUDA device pointers
    cudaArray *texture_ptr;
    checkCudaErrors(cudaGraphicsMapResources(1, &cuda_tex_result_resource, 0));
    checkCudaErrors(cudaGraphicsSubResourceGetMappedArray(&texture_ptr, cuda_tex_result_resource, 0, 0));

    int num_texels = image_width * image_height;
    int num_values = num_texels * 4;
    int size_tex_data = sizeof(GLubyte) * num_values;
    checkCudaErrors(cudaMemcpyToArray(texture_ptr, 0, 0, cuda_dest_resource, size_tex_data, cudaMemcpyDeviceToDevice));

    checkCudaErrors(cudaGraphicsUnmapResources(1, &cuda_tex_result_resource, 0));
#endif
}

// display image to the screen as textured quad
void displayImage(GLuint texture)
{
    glBindTexture(GL_TEXTURE_2D, texture);
    glEnable(GL_TEXTURE_2D);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glViewport(0, 0, window_width, window_height);

    // if the texture is a 8 bits UI, scale the fetch with a GLSL shader
#ifndef USE_TEXSUBIMAGE2D
    glUseProgram(shDrawTex);
    GLint id = glGetUniformLocation(shDrawTex, "texImage");
    glUniform1i(id, 0); // texture unit 0 to "texImage"
    SDK_CHECK_ERROR_GL();
#endif

    glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-1.0, -1.0, 0.5);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(1.0, -1.0, 0.5);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(1.0, 1.0, 0.5);
    glTexCoord2f(0.0, 1.0);
    glVertex3f(-1.0, 1.0, 0.5);
    glEnd();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    glDisable(GL_TEXTURE_2D);

#ifndef USE_TEXSUBIMAGE2D
    glUseProgram(0);
#endif
    SDK_CHECK_ERROR_GL();
}

////////////////////////////////////////////////////////////////////////////////
//! Display callback
////////////////////////////////////////////////////////////////////////////////
void
display()
{
    sdkStartTimer(&timer);

    if (enable_cuda)
    {
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer);
#ifndef USE_TEXTURE_RGBA8UI
        renderScene(false);
#else
        renderScene(true); // output of fragment * by 255 (for RGBA8UI texture)
#endif
        processImage();
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        displayImage(tex_cudaResult);
    }
    else
    {
        renderScene(false);
    }

    // NOTE: I needed to add this call so the timing is consistent.
    // Need to investigate why
    cudaDeviceSynchronize();
    sdkStopTimer(&timer);

    // flip backbuffer
    glutSwapBuffers();

    // If specified, Check rendering against reference,
    if (ref_file && g_CheckRender && g_CheckRender->IsQAReadback())
    {

        static int pass = 0;

        if (pass > 0)
        {
            g_CheckRender->readback(window_width, window_height);
            char currentOutputPPM[256];
            sprintf(currentOutputPPM, "teapot_%d.ppm", blur_radius);
            g_CheckRender->savePPM(currentOutputPPM, true, NULL);

            if (!g_CheckRender->PPMvsPPM(currentOutputPPM, sdkFindFilePath(ref_file, pArgv[0]), MAX_EPSILON, 0.30f))
            {
                g_TotalErrors++;
            }

            Cleanup((g_TotalErrors==0) ? EXIT_SUCCESS : EXIT_FAILURE);
        }

        pass++;
    }

    // Update fps counter, fps/title display and log
    if (++fpsCount == fpsLimit)
    {
        char cTitle[256];
        float fps = 1000.0f / sdkGetAverageTimerValue(&timer);
        sprintf(cTitle, "CUDA GL Post Processing (%d x %d): %.1f fps", window_width, window_height, fps);
        glutSetWindowTitle(cTitle);
        //printf("%s\n", cTitle);
        fpsCount = 0;
        fpsLimit = (int)((fps > 1.0f) ? fps : 1.0f);
        sdkResetTimer(&timer);
    }
}

void timerEvent(int value)
{
    if (animate)
    {
        rotate[0] += 0.2f;

        if (rotate[0] > 360.0f)
        {
            rotate[0] -= 360.0f;
        }

        rotate[1] += 0.6f;

        if (rotate[1] > 360.0f)
        {
            rotate[1] -= 360.0f;
        }

        rotate[2] += 1.0f;

        if (rotate[2] > 360.0f)
        {
            rotate[2] -= 360.0f;
        }
    }

    glutPostRedisplay();
    glutTimerFunc(REFRESH_DELAY, timerEvent, 0);
}

////////////////////////////////////////////////////////////////////////////////
//! Keyboard events handler
////////////////////////////////////////////////////////////////////////////////
void
keyboard(unsigned char key, int /*x*/, int /*y*/)
{
    switch (key)
    {
        case (27) :
            Cleanup(EXIT_SUCCESS);
            break;

        case ' ':
            enable_cuda ^= 1;
#ifdef USE_TEXTURE_RGBA8UI

            if (enable_cuda)
            {
                glClearColorIuiEXT(128,128,128,255);
            }
            else
            {
                glClearColor(0.5, 0.5, 0.5, 1.0);
            }

#endif
            break;

        case 'a':
            animate ^= 1;
            break;

        case '=':
        case '+':
            if (blur_radius < 16)
            {
                blur_radius++;
            }

            printf("radius = %d\n", blur_radius);
            break;

        case '-':
            if (blur_radius > 1)
            {
                blur_radius--;
            }

            printf("radius = %d\n", blur_radius);
            break;
    }
}

void reshape(int w, int h)
{
    window_width = w;
    window_height = h;
}

void mainMenu(int i)
{
    keyboard((unsigned char) i, 0, 0);
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
createTextureSrc(GLuint *tex_screen, unsigned int size_x, unsigned int size_y)
{
    // create a texture
    glGenTextures(1, tex_screen);
    glBindTexture(GL_TEXTURE_2D, *tex_screen);

    // set basic parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    // buffer data
#ifndef USE_TEXTURE_RGBA8UI
    printf("Creating a Texture render target GL_RGBA16F_ARB\n");
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, size_x, size_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
#else
    printf("Creating a Texture render target GL_RGBA8UI_EXT\n");
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8UI_EXT, size_x, size_y, 0, GL_RGBA_INTEGER_EXT, GL_UNSIGNED_BYTE, NULL);
#endif
    SDK_CHECK_ERROR_GL();
    // register this texture with CUDA
    checkCudaErrors(cudaGraphicsGLRegisterImage(&cuda_tex_screen_resource, *tex_screen,
                                                GL_TEXTURE_2D, cudaGraphicsMapFlagsReadOnly));
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
createTextureDst(GLuint *tex_cudaResult, unsigned int size_x, unsigned int size_y)
{
    // create a texture
    glGenTextures(1, tex_cudaResult);
    glBindTexture(GL_TEXTURE_2D, *tex_cudaResult);

    // set basic parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

#ifdef USE_TEXSUBIMAGE2D
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size_x, size_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    SDK_CHECK_ERROR_GL();
#else
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8UI_EXT, size_x, size_y, 0, GL_RGBA_INTEGER_EXT, GL_UNSIGNED_BYTE, NULL);
    SDK_CHECK_ERROR_GL();
    // register this texture with CUDA
    checkCudaErrors(cudaGraphicsGLRegisterImage(&cuda_tex_result_resource, *tex_cudaResult,
                                                GL_TEXTURE_2D, cudaGraphicsMapFlagsWriteDiscard));
#endif
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
deleteTexture(GLuint *tex)
{
    glDeleteTextures(1, tex);
    SDK_CHECK_ERROR_GL();

    *tex = 0;
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
createDepthBuffer(GLuint *depth, unsigned int size_x, unsigned int size_y)
{
    // create a renderbuffer
    glGenRenderbuffersEXT(1, depth);
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, *depth);

    // allocate storage
    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, size_x, size_y);

    // clean up
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

    SDK_CHECK_ERROR_GL();
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
//void
//createRenderBuffer(GLuint* render, unsigned int size_x, unsigned int size_y)
//{
//    // create a renderbuffer
//    glGenRenderbuffersEXT(1, render);
//    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, *render);
//
//    // allocate storage
//    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, size_x, size_y);
//
//    // clean up
//    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
//
//    SDK_CHECK_ERROR_GL();
//
//  checkCudaErrors(cudaGraphicsGLRegisterImage(&cuda_tex_screen_resource, *render,
//                        GL_RENDERBUFFER_EXT, cudaGraphicsMapFlagsReadOnly));
//}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
deleteDepthBuffer(GLuint *depth)
{
    glDeleteRenderbuffersEXT(1, depth);
    SDK_CHECK_ERROR_GL();

    *depth = 0;
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
createFramebuffer(GLuint *fbo, GLuint color, GLuint depth)
{
    // create and bind a framebuffer
    glGenFramebuffersEXT(1, fbo);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo);

    // attach images
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, color, 0);
    //glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, color);
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth);

    // clean up
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

    SDK_CHECK_ERROR_GL();
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void
deleteFramebuffer(GLuint *fbo)
{
    glDeleteFramebuffersEXT(1, fbo);
    SDK_CHECK_ERROR_GL();

    *fbo = 0;
}

////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
#if defined(__linux__)
    setenv ("DISPLAY", ":0", 0);
#endif

    printf("%s Starting...\n\n", argv[0]);

    if (checkCmdLineFlag(argc, (const char **)argv, "radius") &&
        checkCmdLineFlag(argc, (const char **)argv, "file"))
    {

        getCmdLineArgumentString(argc, (const char **)argv, "file", &ref_file);
        blur_radius = getCmdLineArgumentInt(argc, (const char **)argv, "radius");
    }

    pArgc = &argc;
    pArgv = argv;

    // use command-line specified CUDA device, otherwise use device with highest Gflops/s
    if (checkCmdLineFlag(argc, (const char **)argv, "device"))
    {
        printf("[%s]\n", argv[0]);
        printf("   Does not explicitly support -device=n\n");
        printf("   This sample requires OpenGL.  Only -file=<reference> -radius=<n> are supported\n");
        printf("exiting...\n");
        exit(EXIT_WAIVED);
    }

    if (ref_file)
    {
        printf("(Test with OpenGL verification)\n");
        animate         = false;

        runStdProgram(argc, argv);
    }
    else
    {
        printf("(Interactive OpenGL Demo)\n");
        animate         = true;

        runStdProgram(argc, argv);
    }

    exit(EXIT_SUCCESS);
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void FreeResource()
{
    sdkDeleteTimer(&timer);

    // unregister this buffer object with CUDA
    checkCudaErrors(cudaGraphicsUnregisterResource(cuda_tex_screen_resource));
#ifdef USE_TEXSUBIMAGE2D
    checkCudaErrors(cudaGraphicsUnregisterResource(cuda_pbo_dest_resource));
    deletePBO(&pbo_dest);
#else
    cudaFree(cuda_dest_resource);
#endif
    deleteTexture(&tex_screen);
    deleteTexture(&tex_cudaResult);
    deleteDepthBuffer(&depth_buffer);
    deleteFramebuffer(&framebuffer);

    // cudaDeviceReset causes the driver to clean up all state. While
    // not mandatory in normal operation, it is good practice.  It is also
    // needed to ensure correct operation when the application is being
    // profiled. Calling cudaDeviceReset causes all profile data to be
    // flushed before the application exits
    cudaDeviceReset();

    if (iGLUTWindowHandle)
    {
        glutDestroyWindow(iGLUTWindowHandle);
    }

    // finalize logs and leave
    printf("postProcessGL.exe Exiting...\n");
}

void Cleanup(int iExitCode)
{
    FreeResource();
    printf("Images are %s\n", (iExitCode == EXIT_SUCCESS) ? "Matching" : "Not Matching");
    exit(EXIT_SUCCESS);
}

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
GLuint compileGLSLprogram(const char *vertex_shader_src, const char *fragment_shader_src)
{
    GLuint v, f, p = 0;

    p = glCreateProgram();

    if (vertex_shader_src)
    {
        v = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(v, 1, &vertex_shader_src, NULL);
        glCompileShader(v);

        // check if shader compiled
        GLint compiled = 0;
        glGetShaderiv(v, GL_COMPILE_STATUS, &compiled);

        if (!compiled)
        {
            //#ifdef NV_REPORT_COMPILE_ERRORS
            char temp[256] = "";
            glGetShaderInfoLog(v, 256, NULL, temp);
            printf("Vtx Compile failed:\n%s\n", temp);
            //#endif
            glDeleteShader(v);
            return 0;
        }
        else
        {
            glAttachShader(p,v);
        }
    }

    if (fragment_shader_src)
    {
        f = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(f, 1, &fragment_shader_src, NULL);
        glCompileShader(f);

        // check if shader compiled
        GLint compiled = 0;
        glGetShaderiv(f, GL_COMPILE_STATUS, &compiled);

        if (!compiled)
        {
            //#ifdef NV_REPORT_COMPILE_ERRORS
            char temp[256] = "";
            glGetShaderInfoLog(f, 256, NULL, temp);
            printf("frag Compile failed:\n%s\n", temp);
            //#endif
            glDeleteShader(f);
            return 0;
        }
        else
        {
            glAttachShader(p,f);
        }
    }

    glLinkProgram(p);

    int infologLength = 0;
    int charsWritten  = 0;

    GLint linked = 0;
    glGetProgramiv(p, GL_LINK_STATUS, &linked);

    if (linked == 0)
    {
        glGetProgramiv(p, GL_INFO_LOG_LENGTH, (GLint *)&infologLength);

        if (infologLength > 0)
        {
            char *infoLog = (char *)malloc(infologLength);
            glGetProgramInfoLog(p, infologLength, (GLsizei *)&charsWritten, infoLog);
            printf("Shader compilation error: %s\n", infoLog);
            free(infoLog);
        }
    }

    return p;
}

////////////////////////////////////////////////////////////////////////////////
//! Allocate the "render target" of CUDA
////////////////////////////////////////////////////////////////////////////////
#ifndef USE_TEXSUBIMAGE2D
void initCUDABuffers()
{
    // set up vertex data parameter
    num_texels = image_width * image_height;
    num_values = num_texels * 4;
    size_tex_data = sizeof(GLubyte) * num_values;
    checkCudaErrors(cudaMalloc((void **)&cuda_dest_resource, size_tex_data));
    //checkCudaErrors(cudaHostAlloc((void**)&cuda_dest_resource, size_tex_data, ));
}
#endif

////////////////////////////////////////////////////////////////////////////////
//!
////////////////////////////////////////////////////////////////////////////////
void initGLBuffers()
{
    // create pbo
#ifdef USE_TEXSUBIMAGE2D
    createPBO(&pbo_dest, &cuda_pbo_dest_resource);
#endif
    // create texture that will receive the result of CUDA
    createTextureDst(&tex_cudaResult, image_width, image_height);

    // create texture for blitting onto the screen
    createTextureSrc(&tex_screen, image_width, image_height);
    //createRenderBuffer(&tex_screen, image_width, image_height); // Doesn't work

    // create a depth buffer for offscreen rendering
    createDepthBuffer(&depth_buffer, image_width, image_height);

    // create a framebuffer for offscreen rendering
    createFramebuffer(&framebuffer, tex_screen, depth_buffer);

    // load shader programs
    shDrawPot = compileGLSLprogram(NULL, glsl_drawpot_fragshader_src);

#ifndef USE_TEXSUBIMAGE2D
    shDrawTex = compileGLSLprogram(glsl_drawtex_vertshader_src, glsl_drawtex_fragshader_src);
#endif
    SDK_CHECK_ERROR_GL();
}

////////////////////////////////////////////////////////////////////////////////
//! Run standard demo loop with or without GL verification
////////////////////////////////////////////////////////////////////////////////
void
runStdProgram(int argc, char **argv)
{
    // First initialize OpenGL context, so we can properly set the GL for CUDA.
    // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
    if (false == initGL(&argc, argv))
    {
        return;
    }

    // Now initialize CUDA context (GL context has been created already)
    initCUDA(argc, argv, true);

    sdkCreateTimer(&timer);
    sdkResetTimer(&timer);

    // register callbacks
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutReshapeFunc(reshape);
    glutTimerFunc(REFRESH_DELAY, timerEvent, 0);

    // create menu
    glutCreateMenu(mainMenu);
    glutAddMenuEntry("Toggle CUDA Post Processing (on/off) [ ]", ' ');
    glutAddMenuEntry("Toggle Animation (on/off) [a]", 'a');
    glutAddMenuEntry("Increase Blur Radius [=]", '=');
    glutAddMenuEntry("Decrease Blur Radius [-]", '-');
    glutAddMenuEntry("Quit (esc)", '\033');
    glutAttachMenu(GLUT_RIGHT_BUTTON);

    initGLBuffers();
#ifndef USE_TEXSUBIMAGE2D
    initCUDABuffers();
#endif

    // Creating the Auto-Validation Code
    if (ref_file)
    {
        g_CheckRender = new CheckBackBuffer(window_width, window_height, 4);
        g_CheckRender->setPixelFormat(GL_RGBA);
        g_CheckRender->setExecPath(argv[0]);
        g_CheckRender->EnableQAReadback(true);
    }

    printf("\n"
           "\tControls\n"
           "\t(right click mouse button for Menu)\n"
           "\t[ ] : Toggle CUDA Post Processing (on/off)\n"
           "\t[a] : Toggle Animation (on/off)\n"
           "\t[=] : Increase Blur Radius\n"
           "\t[-] : Decrease Blur Radius\n"
           "\t[esc] - Quit\n\n"
          );

    // start rendering mainloop
    glutMainLoop();

    // Normally unused return path
    Cleanup(EXIT_SUCCESS);
}

////////////////////////////////////////////////////////////////////////////////
//! Initialize CUDA context
////////////////////////////////////////////////////////////////////////////////
bool
initCUDA(int argc, char **argv, bool bUseGL)
{
    if (bUseGL)
    {
        findCudaGLDevice(argc, (const char **)argv);
    }
    else
    {
        findCudaDevice(argc, (const char **)argv);
    }

    return true;
}

////////////////////////////////////////////////////////////////////////////////
//! Initialize GL
////////////////////////////////////////////////////////////////////////////////
bool
initGL(int *argc, char **argv)
{
    // Create GL context
    glutInit(argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(window_width, window_height);
    iGLUTWindowHandle = glutCreateWindow("CUDA OpenGL post-processing");

    // initialize necessary OpenGL extensions
    glewInit();

    if (! glewIsSupported(
            "GL_VERSION_2_0 "
            "GL_ARB_pixel_buffer_object "
            "GL_EXT_framebuffer_object "
        ))
    {
        printf("ERROR: Support for necessary OpenGL extensions missing.");
        fflush(stderr);
        return false;
    }

    // default initialization
#ifndef USE_TEXTURE_RGBA8UI
    glClearColor(0.5, 0.5, 0.5, 1.0);
#else
    glClearColorIuiEXT(128,128,128,255);
#endif
    glDisable(GL_DEPTH_TEST);

    // viewport
    glViewport(0, 0, window_width, window_height);

    // projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0, (GLfloat)window_width / (GLfloat) window_height, 0.1f, 10.0f);

    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    glEnable(GL_LIGHT0);
    float red[] = { 1.0f, 0.1f, 0.1f, 1.0f };
    float white[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0f);

    SDK_CHECK_ERROR_GL();

    return true;
}


text:
require 'grep/filter/default'
require 'grep/filter/after_context'

module Grep
  module Filter
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace Speedioc.Registration.Core
{
	/// <summary>
	/// Implemented by classes that represent a property to be
	/// set after an instance of the registered type is created.
	/// </summary>
	/// <seealso cref="IResolvedProperty"/>
	/// <seealso cref="IValueFactoryProperty"/>
	/// <seealso cref="IValueProperty"/>
	/// <seealso cref="INamedMember"/>
	/// <seealso cref="IMember"/>
	public interface IProperty : INamedMember
	{
	}
}


text:
package berkeleydb

/*
#cgo LDFLAGS: -ldb
#include <db.h>
#include "bdb.h"
*/
import "C"

type Environment struct {
	environ *C.DB_ENV
}

func NewEnvironment() (*Environment, error) {
	var env *C.DB_ENV
	err := C.db_env_create(&env, 0)
	if err > 0 {
		return nil, createError(err)
	}

	return &Environment{env}, nil
}

func (env *Environment) Open(path string, flags C.u_int32_t, fileMode int) error {
	mode := C.u_int32_t(fileMode)

	err := C.go_env_open(env.environ, C.CString(path), flags, mode)
	return createError(err)
}

func (env *Environment) Close() error {
	err := C.go_env_close(env.environ, 0)
	return createError(err)
}


text:
//
//  LJMusicsViewController.m
//  01-刘静的音乐
//
//  Created by 刘静 on 15/11/2.
//  Copyright © 2015年 liujing.cn. All rights reserved.
//

#import "LJMusicsViewController.h"
#import "LJMusic.h"
#import "UIImage+Circle.h"
#import "LJPlayingViewController.h"
#import "LJMusicTool.h"
@interface LJMusicsViewController ()
/**
 *  所有音乐的数组
 */
//@property(nonatomic,strong)NSArray *musics;
/**
 *  正在播放的控制器
 */
@property(nonatomic,strong)LJPlayingViewController *playingVc;

@end

@implementation LJMusicsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.rowHeight = 80;

}

#pragma mark - 懒加载
//-(NSArray *)musics{
//    if (_musics == nil) {
//        self.musics =[LJMusic objectArrayWithFilename:@"Musics.plist"];
//    }
//
//    return _musics;
//}

-(LJPlayingViewController *)playingVc{
    if (_playingVc == nil) {

        _playingVc = [[LJPlayingViewController alloc]init];
    }

    return _playingVc;

}

#pragma mark - Table view data source
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// 1. 让cell变为不选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    LJMusic *music = [LJMusicTool musics][indexPath.row];
//    self.playingVc.music = music;

    [LJMusicTool setPlayingMusic:music];

    // 2. 弹出控制器
    [self.playingVc show];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [LJMusicTool musics].count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *ID = @"MusicCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];

    }

    // 1.取出模型对象
    LJMusic *music = [LJMusicTool musics][indexPath.row];

    // 2.给cell设置数据
    cell.imageView.image = [UIImage circleImageWithName:music.singerIcon borderWidth:3.0 borderColor:[UIColor purpleColor]];
    cell.textLabel.text = music.name;
    cell.detailTextLabel.text = music.singer;

    return cell;

}

@end


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/google/apis-client-generator/
 * (build: 2022-02-10 02:07:51 UTC)
 * on 2022-02-10 at 02:08:18 UTC
 * Modify at your own risk.
 */

package com.google.api.services.businessmessages.v1.model;

/**
 * Details for authentication via OAuth.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Business Messages API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class BusinessMessagesAuthenticationRequestOauth extends com.google.api.client.json.GenericJson {

  /**
   * Required. The [ID](https://www.oauth.com/oauth2-servers/client-registration/client-id-secret/)
   * of the application that asks for authorization.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String clientId;

  /**
   * Required. The [code challenge](https://tools.ietf.org/html/rfc7636#section-4.2) used to
   * exchange access tokens.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String codeChallenge;

  /**
   * Optional. The [code challenge method](https://www.oauth.com/oauth2-servers/pkce/authorization-
   * request/) used to generate the code challenge. If this parameter is omitted, the server assumes
   * `plain`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String codeChallengeMethod;

  /**
   * Required. An array that specifies the [scopes](https://oauth.net/2/scope/) of the request.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> scopes;

  /**
   * Required. The [ID](https://www.oauth.com/oauth2-servers/client-registration/client-id-secret/)
   * of the application that asks for authorization.
   * @return value or {@code null} for none
   */
  public java.lang.String getClientId() {
    return clientId;
  }

  /**
   * Required. The [ID](https://www.oauth.com/oauth2-servers/client-registration/client-id-secret/)
   * of the application that asks for authorization.
   * @param clientId clientId or {@code null} for none
   */
  public BusinessMessagesAuthenticationRequestOauth setClientId(java.lang.String clientId) {
    this.clientId = clientId;
    return this;
  }

  /**
   * Required. The [code challenge](https://tools.ietf.org/html/rfc7636#section-4.2) used to
   * exchange access tokens.
   * @return value or {@code null} for none
   */
  public java.lang.String getCodeChallenge() {
    return codeChallenge;
  }

  /**
   * Required. The [code challenge](https://tools.ietf.org/html/rfc7636#section-4.2) used to
   * exchange access tokens.
   * @param codeChallenge codeChallenge or {@code null} for none
   */
  public BusinessMessagesAuthenticationRequestOauth setCodeChallenge(java.lang.String codeChallenge) {
    this.codeChallenge = codeChallenge;
    return this;
  }

  /**
   * Optional. The [code challenge method](https://www.oauth.com/oauth2-servers/pkce/authorization-
   * request/) used to generate the code challenge. If this parameter is omitted, the server assumes
   * `plain`.
   * @return value or {@code null} for none
   */
  public java.lang.String getCodeChallengeMethod() {
    return codeChallengeMethod;
  }

  /**
   * Optional. The [code challenge method](https://www.oauth.com/oauth2-servers/pkce/authorization-
   * request/) used to generate the code challenge. If this parameter is omitted, the server assumes
   * `plain`.
   * @param codeChallengeMethod codeChallengeMethod or {@code null} for none
   */
  public BusinessMessagesAuthenticationRequestOauth setCodeChallengeMethod(java.lang.String codeChallengeMethod) {
    this.codeChallengeMethod = codeChallengeMethod;
    return this;
  }

  /**
   * Required. An array that specifies the [scopes](https://oauth.net/2/scope/) of the request.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getScopes() {
    return scopes;
  }

  /**
   * Required. An array that specifies the [scopes](https://oauth.net/2/scope/) of the request.
   * @param scopes scopes or {@code null} for none
   */
  public BusinessMessagesAuthenticationRequestOauth setScopes(java.util.List<java.lang.String> scopes) {
    this.scopes = scopes;
    return this;
  }

  @Override
  public BusinessMessagesAuthenticationRequestOauth set(String fieldName, Object value) {
    return (BusinessMessagesAuthenticationRequestOauth) super.set(fieldName, value);
  }

  @Override
  public BusinessMessagesAuthenticationRequestOauth clone() {
    return (BusinessMessagesAuthenticationRequestOauth) super.clone();
  }

}


text:
FastFsDirectory::FastFsDirectory( const std::string& dirPath ) :
    m_Path( dirPath ),
    m_FileMap { }
{
}

FastFsDirectory::~FastFsDirectory() {
}

std::string FastFsDirectory::Path() {
    return m_Path;
}

std::shared_ptr< FastFsFile > FastFsDirectory::OpenFile(const std::string& filename, FileOpenMode mode ) {
    auto file = std::make_shared< FastFsFile >( filename );
    m_FileMap[ filename ] = file;
    return file;
}

bool FastFsDirectory::FileExists( const std::string& filePath ) {
    bool fileExists = m_FileMap.find( filePath ) != m_FileMap.end();
    return fileExists;
}

uint32_t FastFsDirectory::FileCount() {
    return m_FileMap.size();
}

FastFsDirectory& FastFsDirectory::operator=( FastFsDirectory other ) {
    m_Path = other.m_Path;
    m_FileMap = other.m_FileMap;
    return *this;
}

bool FastFsDirectory::operator==( const FastFsDirectory& other ) const {
    return ( m_Path == other.m_Path );
}

bool FastFsDirectory::operator!= ( const FastFsDirectory& other ) const {
    return !operator==( other );
}


text:
/**
 * Forge SDK
 * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk's expertise in design and engineering.
 *
 * Contact: forge.help@autodesk.com
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 * 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.
 */

module.exports = (function () {
  'use strict';

  var ApiClient = require('../ApiClient');

  /**
   * The ObjectFullDetailsDeltas model module.
   * @module model/ObjectFullDetailsDeltas
   */

  /**
   * Constructs a ObjectFullDetailsDeltas from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/ObjectFullDetailsDeltas} obj Optional instance to populate.
   * @return {module:model/ObjectFullDetailsDeltas} The populated ObjectFullDetailsDeltas instance.
   */
  var constructFromObject = function (data, obj) {
    if (data) {
      obj = obj || new exports();

      if (data.hasOwnProperty('position')) {
        obj.position = ApiClient.convertToType(data.position, 'Integer');
      }
      if (data.hasOwnProperty('sha1')) {
        obj.sha1 = ApiClient.convertToType(data.sha1, 'String');
      }
    }
    return obj;
  };

  /**
   * Constructs a new ObjectFullDetailsDeltas.
   * @alias module:model/ObjectFullDetailsDeltas
   * @class
   * @param {Object} theData The plain JavaScript object bearing properties of interest.
   * @param {module:model/ObjectFullDetailsDeltas} obj Optional instance to populate.
   */
  var exports = function (theData, obj) {
    var _this = this;

    return constructFromObject(theData, obj || _this);
  };

  /**
   * Constructs a ObjectFullDetailsDeltas from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/ObjectFullDetailsDeltas} obj Optional instance to populate.
   * @return {module:model/ObjectFullDetailsDeltas} The populated ObjectFullDetailsDeltas instance.
   */
  exports.constructFromObject = constructFromObject;

  /**
   * @member {Integer} position
   */
  exports.prototype.position = undefined;
  /**
   * @member {String} sha1
   */
  exports.prototype.sha1 = undefined;

  return exports;
}());


text:
class IOTorch
{
  private:
  void error();

  public:
  void loadData(string file,  real ***data_, real **y_, int &l, int &w, bool bin, int max_load, bool target=true);
  void loadData(string file, sreal ***data_, real **y_, int &l, int &w, bool bin, int max_load, bool target=true);
  void saveData(string file,  real  **data,  real  *y,  int  l, int  w, bool bin, int max_save, bool target=true);
  void saveData(string file, sreal  **data,  real  *y,  int  l, int  w, bool bin, int max_save, bool target=true);
};

#endif


text:
import React from 'react';
import TestAction from '../../action/TestAction';
import TestStore from '../../store/TestStore';

let styles = {
    testInput: {
            padding: '10px',
            border: '1px solid',
            width: '50%',
            textAlign: 'center',
            margin: '20px',
            fontSize: '0.6em'
        }
    }

// 项目列表
const TextComponent = React.createClass({

    getInitialState() {
        return {

        };
    },

    changeTxt(e){
        let val = e.target.value;
        TestAction.change(val);
    },

    render(){

        return (
            <div>
                <input style={styles.testInput} type="text" ref="test-input" onChange={this.changeTxt} />
            </div>
        );
    }
});

module.exports = TextComponent;


text:
<?php

namespace Ticketmatic\Test\Endpoints\Settings\Ticketsales;

use Ticketmatic\Client;
use Ticketmatic\Endpoints\Settings\Ticketsales\Orderfees;
use Ticketmatic\Model\OrderFee;
use Ticketmatic\Model\OrderFeeQuery;

class OrderfeesTest extends \PHPUnit_Framework_TestCase {

    public function testCreateAndDelete() {
        $accountcode = $_SERVER["TM_TEST_ACCOUNTCODE"];
        $accesskey = $_SERVER["TM_TEST_ACCESSKEY"];
        $secretkey = $_SERVER["TM_TEST_SECRETKEY"];
        $client = new Client($accountcode, $accesskey, $secretkey);

        $orderfee = Orderfees::create($client, array(
            "name" => "Order fee test",
            "rule" => array(
                "auto" => array(
                    array(
                        "deliveryscenarioids" => array(
                            1,
                        ),
                        "paymentscenarioids" => array(
                            1,
                        ),
                        "saleschannelids" => array(
                            1,
                        ),
                        "status" => "fixedfee",
                        "value" => 1,
                    ),
                ),
            ),
            "typeid" => 2401,
        ));

        $this->assertNotEquals(0, $orderfee->id);
        $this->assertEquals(2401, $orderfee->typeid);
        $this->assertEquals("Order fee test", $orderfee->name);

        $orderfeescript = Orderfees::create($client, array(
            "name" => "Order fee script test",
            "rule" => array(
                "context" => array(
                    array(
                        "cacheable" => true,
                        "key" => "test",
                        "query" => "select 27 as nbroftickets",
                    ),
                ),
                "script" => "return 2;",
            ),
            "typeid" => 2402,
        ));

        $this->assertNotEquals(0, $orderfeescript->id);
        $this->assertEquals(2402, $orderfeescript->typeid);
        $this->assertEquals("Order fee script test", $orderfeescript->name);
        $this->assertEquals("return 2;", $orderfeescript->rule->script);
        $this->assertEquals("test", $orderfeescript->rule->context[0]->key);
        $this->assertEquals("select 27 as nbroftickets", $orderfeescript->rule->context[0]->query);

        $list = Orderfees::getlist($client, null);

        $this->assertGreaterThan(1, count($list->data));

        Orderfees::delete($client, $orderfee->id);

        Orderfees::delete($client, $orderfeescript->id);

    }

}


text:
/**
 * Created by azu on 2014/02/20.
 * LICENSE : MIT
 */
var cheerio = require('cheerio');
var fs = require("fs");
var path = require("path");
var FS = require("q-io/fs");
var Promise = require("bluebird");
function $rizeFromFilePath(path) {
    var contents = fs.readFileSync(path, "utf-8");
    $ = cheerio.load(contents);
    return $;
}

function html2json(filePath) {
    var baseDir = path.dirname(filePath);
    var baseDirArray = baseDir.split(path.sep);
    var month = parseInt(baseDirArray.pop(), 10),
        year = parseInt(baseDirArray.pop(), 10);
    var indexDate = new Date(year, month, 1);// 日付決められないので1日にする
    var $ = $rizeFromFilePath(filePath);
    var array = [];
    $('blockquote').each(function (index, ele) {
        var $blockquote = $(this);
        var $p = $blockquote.next();
        var title = $blockquote.attr("title");
        var URL = $blockquote.attr("cite");
        var contents = $p.html().replace(/<br>/g, "\n");
        array.push({
            "title": title,
            "url": URL,
            "content": contents,
            "date": indexDate
        });
    });
    return {
        "list" : array
    };
}

function makeIndexJSONPath(filePath) {
    return path.join(path.dirname(filePath), "index.json");
}
var filterNonExistJSON = function (fileList) {
    var invert = function (value) {
        return !value;
    }
    var promiseMap = Promise.filter(fileList, function (filePath) {
        return FS.exists(path.join(path.dirname(filePath), "index.json")).then(invert);
    });
    return Promise.all(promiseMap);
};
FS.listTree("../../data/", function isIndexHTML(filePath, stat) {
    if (stat.isDirectory()) {
        return false;
    }
    return path.basename(filePath) === "index.html";
}).then(filterNonExistJSON).then(function (fileList) {
    var promises = fileList.map(function (filePath) {
        return Promise.cast(html2json(filePath)).then(function (content) {
            return FS.write(makeIndexJSONPath(filePath), JSON.stringify(content, null, 4));
        });
    });
    Promise.all(promises).then(function (res) {
        console.log("All Finish");
    });
})


text:
Mat GetWholeHistLBPWay(Mat imgOrg)
{
	cvtColor(imgOrg, imgOrg, CV_BGR2GRAY);
	resize(imgOrg, imgOrg, Size(130, 150));

	int XStep = 18;
	int YStep = 21;

	Mat TempImage, FinalHist = Mat::zeros(59, 49, CV_64F);
	vector<double> TempHist;

	int j = 0;
	for (int YLocation = 0; YLocation < 7; YLocation++)
	for (int XLocation = 0; XLocation < 7; XLocation++)
	{
		TempImage = imgOrg(cv::Rect(XLocation*XStep, YLocation*YStep, XStep, YStep));
		TempHist = GetPartHistLBPWay(TempImage);

		for (int i = 0; i < TempHist.size(); i++)
		{
			FinalHist.at<double>(i, j) = TempHist[i];
		};
		j++;
	}
	//FinalHist.t();
	FinalHist.reshape(1, 1);

	return FinalHist;
}

vector<double> GetPartHistLBPWay(Mat imgOrg)
{
	int rad = 2;
	int pts = 8;
	std::string mapping = "u2";
	bool outputHist = 1, normalizeHist = 1;

	imgOrg.convertTo(imgOrg, CV_64F);

	Mat lbpImg = Mat(imgOrg.size(), CV_8UC1, Scalar(0));

	// Create an LBP instance of type "mapping" using "pts" support points
	LBP lbp(pts, LBP::strToType(mapping));

	for (int i = 0; i < imgOrg.channels(); i++) {
		// Copy channel i
		Mat img(imgOrg.size(), imgOrg.depth(), 1);
		const int from_to1[] = { i, 0 };
		mixChannels(&imgOrg, 1, &img, 1, from_to1, 1);

		// Calculate the descriptor
		lbp.calcLBP(img, rad, true);

		// Copy lbp image
		const int from_to2[] = { 0, i };
		Mat tmpImg = lbp.getLBPImage();
		mixChannels(&tmpImg, 1, &lbpImg, 1, from_to2, 1);
	}

	vector<double> part_hist = lbp.calcHist().getHist(normalizeHist);

	return part_hist;

}


text:
import test from 'ava';

import { internals } from '../ViewPlugin';

const style = {
  want: 'want_hashed'
};

test('joinClasses', t => {
  t.is('other want_hashed classes', internals.joinClasses(style, 'other want classes'));
  t.is('other want_hashed classes', internals.joinClasses(style, [{ other: true, want: true }, null, ' ', 'classes']));
  t.is('other want_hashed classes', internals.joinClasses(style, { other: true, want: 1, classes: [] }));
});


text:
var _ = require('lodash');
var BaseModel = require("./../../../baseModel");

function thisModule() {
    var cultureCodeSetter = function (value) {
        var culture = {};
        culture.language = value.substring(0, 2).toLowerCase();
        culture.region = value.substring(3, 5).toLowerCase();
        return {'culture.language': culture.language, 'culture.region': culture.region};
    };

    var model = BaseModel.extend({
            data: {
                /** userId: User-Id generated by device */
                userId: {
                    type: String,
                    maxLength: 32,
                    minLength: 0,
                    public: true,
                    index: true,
                    unique: true,
                    sparse: true,
                    convert: 'upper'
                },
                culture: {
                    language: {
                        type: String,
                        minLength: 2,
                        maxLength: 2,
                        match: /[a-zA-Z]{2}/i,
                        required: true,
                        public: {set: false, get: true}
                    },
                    region: {
                        type: String,
                        minLength: 2,
                        maxLength: 2,
                        match: /[a-zA-Z]{2}/i,
                        required: true,
                        public: {set: false, get: true}
                    },
                    code: {
                        type: String,
                        minLength: 5,
                        maxLength: 5,
                        match: /[a-zA-Z]{2}-[a-zA-Z]{2}/i,
                        required: true,
                        public: {set: true, get: false},
                        virtual: cultureCodeSetter,
                        default: 'de-de'
                    }
                },
                date: {
                    type: Date,
                    default: Date.now()
                },
                appversion: {
                    type: String,
                    required: true,
                    max: 20,
                    min: 1,
                    allow: [2, 3, 19]
                }
            },
            compoundIndexes: [
                {
                    fields: ["userId", "culture.region", "culture.language"],
                    unique: true,
                    sparse: true
                },
                {
                    fields: ["appversion", "date"]
                }
            ]
        },
        {
            disabled: false, // Enable /disable controller
            identity: 'TestModel', // Controller name used in routes, policies and followups
            version: '1.0', // Version number of service
            created: '2014-01-09T19:00:00', // Creation date of controller
            modified: '2017-01-11T21:00:00', // Last modified date of controller
            group: 'mia-js-core', // Group this service to a origin,
            collectionName: 'testModel'
        });

    return model;
};

module.exports = thisModule();


text:
<?php

namespace Blog\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Blog\BlogBundle\Entity\Tag ;
use Blog\BlogBundle\Form\TagType ;

class TagController extends Controller
{

  public function ajouterAction(){

    }

    public function editerAction(Categorie $categorie){

    }

    public function supprimerAction(Categorie $categorie){

    }

}


text:
ARM Trusted Firmware User Guide
===============================

Contents :

1.  Introduction
2.  Host machine requirements
3.  Tools
4.  Building the Trusted Firmware
5.  Obtaining the normal world software
6.  Running the software

1.  Introduction
----------------
This document describes how to build ARM Trusted Firmware and run it with a
tested set of other software components using defined configurations on ARM
Fixed Virtual Platform (FVP) models. It is possible to use other software
components, configurations and platforms but that is outside the scope of this
document.

This document should be used in conjunction with the [Firmware Design].

2.  Host machine requirements
-----------------------------

The minimum recommended machine specification for building the software and
running the FVP models is a dual-core processor running at 2GHz with 12GB of
RAM.  For best performance, use a machine with a quad-core processor running at
2.6GHz with 16GB of RAM.

The software has been tested on Ubuntu 12.04.02 (64-bit).  Packages used
for building the software were installed from that distribution unless
otherwise specified.

3.  Tools
---------

The following tools are required to use the ARM Trusted Firmware:

*   `git` package to obtain source code

*   `ia32-libs` package

*   `build-essential` and `uuid-dev` packages for building UEFI and the Firmware
    Image Package(FIP) tool

*   `bc` and `ncurses-dev` packages for building Linux

*   Baremetal GNU GCC tools. Verified packages can be downloaded from [Linaro]
    [Linaro Toolchain]. The rest of this document assumes that the
    `gcc-linaro-aarch64-none-elf-4.8-2013.11_linux.tar.xz` tools are used.

        wget http://releases.linaro.org/13.11/components/toolchain/binaries/gcc-linaro-aarch64-none-elf-4.8-2013.11_linux.tar.xz
        tar -xf gcc-linaro-aarch64-none-elf-4.8-2013.11_linux.tar.xz

*   The Device Tree Compiler (DTC) included with Linux kernel 3.13 is used
    to build the Flattened Device Tree (FDT) source files (`.dts` files)
    provided with this software.

*   (Optional) For debugging, ARM [Development Studio 5 (DS-5)][DS-5] v5.17.

4.  Building the Trusted Firmware
---------------------------------

To build the software for the FVPs, follow these steps:

1.  Clone the ARM Trusted Firmware repository from GitHub:

        git clone https://github.com/ARM-software/arm-trusted-firmware.git

2.  Change to the trusted firmware directory:

        cd arm-trusted-firmware

3.  Set the compiler path, specify a Non-trusted Firmware image (BL3-3) and
    build:

        CROSS_COMPILE=<path-to-aarch64-gcc>/bin/aarch64-none-elf- \
        BL33=<path-to>/<bl33_image>                               \
        make PLAT=fvp all fip

    By default this produces a release version of the build. To produce a debug
    version instead, refer to the "Debugging options" section below. UEFI can be
    used as the BL3-3 image, refer to the "Obtaining the normal world software"
    section below.

    The build process creates products in a `build` directory tree, building
    the objects and binaries for each boot loader stage in separate
    sub-directories.  The following boot loader binary files are created from
    the corresponding ELF files:

    *   `build/<platform>/<build-type>/bl1.bin`
    *   `build/<platform>/<build-type>/bl2.bin`
    *   `build/<platform>/<build-type>/bl31.bin`

    ... where `<platform>` currently defaults to `fvp` and `<build-type>` is
    either `debug` or `release`. A Firmare Image Package(FIP) will be created as
    part of the build. It contains all boot loader images except for `bl1.bin`.

    *   `build/<platform>/<build-type>/fip.bin`

    For more information on FIPs, see the "Firmware Image Package" section in
    the [Firmware Design].

4.  Copy the `bl1.bin` and `fip.bin` binary files to the directory from which
    the FVP will be launched. Symbolic links of the same names may be created
    instead.

5.  (Optional) Build products for a specific build variant can be removed using:

        make DEBUG=<D> PLAT=fvp clean

    ... where `<D>` is `0` or `1`, as specified when building.

    The build tree can be removed completely using:

        make realclean

### Creating a Firmware Image Package

FIPs are automatically created as part of the build instructions described in
the previous section. It is also possible to independently build the FIP
creation tool and FIPs if required. To do this, follow these steps:

Build the tool:

    make -C tools/fip_create

It is recommended to remove the build artifacts before rebuilding:

    make -C tools/fip_create clean

Create a Firmware package that contains existing FVP BL2 and BL3-1 images:

    # fip_create --help to print usage information
    # fip_create <fip_name> <images to add> [--dump to show result]
    ./tools/fip_create/fip_create fip.bin --dump \
       --bl2 build/fvp/debug/bl2.bin --bl31 build/fvp/debug/bl31.bin

     Firmware Image Package ToC:
    ---------------------------
    - Trusted Boot Firmware BL2: offset=0x88, size=0x81E8
      file: 'build/fvp/debug/bl2.bin'
    - EL3 Runtime Firmware BL3-1: offset=0x8270, size=0xC218
      file: 'build/fvp/debug/bl31.bin'
    ---------------------------
    Creating "fip.bin"

View the contents of an existing Firmware package:

    ./tools/fip_create/fip_create fip.bin --dump

     Firmware Image Package ToC:
    ---------------------------
    - Trusted Boot Firmware BL2: offset=0x88, size=0x81E8
    - EL3 Runtime Firmware BL3-1: offset=0x8270, size=0xC218
    ---------------------------

Existing package entries can be individially updated:

    # Change the BL2 from Debug to Release version
    ./tools/fip_create/fip_create fip.bin --dump \
      --bl2 build/fvp/release/bl2.bin

    Firmware Image Package ToC:
    ---------------------------
    - Trusted Boot Firmware BL2: offset=0x88, size=0x7240
      file: 'build/fvp/release/bl2.bin'
    - EL3 Runtime Firmware BL3-1: offset=0x72C8, size=0xC218
    ---------------------------
    Updating "fip.bin"

### Debugging options

To compile a debug version and make the build more verbose use

    CROSS_COMPILE=<path-to-aarch64-gcc>/bin/aarch64-none-elf- \
    BL33=<path-to>/<bl33_image>                               \
    make PLAT=fvp DEBUG=1 V=1 all fip

AArch64 GCC uses DWARF version 4 debugging symbols by default. Some tools (for
example DS-5) might not support this and may need an older version of DWARF
symbols to be emitted by GCC. This can be achieved by using the
`-gdwarf-<version>` flag, with the version being set to 2 or 3. Setting the
version to 2 is recommended for DS-5 versions older than 5.16.

When debugging logic problems it might also be useful to disable all compiler
optimizations by using `-O0`.

NOTE: Using `-O0` could cause output images to be larger and base addresses
might need to be recalculated (see the later memory layout section).

Extra debug options can be passed to the build system by setting `CFLAGS`:

    CFLAGS='-O0 -gdwarf-2'                                    \
    CROSS_COMPILE=<path-to-aarch64-gcc>/bin/aarch64-none-elf- \
    BL33=<path-to>/<bl33_image>                               \
    make PLAT=fvp DEBUG=1 V=1 all fip

NOTE: The Foundation FVP does not provide a debugger interface.

### Checking source code style

When making changes to the source for submission to the project, the source
must be in compliance with the Linux style guide, and to assist with this check
the project Makefile contains two targets, which both utilise the checkpatch.pl
script that ships with the Linux source tree.

To check the entire source tree, you must first download a copy of checkpatch.pl
(or the full Linux source), set the CHECKPATCH environment variable to point to
the script and build the target checkcodebase:

    make CHECKPATCH=../linux/scripts/checkpatch.pl checkcodebase

To just check the style on the files that differ between your local branch and
the remote master, use:

    make CHECKPATCH=../linux/scripts/checkpatch.pl checkpatch

If you wish to check your patch against something other than the remote master,
set the BASE_COMMIT variable to your desired branch.  By default, BASE_COMMIT
is set to 'origin/master'.

5.  Obtaining the normal world software
---------------------------------------

### Obtaining EDK2

Potentially any kind of non-trusted firmware may be used with the ARM Trusted
Firmware but the software has only been tested with the EFI Development Kit 2
(EDK2) open source implementation of the UEFI specification.

Clone the [EDK2 source code][EDK2] from GitHub. This version supports the Base
and Foundation FVPs:

    git clone -n https://github.com/tianocore/edk2.git
    cd edk2
    git checkout c1cdcab9526506673b882017845a043cead8bc69

To build the software to be compatible with Foundation and Base FVPs, follow
these steps:

1.  Copy build config templates to local workspace

        # in edk2/
        . edksetup.sh

2.  Build the EDK2 host tools

        make -C BaseTools clean
        make -C BaseTools

3.  Build the EDK2 software

        CROSS_COMPILE=<absolute-path-to-aarch64-gcc>/bin/aarch64-none-elf- \
        make -f ArmPlatformPkg/Scripts/Makefile EDK2_ARCH=AARCH64          \
        EDK2_DSC=ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-FVP-AArch64.dsc \
        EDK2_TOOLCHAIN=ARMGCC EDK2_MACROS="-n 6 -D ARM_FOUNDATION_FVP=1"

    The EDK2 binary for use with the ARM Trusted Firmware can then be found
    here:

        Build/ArmVExpress-FVP-AArch64/DEBUG_ARMGCC/FV/FVP_AARCH64_EFI.fd

    This will build EDK2 for the default settings as used by the FVPs. The EDK2
    binary `FVP_AARCH64_EFI.fd` should be specified as `BL33` in in the `make`
    command line when building the Trusted Firmware. See the "Building the
    Trusted Firmware" section above.

4.  (Optional) To boot Linux using a VirtioBlock file-system, the command line
    passed from EDK2 to the Linux kernel must be modified as described in the
    "Obtaining a root file-system" section below.

5.  (Optional) If legacy GICv2 locations are used, the EDK2 platform description
    must be updated. This is required as EDK2 does not support probing for the
    GIC location. To do this, first clean the EDK2 build directory.

        make -f ArmPlatformPkg/Scripts/Makefile EDK2_ARCH=AARCH64          \
        EDK2_DSC=ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-FVP-AArch64.dsc \
        EDK2_TOOLCHAIN=ARMGCC clean

    Then rebuild EDK2 as described in step 3, using the following flag:

        -D ARM_FVP_LEGACY_GICV2_LOCATION=1

    Finally rebuild the Trusted Firmware to generate a new FIP using the
    instructions in the "Building the Trusted Firmware" section.

### Obtaining a Linux kernel

The software has been verified using a Linux kernel based on version 3.13.
Patches have been applied in order to enable the CPU idle feature.

Preparing a Linux kernel for use on the FVPs with CPU idle support can
be done as follows (GICv2 support only):

1.  Clone Linux:

        git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

    Not all CPU idle features are included in the mainline kernel yet. To
    use these, add the patches from Sudeep Holla's kernel, based on
    Linux 3.13:

        cd linux
        git remote add -f --tags arm64_idle_genfw_ref git://linux-arm.org/linux-skn.git
        git checkout -b cpuidle arm64_idle_genfw_ref

2.  Build with the Linaro GCC tools.

        # in linux/
        make mrproper
        make ARCH=arm64 defconfig

        # Enable CPU idle
        make ARCH=arm64 menuconfig
        # CPU Power Management ---> CPU Idle ---> [*] CPU idle PM support
        # CPU Power Management ---> CPU Idle ---> ARM64 CPU Idle Drivers ---> [*] Generic ARM64 CPU idle Driver

        CROSS_COMPILE=<path-to-aarch64-gcc>/bin/aarch64-none-elf- \
        make -j6 ARCH=arm64

3.  Copy the Linux image `arch/arm64/boot/Image` to the working directory from
    where the FVP is launched. Alternatively a symbolic link may be used.

### Obtaining the Flattened Device Trees

Depending on the FVP configuration and Linux configuration used, different
FDT files are required. FDTs for the Foundation and Base FVPs can be found in
the Trusted Firmware source directory under `fdts/`. The Foundation FVP has a
subset of the Base FVP components. For example, the Foundation FVP lacks CLCD
and MMC support, and has only one CPU cluster.

*   `fvp-base-gicv2-psci.dtb`

    (Default) For use with both AEMv8 and Cortex-A57-A53 Base FVPs with
    Base memory map configuration.

*   `fvp-base-gicv2legacy-psci.dtb`

    For use with AEMv8 Base FVP with legacy VE GIC memory map configuration.

*   `fvp-base-gicv3-psci.dtb`

    For use with both AEMv8 and Cortex-A57-A53 Base FVPs with Base memory map
    configuration and Linux GICv3 support.

*   `fvp-foundation-gicv2-psci.dtb`

    (Default) For use with Foundation FVP with Base memory map configuration.

*   `fvp-foundation-gicv2legacy-psci.dtb`

    For use with Foundation FVP with legacy VE GIC memory map configuration.

*   `fvp-foundation-gicv3-psci.dtb`

    For use with Foundation FVP with Base memory map configuration and Linux
    GICv3 support.

Copy the chosen FDT blob as `fdt.dtb` to the directory from which the FVP
is launched. Alternatively a symbolic link may be used.

### Obtaining a root file-system

To prepare a Linaro LAMP based Open Embedded file-system, the following
instructions can be used as a guide. The file-system can be provided to Linux
via VirtioBlock or as a RAM-disk. Both methods are described below.

#### Prepare VirtioBlock

To prepare a VirtioBlock file-system, do the following:

1.  Download and unpack the disk image.

    NOTE: The unpacked disk image grows to 2 GiB in size.

        wget http://releases.linaro.org/14.01/openembedded/aarch64/vexpress64-openembedded_lamp-armv8-gcc-4.8_20140126-596.img.gz
        gunzip vexpress64-openembedded_lamp-armv8-gcc-4.8_20140126-596.img.gz

2.  Make sure the Linux kernel has Virtio support enabled using
    `make ARCH=arm64 menuconfig`.

        Device Drivers  ---> Virtio drivers  ---> <*> Platform bus driver for memory mapped virtio devices
        Device Drivers  ---> [*] Block devices  --->  <*> Virtio block driver
        File systems    ---> <*> The Extended 4 (ext4) filesystem

    If some of these configurations are missing, enable them, save the kernel
    configuration, then rebuild the kernel image using the instructions
    provided in the section "Obtaining a Linux kernel".

3.  Change the Kernel command line to include `root=/dev/vda2`. This can either
    be done in the EDK2 boot menu or in the platform file. Editing the platform
    file and rebuilding EDK2 will make the change persist. To do this:

    1.  In EDK2, edit the following file:

            ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-FVP-AArch64.dsc

    2.  Add `root=/dev/vda2` to:

            gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"<Other default options>"

    3.  Remove the entry:

            gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath|""

    4.  Rebuild EDK2 (see "Obtaining UEFI" section above).

4.  The file-system image file should be provided to the model environment by
    passing it the correct command line option. In the FVPs the following
    option should be provided in addition to the ones described in the
    "Running the software" section below.

    NOTE: A symbolic link to this file cannot be used with the FVP; the path
    to the real file must be provided.

    On the Base FVPs:
        -C bp.virtioblockdevice.image_path="<path-to>/<file-system-image>"

    On the Foundation FVP:
        --block-device="<path-to>/<file-system-image>"

5.  Ensure that the FVP doesn't output any error messages. If the following
    error message is displayed:

        ERROR: BlockDevice: Failed to open "<path-to>/<file-system-image>"!

    then make sure the path to the file-system image in the model parameter is
    correct and that read permission is correctly set on the file-system image
    file.

#### Prepare RAM-disk

To prepare a RAM-disk root file-system, do the following:

1.  Download the file-system image:

        wget http://releases.linaro.org/14.01/openembedded/aarch64/linaro-image-lamp-genericarmv8-20140127-635.rootfs.tar.gz

2.  Modify the Linaro image:

        # Prepare for use as RAM-disk. Normally use MMC, NFS or VirtioBlock.
        # Be careful, otherwise you could damage your host file-system.
        mkdir tmp; cd tmp
        sudo sh -c "zcat ../linaro-image-lamp-genericarmv8-20140127-635.rootfs.tar.gz | cpio -id"
        sudo ln -s sbin/init .
        sudo sh -c "echo 'devtmpfs /dev devtmpfs mode=0755,nosuid 0 0' >> etc/fstab"
        sudo sh -c "find . | cpio --quiet -H newc -o | gzip -3 -n > ../filesystem.cpio.gz"
        cd ..

3.  Copy the resultant `filesystem.cpio.gz` to the directory where the FVP is
    launched from. Alternatively a symbolic link may be used.

6.  Running the software
------------------------

This version of the ARM Trusted Firmware has been tested on the following ARM
FVPs (64-bit versions only).

*   `Foundation_v8` (Version 2.0, Build 0.8.5206)
*   `FVP_Base_AEMv8A-AEMv8A` (Version 5.4, Build 0.8.5405)
*   `FVP_Base_Cortex-A57x4-A53x4` (Version 5.4, Build 0.8.5405)
*   `FVP_Base_Cortex-A57x1-A53x1` (Version 5.4, Build 0.8.5405)

NOTE: The software will not work on Version 1.0 of the Foundation FVP.
The commands below would report an `unhandled argument` error in this case.

Please refer to the FVP documentation for a detailed description of the model
parameter options. A brief description of the important ones that affect the
ARM Trusted Firmware and normal world software behavior is provided below.

The Foundation FVP is a cut down version of the AArch64 Base FVP. It can be
downloaded for free from [ARM's website][ARM FVP website].

### Running on the Foundation FVP

The following `Foundation_v8` parameters should be used to boot Linux with
4 CPUs using the ARM Trusted Firmware.

NOTE: Using the `--block-device` parameter is not necessary if a Linux RAM-disk
file-system is used (see the "Obtaining a File-system" section above).

NOTE: The `--data="<path to FIP binary>"@0x8000000` parameter is used to load a
Firmware Image Package at the start of NOR FLASH0 (see the "Building the
Trusted Firmware" section above).

    <path-to>/Foundation_v8                   \
    --cores=4                                 \
    --no-secure-memory                        \
    --visualization                           \
    --gicv3                                   \
    --data="<path-to>/<bl1-binary>"@0x0       \
    --data="<path-to>/<FIP-binary>"@0x8000000 \
    --block-device="<path-to>/<file-system-image>"

The default use-case for the Foundation FVP is to enable the GICv3 device in
the model but use the GICv2 FDT, in order for Linux to drive the GIC in GICv2
emulation mode.

The memory mapped addresses `0x0` and `0x8000000` correspond to the start of
trusted ROM and NOR FLASH0 respectively.

### Running on the AEMv8 Base FVP

The following `FVP_Base_AEMv8A-AEMv8A` parameters should be used to boot Linux
with 8 CPUs using the ARM Trusted Firmware.

NOTE: Using `cache_state_modelled=1` makes booting very slow. The software will
still work (and run much faster) without this option but this will hide any
cache maintenance defects in the software.

NOTE: Using the `-C bp.virtioblockdevice.image_path` parameter is not necessary
if a Linux RAM-disk file-system is used (see the "Obtaining a root file-system"
section above).

NOTE: The `-C bp.flashloader0.fname` parameter is used to load a Firmware Image
Package at the start of NOR FLASH0 (see the "Building the Trusted Firmware"
section above).

NOTE: Setting the `-C bp.secure_memory` parameter to `1` is only supported on
FVP versions 5.4 and newer. Setting this parameter to `0` is also supported.
The `-C bp.tzc_400.diagnostics=1` parameter is optional. It instructs the FVP to
provide some helpful information if a secure memory violation occurs.

    <path-to>/FVP_Base_AEMv8A-AEMv8A                       \
    -C pctl.startup=0.0.0.0                                \
    -C bp.secure_memory=1                                  \
    -C bp.tzc_400.diagnostics=1                            \
    -C cluster0.NUM_CORES=4                                \
    -C cluster1.NUM_CORES=4                                \
    -C cache_state_modelled=1                              \
    -C bp.pl011_uart0.untimed_fifos=1                      \
    -C bp.secureflashloader.fname="<path-to>/<bl1-binary>" \
    -C bp.flashloader0.fname="<path-to>/<FIP-binary>"      \
    -C bp.virtioblockdevice.image_path="<path-to>/<file-system-image>"

### Running on the Cortex-A57-A53 Base FVP

The following `FVP_Base_Cortex-A57x4-A53x4` model parameters should be used to
boot Linux with 8 CPUs using the ARM Trusted Firmware.

NOTE: Using `cache_state_modelled=1` makes booting very slow. The software will
still work (and run much faster) without this option but this will hide any
cache maintenance defects in the software.

NOTE: Using the `-C bp.virtioblockdevice.image_path` parameter is not necessary
if a Linux RAM-disk file-system is used (see the "Obtaining a root file-system"
section above).

NOTE: The `-C bp.flashloader0.fname` parameter is used to load a Firmware Image
Package at the start of NOR FLASH0 (see the "Building the Trusted Firmware"
section above).

NOTE: Setting the `-C bp.secure_memory` parameter to `1` is only supported on
FVP versions 5.4 and newer. Setting this parameter to `0` is also supported.
The `-C bp.tzc_400.diagnostics=1` parameter is optional. It instructs the FVP to
provide some helpful information if a secure memory violation occurs.

    <path-to>/FVP_Base_Cortex-A57x4-A53x4                  \
    -C pctl.startup=0.0.0.0                                \
    -C bp.secure_memory=1                                  \
    -C bp.tzc_400.diagnostics=1                            \
    -C cache_state_modelled=1                              \
    -C bp.pl011_uart0.untimed_fifos=1                      \
    -C bp.secureflashloader.fname="<path-to>/<bl1-binary>" \
    -C bp.flashloader0.fname="<path-to>/<FIP-binary>"      \
    -C bp.virtioblockdevice.image_path="<path-to>/<file-system-image>"

### Configuring the GICv2 memory map

The Base FVP models support GICv2 with the default model parameters at the
following addresses. The Foundation FVP also supports these addresses when
configured for GICv3 in GICv2 emulation mode.

    GICv2 Distributor Interface     0x2f000000
    GICv2 CPU Interface             0x2c000000
    GICv2 Virtual CPU Interface     0x2c010000
    GICv2 Hypervisor Interface      0x2c02f000

The AEMv8 Base FVP can be configured to support GICv2 at addresses
corresponding to the legacy (Versatile Express) memory map as follows. These are
the default addresses when using the Foundation FVP in GICv2 mode.

    GICv2 Distributor Interface     0x2c001000
    GICv2 CPU Interface             0x2c002000
    GICv2 Virtual CPU Interface     0x2c004000
    GICv2 Hypervisor Interface      0x2c006000

The choice of memory map is reflected in the build variant field (bits[15:12])
in the `SYS_ID` register (Offset `0x0`) in the Versatile Express System
registers memory map (`0x1c010000`).

*   `SYS_ID.Build[15:12]`

    `0x1` corresponds to the presence of the Base GIC memory map. This is the
    default value on the Base FVPs.

*   `SYS_ID.Build[15:12]`

    `0x0` corresponds to the presence of the Legacy VE GIC memory map. This is
    the default value on the Foundation FVP.

This register can be configured as described in the following sections.

NOTE: If the legacy VE GIC memory map is used, then the corresponding FDT and
BL3-3 images should be used.

#### Configuring AEMv8 Foundation FVP GIC for legacy VE memory map

The following parameters configure the Foundation FVP to use GICv2 with the
legacy VE memory map:

    <path-to>/Foundation_v8                   \
    --cores=4                                 \
    --no-secure-memory                        \
    --visualization                           \
    --no-gicv3                                \
    --data="<path-to>/<bl1-binary>"@0x0       \
    --data="<path-to>/<FIP-binary>"@0x8000000 \
    --block-device="<path-to>/<file-system-image>"

Explicit configuration of the `SYS_ID` register is not required.

#### Configuring AEMv8 Base FVP GIC for legacy VE memory map

The following parameters configure the AEMv8 Base FVP to use GICv2 with the
legacy VE memory map. They must added to the parameters described in the
"Running on the AEMv8 Base FVP" section above:

    -C cluster0.gic.GICD-offset=0x1000                  \
    -C cluster0.gic.GICC-offset=0x2000                  \
    -C cluster0.gic.GICH-offset=0x4000                  \
    -C cluster0.gic.GICH-other-CPU-offset=0x5000        \
    -C cluster0.gic.GICV-offset=0x6000                  \
    -C cluster0.gic.PERIPH-size=0x8000                  \
    -C cluster1.gic.GICD-offset=0x1000                  \
    -C cluster1.gic.GICC-offset=0x2000                  \
    -C cluster1.gic.GICH-offset=0x4000                  \
    -C cluster1.gic.GICH-other-CPU-offset=0x5000        \
    -C cluster1.gic.GICV-offset=0x6000                  \
    -C cluster1.gic.PERIPH-size=0x8000                  \
    -C gic_distributor.GICD-alias=0x2c001000            \
    -C bp.variant=0x0

The `bp.variant` parameter corresponds to the build variant field of the
`SYS_ID` register.  Setting this to `0x0` allows the ARM Trusted Firmware to
detect the legacy VE memory map while configuring the GIC.

- - - - - - - - - - - - - - - - - - - - - - - - - -

_Copyright (c) 2013-2014, ARM Limited and Contributors. All rights reserved._

[Firmware Design]:  ./firmware-design.md

[ARM FVP website]:  http://www.arm.com/fvp
[Linaro Toolchain]: http://releases.linaro.org/13.09/components/toolchain/binaries/
[EDK2]:             http://github.com/tianocore/edk2
[DS-5]:             http://www.arm.com/products/tools/software-tools/ds-5/index.php


text:
package docs

import (
	"errors"
	"net/http"

	"github.com/Jeffail/benthos/v3/internal/docs"
	"github.com/gorilla/handlers"
)

// ServerCORS contains configuration for allowing CORS headers.
type ServerCORS struct {
	Enabled        bool     `json:"enabled" yaml:"enabled"`
	AllowedOrigins []string `json:"allowed_origins" yaml:"allowed_origins"`
}

// NewServerCORS returns a new server CORS config with default fields.
func NewServerCORS() ServerCORS {
	return ServerCORS{
		Enabled:        false,
		AllowedOrigins: []string{},
	}
}

// WrapHandler wraps a provided HTTP handler with middleware that enables CORS
// requests (when configured).
func (conf ServerCORS) WrapHandler(handler http.Handler) (http.Handler, error) {
	if !conf.Enabled {
		return handler, nil
	}
	if len(conf.AllowedOrigins) == 0 {
		return nil, errors.New("must specify at least one allowed origin")
	}
	return handlers.CORS(
		handlers.AllowedOrigins(conf.AllowedOrigins),
		handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}),
	)(handler), nil
}

// ServerCORSFieldSpec returns a field spec for an http server CORS component.
func ServerCORSFieldSpec() docs.FieldSpec {
	return docs.FieldAdvanced("cors", "Adds Cross-Origin Resource Sharing headers.").WithChildren(
		docs.FieldBool("enabled", "Whether to allow CORS requests.").HasDefault(false),
		docs.FieldString("allowed_origins", "An explicit list of origins that are allowed for CORS requests.").Array().HasDefault([]string{}),
	).AtVersion("3.63.0")
}


text:
<?php

// Returns page title
function get_page_title() {
    if( is_front_page() )
      echo get_bloginfo( 'name' ) . ' - ' . get_bloginfo( 'description' );
    else if( is_home() )
      echo get_the_title( get_option( 'page_for_posts' ) ) . ' - ' . get_bloginfo( 'name' );
    else
      echo get_the_title() . ' - ' . get_bloginfo( 'name' );
}

// Displays publication date
function ws_posted_on() {
    printf(
        '<time class="entry-date" datetime="%s" pubdate>%s</time>',
        esc_attr( get_the_date( 'c' ) ),
        esc_html( get_the_date( 'j F Y' ) )
    );
}

// Register get_template_part function for blocks
function get_block( $file, $variables = null ) {
	return ws_get_template_part( 'blocks/' . $file, $variables );
}

// Register get_template_part function for the edit button
function get_edit_button() {
	return get_template_part( 'blocks/edit', 'button' );
}

// Register get_template_part function for languages
function get_languages( $class = null ) {
	return ws_get_template_part( 'blocks/languages', [  'CLASS' => $class ] );
}

// Register get_template_part function for favicons
function get_favicons() {
	return get_template_part( 'blocks/favicons' );
}

// Register get_template_part function for offcanvas
function get_offcanvas() {
	return get_template_part( 'blocks/offcanvas' );
}

// Register get_template_part function for socials networks meta
function get_socials_meta() {
	return get_template_part( 'blocks/socials', 'meta' );
}

// Register get_template_part function for socials networks
function get_socials_networks() {
	return get_template_part( 'blocks/socials', 'networks' );
}

// Register get_template_part function for navigation
function get_navigation() {
	return get_template_part( 'blocks/navigation' );
}

// Register get_template_part function for navigation
function get_article() {
	return get_template_part( 'blocks/loop' );
}

// Register get_stylesheet_directory_uri function for assets
function get_asset( $file, $folder = 'images' ) {
  return get_stylesheet_directory_uri() . '/assets/' . $folder . '/' . $file;
}

// Register get_stylesheet_directory_uri function for assets
function the_asset( $file, $folder = 'images' ) {
  echo get_asset( $file, $folder );
}

// Check if the current user is an administrator
function is_user_administrator() {
  return current_user_can( 'administrator' );
}

// Check if the current user is an editor
function is_user_editor() {
  return current_user_can( 'editor' );
}

// Check if the current user is an author
function is_user_author() {
  return current_user_can( 'author' );
}

// Check if the current user is a contributor
function is_user_contributor() {
  return current_user_can( 'contributor' );
}

// Check if the current user is a subscriber
function is_user_subscriber() {
  return current_user_can( 'subscriber' );
}

// Returns the good occurrence size
function get_mosaic_size( $i, $count ) {
  if ( $i >= $count )
    return [2,1];
  $isLast = ( $i === $count - 1 );
  switch( $i % 16 ):
    case 0: case 10: return $isLast ? [12,2] : [8,2];
    case 1: case 11: return $isLast ? [4,2] : [4,1];
    case 2: case 6: case 12: return [4,1];
    case 3: return $isLast ? [12,2] : [4,2];
    case 4: return $isLast ? [8,2] : [8,1];
    case 5: return $isLast ? [8,1] : [4,1];
    case 7: case 15: return [12,1];
    case 8: return $isLast ? [12,1] : [4,1];
    case 9: return [8,1];
    case 13: return $isLast ? [12,1] : [4,2];
    case 14: return [8,2];
  endswitch;
}

// Displays pagination
function get_pagination( $pages = null, $range = 2 ) {

    global $paged, $wp_query;
    $showitems = $range * 2 + 1;

    if ( !$paged )                                        $paged = 1;
    if ( !$pages && !$pages = $wp_query->max_num_pages )  $pages = 1;
    if ( $pages <= 1 )                                    return;

    $output = '
';

    if ( $paged > 2 )             $output .= '
«
';
    if ( $paged > 1 )             $output .= '
‹
';

    // Page numbers
    for ( $i = 1; $i <= $pages; ++$i )
      if ( 1 != $pages && ( !($i >= $paged + $range + 1 || $i <= $paged - $range - 1) || $pages <= $showitems ) )
        $output .= $paged == $i ? '
' . $i . '
' :  '
' . $i . '
';

    if ( $paged < $pages )        $output .= '
›
';
    if ( $paged < $pages - 1 )    $output .= '
»
';

    $output .= '
';

    echo $output;

}

/**
 * Like get_template_part() put lets you pass args to the template file
 * Args are available in the tempalte as $args array
 * @param string filepart
 * @param mixed wp_args style argument list
 */
function ws_get_template_part( $file, $args = array(), $cache_args = array() ) {
    $args = wp_parse_args( $args );
    $cache_args = wp_parse_args( $cache_args );
    if ( $cache_args ) {
        foreach ( $args as $key => $value ) {
            if ( is_scalar( $value ) || is_array( $value ) ) {
                $cache_args[$key] = $value;
            } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) {
                $cache_args[$key] = call_user_method( 'get_id', $value );
            }
        }
        if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) {
            if ( ! empty( $args['return'] ) )
                return $cache;
            echo $cache;
            return;
        }
    }
    $file_handle = $file;
    do_action( 'start_operation', 'hm_template_part::' . $file_handle );
    if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) )
        $file = get_stylesheet_directory() . '/' . $file . '.php';
    elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) )
        $file = get_template_directory() . '/' . $file . '.php';
    ob_start();
    $return = require( $file );
    $data = ob_get_clean();
    do_action( 'end_operation', 'hm_template_part::' . $file_handle );
    if ( $cache_args ) {
        wp_cache_set( $file, $data, serialize( $cache_args ), 3600 );
    }
    if ( ! empty( $args['return'] ) )
        if ( $return === false )
            return false;
        else
            return $data;
    echo $data;
}


text:
require "ruboty/ueno_park_event/version"
require "ruboty/handlers/ueno_park_event"
require "ruboty/ueno_park_event/actions/ueno_park_event"

module Ruboty
  module UenoParkEvent
    # Your code goes here...
  end
end


text:
<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="2" android:versionName="0.0.2" package="org.xenth.OfflineCollector" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@drawable/family" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>


text:
@implementation NSCalendar (Juncture)

#pragma mark - First/Last of Week

- (NSDate *)firstDayOfTheWeek
{
    return [self firstDayOfTheWeekUsingReferenceDate:[NSDate date]];
}

- (NSDate *)firstDayOfTheWeekUsingReferenceDate:(NSDate *)date
{
    NSInteger weekday = [self weekdayInDate:date]-1;
    return [self dateBySubtractingDays:weekday fromDate:date];
}

- (NSDate *)lastDayOfTheWeek
{
    return [self lastDayOfTheWeekUsingReferenceDate:[NSDate date]];
}

- (NSDate *)lastDayOfTheWeekUsingReferenceDate:(NSDate *)date
{

    NSDate *d = [self firstDayOfTheWeekUsingReferenceDate:date];
    NSUInteger daysPerWeek = [self daysPerWeekUsingReferenceDate:d];
    return [self dateByAddingDays:daysPerWeek-1 toDate:d];
}

#pragma mark - First/Last of Month

- (NSDate *)firstDayOfTheMonth
{
    return [self firstDayOfTheMonthUsingReferenceDate:[NSDate date]];
}

- (NSDate *)firstDayOfTheMonthUsingReferenceDate:(NSDate *)date
{
    NSDateComponents *c = [self components:NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];

    [c setDay:1];

    return [self dateFromComponents:c];
}

- (NSDate *)lastDayOfTheMonth
{
    return [self firstDayOfTheMonthUsingReferenceDate:[NSDate date]];
}

- (NSDate *)lastDayOfTheMonthUsingReferenceDate:(NSDate *)date
{

    NSDateComponents *c = [self components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:date];

    [c setDay:[self daysPerMonthUsingReferenceDate:date]];

    return [self dateFromComponents:c];
}

#pragma mark
@end


text:
Package.describe({
  name: 'verody:jrpcsec-client-client',
  version: '0.1.1',
  summary: 'JRPCSec client packaged for Meteor client architecture.',
  git: 'git@github.com:ekobi/jrpcsec.git',
  documentation: null
});

Package.onUse(function(api) {
    api.versionsFrom('1.3.4');
    api.addFiles ([
        'forge.verody-bundle.js',
        'binary.min.js',
        'jrpc.min.js',
        'jrpcsec-client.js'], ['client']);
    api.export (['JRPCSec', 'Forge'], ['client']);
});

Package.onTest(function(api) {
    api.use(['underscore']);
    api.use([ 'tinytest', 'random' ]);
    api.use('verody:jrpcsec-client');
    api.mainModule('jrpcsec-client-tests.js');
});


text:
angular.module('adminHomeApp')

    .factory('globals', ['$window', '$rootScope', 'socketService',
        function ($window, $rootScope, socketService) {
            var username;
            var myUniqueCuid;
            var grillName;
            var mySocketRoom;
            var allGrillStatuses = {};
            return {

                username: function (newUsername) {
                    if (newUsername) {
                        username = newUsername;
                        return username;
                    } else {
                        return username;
                    }
                },

                grillName: function (newGrillName) {
                    if (newGrillName) {
                        grillName = newGrillName;
                        return grillName;
                    } else {
                        return grillName;
                    }
                },

                uniqueCuid: function (newUniqueCuid) {
                    if (newUniqueCuid) {
                        myUniqueCuid = newUniqueCuid;
                        return myUniqueCuid;
                    } else {
                        return myUniqueCuid;
                    }
                },

                socketRoom: function (newSocketRoom) {
                    if (newSocketRoom) {
                        mySocketRoom = newSocketRoom;
                    } else {
                        return mySocketRoom;
                    }
                },

                allGrillStatuses: function (newAllGrillStatuses, broadcast, refreshGrillStatus) {
                    if (refreshGrillStatus) {
                        socketService.getAllGrillStatuses()
                            .success(function (resp) {
                                $rootScope.$broadcast('responseStatusHandler', resp);
                                allGrillStatuses = resp.allGrillStatuses;

                                if (broadcast) {
                                    $rootScope.$broadcast('allGrillStatuses', allGrillStatuses);
                                }
                                $rootScope.$broadcast('responseStatusHandler', resp);
                            })
                            .error(function (errResponse) {
                                $rootScope.$broadcast('responseStatusHandler', errResponse);
                            });
                    } else {

                        if (newAllGrillStatuses) {
                            allGrillStatuses = newAllGrillStatuses;
                        }

                        if (broadcast) {
                            $rootScope.$broadcast('allGrillStatuses', allGrillStatuses);
                        }
                    }

                    return allGrillStatuses;
                }

            }
        }]);