text:
#include "SDL_config.h"

#include <unistd.h>
#include <sys/ioctl.h>

#include "SDL_endian.h"
#include "SDL_timer.h"
#include "SDL_thread.h"
#include "SDL_video.h"
#include "SDL_mouse.h"
#include "../SDL_sysvideo.h"
#include "../SDL_pixels_c.h"
#include "../../events/SDL_events_c.h"
#include "SDL_ph_video.h"
#include "SDL_ph_modes_c.h"
#include "SDL_ph_image_c.h"
#include "SDL_ph_events_c.h"
#include "SDL_ph_mouse_c.h"
#include "SDL_ph_wm_c.h"
#include "SDL_ph_gl.h"
#include "SDL_phyuv_c.h"
#include "../blank_cursor.h"

static int  ph_VideoInit(_THIS, SDL_PixelFormat *vformat);
static SDL_Surface *ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
static int  ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors);
static void ph_VideoQuit(_THIS);
static void ph_DeleteDevice(SDL_VideoDevice *device);

static int phstatus=-1;

static int ph_Available(void)
{
    if (phstatus!=0)
    {
        phstatus=PtInit(NULL);
        if (phstatus==0)
        {
           return 1;
        }
        else
        {
           return 0;
        }
    }
    return 1;
}

static SDL_VideoDevice* ph_CreateDevice(int devindex)
{
    SDL_VideoDevice* device;

    /* Initialize all variables that we clean on shutdown */
    device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
    if (device)
    {
        SDL_memset(device, 0, (sizeof *device));
        device->hidden = (struct SDL_PrivateVideoData*)SDL_malloc((sizeof *device->hidden));
        device->gl_data = NULL;
    }
    if ((device == NULL) || (device->hidden == NULL))
    {
        SDL_OutOfMemory();
        ph_DeleteDevice(device);
        return NULL;
    }
    SDL_memset(device->hidden, 0, (sizeof *device->hidden));

    /* Set the driver flags */
    device->handles_any_size = 1;

    /* Set the function pointers */
    device->CreateYUVOverlay = ph_CreateYUVOverlay;
    device->VideoInit = ph_VideoInit;
    device->ListModes = ph_ListModes;
    device->SetVideoMode = ph_SetVideoMode;
    device->ToggleFullScreen = ph_ToggleFullScreen;
    device->UpdateMouse = ph_UpdateMouse;
    device->SetColors = ph_SetColors;
    device->UpdateRects = NULL;                        /* set up in ph_SetupUpdateFunction */
    device->VideoQuit = ph_VideoQuit;
    device->AllocHWSurface = ph_AllocHWSurface;
    device->CheckHWBlit = ph_CheckHWBlit;
    device->FillHWRect = ph_FillHWRect;
    device->SetHWColorKey = ph_SetHWColorKey;
    device->SetHWAlpha = ph_SetHWAlpha;
    device->LockHWSurface = ph_LockHWSurface;
    device->UnlockHWSurface = ph_UnlockHWSurface;
    device->FlipHWSurface = ph_FlipHWSurface;
    device->FreeHWSurface = ph_FreeHWSurface;
    device->SetCaption = ph_SetCaption;
    device->SetIcon = NULL;
    device->IconifyWindow = ph_IconifyWindow;
    device->GrabInput = ph_GrabInput;
    device->GetWMInfo = ph_GetWMInfo;
    device->FreeWMCursor = ph_FreeWMCursor;
    device->CreateWMCursor = ph_CreateWMCursor;
    device->ShowWMCursor = ph_ShowWMCursor;
    device->WarpWMCursor = ph_WarpWMCursor;
    device->MoveWMCursor = NULL;
    device->CheckMouseMode = ph_CheckMouseMode;
    device->InitOSKeymap = ph_InitOSKeymap;
    device->PumpEvents = ph_PumpEvents;

    /* OpenGL support. */
#if SDL_VIDEO_OPENGL
    device->GL_MakeCurrent = ph_GL_MakeCurrent;
    device->GL_SwapBuffers = ph_GL_SwapBuffers;
    device->GL_GetAttribute = ph_GL_GetAttribute;
    device->GL_LoadLibrary = ph_GL_LoadLibrary;
    device->GL_GetProcAddress = ph_GL_GetProcAddress;
#endif /* SDL_VIDEO_OPENGL */

    device->free = ph_DeleteDevice;

    return device;
}

VideoBootStrap ph_bootstrap = {
    "photon", "QNX Photon video output",
    ph_Available, ph_CreateDevice
};

static void ph_DeleteDevice(SDL_VideoDevice *device)
{
    if (device)
    {
        if (device->hidden)
        {
            SDL_free(device->hidden);
            device->hidden = NULL;
        }
        if (device->gl_data)
        {
            SDL_free(device->gl_data);
            device->gl_data = NULL;
        }
        SDL_free(device);
        device = NULL;
    }
}

static PtWidget_t *ph_CreateWindow(_THIS)
{
    PtWidget_t *widget;

    widget = PtCreateWidget(PtWindow, NULL, 0, NULL);

    return widget;
}

static int ph_SetupWindow(_THIS, int w, int h, int flags)
{
    PtArg_t     args[32];
    PhPoint_t   pos = {0, 0};
    PhDim_t*    olddim;
    PhDim_t     dim = {w, h};
    PhRect_t    desktopextent;
    int         nargs = 0;
    const char* windowpos;
    const char* iscentered;
    int         x, y;

    /* check if window size has been changed by Window Manager */
    PtGetResource(window, Pt_ARG_DIM, &olddim, 0);
    if ((olddim->w!=w) || (olddim->h!=h))
    {
       PtSetArg(&args[nargs++], Pt_ARG_DIM, &dim, 0);
    }

    if ((flags & SDL_RESIZABLE) == SDL_RESIZABLE)
    {
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_CLOSE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_RESIZE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_RESIZE | Ph_WM_MOVE | Ph_WM_CLOSE | Ph_WM_MAX | Ph_WM_RESTORE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN);
        PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_TRUE, Pt_RESIZE_XY_AS_REQUIRED);
    }
    else
    {
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE | Ph_WM_CLOSE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_FALSE, Ph_WM_RESIZE | Ph_WM_MAX | Ph_WM_RESTORE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_MOVE | Ph_WM_CLOSE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_MAX | Ph_WM_RENDER_COLLAPSE | Ph_WM_RENDER_RETURN);
        PtSetArg(&args[nargs++], Pt_ARG_RESIZE_FLAGS, Pt_FALSE, Pt_RESIZE_XY_AS_REQUIRED);
    }

    if (((flags & SDL_NOFRAME)==SDL_NOFRAME) || ((flags & SDL_FULLSCREEN)==SDL_FULLSCREEN))
    {
       if ((flags & SDL_RESIZABLE) != SDL_RESIZABLE)
       {
           PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Pt_TRUE);
       }
       else
       {
           PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_FALSE, Pt_TRUE);
           PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_RESIZE | Ph_WM_RENDER_BORDER);
       }
    }
    else
    {
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_RENDER_FLAGS, Pt_TRUE, Ph_WM_RENDER_BORDER | Ph_WM_RENDER_TITLE |
                                 Ph_WM_RENDER_CLOSE | Ph_WM_RENDER_MENU | Ph_WM_RENDER_MIN);
    }

    if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
    {
        PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0);
        PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, Pt_BASIC_PREVENT_FILL);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_FFRONT | Ph_WM_MAX | Ph_WM_TOFRONT | Ph_WM_CONSWITCH);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISFRONT | Ph_WM_STATE_ISFOCUS | Ph_WM_STATE_ISALTKEY);
    }
    else
    {
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_FALSE, Ph_WM_FFRONT | Ph_WM_CONSWITCH);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISFRONT);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISALTKEY);

        if ((flags & SDL_HWSURFACE) == SDL_HWSURFACE)
        {
            PtSetArg(&args[nargs++], Pt_ARG_BASIC_FLAGS, Pt_TRUE, Pt_BASIC_PREVENT_FILL);
        }
        else
        {
            PtSetArg(&args[nargs++], Pt_ARG_FILL_COLOR, Pg_BLACK, 0);
        }
        if (!currently_maximized)
        {
            windowpos = SDL_getenv("SDL_VIDEO_WINDOW_POS");
            iscentered = SDL_getenv("SDL_VIDEO_CENTERED");

            if ((iscentered) || ((windowpos) && (SDL_strcmp(windowpos, "center")==0)))
            {
                PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, 0, &desktopextent);
                if (desktop_mode.width>w)
                {
                    pos.x = (desktop_mode.width - w)/2;
                }
                if (desktop_mode.height>h)
                {
                    pos.y = (desktop_mode.height - h)/2;
                }

                pos.x+=desktopextent.ul.x;
                pos.y+=desktopextent.ul.y;
                PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0);
            }
            else
            {
                if (windowpos)
                {
                    if (SDL_sscanf(windowpos, "%d,%d", &x, &y) == 2)
                    {
                        if ((x<desktop_mode.width) && (y<desktop_mode.height))
                        {
                            PhWindowQueryVisible(Ph_QUERY_CONSOLE, 0, 0, &desktopextent);
                            pos.x=x+desktopextent.ul.x;
                            pos.y=y+desktopextent.ul.y;
                        }
                        PtSetArg(&args[nargs++], Pt_ARG_POS, &pos, 0);
                    }
                }
            }
        }

        /* if window is maximized render it as maximized */
        if (currently_maximized)
        {
           PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISMAX);
        }
        else
        {
           PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISMAX);
        }

        /* do not grab the keyboard by default */
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_FALSE, Ph_WM_STATE_ISALTKEY);

        /* bring the focus to the window */
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_STATE, Pt_TRUE, Ph_WM_STATE_ISFOCUS);

        /* allow to catch hide event */
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_MANAGED_FLAGS, Pt_TRUE, Ph_WM_HIDE);
        PtSetArg(&args[nargs++], Pt_ARG_WINDOW_NOTIFY_FLAGS, Pt_TRUE, Ph_WM_HIDE);
    }

    PtSetResources(window, nargs, args);
    PtRealizeWidget(window);
    PtWindowToFront(window);

#if 0 /* FIXME */
    PtGetResource(window, Pt_ARG_POS, &olddim, 0);
    fprintf(stderr, "POSITION: %d, %d\n", olddim->w, olddim->h);
#endif

    return 0;
}

static const struct ColourMasks* ph_GetColourMasks(int bpp)
{
    /* The alpha mask doesn't appears to be needed */
    static const struct ColourMasks phColorMasks[5] = {
        /*  8 bit      */  {0, 0, 0, 0, 8},
        /* 15 bit ARGB */  {0x7C00, 0x03E0, 0x001F, 0x8000, 15},
        /* 16 bit  RGB */  {0xF800, 0x07E0, 0x001F, 0x0000, 16},
        /* 24 bit  RGB */  {0xFF0000, 0x00FF00, 0x0000FF, 0x000000, 24},
        /* 32 bit ARGB */  {0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, 32},
    };

    switch (bpp)
    {
        case 8:
             return &phColorMasks[0];
        case 15:
             return &phColorMasks[1];
        case 16:
             return &phColorMasks[2];
        case 24:
             return &phColorMasks[3];
        case 32:
             return &phColorMasks[4];
    }
    return NULL;
}

static int ph_VideoInit(_THIS, SDL_PixelFormat* vformat)
{
    PgHWCaps_t hwcaps;
    int i;

    window=NULL;
    desktoppal=SDLPH_PAL_NONE;

#if SDL_VIDEO_OPENGL
    oglctx=NULL;
    oglbuffers=NULL;
    oglflags=0;
    oglbpp=0;
#endif

    old_video_mode=-1;
    old_refresh_rate=-1;

    if (NULL == (phevent = SDL_malloc(EVENT_SIZE)))
    {
        SDL_OutOfMemory();
        return -1;
    }
    SDL_memset(phevent, 0x00, EVENT_SIZE);

    window = ph_CreateWindow(this);
    if (window == NULL)
    {
        SDL_SetError("ph_VideoInit(): Couldn't create video window !\n");
        return -1;
    }

    /* Create the blank cursor */
    SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask,
                                          (int)BLANK_CWIDTH, (int)BLANK_CHEIGHT,
                                          (int)BLANK_CHOTX, (int)BLANK_CHOTY);

    if (SDL_BlankCursor == NULL)
    {
        return -1;
    }

    if (PgGetGraphicsHWCaps(&hwcaps) < 0)
    {
        SDL_SetError("ph_VideoInit(): GetGraphicsHWCaps function failed !\n");
        this->FreeWMCursor(this, SDL_BlankCursor);
        return -1;
    }

    if (PgGetVideoModeInfo(hwcaps.current_video_mode, &desktop_mode) < 0)
    {
        SDL_SetError("ph_VideoInit(): PgGetVideoModeInfo function failed !\n");
        this->FreeWMCursor(this, SDL_BlankCursor);
        return -1;
    }

   /* Determine the current screen size */
   this->info.current_w = desktop_mode.width;
   this->info.current_h = desktop_mode.height;

    /* We need to return BytesPerPixel as it in used by CreateRGBsurface */
    vformat->BitsPerPixel = desktop_mode.bits_per_pixel;
    vformat->BytesPerPixel = desktop_mode.bytes_per_scanline/desktop_mode.width;
    desktopbpp = desktop_mode.bits_per_pixel;

    /* save current palette */
    if (desktopbpp==8)
    {
        PgGetPalette(savedpal);
        PgGetPalette(syspalph);
    }
    else
    {
        for(i=0; i<_Pg_MAX_PALETTE; i++)
        {
            savedpal[i]=PgRGB(0, 0, 0);
            syspalph[i]=PgRGB(0, 0, 0);
        }
    }

    currently_fullscreen = 0;
    currently_hided = 0;
    currently_maximized = 0;
    current_overlay = NULL;

    OCImage.direct_context = NULL;
    OCImage.offscreen_context = NULL;
    OCImage.offscreen_backcontext = NULL;
    OCImage.oldDC = NULL;
    OCImage.CurrentFrameData = NULL;
    OCImage.FrameData0 = NULL;
    OCImage.FrameData1 = NULL;
    videomode_emulatemode = 0;

    this->info.wm_available = 1;

    ph_UpdateHWInfo(this);

    return 0;
}

static SDL_Surface* ph_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags)
{
    const struct ColourMasks* mask;

    /* Lock the event thread, in multi-threading environments */
    SDL_Lock_EventThread();

    current->flags = flags;

    /* if we do not have desired fullscreen mode, then fallback into window mode */
    if (((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) && (ph_GetVideoMode(width, height, bpp)==0))
    {
       current->flags &= ~SDL_FULLSCREEN;
       current->flags &= ~SDL_NOFRAME;
       current->flags &= ~SDL_RESIZABLE;
    }

    ph_SetupWindow(this, width, height, current->flags);

    mask = ph_GetColourMasks(bpp);
    if (mask != NULL)
    {
        SDL_ReallocFormat(current, mask->bpp, mask->red, mask->green, mask->blue, 0);
    }
    else
    {
        SDL_SetError("ph_SetVideoMode(): desired bpp is not supported by photon !\n");
        return NULL;
    }

    if ((current->flags & SDL_OPENGL)==SDL_OPENGL)
    {
#if !SDL_VIDEO_OPENGL
        /* if no built-in OpenGL support */
        SDL_SetError("ph_SetVideoMode(): no OpenGL support, you need to recompile SDL.\n");
        current->flags &= ~SDL_OPENGL;
        return NULL;
#endif /* SDL_VIDEO_OPENGL */
    }
    else
    {
        /* Initialize internal variables */
        if ((current->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN)
        {
            if (bpp==8)
            {
               desktoppal=SDLPH_PAL_SYSTEM;
            }

            current->flags &= ~SDL_RESIZABLE; /* no resize for Direct Context */
            current->flags |= SDL_HWSURFACE;
        }
        else
        {
            /* remove this if we'll have support for the non-fullscreen sw/hw+doublebuf one day */
            current->flags &= ~SDL_DOUBLEBUF;

            /* Use offscreen memory if SDL_HWSURFACE flag is set */
            if ((current->flags & SDL_HWSURFACE) == SDL_HWSURFACE)
            {
                if (desktopbpp!=bpp)
                {
                   current->flags &= ~SDL_HWSURFACE;
                }
            }

            /* using palette emulation code in window mode */
            if (bpp==8)
            {
                if (desktopbpp>=15)
                {
                    desktoppal = SDLPH_PAL_EMULATE;
                }
                else
                {
                    desktoppal = SDLPH_PAL_SYSTEM;
                }
            }
            else
            {
               desktoppal = SDLPH_PAL_NONE;
            }
        }
    }

    current->w = width;
    current->h = height;

    if (desktoppal==SDLPH_PAL_SYSTEM)
    {
       current->flags|=SDL_HWPALETTE;
    }

    /* Must call at least once for setup image planes */
    if (ph_SetupUpdateFunction(this, current, current->flags)==-1)
    {
        /* Error string was filled in the ph_SetupUpdateFunction() */
        return NULL;
    }

    /* finish window drawing, if we are not in fullscreen, of course */
    if ((current->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN)
    {
       PtFlush();
    }
    else
    {
       PgFlush();
    }

    visualbpp=bpp;

    ph_UpdateHWInfo(this);

    SDL_Unlock_EventThread();

    /* We've done! */
    return (current);
}

static void ph_VideoQuit(_THIS)
{
    /* restore palette */
    if (desktopbpp==8)
    {
        PgSetPalette(syspalph, 0, -1, 0, 0, 0);
        PgSetPalette(savedpal, 0, 0, _Pg_MAX_PALETTE, Pg_PALSET_GLOBAL | Pg_PALSET_FORCE_EXPOSE, 0);
        PgFlush();
    }

    ph_DestroyImage(this, SDL_VideoSurface);

    if (window)
    {
        PtUnrealizeWidget(window);
        PtDestroyWidget(window);
        window=NULL;
    }

    if (phevent!=NULL)
    {
        SDL_free(phevent);
        phevent=NULL;
    }
}

static int ph_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
{
    int i;
    SDL_Rect updaterect;

    updaterect.x = updaterect.y = 0;
    updaterect.w = this->screen->w;
    updaterect.h = this->screen->h;

    /* palette emulation code, using palette of the PhImage_t struct */
    if (desktoppal==SDLPH_PAL_EMULATE)
    {
        if ((SDL_Image) && (SDL_Image->palette))
        {
            for (i=firstcolor; i<firstcolor+ncolors; i++)
            {
                syspalph[i] = PgRGB(colors[i-firstcolor].r, colors[i-firstcolor].g, colors[i-firstcolor].b);
                SDL_Image->palette[i] = syspalph[i];
            }

            /* image needs to be redrawn */
            this->UpdateRects(this, 1, &updaterect);
        }
    }
    else
    {
        if (desktoppal==SDLPH_PAL_SYSTEM)
        {
            for (i=firstcolor; i<firstcolor+ncolors; i++)
            {
                syspalph[i] = PgRGB(colors[i-firstcolor].r, colors[i-firstcolor].g, colors[i-firstcolor].b);
            }

            if ((this->screen->flags & SDL_FULLSCREEN) != SDL_FULLSCREEN)
            {
                 /* window mode must use soft palette */
                PgSetPalette(&syspalph[firstcolor], 0, firstcolor, ncolors, Pg_PALSET_GLOBAL, 0);
                /* image needs to be redrawn */
                this->UpdateRects(this, 1, &updaterect);
            }
            else
            {
                /* fullscreen mode must use hardware palette */
                PgSetPalette(&syspalph[firstcolor], 0, firstcolor, ncolors, Pg_PALSET_GLOBAL, 0);
            }
        }
        else
        {
            /* SDLPH_PAL_NONE do nothing */
        }
    }

    return 1;
}


text:
package com.amazonaws.wrapper.model;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateSubnetRequest;
import com.amazonaws.services.ec2.model.CreateSubnetResult;
import com.amazonaws.services.ec2.model.DeleteVpcRequest;
import com.amazonaws.services.ec2.model.DescribeSubnetsRequest;
import com.amazonaws.services.ec2.model.DescribeSubnetsResult;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Subnet;
import com.amazonaws.wrapper.exception.ResourceDoesNotExistException;

public class Ec2SubNetwork extends Ec2Resource<Subnet, Ec2SubNetwork> {

    private final static Logger LOGGER = LoggerFactory.getLogger(Ec2SubNetwork.class);

    public final static String CREATE_PARAM_VPC_ID = "vpc_id";
    public final static String CREATE_PARAM_DESCRIPTION = "description";

    public Ec2SubNetwork(Subnet subnetwork) {
        super(subnetwork);
    }

    public Ec2SubNetwork(String id) throws ResourceDoesNotExistException {
        super(id);
        refresh();
    }

    public Ec2SubNetwork() {
    }

    @Override
    protected void doCreateRequest(AmazonEC2 ec2, String vpcId, Properties props, AdapterSettings settings) {
        CreateSubnetRequest request = new CreateSubnetRequest();
        request.withVpcId(vpcId);
        CreateSubnetResult result = ec2.createSubnet(request);
        setId(result.getSubnet().getSubnetId());
        try {
            refresh();
        } catch (ResourceDoesNotExistException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    protected void doDeleteRequest() {
        getEc2().deleteVpc(new DeleteVpcRequest().withVpcId(getId()));
    }

    @Override
    protected String getResourceId() {
        return getResource().getSubnetId();
    }

    @Override
    protected AmazonWebServiceRequest applyFiltersForRequest(Filter... filters) {
        return new DescribeSubnetsRequest().withFilters(filters);
    }

    @Override
    protected List<Ec2SubNetwork> processDescribe(AmazonEC2 amazonEC2, AmazonWebServiceRequest request) {
        List<Ec2SubNetwork> subNets = new ArrayList<Ec2SubNetwork>();

        DescribeSubnetsResult result = amazonEC2.describeSubnets(((DescribeSubnetsRequest) request));
        for (Subnet subnet : result.getSubnets()) {
            subNets.add(new Ec2SubNetwork(subnet));
        }
        return subNets;
    }

    @Override
    protected Subnet processDescribe() throws ResourceDoesNotExistException {
        try {
            List<Subnet> subnetworks = getEc2().describeSubnets(new DescribeSubnetsRequest().withSubnetIds(getId())).getSubnets();
            return subnetworks.get(0);
        } catch (Exception ex) {
            throw new ResourceDoesNotExistException(getId());
        }
    }

    public static List<Ec2SubNetwork> getAllSubnets() {
        return new Ec2SubNetwork().getAll();
    }

    public String getVpcId() {
        return getResource().getVpcId();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Figaromedias\Bundle\DsAutomobilesBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * DsGalleryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class DsGalleryRepository extends EntityRepository
{
    public function getAll($filters)
    {
        $qb = $this->createQueryBuilder('a');

        $qb
            ->where('a.published >= :published')
            ->setParameter('published', $filters['published'])
        ;

        if (isset($filters['_order']))
            $qb->orderBy($filters['_order'], $filters['_orderBy']);

        return $qb
            ->getQuery()
            ->getResult()
        ;
    }
}


text:
//
//  BuildTimeLogger-Bridging-Header.h
//  BuildTimeLogger
//
//  Created by Marcin Religa on 22/02/2017.
//  Copyright © 2017 Marcin Religa. All rights reserved.
//

#ifndef BuildTimeLogger_Bridging_Header_h
#define BuildTimeLogger_Bridging_Header_h

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "NSData+GZIP.h"

#endif /* BuildTimeLogger_Bridging_Header_h */


text:
mv data{,.old} && echo 'Moved old data to data.old'
if [ -f ~/Dropbox/GameDev/oyunum/data.tar.gz ]; then
    cp ~/Dropbox/GameDev/oyunum/data.tar.gz .
else
    wget https://www.dropbox.com/s/ystc9qq6dqxy2nu/data.tar.gz?dl=0 -O data.tar.gz
fi
tar xf data.tar.gz && echo 'Extracted tar archive to data directory.' && rm -v data.tar.gz && echo 'Removed tar archive' && rm -rf data.old && echo 'Deleted data.old'


text:
package se.callista.springmvc.asynch.pattern.aggregator;

import akka.actor.ActorSystem;
import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import com.ning.http.client.Response;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import scala.concurrent.ExecutionContext;
import scala.concurrent.ExecutionContextExecutor;
import scala.concurrent.Future;
import scala.concurrent.Promise;
import scala.concurrent.duration.FiniteDuration;
import se.callista.springmvc.asynch.common.AsyncHttpClientAkka;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;

import static akka.dispatch.Futures.future;
import static se.callista.springmvc.asynch.common.AkkaUtils.completer;
import static se.callista.springmvc.asynch.common.AkkaUtils.mapper;
import static se.callista.springmvc.asynch.common.AkkaUtils.runnable;

/**
 * @author Pär Wenåker <par.wenaker@callistaenterprise.se>
 */
@RestController
public class AggregatorNonBlockingAkkaFuturesController implements InitializingBean{

    @Value("${sp.non_blocking.url}")
    private String SP_NON_BLOCKING_URL;

    @Value("${aggregator.timeoutMs}")
    private int TIMEOUT_MS;

    @Autowired
    @Qualifier("dbThreadPoolExecutor")
    private TaskExecutor dbThreadPoolExecutor;

    @Autowired
    private ActorSystem actorSystem;

    @Autowired
    private AsyncHttpClientAkka asyncHttpClientAkka;

    ExecutionContextExecutor ec;

    /**
     * Sample usage: curl "http://localhost:9080/aggregate-non-blocking-rx?minMs=1000&maxMs=2000"
     */
    @RequestMapping("/aggregate-non-blocking-akkafutures")
    public DeferredResult<String> nonBlockingAggregator(
        @RequestParam(value = "dbLookupMs", required = false, defaultValue = "0")    int dbLookupMs,
        @RequestParam(value = "dbHits",     required = false, defaultValue = "3")    int dbHits,
        @RequestParam(value = "minMs",      required = false, defaultValue = "0")    int minMs,
        @RequestParam(value = "maxMs",      required = false, defaultValue = "0")    int maxMs) throws IOException {

        DbLookup dbLookup = new DbLookup(dbLookupMs, dbHits);
        DeferredResult<String> deferredResult = new DeferredResult<>();

        String url = SP_NON_BLOCKING_URL + "?minMs=" + minMs + "&maxMs=" + maxMs;

        ExecutionContext dbEc = ExecutionContexts.fromExecutor(dbThreadPoolExecutor);

        future(dbLookup::executeDbLookup, dbEc)
            .map(mapper(noOfCalls -> IntStream.range(0, noOfCalls)), ec)
            .flatMap(mapper(intStream ->
                Futures.sequence(intStream.mapToObj(n ->
                    doAsyncCall(url, 3)
                ).collect(Collectors.toList()), ec)
            ), ec)
            .map(mapper(responses ->
                StreamSupport.stream(responses.spliterator(), false)
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .map(this::getResponseBody)
                    .collect(Collectors.toList())
            ), ec)
            .onComplete(completer(
                    deferredResult::setErrorResult,
                    results -> deferredResult.setResult(getTotalResult(results))
            ), ec);

        return deferredResult;
    }

    private Future<Optional<Response>> doAsyncCall(String url, long seconds) {
        Promise<Optional<Response>> promise = Futures.promise();

        actorSystem.scheduler().scheduleOnce(
                new FiniteDuration(seconds, TimeUnit.SECONDS),
                runnable(() -> promise.success(Optional.empty())),
                ec);

        Future<Optional<Response>> response =
                asyncHttpClientAkka.execute(url).map(mapper(Optional::of), ec);

        return Futures.firstCompletedOf(Arrays.asList(response, promise.future()), ec);
    }

    private String getResponseBody(Response response) {
        try {
            return response.getResponseBody();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getTotalResult(List<String> resultArr) {
        String totalResult = "";
        for (String r : resultArr)
            totalResult += r + '\n';
        return totalResult;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.ec = actorSystem.dispatcher();
    }
}


text:
layout: page
permalink: /:basename/
---
<link rel="stylesheet" type="text/css" href="../css/promisepage.css">

Be a cheerleader for America and bring the country's spirit back. "Take the brand of the United States and make it great again."

	    Share
       Tweet

Category: Culture

Status: Not started

Sources:

https://www.washingtonpost.com/news/post-politics/wp/2016/01/22/here-are-76-of-donald-trumps-many-campaign-promises

Comments

	   Place comment

Please enable Javascript and disable any adblocker to view comments.


text:
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfRangeControls
{
    public class RangePanel : Panel
    {
        static RangePanel()
        {
            ClipToBoundsProperty.OverrideMetadata(typeof(RangePanel), new FrameworkPropertyMetadata(true));

            HorizontalAlignmentProperty.OverrideMetadata(typeof(RangePanel), new FrameworkPropertyMetadata(HorizontalAlignment.Stretch));

            VerticalAlignmentProperty.OverrideMetadata(typeof(RangePanel), new FrameworkPropertyMetadata(VerticalAlignment.Stretch));
        }

        public static double GetPosition(DependencyObject obj)
        {
            return (double)obj.GetValue(PositionProperty);
        }

        public static void SetPosition(DependencyObject obj, double value)
        {
            obj.SetValue(PositionProperty, value);
        }

        // Using a DependencyProperty as the backing store for Position.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PositionProperty =
            DependencyProperty.RegisterAttached(
                "Position",
                typeof(double),
                typeof(RangePanel),
                new FrameworkPropertyMetadata(
                    (double)0,
                    FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsParentMeasure)
        );

        protected override bool HasLogicalOrientation => true;

        protected override Orientation LogicalOrientation => Orientation;

        public Orientation Orientation
        {
            get => (Orientation)GetValue(OrientationProperty);
            set => SetValue(OrientationProperty, value);
        }

        // Using a DependencyProperty as the backing store for Orientation.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OrientationProperty =
            DependencyProperty.Register(
                "Orientation",
                typeof(Orientation),
                typeof(RangePanel),
                new FrameworkPropertyMetadata(
                        Orientation.Vertical,
                        FrameworkPropertyMetadataOptions.AffectsMeasure,
                        OnOrientationChanged));

        private static void OnOrientationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is UIElement el))
                return;
            el.InvalidateMeasure();
        }

        #region minimum property

        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register(
                "Minimum",
                typeof(double),
                typeof(RangePanel),
                new FrameworkPropertyMetadata(0.0d, FrameworkPropertyMetadataOptions.AffectsMeasure));

        /// <summary>
        ///     Minimum restricts the minimum value of range
        /// </summary>
        [Bindable(true), Category("Behavior")]
        public double Minimum
        {
            get => (double)GetValue(MinimumProperty);
            set => SetValue(MinimumProperty, value);
        }

        #endregion

        #region Maximum property

        public static readonly DependencyProperty MaximumProperty =
            DependencyProperty.Register(
                "Maximum",
                typeof(double),
                typeof(RangePanel),
                new FrameworkPropertyMetadata(100.0d, FrameworkPropertyMetadataOptions.AffectsMeasure));

        /// <summary>
        ///     Minimum restricts the minimum value of range
        /// </summary>
        [Bindable(true), Category("Behavior")]
        public double Maximum
        {
            get => (double)GetValue(MaximumProperty);
            set => SetValue(MaximumProperty, value);
        }

        #endregion

        public RangePanel()
        {
            ClipToBounds = true;
        }

        protected override Size MeasureOverride(Size constraint)
        {

            double w = 0;
            double h = 0;

            foreach (var child in InternalChildren.OfType<UIElement>())
            {
                child.Measure(constraint);
                var s = GetItemPosition(constraint, child);

                if (s.Right > w)
                    w = s.Right;

                if (s.Bottom > h)
                    h = s.Bottom;
            }

            if (!double.IsNaN(Width))
                w = Width;

            if (!double.IsNaN(Height))
                h = Height;

            if (HorizontalAlignment == HorizontalAlignment.Stretch)
                w = 0;

            if (VerticalAlignment == VerticalAlignment.Stretch)
                h = 0;

            return new Size(w, h);
        }

        private double ScaleToSize(double val, double size)
        {
            var len = Maximum - Minimum;
            return val / len * size;
        }

        /// <summary>
        /// this should do same thing as canvas arrange
        /// </summary>
        /// <param name="arrangeSize"></param>
        /// <returns></returns>
        protected override Size ArrangeOverride(Size arrangeSize)
        {
            foreach (var item in InternalChildren.OfType<UIElement>())
            {
                Rect r = GetItemPosition(arrangeSize, item);
                item.Arrange(r);
            }
            return arrangeSize;
        }

        private Rect GetItemPosition(Size arrangeSize, UIElement item)
        {
            if (item is ContentPresenter && item.ReadLocalValue(PositionProperty) == DependencyProperty.UnsetValue)
            { //should this be recursive until uielement with set Position is found?

                if (VisualTreeHelper.GetChild(item, 0) is UIElement elm)
                    item = elm;
            }

            var pos = GetPosition(item);

            double x = 0;
            double y = 0;
            double w = item.DesiredSize.Width;
            double h = item.DesiredSize.Height;

            Size size;

            if (Orientation == Orientation.Horizontal)
            {
                x = ScaleToSize(pos, arrangeSize.Width);
                size = new Size(w, arrangeSize.Height);
                x -= SizeAdjustment(w);
            }
            else
            {
                y = ScaleToSize(pos, arrangeSize.Height);
                size = new Size(arrangeSize.Width, h);
                y -= SizeAdjustment(h);
            }

            return new Rect(new Point(x, y), size);
        }

        private static double SizeAdjustment(double size) => size / 2;
    }

}


text:
package com.alejandrocelaya.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by cta on 28/04/2015.
 */
public class CirculoView extends View {
    private Paint pincel;

    public CirculoView(Context context) {
        this(context, null);
    }

    public CirculoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CirculoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        pincel = new Paint();
        pincel.setColor(Color.BLUE);
        pincel.setStrokeWidth(13);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(300, 300, 100, pincel);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}


text:
<?php
/**
 * Generated by Protobuf protoc plugin.
 *
 * File descriptor :
 * POGOProtos/Networking/Requests/Messages/ClaimCodenameMessage.proto
 */

namespace POGOProtos\Networking\Requests\Messages;

/**
 * Protobuf message : POGOProtos.Networking.Requests.Messages.ClaimCodenameMessage
 */
class ClaimCodenameMessage extends \Protobuf\AbstractMessage
{

    /**
     * @var \Protobuf\UnknownFieldSet
     */
    protected $unknownFieldSet = null;

    /**
     * @var \Protobuf\Extension\ExtensionFieldMap
     */
    protected $extensions = null;

    /**
     * codename optional string = 1
     *
     * @var string
     */
    protected $codename = null;

    /**
     * force optional bool = 2
     *
     * @var bool
     */
    protected $force = null;

    /**
     * Check if 'codename' has a value
     *
     * @return bool
     */
    public function hasCodename()
    {
        return $this->codename !== null;
    }

    /**
     * Get 'codename' value
     *
     * @return string
     */
    public function getCodename()
    {
        return $this->codename;
    }

    /**
     * Set 'codename' value
     *
     * @param string $value
     */
    public function setCodename($value = null)
    {
        $this->codename = $value;
    }

    /**
     * Check if 'force' has a value
     *
     * @return bool
     */
    public function hasForce()
    {
        return $this->force !== null;
    }

    /**
     * Get 'force' value
     *
     * @return bool
     */
    public function getForce()
    {
        return $this->force;
    }

    /**
     * Set 'force' value
     *
     * @param bool $value
     */
    public function setForce($value = null)
    {
        $this->force = $value;
    }

    /**
     * {@inheritdoc}
     */
    public function extensions()
    {
        if ( $this->extensions !== null) {
            return $this->extensions;
        }

        return $this->extensions = new \Protobuf\Extension\ExtensionFieldMap(__CLASS__);
    }

    /**
     * {@inheritdoc}
     */
    public function unknownFieldSet()
    {
        return $this->unknownFieldSet;
    }

    /**
     * {@inheritdoc}
     */
    public static function fromStream($stream, \Protobuf\Configuration $configuration = null)
    {
        return new self($stream, $configuration);
    }

    /**
     * {@inheritdoc}
     */
    public static function fromArray(array $values)
    {
        $message = new self();
        $values  = array_merge([
            'codename' => null,
            'force' => null
        ], $values);

        $message->setCodename($values['codename']);
        $message->setForce($values['force']);

        return $message;
    }

    /**
     * {@inheritdoc}
     */
    public static function descriptor()
    {
        return \google\protobuf\DescriptorProto::fromArray([
            'name'      => 'ClaimCodenameMessage',
            'field'     => [
                \google\protobuf\FieldDescriptorProto::fromArray([
                    'number' => 1,
                    'name' => 'codename',
                    'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_STRING(),
                    'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL()
                ]),
                \google\protobuf\FieldDescriptorProto::fromArray([
                    'number' => 2,
                    'name' => 'force',
                    'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_BOOL(),
                    'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL()
                ]),
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function toStream(\Protobuf\Configuration $configuration = null)
    {
        $config  = $configuration ?: \Protobuf\Configuration::getInstance();
        $context = $config->createWriteContext();
        $stream  = $context->getStream();

        $this->writeTo($context);
        $stream->seek(0);

        return $stream;
    }

    /**
     * {@inheritdoc}
     */
    public function writeTo(\Protobuf\WriteContext $context)
    {
        $stream      = $context->getStream();
        $writer      = $context->getWriter();
        $sizeContext = $context->getComputeSizeContext();

        if ($this->codename !== null) {
            $writer->writeVarint($stream, 10);
            $writer->writeString($stream, $this->codename);
        }

        if ($this->force !== null) {
            $writer->writeVarint($stream, 16);
            $writer->writeBool($stream, $this->force);
        }

        if ($this->extensions !== null) {
            $this->extensions->writeTo($context);
        }

        return $stream;
    }

    /**
     * {@inheritdoc}
     */
    public function readFrom(\Protobuf\ReadContext $context)
    {
        $reader = $context->getReader();
        $length = $context->getLength();
        $stream = $context->getStream();

        $limit = ($length !== null)
            ? ($stream->tell() + $length)
            : null;

        while ($limit === null || $stream->tell() < $limit) {

            if ($stream->eof()) {
                break;
            }

            $key  = $reader->readVarint($stream);
            $wire = \Protobuf\WireFormat::getTagWireType($key);
            $tag  = \Protobuf\WireFormat::getTagFieldNumber($key);

            if ($stream->eof()) {
                break;
            }

            if ($tag === 1) {
                \Protobuf\WireFormat::assertWireType($wire, 9);

                $this->codename = $reader->readString($stream);

                continue;
            }

            if ($tag === 2) {
                \Protobuf\WireFormat::assertWireType($wire, 8);

                $this->force = $reader->readBool($stream);

                continue;
            }

            $extensions = $context->getExtensionRegistry();
            $extension  = $extensions ? $extensions->findByNumber(__CLASS__, $tag) : null;

            if ($extension !== null) {
                $this->extensions()->add($extension, $extension->readFrom($context, $wire));

                continue;
            }

            if ($this->unknownFieldSet === null) {
                $this->unknownFieldSet = new \Protobuf\UnknownFieldSet();
            }

            $data    = $reader->readUnknown($stream, $wire);
            $unknown = new \Protobuf\Unknown($tag, $wire, $data);

            $this->unknownFieldSet->add($unknown);

        }
    }

    /**
     * {@inheritdoc}
     */
    public function serializedSize(\Protobuf\ComputeSizeContext $context)
    {
        $calculator = $context->getSizeCalculator();
        $size       = 0;

        if ($this->codename !== null) {
            $size += 1;
            $size += $calculator->computeStringSize($this->codename);
        }

        if ($this->force !== null) {
            $size += 1;
            $size += 1;
        }

        if ($this->extensions !== null) {
            $size += $this->extensions->serializedSize($context);
        }

        return $size;
    }

    /**
     * {@inheritdoc}
     */
    public function clear()
    {
        $this->codename = null;
        $this->force = null;
    }

    /**
     * {@inheritdoc}
     */
    public function merge(\Protobuf\Message $message)
    {
        if ( ! $message instanceof \POGOProtos\Networking\Requests\Messages\ClaimCodenameMessage) {
            throw new \InvalidArgumentException(sprintf('Argument 1 passed to %s must be a %s, %s given', __METHOD__, __CLASS__, get_class($message)));
        }

        $this->codename = ($message->codename !== null) ? $message->codename : $this->codename;
        $this->force = ($message->force !== null) ? $message->force : $this->force;
    }

}


text:
require_dependency "rails_identity/application_controller"

module RailsIdentity

  ##
  # Users controller that performs CRUD on users.
  #
  class UsersController < ApplicationController

    # All except user creation requires a session token. Note that reset
    # token is also a legit session token, so :require_token will suffice.
    prepend_before_action :require_auth, only: [:show, :destroy]
    prepend_before_action :accept_auth, only: [:update, :create]
    prepend_before_action :require_admin_auth, only: [:index]

    # Some actions must have a user specified.
    before_action :get_user, only: [:show, :destroy]

    ##
    # List all users (but only works for admin user).
    #
    def index
      @users = User.all
      render json: @users, except: [:password_digest]
    end

    ##
    # Creates a new user. This action does not require any auth although it
    # is optional.
    #
    def create
      logger.debug("Create new user")
      @user = User.new(user_params)
      if @user.save

        # Save succeeded. Render the response based on the created user.
        render json: @user,
               except: [:verification_token, :reset_token, :password_digest],
               status: 201

        # Then, issue the verification token and send the email for
        # verification.
        @user.issue_token(:verification_token)
        @user.save
        user_mailer.email_verification(@user).deliver_later
      else
        render_errors 400, @user.errors.full_messages
      end
    end

    ##
    # Renders a user data.
    #
    def show
      render json: @user, except: [:password_digest]
    end

    ##
    # Patches the user object. There are four notable operations:
    #
    # - issue reset token
    # - issue verification token
    # - change password
    # - others
    #
    # Issuing either reset token or verification token requires NO
    # authentication. However, for that reason, the request does not get any
    # meaningful response. Instead, an email is sent out for either request.
    #
    # For changing password, there are two ways. One is to use old password
    # and the other is to use reset token.
    #
    # Otherwise, it's a normal update operation.
    #
    def update
      if params[:issue_reset_token] || params[:issue_verification_token]
        # For issuing a reset token, one does not need an auth token. so do
        # not authorize the request. For consistency, we require the id to
        # be "current".
        raise ApplicationController::UNAUTHORIZED_ERROR unless params[:id] == "current"
        get_user_for_token()
        if params[:issue_reset_token]
          update_token(:reset_token)
        else
          update_token(:verification_token)
        end
      else
        get_user()
        allow_password_change? if params[:password]
        update_user(user_params)
      end
    end

    ##
    # Deletes a user.
    #
    def destroy
      if @user.destroy
        render body: '', status: 204
      else
        # :nocov:
        render_error 400, @user.errors.full_messages
        # :nocov:
      end
    end

    protected

      ##
      # Override this method to app specific mailer.
      #
      def user_mailer
        return UserMailer
      end

      ##
      # Check if password change should be allowed. Two ways to do this: one
      # is to use old password or to use a valid reset token.
      #
      # A ApplicationController::UNAUTHORIZED_ERROR is thrown for invalid old password or
      # invalid reset token
      #
      def allow_password_change?
        if params[:old_password]
          unless @user.authenticate(params[:old_password])
            raise ApplicationController::UNAUTHORIZED_ERROR
          end
        else
          unless @token == @user.reset_token
            raise ApplicationController::UNAUTHORIZED_ERROR
          end
        end
        return true
      end

      ##
      # This method normally updates the user using permitted params.
      #
      def update_user(update_user_params)
        if @user.update_attributes(update_user_params)
          render json: @user, except: [:password_digest]
        else
          render_errors 400, @user.errors.full_messages
        end
      end

      ##
      # This method updates user with a new reset token. Only used for this
      # operation.
      #
      def update_token(kind)
        @user.issue_token(kind)
        @user.save
        if kind == :reset_token
          user_mailer.password_reset(@user).deliver_later
        else
          user_mailer.email_verification(@user).deliver_later
        end
        render body: '', status: 204
      end

    private

      ##
      # This overrides the application controller's get_user method. Since
      # resource object of this users controller is user, the id is
      # specified in :id param.
      #
      def get_user
        if params[:id] == "current"
          raise ApplicationController::UNAUTHORIZED_ERROR if @auth_user.nil?
          params[:id] = @auth_user.uuid
        end
        @user = find_object(User, params[:id])
        authorize_for!(@user)
        return @user
      end

      ##
      # For issuing a new reset or for re-issuing a verification token, use
      # this method to get user.
      #
      def get_user_for_token
        @user = User.find_by_username(params[:username])
        raise Repia::Errors::NotFound if @user.nil?
        return @user
      end

      def user_params
        # Only ADMIN can assign the attribute role. The attribute value will
        # be ignored if the user is not an ADMIN.
        if has_admin_auth?
          params.permit(:username, :password, :password_confirmation, :role, :verified)
        else
          params.permit(:username, :password, :password_confirmation, :verified)
        end
      end
  end
end


text:
import { Component,OnInit} from '@angular/core';
import { Data_Struct } from './../../data-service/data-struct.component';
import { BufferDataService } from './../../data-service/buffer-data.service';

@Component({
    selector:'Hacker-fuzz',
    templateUrl:'./fuzz.html',
})

export class FuzzComponent implements OnInit{

    public button_name = 'one-byte fuzzing';
    public ratio_of_end:number;

    buffer_name:string;
    buffer_data:Data_Struct[];

    IV_fuzz_interval:number;

    IV_fuzz_onebyte_fuzz_or_no_fuzz:number;
    IV_fuzz_onebyte_byte:number;

    IV_fuzz_gen_ID:number;
    IV_fuzz_gen_data:number;
    IV_fuzz_gen_index:number;
    IV_fuzz_gen_byte:number;

    constructor(private buffer_data_service:BufferDataService,){

    }

    INFC_add():void{
        this.ratio_of_end = this.ratio_of_end + 1;
    }

    FC_Load():void{
        this.ratio_of_end = 0;
        for(let i = 0;i < 100 ;i++){
            setTimeout(this.INFC_add(),1000);
            console.info(this.ratio_of_end);
        }
    }

    FC_Change_Button_Name(id:number):void{
        if(id === 1){
            this.button_name = 'one-byte fuzzing';
        }
        else{
            this.button_name = 'gen-fuzz';
        }
    }
    FC_Change_Buffer_Name(id:number):void{
        this.buffer_name = this.buffer_data[id].name;
    }

    FC_Start():void{

        this.IV_fuzz_interval=parseFloat(document.getElementById('id_fuzz_interval')['value']);
        console.info("IV_fuzz_interval:"+this.IV_fuzz_interval+'\n');

        if(this.button_name === 'one-byte fuzzing'){
            this.IV_fuzz_onebyte_fuzz_or_no_fuzz=parseFloat(document.getElementById('id_fuzz_onebyte_fuzz_or_no_fuzz')['value']);
            this.IV_fuzz_onebyte_byte=parseFloat(document.getElementById('id_fuzz_onebyte_byte')['value']);

            // document.getElementById('id_ping_can_range_start')['value'] = '';
            // document.getElementById('id_ping_can_range_end')['value'] = '';

            console.info("IV_fuzz_onebyte_fuzz_or_no_fuzz: "+this.IV_fuzz_onebyte_fuzz_or_no_fuzz+'\n'
                        +"IV_fuzz_onebyte_byte: "+this.IV_fuzz_onebyte_byte+'\n');
        }
        else if(this.button_name === 'gen-fuzz'){
            this.IV_fuzz_gen_ID=parseFloat(document.getElementById('id_fuzz_gen_ID')['value']);
            this.IV_fuzz_gen_data=parseFloat(document.getElementById('id_fuzz_gen_data')['value']);
            this.IV_fuzz_gen_index=parseFloat(document.getElementById('id_fuzz_gen_index')['value']);
            this.IV_fuzz_gen_byte=parseFloat(document.getElementById('id_fuzz_gen_byte')['value']);

            // document.getElementById('id_ping_uds_range_start')['value'] = '';
            // document.getElementById('id_ping_uds_range_end')['value'] = '';

            console.info("IV_fuzz_gen_ID: "+this.IV_fuzz_gen_ID+'\n'
                        +"IV_fuzz_gen_data: "+this.IV_fuzz_gen_data+'\n'
                        +"IV_fuzz_gen_index: "+this.IV_fuzz_gen_index+'\n'
                        +"IV_fuzz_gen_byte: "+this.IV_fuzz_gen_byte+'\n');
        }
    }

    ngOnInit():void{
        this.ratio_of_end = 0;
        this.buffer_data_service.FC_getBufferData().then(buffer_data_result => {this.buffer_data = buffer_data_result;this.buffer_name = this.buffer_data[0].name});
    }
}


text:
package poet

import (
	"bytes"
	"testing"

	. "gopkg.in/check.v1"
)

func _(t *testing.T) { TestingT(t) }

type TypeAliasSuite struct{}

var _ = Suite(&TypeAliasSuite{})

func (s *TypeAliasSuite) TestAlias(c *C) {
	expected := "type foo string\n"
	actual := NewTypeAliasSpec("foo", String).String()
	c.Assert(actual, Equals, expected)
}

func (s *TypeAliasSuite) TestAliasWithComment(c *C) {
	expected := "// foo is an alias\ntype foo string\n"
	actual := NewTypeAliasSpec("foo", String).AliasComment("foo is an alias").String()
	c.Assert(actual, Equals, expected)
}

func (s *TypeAliasSuite) TestAliasWithImport(c *C) {
	spec := NewTypeAliasSpec("foo", TypeReferenceFromInstance(&bytes.Buffer{}))
	c.Assert(spec.String(), Equals, "type foo *bytes.Buffer\n")
	c.Assert(spec.GetImports()[0].GetPackage(), Equals, "bytes")
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Namespace PHPFastCGI\FastCGIDaemon\Http</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Namespaces

						PHPFastCGI

						FastCGIDaemon

						Command

						Connection

						ConnectionHandler

						Exception

						Http

Classes

Request

Interfaces

RequestInterface

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

Namespace

Class

Namespace PHPFastCGI\FastCGIDaemon\Http

Classes summary

	Request
	The default implementation of the RequestInterface

Interfaces summary

	RequestInterface

The RequestBuilderInterface defines a set of methods used by a FastCGIDaemon
ConnectionHandler to build PSR-7 server request objects.

		 API documentation generated by ApiGen


text:
<?php

namespace notamedia\locker\rest;

use Yii;
use yii\db\ActiveRecordInterface;
use yii\di\Instance;
use yii\base\ActionFilter;
use yii\base\InvalidConfigException;
use yii\web\MethodNotAllowedHttpException;
use yii\web\NotFoundHttpException;
use notamedia\locker\LockManagerInterface;
use notamedia\locker\LockableInterface;
use notamedia\locker\LockAnotherUserException;
use notamedia\locker\LockNotExistException;
use notamedia\locker\LockNotExpiredException;

/**
 * Filter check record lock activity for actions
 *
 * ```php
 *  [
 *      ...
 *      [
 *          'class' => LockControlFilter::class,
 *          'only' => ['update']
 *      ],
 *      ...
 *  ]
 * ```
 */
class LockControlFilter extends ActionFilter
{
    /**
     * @var callable a PHP callable that will be called to return the model corresponding
     * to the specified primary key value. If not set, [[findModel()]] will be used instead.
     * The signature of the callable should be:
     *
     * ```php
     * function ($id, $action) {
     *     // $id is the primary key value. If composite primary key, the key values
     *     // will be separated by comma.
     *     // $action is the action object currently running
     * }
     * ```
     */
    public $findModel;
    /** @var string the name of the GET parameter that specifies the identificator. */
    public $idParam = 'id';
    /** @var LockManagerInterface|string lock manager component name */
    public $lockManager = 'lockManager';

    /**
     * @inheritdoc
     * @throws InvalidConfigException if lock manager not found
     */
    public function init()
    {
        parent::init();

        $this->lockManager = Instance::ensure($this->lockManager, LockManagerInterface::class);
        if (!$this->lockManager instanceof LockManagerInterface) {
            throw new InvalidConfigException(
                'Not found correct lock manager component implementing `LockManagerInterface`'
            );
        }
    }

    /**
     * @inheritdoc
     * @param yii\rest\Action $action
     * @throws NotFoundHttpException
     * @throws InvalidConfigException
     * @throws MethodNotAllowedHttpException
     * @throws LockAnotherUserException
     * @throws LockNotExpiredException
     * @throws LockNotExistException
     * @throws \Exception
     */
    public function beforeAction($action)
    {
        $model = $this->getModel($action);
        if (!$model instanceof LockableInterface) {
            throw new MethodNotAllowedHttpException('Method not supported by the target resource');
        }

        $this->lockManager->checkLockActual($model, true);

        return parent::beforeAction($action);
    }

    /**
     * Returns the model
     * @param yii\rest\Action $action
     * @throws NotFoundHttpException if the model cannot be found
     * @return ActiveRecordInterface the model found
     */
    public function getModel(yii\rest\Action $action)
    {
        if ($this->findModel !== null) {
            return call_user_func($this->findModel, $this);
        }

        $request = Yii::$app->getRequest();
        if ($request->getIsGet()) {
            $id = $request->get($this->idParam);
        } else {
            $id = $request->post($this->idParam);
        }

        $model = $action->findModel($id);
        $modelClass = $action->modelClass;

        if (!$model instanceof $modelClass) {
            throw new NotFoundHttpException('Record not found:' . $id);
        }

        return $model;
    }
}


text:
backTitleUrl = "";
backBodyUrl = "";

$(function (){
	$("#topBar").show("fast");
});


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_

#include <memory>
#include <set>
#include <unordered_map>

#include "flutter/services/semantics/semantics.mojom.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#include "flutter/sky/engine/platform/geometry/FloatRect.h"
#include "lib/ftl/macros.h"
#include "mojo/public/cpp/bindings/array.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"
#include "third_party/skia/include/core/SkMatrix44.h"
#include "third_party/skia/include/core/SkRect.h"

namespace shell {
class AccessibilityBridge;
}  // namespace shell

@interface SemanticObject : NSObject

/**
 * The globally unique identifier for this node.
 */
@property(nonatomic, readonly) uint32_t uid;

/**
 * The parent of this node in the node tree. Will be nil for the root node and
 * during transient state changes.
 */
@property(nonatomic, assign) SemanticObject* parent;

- (instancetype)init __attribute__((unavailable("Use initWithBridge instead")));
- (instancetype)initWithBridge:(shell::AccessibilityBridge*)bridge
                           uid:(uint32_t)uid NS_DESIGNATED_INITIALIZER;

@end

namespace shell {

class AccessibilityBridge final : public semantics::SemanticsListener {
 public:
  AccessibilityBridge(UIView*, mojo::ServiceProvider*);
  ~AccessibilityBridge() override;

  void UpdateSemanticsTree(mojo::Array<semantics::SemanticsNodePtr>) override;

  UIView* view() { return view_; }
  semantics::SemanticsServer* server() { return semantics_server_.get(); }

 private:
  SemanticObject* UpdateSemanticObject(
      const semantics::SemanticsNodePtr& node,
      std::set<SemanticObject*>* updated_objects,
      std::set<SemanticObject*>* removed_objects);
  void RemoveSemanticObject(SemanticObject* node,
                            std::set<SemanticObject*>* updated_objects);

  UIView* view_;
  semantics::SemanticsServerPtr semantics_server_;
  std::unordered_map<int, SemanticObject*> objects_;

  mojo::Binding<semantics::SemanticsListener> binding_;

  FTL_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge);
};

}  // namespace shell

#endif  // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_


text:
* https://golang.org/

### ppt for language compare
* 并发效率和代码简洁度 http://talks.golang.org/2014/gocon-tokyo.slide#31
* 可读性和运行效率比较 http://talks.golang.org/2014/gocon-tokyo.slide#28

### go指南
* https://tour.go-zh.org/list
* Go 切片:用法和本质 https://blog.go-zh.org/go-slices-usage-and-internals

### oop in go
* http://www.goinggo.net/2013/07/object-oriented-programming-in-go.html

### Go Concurrency Patterns
* https://talks.go-zh.org/2012/concurrency.slide#1

### books
* the way to Go https://github.com/Unknwon/the-way-to-go_ZH_CN
* Go圣经: 《The Go Programming Language》 https://github.com/golang-china/gopl-zh

### video
* https://www.youtube.com/watch?v=CF9S4QZuV30
* 《Go编程基础》 https://github.com/Unknwon/go-fundamental-programming


text:
[![NPM version](http://img.shields.io/npm/v/terra-avatar.svg)](https://www.npmjs.org/package/terra-avatar)
[![Build Status](https://travis-ci.org/cerner/terra-core.svg?branch=master)](https://travis-ci.org/cerner/terra-core)

The terra-avatar component displays an avatar, which can be either an image or text, in a circular frame. If neither an image or text is provided, a variant-based fallback icon is used.

- [Getting Started](#getting-started)
- [Documentation](https://github.com/cerner/terra-core/tree/master/packages/terra-avatar/docs)
- [LICENSE](#license)

## Getting Started

- Install from [npmjs](https://www.npmjs.com): `npm install terra-avatar`

## LICENSE

Copyright 2018 Cerner Innovation, Inc.

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.


text:
/**
 * Created by feichongzheng on 16/12/30.
 */
import Config from '../config.json';
import Package from '../../../package.json';

const createIframe = (callback) => {
    const version = Package.version;
    let loginIframe = document.createElement('iframe');
    loginIframe.src = Config.location + '/' + version +'/login.html';
    loginIframe.width = '0';
    loginIframe.height = '0';
    loginIframe.style.border = '0';
    loginIframe.style.position = 'absolute';
    let first = document.body.firstChild;

    document.body.insertBefore(loginIframe, first);
    callback && iframeOnload(callback);
};

const iframeOnload = (callback) => {
    if (loginIframe.attachEvent) {
        loginIframe.attachEvent('onload', () => {
            callback();
        });
    } else {
        loginIframe.onload = () => {
            callback();
        };
    }
};

const LoginFrame = {
    createIframe: createIframe,
};

export default LoginFrame;


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('bandwidthtest', '0002_auto_20150525_2156'),
    ]

    operations = [
        migrations.AlterField(
            model_name='bandwidthtest',
            name='test_start',
            field=models.DateTimeField(unique=True),
            preserve_default=True,
        ),
    ]


text:
require 'spec_helper'

describe CourseController do

  describe "GET 'index'" do
  	before { controller.stub(:authenticate_user!).and_return true }
    it "returns http success" do
      get "/courses"
      response.should be_success
    end
  end

end


text:
package com.facebook.buck.cli;

import com.facebook.buck.support.cli.args.PluginBasedSubCommandFactory;
import com.facebook.buck.support.cli.args.PluginBasedSubCommands;
import com.google.common.collect.ImmutableList;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.ClassParser;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.IllegalAnnotationError;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.ParserProperties;
import org.kohsuke.args4j.spi.FieldSetter;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Setters;
import org.pf4j.PluginManager;

/**
 * {@link CmdLineParser} with nested options via the {@link AdditionalOptions} annotation.
 *
 * <p>Fields annotated with it should be of classes which have a default constructor, and will be
 * automatically instantiated.
 */
public class AdditionalOptionsCmdLineParser extends CmdLineParser {

  @SuppressWarnings("rawtypes")
  static final Comparator<OptionHandler> DEFAULT_COMPARATOR =
      Comparator.comparing(o -> o.option.toString());

  private final PluginManager pluginManager;

  /**
   * Creates a new command line owner that parses arguments/options and set them into the given
   * object.
   *
   * @param bean instance of a class annotated by {@link Option}, {@link Argument} and {@link
   *     AdditionalOptions}. This object will receive values. If this is null, the processing will
   *     be skipped, which is useful if you'd like to feed metadata from other sources.
   * @throws IllegalAnnotationError if the option bean class is using args4j annotations
   *     incorrectly.
   * @see CmdLineParser#CmdLineParser(Object)
   */
  public AdditionalOptionsCmdLineParser(PluginManager pluginManager, Object bean) {
    /**
     * Disable '@' syntax. We convert this ourselves in {@link BuckArgsMethods#expandAtFiles}, so
     * options passed to parseArgument() should already be properly expanded. This allows us to have
     * things like `buck run @file //:script -- @this_goes_to_the_script`, as @file is expanded
     * before hitting this method.
     */
    super(null, ParserProperties.defaults().withAtSyntax(false));
    this.pluginManager = pluginManager;

    // This is copied in simplified form from CmdLineParser constructor and put here to save the
    // reference to the plugin manager before doing the parsing of options.
    new ClassParser().parse(bean, this);
    getOptions().sort(DEFAULT_COMPARATOR);

    Set<Class<?>> visited = new HashSet<>();
    parseAnnotations(new ClassParser(), bean, visited);
  }

  public PluginManager getPluginManager() {
    return pluginManager;
  }

  private void parseAnnotations(ClassParser classParser, Object bean, Set<Class<?>> visited) {
    // The top-level bean was already parsed by the superclass constructor,
    // so an empty visited set means we're parsing the top-level bean.
    if (!visited.isEmpty()) {
      classParser.parse(bean, this); // 'Parse' the class of the bean looking for annotations.
    }
    Class<?> beanClass = bean.getClass();
    if (visited.contains(beanClass)) {
      throw new IllegalAnnotationError(beanClass.getCanonicalName() + " used more than once.");
    } else {
      visited.add(beanClass);
    }

    for (Field f : beanClass.getDeclaredFields()) {
      parseAdditionalOptions(classParser, bean, visited, f);
      parsePluginBasedOption(classParser, bean, visited, f);
    }
  }

  @SuppressWarnings("unchecked")
  private void parseAdditionalOptions(
      ClassParser classParser, Object bean, Set<Class<?>> visited, Field f) {
    if (f.isAnnotationPresent(AdditionalOptions.class)) {
      try {
        // TODO(vlada): nicer to do this lazily in parseArgument()
        Object fieldValue = f.getType().newInstance();
        Setters.create(f, bean).addValue(fieldValue);
        parseAnnotations(classParser, fieldValue, visited);
      } catch (CmdLineException | IllegalAccessException | InstantiationException e) {
        throw new RuntimeException(e);
      }
    }
  }

  private void parsePluginBasedOption(
      ClassParser classParser, Object bean, Set<Class<?>> visited, Field f) {
    if (f.isAnnotationPresent(PluginBasedSubCommands.class)) {
      PluginBasedSubCommands optionAnnotation = f.getAnnotation(PluginBasedSubCommands.class);
      ImmutableList<Object> commands =
          pluginManager.getExtensions(optionAnnotation.factoryClass()).stream()
              .map(PluginBasedSubCommandFactory::createSubCommand)
              .collect(ImmutableList.toImmutableList());

      new FieldSetter(bean, f).addValue(commands);
      commands.forEach(cmd -> parseAnnotations(classParser, cmd, visited));
    }
  }
}


text:
echo run this from the top-level SEAL directory as 'sh scripts save-and-index.sh'
echo you should edit the directories in these scripts and config files before running this:
echo
echo - scripts/seal.properties.saving-wrappers
echo -- change stopwordsList from /usr0/wcohen/code/seal/lib/stopwords.txt
echo -- optionally change cacheDir from /usr2/bigdata/seal/cache/kdd
echo -- change savedWrapperDir from /usr2/bigdata/seal/test/wrappers to SOMEWHERE/wrappers
echo -- ... and make sure that the directory SOMEWHERE exists
echo
echo - scripts/seal.properties.indexing-wrappers
echo -- change stopwordsList from /usr0/wcohen/code/seal/lib/stopwords.txt
echo -- change localRoot from /usr2/bigdata/seal/test to to SOMEWHERE
echo -- ... and make sure that directory exists but SOMEWHERE/index does NOT exist
echo
echo - scripts/save-wrappers.pl
echo -- change SEAL_DIR to be your seal cvs directory
echo -- optionally, change INPUT_FILE to be an appropriate list of concepts
echo -- change OUTPUT_LOG_DIR from '/usr2/bigdata/seal/test/kdd-wrapper-outputs/' to SOMEWHERE/something
echo -- ... and make sure that directory exists
echo
echo - scripts/index-wrappers.pl
echo -- change SEAL_DIR to be your seal cvs directory
echo -- change LOCAL_ROOT to the value of localRoot in seal.properties.indexing-wrappers
echo

cp scripts/seal.properties.saving-wrappers config/seal.properties
perl scripts/save-wrappers.pl

cp scripts/seal.properties.indexing-wrappers config/seal.properties
perl scripts/index-wrappers.pl


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lhd.keyboard" />


text:
ruby-codekata
=============

Codekata using ruby


text:
package com.yxy.chukonu.java.dp.command;

public class Keyboard {
	private Command playCommand;
	private Command rewindCommand;
	private Command stopCommand;

    public void setPlayCommand(Command playCommand) {
        this.playCommand = playCommand;
    }

    public void setRewindCommand(Command rewindCommand) {
        this.rewindCommand = rewindCommand;
    }

    public void setStopCommand(Command stopCommand) {
        this.stopCommand = stopCommand;
    }

    /**
     * 执行播放方法
     */
    public void play(){
        playCommand.execute();
    }

    /**
     * 执行倒带方法
     */
    public void rewind(){
        rewindCommand.execute();
    }

    /**
     * 执行播放方法
     */
    public void stop(){
        stopCommand.execute();
    }

}


text:
You decided to move forward...

That's clever.

But wait. The rat starts growing in size.

You better look scared.

The dark place has some light now.Not the spotlight!!

A fire ring around your battlefield. Yes,a battlefield!!

[Start fighting](fight/fight.md)

[Yes you don't have an option!!!Start fighting!!!](fight/fight.md)


text:
#!/usr/bin/env bash
#
# Git worktree switcher
#
# Usage:
#     Source this in your .bashrc and call `worktree` in your working
#     directory. Calling with no arguments lists existing worktrees if any.
#
#     `worktree <name>` changes current directory to named worktree.
#     `worktree --main` changes current directory to main working copy.

__worktree_cd() {
    MAIN_DIR=$1
    WORK_TREE=$2

    if [ "--main" == "$WORK_TREE" ] || [ "-m" == "$WORK_TREE" ]; then
        cd $MAIN_DIR
        return
    fi

    if [ ! -d "$MAIN_DIR/.git/worktrees/$WORK_TREE" ]; then
        echo "No such worktree '$WORK_TREE'"
        return 1
    fi

    gitdir=$(cat $MAIN_DIR/.git/worktrees/$WORK_TREE/gitdir)
    dir=$(dirname $gitdir)
    cd $dir
}

__worktree_ls() {
    MAIN_DIR=$1
    echo "Worktrees:"

    for worktree in $MAIN_DIR/.git/worktrees/* ; do
        name=$(basename $worktree)
        dir=$(dirname $(cat $worktree/gitdir))
        echo $'\t'"$name "$'\t'"- $dir"
    done
    echo '`worktree <name>` switches to named worktree'
}

__worktree_in_maindir() {
    gitdir="$1"
    targetdir="$2"

    if [ ! -d "$gitdir/.git/worktrees" ]; then
        echo "No worktrees"
        return
    fi

    if [ -z "$targetdir" ]; then
        __worktree_ls "$gitdir"
    else
        __worktree_cd "$gitdir" "$targetdir"
    fi
}

__worktree_in_workdir() {
    gitdir="$1"
    targetdir="$2"

    MAIN_DIR=$(cat "$gitdir/.git" | sed 's/gitdir: //' | sed 's/\/\.git.*//')

    if [ -z "$targetdir" ]; then
        echo "In worktree $gitdir"
        echo "       from $MAIN_DIR"
        echo '`worktree --main` switches to main dir'
        echo
        __worktree_ls "$MAIN_DIR"
    else
        __worktree_cd "$MAIN_DIR" "$targetdir"
    fi
}

__worktree_complete() {
    local list=""

    gitdir=$(git rev-parse --show-toplevel)
    if [ -d "$gitdir/.git" ]; then
        MAIN_DIR=$gitdir
    elif [ -f "$gitdir/.git" ]; then
        MAIN_DIR=$(cat "$gitdir/.git" | sed 's/gitdir: //' | sed 's/\/\.git.*//')
        list="--main"
        current_tree=$(cat "$gitdir/.git" | sed 's/gitdir: //')
    fi

    if [ -z "$MAIN_DIR" ]; then
        COMPREPLY=()
        return
    fi

    if [ ! -d "$MAIN_DIR/.git/worktrees" ]; then
        COMPREPLY=()
        return
    fi

    if [ $COMP_CWORD -gt 1 ]; then
        COMPREPLY=()
        return
    fi

    local cur=${COMP_WORDS[COMP_CWORD]}

    for worktree in $MAIN_DIR/.git/worktrees/* ; do
        if [ "$current_tree" != "$worktree" ]; then
            name=$(basename $worktree)
            if [ -z "$list" ]; then
                list="$name"
            else
                list="$list $name"
            fi
        fi
    done

    COMPREPLY=( $(compgen -W "$list" -- $cur) )
}

worktree() {
    gitdir=$(git rev-parse --show-toplevel)
    if [ -d "$gitdir/.git" ]; then
        __worktree_in_maindir "$gitdir" $*
    elif [ -f "$gitdir/.git" ]; then
        __worktree_in_workdir "$gitdir" $*
    else
        echo "Not in a git workspace"
        return 1
    fi
}

complete -F __worktree_complete worktree


text:
<?php
require_once ('/var/www/html/app/model/connect.php');

function insertUselog(){

	//print_r($_POST);

if (isset($_POST)) {
    $equipid = $_POST['equipid'];
    $equipname = $_POST['equipname'];
	$empid = $_POST['empid'];
	$zoneid = $_POST['zoneid'];
    $borrowdate = $_POST['borrowdate'];
    $returndate = $_POST['returndate'];

	// an array that want to insert this can be multiple array at the time.
   $data = array($equipid,$equipname,$empid,$zoneid );

 // print var_dump to display an array of variable data with type that prepare for query.
 //echo var_dump($data) ."
";
}

// define $conn from model
$conn = dbConnect();

if ($conn) {
$sql = 'INSERT INTO EMM_ZOO.SANI_EQUIPUSELOG (EQUIPID, EMPID, WORKZONEID, BORROWDATE, RETURNDATE) VALUES (?,?,?,?,?);';
//$sql2 = 'INSERT INTO EMM_ZOO.EMP_SANI (EMPID) VALUES (?);';
//echo $sql;
// prepare statement using connection and sql
$stmt = db2_prepare($conn, $sql);
// If statement is valid execute it to db2
if ($stmt) {
	    //echo "SQL is valid
";
    $result = db2_execute($stmt, $data);
    if ($result) {
        $resultMessage = "Successfully added to Equipment use log";
        //echo "Successfully added";
        echo "";
         header('Location: addUselogHome.php');
         exit();
    }
    else {
    	  $resultMessage = "Failed to query into database";
    	   echo "";
    }
}
else { // If statement is error why see the code
	 die('Critical error:' . db2_stmt_error());
}
db2_free_stmt($stmt);
db2_close($conn);
}
// callback alert if failed to connect to database return msg
else {
   echo db2_conn_errormsg();
}
}

?>


text:
"""Test class for iBoot PDU driver module."""

import types

import mock

from ironic.common import driver_factory
from ironic.common import exception
from ironic.common import states
from ironic.conductor import task_manager
from ironic.drivers.modules import iboot
from ironic.tests.conductor import utils as mgr_utils
from ironic.tests.db import base as db_base
from ironic.tests.db import utils as db_utils
from ironic.tests.objects import utils as obj_utils

INFO_DICT = db_utils.get_test_iboot_info()

class IBootPrivateMethodTestCase(db_base.DbTestCase):

    def setUp(self):
        super(IBootPrivateMethodTestCase, self).setUp()
        self.config(max_retry=0, group='iboot')
        self.config(retry_interval=0, group='iboot')

    def test__parse_driver_info_good(self):
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)
        self.assertIsNotNone(info.get('address'))
        self.assertIsNotNone(info.get('username'))
        self.assertIsNotNone(info.get('password'))
        self.assertIsNotNone(info.get('port'))
        self.assertIsNotNone(info.get('relay_id'))

    def test__parse_driver_info_good_with_explicit_port(self):
        info = dict(INFO_DICT)
        info['iboot_port'] = '1234'
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        info = iboot._parse_driver_info(node)
        self.assertEqual(1234, info.get('port'))

    def test__parse_driver_info_good_with_explicit_relay_id(self):
        info = dict(INFO_DICT)
        info['iboot_relay_id'] = '2'
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        info = iboot._parse_driver_info(node)
        self.assertEqual(2, info.get('relay_id'))

    def test__parse_driver_info_missing_address(self):
        info = dict(INFO_DICT)
        del info['iboot_address']
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        self.assertRaises(exception.MissingParameterValue,
                          iboot._parse_driver_info,
                          node)

    def test__parse_driver_info_missing_username(self):
        info = dict(INFO_DICT)
        del info['iboot_username']
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        self.assertRaises(exception.MissingParameterValue,
                          iboot._parse_driver_info,
                          node)

    def test__parse_driver_info_missing_password(self):
        info = dict(INFO_DICT)
        del info['iboot_password']
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        self.assertRaises(exception.MissingParameterValue,
                          iboot._parse_driver_info,
                          node)

    def test__parse_driver_info_bad_port(self):
        info = dict(INFO_DICT)
        info['iboot_port'] = 'not-integer'
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        self.assertRaises(exception.InvalidParameterValue,
                          iboot._parse_driver_info,
                          node)

    def test__parse_driver_info_bad_relay_id(self):
        info = dict(INFO_DICT)
        info['iboot_relay_id'] = 'not-integer'
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=info)
        self.assertRaises(exception.InvalidParameterValue,
                          iboot._parse_driver_info,
                          node)

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_on(self, mock_get_conn):
        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        mock_connection.get_relays.return_value = [True]
        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)

        status = iboot._power_status(info)

        self.assertEqual(states.POWER_ON, status)
        mock_get_conn.assert_called_once_with(info)
        mock_connection.get_relays.assert_called_once_with()

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_off(self, mock_get_conn):
        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        mock_connection.get_relays.return_value = [False]
        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)

        status = iboot._power_status(info)

        self.assertEqual(states.POWER_OFF, status)
        mock_get_conn.assert_called_once_with(info)
        mock_connection.get_relays.assert_called_once_with()

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_exception(self, mock_get_conn):
        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        mock_connection.get_relays.return_value = None
        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)

        status = iboot._power_status(info)
        self.assertEqual(states.ERROR, status)
        mock_get_conn.assert_called_once_with(info)
        mock_connection.get_relays.assert_called_once_with()

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_exception_type_error(self, mock_get_conn):
        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        side_effect = TypeError("Surprise!")
        mock_connection.get_relays.side_effect = side_effect

        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)

        status = iboot._power_status(info)
        self.assertEqual(states.ERROR, status)
        mock_get_conn.assert_called_once_with(info)
        mock_connection.get_relays.assert_called_once_with()

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_exception_index_error(self, mock_get_conn):
        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        side_effect = IndexError("Gotcha!")
        mock_connection.get_relays.side_effect = side_effect

        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)
        status = iboot._power_status(info)
        self.assertEqual(states.ERROR, status)

        mock_get_conn.assert_called_once_with(info)
        mock_connection.get_relays.assert_called_once_with()

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_error(self, mock_get_conn):
        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        mock_connection.get_relays.return_value = list()
        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)

        status = iboot._power_status(info)

        self.assertEqual(states.ERROR, status)
        mock_get_conn.assert_called_once_with(info)
        mock_connection.get_relays.assert_called_once_with()

    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__power_status_retries(self, mock_get_conn):
        self.config(max_retry=1, group='iboot')

        mock_connection = mock.MagicMock(spec_set=['get_relays'])
        side_effect = TypeError("Surprise!")
        mock_connection.get_relays.side_effect = side_effect

        mock_get_conn.return_value = mock_connection
        node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        info = iboot._parse_driver_info(node)

        status = iboot._power_status(info)
        self.assertEqual(states.ERROR, status)
        mock_get_conn.assert_called_once_with(info)
        self.assertEqual(2, mock_connection.get_relays.call_count)

class IBootDriverTestCase(db_base.DbTestCase):

    def setUp(self):
        super(IBootDriverTestCase, self).setUp()
        self.config(max_retry=0, group='iboot')
        self.config(retry_interval=0, group='iboot')
        mgr_utils.mock_the_extension_manager(driver='fake_iboot')
        self.driver = driver_factory.get_driver('fake_iboot')
        self.node = obj_utils.create_test_node(
            self.context,
            driver='fake_iboot',
            driver_info=INFO_DICT)
        self.info = iboot._parse_driver_info(self.node)

    def test_get_properties(self):
        expected = iboot.COMMON_PROPERTIES
        with task_manager.acquire(
                self.context, self.node.uuid, shared=True) as task:
            self.assertEqual(expected, task.driver.get_properties())

    @mock.patch.object(iboot, '_power_status', autospec=True)
    @mock.patch.object(iboot, '_switch', autospec=True)
    def test_set_power_state_good(self, mock_switch, mock_power_status):
        mock_power_status.return_value = states.POWER_ON

        with task_manager.acquire(self.context, self.node.uuid) as task:
            task.driver.power.set_power_state(task, states.POWER_ON)

        # ensure functions were called with the valid parameters
        mock_switch.assert_called_once_with(self.info, True)
        mock_power_status.assert_called_once_with(self.info)

    @mock.patch.object(iboot, '_power_status', autospec=True)
    @mock.patch.object(iboot, '_switch', autospec=True)
    def test_set_power_state_bad(self, mock_switch, mock_power_status):
        mock_power_status.return_value = states.POWER_OFF

        with task_manager.acquire(self.context, self.node.uuid) as task:
            self.assertRaises(exception.PowerStateFailure,
                              task.driver.power.set_power_state,
                              task, states.POWER_ON)

        # ensure functions were called with the valid parameters
        mock_switch.assert_called_once_with(self.info, True)
        mock_power_status.assert_called_once_with(self.info)

    @mock.patch.object(iboot, '_power_status', autospec=True)
    @mock.patch.object(iboot, '_switch', autospec=True)
    def test_set_power_state_invalid_parameter(self, mock_switch,
                                               mock_power_status):
        mock_power_status.return_value = states.POWER_ON

        with task_manager.acquire(self.context, self.node.uuid) as task:
            self.assertRaises(exception.InvalidParameterValue,
                              task.driver.power.set_power_state,
                              task, states.NOSTATE)

    @mock.patch.object(iboot, '_power_status', autospec=True)
    @mock.patch.object(iboot, '_switch', spec_set=types.FunctionType)
    def test_reboot_good(self, mock_switch, mock_power_status):
        manager = mock.MagicMock(spec_set=['switch'])
        mock_power_status.return_value = states.POWER_ON

        manager.attach_mock(mock_switch, 'switch')
        expected = [mock.call.switch(self.info, False),
                    mock.call.switch(self.info, True)]

        with task_manager.acquire(self.context, self.node.uuid) as task:
            task.driver.power.reboot(task)

        self.assertEqual(manager.mock_calls, expected)

    @mock.patch.object(iboot, '_power_status', autospec=True)
    @mock.patch.object(iboot, '_switch', spec_set=types.FunctionType)
    def test_reboot_bad(self, mock_switch, mock_power_status):
        manager = mock.MagicMock(spec_set=['switch'])
        mock_power_status.return_value = states.POWER_OFF

        manager.attach_mock(mock_switch, 'switch')
        expected = [mock.call.switch(self.info, False),
                    mock.call.switch(self.info, True)]

        with task_manager.acquire(self.context, self.node.uuid) as task:
            self.assertRaises(exception.PowerStateFailure,
                              task.driver.power.reboot, task)

        self.assertEqual(manager.mock_calls, expected)

    @mock.patch.object(iboot, '_power_status', autospec=True)
    @mock.patch.object(iboot, '_get_connection', autospec=True)
    def test__switch_retries(self, mock_get_conn, mock_power_status):
        self.config(max_retry=1, group='iboot')
        mock_power_status.return_value = states.POWER_ON

        mock_connection = mock.MagicMock(spec_set=['switch'])
        side_effect = TypeError("Surprise!")
        mock_connection.switch.side_effect = side_effect
        mock_get_conn.return_value = mock_connection

        iboot._switch(self.info, False)
        self.assertEqual(2, mock_connection.switch.call_count)

    @mock.patch.object(iboot, '_power_status', autospec=True)
    def test_get_power_state(self, mock_power_status):
        mock_power_status.return_value = states.POWER_ON

        with task_manager.acquire(self.context, self.node.uuid) as task:
            state = task.driver.power.get_power_state(task)
            self.assertEqual(state, states.POWER_ON)

        # ensure functions were called with the valid parameters
        mock_power_status.assert_called_once_with(self.info)

    @mock.patch.object(iboot, '_parse_driver_info', autospec=True)
    def test_validate_good(self, parse_drv_info_mock):
        with task_manager.acquire(self.context, self.node.uuid,
                                  shared=True) as task:
            task.driver.power.validate(task)
        self.assertEqual(1, parse_drv_info_mock.call_count)

    @mock.patch.object(iboot, '_parse_driver_info', autospec=True)
    def test_validate_fails(self, parse_drv_info_mock):
        side_effect = iter([exception.InvalidParameterValue("Bad input")])
        parse_drv_info_mock.side_effect = side_effect
        with task_manager.acquire(self.context, self.node.uuid,
                                  shared=True) as task:
            self.assertRaises(exception.InvalidParameterValue,
                              task.driver.power.validate, task)
        self.assertEqual(1, parse_drv_info_mock.call_count)


text:
package org.elasticsearch.test.unit.index.search.nested;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.index.IndexableField;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.fieldcomparator.LongValuesComparatorSource;
import org.elasticsearch.index.fielddata.fieldcomparator.SortMode;
import org.elasticsearch.index.fielddata.plain.LongArrayIndexFieldData;

/**
 */
public class LongNestedSortingTests extends AbstractNumberNestedSortingTests {

    @Override
    protected FieldDataType getFieldDataType() {
        return new FieldDataType("long");
    }

    @Override
    protected IndexFieldData.XFieldComparatorSource createInnerFieldComparator(String fieldName, SortMode sortMode) {
        LongArrayIndexFieldData fieldData = getForField(fieldName);
        return new LongValuesComparatorSource(fieldData, null, sortMode);
    }

    @Override
    protected IndexableField createField(String name, int value, Field.Store store) {
        return new LongField(name, value, store);
    }

}


text:
SELECT row_to_json(t)
from (
SELECT * FROM pg_stat_database
) t;


text: Better than TwistTheWeb.com