text:
namespace google_drive_api {
using namespace googleapis;

// Object factory method (static).
ParentReference* ParentReference::New() {
  return new client::JsonCppCapsule<ParentReference>;
}

// Standard immutable constructor.
ParentReference::ParentReference(const Json::Value& storage)
  : client::JsonCppData(storage) {
}

// Standard mutable constructor.
ParentReference::ParentReference(Json::Value* storage)
  : client::JsonCppData(storage) {
}

// Standard destructor.
ParentReference::~ParentReference() {
}
}  // namespace google_drive_api


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                 Code sequence state machine generator                     XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

#include "smgen.h"
#include "smcommon.cpp"

static bool debug = false;

#define debugprint(x) if (debug) printf x;

//
// State machine generator
//

SMGen::SMGen()
{
    memset(this, 0, sizeof(*this));

    States[SM_STATE_ID_START].id = SM_STATE_ID_START;
    SMGenDestStateDesc * pDestStateListHead = new SMGenDestStateDesc();
    pDestStateListHead->next                = NULL;
    States[SM_STATE_ID_START].destStateList = pDestStateListHead;

    lastStateID = 1;

    //
    // Process all interesting code sequences
    //

    debugprint(("\n======== The code sequences =================\n"));

    SM_OPCODE * CodeSeqs = (SM_OPCODE *)s_CodeSeqs;

    while (*CodeSeqs != CODE_SEQUENCE_END)
    {
        ProcessSeq(CodeSeqs);
        CodeSeqs += MAX_CODE_SEQUENCE_LENGTH;
    }

    debugprint(("\n======== The state machine =================\n"));

    for (SM_STATE_ID i=1; i<=lastStateID; ++i)
    {
        debugprint(("State %-4d : length=%-2d prev=%-4d lngest=%-4d  (%c) Desc=[%s]\n",
               i, States[i].length, States[i].prevState, States[i].longestTermState,
               States[i].term?'*':' ', StateDesc(i)));

        for (unsigned j=0; j<SM_COUNT; ++j)
        {
            if (States[i].getDestState((SM_OPCODE)j) != 0)
            {
                debugprint(("    [%s] ==> %d\n",
                       smOpcodeNames[(SM_OPCODE)j],
                       States[i].getDestState((SM_OPCODE)j)));
            }
        }
    }

    debugprint(("\n# MethodName| NativeSize| ILBytes| ILInstrCount| 0Args| 1Args| 2Args| 3AndMoreArgs| NoLocals| NoCalls"));

    unsigned termStateCount = 0;

    for (SM_STATE_ID i=1; i<=lastStateID; ++i)
    {
        if (States[i].term)
        {
            ++termStateCount;
            debugprint(("| %s[%d]", StateDesc(i), i));
        }
    }

    debugprint(("\n\n%d termination states.\n", termStateCount));
}

SMGen::~SMGen()
{
}

void  SMGen::ProcessSeq(SM_OPCODE * CodeSeq)
{
    SM_STATE_ID longestTermState = 0;

    SM_STATE_ID curState = SM_STATE_ID_START;
    BYTE        curLen = 0;

    SM_OPCODE * pOpcode = CodeSeq;
    SM_OPCODE   opcode;

    debugprint(("\nCodeSeq : {"));

    do
    {
        opcode = * pOpcode;

        debugprint(("%s, " , smOpcodeNames[opcode]));

        assert(curLen < MAX_CODE_SEQUENCE_LENGTH);
        assert(curLen < 255);

        ++curLen;

        SM_STATE_ID nextState = States[curState].getDestState(opcode);
        if (nextState == 0)
        {
            // Need to create a new state
            assert(lastStateID < MAX_NUM_STATES);
            ++lastStateID;

            States[curState].setDestState(opcode, lastStateID);

            States[lastStateID].id               = lastStateID;
            States[lastStateID].longestTermState = longestTermState;
            States[lastStateID].prevState        = curState;
            States[lastStateID].opc              = opcode;
            States[lastStateID].term             = false;

            SMGenDestStateDesc * pDestStateListHead = new SMGenDestStateDesc();
            pDestStateListHead->next                = NULL;
            States[lastStateID].destStateList       = pDestStateListHead;

            curState = lastStateID;
            States[curState].length = curLen;
        }
        else
        {
            curState = nextState;
            if (States[curState].term)
            {
                longestTermState = curState;
            }
        }
    }
    while (* (++pOpcode) != CODE_SEQUENCE_END);

    assert(curState != SM_STATE_ID_START);
    assert(!States[curState].term && "Duplicated rule.");

    States[curState].term = true;

    debugprint(("    }\n"));
}

void  SMGen::Emit()
{
    // Zero out the entire buffer.
    memset(&emitBuffer, 0, sizeof(emitBuffer));

    BYTE * pBuffer = (BYTE *)&emitBuffer;
    pAllStates = (SMState *) pBuffer;

    pBuffer += sizeof(*pAllStates) * (lastStateID+1);
    pAllJumpTables = (JumpTableCell *) pBuffer;

    pJumpTableMax  = 0;

    //
    // Loop through each state and fill in the buffer
    //
    for (SM_STATE_ID i=1; i<=lastStateID; ++i)
    {
        SMState *  pState = pAllStates+i;

        pState->term             = States[i].term;
        pState->length           = States[i].length;
        pState->longestTermState = States[i].longestTermState;
        pState->prevState        = States[i].prevState;
        pState->opc              = States[i].opc;
        pState->jumpTableByteOffset  = JumpTableSet(i);

    }

    debugprint(("pJumpTableMax at starts at cell# %d\n", pJumpTableMax-pAllJumpTables));

    totalCellNeeded = pJumpTableMax - pAllJumpTables + SM_COUNT;

    debugprint(("MAX_NUM_STATES = %d\n", MAX_NUM_STATES));
    debugprint(("Actual total number of states = %d\n", lastStateID+1));
    assert(lastStateID+1 <= MAX_NUM_STATES);

    debugprint(("Total number of cells  = %d\n", totalCellNeeded));
    assert(totalCellNeeded <= MAX_CELL_COUNT);

    debugprint(("sizeof(SMState) = %d\n", sizeof(SMState)));
    debugprint(("sizeof(JumpTableCell) = %d\n", sizeof(JumpTableCell)));
    debugprint(("sizeof(emitBuffer) = %d\n", sizeof(emitBuffer)));

    EmitDone();
}

void  SMGen::EmitDone()
{
    printf("// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    printf("//\n");
    printf("//   Automatically generated code. DO NOT MODIFY! \n");
    printf("//   To generate this file. Do \"smgen.exe > SMData.cpp\" \n");
    printf("//\n");
    printf("// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");

    printf("#include \"jitpch.h\"\n");

    printf("//\n");
    printf("// States in the state machine\n");
    printf("//\n");

    printf("const SMState g_SMStates[] = \n{\n");

    printf(" // {term, len, lng, prev, SMOpcode and SMOpcodeName           , offsets  }           //  state ID and name\n");

    // Print out states
    for (SM_STATE_ID id=0; id<=lastStateID; ++id)
    {
        SMState *  pState = pAllStates+id;
        printf("    {");
        printf("%4d, ",  pState->term);
        printf("%3d, ",  pState->length);
        printf("%3d, ",  pState->longestTermState);
        printf("%4d, ",  pState->prevState);
        printf("(SM_OPCODE)%3d /* %-15s */, ",  pState->opc, smOpcodeNames[pState->opc]);
        printf("%7d" ,  pState->jumpTableByteOffset);

        printf("  },          //  ");
        printf("state %d [%s]", id,  StateDesc(id));

        printf("\n");
    }

    printf("};\n\n");

    printf("static_assert_no_msg(NUM_SM_STATES == sizeof(g_SMStates)/sizeof(g_SMStates[0]));\n\n");

    printf("const SMState * gp_SMStates = g_SMStates;\n\n");

    printf("//\n");
    printf("// JumpTableCells in the state machine\n");
    printf("//\n");

    printf("const JumpTableCell g_SMJumpTableCells[] = \n{\n");
    printf(" // {src, dest  }\n");

    for (unsigned i=0; i<totalCellNeeded; ++i)
    {
        JumpTableCell * cell = pAllJumpTables+i;

        printf("    {");
        printf("%3d, ", cell->srcState);
        printf("%4d",  cell->destState);
        printf("  },   // cell# %d", i);

        if (cell->srcState != 0)
        {
            JumpTableCell * pThisJumpTable =
                (JumpTableCell * )(((PBYTE)pAllJumpTables) + pAllStates[cell->srcState].jumpTableByteOffset);

            assert(cell >= pThisJumpTable);

            SM_OPCODE opcode = (SM_OPCODE) (cell - pThisJumpTable);

            printf(" : state %d [%s]", cell->srcState, StateDesc(cell->srcState));

            printf(" --(%d %s)--> ", opcode, smOpcodeNames[opcode]);

            printf("state %d [%s]", cell->destState, StateDesc(cell->destState));
        }
        printf("\n");
     }

    printf("};\n\n");

    printf("const JumpTableCell * gp_SMJumpTableCells = g_SMJumpTableCells;\n\n");
}

unsigned short  SMGen::JumpTableSet(SM_STATE_ID id)
{
    JumpTableCell * pThisJumpTable = pAllJumpTables;

    while (true)
    {
        if (bJumpTableFit(pThisJumpTable, id))
        {
            JumpTableFill(pThisJumpTable, id);

            if (pThisJumpTable > pJumpTableMax)
                pJumpTableMax = pThisJumpTable;

            unsigned offset = ((BYTE*)pThisJumpTable) - ((BYTE*)pAllJumpTables);

            assert(offset == (unsigned short)offset);

            return (unsigned short)offset;
        }

        ++pThisJumpTable;
    }
}

bool   SMGen::bJumpTableFit(JumpTableCell * pTable, SM_STATE_ID id)
{
    SMGenDestStateDesc * p = States[id].destStateList->next; // Skip the list head.

    while (p)
    {
        SM_OPCODE opcode = p->opcode;
        JumpTableCell * pCell = pTable + opcode;
        if (pCell->srcState != 0)
        {
            // This cell has been occupied.
            return false;
        }

        p = p->next;
    }

    debugprint(("JumpTable for state %d [%s] starts at cell# %d:\n",
               id,
               StateDesc(id),
               pTable-pAllJumpTables));
    return true;
}

void   SMGen::JumpTableFill(JumpTableCell * pTable, SM_STATE_ID id)
{
    SMGenDestStateDesc * p = States[id].destStateList->next;  // Skip the list head.

    while (p)
    {
        SM_OPCODE opcode = p->opcode;
        JumpTableCell * pCell = pTable + opcode;
        assert(pCell->srcState == 0);

        pCell->srcState  = id;
        pCell->destState = p->destState;

        debugprint(("    cell# %d : [%s (%d)] --> %d\n",
                   pCell-pAllJumpTables,
                   smOpcodeNames[opcode],
                   opcode,
                   pCell->destState));

        p = p->next;
    }
}

char * SMGen::StateDesc(SM_STATE_ID stateID)
{
    static char      s_StateDesc[500];
    static SM_OPCODE s_StateDescOpcodes[MAX_CODE_SEQUENCE_LENGTH];

    if (stateID == 0)
        return "invalid";

    if (stateID == SM_STATE_ID_START)
        return "start";

    unsigned i = 0;

    SM_STATE_ID b = stateID;

    while (States[b].prevState != 0)
    {
        s_StateDescOpcodes[i] = States[b].opc;
        b = States[b].prevState;
        ++i;
    }

    assert(i == States[stateID].length && i>0);

    * s_StateDesc = 0;

    while (--i>0)
    {
        strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[i]]);
        strcat(s_StateDesc, " -> ");
    }

    strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[0]]);

    return s_StateDesc;
}

SM_STATE_ID  SMGenState::getDestState(SM_OPCODE opcode)
{
    assert(opcode < SM_COUNT);

    SMGenDestStateDesc * p = destStateList->next;  // Skip the list head.
    int lastSeenOpcode = -1;

    while (p)
    {
       assert(lastSeenOpcode < p->opcode); // opcode should be in accending order.
       lastSeenOpcode = p->opcode;
       if (p->opcode == opcode)
       {
           assert(p->destState != 0);
           return p->destState;
       }
       p = p->next;
    }

    return 0;
}

void  SMGenState::setDestState(SM_OPCODE opcode, SM_STATE_ID destState)
{
    assert(id != 0);  // Should not have come here for the invalid state.

    assert(getDestState(opcode) == 0); // Don't set it twice.

    SMGenDestStateDesc * newSMGenDestStateDesc = new SMGenDestStateDesc();

    newSMGenDestStateDesc->opcode    = opcode;
    newSMGenDestStateDesc->destState = destState;

    // Insert the new entry in accending order

    SMGenDestStateDesc * p = destStateList;
    SMGenDestStateDesc * q = p->next;

    while (q)
    {
        if (q->opcode > opcode)
            break;

        p = q;
        q = q->next;
    }

    newSMGenDestStateDesc->next = p->next;
    p->next                     = newSMGenDestStateDesc;
}

void Usage()
{
    printf("JIT code sequence state machine generator\n");
    printf("==============================================\n");
    printf("smgen -?   : Print usage.\n");
    printf("smgen      : Generate static array for the state machine.\n");
    printf("smgen debug: Print debug info.\n");
}

//-----------------------------------------------------------------------------
// main
//-----------------------------------------------------------------------------
extern "C" int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv)
{
    if (argc > 1)
    {
        if (wcscmp(argv[1], W("-?")) == 0  || wcscmp(argv[1], W("/?")) == 0)
        {
            Usage();
            return 1;
        }

        if (wcscmp(argv[1], W("debug")) == 0)
        {
            debug = true;
        }
    }

    // Generate the state machine
    SMGen smGen;
    smGen.Emit();

    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
module TrelloImporter
  VERSION = "0.1.0"
end


text:
package com.asofdate.batch.dao.impl;

import com.asofdate.batch.dao.BatchGroupDao;
import com.asofdate.batch.dao.impl.sql.BatchSqlText;
import com.asofdate.batch.entity.BatchGroupEntity;
import com.asofdate.batch.entity.GroupDependencyEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * Created by hzwy23 on 2017/5/24.
 */
@Repository
public class BatchGroupDaoImpl implements BatchGroupDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BatchSqlText batchSqlText;

    @Override
    public List findAll(String domainId, String batchId) {
        RowMapper<BatchGroupEntity> rowMapper = new BeanPropertyRowMapper<>(BatchGroupEntity.class);
        return jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_106"), rowMapper, domainId, batchId);
    }

    @Override
    public List<BatchGroupEntity> getGroup(String batchId) {
        RowMapper<BatchGroupEntity> rowMapper = new BeanPropertyRowMapper<>(BatchGroupEntity.class);
        return jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_137"), rowMapper, batchId);
    }

    @Transactional
    @Override
    public int addGroup(List<BatchGroupEntity> list) {
        for (BatchGroupEntity m : list) {

            String id = UUID.randomUUID().toString().replace("-", "");
            String batch_id = m.getBatchId();
            String group_id = m.getGroupId();
            String domain_id = m.getDomainId();

            if (1 != jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_154"),
                    id, batch_id, group_id, domain_id)) {
                return -1;
            }
        }
        return 1;
    }

    @Transactional
    @Override
    public int deleteGroup(List<BatchGroupEntity> list) {
        for (BatchGroupEntity m : list) {
            String id = m.getSuiteKey();
            if (1 != jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_155"), id)) {
                return -1;
            }
        }
        return 1;
    }

    @Override
    public List<BatchGroupEntity> getDependency(String batchid, String id) {
        List<BatchGroupEntity> list = getGroup(batchid);
        Set<String> set = getChildren(batchid, id);

        for (int i = 0; i < list.size(); i++) {
            String sub = list.get(i).getSuiteKey();
            if (set.contains(sub)) {
                list.remove(i);
                i--;
            }
        }
        return list;
    }

    private Set<String> getChildren(String batchId, String id) {
        RowMapper<GroupDependencyEntity> rowMapper = new BeanPropertyRowMapper<>(GroupDependencyEntity.class);
        List<GroupDependencyEntity> list = jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_073"), rowMapper, batchId);

        Set<String> set = new HashSet<>();
        children(list, id, set);
        set.add(id);

        for (BatchGroupEntity m : getOwner(id)) {
            set.add(m.getUpSuiteKey());
        }
        return set;
    }

    private List<BatchGroupEntity> getOwner(String id) {
        RowMapper<BatchGroupEntity> rowMapper = new BeanPropertyRowMapper<>(BatchGroupEntity.class);
        return jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_138"), rowMapper, id);
    }

    private void children(List<GroupDependencyEntity> all, String id, Set<String> set) {
        for (GroupDependencyEntity m : all) {
            String upId = m.getUpSuiteKey();
            if (upId == null || set.contains(m.getSuiteKey())) {
                continue;
            }
            if (id.equals(upId)) {
                set.add(m.getSuiteKey());
                children(all, m.getSuiteKey(), set);
            }
        }
    }

    @Override
    public List<BatchGroupEntity> getGroupDependency(String suiteKey) {
        RowMapper<BatchGroupEntity> rowMapper = new BeanPropertyRowMapper<>(BatchGroupEntity.class);
        return jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_138"), rowMapper, suiteKey);
    }

    @Override
    public int deleteGroupDependency(String uuid) {
        return jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_153"), uuid);
    }

    @Transactional
    @Override
    public int addGroupDependency(List<GroupDependencyEntity> list) {
        for (GroupDependencyEntity m : list) {
            String domainId = m.getDomainId();
            String id = m.getSuiteKey();
            String upId = m.getUpSuiteKey();
            if (1 != jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_156"), id, upId, domainId)) {
                return -1;
            }
        }
        return 1;
    }

}


text:
<?php

namespace ZF\Hal;

use Zend\Stdlib\Hydrator\HydratorPluginManager;
use Zend\Mvc\MvcEvent;

/**
 * ZF2 module
 */
class Module
{
    /**
     * Retrieve autoloader configuration
     *
     * @return array
     */
    public function getAutoloaderConfig()
    {
        return array('Zend\Loader\StandardAutoloader' => array('namespaces' => array(
            __NAMESPACE__ => __DIR__ . '/src/',
        )));
    }

    /**
     * Retrieve module configuration
     *
     * @return array
     */
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /**
     * Retrieve Service Manager configuration
     *
     * Defines ZF\Hal\JsonStrategy service factory.
     *
     * @return array
     */
    public function getServiceConfig()
    {
        return array('factories' => array(
            'ZF\Hal\MetadataMap' => function ($services) {
                $config = array();
                if ($services->has('config')) {
                    $config = $services->get('config');
                }

                if ($services->has('HydratorManager')) {
                    $hydrators = $services->get('HydratorManager');
                } else {
                    $hydrators = new HydratorPluginManager();
                }

                $map = array();
                if (isset($config['zf-hal'])
                    && isset($config['zf-hal']['metadata_map'])
                    && is_array($config['zf-hal']['metadata_map'])
                ) {
                    $map = $config['zf-hal']['metadata_map'];
                }

                return new Metadata\MetadataMap($map, $hydrators);
            },
            'ZF\Hal\JsonRenderer' => function ($services) {
                $helpers            = $services->get('ViewHelperManager');
                $apiProblemRenderer = $services->get('ZF\ApiProblem\ApiProblemRenderer');
                $config             = $services->get('Config');

                $renderer = new View\HalJsonRenderer($apiProblemRenderer);
                $renderer->setHelperPluginManager($helpers);

                return $renderer;
            },
            'ZF\Hal\JsonStrategy' => function ($services) {
                $renderer = $services->get('ZF\Hal\JsonRenderer');
                return new View\HalJsonStrategy($renderer);
            },
        ));
    }

    /**
     * Define factories for controller plugins
     *
     * Defines the "Hal" plugin.
     *
     * @return array
     */
    public function getControllerPluginConfig()
    {
        return array('factories' => array(
            'Hal' => function ($plugins) {
                $services = $plugins->getServiceLocator();
                $helpers  = $services->get('ViewHelperManager');
                return $helpers->get('Hal');
            },
        ));
    }

    /**
     * Defines the "Hal" view helper
     *
     * @return array
     */
    public function getViewHelperConfig()
    {
        return array('factories' => array(
            'Hal' => function ($helpers) {
                $serverUrlHelper = $helpers->get('ServerUrl');
                $urlHelper       = $helpers->get('Url');

                $services        = $helpers->getServiceLocator();
                $config          = $services->get('Config');
                $metadataMap     = $services->get('ZF\Hal\MetadataMap');
                $hydrators       = $metadataMap->getHydratorManager();

                $helper          = new Plugin\Hal($hydrators);
                $helper->setMetadataMap($metadataMap);
                $helper->setServerUrlHelper($serverUrlHelper);
                $helper->setUrlHelper($urlHelper);

                if (isset($config['zf-hal'])
                    && isset($config['zf-hal']['renderer'])
                ) {
                    $config = $config['zf-hal']['renderer'];

                    if (isset($config['default_hydrator'])) {
                        $hydratorServiceName = $config['default_hydrator'];

                        if (!$hydrators->has($hydratorServiceName)) {
                            throw new Exception\DomainException(
                                sprintf(
                                    'Cannot locate default hydrator by name "%s" via the HydratorManager',
                                    $hydratorServiceName
                                )
                            );
                        }

                        $hydrator = $hydrators->get($hydratorServiceName);
                        $helper->setDefaultHydrator($hydrator);
                    }

                    if (isset($config['render_embedded_resources'])) {
                        $helper->setRenderEmbeddedEntities($config['render_embedded_resources']);
                    }

                    if (isset($config['render_embedded_entities'])) {
                        $helper->setRenderEmbeddedEntities($config['render_embedded_entities']);
                    }

                    if (isset($config['render_collections'])) {
                        $helper->setRenderCollections($config['render_collections']);
                    }

                    if (isset($config['hydrators']) && is_array($config['hydrators'])) {
                        $hydratorMap = $config['hydrators'];
                        foreach ($hydratorMap as $class => $hydratorServiceName) {
                            $helper->addHydrator($class, $hydratorServiceName);
                        }
                    }
                }

                return $helper;
            }
        ));
    }

    /**
     * Listener for bootstrap event
     *
     * Attaches a render event.
     *
     * @param  \Zend\Mvc\MvcEvent $e
     */
    public function onBootstrap($e)
    {
        $app      = $e->getTarget();
        $services = $app->getServiceManager();
        $events   = $app->getEventManager();
        $events->attach(MvcEvent::EVENT_RENDER, array($this, 'onRender'), 100);
    }

    /**
     * Listener for the render event
     *
     * Attaches a rendering/response strategy to the View.
     *
     * @param  \Zend\Mvc\MvcEvent $e
     */
    public function onRender($e)
    {
        $result = $e->getResult();
        if (!$result instanceof View\HalJsonModel) {
            return;
        }

        $app                 = $e->getTarget();
        $services            = $app->getServiceManager();
        $view                = $services->get('View');
        $events              = $view->getEventManager();

        // register at high priority, to "beat" normal json strategy registered
        // via view manager
        $events->attach($services->get('ZF\Hal\JsonStrategy'), 200);
    }
}


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/carlescere/microservices/models"
	"github.com/gorilla/mux"
)

const (
	DefaultPort  = 8000
	bookingsPath = "database/bookings.json"
)

var (
	bookings models.BookingCollection
	port     int
)

func list(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprint(w, bookings)
}

func user(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	booking, ok := bookings[vars["username"]]
	if !ok {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprint(w, booking)
}

func init() {
	content, err := ioutil.ReadFile(bookingsPath)
	if err != nil {
		log.Fatal(err)
	}
	json.Unmarshal(content, &bookings)
}

func main() {
	flag.IntVar(&port, "port", DefaultPort, "webserver port")
	flag.Parse()

	r := mux.NewRouter()
	r.HandleFunc("/bookings", list).Methods("GET")
	r.HandleFunc("/bookings/{username}", user).Methods("GET")
	fmt.Printf("Listening in port %d", port)
	http.Handle("/", r)
	http.ListenAndServe(fmt.Sprint(":", port), nil)
}


text:
@implementation UIFont (UISS)

+ (UIFont *)uissDemoFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"Futura-Medium" size:fontSize];
}

@end


text:
def deaf_grandma
  while line = gets
    line.chomp!
    break if line == "BYE"
    if line == line.upcase && line != ""
      puts "NO, NOT SINCE 1938!"
    else
      puts "HUH?! SPEAK UP, SONNY!"
    end
  end
end

deaf_grandma if $0 == __FILE__ # this will call your code so you can run it from the terminal


text:
<?php

namespace edu\wisc\services\caos;

class GetUniqueClassInstructionModesInTermRequest
{

    /**
     * @var termCodeType $termCode
     */
    protected $termCode = null;

    /**
     * @param termCodeType $termCode
     */
    public function __construct($termCode)
    {
      $this->termCode = $termCode;
    }

    /**
     * @return termCodeType
     */
    public function getTermCode()
    {
      return $this->termCode;
    }

    /**
     * @param termCodeType $termCode
     * @return \edu\wisc\services\caos\GetUniqueClassInstructionModesInTermRequest
     */
    public function setTermCode($termCode)
    {
      $this->termCode = $termCode;
      return $this;
    }

}


text:
class ReservationIdIsReallyAString < ActiveRecord::Migration[4.2]
  def change
    change_column(:rentals, :reservation_id, :string)
  end
end


text:
const char* rev="A ";

int mainpalindromes(){
//    printf("hello");
    return 0;
}


text:
package org.apache.bookkeeper.client;

import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.bookkeeper.bookie.Bookie;
import org.apache.bookkeeper.bookie.BookieException;
import org.apache.bookkeeper.bookie.InterleavedLedgerStorage;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.apache.bookkeeper.client.api.LedgerMetadata;
import org.apache.bookkeeper.client.api.WriteFlag;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.meta.HierarchicalLedgerManagerFactory;
import org.apache.bookkeeper.meta.LedgerManager;
import org.apache.bookkeeper.meta.LedgerManagerFactory;
import org.apache.bookkeeper.meta.MetadataDrivers;
import org.apache.bookkeeper.meta.exceptions.Code;
import org.apache.bookkeeper.meta.exceptions.MetadataException;
import org.apache.bookkeeper.meta.zk.ZKMetadataBookieDriver;
import org.apache.bookkeeper.meta.zk.ZKMetadataClientDriver;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.proto.BookieProtocol;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.LedgerMetadataListener;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.Processor;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback;
import org.apache.bookkeeper.proto.checksum.DigestManager;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.util.ByteBufList;
import org.apache.bookkeeper.versioning.Version;
import org.apache.bookkeeper.versioning.Versioned;
import org.apache.commons.lang3.mutable.MutableInt;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.KeeperException;
import org.junit.After;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test parallel ledger recovery.
 */
public class ParallelLedgerRecoveryTest extends BookKeeperClusterTestCase {

    static final Logger LOG = LoggerFactory.getLogger(ParallelLedgerRecoveryTest.class);

    static class TestLedgerManager implements LedgerManager {

        final LedgerManager lm;
        volatile CountDownLatch waitLatch = null;
        final ExecutorService executorService;

        TestLedgerManager(LedgerManager lm) {
            this.lm = lm;
            this.executorService = Executors.newSingleThreadExecutor();
        }

        void setLatch(CountDownLatch waitLatch) {
            this.waitLatch = waitLatch;
        }

        @Override
        public CompletableFuture<Versioned<LedgerMetadata>> createLedgerMetadata(
                long ledgerId, LedgerMetadata metadata) {
            return lm.createLedgerMetadata(ledgerId, metadata);
        }

        @Override
        public CompletableFuture<Void> removeLedgerMetadata(long ledgerId, Version version) {
            return lm.removeLedgerMetadata(ledgerId, version);
        }

        @Override
        public CompletableFuture<Versioned<LedgerMetadata>> readLedgerMetadata(long ledgerId) {
            return lm.readLedgerMetadata(ledgerId);
        }

        @Override
        public LedgerRangeIterator getLedgerRanges(long zkOpTimeoutMs) {
            return lm.getLedgerRanges(zkOpTimeoutMs);
        }

        @Override
        public CompletableFuture<Versioned<LedgerMetadata>> writeLedgerMetadata(long ledgerId, LedgerMetadata metadata,
                                                                                Version currentVersion) {
            final CountDownLatch cdl = waitLatch;
            if (null != cdl) {
                CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>();
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            cdl.await();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            LOG.error("Interrupted on waiting latch : ", e);
                        }
                        lm.writeLedgerMetadata(ledgerId, metadata, currentVersion)
                            .whenComplete((metadata, exception) -> {
                                    if (exception != null) {
                                        promise.completeExceptionally(exception);
                                    } else {
                                        promise.complete(metadata);
                                    }
                                });
                    }
                });
                return promise;
            } else {
                return lm.writeLedgerMetadata(ledgerId, metadata, currentVersion);
            }
        }

        @Override
        public void registerLedgerMetadataListener(long ledgerId, LedgerMetadataListener listener) {
            lm.registerLedgerMetadataListener(ledgerId, listener);
        }

        @Override
        public void unregisterLedgerMetadataListener(long ledgerId, LedgerMetadataListener listener) {
            lm.unregisterLedgerMetadataListener(ledgerId, listener);
        }

        @Override
        public void asyncProcessLedgers(Processor<Long> processor, VoidCallback finalCb, Object context,
                                        int successRc, int failureRc) {
            lm.asyncProcessLedgers(processor, finalCb, context, successRc, failureRc);
        }

        @Override
        public void close() throws IOException {
            lm.close();
            executorService.shutdown();
        }
    }

    static class TestLedgerManagerFactory extends HierarchicalLedgerManagerFactory {
        @Override
        public LedgerManager newLedgerManager() {
            return new TestLedgerManager(super.newLedgerManager());
        }
    }

    static class TestMetadataClientDriver extends ZKMetadataClientDriver {

        @Override
        public synchronized LedgerManagerFactory getLedgerManagerFactory() throws MetadataException {
            if (null == lmFactory) {
                try {
                    lmFactory = new TestLedgerManagerFactory()
                        .initialize(conf, layoutManager, TestLedgerManagerFactory.CUR_VERSION);
                } catch (IOException e) {
                    throw new MetadataException(Code.METADATA_SERVICE_ERROR, e);
                }
            }
            return lmFactory;
        }
    }

    static class TestMetadataBookieDriver extends ZKMetadataBookieDriver {

        @Override
        public synchronized LedgerManagerFactory getLedgerManagerFactory() throws MetadataException {
            if (null == lmFactory) {
                try {
                    lmFactory = new TestLedgerManagerFactory()
                        .initialize(conf, layoutManager, TestLedgerManagerFactory.CUR_VERSION);
                } catch (IOException e) {
                    throw new MetadataException(Code.METADATA_SERVICE_ERROR, e);
                }
            }
            return lmFactory;
        }
    }

    final DigestType digestType;

    public ParallelLedgerRecoveryTest() throws Exception {
        super(3);

        this.digestType = DigestType.CRC32;
    }

    @Override
    protected void startBKCluster(String metadataServiceUri) throws Exception {
        MetadataDrivers.registerClientDriver("zk", TestMetadataClientDriver.class, true);
        MetadataDrivers.registerBookieDriver("zk", TestMetadataBookieDriver.class, true);
        baseConf.setLedgerManagerFactoryClass(TestLedgerManagerFactory.class);
        baseClientConf.setLedgerManagerFactoryClass(TestLedgerManagerFactory.class);
        baseClientConf.setReadEntryTimeout(60000);
        baseClientConf.setAddEntryTimeout(60000);

        super.startBKCluster(metadataServiceUri);
    }

    @After
    @Override
    public void tearDown() throws Exception {
        try {
            super.tearDown();
        } finally {
            MetadataDrivers.registerClientDriver("zk", ZKMetadataClientDriver.class, true);
            MetadataDrivers.registerBookieDriver("zk", ZKMetadataBookieDriver.class, true);
        }
    }

    @Test
    public void testRecoverBeforeWriteMetadata1() throws Exception {
        rereadDuringRecovery(true, 1, false, false);
    }

    @Test
    public void testRecoverBeforeWriteMetadata2() throws Exception {
        rereadDuringRecovery(true, 3, false, false);
    }

    @Test
    public void testRecoverBeforeWriteMetadata3() throws Exception {
        rereadDuringRecovery(false, 1, false, false);
    }

    @Test
    public void testRecoverBeforeWriteMetadata4() throws Exception {
        rereadDuringRecovery(false, 3, false, false);
    }

    @Test
    public void testRereadDuringRecovery1() throws Exception {
        rereadDuringRecovery(true, 1, true, false);
    }

    @Test
    public void testRereadDuringRecovery2() throws Exception {
        rereadDuringRecovery(true, 3, true, false);
    }

    @Test
    public void testRereadDuringRecovery3() throws Exception {
        rereadDuringRecovery(false, 1, true, false);
    }

    @Test
    public void testRereadDuringRecovery4() throws Exception {
        rereadDuringRecovery(false, 3, true, false);
    }

    @Test
    public void testConcurrentRecovery1() throws Exception {
        rereadDuringRecovery(true, 1, true, false);
    }

    @Test
    public void testConcurrentRecovery2() throws Exception {
        rereadDuringRecovery(true, 3, true, false);
    }

    @Test
    public void testConcurrentRecovery3() throws Exception {
        rereadDuringRecovery(false, 1, true, false);
    }

    @Test
    public void testConcurrentRecovery4() throws Exception {
        rereadDuringRecovery(false, 3, true, false);
    }

    private void rereadDuringRecovery(boolean parallelRead, int batchSize,
                                      boolean updateMetadata, boolean close) throws Exception {
        ClientConfiguration newConf = new ClientConfiguration();
        newConf.addConfiguration(baseClientConf);
        newConf.setEnableParallelRecoveryRead(parallelRead);
        newConf.setRecoveryReadBatchSize(batchSize);
        BookKeeper newBk = new BookKeeper(newConf);

        TestLedgerManager tlm = (TestLedgerManager) newBk.getUnderlyingLedgerManager();

        final LedgerHandle lh = newBk.createLedger(numBookies, 2, 2, digestType, "".getBytes());
        CountDownLatch latch1 = new CountDownLatch(1);
        CountDownLatch latch2 = new CountDownLatch(1);
        sleepBookie(lh.getCurrentEnsemble().get(0), latch1);
        sleepBookie(lh.getCurrentEnsemble().get(1), latch2);

        int numEntries = (numBookies * 3) + 1;
        final AtomicInteger numPendingAdds = new AtomicInteger(numEntries);
        final CountDownLatch addDone = new CountDownLatch(1);
        for (int i = 0; i < numEntries; i++) {
            lh.asyncAddEntry(("" + i).getBytes(), new org.apache.bookkeeper.client.AsyncCallback.AddCallback() {
                @Override
                public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
                    if (BKException.Code.OK != rc) {
                        addDone.countDown();
                        return;
                    }
                    if (numPendingAdds.decrementAndGet() == 0) {
                        addDone.countDown();
                    }
                }
            }, null);
        }
        latch1.countDown();
        latch2.countDown();
        addDone.await(10, TimeUnit.SECONDS);
        assertEquals(0, numPendingAdds.get());

        LOG.info("Added {} entries to ledger {}.", numEntries, lh.getId());

        long ledgerLenth = lh.getLength();

        LedgerHandle recoverLh = newBk.openLedgerNoRecovery(lh.getId(), digestType, "".getBytes());
        assertEquals(BookieProtocol.INVALID_ENTRY_ID, recoverLh.getLastAddPushed());
        assertEquals(BookieProtocol.INVALID_ENTRY_ID, recoverLh.getLastAddConfirmed());
        assertEquals(0, recoverLh.getLength());

        LOG.info("OpenLedgerNoRecovery {}.", lh.getId());

        final CountDownLatch metadataLatch = new CountDownLatch(1);

        tlm.setLatch(metadataLatch);

        final CountDownLatch recoverLatch = new CountDownLatch(1);
        final AtomicBoolean success = new AtomicBoolean(false);
        ((ReadOnlyLedgerHandle) recoverLh).recover(new GenericCallback<Void>() {
            @Override
            public void operationComplete(int rc, Void result) {
                LOG.info("Recovering ledger {} completed : {}.", lh.getId(), rc);
                success.set(BKException.Code.OK == rc);
                recoverLatch.countDown();
            }
        });

        // clear the metadata latch
        tlm.setLatch(null);

        if (updateMetadata) {
            if (close) {
                LOG.info("OpenLedger {} to close.", lh.getId());
                LedgerHandle newRecoverLh = newBk.openLedger(lh.getId(), digestType, "".getBytes());
                newRecoverLh.close();
            } else {
                LOG.info("OpenLedgerNoRecovery {} again.", lh.getId());
                LedgerHandle newRecoverLh = newBk.openLedgerNoRecovery(lh.getId(), digestType, "".getBytes());
                assertEquals(BookieProtocol.INVALID_ENTRY_ID, newRecoverLh.getLastAddPushed());
                assertEquals(BookieProtocol.INVALID_ENTRY_ID, newRecoverLh.getLastAddConfirmed());

                // mark the ledger as in recovery to update version.
                ClientUtil.transformMetadata(newBk.getClientCtx(), newRecoverLh.getId(),
                        (metadata) -> LedgerMetadataBuilder.from(metadata).withInRecoveryState().build());

                newRecoverLh.close();
                LOG.info("Updated ledger manager {}.", newRecoverLh.getLedgerMetadata());
            }
        }

        // resume metadata operation on recoverLh
        metadataLatch.countDown();

        LOG.info("Resume metadata update.");

        // wait until recover completed
        recoverLatch.await(20, TimeUnit.SECONDS);
        assertTrue(success.get());
        assertEquals(numEntries - 1, recoverLh.getLastAddPushed());
        assertEquals(numEntries - 1, recoverLh.getLastAddConfirmed());
        assertEquals(ledgerLenth, recoverLh.getLength());
        assertTrue(recoverLh.getLedgerMetadata().isClosed());

        Enumeration<LedgerEntry> enumeration = recoverLh.readEntries(0, numEntries - 1);
        int numReads = 0;
        while (enumeration.hasMoreElements()) {
            LedgerEntry entry = enumeration.nextElement();
            assertEquals((long) numReads, entry.getEntryId());
            assertEquals(numReads, Integer.parseInt(new String(entry.getEntry())));
            ++numReads;
        }
        assertEquals(numEntries, numReads);

        recoverLh.close();
        newBk.close();
    }

    @Test
    public void testRecoveryOnEntryGap() throws Exception {
        byte[] passwd = "recovery-on-entry-gap".getBytes(UTF_8);
        LedgerHandle lh = bkc.createLedger(1, 1, 1, DigestType.CRC32, passwd);
        for (int i = 0; i < 10; i++) {
            lh.addEntry(("recovery-on-entry-gap-" + i).getBytes(UTF_8));
        }

        // simulate ledger writer failure on concurrent writes causing gaps

        long entryId = 14;
        long lac = 8;
        byte[] data = "recovery-on-entry-gap-gap".getBytes(UTF_8);
        ByteBufList toSend =
                lh.macManager.computeDigestAndPackageForSending(
                        entryId, lac, lh.getLength() + 100, Unpooled.wrappedBuffer(data, 0, data.length));
        final CountDownLatch addLatch = new CountDownLatch(1);
        final AtomicBoolean addSuccess = new AtomicBoolean(false);
        LOG.info("Add entry {} with lac = {}", entryId, lac);

        bkc.getBookieClient().addEntry(lh.getCurrentEnsemble().get(0),
                                       lh.getId(), lh.ledgerKey, entryId, toSend,
                                       new WriteCallback() {
                                           @Override
                                           public void writeComplete(int rc, long ledgerId, long entryId,
                                                                     BookieSocketAddress addr, Object ctx) {
                                               addSuccess.set(BKException.Code.OK == rc);
                                               addLatch.countDown();
                                           }
                                       }, 0, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
        addLatch.await();
        assertTrue("add entry 14 should succeed", addSuccess.get());

        ClientConfiguration newConf = new ClientConfiguration();
        newConf.addConfiguration(baseClientConf);
        newConf.setEnableParallelRecoveryRead(true);
        newConf.setRecoveryReadBatchSize(10);

        BookKeeper newBk = new BookKeeper(newConf);

        final LedgerHandle recoverLh =
                newBk.openLedgerNoRecovery(lh.getId(), DigestType.CRC32, passwd);

        assertEquals("wrong lac found", 8L, recoverLh.getLastAddConfirmed());

        final CountDownLatch recoverLatch = new CountDownLatch(1);
        final AtomicLong newLac = new AtomicLong(-1);
        final AtomicBoolean isMetadataClosed = new AtomicBoolean(false);
        final AtomicInteger numSuccessCalls = new AtomicInteger(0);
        final AtomicInteger numFailureCalls = new AtomicInteger(0);
        ((ReadOnlyLedgerHandle) recoverLh).recover(new GenericCallback<Void>() {
            @Override
            public void operationComplete(int rc, Void result) {
                if (BKException.Code.OK == rc) {
                    newLac.set(recoverLh.getLastAddConfirmed());
                    isMetadataClosed.set(recoverLh.getLedgerMetadata().isClosed());
                    numSuccessCalls.incrementAndGet();
                } else {
                    numFailureCalls.incrementAndGet();
                }
                recoverLatch.countDown();
            }
        });
        recoverLatch.await();
        assertEquals("wrong lac found", 9L, newLac.get());
        assertTrue("metadata isn't closed after recovery", isMetadataClosed.get());
        Thread.sleep(5000);
        assertEquals("recovery callback should be triggered only once", 1, numSuccessCalls.get());
        assertEquals("recovery callback should be triggered only once", 0, numFailureCalls.get());
    }

    static class DelayResponseBookie extends Bookie {

        static final class WriteCallbackEntry {

            private final WriteCallback cb;
            private final int rc;
            private final long ledgerId;
            private final long entryId;
            private final BookieSocketAddress addr;
            private final Object ctx;

            WriteCallbackEntry(WriteCallback cb,
                               int rc, long ledgerId, long entryId,
                               BookieSocketAddress addr, Object ctx) {
                this.cb = cb;
                this.rc = rc;
                this.ledgerId = ledgerId;
                this.entryId = entryId;
                this.addr = addr;
                this.ctx = ctx;
            }

            public void callback() {
                cb.writeComplete(rc, ledgerId, entryId, addr, ctx);
            }
        }

        private final AtomicBoolean delayAddResponse = new AtomicBoolean(false);
        private final AtomicBoolean delayReadResponse = new AtomicBoolean(false);
        private final AtomicLong delayReadOnEntry = new AtomicLong(-1234L);
        private volatile CountDownLatch delayReadLatch = null;
        private final LinkedBlockingQueue<WriteCallbackEntry> delayQueue =
                new LinkedBlockingQueue<WriteCallbackEntry>();

        public DelayResponseBookie(ServerConfiguration conf)
                throws IOException, KeeperException, InterruptedException, BookieException {
            super(conf);
        }

        @Override
        public void addEntry(ByteBuf entry, boolean ackBeforeSync, final WriteCallback cb, Object ctx, byte[] masterKey)
                throws IOException, BookieException, InterruptedException {
            super.addEntry(entry, ackBeforeSync, new WriteCallback() {
                @Override
                public void writeComplete(int rc, long ledgerId, long entryId,
                                          BookieSocketAddress addr, Object ctx) {
                    if (delayAddResponse.get()) {
                        delayQueue.add(new WriteCallbackEntry(cb, rc, ledgerId, entryId, addr, ctx));
                    } else {
                        cb.writeComplete(rc, ledgerId, entryId, addr, ctx);
                    }
                }
            }, ctx, masterKey);
        }

        @Override
        public ByteBuf readEntry(long ledgerId, long entryId) throws IOException, NoLedgerException {
            LOG.info("ReadEntry {} - {}", ledgerId, entryId);
            if (delayReadResponse.get() && delayReadOnEntry.get() == entryId) {
                CountDownLatch latch = delayReadLatch;
                if (null != latch) {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        // no-op
                    }
                }
            }
            return super.readEntry(ledgerId, entryId);
        }

        void delayAdd(boolean delayed) {
            this.delayAddResponse.set(delayed);
        }

        void delayRead(boolean delayed, long entryId, CountDownLatch delayReadLatch) {
            this.delayReadResponse.set(delayed);
            this.delayReadOnEntry.set(entryId);
            this.delayReadLatch = delayReadLatch;
        }

    }

    @Test
    public void testRecoveryWhenClosingLedgerHandle() throws Exception {
        byte[] passwd = "recovery-when-closing-ledger-handle".getBytes(UTF_8);

        ClientConfiguration newConf = new ClientConfiguration();
        newConf.addConfiguration(baseClientConf);
        newConf.setEnableParallelRecoveryRead(true);
        newConf.setRecoveryReadBatchSize(1);
        newConf.setAddEntryTimeout(9999999);
        newConf.setReadEntryTimeout(9999999);

        final BookKeeper newBk0 = new BookKeeper(newConf);
        final LedgerHandle lh0 = newBk0.createLedger(1, 1, 1, digestType, passwd);

        final BookKeeper newBk1 = new BookKeeper(newConf);
        final LedgerHandle lh1 = newBk1.openLedgerNoRecovery(lh0.getId(), digestType, passwd);
        final TestLedgerManager tlm1 = (TestLedgerManager) newBk1.getUnderlyingLedgerManager();

        final BookKeeper readBk = new BookKeeper(newConf);
        final LedgerHandle readLh = readBk.openLedgerNoRecovery(lh0.getId(), digestType, passwd);

        LOG.info("Create ledger {}", lh0.getId());

        // 0) place the bookie with a fake bookie
        BookieSocketAddress address = lh0.getCurrentEnsemble().get(0);
        ServerConfiguration conf = killBookie(address);
        conf.setLedgerStorageClass(InterleavedLedgerStorage.class.getName());
        DelayResponseBookie fakeBookie = new DelayResponseBookie(conf);
        bs.add(startBookie(conf, fakeBookie));
        bsConfs.add(conf);

        // 1) bk0 write two entries
        lh0.addEntry("entry-0".getBytes(UTF_8));
        lh0.addEntry("entry-1".getBytes(UTF_8));

        // 2) readBk read last add confirmed
        long lac = readLh.readLastConfirmed();
        assertEquals(0L, lac);
        lac = lh1.readLastConfirmed();
        assertEquals(0L, lac);

        final CountDownLatch addLatch = new CountDownLatch(3);
        final AtomicInteger numAddFailures = new AtomicInteger(0);
        // 3) bk0 write more entries in parallel
        fakeBookie.delayAdd(true);
        for (int i = 2; i < 5; i++) {
            lh0.asyncAddEntry(("entry-" + i).getBytes(UTF_8), new AsyncCallback.AddCallback() {
                @Override
                public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
                    if (BKException.Code.OK != rc) {
                        numAddFailures.incrementAndGet();
                    }
                    addLatch.countDown();
                }
            }, null);
        }
        while (fakeBookie.delayQueue.size() < 3) {
            // wait until all add requests are queued
            Thread.sleep(100);
        }

        // 4) lac moved to 1L
        lac = readLh.readLastConfirmed();
        assertEquals(1L, lac);
        lac = lh1.readLastConfirmed();
        assertEquals(1L, lac);

        // 5) bk1 is doing recovery, but the metadata update is delayed
        final CountDownLatch readLatch = new CountDownLatch(1);
        fakeBookie.delayAdd(false);
        fakeBookie.delayRead(true, 3L, readLatch);
        final CountDownLatch metadataLatch = new CountDownLatch(1);
        tlm1.setLatch(metadataLatch);
        final CountDownLatch recoverLatch = new CountDownLatch(1);
        final AtomicBoolean recoverSuccess = new AtomicBoolean(false);
        ((ReadOnlyLedgerHandle) lh1).recover(new GenericCallback<Void>() {
            @Override
            public void operationComplete(int rc, Void result) {
                LOG.info("Recovering ledger {} completed : {}", lh1.getId(), rc);
                recoverSuccess.set(BKException.Code.OK == rc);
                recoverLatch.countDown();
            }
        });
        Thread.sleep(2000);
        readLatch.countDown();

        // we don't expected lac being updated before we successfully marked the ledger in recovery
        lac = readLh.readLastConfirmed();
        assertEquals(1L, lac);

        // 6) bk0 closes ledger before bk1 marks in recovery
        lh0.close();
        assertEquals(1L, lh0.getLastAddConfirmed());

        // 7) bk1 proceed recovery and succeed
        metadataLatch.countDown();
        recoverLatch.await();
        assertTrue(recoverSuccess.get());
        assertEquals(1L, lh1.getLastAddConfirmed());

        // 8) make sure we won't see lac advanced during ledger is closed by bk0 and recovered by bk1
        final AtomicLong lacHolder = new AtomicLong(-1234L);
        final AtomicInteger rcHolder = new AtomicInteger(-1234);
        final CountDownLatch doneLatch = new CountDownLatch(1);

        new ReadLastConfirmedOp(readLh, bkc.getBookieClient(),
                                readLh.getLedgerMetadata().getAllEnsembles().lastEntry().getValue(),
                new ReadLastConfirmedOp.LastConfirmedDataCallback() {
                    @Override
                    public void readLastConfirmedDataComplete(int rc, DigestManager.RecoveryData data) {
                        rcHolder.set(rc);
                        lacHolder.set(data.getLastAddConfirmed());
                        doneLatch.countDown();
                    }
                }).initiate();
        doneLatch.await();
        assertEquals(BKException.Code.OK, rcHolder.get());
        assertEquals(1L, lacHolder.get());

        newBk0.close();
        newBk1.close();
        readBk.close();
    }

    /**
     * Validate ledger can recover with response: (Qw - Qa)+1.
     * @throws Exception
     */
    @Test
    public void testRecoveryWithUnavailableBookie() throws Exception {

        byte[] passwd = "".getBytes(UTF_8);
        ClientConfiguration newConf = new ClientConfiguration();
        newConf.addConfiguration(baseClientConf);
        final BookKeeper readBk = new BookKeeper(newConf);
        final BookKeeper newBk0 = new BookKeeper(newConf);

        /**
         * Test Group-1 : Expected Response for recovery: Qr = (Qw - Qa)+1 = (3
         * -2) + 1 = 2
         */
        int ensembleSize = 3;
        int writeQuorumSize = 3;
        int ackQuormSize = 2;
        LedgerHandle lh0 = newBk0.createLedger(ensembleSize, writeQuorumSize, ackQuormSize, DigestType.DUMMY, passwd);
        LedgerHandle readLh = readBk.openLedgerNoRecovery(lh0.getId(), DigestType.DUMMY, passwd);
        // Test 1: bookie response: OK, NO_SUCH_LEDGER_EXISTS, NOT_AVAILABLE
        // Expected: Recovery successful Q(response) = 2
        int responseCode = readLACFromQuorum(readLh, BKException.Code.BookieHandleNotAvailableException,
                BKException.Code.OK, BKException.Code.NoSuchLedgerExistsException);
        assertEquals(responseCode, BKException.Code.OK);
        // Test 2: bookie response: OK, NOT_AVAILABLE, NOT_AVAILABLE
        // Expected: Recovery fail Q(response) = 1
        responseCode = readLACFromQuorum(readLh, BKException.Code.BookieHandleNotAvailableException,
                BKException.Code.OK, BKException.Code.BookieHandleNotAvailableException);
        assertEquals(responseCode, BKException.Code.BookieHandleNotAvailableException);

        /**
         * Test Group-2 : Expected Response for recovery: Qr = (Qw - Qa)+1 = (2
         * -2) + 1 = 1
         */
        ensembleSize = 2;
        writeQuorumSize = 2;
        ackQuormSize = 2;
        lh0 = newBk0.createLedger(ensembleSize, writeQuorumSize, ackQuormSize, DigestType.DUMMY, passwd);
        readLh = readBk.openLedgerNoRecovery(lh0.getId(), DigestType.DUMMY, passwd);
        // Test 1: bookie response: OK, NOT_AVAILABLE
        // Expected: Recovery successful Q(response) = 1
        responseCode = readLACFromQuorum(readLh, BKException.Code.BookieHandleNotAvailableException,
                BKException.Code.OK);
        assertEquals(responseCode, BKException.Code.OK);

        // Test 1: bookie response: OK, NO_SUCH_LEDGER_EXISTS
        // Expected: Recovery successful Q(response) = 2
        responseCode = readLACFromQuorum(readLh, BKException.Code.NoSuchLedgerExistsException, BKException.Code.OK);
        assertEquals(responseCode, BKException.Code.OK);

        // Test 3: bookie response: NOT_AVAILABLE, NOT_AVAILABLE
        // Expected: Recovery fail Q(response) = 0
        responseCode = readLACFromQuorum(readLh, BKException.Code.BookieHandleNotAvailableException,
                BKException.Code.BookieHandleNotAvailableException);
        assertEquals(responseCode, BKException.Code.BookieHandleNotAvailableException);

        newBk0.close();
        readBk.close();
    }

    private int readLACFromQuorum(LedgerHandle ledger, int... bookieLACResponse) throws Exception {
        MutableInt responseCode = new MutableInt(100);
        CountDownLatch responseLatch = new CountDownLatch(1);
        ReadLastConfirmedOp readLCOp = new ReadLastConfirmedOp(ledger, bkc.getBookieClient(),
                ledger.getLedgerMetadata().getAllEnsembles().lastEntry().getValue(),
                new ReadLastConfirmedOp.LastConfirmedDataCallback() {
                    @Override
                    public void readLastConfirmedDataComplete(int rc, DigestManager.RecoveryData data) {
                        System.out.println("response = " + rc);
                        responseCode.setValue(rc);
                        responseLatch.countDown();
                    }
                });
        byte[] lac = new byte[Long.SIZE * 3];
        ByteBuf data = Unpooled.wrappedBuffer(lac, 0, lac.length);
        int writerIndex = data.writerIndex();
        data.resetWriterIndex();
        data.writeLong(ledger.getId());
        data.writeLong(0L);
        data.writerIndex(writerIndex);
        for (int i = 0; i < bookieLACResponse.length; i++) {
            readLCOp.readEntryComplete(bookieLACResponse[i], 0, 0, data, i);
        }
        responseLatch.await();
        return responseCode.intValue();
    }
}


text:
layout: page
title: Rachel Potter's 82nd Birthday
date: 2016-05-24
author: Diana Mccall
tags: weekly links, java
status: published
summary: Mauris porta enim eget maximus.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/19/2016
  endDate: 04/22/2016
  ctyhocn: JANHSHX
  groupCode: RP8B
published: true
---
Quisque commodo auctor hendrerit. Aenean a dui sodales, scelerisque massa quis, malesuada orci. Mauris lorem nisl, semper quis lectus ut, eleifend pharetra dui. Suspendisse potenti. Proin id dolor leo. Pellentesque nec velit sit amet sem aliquet volutpat. Duis congue metus justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris auctor nibh et urna scelerisque, at bibendum velit tincidunt. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis vitae mattis magna, nec molestie nisl. Integer eu elit sed ex fringilla sollicitudin eleifend ac arcu. Suspendisse id molestie metus. Morbi massa justo, convallis malesuada odio ac, bibendum pulvinar libero. Nam porta erat vel ipsum gravida, blandit vestibulum felis cursus. Morbi a tellus in lectus eleifend vehicula vel aliquet arcu.

* Nullam molestie dui vitae eros luctus consequat
* Donec bibendum quam nec arcu vulputate iaculis
* Fusce gravida nulla feugiat ex vehicula tincidunt.

Suspendisse non varius est. Cras semper commodo fringilla. Nulla ac faucibus nibh. Nulla consectetur mi odio, sed rutrum lorem volutpat eget. Vestibulum tincidunt luctus scelerisque. Aliquam id nulla et orci aliquet porta eu eu nulla. Curabitur feugiat, orci a suscipit vestibulum, tellus felis ultricies ipsum, eu faucibus sem diam sed quam. Mauris nec sapien rhoncus, mollis leo sed, vulputate enim. Sed posuere augue sed ex maximus pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id sem eros. Pellentesque nec felis in risus aliquet euismod. Vivamus fermentum leo ut nisi luctus, ac sodales nibh consectetur. Integer ornare non erat eu posuere. Integer vitae nulla sodales, mollis ligula ut, fermentum risus. Sed rutrum, ligula non interdum convallis, ipsum nulla feugiat nibh, at lacinia ante odio vel tellus.


text:
package com.kkmoving.oosqlite;

/**
 * Created by kkmoving on 2016/1/4.
 */
public class Constants {

    static final String DEBUG_TAG = "OOSQLITE";
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.4.0//EN"
    "http://google-web-toolkit.googlecode.com/svn/tags/2.5.0/distro-source/core/src/gwt-module.dtd">
<module>

  <!-- Uberfire dependencies -->
  <inherits name="org.uberfire.UberfireClientAll"/>
  <inherits name="org.uberfire.client.views.Bootstrap2"/>

  <!-- Wires dependencies -->
  <inherits name="com.ait.lienzo.Lienzo"/>
  <inherits name="org.uberfire.ext.wires.core.WiresCoreClient"/>

  <!-- Wires Scratch Pad dependencies -->
  <inherits name="org.uberfire.ext.wires.core.scratchpad.WiresCoreScratchPad"/>

  <!-- Wires Trees dependencies -->
  <inherits name="org.uberfire.ext.wires.core.trees.WiresCoreTrees"/>

  <!-- Bayesian Network dependencies -->
  <inherits name="org.uberfire.ext.wires.bayesian.network.parser.BayesianNetworkAPI"/>
  <inherits name="org.uberfire.ext.wires.bayesian.network.BayesianNetworkClient"/>

  <!-- BPMN dependencies -->
  <inherits name="org.uberfire.ext.wires.bpmn.WiresBpmnApi"/>
  <inherits name="org.uberfire.ext.wires.bpmn.WiresBpmnClient"/>

  <!-- Specify the application specific style sheet. -->
  <set-property name="user.agent" value="safari"/>
  <stylesheet src='css/uberfire-showcase.css'/>

  <!-- Specify the paths for translatable code -->
  <source path='client'/>
  <source path='shared'/>

</module>


text:
package br.com.objectos.way.flat;

import br.com.objectos.way.code.AnnotationInfo;
import br.com.objectos.way.flat.FlatFactoryList.PropertyWriter;
import br.com.objectos.way.on.ConcretePropertyQuery;

/**
 * @author Marcio Endo
 */
class CustomFlatProperty extends FlatProperty {

  private CustomFlatProperty(ConcretePropertyQuery property, AnnotationInfo fieldAnnotation) {
    super(property, fieldAnnotation);
  }

  static FlatProperty of(ConcretePropertyQuery property, AnnotationInfo fieldAnnotation) {
    return new CustomFlatProperty(property, fieldAnnotation);
  }

  @Override
  public int length() {
    return fieldAnnotationIntValue("length");
  }

  @Override
  void accept(FlatFactoryList factory) {
    PropertyWriter writer = factory.propertyWriter(property);
    writer.add(".custom($L, new $T())",
        fieldAnnotationIntValue("length"),
        fieldAnnotationSimpleTypeInfoValue("formatter").typeName());
  }

  @Override
  void accept(FlatWritableMethod method) {
    method.addCode(".custom($L, $L, new $T())",
        property.propertyName(),
        fieldAnnotationIntValue("length"),
        fieldAnnotationSimpleTypeInfoValue("formatter").typeName());
  }

  @Override
  void recordReaderCode(Body body) {
    body.add(".custom($L, new $T())",
        fieldAnnotationIntValue("length"),
        fieldAnnotationSimpleTypeInfoValue("formatter").typeName());
  }

}


text:
require 'bonekit'

compass = HMC5883L.new

loop do
  puts "Heading: #{compass.heading} degrees"
  sleep(0.1)
end


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * yNeo4jRestClient
 *
 * @package yuki
 * @subpackage restClient
 * @author olamedia
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 */
class yNeo4jRestClient extends yRestClient{
    public function __construct(){
        parent::__construct();
        curl_setopt($this->_curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
    }
    public function bind($url){
        parent::bind($url);
        $this->_curl = curl_init($url);
        curl_setopt($this->_curl, CURLOPT_HTTPPROXYTUNNEL, false);
        curl_setopt($this->_curl, CURLOPT_PROXY, false);
        curl_setopt($this->_curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
        curl_setopt($this->_curl, CURLOPT_PORT, 7474);
    }
    /**
     * Get root
     */
    public function getRoot(){
        $json = $this->getJson('');
        //return $json;
        if ($this->_code() == 200){
            return $json;
        }
        return false;
    }
    public function createNode(){
        $this->post('node');
        if ($this->_code() == 201){
            return $this->_location();
        }
        return false;
    }
    /**
     * Get node
     * 200: OK
     * 404: Node not found
     * @param integer $id
     * @return stdClass
     */
    public function getNode($id){
        return $this->getJson('node/'.$id);
    }
    public function setNodeProperties($nodeId, $properties){

    }
    public function getNodeProperties($nodeId){
        return $this->getJson('node/'.$nodeId.'/properties');
    }
    public function removeNodeProperties($id){
        // 204: OK, no content returned
        // 404: Node not found
        $this->delete('node/'.$id.'/properties');
        if ($this->_code() == 204){
            return true;
        }
        return false;
    }
    public function getRelations($nodeId, $dir = 'all', $types = false){
        if (is_array($types)){
            $types = implode('&', $types);
        }
        return $this->getJson('node/'.$nodeId.'/relationships/'.$dir.($types === false?'':'/'.$types));
    }
}


text:
package v1alpha1

import (
	"github.com/openebs/maya/pkg/debug"
	"strings"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	kclient "github.com/openebs/maya/pkg/kubernetes/client/v1alpha1"
	errors "github.com/pkg/errors"

	apisv1alpha1 "github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
	clientset "github.com/openebs/maya/pkg/client/generated/clientset/versioned"
	"k8s.io/apimachinery/pkg/types"
)

// getClientsetFn is a typed function that
// abstracts fetching of internal clientset
type getClientsetFn func() (clientset *clientset.Clientset, err error)

// getClientsetFromPathFn is a typed function that
// abstracts fetching of clientset from kubeConfigPath
type getClientsetForPathFn func(kubeConfigPath string) (clientset *clientset.Clientset, err error)

// listFn is a typed function that abstracts
// listing of CStorPoolCluster
type listFn func(
	cli *clientset.Clientset,
	namespace string,
	opts metav1.ListOptions) (*apisv1alpha1.CStorPoolClusterList, error)

// getFn is a typed function that
// abstracts fetching of CStorPoolCluster
type getFn func(
	cli *clientset.Clientset,
	namespace, name string,
	opts metav1.GetOptions) (*apisv1alpha1.CStorPoolCluster, error)

// createFn is a typed function that abstracts
// creation of CStorPoolCluster
type createFn func(
	cli *clientset.Clientset,
	namespace string,
	cspc *apisv1alpha1.CStorPoolCluster) (*apisv1alpha1.CStorPoolCluster, error)

// deleteFn is a typed function that abstracts
// deletion of cspcs
type deleteFn func(
	cli *clientset.Clientset,
	namespace string,
	name string,
	deleteOpts *metav1.DeleteOptions) error

// deleteFn is a typed function that abstracts
// deletion of cspc's collection
type deleteCollectionFn func(
	cli *clientset.Clientset,
	namespace string,
	listOpts metav1.ListOptions,
	deleteOpts *metav1.DeleteOptions) error

// patchFn is a typed function that abstracts
// to patch CStorPoolCluster claim
type patchFn func(
	cli *clientset.Clientset,
	namespace,
	name string,
	pt types.PatchType,
	data []byte, subresources ...string) (*apisv1alpha1.CStorPoolCluster, error)

// updateFn is a typed function that abstracts
// update of CStorPoolCluster
type updateFn func(
	cli *clientset.Clientset,
	namespace string,
	cspc *apisv1alpha1.CStorPoolCluster) (*apisv1alpha1.CStorPoolCluster, error)

// Kubeclient enables kubernetes API operations
// on CStorPoolCluster instance
type Kubeclient struct {
	// clientset refers to CStorPoolCluster
	// clientset that will be responsible to
	// make kubernetes API calls
	clientset *clientset.Clientset
	// kubeconfig path to get kubernetes clientset
	kubeConfigPath string
	namespace      string
	// functions useful during mocking
	getClientset        getClientsetFn
	getClientsetForPath getClientsetForPathFn
	list                listFn
	get                 getFn
	create              createFn
	del                 deleteFn
	delCollection       deleteCollectionFn
	patch               patchFn
	update              updateFn
}

// KubeclientBuildOption defines the abstraction
// to build a kubeclient instance
type KubeclientBuildOption func(*Kubeclient)

// WithDefaults sets the default options
// of kubeclient instance
func (k *Kubeclient) WithDefaults() {
	if k.getClientset == nil {
		k.getClientset = func() (clients *clientset.Clientset, err error) {
			config, err := kclient.GetConfig(kclient.New())
			if err != nil {
				return nil, err
			}
			return clientset.NewForConfig(config)
		}
	}
	if k.getClientsetForPath == nil {
		k.getClientsetForPath = func(kubeConfigPath string) (clients *clientset.Clientset, err error) {
			config, err := kclient.GetConfig(kclient.New(kclient.WithKubeConfigPath(kubeConfigPath)))
			if err != nil {
				return nil, err
			}
			return clientset.NewForConfig(config)
		}
	}
	if k.list == nil {
		k.list = func(
			cli *clientset.Clientset,
			namespace string,
			opts metav1.ListOptions) (*apisv1alpha1.CStorPoolClusterList, error) {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).List(opts)
		}
	}

	if k.get == nil {
		k.get = func(
			cli *clientset.Clientset,
			namespace,
			name string,
			opts metav1.GetOptions) (*apisv1alpha1.CStorPoolCluster, error) {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).Get(name, opts)
		}
	}
	if k.create == nil {
		k.create = func(
			cli *clientset.Clientset,
			namespace string,
			cspc *apisv1alpha1.CStorPoolCluster) (*apisv1alpha1.CStorPoolCluster, error) {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).Create(cspc)
		}
	}
	if k.del == nil {
		k.del = func(
			cli *clientset.Clientset,
			namespace string,
			name string,
			deleteOpts *metav1.DeleteOptions) error {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).Delete(name, deleteOpts)
		}
	}
	if k.delCollection == nil {
		k.delCollection = func(
			cli *clientset.Clientset,
			namespace string,
			listOpts metav1.ListOptions,
			deleteOpts *metav1.DeleteOptions) error {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).DeleteCollection(deleteOpts, listOpts)
		}
	}
	if k.patch == nil {
		k.patch = func(
			cli *clientset.Clientset,
			namespace,
			name string,
			pt types.PatchType,
			data []byte, subresources ...string) (*apisv1alpha1.CStorPoolCluster, error) {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).Patch(name, pt, data, subresources...)
		}
	}
	if k.update == nil {
		k.update = func(
			cli *clientset.Clientset,
			namespace string,
			cspc *apisv1alpha1.CStorPoolCluster) (*apisv1alpha1.CStorPoolCluster, error) {
			return cli.OpenebsV1alpha1().CStorPoolClusters(namespace).Update(cspc)
		}
	}
}

// WithKubeClient sets the kubernetes client against
// the kubeclient instance
func WithKubeClient(c *clientset.Clientset) KubeclientBuildOption {
	return func(k *Kubeclient) {
		k.clientset = c
	}
}

// WithKubeConfigPath sets the kubeConfig path
// against client instance
func WithKubeConfigPath(kubeConfigPath string) KubeclientBuildOption {
	return func(k *Kubeclient) {
		k.kubeConfigPath = kubeConfigPath
	}
}

// NewKubeClient returns a new instance of kubeclient meant for
// CStorPoolCluster operations
func NewKubeClient(opts ...KubeclientBuildOption) *Kubeclient {
	k := &Kubeclient{}
	for _, o := range opts {
		o(k)
	}
	k.WithDefaults()
	return k
}

func (k *Kubeclient) getClientsetForPathOrDirect() (*clientset.Clientset, error) {
	if k.kubeConfigPath != "" {
		return k.getClientsetForPath(k.kubeConfigPath)
	}
	return k.getClientset()
}

// WithNamespace sets the kubernetes namespace against
// the provided namespace
func (k *Kubeclient) WithNamespace(namespace string) *Kubeclient {
	k.namespace = namespace
	return k
}

// getClientOrCached returns either a new instance
// of kubernetes client or its cached copy
func (k *Kubeclient) getClientsetOrCached() (*clientset.Clientset, error) {
	if k.clientset != nil {
		return k.clientset, nil
	}
	c, err := k.getClientsetForPathOrDirect()
	if err != nil {
		return nil, err
	}
	k.clientset = c
	return k.clientset, nil
}

// List returns a list of disk
// instances present in kubernetes cluster
func (k *Kubeclient) List(opts metav1.ListOptions) (*apisv1alpha1.CStorPoolClusterList, error) {

	if debug.EI.IsCSPCListErrorInjected() {
		return nil, errors.New("CSPC list error via injection")
	}

	cli, err := k.getClientsetOrCached()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to list cspc in namespace {%s}", k.namespace)
	}
	return k.list(cli, k.namespace, opts)
}

// Get returns a disk object
func (k *Kubeclient) Get(name string, opts metav1.GetOptions) (*apisv1alpha1.CStorPoolCluster, error) {

	if debug.EI.IsCSPCGetErrorInjected() {
		return nil, errors.New("CSPC get error via injection")
	}

	if strings.TrimSpace(name) == "" {
		return nil, errors.New("failed to get cspc: missing cspc name")
	}
	cli, err := k.getClientsetOrCached()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to get cspc {%s} in namespace {%s}", name, k.namespace)
	}
	return k.get(cli, k.namespace, name, opts)
}

// Create creates a cspc in specified namespace in kubernetes cluster
func (k *Kubeclient) Create(cspc *apisv1alpha1.CStorPoolCluster) (*apisv1alpha1.CStorPoolCluster, error) {

	if debug.EI.IsCSPCCreateErrorInjected() {
		return nil, errors.New("CSPC create error via injection")
	}

	if cspc == nil {
		return nil, errors.New("failed to create cspc: nil cspc object")
	}
	cli, err := k.getClientsetOrCached()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to create cspc {%s} in namespace {%s}", cspc.Name, cspc.Namespace)
	}
	return k.create(cli, k.namespace, cspc)
}

// DeleteCollection deletes a collection of cspc objects.
func (k *Kubeclient) DeleteCollection(listOpts metav1.ListOptions, deleteOpts *metav1.DeleteOptions) error {

	if debug.EI.IsCSPCDeleteCollectionErrorInjected() {
		return errors.New("CSPC delete collection error via injection")
	}

	cli, err := k.getClientsetOrCached()
	if err != nil {
		return errors.Wrapf(err, "failed to delete the collection of cspcs")
	}
	return k.delCollection(cli, k.namespace, listOpts, deleteOpts)
}

// Delete deletes a cspc instance from the
// kubecrnetes cluster
func (k *Kubeclient) Delete(name string, deleteOpts *metav1.DeleteOptions) error {

	if debug.EI.IsCSPCDeleteErrorInjected() {
		return errors.New("CSPC delete error via injection")
	}

	if strings.TrimSpace(name) == "" {
		return errors.New("failed to delete cspc: missing cspc name")
	}
	cli, err := k.getClientsetOrCached()
	if err != nil {
		return errors.Wrapf(err, "failed to delete cspc {%s} in namespace {%s}", name, k.namespace)
	}
	return k.del(cli, k.namespace, name, deleteOpts)
}

// Patch patches the CStorPoolCluster claim if present in kubernetes cluster
func (k *Kubeclient) Patch(
	name string,
	pt types.PatchType,
	data []byte, subresources ...string) (*apisv1alpha1.CStorPoolCluster, error) {

	if debug.EI.IsCSPCPatchErrorInjected() {
		return nil, errors.New("CSPC patch error via injection")
	}

	if len(name) == 0 {
		return nil, errors.New("failed to patch cspc : missing cspc name")
	}
	cli, err := k.getClientsetOrCached()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to patch cspc: {%s}", name)
	}
	return k.patch(cli, k.namespace, name, pt, data, subresources...)
}

// Update updates the cspc in specified namespace in kubernetes cluster
func (k *Kubeclient) Update(cspc *apisv1alpha1.CStorPoolCluster) (*apisv1alpha1.CStorPoolCluster, error) {

	if debug.EI.IsCSPCUpdateErrorInjected() {
		return nil, errors.New("CSPC update error via injection")
	}

	if cspc == nil {
		return nil, errors.New("failed to update cspc: nil cspc object")
	}
	cli, err := k.getClientsetOrCached()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to update cspc {%s} in namespace {%s}", cspc.Name, cspc.Namespace)
	}
	return k.update(cli, k.namespace, cspc)
}


text:
package com.yammer.schedulizer.auth;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Authorize {
    Role[] value() default {Role.ADMIN, Role.MEMBER, Role.GUEST};
}


text:
package com.purity.template.engine.core.security.impl;

import com.purity.template.engine.core.security.SecurityAccess;

/**
 * SecurityAccess implementation, which will allow everything.
 */
public class DefaultSecurityAccess implements SecurityAccess{

	/**
	 * Allow access always
	 */
	@Override
	public Boolean isPermittedToRenderTemplate(String templateId)
	{
		return true;
	}

}


text:
namespace base {

class FilePath;

#if defined(OS_WIN)
typedef HANDLE PlatformFile;
#elif defined(OS_POSIX)
typedef int PlatformFile;
#endif

// Thin wrapper around an OS-level file.
// Note that this class does not provide any support for asynchronous IO, other
// than the ability to create asynchronous handles on Windows.
//
// Note about const: this class does not attempt to determine if the underlying
// file system object is affected by a particular method in order to consider
// that method const or not. Only methods that deal with member variables in an
// obvious non-modifying way are marked as const. Any method that forward calls
// to the OS is not considered const, even if there is no apparent change to
// member variables.
class BASE_EXPORT File {
  MOVE_ONLY_TYPE_FOR_CPP_03(File, RValue)

 public:
  // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
  // of the five (possibly combining with other flags) when opening or creating
  // a file.
  // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
  // will be consistent with O_APPEND on POSIX.
  // FLAG_EXCLUSIVE_(READ|WRITE) only grant exclusive access to the file on
  // creation on POSIX; for existing files, consider using Lock().
  enum Flags {
    FLAG_OPEN = 1 << 0,             // Opens a file, only if it exists.
    FLAG_CREATE = 1 << 1,           // Creates a new file, only if it does not
                                    // already exist.
    FLAG_OPEN_ALWAYS = 1 << 2,      // May create a new file.
    FLAG_CREATE_ALWAYS = 1 << 3,    // May overwrite an old file.
    FLAG_OPEN_TRUNCATED = 1 << 4,   // Opens a file and truncates it, only if it
                                    // exists.
    FLAG_READ = 1 << 5,
    FLAG_WRITE = 1 << 6,
    FLAG_APPEND = 1 << 7,
    FLAG_EXCLUSIVE_READ = 1 << 8,   // EXCLUSIVE is opposite of Windows SHARE.
    FLAG_EXCLUSIVE_WRITE = 1 << 9,
    FLAG_ASYNC = 1 << 10,
    FLAG_TEMPORARY = 1 << 11,       // Used on Windows only.
    FLAG_HIDDEN = 1 << 12,          // Used on Windows only.
    FLAG_DELETE_ON_CLOSE = 1 << 13,
    FLAG_WRITE_ATTRIBUTES = 1 << 14,  // Used on Windows only.
    FLAG_SHARE_DELETE = 1 << 15,      // Used on Windows only.
    FLAG_TERMINAL_DEVICE = 1 << 16,   // Serial port flags.
    FLAG_BACKUP_SEMANTICS = 1 << 17,  // Used on Windows only.
    FLAG_EXECUTE = 1 << 18,           // Used on Windows only.
  };

  // This enum has been recorded in multiple histograms. If the order of the
  // fields needs to change, please ensure that those histograms are obsolete or
  // have been moved to a different enum.
  //
  // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
  // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
  // policy doesn't allow the operation to be executed.
  enum Error {
    FILE_OK = 0,
    FILE_ERROR_FAILED = -1,
    FILE_ERROR_IN_USE = -2,
    FILE_ERROR_EXISTS = -3,
    FILE_ERROR_NOT_FOUND = -4,
    FILE_ERROR_ACCESS_DENIED = -5,
    FILE_ERROR_TOO_MANY_OPENED = -6,
    FILE_ERROR_NO_MEMORY = -7,
    FILE_ERROR_NO_SPACE = -8,
    FILE_ERROR_NOT_A_DIRECTORY = -9,
    FILE_ERROR_INVALID_OPERATION = -10,
    FILE_ERROR_SECURITY = -11,
    FILE_ERROR_ABORT = -12,
    FILE_ERROR_NOT_A_FILE = -13,
    FILE_ERROR_NOT_EMPTY = -14,
    FILE_ERROR_INVALID_URL = -15,
    FILE_ERROR_IO = -16,
    // Put new entries here and increment FILE_ERROR_MAX.
    FILE_ERROR_MAX = -17
  };

  // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
  enum Whence {
    FROM_BEGIN   = 0,
    FROM_CURRENT = 1,
    FROM_END     = 2
  };

  // Used to hold information about a given file.
  // If you add more fields to this structure (platform-specific fields are OK),
  // make sure to update all functions that use it in file_util_{win|posix}.cc
  // too, and the ParamTraits<base::PlatformFileInfo> implementation in
  // chrome/common/common_param_traits.cc.
  struct BASE_EXPORT Info {
    Info();
    ~Info();

    // The size of the file in bytes.  Undefined when is_directory is true.
    int64 size;

    // True if the file corresponds to a directory.
    bool is_directory;

    // True if the file corresponds to a symbolic link.
    bool is_symbolic_link;

    // The last modified time of a file.
    base::Time last_modified;

    // The last accessed time of a file.
    base::Time last_accessed;

    // The creation time of a file.
    base::Time creation_time;
  };

  File();

  // Creates or opens the given file. This will fail with 'access denied' if the
  // |name| contains path traversal ('..') components.
  File(const FilePath& name, uint32 flags);

  // Takes ownership of |platform_file|.
  explicit File(PlatformFile platform_file);

  // Creates an object with a specific error_details code.
  explicit File(Error error_details);

  // Move constructor for C++03 move emulation of this type.
  File(RValue other);

  ~File();

  // Move operator= for C++03 move emulation of this type.
  File& operator=(RValue other);

  // Creates or opens the given file.
  void Initialize(const FilePath& name, uint32 flags);

  // Creates or opens the given file, allowing paths with traversal ('..')
  // components. Use only with extreme care.
  void InitializeUnsafe(const FilePath& name, uint32 flags);

  bool IsValid() const;

  // Returns true if a new file was created (or an old one truncated to zero
  // length to simulate a new file, which can happen with
  // FLAG_CREATE_ALWAYS), and false otherwise.
  bool created() const { return created_; }

  // Returns the OS result of opening this file. Note that the way to verify
  // the success of the operation is to use IsValid(), not this method:
  //   File file(name, flags);
  //   if (!file.IsValid())
  //     return;
  Error error_details() const { return error_details_; }

  PlatformFile GetPlatformFile() const;
  PlatformFile TakePlatformFile();

  // Destroying this object closes the file automatically.
  void Close();

  // Changes current position in the file to an |offset| relative to an origin
  // defined by |whence|. Returns the resultant current position in the file
  // (relative to the start) or -1 in case of error.
  int64 Seek(Whence whence, int64 offset);

  // Reads the given number of bytes (or until EOF is reached) starting with the
  // given offset. Returns the number of bytes read, or -1 on error. Note that
  // this function makes a best effort to read all data on all platforms, so it
  // is not intended for stream oriented files but instead for cases when the
  // normal expectation is that actually |size| bytes are read unless there is
  // an error.
  int Read(int64 offset, char* data, int size);

  // Same as above but without seek.
  int ReadAtCurrentPos(char* data, int size);

  // Reads the given number of bytes (or until EOF is reached) starting with the
  // given offset, but does not make any effort to read all data on all
  // platforms. Returns the number of bytes read, or -1 on error.
  int ReadNoBestEffort(int64 offset, char* data, int size);

  // Same as above but without seek.
  int ReadAtCurrentPosNoBestEffort(char* data, int size);

  // Writes the given buffer into the file at the given offset, overwritting any
  // data that was previously there. Returns the number of bytes written, or -1
  // on error. Note that this function makes a best effort to write all data on
  // all platforms.
  // Ignores the offset and writes to the end of the file if the file was opened
  // with FLAG_APPEND.
  int Write(int64 offset, const char* data, int size);

  // Save as above but without seek.
  int WriteAtCurrentPos(const char* data, int size);

  // Save as above but does not make any effort to write all data on all
  // platforms. Returns the number of bytes written, or -1 on error.
  int WriteAtCurrentPosNoBestEffort(const char* data, int size);

  // Returns the current size of this file, or a negative number on failure.
  int64 GetLength();

  // Truncates the file to the given length. If |length| is greater than the
  // current size of the file, the file is extended with zeros. If the file
  // doesn't exist, |false| is returned.
  bool SetLength(int64 length);

  // Flushes the buffers.
  bool Flush();

  // Updates the file times.
  bool SetTimes(Time last_access_time, Time last_modified_time);

  // Returns some basic information for the given file.
  bool GetInfo(Info* info);

  // Attempts to take an exclusive write lock on the file. Returns immediately
  // (i.e. does not wait for another process to unlock the file). If the lock
  // was obtained, the result will be FILE_OK. A lock only guarantees
  // that other processes may not also take a lock on the same file with the
  // same API - it may still be opened, renamed, unlinked, etc.
  //
  // Common semantics:
  //  * Locks are held by processes, but not inherited by child processes.
  //  * Locks are released by the OS on file close or process termination.
  //  * Locks are reliable only on local filesystems.
  //  * Duplicated file handles may also write to locked files.
  // Windows-specific semantics:
  //  * Locks are mandatory for read/write APIs, advisory for mapping APIs.
  //  * Within a process, locking the same file (by the same or new handle)
  //    will fail.
  // POSIX-specific semantics:
  //  * Locks are advisory only.
  //  * Within a process, locking the same file (by the same or new handle)
  //    will succeed.
  //  * Closing any descriptor on a given file releases the lock.
  Error Lock();

  // Unlock a file previously locked.
  Error Unlock();

  bool async() const { return async_; }

#if defined(OS_WIN)
  static Error OSErrorToFileError(DWORD last_error);
#elif defined(OS_POSIX)
  static Error OSErrorToFileError(int saved_errno);
#endif

 private:
  void SetPlatformFile(PlatformFile file);

#if defined(OS_WIN)
  win::ScopedHandle file_;
#elif defined(OS_POSIX)
  ScopedFD file_;
#endif

  Error error_details_;
  bool created_;
  bool async_;
};

}  // namespace base

#endif  // BASE_FILES_FILE_H_


text:
Eve.NET Testbed
===============

An [Eve][1] instance running out there in the wild so [Eve.NET][2] developers
can run their tests against it.

You can clone this repo and run the instance locally (highly reccomended; needs
a working Python environment - see Eve documentation) or you can opt to consume
the free testbed instance available at http://evenet-testbed.herokuapp.com
(will be slow and please, don't abuse it).

Eve and Eve.NET are [Nicola Iarocci][3] and [Gestionali Amica][4] open source
projects, distributed under the [BSD license][5]

[1]: http://python-eve.org
[2]: https://github.com/pyeve/Eve.NET
[3]: http://nicolaiarocci.com
[4]: http://gestionaleamica.com
[5]: https://github.com/CIR2000/evenet-testbed/blob/master/LICENSE


text:
class ProjectAdmin < IntrospectiveAdmin::Base
  register Project do

  end

end


text:
package org.sociotech.urbanlifeplus.microinforadiator.service;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sociotech.urbanlifeplus.microinforadiator.CoreConfiguration;
import org.sociotech.urbanlifeplus.microinforadiator.interfaces.proximity.ProximityEvent;
import org.sociotech.urbanlifeplus.microinforadiator.model.User;
import org.sociotech.urbanlifeplus.microinforadiator.model.event.UserProximityEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * Service that delegates changes in user proximity to the reactor event bus. E.g. if a user comes near to this
 * device using iBeacon, an event containing the user data is pushed to the bus.
 *
 * @author vituslehner 03.07.17
 */
@Service
public class ProximityService {

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

    private final EventBus interfaceEventBus;
    private final EventBus reactorEventBus;

    private final UserService userService;
    private final CoreConfiguration coreConfiguration;

    @Autowired
    public ProximityService(@Qualifier("interfaceEventBus") EventBus interfaceEventBus,
                            @Qualifier("reactorEventBus") EventBus reactorEventBus,
                            UserService userService, CoreConfiguration coreConfiguration) {
        this.interfaceEventBus = interfaceEventBus;
        this.reactorEventBus = reactorEventBus;
        this.userService = userService;
        this.coreConfiguration = coreConfiguration;

        this.interfaceEventBus.register(this);
    }

    /**
     * Listens to nearing users on proximity interfaces and submit a reactor event with retrieved
     * user information to the reactor event bus.
     *
     * @param interfaceEvent the interface event that triggers the action
     */
    @Subscribe
    public void update(ProximityEvent interfaceEvent) {
        LOGGER.debug("INTRFC: Received proximity event: {}", interfaceEvent);
        User user = userService.findUserbyId(interfaceEvent.getUserId());

        UserProximityEvent reactorEvent = new UserProximityEvent(user, coreConfiguration.getMirId(), interfaceEvent.getProximity());
        reactorEventBus.post(reactorEvent);
    }

}