text:
'use strict';

const _ = require('lodash');
const events = require('events');
const { debugLogger } = require('@terascope/job-components');
const messagingModule = require('../../lib/cluster/services/cluster/backends/native/messaging');

describe('messaging module', () => {
    const logger = debugLogger('messaging');

    const testExId = '7890';

    let firstWorkerMsg = null; // eslint-disable-line
    let secondWorkerMsg = null; // eslint-disable-line

    let clusterFn = () => {};

    class MyCluster extends events.EventEmitter {
        constructor() {
            super();
            this.workers = {
                first: {
                    ex_id: testExId,
                    assignment: 'execution_controller',
                    connected: true,
                    send: (msg) => {
                        firstWorkerMsg = msg;
                    },
                    on: (key, fn) => {
                        clusterFn = fn;
                    },
                    removeListener: () => {}
                },
                second: {
                    ex_id: testExId,
                    assignment: 'worker',
                    connected: true,
                    send: (msg) => {
                        secondWorkerMsg = msg;
                    },
                    on: (key, fn) => {
                        clusterFn = fn;
                    },
                    removeListener: () => {}
                },
                third: {
                    ex_id: 'somethingElse',
                    assignment: 'worker',
                    connected: true,
                    send: () => {
                    },
                    on: (key, fn) => {
                        clusterFn = fn;
                    },
                    removeListener: () => {}
                }
            };
        }
    }

    let emitMsg = null;
    const connected = {};

    const io = {
        emit: (msg, msgObj) => {
            emitMsg = { message: msg, data: msgObj };
        },
        sockets: {
            in: (address) => ({
                emit: (msg, msgObj) => {
                    const socketMsg = { message: msg, data: msgObj, address };
                    logger.debug(socketMsg);
                }
            }),
            connected
        },
        eio: {
            clientsCount: 2
        },
        close() {}
    };

    function getContext(obj) {
        const emitter = new events.EventEmitter();
        emitter.setMaxListeners(40);
        const systemEvents = new events.EventEmitter();
        systemEvents.setMaxListeners(40);
        const clusterEmitter = new MyCluster();
        clusterEmitter.setMaxListeners(40);
        const config = Object.assign(emitter, obj);

        const cleanup = () => {
            emitter.removeAllListeners();
            systemEvents.removeAllListeners();
            clusterEmitter.removeAllListeners();
        };

        return {
            sysconfig: {
                teraslice: {
                    master_hostname: '127.0.0.1',
                    port: 47898,
                    action_timeout: 5000,
                    network_latency_buffer: 10
                }
            },
            apis: {
                foundation: {
                    getSystemEvents: () => systemEvents
                }
            },
            cluster: clusterEmitter,
            __testingModule: config,
            cleanup
        };
    }

    beforeEach(() => {
        firstWorkerMsg = null;
        secondWorkerMsg = null;
        _.omitBy(connected);
    });

    afterEach(() => {
        process.removeAllListeners('message');
    });

    it('can make a hostname', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const messaging = messagingModule(testContext, logger);
        messaging.__test_context(io);
        const makeHostName = messaging.__test_context()._makeHostName;
        const { getHostUrl } = messaging;

        expect(makeHostName('127.0.0.1', 5647)).toEqual('http://127.0.0.1:5647');
        expect(makeHostName('127.0.0.1:', 5647)).toEqual('http://127.0.0.1:5647');

        expect(makeHostName('http://127.0.0.1', 5647)).toEqual('http://127.0.0.1:5647');
        expect(makeHostName('https://127.0.0.1', 5647)).toEqual('https://127.0.0.1:5647');

        expect(makeHostName('127.0.0.1', 5647, 'v1')).toEqual('http://127.0.0.1:5647/v1');
        expect(getHostUrl()).toEqual('http://127.0.0.1:47898');
        testContext.cleanup();
    });

    it('can detect itself and make configurations', () => {
        function getConfig(type) {
            const job = JSON.stringify({
                slicer_hostname: '127.0.0.1',
                slicer_port: 47898
            });
            const testContext = getContext({ env: { assignment: type, job } });
            const testModule = messagingModule(testContext, logger).__test_context(io);
            const result = testModule._makeConfigurations();
            testContext.cleanup();
            return result;
        }

        expect(getConfig('node_master')).toEqual({
            clients: { networkClient: true, ipcClient: false },
            hostURL: 'http://127.0.0.1:47898',
            assignment: 'node_master'
        });
        expect(getConfig('cluster_master')).toEqual({
            clients: { networkClient: false, ipcClient: true },
            assignment: 'cluster_master'
        });

        expect(getConfig('assets_service')).toEqual({
            clients: { networkClient: true, ipcClient: true },
            hostURL: 'http://127.0.0.1:47898',
            assignment: 'assets_service'
        });
    });

    it('can be called without errors', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        expect(() => messagingModule(testContext, logger)).not.toThrow();
        testContext.cleanup();
    });

    it('has a router', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const messaging = messagingModule(testContext, logger);
        messaging.__test_context(io);
        const { routing } = messaging.__test_context();

        const routingData = {
            cluster_master: {
                node_master: 'network'
            },
            node_master: {
                cluster_process: 'ipc',
                cluster_master: 'network'
            },
            assets_service: { cluster_master: 'ipc' }
        };

        expect(routing).toEqual(routingData);
        testContext.cleanup();
    });

    it('can determie path for message', () => {
        const testContext1 = getContext({ env: { assignment: 'node_master' } });
        const messaging1 = messagingModule(testContext1, logger);
        const routerNodeMaster = messaging1.__test_context(io)._determinePathForMessage;

        const testContext2 = getContext({ env: { assignment: 'cluster_master' } });
        const messaging2 = messagingModule(testContext2, logger);
        const routerClusterMaster = messaging2.__test_context(io)._determinePathForMessage;

        const testContext4 = getContext({ env: { assignment: 'assets_service' } });
        const messaging4 = messagingModule(testContext4, logger);
        const routerAssetsService = messaging4.__test_context(io)._determinePathForMessage;

        const failureMessage1 = { to: 'theUnknown' };

        expect(routerNodeMaster({ to: 'cluster_process' })).toEqual('ipc');
        expect(routerNodeMaster({ to: 'cluster_master' })).toEqual('network');

        expect(() => routerNodeMaster(failureMessage1)).toThrow();

        expect(routerClusterMaster({ to: 'node_master' })).toEqual('network');

        expect(routerAssetsService({ to: 'cluster_master' })).toEqual('ipc');
        testContext1.cleanup();
        testContext2.cleanup();
        testContext4.cleanup();
    });

    it('can get a list of rooms as the cluster_master', () => {
        connected['some-socket-id'] = {
            rooms: {
                'room-a': 'room-a',
                'room-b': 'room-b'
            }
        };

        connected['another-socket-id'] = {
            rooms: {
                'room-1': 'room-1'
            }
        };

        const testContext = getContext({
            env: {
                assignment: 'cluster_master'
            }
        });

        const messaging = messagingModule(testContext, logger);

        messaging.__test_context(io);

        const rooms = messaging.listRooms();

        expect(rooms).toEqual(['room-a', 'room-b', 'room-1']);

        testContext.cleanup();
    });

    it('can forward/broadcast messages', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const messaging = messagingModule(testContext, logger);
        const forwardMessage = messaging.__test_context(io)._forwardMessage;

        forwardMessage({ to: 'cluster_master', message: 'someEvent' });
        // should be a network emit msg
        expect(emitMsg).toEqual({
            message: 'someEvent',
            data: {
                to: 'cluster_master',
                message: 'someEvent'
            }
        });

        messaging.broadcast('someEvent', { some: 'data' });
        expect(emitMsg).toEqual({
            message: 'networkMessage',
            data: {
                some: 'data',
                message: 'someEvent'
            }
        });

        testContext.cleanup();
    });

    it('can work with messaging:response messages', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const eventEmitter = testContext.apis.foundation.getSystemEvents();
        const messaging = messagingModule(testContext, logger);
        const handleResponse = messaging.__test_context(io)._handleResponse;
        const msgId = 'someId';
        const nodeMsg = { __source: 'node_master', __msgId: msgId, message: 'someMessage' };

        let emittedData = null;

        eventEmitter.once(msgId, (data) => {
            emittedData = data;
        });

        handleResponse(nodeMsg);
        expect(emittedData).toEqual(nodeMsg);

        testContext.cleanup();
    });

    it('can getClientCounts', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const messaging = messagingModule(testContext, logger);

        expect(messaging.getClientCounts()).toEqual(0);
        messaging.__test_context(io);

        expect(messaging.getClientCounts()).toEqual(2);
        testContext.cleanup();
    });

    // This test is broken but it works.
    // We may not need a test for this because this messaging service
    // should be replaced with @terascope/teraslice-messaging.
    // eslint-disable-next-line jest/no-disabled-tests
    xit('can send transactional and non-transactional messages', async () => {
        const testContext = getContext({ env: { assignment: 'cluster_master' } });
        const eventEmitter = testContext.apis.foundation.getSystemEvents();
        const messaging = messagingModule(testContext, logger);
        messaging.__test_context(io);
        const workerMsg = {
            to: 'node_master',
            node_id: 'someId',
            message: 'cluster:execution:stop'
        };
        const transactionalMsg = Object.assign({}, workerMsg, { response: true });
        const transactionalErrorMsg = Object.assign({}, workerMsg, {
            response: true,
            error: 'someError'
        });
        const transactionalTimeoutErrorMsg = Object.assign({}, workerMsg, {
            response: true,
            error: 'someError',
            timeout: 30
        });

        function sendEvent(timer) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    let msgId;
                    if (secondWorkerMsg) {
                        msgId = secondWorkerMsg.__msgId;
                    } else {
                        msgId = '12345';
                    }
                    eventEmitter.emit(msgId, secondWorkerMsg);
                    resolve();
                }, timer);
            });
        }

        // this is technically a sync message, but a promise is returned for composability
        // and to act similiar to its transactional counterpart
        try {
            const bool = await messaging.send(workerMsg);
            expect(bool).toEqual(true);
            expect(firstWorkerMsg).toEqual(workerMsg);

            const [results] = await Promise.all([messaging.send(transactionalMsg), sendEvent(20)]);
            expect(results).toEqual(secondWorkerMsg);

            // testing error scenario
            try {
                await Promise.all([messaging.send(transactionalErrorMsg), sendEvent(20)]);
            } catch (err) {
                expect(err).toEqual('Error: someError occurred on node: node_master');
                try {
                    await Promise.all([
                        messaging.send(transactionalTimeoutErrorMsg),
                        sendEvent(100)
                    ]);
                } catch (error) {
                    const messageSent = secondWorkerMsg;
                    expect(error.message).toEqual(
                        `timeout error while communicating with ${messageSent.to}, msg: ${
                            messageSent.message
                        }, data: ${JSON.stringify(messageSent)}`
                    );
                }
            }
        } finally {
            testContext.cleanup();
        }
    });

    it('can register callbacks and attach them to socket/io', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const messaging = messagingModule(testContext, logger);
        const getRegistry = messaging.__test_context(io)._getRegistry;
        const registerFns = messaging.__test_context(io)._registerFns;
        let exitIsCalled = false;
        const socketSettings = [];

        messaging.register({
            event: 'network:connect',
            identifier: 'node_id',
            callback: (msg, id, identifier) => {
                socketSettings.push({ msg, id, identifier });
                return true;
            }
        });

        messaging.register({
            event: 'cluster:node:get_port',
            callback: () => 3452
        });

        messaging.register({
            event: 'child:exit',
            callback: () => {
                exitIsCalled = true;
            }
        });

        expect(() => messaging.register({
            event: 'some:event',
            callback: () => {
                exitIsCalled = true;
            }
        })).toThrow();

        const results = getRegistry();

        expect(results['cluster:node:get_port']).toBeDefined();
        expect(typeof results['cluster:node:get_port']).toEqual('function');
        expect(results['cluster:node:get_port']()).toEqual(3452);

        // it internally maps 'network:connect' to connect
        expect(results.connect).toBeDefined();
        expect(typeof results.connect).toEqual('function');
        expect(results.connect()).toEqual(true);
        expect(results.connect.__socketIdentifier).toEqual('node_id');

        // node master sets the event on the cluster obj
        testContext.cluster.emit('exit');
        expect(exitIsCalled).toEqual(true);

        socketSettings.shift();

        const socketList = {};
        const joinList = {};
        const socket = {
            rooms: joinList,
            on: (key, fn) => {
                socketList[key] = fn;
            },
            join: (id) => {
                joinList[id] = id;
            },
            removeListener: (key) => {
                delete socketList[key];
            },
            removeListeners: (key) => {
                delete socketList[key];
            }
        };

        registerFns(socket);
        socketList.connect({ node_id: 'someId' });
        expect(socketSettings[0]).toEqual({
            msg: { node_id: 'someId' },
            id: 'someId',
            identifier: 'node_id'
        });

        testContext.cleanup();
    });

    it('can fail if the registering an event for another assignment', () => {
        const testContext = getContext({ env: { assignment: 'node_master' } });
        const messaging = messagingModule(testContext, logger);
        messaging.__test_context(io);
        const socketSettings = [];

        expect(() => {
            messaging.register({
                // this event is not available to node_master
                event: 'node:online',
                identifier: 'node_id',
                callback: (msg, id, identifier) => {
                    socketSettings.push({ msg, id, identifier });
                    return true;
                }
            });
        }).toThrow();

        testContext.cleanup();
    });

    it('can listen and setup server', async () => {
        const testContext1 = getContext({ env: { assignment: 'node_master' } });
        const messaging1 = messagingModule(testContext1, logger);

        const testContext2 = getContext({ env: { assignment: 'cluster_master' } });
        const messaging2 = messagingModule(testContext2, logger);

        expect(() => messaging1.listen()).not.toThrow();
        expect(() => messaging2.listen({ server: 45645 })).not.toThrow();

        await messaging1.shutdown();
        await messaging2.shutdown();

        testContext1.cleanup();
        testContext2.cleanup();
    });

    it('sets up listerns', () => {
        const testContext1 = getContext({ env: { assignment: 'node_master' } });
        const messaging1 = messagingModule(testContext1, logger);
        messaging1.__test_context(io);
        const spy = jest.fn();

        messaging1.registerChildOnlineHook(spy);

        testContext1.cluster.emit('online', { id: 'first' });
        clusterFn({ to: 'cluster_master' });
        clusterFn({ to: 'node_master' });
        clusterFn({ to: 'worker' });

        expect(spy).toHaveBeenCalled();

        testContext1.cleanup();
    });
});


text:
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>

#include <perfmon/pfmlib.h>
#include <perfmon/pfmlib_itanium2.h>

#define NUM_PMCS PMU_MAX_PMCS
#define NUM_PMDS PMU_MAX_PMDS

/*
 * The BRANCH_EVENT is increment by 1 for each branch event. Such event is composed of
 * two entries in the BTB: a source and a target entry. The BTB is full after 4 branch
 * events.
 */
#define SMPL_PERIOD	(4UL*256)

/*
 * We use a small buffer size to exercise the overflow handler
 */
#define SMPL_BUF_NENTRIES	64

#define M_PMD(x)		(1UL<<(x))
#define BTB_REGS_MASK		(M_PMD(8)|M_PMD(9)|M_PMD(10)|M_PMD(11)|M_PMD(12)|M_PMD(13)|M_PMD(14)|M_PMD(15)|M_PMD(16))

static void *smpl_vaddr;
static unsigned long smpl_regs; /* just 64 registers for now */
static pfmlib_param_t evt;

/*
 * we don't use static to make sure the compiler does not inline the function
 */
long func1(void) { return 0;}

long
do_test(unsigned long loop)
{
	long sum  = 0;

	pfm_start();
	while(loop--) {
		if (loop & 0x1)
			sum += func1();
		else
			sum += loop;
	}
	pfm_stop();
	return sum;
}

static void fatal_error(char *fmt,...) __attribute__((noreturn));

static void
fatal_error(char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);

	exit(1);
}

/*
 * print content of sampling buffer
 *
 * XXX: using stdio to print from a signal handler is not safe with multi-threaded
 * applications
 */
#define safe_printf	printf

static int
show_btb_reg(int j, pfm_ita2_reg_t reg)
{
	int ret;
	int is_valid = reg.pmd8_15_ita2_reg.btb_b == 0 && reg.pmd8_15_ita2_reg.btb_mp == 0 ? 0 :1;

	ret = safe_printf("\tPMD%-2d: 0x%016lx b=%d mp=%d valid=%c\n",
			j,
			reg.reg_val,
			 reg.pmd8_15_ita2_reg.btb_b,
			 reg.pmd8_15_ita2_reg.btb_mp,
			is_valid ? 'Y' : 'N');

	if (!is_valid) return ret;

	if (reg.pmd8_15_ita2_reg.btb_b) {
		unsigned long addr;

		addr = 	reg.pmd8_15_ita2_reg.btb_addr<<4;
		addr |= reg.pmd8_15_ita2_reg.btb_slot < 3 ?  reg.pmd8_15_ita2_reg.btb_slot : 0;

		ret = safe_printf("\t       Source Address: 0x%016lx\n"
				  "\t       Taken=%c Prediction: %s\n\n",
			 addr,
			 reg.pmd8_15_ita2_reg.btb_slot < 3 ? 'Y' : 'N',
			 reg.pmd8_15_ita2_reg.btb_mp ? "Failure" : "Success");
	} else {
		ret = safe_printf("\t       Target Address: 0x%016lx\n\n",
			 ((unsigned long)reg.pmd8_15_ita2_reg.btb_addr<<4));
	}
	return ret;
}

static void
show_btb(pfm_ita2_reg_t *btb, pfm_ita2_reg_t *pmd16)
{
	int i, last;

	i    = (pmd16->pmd16_ita2_reg.btbi_full) ? pmd16->pmd16_ita2_reg.btbi_bbi : 0;
	last = pmd16->pmd16_ita2_reg.btbi_bbi;

	do {
		show_btb_reg(i+8, btb[i]);
		i = (i+1) % 8;
	} while (i != last);
}

int
process_smpl_buffer(void)
{
	perfmon_smpl_hdr_t *hdr = (perfmon_smpl_hdr_t *)smpl_vaddr;
	perfmon_smpl_entry_t *ent;
	unsigned long pos;
	unsigned long smpl_entry = 0;
	pfm_ita2_reg_t *reg, *pmd16;
	int i, ret;

	/*
	 * Make sure the kernel uses the format we understand
	 */
	if (PFM_VERSION_MAJOR(hdr->hdr_version) != PFM_VERSION_MAJOR(PFM_SMPL_VERSION)) {
		fatal_error("Perfmon v%u.%u sampling format is not supported\n",
				PFM_VERSION_MAJOR(hdr->hdr_version),
				PFM_VERSION_MINOR(hdr->hdr_version));
	}

	pos = (unsigned long)(hdr+1);
	/*
	 * walk through all the entries recored in the buffer
	 */
	for(i=0; i < hdr->hdr_count; i++) {

		ret = 0;

		ent = (perfmon_smpl_entry_t *)pos;
		/*
		 * print entry header
		 */
		safe_printf("Entry %ld PID:%d CPU:%d STAMP:0x%lx IIP:0x%016lx\n",
			smpl_entry++,
			ent->pid,
			ent->cpu,
			ent->stamp,
			ent->ip);

		/*
		 * point to first recorded register (always contiguous with entry header)
		 */
		reg = (pfm_ita2_reg_t*)(ent+1);

		/*
		 * in this particular example, we have pmd8-pmd15 has the BTB. We have also
		 * included pmd16 (BTB index) has part of the registers to record. This trick
		 * allows us to get the index to decode the sequential order of the BTB.
		 *
		 * Recorded registers are always recorded in increasing order. So we know
		 * that pmd16 is at a fixed offset (+8*sizeof(unsigned long)) from pmd8.
		 */
		pmd16 = reg+8;
		show_btb(reg, pmd16);

		/*
		 * move to next entry
		 */
		pos += hdr->hdr_entry_size;

	}
	return 0;
}

static void
overflow_handler(int n, struct pfm_siginfo *info, struct sigcontext *sc)
{
	unsigned long mask =info->sy_pfm_ovfl[0];
	pfarg_reg_t pd[1];

	/*
	 * Check to see if we received a spurious SIGPROF, i.e., one not
	 * generated by the perfmon subsystem.
	 */
	if (info->sy_code != PROF_OVFL) {
		printf("Received spurious SIGPROF si_code=%d\n", info->sy_code);
		return;
	}
	/*
	 * Each bit set in the overflow mask represents an overflowed counter.
	 *
	 * Here we check that the overflow was caused by our first counter.
	 */
	if ((mask & (1UL<< evt.pfp_pc[0].reg_num)) == 0) {
		printf("Something is wrong, unexpected mask 0x%lx\n", mask);
		exit(1);
	}

	/*
	 * Read the value of the second counter
	 */
	pd[0].reg_num = evt.pfp_pc[1].reg_num;

	if (perfmonctl(getpid(), PFM_READ_PMDS, pd, 1) == -1) {
		perror("PFM_READ_PMDS");
		exit(1);
	}

	printf("Notification received\n");
	process_smpl_buffer();
	/*
	 * And resume monitoring
	 */
	if (perfmonctl(getpid(), PFM_RESTART,NULL, 0) == -1) {
		perror("PFM_RESTART");
		exit(1);
	}
	/* Here we have the PMU enabled and are capturing events */
}

int
main(void)
{
	int ret;
	int type = 0;
	pid_t pid = getpid();
	pfmlib_ita2_param_t ita_param;
	pfarg_reg_t pd[NUM_PMDS];
	pfarg_context_t ctx[1];
	pfmlib_options_t pfmlib_options;
	struct sigaction act;

	/*
	 * Initialize pfm library (required before we can use it)
	 */
	if (pfm_initialize() != PFMLIB_SUCCESS) {
		fatal_error("Can't initialize library\n");
	}

	/*
	 * Let's make sure we run this on the right CPU
	 */
	pfm_get_pmu_type(&type);
	if (type != PFMLIB_ITANIUM2_PMU) {
		char *model;
		pfm_get_pmu_name(&model);
		fatal_error("this program does not work with %s PMU\n", model);
	}

	/*
	 * Install the overflow handler (SIGPROF)
	 */
	memset(&act, 0, sizeof(act));
	act.sa_handler = (sig_t)overflow_handler;
	sigaction (SIGPROF, &act, 0);

	/*
	 * pass options to library (optional)
	 */
	memset(&pfmlib_options, 0, sizeof(pfmlib_options));
	pfmlib_options.pfm_debug = 0; /* set to 1 for debug */
	pfmlib_options.pfm_verbose = 0; /* set to 1 for debug */
	pfm_set_options(&pfmlib_options);

	memset(pd, 0, sizeof(pd));
	memset(ctx, 0, sizeof(ctx));

	/*
	 * prepare parameters to library. we don't use any Itanium
	 * specific features here. so the pfp_model is NULL.
	 */
	memset(&evt,0, sizeof(evt));
	memset(&ita_param,0, sizeof(ita_param));

	/*
	 * because we use a model specific feature, we must initialize the
	 * model specific pfmlib parameter structure and link it to the
	 * common structure.
	 * The magic number is a simple mechanism used by the library to check
	 * that the model specific data structure is decent. You must set it manually
	 * otherwise the model specific feature won't work.
	 */
	ita_param.pfp_magic = PFMLIB_ITA2_PARAM_MAGIC;
	evt.pfp_model       = &ita_param;

	/*
	 * Before calling pfm_find_dispatch(), we must specify what kind
	 * of branches we want to capture. We are interesteed in all the mispredicted branches,
	 * therefore we program we set the various fields of the BTB config to:
	 */
	ita_param.pfp_ita2_btb.btb_used = 1;

	ita_param.pfp_ita2_btb.btb_ds  = 0;
	ita_param.pfp_ita2_btb.btb_tm  = 0x3;
	ita_param.pfp_ita2_btb.btb_ptm = 0x3;
	ita_param.pfp_ita2_btb.btb_ppm = 0x3;
	ita_param.pfp_ita2_btb.btb_brt = 0x0;
	ita_param.pfp_ita2_btb.btb_plm = PFM_PLM3;

	/*
	 * To count the number of occurence of this instruction, we must
	 * program a counting monitor with the IA64_TAGGED_INST_RETIRED_PMC8
	 * event.
	 */
	if (pfm_find_event_byname("BRANCH_EVENT", &evt.pfp_events[0].event) != PFMLIB_SUCCESS) {
		fatal_error("cannot find event BRANCH_EVENT\n");
	}

	/*
	 * set the (global) privilege mode:
	 * 	PFM_PLM3 : user level only
	 */
	evt.pfp_dfl_plm   = PFM_PLM3;
	/*
	 * how many counters we use
	 */
	evt.pfp_event_count = 1;

	/*
	 * let the library figure out the values for the PMCS
	 */
	if ((ret=pfm_dispatch_events(&evt)) != PFMLIB_SUCCESS) {
		fatal_error("cannot configure events: %s\n", pfm_strerror(ret));
	}
	/*
	 * for this example, we will get notified ONLY when the sampling
	 * buffer is full. The monitoring is not to be inherited
	 * in derived tasks
	 */
	ctx[0].ctx_flags        = PFM_FL_INHERIT_NONE;
	ctx[0].ctx_notify_pid   = getpid();
	ctx[0].ctx_smpl_entries = SMPL_BUF_NENTRIES;
	ctx[0].ctx_smpl_regs[0] = smpl_regs = BTB_REGS_MASK;

	/*
	 * now create the context for self monitoring/per-task
	 */
	if (perfmonctl(pid, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) {
		if (errno == ENOSYS) {
			fatal_error("Your kernel does not have performance monitoring support!\n");
		}
		fatal_error("Can't create PFM context %s\n", strerror(errno));
	}

	printf("Sampling buffer mapped at %p\n", ctx[0].ctx_smpl_vaddr);

	smpl_vaddr = ctx[0].ctx_smpl_vaddr;

	/*
	 * Must be done before any PMD/PMD calls (unfreeze PMU). Initialize
	 * PMC/PMD to safe values. psr.up is cleared.
	 */
	if (perfmonctl(pid, PFM_ENABLE, NULL, 0) == -1) {
		fatal_error("perfmonctl error PFM_ENABLE errno %d\n",errno);
	}

	/*
	 * indicate we want notification when buffer is full
	 */
	evt.pfp_pc[0].reg_flags |= PFM_REGFL_OVFL_NOTIFY;

	/*
	 * Now prepare the argument to initialize the PMD and the sampling period
	 */
	pd[0].reg_num         = evt.pfp_pc[0].reg_num;
	pd[0].reg_value       = (~0UL) - SMPL_PERIOD +1;
	pd[0].reg_long_reset  = (~0UL) - SMPL_PERIOD +1;
	pd[0].reg_short_reset = (~0UL) - SMPL_PERIOD +1;

	/*
	 * When our counter overflows, we want to BTB index to be reset, so that we keep
	 * in sync. This is required to make it possible to interpret pmd16 on overflow
	 * to avoid repeating the same branch several times.
	 */
	evt.pfp_pc[0].reg_reset_pmds[0] = M_PMD(16);

	/*
	 * reset pmd16, short and long reset value are set to zero as well
	 */
	pd[1].reg_num         = 16;
	pd[1].reg_value       = 0UL;

	/*
	 * Now program the registers
	 *
	 * We don't use the save variable to indicate the number of elements passed to
	 * the kernel because, as we said earlier, pc may contain more elements than
	 * the number of events we specified, i.e., contains more thann coutning monitors.
	 */
	if (perfmonctl(pid, PFM_WRITE_PMCS, evt.pfp_pc, evt.pfp_pc_count) == -1) {
		fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno);
	}
	if (perfmonctl(pid, PFM_WRITE_PMDS, pd, 2) == -1) {
		fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno);
	}

	/*
	 * Let's roll now.
	 */

	do_test(100000);

	/*
	 * We must call the processing routine to cover the last entries recorded
	 * in the sampling buffer, i.e. which may not be full
	 */
	process_smpl_buffer();

	/*
	 * let's stop this now
	 */
	if (perfmonctl(pid, PFM_DESTROY_CONTEXT, NULL, 0) == -1) {
		fatal_error("perfmonctl error PFM_DESTROY errno %d\n",errno);
	}
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
@interface BNRColorViewController ()

@property (nonatomic, weak) IBOutlet UITextField *textField;

@property (nonatomic, weak) IBOutlet UISlider *redSlider;
@property (nonatomic, weak) IBOutlet UISlider *greenSlider;
@property (nonatomic, weak) IBOutlet UISlider *blueSlider;

@end

@implementation BNRColorViewController

- (IBAction)changeColor:(id)sender
{
    float red = self.redSlider.value;
    float green = self.greenSlider.value;
    float blue = self.blueSlider.value;
    UIColor *newColor = [UIColor colorWithRed:red
                                        green:green
                                         blue:blue
                                        alpha:1.0];
    self.view.backgroundColor = newColor;
}

-(IBAction)dismiss:(id)sender{
    [self.presentingViewController dismissViewControllerAnimated:YES
                           completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    UIColor *color = self.colorDescription.color;

    CGFloat red,green,blue;
    [color getRed:&red
            green:&green
             blue:&blue
            alpha:nil];

    self.redSlider.value = red;
    self.greenSlider.value = green;
    self.blueSlider.value = blue;

    self.view.backgroundColor = color;
    self.textField.text = self.colorDescription.name;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.existingColor) {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.colorDescription.name = self.textField.text;
    self.colorDescription.color = self.view.backgroundColor;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<link rel="import" href="../../../../packages/polymer/polymer.html">

<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/space.html">
<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/button.html">
<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/toolbar.html">
<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/view_port.html">
<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/layout.html">
<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/dialog_message.html">
<link rel="import" href="../../../../packages/gex_webapp_kit/client/elements/loading_space.html">
<link rel="import" href="../../../../packages/paper_elements/paper_toast.html">

<polymer-element name="gex-application">
  <template>
    <gex-view-port id="viewPort">

      <gex-loading-space id="loadingSpace"  ></gex-loading-space>
      <content></content>
      <gex-dialog-message id="message"  ></gex-dialog-message>
      <gex-dialog-message id="warningAuthentication"  >

Authentication by Google account failed

If you are not currently connected to a Google account, the application tried to open a popup so that you can fill your Google account credentials.

Most modern browsers block popups... you might consider add an excpetion for this site in order to Login or Register.

Sorry for the inconvenience.

      </gex-dialog-message>
    </gex-view-port>
  </template>

</polymer-element>


text:
package com.planet_ink.coffee_mud.Abilities.Thief;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Thief_TrapImmunity extends ThiefSkill
{
	@Override
	public String ID()
	{
		return "Thief_TrapImmunity";
	}

	private final static String	localizedName	= CMLib.lang().L("Trap Immunity");

	@Override
	public String name()
	{
		return localizedName;
	}

	@Override
	public String displayText()
	{
		return "";
	}

	@Override
	protected int canAffectCode()
	{
		return CAN_MOBS;
	}

	@Override
	protected int canTargetCode()
	{
		return 0;
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_OK_SELF;
	}

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

	@Override
	public boolean canBeUninvoked()
	{
		return false;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_THIEF_SKILL | Ability.DOMAIN_DETRAP;
	}

	@Override
	public void affectCharStats(final MOB affected, final CharStats affectableStats)
	{
		super.affectCharStats(affected,affectableStats);
		affectableStats.setStat(CharStats.STAT_SAVE_TRAPS,affectableStats.getStat(CharStats.STAT_SAVE_TRAPS)+(proficiency()/2)+(2*getXLEVELLevel(invoker())));
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!(affected instanceof MOB))
			return super.okMessage(myHost,msg);
		final MOB mob=(MOB)affected;
		if(msg.amITarget(mob)
		&&(!msg.amISource(mob))
		&&(msg.tool() instanceof Trap)
		&&(msg.sourceMinor()!=CMMsg.TYP_TEACH))
		{
			mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> deftly avoid(s) a trap."));
			helpProficiency(mob, 0);
			return false;
		}
		return super.okMessage(myHost,msg);
	}
}


text:
ig.module(
	'impact.entity-pool'
)
.requires(
	'impact.game'
)
.defines(function(){ "use strict";

ig.EntityPool = {
	pools: {},

	mixin: {
		staticInstantiate: function( x, y, settings ) {
			return ig.EntityPool.getFromPool( this.classId, x, y, settings );
		},

		erase: function() {
			ig.EntityPool.putInPool( this );
		}
	},

	enableFor: function( Class ) {
		Class.inject(this.mixin);
	},

	getFromPool: function( classId, x, y, settings ) {
		var pool = this.pools[classId];
		if( !pool || !pool.length ) { return null; }

		var instance = pool.pop();
		instance.reset(x, y, settings);
		return instance;
	},

	putInPool: function( instance ) {
		if( !this.pools[instance.classId] ) {
			this.pools[instance.classId] = [instance];
		}
		else {
			this.pools[instance.classId].push(instance);
		}
	},

	drainPool: function( classId ) {
		delete this.pools[classId];
	},

	drainAllPools: function() {
		this.pools = {};
	}
};

ig.Game.inject({
	loadLevel: function( data ) {
		ig.EntityPool.drainAllPools();
		this.parent(data);
	}
});

});


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape
            android:shape="oval">
            <stroke
                android:width="5dp"
                android:color="#d0d4d7"
                />
            <solid android:color="#eef2f5"/>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip android:clipOrientation="vertical" android:gravity="bottom">
            <shape
                android:shape="oval">
                <stroke
                    android:width="5dp"
                    android:color="#ff0001"
                    />
                <gradient
                    android:startColor="#7fc97c"
                    android:endColor="#99f396"
                    android:centerColor="#89e386"
                    android:angle="270"
                    android:gradientRadius="50"
                    android:centerY=".50"
                    />
            </shape>
        </clip>
    </item>
</layer-list>


text:
<?php

App::uses('HtmlElement', 'Ctk.View/Factory/Html/Objects');

/**
 * Creates an object representing a FIELDSET element in HTML.
 *
 * @package       Ctk.Factory
 */
class HtmlFieldset extends HtmlElement {

/**
 * The template to use for this object.
 *
 * @var string The name of the template.
 */
	protected $_template = 'fieldset';

/**
 * The configuration parameters used by the template for this object.
 *
 * @var array The template configuration parameters.
 */
	protected $_params = array(
		'disabled' => null,
		'form' => null,
		'name' => null
	);

/**
 * The type of element this object represents.
 *
 * @var string The element type.
 */
	protected $_nodeType = 'fieldset';
}


text:
class Authorization < ActiveRecord::Base
  belongs_to :user

  validates_presence_of :user_id, :uid, :provider
  # don't allow more than one uid(google token) from the same provider and host
  validates_uniqueness_of :uid, :scope => [:provider,:host]
  # don't allow more than one user id more than once with same host and provider
  validates_uniqueness_of :user_id, :scope => [:host, :provider]

  def self.find_from_hash(hash, host)
    where(provider: hash['provider'], uid: hash['uid'], host: host).first
  end

  def self.create_from_hash(hash, user = nil, host='')
    user ||= User.create_or_find_from_hash!(hash)
    Authorization.create(:user => user, :uid => hash['uid'], :provider => hash['provider'], host: host)
  end
end


text:
package flow

import (
	"github.com/skydive-project/skydive/graffiti/getter"
	"strings"
)

func (obj *FlowLayer) GetFieldBool(key string) (bool, error) {
	return false, getter.ErrFieldNotFound
}

func (obj *FlowLayer) GetFieldInt64(key string) (int64, error) {
	switch key {
	case "ID":
		return int64(obj.ID), nil
	}
	return 0, getter.ErrFieldNotFound
}

func (obj *FlowLayer) GetFieldString(key string) (string, error) {
	switch key {
	case "Protocol":
		return obj.Protocol.String(), nil
	case "A":
		return string(obj.A), nil
	case "B":
		return string(obj.B), nil
	}
	return "", getter.ErrFieldNotFound
}

func (obj *FlowLayer) GetFieldKeys() []string {
	return []string{
		"Protocol",
		"A",
		"B",
		"ID",
	}
}

func (obj *FlowLayer) MatchBool(key string, predicate getter.BoolPredicate) bool {
	return false
}

func (obj *FlowLayer) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if b, err := obj.GetFieldInt64(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *FlowLayer) MatchString(key string, predicate getter.StringPredicate) bool {
	if b, err := obj.GetFieldString(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *FlowLayer) GetField(key string) (interface{}, error) {
	if s, err := obj.GetFieldString(key); err == nil {
		return s, nil
	}

	if i, err := obj.GetFieldInt64(key); err == nil {
		return i, nil
	}
	return nil, getter.ErrFieldNotFound
}

func (obj *FlowMetric) GetFieldBool(key string) (bool, error) {
	return false, getter.ErrFieldNotFound
}

func (obj *FlowMetric) GetFieldInt64(key string) (int64, error) {
	switch key {
	case "ABPackets":
		return int64(obj.ABPackets), nil
	case "ABBytes":
		return int64(obj.ABBytes), nil
	case "BAPackets":
		return int64(obj.BAPackets), nil
	case "BABytes":
		return int64(obj.BABytes), nil
	case "Start":
		return int64(obj.Start), nil
	case "Last":
		return int64(obj.Last), nil
	case "RTT":
		return int64(obj.RTT), nil
	}
	return 0, getter.ErrFieldNotFound
}

func (obj *FlowMetric) GetFieldString(key string) (string, error) {
	return "", getter.ErrFieldNotFound
}

func (obj *FlowMetric) GetFieldKeys() []string {
	return []string{
		"ABPackets",
		"ABBytes",
		"BAPackets",
		"BABytes",
		"Start",
		"Last",
		"RTT",
	}
}

func (obj *FlowMetric) MatchBool(key string, predicate getter.BoolPredicate) bool {
	return false
}

func (obj *FlowMetric) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if b, err := obj.GetFieldInt64(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *FlowMetric) MatchString(key string, predicate getter.StringPredicate) bool {
	return false
}

func (obj *FlowMetric) GetField(key string) (interface{}, error) {
	if i, err := obj.GetFieldInt64(key); err == nil {
		return i, nil
	}
	return nil, getter.ErrFieldNotFound
}

func (obj *ICMPLayer) GetFieldBool(key string) (bool, error) {
	return false, getter.ErrFieldNotFound
}

func (obj *ICMPLayer) GetFieldInt64(key string) (int64, error) {
	switch key {
	case "Code":
		return int64(obj.Code), nil
	case "ID":
		return int64(obj.ID), nil
	}
	return 0, getter.ErrFieldNotFound
}

func (obj *ICMPLayer) GetFieldString(key string) (string, error) {
	switch key {
	case "Type":
		return obj.Type.String(), nil
	}
	return "", getter.ErrFieldNotFound
}

func (obj *ICMPLayer) GetFieldKeys() []string {
	return []string{
		"Type",
		"Code",
		"ID",
	}
}

func (obj *ICMPLayer) MatchBool(key string, predicate getter.BoolPredicate) bool {
	return false
}

func (obj *ICMPLayer) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if b, err := obj.GetFieldInt64(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *ICMPLayer) MatchString(key string, predicate getter.StringPredicate) bool {
	if b, err := obj.GetFieldString(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *ICMPLayer) GetField(key string) (interface{}, error) {
	if s, err := obj.GetFieldString(key); err == nil {
		return s, nil
	}

	if i, err := obj.GetFieldInt64(key); err == nil {
		return i, nil
	}
	return nil, getter.ErrFieldNotFound
}

func (obj *IPMetric) GetFieldBool(key string) (bool, error) {
	return false, getter.ErrFieldNotFound
}

func (obj *IPMetric) GetFieldInt64(key string) (int64, error) {
	switch key {
	case "Fragments":
		return int64(obj.Fragments), nil
	case "FragmentErrors":
		return int64(obj.FragmentErrors), nil
	}
	return 0, getter.ErrFieldNotFound
}

func (obj *IPMetric) GetFieldString(key string) (string, error) {
	return "", getter.ErrFieldNotFound
}

func (obj *IPMetric) GetFieldKeys() []string {
	return []string{
		"Fragments",
		"FragmentErrors",
	}
}

func (obj *IPMetric) MatchBool(key string, predicate getter.BoolPredicate) bool {
	return false
}

func (obj *IPMetric) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if b, err := obj.GetFieldInt64(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *IPMetric) MatchString(key string, predicate getter.StringPredicate) bool {
	return false
}

func (obj *IPMetric) GetField(key string) (interface{}, error) {
	if i, err := obj.GetFieldInt64(key); err == nil {
		return i, nil
	}
	return nil, getter.ErrFieldNotFound
}

func (obj *TCPMetric) GetFieldBool(key string) (bool, error) {
	return false, getter.ErrFieldNotFound
}

func (obj *TCPMetric) GetFieldInt64(key string) (int64, error) {
	switch key {
	case "ABSynStart":
		return int64(obj.ABSynStart), nil
	case "BASynStart":
		return int64(obj.BASynStart), nil
	case "ABSynTTL":
		return int64(obj.ABSynTTL), nil
	case "BASynTTL":
		return int64(obj.BASynTTL), nil
	case "ABFinStart":
		return int64(obj.ABFinStart), nil
	case "BAFinStart":
		return int64(obj.BAFinStart), nil
	case "ABRstStart":
		return int64(obj.ABRstStart), nil
	case "BARstStart":
		return int64(obj.BARstStart), nil
	case "ABSegmentOutOfOrder":
		return int64(obj.ABSegmentOutOfOrder), nil
	case "ABSegmentSkipped":
		return int64(obj.ABSegmentSkipped), nil
	case "ABSegmentSkippedBytes":
		return int64(obj.ABSegmentSkippedBytes), nil
	case "ABPackets":
		return int64(obj.ABPackets), nil
	case "ABBytes":
		return int64(obj.ABBytes), nil
	case "ABSawStart":
		return int64(obj.ABSawStart), nil
	case "ABSawEnd":
		return int64(obj.ABSawEnd), nil
	case "BASegmentOutOfOrder":
		return int64(obj.BASegmentOutOfOrder), nil
	case "BASegmentSkipped":
		return int64(obj.BASegmentSkipped), nil
	case "BASegmentSkippedBytes":
		return int64(obj.BASegmentSkippedBytes), nil
	case "BAPackets":
		return int64(obj.BAPackets), nil
	case "BABytes":
		return int64(obj.BABytes), nil
	case "BASawStart":
		return int64(obj.BASawStart), nil
	case "BASawEnd":
		return int64(obj.BASawEnd), nil
	}
	return 0, getter.ErrFieldNotFound
}

func (obj *TCPMetric) GetFieldString(key string) (string, error) {
	return "", getter.ErrFieldNotFound
}

func (obj *TCPMetric) GetFieldKeys() []string {
	return []string{
		"ABSynStart",
		"BASynStart",
		"ABSynTTL",
		"BASynTTL",
		"ABFinStart",
		"BAFinStart",
		"ABRstStart",
		"BARstStart",
		"ABSegmentOutOfOrder",
		"ABSegmentSkipped",
		"ABSegmentSkippedBytes",
		"ABPackets",
		"ABBytes",
		"ABSawStart",
		"ABSawEnd",
		"BASegmentOutOfOrder",
		"BASegmentSkipped",
		"BASegmentSkippedBytes",
		"BAPackets",
		"BABytes",
		"BASawStart",
		"BASawEnd",
	}
}

func (obj *TCPMetric) MatchBool(key string, predicate getter.BoolPredicate) bool {
	return false
}

func (obj *TCPMetric) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if b, err := obj.GetFieldInt64(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *TCPMetric) MatchString(key string, predicate getter.StringPredicate) bool {
	return false
}

func (obj *TCPMetric) GetField(key string) (interface{}, error) {
	if i, err := obj.GetFieldInt64(key); err == nil {
		return i, nil
	}
	return nil, getter.ErrFieldNotFound
}

func (obj *TransportLayer) GetFieldBool(key string) (bool, error) {
	return false, getter.ErrFieldNotFound
}

func (obj *TransportLayer) GetFieldInt64(key string) (int64, error) {
	switch key {
	case "A":
		return int64(obj.A), nil
	case "B":
		return int64(obj.B), nil
	case "ID":
		return int64(obj.ID), nil
	}
	return 0, getter.ErrFieldNotFound
}

func (obj *TransportLayer) GetFieldString(key string) (string, error) {
	switch key {
	case "Protocol":
		return obj.Protocol.String(), nil
	}
	return "", getter.ErrFieldNotFound
}

func (obj *TransportLayer) GetFieldKeys() []string {
	return []string{
		"Protocol",
		"A",
		"B",
		"ID",
	}
}

func (obj *TransportLayer) MatchBool(key string, predicate getter.BoolPredicate) bool {
	return false
}

func (obj *TransportLayer) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if b, err := obj.GetFieldInt64(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *TransportLayer) MatchString(key string, predicate getter.StringPredicate) bool {
	if b, err := obj.GetFieldString(key); err == nil {
		return predicate(b)
	}
	return false
}

func (obj *TransportLayer) GetField(key string) (interface{}, error) {
	if s, err := obj.GetFieldString(key); err == nil {
		return s, nil
	}

	if i, err := obj.GetFieldInt64(key); err == nil {
		return i, nil
	}
	return nil, getter.ErrFieldNotFound
}

func init() {
	strings.Index("", ".")
}


text:
IMPORTANT: comment on: [What about merging whith Ultisnip using its engine](https://github.com/garbas/vim-snipmate/issues/114)

Snipmate & UltiSnip Snippets
============================

This repository contains snippets files for various programming languages.

It is community-maintained and many people have contributed snippet files and
other improvements already.

Contents
========

    snippets/*: snippets using snipmate format
    UltiSnips/*: snippets using UltiSnips format

Snippet engines
===============

There are different forks of snippet engines which allow the user to insert
sippets by typing the name of a snippet hitting the expansion mapping.

    garbas/vim-snipmate [4]:
      VimL, snipmate-snippets, engine sometimes behaves strange, supports
      rewriting snippets on the fly (eg adding a second version with folding
      markers)

    MarcWeber/UltiSnips [6]:
      python, snipmate-snippets and UltiSnips-snippets

    SirVer/ultisnips [7]:
      python, UltiSnips-snippets

    github.com/Shougo/neosnippet [5]:
      viml, has a compatible mode allowing to reuse most snipmate snippets ?

    XPTemplate:
      totally different syntax, does not read snippets contained in this file,
      but it is also very powerful

    ... there are some more, but they have less features which is why I don't
    mention them here

UltiSnips engine has additional features such as "nested snippets".

Which one to use? If you have python give MarcWeber/UltiSnips a try because its
fast and supports all important features. You can prefer the UltiSnip versions
of the snippets by setting the "always_use_first_snippet" option to 1.

If you have VimL only (vim without python support) your best option is using
garbas/vim-snipmate and cope with the minor bugs found in the engine.

Policies / for contributors
===========================
Some snippets are useful for almost all languages, so let's try to have the same
triggers for them:

```
if : if without else
ife: if $1 else $2
eif : else if ($1) { .. }
el  : else ..
```

If you're not satisfied with these defaults, open a ticket that we implement
aliasing. Then you can remap "else" to "el" or the like.

Don't add stupid placeholder default texts like
```
if (${1:condition}){
  ${2:some code here}
}
```
instead use:

```
if (${1}){
  ${2}
}
```

Exception: Functions which are used less often, such as Vim's matchall(), matchstr()
functions which case hints may be helpful to remember order. In the VimL case
get vim-dev plugin which has function completion

Thus for conditions (while, if ..) and block bodies just use ${N} - Thanks

Open questions:
What about one line if ee then .. else .. vs if \n .. then \n ... \n else \n .. ?
What about wh(ile), which trigger?
Discuss at: https://github.com/honza/vim-snippets/issues/230

Related repositories
====================
We also encourage people to maintain sets of snippets for particular use cases
so that all users can benefit from them.  People can list their snippet repositories here:

     * https://github.com/rbonvall/snipmate-snippets-bib (snippets for BibTeX files)
     * https://github.com/sudar/vim-arduino-snippets (snippets for Arduino files)
     * https://github.com/zedr/zope-snipmate-bundle.git (snippets for Python, TAL and ZCML)
     * https://github.com/bonsaiben/bootstrap-snippets (snippets for Twitter Bootstrap markup, in HTML and Haml)

Installation using VAM: "github:rbonvall/snipmate-snippets-bib"

Future - ideas - examples
=========================
[overview snippet engines](http://vim-wiki.mawercer.de/wiki/topic/text-snippets-skeletons-templates.html)
If you have ideas you can add them to that list of "snippet engine features by example".

Historical notes
================

[vim-snipmate][1] was originally started by [Michael Sanders][2] who has now
unfortunately abandoned the project. [Rok Garbas][3] is now maintaining a
[fork][4] of the project in hopes of improving the existing code base.

Versions / dialects / ..
========================
There are some issues, such as newer language versions may require other
snippets than older. If this exists we currently recommend doing this:

add snippets/ruby.snippets (common snippets)
add snippets/ruby-1.8.snippets (1.8 only)
add snippets/ruby-1.9.snippets (1.9 only)

then configure github.com/garbas/vim-snipmate this way:

```vim
let g:snipMate = {}
let g:snipMate.scope_aliases = {}
let g:snipMate.scope_aliases['ruby'] = 'ruby,ruby-rails,ruby-1.9'
```

or github.com/MarcWeber/UltiSnips this way:

```vim
let g:UltiSnips = {}

let g:UltiSnips.snipmate_ft_filter = {
	    \ 'default' : {'filetypes': ["FILETYPE"] },
	    \ 'ruby'    : {'filetypes': ["ruby", "ruby-rails", "ruby-1.9"] },
```

If it happens that you work on a project requiring ruby-1.8 snippets instead,
consider using vim-addon-local-vimrc and override the filetypes.

Well - of course it may not make sense to create a new file for each
ruby-library-version triplet. Sometimes postfixing a name such as

    migrate_lib_20_down
    migrate_lib_20_up

will do it then if syntax has changed.

Language maintainers
--------------------

No one can really be proficient in all programming languages. If you would like
to maintain snippets for a language, please get in touch.

Notes: People are interested in snippets - and their interest may stop again
at will. So its ok if people maintain a language only for a short period of
time - or jump in and get things done - don't let the flow stop :)
vim-snippets is not like the "linux kernel".

* Python - [honza](http://github.com/honza)
* Javascript - [honza](http://github.com/honza)
* HTML Django - [honza](http://github.com/honza)
* Markdown - [honza](http://github.com/honza)
* Ruby - [taq](http://github.com/taq)
* PHP - [chrisyue](http://github.com/chrisyue)
* Scala - [gorodinskiy](https://github.com/gorodinskiy)
* Falcon - [steveno](https://github.com/steveno)
* Elixir - [iurifq](https://github.com/iurifq)

Contributing notes
------------------

Until further work is done on `vim-snipmate`, please don't add folding markers
into snippets. `vim-snipmate` has some comments about how to patch all snippets
on the fly adding those.

Because MarcWeber/UltiSnips [6] supports also snipmate-snippets there is no
need to duplicate all snippets - only those snippets who use advanced UltiSnips
features should be duplicated in UltiSnips (?)

Currently all snippets from UltiSnips have been put into UltiSnips - some work
on merging should be done (dropping duplicates etc)

Authors
-------

For a list of authors, please see the `AUTHORS` files.

License
-------

Just as the original snipMate plugin, all the snippets are licensed under the
terms of the MIT license.

[1]: http://github.com/garbas/vim-snipmate
[2]: http://github.com/msanders
[3]: http://github.com/garbas
[4]: http://github.com/garbas/vim-snipmate
[5]: http://github.com/Shougo/neosnippet
[6]: http://github.com/MarcWeber/UltiSnips
[7]: http://github.com/SirVer/ultisnips


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
    Linux on Hyper-V and Azure Test Code, ver. 1.0.0
    Copyright (c) Microsoft Corporation

    All rights reserved.
    Licensed under the Apache License, Version 2.0 (the ""License"");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
    OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
    ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
    PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing
    permissions and limitations under the License.
-->

<config>
    <global>
        <defaultSnapshot>ICABase</defaultSnapshot>
        <LisaInitScript>
            <file>.\setupScripts\CreateVMs.ps1</file>
        </LisaInitScript>
       <imageStoreDir>\\unc\path</imageStoreDir>
    </global>
    <testSuites>
        <suite>
            <suiteName>hv-sock</suiteName>
            <suiteTests>
                <suiteTest>MainVM_Checkpoint</suiteTest>
                <suiteTest>HV_Sock_HostAsServer</suiteTest>
                <suiteTest>HV_Sock_VmAsServer</suiteTest>
            </suiteTests>
        </suite>
    </testSuites>
    <testCases>
        <test>
            <testName>MainVM_Checkpoint</testName>
            <testScript>setupscripts\PreVSS_TakeSnapshot.ps1</testScript>
            <timeout>600</timeout>
            <testParams>
                <param>TC_COVERED=snapshot</param>
                <param>snapshotVm=main</param>
                <param>snapshotName=ICABase</param>
            </testParams>
            <onError>Continue</onError>
            <noReboot>False</noReboot>
        </test>
        <test>
            <testName>HV_Sock_HostAsServer</testName>
            <testScript>setupscripts\HV_Sock_Basic.ps1</testScript>
            <files>tools/hv-sock/client_on_vm.c,tools/hv-sock/client_on_vm</files>
            <testParams>
                <param>TC_COVERED=HV-Sock-01</param>
                <param>TEST_TYPE=1</param>
            </testParams>
            <postTest>SetupScripts\GcovDataCollect.ps1</postTest>
            <timeout>400</timeout>
        </test>
        <test>
            <testName>HV_Sock_VmAsServer</testName>
            <testScript>setupscripts\HV_Sock_Basic.ps1</testScript>
            <files>tools/hv-sock/server_on_vm.c,tools/hv-sock/server_on_vm</files>
            <testParams>
                <param>TC_COVERED=HV-Sock-02</param>
                <param>TEST_TYPE=2</param>
            </testParams>
            <noReboot>True</noReboot>
            <postTest>SetupScripts\GcovDataCollect.ps1</postTest>
            <timeout>400</timeout>
        </test>
    </testCases>
    <VMs>
        <vm>
            <role>SUT1</role>
            <hvServer>localhost</hvServer>
            <vmName>code-coverage-hv-sock</vmName>
            <os>Linux</os>
            <ipv4></ipv4>
            <sshKey>rhel5_id_rsa.ppk</sshKey>
            <testParams>
                <param>SSH_PRIVATE_KEY=rhel5_id_rsa</param>
                <param>snapshotName=ICABase</param>
                <param>VMSnapshot=ICABase</param>
            </testParams>
            <suite>hv-sock</suite>
            <hardware>
                <create>true</create>
                <numCPUs>8</numCPUs>
                <memSize>8192</memSize>
                <disableDiff>True</disableDiff>
                <generation>1</generation>
                <nic>VMBus,External</nic>
            </hardware>
        </vm>
    </VMs>
</config>


text:
namespace Blinds.Data.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;

    using Blinds.Data.Models.Enumerations;
    using Contracts;
    using Common;
    public class FabricAndLamel : IDeletableEntity
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public Color Color { get; set; }

        [Required]
        public Material Material { get; set; }

        [Required]
        public decimal Quantity { get; set; }

        [Required]
        [Range(0, int.MaxValue, ErrorMessage = GlobalConstants.PriceMinValue)]
        public decimal Price { get; set; }

        public virtual BlindType BlindType { get; set; }

        [Required]
        public int BlindTypeId { get; set; }

        public bool Deleted { get; set; }

        public DateTime? DeletedOn { get; set; }
    }
}


text:
"""
== Juggler Sequence ==
Juggler sequence start with any positive integer n. The next term is
obtained as follows:
    If n term is even, the next term is floor value of square root of n .
    If n is odd, the next term is floor value of 3 time the square root of n.

https://en.wikipedia.org/wiki/Juggler_sequence
"""

# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
import math

def juggler_sequence(number: int) -> list[int]:
    """
    >>> juggler_sequence(0)
    Traceback (most recent call last):
        ...
    ValueError: Input value of [number=0] must be a positive integer
    >>> juggler_sequence(1)
    [1]
    >>> juggler_sequence(2)
    [2, 1]
    >>> juggler_sequence(3)
    [3, 5, 11, 36, 6, 2, 1]
    >>> juggler_sequence(5)
    [5, 11, 36, 6, 2, 1]
    >>> juggler_sequence(10)
    [10, 3, 5, 11, 36, 6, 2, 1]
    >>> juggler_sequence(25)
    [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1]
    >>> juggler_sequence(6.0)
    Traceback (most recent call last):
        ...
    TypeError: Input value of [number=6.0] must be an integer
    >>> juggler_sequence(-1)
    Traceback (most recent call last):
        ...
    ValueError: Input value of [number=-1] must be a positive integer
    """
    if not isinstance(number, int):
        raise TypeError(f"Input value of [number={number}] must be an integer")
    if number < 1:
        raise ValueError(f"Input value of [number={number}] must be a positive integer")
    sequence = [number]
    while number != 1:
        if number % 2 == 0:
            number = math.floor(math.sqrt(number))
        else:
            number = math.floor(
                math.sqrt(number) * math.sqrt(number) * math.sqrt(number)
            )
        sequence.append(number)
    return sequence

if __name__ == "__main__":
    import doctest

    doctest.testmod()


text:
<?php

namespace Elcodi\Component\Coupon\Exception;

use Elcodi\Component\Coupon\Exception\Abstracts\AbstractCouponException;

/**
 * Custom CouponIncompatibleException.
 */
class CouponIncompatibleException extends AbstractCouponException
{
}


text:
/*
 * iBankApp
 *
 * License : Apache License,Version 2.0, January 2004
 *
 * See the LICENSE file in English or LICENSE.zh_CN in chinese
 * in the root directory or <http://www.apache.org/licenses/>.
 */

/*
 * iBankApp
 *
 * License : Apache License,Version 2.0, January 2004
 *
 * See the LICENSE file in English or LICENSE.zh_CN in chinese
 * in the root directory or <http://www.apache.org/licenses/>.
 */

/*
 * iBankApp
 *
 * License : Apache License,Version 2.0, January 2004
 *
 * See the LICENSE file in English or LICENSE.zh_CN in chinese
 * in the root directory or <http://www.apache.org/licenses/>.
 */

/*
 * iBankApp
 *
 * License : Apache License,Version 2.0, January 2004
 *
 * See the LICENSE file in English or LICENSE.zh_CN in chinese
 * in the root directory or <http://www.apache.org/licenses/>.
 */

package org.ibankapp.base.persistence.validation.test;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "TEST_MODELWITHUNIQUE")
public class TestModelWithInheritedUnique extends TestModelWithUnique {

  private String type;

  @Column
  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Writ. 7(72): 1281 (1924)

#### Original name
Camillea luzonensis Lloyd

### Remarks
null


text:
kubeflow.fairing.builders.append package
========================================

Submodules
----------

kubeflow.fairing.builders.append.append module
----------------------------------------------

.. automodule:: kubeflow.fairing.builders.append.append
   :members:
   :undoc-members:
   :show-inheritance:

Module contents
---------------

.. automodule:: kubeflow.fairing.builders.append
   :members:
   :undoc-members:
   :show-inheritance:


text:
export interface ChangeEvent<T> {
    value: T;
}


text:
define(["cmwapi/cmwapi", "esri/kernel", "esri/geometry/Extent", "esri/geometry/Point",
    "cmwapi-adapter/ViewUtils", "esri/tasks/PrintTask", "esri/tasks/PrintParameters", "esri/tasks/PrintTemplate",
    "OWFWidgetExtensions/owf-widget-extended"],
    function(CommonMapApi, EsriNS, Extent, Point, ViewUtils, PrintTask, PrintParameters, PrintTemplate,
        OWFWidgetExtensions) {

    /**
     * @constructor
     * @param map {object} ESRI map object for which this adapter should apply
     * @param overlayManager {module:cmwapi-adapter/EsriOverlayManager}
     * @alias module:cmwapi-adapter/View
     */
    var View = function(map, overlayManager) {
        var me = this;

        var OVERLAY_PREF_NAMESPACE = 'com.esri';
        var OVERLAY_PREF_NAME = 'mapView';

        /**
         * Zooms a map to a particular range.  If given an array of zoom ranges,
         * only the last one is used for the attached Map.
         * @method handleZoom
         * @see module:cmwapi/map/view/Zoom~Handler
         * @memberof module:cmwapi-adapter/View#
         */
        me.handleZoom = function(sender, data) {
            if(data.length > 1) {
                // Only respond to the last position sent.  No need to make the map jump around.
                var lastPos = data.length - 1;
                //map.setScale(data[lastPos].range);
                map.setScale(ViewUtils.zoomAltitudeToScale(map, data[lastPos].range));
            } else {
                //map.setScale(data.range);
                map.setScale(ViewUtils.zoomAltitudeToScale(map, data.range));
            }
        };
        CommonMapApi.view.zoom.addHandler(me.handleZoom);

        /**
         * Centers/zooms a map to a particular overlay.  If given an overlay and zoom level, it will attempt to center
         * on the union of all Features under that overlay.  If given an array of overlays and zoom ranges are provided,
         * only the last one is used to center the map.
         * @method handleCenterOverlay
         * @see module:cmwapi/map/view/CenterOverlay~Handler
         * @memberof module:cmwapi-adapter/View#
         */
        me.handleCenterOverlay = function(sender, data) {
            if(data.length > 1) {
                // Only respond to the last position sent.  No need to make the map jump around.
                var lastPos = data.length - 1;
                var lastData = data[lastPos];
                overlayManager.overlay.zoom(sender, lastData.overlayId, lastData.zoom);
            } else {
                overlayManager.overlay.zoom(sender, data.overlayId, data.zoom);
            }
        };
        CommonMapApi.view.center.overlay.addHandler(me.handleCenterOverlay);

        /**
         * Centers/zooms a map to a particular CMWAPI feature.  If given an array of features and zoom ranges,
         * only the last one is used to center the map.
         * @method handleCenterFeature
         * @see module:cmwapi/map/view/CenterFeaure~Handler
         * @memberof module:cmwapi-adapter/View#
         */
        me.handleCenterFeature = function(sender, data) {
            if(data.length > 1) {
                // Only respond to the last position sent.  No need to make the map jump around.
                var lastPos = data.length - 1;
                var lastData = data[lastPos];
                overlayManager.feature.zoom(sender, lastData.overlayId, lastData.featureId,
                    null, null, lastData.zoom);
            } else {
                overlayManager.feature.zoom(sender, data.overlayId, data.featureId,
                    null, null, data.zoom);
            }
        };
        CommonMapApi.view.center.feature.addHandler(me.handleCenterFeature);

        /**
         * Centers/zooms a map to a particular location as specified by latitude/longitude.  If given an array of
         * locations, only the last one is used.
         * @method handleCenterLocation
         * @see module:cmwapi/map/view/CenterLocation~Handler
         * @memberof module:cmwapi-adapter/View#
         */
        me.handleCenterLocation = function(sender, data) {
            var point;
            if(data.length > 1) {
                // Only respond to the last position sent.  No need to make the map jump around.
                var lastPos = data.length - 1;
                point = new Point(data[lastPos].location.lon,
                    data[lastPos].location.lat,
                    map.geographicExtent.spatialReference);

                // Set the zoom level or just the center, depending upon zoom param.
                if (data[lastPos].zoom && data[lastPos].zoom.toString().toLowerCase() === "auto") {
                    map.setZoom(map.getMaxZoom());
                }
                else if (data[lastPos].zoom) {
                    map.setScale(ViewUtils.zoomAltitudeToScale(map, data[lastPos].zoom));
                }

                // Recenter the map.
                map.centerAt(point);

            } else {
                point = new Point(data.location.lon,
                    data.location.lat,
                    map.geographicExtent.spatialReference);
                // Set the zoom level or just the center, depending upon zoom param.
                if (data.zoom && data.zoom.toString().toLowerCase() === "auto") {
                    map.setZoom(map.getMaxZoom());
                }
                else if (data.zoom) {
                    map.setScale(ViewUtils.zoomAltitudeToScale(map, data.zoom));
                }

                // Recenter the map.
                map.centerAt(point);
            }
        };
        CommonMapApi.view.center.location.addHandler(me.handleCenterLocation);

        /**
         * Centers/zooms a map to a particular CMWAPI bounds.  If given an array of bounds and zoom ranges,
         * only the last one is used to adjust the map.
         * @method handleCenterBounds
         * @see module:cmwapi/map/view/CenterBounds~Handler
         * @memberof module:cmwapi-adapter/View#
         */
        me.handleCenterBounds = function(sender, data) {
            var extent;
            var payload;

            if(data.length > 1) {
                // Only respond to the last position sent.  No need to make the map jump around.
                var lastPos = data.length - 1;
                extent = new Extent(data[lastPos].bounds.southWest.lon,
                    data[lastPos].bounds.southWest.lat,
                    data[lastPos].bounds.northEast.lon,
                    data[lastPos].bounds.northEast.lat,
                    map.geographicExtent.spatialReference);
                payload = data[lastPos];
            } else {
                extent = new Extent(data.bounds.southWest.lon,
                    data.bounds.southWest.lat,
                    data.bounds.northEast.lon,
                    data.bounds.northEast.lat,
                    map.geographicExtent.spatialReference);
                payload = data;
            }

            // If auto zoom, reset the entire extent.
            if (payload.zoom === "auto") {
                map.setExtent(extent, true);
            }
            // If we have a non-auto zoom, recenter the map and zoom.
            else if (typeof payload.zoom !== "undefined") {
                // Set the zoom level.
                map.setScale(ViewUtils.zoomAltitudeToScale(map, payload.zoom));

                // Recenter the map.
                map.centerAt(extent.getCenter());
            }
            // Otherwise, recenter the map.
            else {
                map.centerAt(extent.getCenter());
            }
        };
        CommonMapApi.view.center.bounds.addHandler(me.handleCenterBounds);

        /**
         * Prints/ Saves the current view of the given map.  If given a value for template,
         * create the saved file according to the passed template values.
         * @method printView
         * @see module:cmwapi/map/view/Print
         * @memberof module:cmwapi-adapter/View#
         */
        me.printView = function(sender, data) {
            var params = new PrintParameters();
            params.map = map;
            var filename;
            var printTask = new PrintTask(window.esriPrintService);
            if(data.template) {
                var t = new PrintTemplate();
                t.format = data.template.format;
                t.layout = data.template.name;
                t.layoutOptions = data.template.options;
                filename = t.label = data.template.label;
                params.template = t;
            }
            printTask.execute(params, function(e) {
                filename  = filename || e.url;
                var a = $("<a>").attr("href", e.url).attr("download", filename).appendTo("body");
                a[0].click();
                a.remove();
            });
        };
        CommonMapApi.view.print.addHandler(me.printView);

        me.saveView = function() {
            var bounds = {
                southWest: {
                    lat: map.geographicExtent.ymin,
                    lon: Extent.prototype._normalizeX(map.geographicExtent.xmin, map.geographicExtent.spatialReference._getInfo()).x
                },
                northEast: {
                    lat: map.geographicExtent.ymax,
                    lon: Extent.prototype._normalizeX(map.geographicExtent.xmax, map.geographicExtent.spatialReference._getInfo()).x
                }
            };

            var center = {
                lat: map.geographicExtent.getCenter().y,
                lon: Extent.prototype._normalizeX(map.geographicExtent.getCenter().x, map.geographicExtent.spatialReference._getInfo()).x
            };

            var range = ViewUtils.scaleToZoomAltitude(map);

            var successHandler = function() {
                // Empty example handler.  No action required.
            };
            var failureHandler = function() {
                CommonMapApi.error.send({
                    sender: OWF.getInstanceId(),
                    type: "internal error",
                    msg: "Unable to archive state",
                    error: "Error: " + e
                });
            };
            var dataValue = OWFWidgetExtensions.Util.toString({bounds: bounds, center: center, range: range});
            OWFWidgetExtensions.Preferences.setWidgetInstancePreference({
                namespace: OVERLAY_PREF_NAMESPACE,
                name: OVERLAY_PREF_NAME,
                value: dataValue,
                onSuccess: successHandler,
                onFailure: failureHandler
            });
        };

        /**
         * Sets the initial view extent to last extent saved in an OWF user preference
         * for this map.
         * @method setInitialView
         * @memberof module:cmwapi-adapter/View#
         */
        me.setInitialView = function() {
            var successHandler = function(retValue) {
                var viewDetails;
                if (retValue && retValue.value) {
                    viewDetails = OWFWidgetExtensions.Util.parseJson(retValue.value);
                    viewDetails.zoom = viewDetails.range;
                }

                me.handleCenterBounds(null, viewDetails)

                map.on("extent-change", me.saveView);
            };

            var failureHandler = function(e) {
                CommonMapApi.error.send({
                    sender: OWF.getInstanceId(),
                    type: "internal error",
                    msg: "Error in getting preference.",
                    error: "Error: " + e
                });

                me.handleCenterLocation(null, {location: {lon: -76.809469, lat: 39.168101}, zoom: '447946.6823900473'});

                map.on("extent-change", me.saveView);
            };

            OWFWidgetExtensions.Preferences.getWidgetInstancePreference({
                namespace: OVERLAY_PREF_NAMESPACE,
                name: OVERLAY_PREF_NAME,
                onSuccess: successHandler,
                onFailure: failureHandler
            });
        }

    };

    return View;
});


text:
Usage Examples
==============

These examples are meant to provide some basic usage scenarios for what is possible with querybuilder. More advanced
examples will be added in the future.

Selecting records as dictionaries
---------------------------------

The simplest query is to just specify a table name to select from. By default, all fields ('*') will be used
for the field list.
Select all fields from a table:

.. code-block:: python

    from querybuilder.query import Query

    query = Query().from_table('account')
    query.select()
    # [{"id": 1, "name": "Person 1"}, {"id": 2, "name": "Person 2"}]
    query.get_sql()
    # "SELECT account.* FROM account"

If all fields are not needed, it is possible to specify fields by name.
Select specific fields:

.. code-block:: python

    from querybuilder.query import Query

    query = Query().from_table('account', ['name'])
    query.select()
    # [{"name": "Person 1"}, {"name": "Person 2"}]
    query.get_sql()
    # "SELECT account.name FROM account"

It is possible to use a django model class instead of a table name. This is not only more convenient, but it also
lets querybuilder know meta data about your table to do some automatic generation as seen in later examples.
Select from a django model:

.. code-block:: python

    from querybuilder.query import Query
    from querybuilder.tests.models import User

    query = Query().from_table(User)
    query.select()
    # [{"id": 1, "email": "user1@test.com"}, {"id": 2, "email": "user2@test.com"}]
    query.get_sql()
    # "SELECT tests_user.* FROM tests_user"

All of the fields can be explicitly selected by passing the extract_fields flag
Explicitly select all fields:

.. code-block:: python

    from querybuilder.query import Query
    from querybuilder.tests.models import User

    query = Query().from_table(User, extract_fields=True)
    query.select()
    # [{"id": 1, "email": "user1@test.com"}, {"id": 2, "email": "user2@test.com"}]
    query.get_sql()
    # "SELECT tests_user.id, tests_user.email FROM tests_user"

All tables, fields, and nested queries can be aliased so you can reference them by another name.
Alias a table and fields:

.. code-block:: python

    from querybuilder.query import Query

    query = Query().from_table({
        'my_table': User
    }, [{
        'the_id': 'id'
    }, {
        'the_email': 'email'
    }])
    query.select()
    # [{"the_id": 1, "the_email": "user1@test.com"}, {"the_id": 2, "the_email": "user2@test.com"}]
    query.get_sql()
    # "SELECT my_table.id AS the_id, my_table.email AS the_email FROM tests_user AS my_table"

A field object can also be passed in the field list so any other field options can be included. This is especially
useful for custom fields, aggregates, and date part fields.

.. code-block:: python

    query = Query().from_table(User, [
        SimpleField('id', alias='the_id'),
        {'the_email': SimpleField('email')}
    ])
    query.select()
    # [{"the_id": 1, "the_email": "user1@test.com"}, {"the_id": 2, "the_email": "user2@test.com"}]
    query.get_sql()
    # "SELECT my_table.id AS the_id, my_table.email AS the_email FROM tests_user AS my_table"

Selecting from inner queries is just as simple as selecting from a table. The inner query can be aliased and
query builder with set up the nested queries using a WITH clause
Select from Query:

.. code-block:: python

    from querybuilder.query import Query
    from querybuilder.tests.models import User

    inner_query = Query().from_table(User)
    query = Query().from_table({
        'inner_query': inner_query
    })
    query.select()
    # [{"id": 1, "email": "user1@test.com"}, {"id": 2, "email": "user2@test.com"}]
    query.get_sql()
    # WITH inner_query AS (SELECT tests_user.* FROM tests_user) SELECT inner_query.* FROM inner_query

This simple example is meant to demonstrate that query nesting is possible, but the usefulness is really
demonstrated in the more complex examples.

Sorting
-------
Select all fields using a django model and order by id desc:

.. code-block:: python

    from querybuilder.query import Query

    query = Query().from_table(User).order_by('-id')
    query.select()
    # [{"id": 2, "email": "user2@test.com"}, {"id": 1, "email": "user1@test.com"}]
    query.get_sql()
    # "SELECT tests_user.* FROM tests_user ORDER BY id DESC"

Sort direction can also be specified by passing a flag:

.. code-block:: python

    from querybuilder.query import Query

    query = Query().from_table(User).order_by('id', desc=True)
    query.get_sql()
    # "SELECT tests_user.* FROM tests_user ORDER BY id DESC"

Limit and Offset
----------------
Limiting the result set is possible by specifying a limit value and an optional offset value

.. code-block:: python

    from querybuilder.query import Query

    query = Query().from_table(User).limit(1)
    query.select()
    # [{"id": 1, "email": "user1@test.com"}]
    query.get_sql()
    # "SELECT tests_user.* FROM tests_user LIMIT 1"

    query = Query().from_table(User).limit(1, 1)
    query.select()
    # [{"id": 2, "email": "user2@test.com"}]
    query.get_sql()
    # "SELECT tests_user.* FROM tests_user LIMIT 1, 1"

Filtering
---------
Specifying a where clause is similar to django's filtering system.

.. code-block:: python

    query = Query().from_table(User).where(id=1)
    query.select()
    # [{"id": 1, "email": "user1@test.com"}]
    query.get_sql()
    # "SELECT tests_user.* FROM tests_user WHERE (id = %(A0s)"
    query.get_args()
    # {'A0': 1}

The actual query arguments are passed into django's cursor.execute function to be escaped properly.

Multiple where clauses can be chained together, or multiple clauses can be passed to a single where call:

.. code-block:: python

    query = Query().from_table(User).where(id__eq=1, id__lt=5)
    query.get_sql()
    # SELECT tests_user.* FROM tests_user WHERE (id > %(A0)s AND id < %(A1)s)
    query.get_args()
    # {'A1': 5, 'A0': 1}

    query = Query().from_table(User).where(id__eq=1).where(id__lt=5)
    query.get_sql()
    # SELECT tests_user.* FROM tests_user WHERE (id > %(A0)s AND id < %(A1)s)
    query.get_args()
    # {'A1': 5, 'A0': 1}

By default, the conditions are ANDed together, but they can be ORed as well.

.. code-block:: python

    query = Query().from_table(User).where(id__eq=1).where(id__eq=5, where_type='OR')
    query.get_sql()
    # SELECT tests_user.* FROM tests_user WHERE ((id = %(A0)s) OR (id = %(A1)s))
    query.get_args()
    # {'A1': 5, 'A0': 1}

This is actually using django's Q object internally, so any complex Q object can be passed in as an argument

.. code-block:: python

    condition = Q(id=1) | Q(id=5)
    query = Query().from_table(User).where(condition)
    query.get_sql()
    # SELECT tests_user.* FROM tests_user WHERE ((id = %(A0)s) OR (id = %(A1)s))
    query.get_args()
    # {'A1': 5, 'A0': 1}

Other supported comparisons:
eq
gt
gte
lt
lte
contains
startswith

Fields
------
All fields in querybuilder inherit from the base Field class. Some field types like SimpleField only have a name
specified, but more complex fields like aggregates and date parts provide much more functionality. Custom fields
can easily be created by extending one of these field classes as demonstrated later in the examples.

Aggregates
----------
A full list of available fields is available in the Field API documentation. Some more examples are in the
field_tests.py file. Some more examples will be added to demonstrate why these are useful. To become more familiar
with window functions and how these are used, check out the postgres docs
http://www.postgresql.org/docs/9.3/static/functions-window.html

.. code-block:: python

    query = Query().from_table(Order, [SumField('revenue')])
    query.get_sql()
    # SELECT SUM(tests_order.revenue) AS revenue_sum FROM tests_order

    query = Query().from_table(Order, ['*', RowNumberField('revenue', over=QueryWindow().order_by('margin'))])
    query.get_sql()
    # SELECT tests_order.*, ROW_NUMBER() OVER (ORDER BY margin ASC) AS revenue_row_number FROM tests_order

    query = Query().from_table(
        Order,
        ['*', RowNumberField('revenue', over=QueryWindow().order_by('margin').partition_by('account_id'))]
    )
    query.get_sql()
    # SELECT tests_order.*, ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY margin ASC) AS revenue_row_number
    # FROM tests_order

CustomFields
------------
It is possible to create your own custom field and use it in a query by extending a field class.

.. code-block:: python

    class MultiplyField(MultiField):
        def __init__(self, field=None, table=None, alias=None, cast=None, distinct=None, multiply_by=1):
            super(MultiplyField, self).__init__(field, table, alias, cast, distinct)
            self.multiply_by = multiply_by
            self.auto_alias = '{0}_{1}'.format(self.field.name, 'mult')

        def get_select_sql(self):
            return '({0}*{1})'.format(self.get_field_identifier(), self.multiply_by)

    query = Query().from_table(Order, ['revenue', MultiplyField('revenue', multiply_by=2)])
    query.get_sql()
    # SELECT tests_order.revenue, (tests_order.revenue*2) AS revenue_mult FROM tests_order

Date functions
--------------
Several date part functions exist in order to extract date parts (year, month, day, hour, minute, second).

.. code-block:: python

    query = Query().from_table(Order, [Day('time')])
    query.get_sql()
    # SELECT CAST(EXTRACT(day FROM tests_order.time) AS INT) AS time__day FROM tests_order
    query.select()
    # [{'time__day': 19}, {'time__day': 19}, {'time__day': 19}, {'time__day': 19}]

A more useful way to use these functions is to pass the auto=True flag. This is used if you want to group records
by specific date parts. Normally, to group by day, you would have to extract year, month, and day then group by
year, month, and day in addition to any other grouping criteria.

.. code-block:: python

    query = Query().from_table(Order, [SumField('revenue'), Day('time', auto=True)])
    query.get_sql()
    # SELECT SUM(tests_order.revenue) AS revenue_sum,
    # CAST(EXTRACT(year FROM tests_order.time) AS INT) AS time__year,
    # CAST(EXTRACT(month FROM tests_order.time) AS INT) AS time__month,
    # CAST(EXTRACT(day FROM tests_order.time) AS INT) AS time__day,
    # CAST(EXTRACT(epoch FROM date_trunc('day', tests_order.time)) AS INT) AS time__epoch
    # FROM tests_order GROUP BY time__year, time__month, time__day, time__epoch ORDER BY time__epoch ASC
    query.select()
    # [{'time__day': 19, 'time__month': 10, 'revenue_sum': 1800.0, 'time__year': 2012, 'time__epoch': 1350604800}]

Providing additional grouping criteria is simple. Let's say you want to see this data grouped per account:

.. code-block:: python

    query = Query().from_table(Order, ['account_id', SumField('revenue'), Day('time', auto=True)]).group_by('account_id')
    query.get_sql()
    # SELECT tests_order.account_id,
    # SUM(tests_order.revenue) AS revenue_sum,
    # CAST(EXTRACT(year FROM tests_order.time) AS INT) AS time__year,
    # CAST(EXTRACT(month FROM tests_order.time) AS INT) AS time__month,
    # CAST(EXTRACT(day FROM tests_order.time) AS INT) AS time__day,
    # CAST(EXTRACT(epoch FROM date_trunc('day', tests_order.time)) AS INT) AS time__epoch
    # FROM tests_order GROUP BY time__year, time__month, time__day, time__epoch, account_id ORDER BY time__epoch ASC
    query.select()
    # [
    #     {'account_id': 1, 'time__day': 19, 'time__month': 10, 'time__year': 2012, 'time__epoch': 1350604800, 'revenue_sum': 300.0},
    #     {'account_id': 2, 'time__day': 19, 'time__month': 10, 'time__year': 2012, 'time__epoch': 1350604800, 'revenue_sum': 1500.0}
    # ]

Going off of this same example, lets say you wanted to rank the accounts:

.. code-block:: python

    query = Query().from_table(Order, ['account_id', SumField('revenue'), Day('time', auto=True)]).group_by('account_id')
    rank_query = Query().from_table(query, ['account_id', RankField(over=QueryWindow().order_by('-revenue_sum'))])
    rank_query.get_sql()
    # WITH T0 AS (
    # SELECT tests_order.account_id,
    # SUM(tests_order.revenue) AS revenue_sum,
    # CAST(EXTRACT(year FROM tests_order.time) AS INT) AS time__year,
    # CAST(EXTRACT(month FROM tests_order.time) AS INT) AS time__month,
    # CAST(EXTRACT(day FROM tests_order.time) AS INT) AS time__day,
    # CAST(EXTRACT(epoch FROM date_trunc('day', tests_order.time)) AS INT) AS time__epoch
    # FROM tests_order
    # GROUP BY time__year, time__month, time__day, time__epoch, account_id
    # ORDER BY time__epoch ASC)
    # SELECT T0.account_id, RANK() OVER (ORDER BY revenue_sum DESC) AS rank FROM T0
    rank_query.select()
    # [{'account_id': 2, 'rank': 1L}, {'account_id': 1, 'rank': 2L}]

This obviously is not an efficient query for large data sets, but it can be convenient in many cases.

Joins
-----

Json Fields
-----------
Filtering and ordering by json fields is currently in an experimental phase. This only works with versions of
postgres that have a json data type field and versions of jsonfield that use json field types like jsonfield==0.9.20

Queryset example:

.. code-block:: python

    from querybuilder.query import JsonQueryset

    records = JsonQueryset(model=MetricRecord).filter(**{'data->field_name': 'my_value'}).order_by('data->my_sort_field')

Custom field example:

.. code-block:: python

    from querybuilder.fields import JsonField

    my_field = JsonField('data', key='field_name', alias='my_field_alias')
    query = Query().from_table(MetricRecord, fields=[my_field]).where(**{
        my_field.get_where_key(): 'my_value'
    })

Connection Setup
----------------

Arbitrary django connections can be passed into the Query constructor to connect to alternate databases.

.. code-block:: python

    from django.db import connections
    from querybuilder.query import Query

    connections.all()
    #[<django.db.backends.postgresql_psycopg2.base.DatabaseWrapper at 0x1127b4390>,
    # <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper at 0x1127b44d0>]

    Query(connections.all()[0]).from_table('auth_user').count()
    # 15L
    Query(connections.all()[1]).from_table('auth_user').count()
    # 223L

Reference Material
------------------
* http://www.postgresql.org/docs/9.3/static/functions-window.html


text:
require 'spec/runner/formatter/progress_bar_formatter'

module Spec
  module Runner
    module Formatter
      class InstantDisappointmentFormatter < ProgressBarFormatter
        VERSION = "1.1.0"
        SHOW_TOP = (ENV['PROFILE_SHOW_TOP'] || 20).to_i

        def initialize(*args)
          super
          @example_times = []
        end

        def example_started(*args)
          @time = Time.now
        end

        def example_passed(example)
          super
          @example_times << [
            example_group.description,
            example.description,
            Time.now - @time
          ]
        end

        alias :example_failed_without_instant_disappointment :example_failed
        alias :dump_failure_without_lockout :dump_failure

        def example_failed(example, counter, failure)
          example_failed_without_instant_disappointment(example, counter, failure)
          puts
          dump_failure(counter, failure)
          puts
          output.flush
        end

        def dump_failure(counter, failure)
          return if @in_dump
          super
        end

        def start_dump
          dump_group_times
          dump_example_times
          @in_dump = true
        end

        private

        def dump_example_times
          @output.puts "\n\nSingle examples:\n"

          sorted_by_time(@example_times)[0..SHOW_TOP].each do |group, example, time|
            @output.puts "#{red(sprintf("%.7f", time))} #{group} #{example}"
          end
        end

        def dump_group_times
          @output.puts "\n\nGroups:\n"

          group_times = Hash.new(0)
          @example_times.each do |group, example, time|
            group_times[group]+=time
          end

          sorted_by_time(group_times)[0..SHOW_TOP].each do |group,time|
            @output.puts "#{red(sprintf("%.7f", time))} #{group}"
          end
        end

        #sorted by last ascending
        def sorted_by_time(times)
          times.to_a.sort_by{|x| x.last}.reverse
        end
      end
    end
  end
end