text:
import _ = require('./lodashMini');
import assert = require('assert');

import MapShim from './MapShim';
import Options from './Options';
import { SubscriptionCallbackFunction } from './Types';

export interface AutoSubscription {
    store: StoreBase;
    callback: () => void;
    key: string;
    used: boolean;
}

export abstract class StoreBase {
    static Key_All = '%!$all';

    private _subscriptions: _.Dictionary<SubscriptionCallbackFunction[]> = {};
    private _autoSubscriptions: _.Dictionary<AutoSubscription[]> = {};

    private _subTokenNum = 1;
    private _subsByNum: { [token: number]: { key: string, callback: SubscriptionCallbackFunction } } = {};

    storeId = _.uniqueId('store');

    private _gatheredCallbacks = new MapShim<SubscriptionCallbackFunction, string[]|null>();

    private _throttleMs: number;
    private _throttleTimerId: number|undefined;

    private _bypassTriggerBlocks: boolean;
    private _triggerBlocked = false;
    private _isTriggering = false;
    private _triggerPending = false;

    private static _triggerBlockCount = 0;
    private static _triggerBlockedStoreList: StoreBase[] = [];
    private static _pendingThrottledStores: StoreBase[] = [];
    private static _bypassThrottle = false;

    static pushTriggerBlock() {
        this._triggerBlockCount++;
    }

    static popTriggerBlock() {
        this._triggerBlockCount--;
        assert.ok(this._triggerBlockCount >= 0, 'Over-popped trigger blocks!');

        if (this._triggerBlockCount === 0) {
            // Go through the list of stores awaiting resolution and resolve them all
            const awaitingList = this._triggerBlockedStoreList;
            this._triggerBlockedStoreList = [];
            _.forEach(awaitingList, store => {
                store._resolveThrottledCallbacks();
            });
        }
    }

    static setThrottleStatus(enabled: boolean) {
        this._bypassThrottle = !enabled;

        // If we're going to bypass the throttle, trigger all pending stores now
        if (this._bypassThrottle) {
            let pendingThrottledStore = this._pendingThrottledStores.shift();
            while (!!pendingThrottledStore) {
                pendingThrottledStore._resolveThrottledCallbacks();
                pendingThrottledStore = this._pendingThrottledStores.shift();
            }
        }
    }

    constructor(throttleMs: number = 0, bypassTriggerBans = false) {
        this._throttleMs = throttleMs;
        this._bypassTriggerBlocks = bypassTriggerBans;
    }

    // If you trigger a specific set of keys, then it will only trigger that specific set of callbacks (and subscriptions marked
    // as "All" keyed).  If the key is all, it will trigger all callbacks.
    protected trigger(keyOrKeys?: string|number|(string|number)[]) {
        let keys: string[]|undefined;

        // trigger(0) is valid, ensure that we catch this case
        if (keyOrKeys || _.isNumber(keyOrKeys)) {
            keys = _.map(_.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys], key => _.isNumber(key) ? key.toString() : key);
        }

        // Build a list of callbacks to call, trying to accumulate keys into a single callback set to avoid multiple callbacks
        // to the same target with different keys.

        if (!keys) {
            // Inspecific key, so generic callback call
            const allSubs = _.flatten(_.values(this._subscriptions));
            _.forEach(allSubs, callback => {
                // Clear the key list to null for the callback
                this._gatheredCallbacks.set(callback, null);
            });

            _.forEach(_.flatten(_.values(this._autoSubscriptions)),
                sub => {
                    this._gatheredCallbacks.set(sub.callback, null);
                });
        } else {
            // Key list, so go through each key and queue up the callback
            _.forEach(keys, key => {
                _.forEach(this._subscriptions[key], callback => {
                    const existingKeys = this._gatheredCallbacks.get(callback);
                    if (existingKeys === undefined) {
                        this._gatheredCallbacks.set(callback, [key]);
                    } else if (existingKeys === null) {
                        // Do nothing since it's already an all-key-trigger
                    } else {
                        // Add it to the end of the list
                        existingKeys.push(key);
                    }
                });

                _.forEach(this._autoSubscriptions[key], sub => {
                    const existingKeys = this._gatheredCallbacks.get(sub.callback);
                    if (existingKeys === undefined) {
                        this._gatheredCallbacks.set(sub.callback, [key]);
                    } else if (existingKeys === null) {
                        // Do nothing since it's already an all-key-trigger
                    } else {
                        // Add it to the end of the list
                        existingKeys.push(key);
                    }
                });
            });

            // Go through each of the all-key subscriptions and add the full key list to their gathered list
            _.forEach(this._subscriptions[StoreBase.Key_All], callback => {
                const existingKeys = this._gatheredCallbacks.get(callback);
                if (existingKeys === undefined) {
                    this._gatheredCallbacks.set(callback, _.clone(keys!!!));
                } else if (existingKeys === null) {
                    // Do nothing since it's already an all-key-trigger
                } else {
                    // Add them all to the end of the list
                    _.forEach(keys, key => {
                        existingKeys.push(key);
                    });
                }
            });

            _.forEach(this._autoSubscriptions[StoreBase.Key_All], sub => {
                const existingKeys = this._gatheredCallbacks.get(sub.callback);
                if (existingKeys === undefined) {
                    this._gatheredCallbacks.set(sub.callback, _.clone(keys!!!));
                } else if (existingKeys === null) {
                    // Do nothing since it's already an all-key-trigger
                } else {
                    // Add them all to the end of the list
                    _.forEach(keys, key => {
                        existingKeys.push(key);
                    });
                }
            });
        }

        if (this._throttleMs && !StoreBase._bypassThrottle) {
            // Needs to accumulate and trigger later -- start a timer if we don't have one running already
            // If there are no callbacks, don't bother setting up the timer
            if (!this._throttleTimerId && this._gatheredCallbacks.size !== 0) {
                this._throttleTimerId = Options.setTimeout(this._resolveThrottledCallbacks, this._throttleMs);
            }
        } else {
            // No throttle timeout, so just resolve now
            this._resolveThrottledCallbacks();
        }
    }

    private _resolveThrottledCallbacks = () => {
        // Prevent a store from trigginer while it's already in a trigger state
        if (this._isTriggering) {
            this._triggerPending = true;
            return;
        }

        // Clear a timer if one's still pending
        if (this._throttleTimerId) {
            Options.clearTimeout(this._throttleTimerId);
            this._throttleTimerId = undefined;
            _.remove(StoreBase._pendingThrottledStores, this);
        }

        if (StoreBase._triggerBlockCount > 0 && !this._bypassTriggerBlocks) {
            // Trigger-blocked without a bypass flag.  Please wait until later.
            if (!this._triggerBlocked) {
                // Save this store to the global list that will be resolved when the block count is popped back to zero.
                StoreBase._triggerBlockedStoreList.push(this);
                this._triggerBlocked = true;
            }
            return;
        }

        this._triggerBlocked = false;
        this._isTriggering = true;
        this._triggerPending = false;

        // Store the callbacks early, since calling callbacks may actually cause cascade changes to the subscription system and/or
        // pending callbacks.
        const storedCallbacks = this._gatheredCallbacks;
        this._gatheredCallbacks = new MapShim<SubscriptionCallbackFunction, string[]>();

        storedCallbacks.forEach((keys, callback) => {
            // Do a quick dedupe on keys
            const uniquedKeys = keys ? _.uniq(keys) : keys;
            // Convert null key (meaning "all") to undefined for the callback.
            callback(uniquedKeys || undefined);
        });
        this._isTriggering = false;

        if (this._triggerPending) {
            this._resolveThrottledCallbacks();
        }
    }

    // Subscribe to triggered events from this store.  You can leave the default key, in which case you will be
    // notified of any triggered events, or you can use a key to filter it down to specific event keys you want.
    // Returns a token you can pass back to unsubscribe.
    subscribe(callback: SubscriptionCallbackFunction, rawKey: string|number = StoreBase.Key_All): number {
        const key = _.isNumber(rawKey) ? rawKey.toString() : rawKey;

        // Adding extra type-checks since the key is often the result of following a string path, which is not type-safe.
        assert.ok(key && _.isString(key), 'Trying to subscribe to invalid key: "' + key + '"');

        let callbacks = this._subscriptions[key];
        if (!callbacks) {
            this._subscriptions[key] = [callback];

            if (key !== StoreBase.Key_All && !this._autoSubscriptions[key]) {
                this._startedTrackingKey(key);
            }
        } else {
            callbacks.push(callback);
        }

        let token = this._subTokenNum++;
        this._subsByNum[token] = { key: key, callback: callback };
        return token;
    }

    // Unsubscribe from a previous subscription.  Pass in the token the subscribe function handed you.
    unsubscribe(subToken: number) {
        assert.ok(this._subsByNum[subToken], 'No subscriptions found for token ' + subToken);

        let key = this._subsByNum[subToken].key;
        let callback = this._subsByNum[subToken].callback;
        delete this._subsByNum[subToken];

        // Remove this callback set from our tracking lists
        this._gatheredCallbacks.delete(callback);

        let callbacks = this._subscriptions[key];
        assert.ok(callbacks, 'No subscriptions under key ' + key);

        const index = _.indexOf(callbacks, callback);
        if (index !== -1) {
            callbacks.splice(index, 1);
            if (callbacks.length === 0) {
                // No more callbacks for key, so clear it out
                delete this._subscriptions[key];

                if (key !== StoreBase.Key_All && !this._autoSubscriptions[key]) {
                    this._stoppedTrackingKey(key);
                }
            }
        } else {
            assert.ok(false, 'Subscription not found during unsubscribe...');
        }
    }

    trackAutoSubscription(subscription: AutoSubscription) {
        const key = subscription.key;
        const callbacks = this._autoSubscriptions[key];
        if (!callbacks) {
            this._autoSubscriptions[key] = [subscription];

            if (key !== StoreBase.Key_All && !this._subscriptions[key]) {
                this._startedTrackingKey(key);
            }
        } else {
            callbacks.push(subscription);
        }
    }

    removeAutoSubscription(subscription: AutoSubscription) {
        const key = subscription.key;

        let subs = this._autoSubscriptions[key];
        assert.ok(subs, 'No subscriptions under key ' + key);

        const oldLength = subs.length;
        _.pull(subs, subscription);
        assert.equal(subs.length, oldLength - 1, 'Subscription not found during unsubscribe...');

        this._gatheredCallbacks.delete(subscription.callback);

        if (subs.length === 0) {
            // No more callbacks for key, so clear it out
            delete this._autoSubscriptions[key];

            if (key !== StoreBase.Key_All && !this._subscriptions[key]) {
                this._stoppedTrackingKey(key);
            }
        }
    }

    protected _startedTrackingKey(key: string): void {
        // Virtual function, noop default behavior
    }

    protected _stoppedTrackingKey(key: string): void {
        // Virtual function, noop default behavior
    }

    protected _getSubscriptionKeys() {
        return _.union(_.keys(this._subscriptions), _.keys(this._autoSubscriptions));
    }

    protected _isTrackingKey(key: string) {
        return !!this._subscriptions[key] || !!this._autoSubscriptions[key];
    }
}


text:
/*global describe, beforeEach, module, it, expect, runTest */
describe('uiScroll', function () {
	'use strict';

	beforeEach(module('ui.scroll'));
    beforeEach(module('ui.scroll.test.datasources'));

	describe('applyUpdates tests\n', function () {
		var scrollSettings = {datasource: 'myOnePageDatasource', adapter: 'adapter'};

		it('should create adapter object', function () {
			runTest(scrollSettings,
				function (viewport, scope) {
					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should update rows in place', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							return [item + ' *' + scope.$index];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);
					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one *1');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two *2');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three *3');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one *1');
				}
			);
		});

		it('should update selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							if (item === 'one')
								return [item + ' *' + scope.$index];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one *1');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one *1');
				}
			);
		});

		it('should update selected (middle) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							if (item === 'two')
								return [item + ' *' + scope.$index];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two *2');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should update selected (last) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							if (item === 'three')
								return [item + ' *' + scope.$index];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three *3');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should delete selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'one')
								return [];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(4);

					var row2 = viewport.children()[1];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('1: two');

					var row3 = viewport.children()[2];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('2: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: two');
				}
			);
		});

		it('should delete selected (middle) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'two')
								return [];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(4);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should delete selected (last) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'three')
								return [];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(4);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should insert a new element before selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'one')
								return ['before one', item];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: before one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: one');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: two');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: before one');
				}
			);
		});

		it('should insert a new element after selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'one')
								return [item, 'after one'];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: after one');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: two');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should insert a new element before selected (middle) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'two')
								return ['before two', item];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: before two');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: two');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should insert a new element after selected (last) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item) {
							if (item === 'three')
								return [item, 'after three'];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: two');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: three');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: after three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});
	});

	describe('applyUpdates tests (index based)\n', function () {
		var scrollSettings = {datasource: 'myOnePageDatasource', adapter: 'adapter'};

		it('should update selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(1, ['one *1']);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one *1');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one *1');
				}
			);
		});

		it('should ignore out of bound indexes', function () {
			runTest(scrollSettings,
				function (viewport, scope) {

					scope.adapter.applyUpdates(0, ['invalid']);

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should ignore out of bound indexes 2', function () {
			runTest(scrollSettings,
				function (viewport, scope) {

					scope.adapter.applyUpdates(4, ['invalid']);

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should update selected (middle) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(2, ['two *2']);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two *2');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should update selected (last) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(3, ['three *3']);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three *3');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should delete selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(1, []);

					$timeout.flush();

					expect(viewport.children().length).toBe(4);

					var row2 = viewport.children()[1];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('1: two');

					var row3 = viewport.children()[2];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('2: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: two');
				}
			);
		});

		it('should delete selected (middle) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(2, []);

					$timeout.flush();

					expect(viewport.children().length).toBe(4);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should delete selected (last) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(3, []);

					$timeout.flush();

					expect(viewport.children().length).toBe(4);

					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should insert a new element before selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(1, ['before one', 'one']);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: before one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: one');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: two');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: before one');
				}
			);
		});

		it('should insert a new element after selected (first) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(1, ['one', 'after one']);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: after one');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: two');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should insert a new element before selected (middle) row', function () {

			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(2, ['before two', 'two']);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: before two');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: two');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});

		it('should insert a new element after selected (last) row', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(3, ['three', 'after three']);

					$timeout.flush();

					expect(viewport.children().length).toBe(6);

					var row0 = viewport.children()[1];
					expect(row0.tagName.toLowerCase()).toBe('div');
					expect(row0.innerHTML).toBe('1: one');

					var row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: two');

					var row2 = viewport.children()[3];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('3: three');

					var row3 = viewport.children()[4];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('4: after three');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
				}
			);
		});
	});

	describe('applyUpdates tests with object items\n', function () {
		var scrollSettings = {
			datasource: 'myObjectDatasource',
			adapter: 'adapter',
			template: '{{$index}}: {{item.text}}'
		};

		it('should update existing item inplace', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							item.text += ' *' + scope.$index;
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);
					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one *1');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two *2');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three *3');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one *1');
				}
			);
		});

		it('should replace existing item with an updated one', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							return [
								{
									text: item.text + ' *' + scope.$index
								}
							];
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(5);
					var row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one *1');

					var row2 = viewport.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two *2');

					var row3 = viewport.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three *3');

					expect(scope.adapter).toBeTruthy();
					expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one *1');
				}
			);
		});

		it('should preserve the order of inserted items', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							if (scope.$index == 1) {
								item.text += ' *' + scope.$index;
								return [
									{text: item.text + ' before 1'},
									{text: item.text + ' before 2'},
									item,
									{text: item.text + ' after 1'},
									{text: item.text + ' after 2'}
								];
							}
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(9);
					var row1, row2, row3;

					row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one *1 before 1');

					row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: one *1 before 2');

					row1 = viewport.children()[3];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('3: one *1');

					row1 = viewport.children()[4];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('4: one *1 after 1');

					row1 = viewport.children()[5];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('5: one *1 after 2');

					row2 = viewport.children()[6];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('6: two');

					row3 = viewport.children()[7];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('7: three');

					expect(scope.adapter).toBeTruthy();
				}
			);
		});

		it('should preserve the order of inserted items 2', function () {
			runTest(scrollSettings,
				function (viewport, scope, $timeout) {

					scope.adapter.applyUpdates(
						function (item, scope) {
							if (scope.$index == 2) {
								item.text += ' *' + scope.$index;
								return [
									{text: item.text + ' before 1'},
									{text: item.text + ' before 2'},
									item,
									{text: item.text + ' after 1'},
									{text: item.text + ' after 2'}
								];
							}
						}
					);

					$timeout.flush();

					expect(viewport.children().length).toBe(9);
					var row1, row2, row3;

					row1 = viewport.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					row1 = viewport.children()[2];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('2: two *2 before 1');

					row1 = viewport.children()[3];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('3: two *2 before 2');

					row2 = viewport.children()[4];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('4: two *2');

					row1 = viewport.children()[5];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('5: two *2 after 1');

					row1 = viewport.children()[6];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('6: two *2 after 2');

					row3 = viewport.children()[7];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('7: three');

					expect(scope.adapter).toBeTruthy();
				}
			);
		});
	});

    describe('append tests\n', function () {
        var scrollSettings = {datasource: 'myOnePageDatasource', adapter: 'adapter'};

        it('should append two rows to the dataset', function () {
            runTest(scrollSettings,
                function (viewport, scope, $timeout) {

                    scope.adapter.append(['appended one', 'appended two']);

                    $timeout.flush();

                    expect(viewport.children().length).toBe(7);

                    var row1 = viewport.children()[1];
                    expect(row1.tagName.toLowerCase()).toBe('div');
                    expect(row1.innerHTML).toBe('1: one');

                    var row2 = viewport.children()[2];
                    expect(row2.tagName.toLowerCase()).toBe('div');
                    expect(row2.innerHTML).toBe('2: two');

                    var row3 = viewport.children()[3];
                    expect(row3.tagName.toLowerCase()).toBe('div');
                    expect(row3.innerHTML).toBe('3: three');

                    var row4 = viewport.children()[4];
                    expect(row4.tagName.toLowerCase()).toBe('div');
                    expect(row4.innerHTML).toBe('4: appended one');

                    var row5 = viewport.children()[5];
                    expect(row5.tagName.toLowerCase()).toBe('div');
                    expect(row5.innerHTML).toBe('5: appended two');

                    expect(scope.adapter).toBeTruthy();
                    expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: one');
                }
            );
        });

        var emptyScrollSettings = {datasource: 'myEmptyDatasource', adapter: 'adapter'};

        it('should append two rows to the empty dataset', function () {
            runTest(emptyScrollSettings,
                function (viewport, scope, $timeout) {

                    scope.adapter.append(['appended one', 'appended two']);

                    $timeout.flush();

                    expect(viewport.children().length).toBe(4);

                    var row4 = viewport.children()[1];
                    expect(row4.tagName.toLowerCase()).toBe('div');
                    expect(row4.innerHTML).toBe('1: appended one');

                    var row5 = viewport.children()[2];
                    expect(row5.tagName.toLowerCase()).toBe('div');
                    expect(row5.innerHTML).toBe('2: appended two');

                    expect(scope.adapter).toBeTruthy();
                    expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('1: appended one');
                }
            );
        });

    });

    describe('prepend tests\n', function () {
        var scrollSettings = {datasource: 'myOnePageDatasource', adapter: 'adapter'};

        it('should prepend two rows to the dataset', function () {
            runTest(scrollSettings,
                function (viewport, scope, $timeout) {

                    scope.adapter.prepend(['prepended one', 'prepended two']);

                    $timeout.flush();

                    expect(viewport.children().length).toBe(7);

                    var row4 = viewport.children()[1];
                    expect(row4.tagName.toLowerCase()).toBe('div');
                    expect(row4.innerHTML).toBe('-1: prepended one');

                    var row5 = viewport.children()[2];
                    expect(row5.tagName.toLowerCase()).toBe('div');
                    expect(row5.innerHTML).toBe('0: prepended two');

                    var row1 = viewport.children()[3];
                    expect(row1.tagName.toLowerCase()).toBe('div');
                    expect(row1.innerHTML).toBe('1: one');

                    var row2 = viewport.children()[4];
                    expect(row2.tagName.toLowerCase()).toBe('div');
                    expect(row2.innerHTML).toBe('2: two');

                    var row3 = viewport.children()[5];
                    expect(row3.tagName.toLowerCase()).toBe('div');
                    expect(row3.innerHTML).toBe('3: three');

                    expect(scope.adapter).toBeTruthy();
                    expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('-1: prepended one');
                }
            );
        });

        var emptyScrollSettings = {datasource: 'myEmptyDatasource', adapter: 'adapter'};

        it('should prepend two rows to the empty dataset', function () {
            runTest(emptyScrollSettings,
                function (viewport, scope, $timeout) {

                    scope.adapter.prepend(['prepended one', 'prepended two']);

                    $timeout.flush();

                    expect(viewport.children().length).toBe(4);

                    var row4 = viewport.children()[1];
                    expect(row4.tagName.toLowerCase()).toBe('div');
                    expect(row4.innerHTML).toBe('-1: prepended one');

                    var row5 = viewport.children()[2];
                    expect(row5.tagName.toLowerCase()).toBe('div');
                    expect(row5.innerHTML).toBe('0: prepended two');

                    expect(scope.adapter).toBeTruthy();
                    expect(scope.adapter.topVisibleElement[0].innerHTML).toBe('-1: prepended one');
                }
            );
        });

    });

    describe('adapter reload tests', function () {
        var scrollSettings = {datasource: 'myInfiniteDatasource', adapter: 'adapter'};

        it ('initial load should be positioned at item#1', function () {
            runTest (scrollSettings,
                function (viewport, scope) {
                    expect(scope.adapter.topVisible).toBe('item1');
                }
            );
        });

        it ('reload(100) should position it at item#100', function () {
            runTest (scrollSettings,
                function (viewport, scope, $timeout) {
                    expect(scope.adapter.topVisible).toBe('item1');

                    scope.adapter.reload(100);
                    $timeout.flush();

                    expect(scope.adapter.topVisible).toBe('item100');
                }
            );
        });

        it ('reload() should position it at item#1', function () {
            runTest (scrollSettings,
                function (viewport, scope, $timeout) {
                    expect(scope.adapter.topVisible).toBe('item1');

                    scope.adapter.reload(100);
                    $timeout.flush();

                    expect(scope.adapter.topVisible).toBe('item100');

                    scope.adapter.reload();
                    $timeout.flush();

                    expect(scope.adapter.topVisible).toBe('item100');
                }
            );
        });

        it ('reload(0) should position it at item#0', function () {
            runTest (scrollSettings,
                function (viewport, scope, $timeout) {
                    expect(scope.adapter.topVisible).toBe('item1');

                    scope.adapter.reload(100);
                    $timeout.flush();

                    expect(scope.adapter.topVisible).toBe('item100');

                    scope.adapter.reload(0);
                    $timeout.flush();

                    expect(scope.adapter.topVisible).toBe('item0');
                }
            );
        });

    });

});

redpajama_set_name: RedPajamaGithub


text:
package net.kebernet.configuration.server.system;

/**
 *
 */
public interface SystemInspector {

    boolean isWifiActive();
    boolean isAdHocMode();
    boolean isDesiredNetworkVisible();
}


text:
var QueryString = parseurl();
    var chancesl = [];
    var survive = predict(QueryString.age, QueryString.gender, QueryString.class);
    var result;

    if (survive) {
        result = "You Lived"
    } else {
        result = "You died"
    }

    document.getElementById("logo__lusitania").innerHTML = result + ', with a ' + chancesl + '% survival rate on the Lusitania.';
    document.getElementById("logo__lusitania").setAttribute("result", chancesl.toString());

/* Function that gets the arguments from the URL */
function parseurl () {
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  }
    return query_string;
};

/* Function that does the actual prediction of life or death. */
function predict (age, gender,  ticket_class) {
    /* If you're younger then 32 */
    if (age <= 32.1447) {
        /* If you're younger then 6 1/2 years old */
        if (age <= 6.5000) {
            /* If you're younger then 2 1/2 years old, You have a 22% chance to live. [35 died , 10 lived] */
            if (age <= 2.5000) { if (Math.floor((Math.random() * 45) + 1) <= 35) { chancesl.push(22); return false; } else { chancesl.push(22); return true; } }
            /* If you're between 6 1/2 years old and 2 1/2 years old you have a 30% chance to live [21 died, 9 lived] */
            else { if (Math.floor((Math.random() * 30) + 1) <= 21) { chancesl.push(30); return false; } else { chancesl.push(30); return true; } }
        }
        /* If you're between 32 and 6 1/2 years old */
        else {
            /* If you're between 30 and 6 1/2 years old you have a 45% chance to live [207 died, 107 lived] */
            if (age <= 30.5000) { if (Math.floor((Math.random() * 379) + 1) <= 207) { chancesl.push(45); return false; } else { chancesl.push(45); return true; } }
            /* If you're between 32 and 30 years old you have a 38% chance to live [27 died, 44 lived] */
            else { if (Math.floor((Math.random() * 71) + 1) <= 27) { chancesl.push(62); return false; } else { chancesl.push(62); return true; } }
        }
    }
    /* If you're older then 32 */
    else {
        /* If you're between 32 and 56 years old */
        if (age <= 56.5000) {
            /* If you're middle class or upper class then you have a 60% chance to live [404 died , 262 lived] */
            if (ticket_class >= 2) { if (Math.floor((Math.random() * 664) + 1) <= 404) { chancesl.push(40); return false; } else { chancesl.push(40); return true; } }
            /* If you're lower class then you have a 69% chance to live [154 died , 69 lived] */
            else { if(Math.floor((Math.random() * 223) + 1) <= 154) { chancesl.push(31); return false; } else { chancesl.push(31); return true; } }
        }
        /* If you're older then 56 years old */
        else {
            /*If you're lower class then you have a 76% chance to live [35 died , 11 lived]*/
            if (ticket_class >= 3) { if (Math.floor((Math.random() * 46) + 1) <= 35) { chancesl.push(76); return false; } else { chancesl.push(76); return true; } }
            /*If you're middler or upper class then you have a 10% chance to live [9 died , 1 lived] */
            else { if (Math.floor((Math.random() * 10) + 1) <= 9){ chancesl.push(10); return false; } else { chancesl.push(10); return true; } }
        }
    }
}


text:
using base::FilePath;

#if defined(OS_MACOSX)
#include "components/breakpad/app/breakpad_mac.h"
#include "content/nw/src/paths_mac.h"
#endif  // OS_MACOSX

#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#include "components/breakpad/app/breakpad_win.h"
#endif

#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include "components/breakpad/app/breakpad_linux.h"
#endif

#include "ipc/ipc_message.h"  // For IPC_MESSAGE_LOG_ENABLED.

#if defined(IPC_MESSAGE_LOG_ENABLED)
#define IPC_MESSAGE_MACROS_LOG_ENABLED
#include "content/public/common/content_ipc_logging.h"
#define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \
    content::RegisterIPCLogger(msg_id, logger)
#include "content/nw/src/common/common_message_generator.h"
#include "components/autofill/content/common/autofill_messages.h"
#endif

namespace {

#if defined(OS_WIN)
// If "Content Shell" doesn't show up in your list of trace providers in
// Sawbuck, add these registry entries to your machine (NOTE the optional
// Wow6432Node key for x64 machines):
// 1. Find:  HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers
// 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}"
// 3. Add these values:
//    "default_flags"=dword:00000001
//    "default_level"=dword:00000004
//    @="Content Shell"

// {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}
const GUID kContentShellProviderName = {
    0x6a3e50a4, 0x7e15, 0x4099,
        { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } };
#endif

base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky
    g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER;

void InitLogging() {
  base::FilePath log_filename;
  PathService::Get(base::DIR_EXE, &log_filename);
  log_filename = log_filename.AppendASCII("debug.log");
  logging::LoggingSettings settings;
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableLogging)) {
    settings.logging_dest = logging::LOG_TO_ALL;
    settings.log_file = log_filename.value().c_str();
    settings.delete_old = logging::DELETE_OLD_LOG_FILE;
  }else{
#if defined(OS_WIN)
    settings.logging_dest = logging::LOG_NONE;
#endif
  }
  logging::InitLogging(settings);
  logging::SetLogItems(true, false, true, false);
}

}  // namespace

namespace content {

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  const CommandLine::StringVector& args = command_line->GetArgs();
  if (args.size() > 0) {
    zip::ZipReader reader;
    FilePath fp(args[0]);
    if (!command_line->HasSwitch(switches::kProcessType) &&
        PathExists(fp) && !DirectoryExists(fp) && !reader.Open(fp)) {
      *exit_code = node::Start(command_line->argc0(), command_line->argv0());
      return true;
    }
  }

#if defined(OS_WIN)
  // Enable trace control and transport through event tracing for Windows.
  logging::LogEventProvider::Initialize(kContentShellProviderName);
#endif

#if defined(OS_MACOSX)
  // Needs to happen before InitializeResourceBundle() and before
  // WebKitTestPlatformInitialize() are called.
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
  // FIXME: EnsureCorrectResolutionSettings();
  l10n_util::OverrideLocaleWithUserDefault();
#endif  // OS_MACOSX

  InitLogging();
  // FIXME: net::CookieMonster::EnableFileScheme();

  SetContentClient(&content_client_);
  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
  breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer());
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  std::string pref_locale;
  if (command_line->HasSwitch(switches::kLang)) {
    pref_locale = command_line->GetSwitchValueASCII(switches::kLang);
  }

  InitializeResourceBundle(pref_locale);

  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);

  if (process_type != switches::kZygoteProcess)
    breakpad::InitCrashReporter(process_type);

  // Just prevent sandbox.
  command_line->AppendSwitch(switches::kNoSandbox);

  // Make sure we keep using only one render process for one app, by using the
  // process-per-tab mode, we can make Chrome only create new site instance
  // when we require to, the default mode is creating different site instances
  // for different domains.
  // This is needed because we want our Window API to have full control of new
  // windows created, which require all windows to be in one render process
  // host.
  command_line->AppendSwitch(switches::kProcessPerTab);

  // Allow file:// URIs can read other file:// URIs by default.
  command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const MainFunctionParams& main_function_params) {
  if (!process_type.empty())
    return -1;

  return ShellBrowserMain(main_function_params);
}

void ShellMainDelegate::InitializeResourceBundle(const std::string& pref_locale) {
  FilePath pak_file;
#if defined(OS_MACOSX)
  FilePath locale_file;
  if (!GetResourcesPakFilePath(pak_file))
    LOG(FATAL) << "nw.pak file not found.";
  std::string locale = l10n_util::GetApplicationLocale(pref_locale);
  if (!GetLocalePakFilePath(locale, locale_file)) {
    LOG(WARNING) << locale << ".pak file not found.";
    locale = "en-US";
    if (!GetLocalePakFilePath(locale, locale_file))
      LOG(ERROR) << locale << ".pak file not found.";
  }
  ui::ResourceBundle::InitSharedInstanceWithPakPath2(pak_file, locale_file);
#else
  FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak"));
  CHECK(base::PathExists(pak_file)) << "nw.pak is missing";
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
#endif
}

ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new ShellContentBrowserClient);
  return browser_client_.get();
}

ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new ShellContentRendererClient);
  return renderer_client_.get();
}

#if defined(OS_POSIX) && !defined(OS_MACOSX)
void ShellMainDelegate::ZygoteForked() {
  // Needs to be called after we have chrome::DIR_USER_DATA.  BrowserMain sets
  // this up for the browser process in a different manner.
  const CommandLine* command_line = CommandLine::ForCurrentProcess();
  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);
  breakpad::InitCrashReporter(process_type);
}
#endif

}  // namespace content


text:
local commandname="UPDATE"
local commandaction="Update"
local function_selfname="$(basename $(readlink -f "${BASH_SOURCE[0]}"))"

fn_update_mumble_dl(){
	fn_fetch_file "https://github.com/mumble-voip/mumble/releases/download/${availablebuild}/murmur-static_${mumblearch}-${availablebuild}.tar.bz2" "${tmpdir}" "murmur-static_${mumblearch}-${availablebuild}.tar.bz2"
	fn_dl_extract "${tmpdir}" "murmur-static_${mumblearch}-${availablebuild}.tar.bz2" "${tmpdir}"
	echo -e "copying to ${filesdir}...\c"
	fn_script_log "Copying to ${filesdir}"
	cp -R "${tmpdir}/murmur-static_${mumblearch}-${availablebuild}/"* "${filesdir}"
	local exitcode=$?
	if [ ${exitcode} -eq 0 ]; then
		fn_print_ok_eol_nl
	else
		fn_print_fail_eol_nl
	fi
}

fn_update_mumble_currentbuild(){
	# Gets current build info
	# Checks if current build info is available. If it fails, then a server restart will be forced to generate logs.
	if [ ! -f "${consolelogdir}/${servicename}-console.log" ]; then
		fn_print_error "Checking for update: GitHub"
		sleep 1
		fn_print_error_nl "Checking for update: GitHub: No logs with server version found"
		fn_script_log_error "Checking for update: GitHub: No logs with server version found"
		sleep 1
		fn_print_info_nl "Checking for update: GitHub: Forcing server restart"
		fn_script_log_info "Checking for update: GitHub: Forcing server restart"
		sleep 1
		exitbypass=1
		command_stop.sh
		exitbypass=1
		command_start.sh
		sleep 1
		# Check again and exit on failure.
		if [ ! -f "${consolelogdir}/${servicename}-console.log" ]; then
			fn_print_fail_nl "Checking for update: GitHub: Still No logs with server version found"
			fn_script_log_fatal "Checking for update: GitHub: Still No logs with server version found"
			core_exit.sh
		fi
	fi

	# Get current build from logs
	currentbuild=$(cat "${consolelogdir}"/"${servicename}"-console.log 2> /dev/null | sort | egrep 'Murmur ((\.)?[0-9]{1,3}){1,3}\.[0-9]{1,3}' | awk '{print $4}')
	if [ -z "${currentbuild}" ]; then
		fn_print_error_nl "Checking for update: GitHub: Current build version not found"
		fn_script_log_error "Checking for update: GitHub: Current build version not found"
		sleep 1
		fn_print_info_nl "Checking for update: GitHub: Forcing server restart"
		fn_script_log_info "Checking for update: GitHub: Forcing server restart"
		exitbypass=1
		command_stop.sh
		exitbypass=1
		command_start.sh
		currentbuild=$(cat "${consolelogdir}"/"${servicename}"-console.log 2> /dev/null | sort | egrep 'Murmur ((\.)?[0-9]{1,3}){1,3}\.[0-9]{1,3}' | awk '{print $4}')
		if [ -z "${currentbuild}" ]; then
			fn_print_fail_nl "Checking for update: GitHub: Current build version still not found"
			fn_script_log_fatal "Checking for update: GitHub: Current build version still not found"
			core_exit.sh
		fi
	fi
}

fn_update_mumble_arch(){
	# Mumble is x86 only for now
	mumblearch="x86"
}

fn_update_mumble_availablebuild(){
	# Gets latest build info.
	availablebuild=$(curl -s https://api.github.com/repos/mumble-voip/mumble/releases/latest | grep 'murmur-static_x86.*\.bz2"' | tail -1 | awk -F"/" '{ print $8 }')
	sleep 1

	# Checks if availablebuild variable has been set
	if [ -z "${availablebuild}" ]; then
		fn_print_fail "Checking for update: GitHub"
		sleep 1
		fn_print_fail "Checking for update: GitHub: Not returning version info"
		fn_script_log_fatal "Failure! Checking for update: GitHub: Not returning version info"
		core_exit.sh
	else
		fn_print_ok "Checking for update: GitHub"
		fn_script_log_pass "Checking for update: GitHub"
		sleep 1
	fi
}

fn_update_mumble_compare(){
	# Removes dots so if can compare version numbers
	currentbuilddigit=$(echo "${currentbuild}"|tr -cd '[:digit:]')
	availablebuilddigit=$(echo "${availablebuild}"|tr -cd '[:digit:]')

	if [ "${currentbuilddigit}" -ne "${availablebuilddigit}" ]; then
		echo -e "\n"
		echo -e "Update available:"
		sleep 1
		echo -e "	Current build: ${red}${currentbuild} ${mumblearch}${default}"
		echo -e "	Available build: ${green}${availablebuild} ${mumblearch}${default}"
		echo -e ""
		sleep 1
		echo ""
		echo -en "Applying update.\r"
		sleep 1
		echo -en "Applying update..\r"
		sleep 1
		echo -en "Applying update...\r"
		sleep 1
		echo -en "\n"
		fn_script_log "Update available"
		fn_script_log "Current build: ${currentbuild}"
		fn_script_log "Available build: ${availablebuild}"
		fn_script_log "${currentbuild} > ${availablebuild}"

		unset updateonstart

		check_status.sh
		if [ "${status}" == "0" ]; then
			fn_update_mumble_dl
			exitbypass=1
			command_start.sh
			exitbypass=1
			command_stop.sh
		else
			exitbypass=1
			command_stop.sh
			fn_update_mumble_dl
			exitbypass=1
			command_start.sh
		fi
		alert="update"
		alert.sh
	else
		echo -e "\n"
		echo -e "No update available:"
		echo -e "	Current version: ${green}${currentbuild}${default}"
		echo -e "	Available version: ${green}${availablebuild}${default}"
		echo -e ""
		fn_print_ok_nl "No update available"
		fn_script_log_info "Current build: ${currentbuild}"
		fn_script_log_info "Available build: ${availablebuild}"
	fi
}

fn_update_mumble_arch
if [ "${installer}" == "1" ]; then
	fn_update_mumble_availablebuild
	fn_update_mumble_dl
else
	# Checks for server update from github.com
	fn_print_dots "Checking for update: github.com"
	fn_script_log_info "Checking for update: github.com"
	sleep 1
	fn_update_mumble_currentbuild
	fn_update_mumble_availablebuild
	fn_update_mumble_compare
fi


text:
const fs = require('fs')
const { join } = require('path')

const appPaths = require('../app-paths')

const cssVariables = {
  quasarSrcExt: 'css',

  appFile: {
    scss: fs.existsSync(appPaths.resolve.src('css/quasar.variables.scss')),
    sass: fs.existsSync(appPaths.resolve.src('css/quasar.variables.sass'))
  },

  loaders: {
    scss: join(__dirname, '../webpack/loader.quasar-scss-variables'),
    sass: join(__dirname, '../webpack/loader.quasar-sass-variables')
  }
}

for (const ext of Object.keys(cssVariables.appFile)) {
  if (cssVariables.appFile[ext]) {
    cssVariables.quasarSrcExt = ext === 'scss' ? 'sass' : ext
    break
  }
}

module.exports = cssVariables


text:
class DonationsController < ApplicationController
  def new
    pluggable_js(
      stripe_publishable_key: Figaro.env.STRIPE_PUBLISHABLE_KEY,
      logo_url: view_context.asset_url('logo.png')
    )
  end

  def create
    @amount = 0

    if params[:amount] == 'custom'
      # The user gives us a floating point number for the amount. Here we
      # convert it to pennies.
      @amount = (params[:custom_amount].to_f * 100).to_i
    else
      @amount = params[:amount].to_i
    end

    # Convert whether the payment is recurring to a boolean
    recurring = (params[:recurring] == 'true')

    # Get the Stripe customer object so we can charge the user.
    #
    # We use the Donor model to keep track of all of our existing donors. If the
    # person has previously donated, then we use their existing customer object
    # in Stripe. If they're a first time donor, then we create a new customer
    # object in Stripe and create a new Donor object with their Stripe info.
    donor = Donor.find_by(email: params[:stripe_email])
    customer = nil
    if donor == nil # Create a new donor object & customer
      customer = Stripe::Customer.create(
        email: params[:stripe_email],
        source: params[:stripe_token]
      )

      Donor.create!(email: customer.email, stripe_id: customer.id)
    else # Retrieve existing customer
      customer = Stripe::Customer.retrieve(donor.stripe_id)
    end

    if recurring
      plan = plan_for(@amount)
      customer.subscriptions.create(plan: plan.id)
    else
      charge = Stripe::Charge.create(
        customer: customer.id,
        amount: @amount,
        description: 'Hack Club donation',
        currency: 'usd'
      )
    end

    pluggable_js(
      donation_successful: true,
      stripe_publishable_key: Figaro.env.STRIPE_PUBLISHABLE_KEY,
      logo_url: view_context.asset_url('logo.png')
    )

    render :new

  rescue Stripe::CardError => e
    flash[:alert] = e.message
    redirect_to donate_path
  end

  private

  # Monthly plans are named `donation_m_<amount>`. Examples: `donation_m_2500`,
  # `donation_m_500`, and `donation_m_1500` for the $25/m, $5/m, and $15/m
  # plans, respectively.
  #
  # If there isn't already a plan for the given amount, we create it.
  def plan_for(amount)
    plan_id = "donation_m_#{amount}"
    plan_name = "#{format_amount amount} Monthly Contribution"

    begin
      Stripe::Plan.retrieve(plan_id)
    rescue Stripe::InvalidRequestError => e
      # Raise the exception again if the error is anything but a 404. If it's a
      # 404, then we should go ahead and create a new plan.
      unless e.http_status == 404
        raise e
      end

      Stripe::Plan.create(
        amount: amount,
        interval: 'month',
        name: plan_name,
        currency: 'usd',
        id: plan_id,
      )
    end
  end

  # Formats amount for display. Example: converts 1523 to $15.23.
  def format_amount(amount)
    ActionController::Base.helpers.number_to_currency(amount.to_f / 100)
  end
end


text:
project "Engine"
   targetname "Engine"
   language "C++"
   kind "WindowedApp"
   targetdir "../../"

   includedirs {
      "../../engine/source",
      "../../engine/lib/ljpeg",
      "../../engine/lib/lpng",
      "../../engine/lib/zlib",
   }

   files {
      "../../engine/source/algorithm/**",
      "../../engine/source/audio/**",
      "../../engine/source/collection/**",
      "../../engine/source/component/**",
      "../../engine/source/console/**",
      "../../engine/source/debug/**",
      "../../engine/source/delegates/**",
      "../../engine/source/game/**",
      "../../engine/source/graphics/**",
      "../../engine/source/gui/**",
      "../../engine/source/input/**",
      "../../engine/source/io/**",
      "../../engine/source/math/*.cpp",
      "../../engine/source/math/*.cc",
      "../../engine/source/math/*.h",
      "../../engine/source/memory/**",
      "../../engine/source/messaging/**",
      "../../engine/source/network/**",
      "../../engine/source/platform/**",
      "../../engine/source/sim/**",
      "../../engine/source/string/**",
      "../../engine/source/utility/**",
      "../../engine/source/torqueConfig.h",
   }

   links {
      "JPEG",
      "PNG",
      "zlib",
   }

   -- Platform specific files for Windows
   configuration "windows"
      includedirs {
         "../../engine/lib/openal/win32",
      }
      files {
         "../../engine/source/platformWin32/**",
         "../../engine/source/**.asm",
      }
      removefiles {
         "../../engine/source/platform/platformNetAsync.unix.cc",
      }

   -- Platform specific files for OSX
   configuration "macosx"
      files {
         "../../engine/source/platformOSX/**",
         "../../engine/source/**.mm",
         "../../engine/source/**.m",
      }
      removefiles {
      	"../../engine/source/math/mMathAMD.cc",
      	"../../engine/source/math/mMathSSE.cc",
      }

   -- Platform specific files for BSD and Linux based systems
   configuration "linux or bsd"
      files {
         "../../engine/source/platformX86Unix/**",
      }

   -- Platform specific files for Linux based systems
   configuration "linux"
      includedirs {
         "../../engine/lib/openal/LINUX",
      }

   -- Platform specific files for FreeBSD
   configuration "bsd"
      includedirs {
         "../../engine/lib/openal/FreeBSD"
      }

   configuration "Debug"
      targetname "Game_DEBUG"
      defines {
         "_DEBUG",
         "TORQUE_DEBUG",
         "TORQUE_ENABLE_PROFILER",
         "TORQUE_DEBUG_GUARD",
      }
      flags   { "Symbols" }

   configuration "Release"
      defines { "NDEBUG" }
      flags   { "OptimizeSpeed" }

   configuration "vs*"
      defines      { "_CRT_SECURE_NO_WARNINGS", "UNICODE" }
      flags        { "NoNativeWChar", "StaticRuntime" }
      buildoptions { "/wd4100", "/wd4800" }

   configuration "windows"
      targetdir "../Windows"
      links {
         "COMCTL32",
         "COMDLG32",
         "USER32",
         "ADVAPI32",
         "GDI32",
         "RPCRT4",
         "WINMM",
         "WSOCK32",
         "vfw32",
         "Imm32",
         "shell32",
         "shlwapi",
         "ole32",
         "opengl32",
      }

   configuration "linux"
      links { "dl" }

   configuration "macosx"
      defines { }
      links {
      	"AppKit.framework",
         "Cocoa.framework",
         "CoreData.framework",
         "CoreServices.framework",
         "Foundation.framework",
         "OpenAL.framework",
         "OpenGL.framework",
      }

   	-- Include the plist and language files
   	files {
   		"../../engine/resources/**",
   	}

   configuration { "macosx", "gmake" }
      buildoptions {"-mmacosx-version-min=10.4" }
      linkoptions  {"-mmacosx-version-min=10.4" }


text:
using System.Collections;
using DomainAndServices.Domain;

namespace DomainAndServices.Services
{
    public class FoodDataService
    {
        public ArrayList GetAllFoods()
        {
            var apple = new Food
            {
                Id = 1,
                Name = "Apple",
                Calories = 45
            };

            var tomato = new Food
            {
                Id = 2,
                Name = "Tomato",
                Calories = 30
            };

            var kiwi = new Food
            {
                Id = 3,
                Name = "Kiwi",
                Calories = 1000
            };

            var foods = new ArrayList
            {
                apple,
                tomato,
                kiwi
            };
            return foods;
        }
    }
}


text:
define("pat-gallery", [
    "jquery",
    "pat-registry",
    "pat-base",
    "pat-parser",
    "photoswipe",
    "photoswipe-ui",
    "tpl!photoswipe-template",
    "underscore"
], function($, patterns, Base, Parser, PhotoSwipe, PhotoSwipeUI, template, _) {
    var parser = new Parser("gallery");
    parser.addArgument("loop", true);
    parser.addArgument("scale-method", "fit", ["fit", "fitNoUpscale", "zoom"]);
    parser.addArgument("delay", 30000);
    parser.addArgument("effect-duration", 250);

    return Base.extend({
        name: "gallery",
        trigger: ".pat-gallery",

        init: function patGalleryInit($el, opts) {
            this.options = parser.parse(this.$el, opts);
            if ($('#photoswipe-template').length === 0) {
                $('body').append(template());
            }
            var images = $("a", this.$el).map(function () {
                return { 'w': 0, 'h': 0, 'src': this.href, 'title': $(this).find('img').attr('title') };
            });
            var pswpElement = document.querySelectorAll('.pswp')[0];
            var options = {
                index: 0,
                scaleMode: this.options.scaleMethod,
                loop: this.options.loop,
                slideshowDelay: this.options.delay,
                hideAnimationDuration: this.options.effectDuration,
                showAnimationDuration: this.options.effectDuration
            };
            $("a", this.$el).click(function (ev) {
                ev.preventDefault();
                if (this.href) {
                    options.index = _.indexOf(_.pluck(images, 'src'), this.href);
                } else {
                    options.index = 0;
                }
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI, images, options);
                gallery.listen('gettingData', function(index, item) {
                    // Workaround for the fact that we don't know the image sizes.
                    // https://github.com/dimsemenov/PhotoSwipe/issues/796
                    if (item.w < 1 || item.h < 1) { // unknown size
                        var img = new Image();
                        img.onload = function() { // will get size after load
                            item.w = this.width; // set image width
                            item.h = this.height; // set image height
                            gallery.invalidateCurrItems(); // reinit Items
                            gallery.updateSize(true); // reinit Items
                        };
                        img.src = item.src; // let's download image
                    }
                });
                gallery.init();
            });
        },
    });
});


text:
package org.gradoop.flink.model.impl.operators.matching.common.query.predicates.booleans;

import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.CNF;
import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.CNFElement;
import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.QueryPredicate;
import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.expressions.ComparisonExpression;
import org.s1ck.gdl.model.comparables.ComparableExpression;
import org.s1ck.gdl.model.predicates.Predicate;
import org.s1ck.gdl.model.predicates.booleans.And;
import org.s1ck.gdl.model.predicates.booleans.Not;
import org.s1ck.gdl.model.predicates.booleans.Or;
import org.s1ck.gdl.model.predicates.expressions.Comparison;
import org.s1ck.gdl.utils.Comparator;

/**
 * Wraps a {@link org.s1ck.gdl.model.predicates.booleans.Not} predicate
 */
public class NotPredicate extends QueryPredicate {

  /**
   * Holds the wrapped not predicate
   */
  private final Not not;

  /**
   * Create a new wrapper
   * @param not the wrapped not predicate
   */
  public NotPredicate(Not not) {
    this.not = not;
  }

  /**
   * Converts the predicate into conjunctive normal form
   * @return predicate in cnf
   */
  @Override
  public CNF asCNF() {
    Predicate expression = not.getArguments()[0];

    if (expression.getClass() == Comparison.class) {
      CNF cnf = new CNF();
      CNFElement cnfElement = new CNFElement();
      cnfElement.addPredicate(new ComparisonExpression(invertComparison((Comparison) expression)));
      cnf.addPredicate(cnfElement);
      return cnf;

    } else if (expression.getClass() == Not.class) {
      return QueryPredicate.createFrom(expression.getArguments()[0]).asCNF();

    } else if (expression.getClass() == And.class) {
      Predicate[] otherArguments = expression.getArguments();
      Or or = new Or(
        new Not(otherArguments[0]),
        new Not(otherArguments[0])
      );
      return QueryPredicate.createFrom(or).asCNF();

    } else if (expression.getClass() == Or.class) {
      Predicate[] otherArguments = expression.getArguments();
      And and = new And(
        new Not(otherArguments[0]),
        new Not(otherArguments[1])
      );

      return QueryPredicate.createFrom(and).asCNF();

    } else {
      Predicate[] otherArguments = expression.getArguments();
      Or or = new Or(
        new And(
          otherArguments[0],
          otherArguments[1]),
        new And(
          new Not(otherArguments[0]),
          new Not(otherArguments[0]))
      );

      return QueryPredicate.createFrom(or).asCNF();
    }
  }

  /**
   * Invert a comparison
   * eg NOT(a > b) == (a <= b)
   * @param comparison the comparison that will be inverted
   * @return inverted comparison
   */
  private Comparison invertComparison(
    Comparison comparison) {
    ComparableExpression[] arguments = comparison.getComparableExpressions();
    Comparator op = comparison.getComparator();

    return new Comparison(
      arguments[0],
      op.getInverse(),
      arguments[1]
    );
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    NotPredicate that = (NotPredicate) o;

    return not != null ? not.equals(that.not) : that.not == null;

  }

  @Override
  public int hashCode() {
    return not != null ? not.hashCode() : 0;
  }
}


text:
namespace Caliburn.Micro.HelloScreens.Customers
{
    public class AddressViewModel : Screen
    {
        public AddressViewModel() {
            DisplayName = "Address";
        }
    }
}


text:
package org.apache.causeway.viewer.restfulobjects.rendering.domaintypes;

import org.apache.causeway.core.metamodel.spec.ObjectSpecification;
import org.apache.causeway.core.metamodel.spec.feature.OneToManyAssociation;
import org.apache.causeway.viewer.restfulobjects.applib.JsonRepresentation;
import org.apache.causeway.viewer.restfulobjects.applib.Rel;
import org.apache.causeway.viewer.restfulobjects.applib.RepresentationType;
import org.apache.causeway.viewer.restfulobjects.rendering.IResourceContext;
import org.apache.causeway.viewer.restfulobjects.rendering.LinkBuilder;
import org.apache.causeway.viewer.restfulobjects.rendering.LinkFollowSpecs;

import lombok.val;

public class CollectionDescriptionReprRenderer
extends AbstractTypeMemberReprRenderer<OneToManyAssociation> {

    public static LinkBuilder newLinkToBuilder(
            final IResourceContext resourceContext,
            final Rel rel,
            final ObjectSpecification objectSpecification,
            final OneToManyAssociation collection) {
        final String domainType = objectSpecification.getLogicalTypeName();
        final String collectionId = collection.getId();
        final String url = "domain-types/" + domainType + "/collections/" + collectionId;
        return LinkBuilder.newBuilder(resourceContext, rel.getName(), RepresentationType.COLLECTION_DESCRIPTION, url);
    }

    public CollectionDescriptionReprRenderer(
            final IResourceContext resourceContext,
            final LinkFollowSpecs linkFollower,
            final JsonRepresentation representation) {
        super(resourceContext, linkFollower, RepresentationType.COLLECTION_DESCRIPTION, representation);
    }

    @Override
    protected void addLinksSpecificToFeature() {
        addLinkToElementTypeIfAny();
    }

    @Override
    protected void putExtensionsSpecificToFeature() {
        putExtensionsName();
        putExtensionsDescriptionIfAvailable();
    }

    // -- HELPER

    private void addLinkToElementTypeIfAny() {
        val elementTypeSpec = getObjectFeature().getElementType();
        if (elementTypeSpec == null) {
            return;
        }
        getLinks().arrayAdd(
                DomainTypeReprRenderer
                .newLinkToBuilder(getResourceContext(), Rel.ELEMENT_TYPE, elementTypeSpec)
                .build());
    }

}


text:
===================
PHP_Depend Handbook
===================

- `Introduction`__
- `Installation`__

  - `PEAR Installer`__
  - `PHAR Archive`__
  - `GitHub Repository`__

- `Command-Line`__
- `Configuration`__
- `Reports`__

  - `Abstraction Instability Chart`__
  - `Overview Pyramid`__

__ /documentation/handbook/introduction.html
__ /documentation/handbook/installation.html
__ /documentation/handbook/installation/pear-installer.html
__ /documentation/handbook/installation/phar-archive.html
__ /documentation/handbook/installation/github-repository.html
__ /documentation/handbook/command-line.html
__ /documentation/handbook/configuration.html
__ /documentation/handbook/reports.html
__ /documentation/handbook/reports/abstraction-instability-chart.html
__ /documentation/handbook/reports/overview-pyramid.html


text:
package it.polimi.export.processing.rspengine.windowed.esper.listeners;

import it.polimi.export.processing.rspengine.windowed.esper.plain.events.TripleEvent;
import it.polimi.processing.EventProcessor;
import it.polimi.processing.events.TripleContainer;
import it.polimi.processing.events.interfaces.Event;

import java.util.HashSet;
import java.util.Set;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j;

import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.UpdateListener;

@Data
@Log4j
@AllArgsConstructor()
@EqualsAndHashCode(callSuper = false)
public class ResultCollectorListener implements UpdateListener {

	private final EventProcessor<Event> resultCollector;
	private String name;

	private int eventNumber = 0;

	@Override
	public void update(EventBean[] newEvents, EventBean[] oldEvents) {

		log.debug("Run the Listener");

		Set<TripleContainer> statements = new HashSet<TripleContainer>();
		Set<TripleContainer> ABoxTriples = new HashSet<TripleContainer>();
		for (EventBean eventBean : newEvents) {
			TripleEvent storableEvent = (TripleEvent) eventBean.getUnderlying();
			for (TripleContainer strings : storableEvent.getTriples()) {
				statements.add(strings);
				if (eventBean.get("channel").equals("Input")) {
					ABoxTriples.add(strings);
				}
			}
		}

		// try {
		// log.debug("Send Event to the StoreCollector");
		// // resultCollector.store(new Result(statements, eventNumber, (eventNumber +
		// // ABoxTriples.size()), System.currentTimeMillis()), "Result");
		// // resultCollector.store(new Result(ABoxTriples, eventNumber, (eventNumber +
		// // ABoxTriples.size()), System.currentTimeMillis()), "Window");
		// eventNumber += ABoxTriples.size() + 1;
		// } catch (IOException e) {
		// log.error("Something went wrong, can't save the event");
		// }
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
		<title>StratosLive</title>
		<link href="style.css" rel="stylesheet" type="text/css" media="all" />
		<link rel="icon" href="images/favicon.ico" type="image/x-icon"/>
		<meta name="description" content="WSO2 is the lean enterprise middleware company, delivering the only complete open source enterprise SOA middleware stack available internally and in the cloud." />
		<meta name="keywords" content="cloud, platform-as-a-service, PaaS" />

The WSO2 Identity Server, providing multidisciplinary identity and entitlement management with a set of state-of-the art, powerful security mechanisms, delivered as a multi-tenant, elastically scaling, metered platform.

Features

User Profile

							Update your user profile or add multiple user profiles.The value from your profile will be used to populate your Information card and OpenID profiles.

OpenID

							This OpenID can be used with any OpenID relying party which trusts your domain for login.

Information Card

							This card can be used with any identity selector that supports Microsoft CardSpace specifications and will allow you to login to web applications that support information card logins.

					Terms of Service | Privacy Policy | Support

						Powered by

					©stratoslive.wso2.com copyright 2010-2011 WSO2, Inc.


text:
cask 'now' do
  version '3.8.23'
  sha256 '6dffc92d64b9da54856c346810dbac9862a5e97f8c4ada4bcbd45c0c6038dec8'

  # github.com/zeit/now-desktop was verified as official when first introduced to the cask
  url "https://github.com/zeit/now-desktop/releases/download/#{version}/now-desktop-#{version}-mac.zip"
  appcast 'https://github.com/zeit/now-desktop/releases.atom',
          checkpoint: '44409edbcdcacdd40f9d34760e1bb3592e62dd380d377f92889c2caaa25c92ea'
  name 'Now'
  homepage 'https://zeit.co/now'

  app 'Now.app'

  uninstall delete:     '/usr/local/bin/now',
            login_item: 'Now',
            signal:     ['TERM', 'co.zeit.now']

  zap trash: [
               '~/.now.json',
               '~/Library/Application Support/Now',
               '~/Library/Caches/co.zeit.now',
               '~/Library/Caches/co.zeit.now.ShipIt',
               '~/Library/Preferences/co.zeit.now.plist',
               '~/Library/Preferences/co.zeit.now.helper.plist',
             ]
end


text:
package math;

public class Math {
/**
 * Numerical differentiaton should happen here
 */

}


text:
import subprocess,os,sys
sys.path.append('/home/shangzhong/Codes/Pipeline')
from Modules.f05_IDConvert import extract_from_gene2ref,prIDMap2geneIDMap
from Modules.p04_ParseBlast import blastName2ID

def rosetta_pair(group):
    """
    This functions detects rosetta pairs, given a list of lines which have same 2nd column.

    * group: a list of blast tabular results. each item in the list is a line of blast tabular result.
            they should have same 2nd reference name.
    """
    rosetta = []
    for i in range(len(group)-1):
        for j in range(i + 1,len(group)):
            if (max(int(group[i][8]),int(group[i][9])) < min(int(group[j][8]),int(group[j][9]))):
                ref = group[i][1]; firstName = group[i][0]; secondName = group[j][0]
                firBegin=group[i][8];firEnd=group[i][9]
                secBegin=group[j][8];secEnd=group[j][9]
                rosetta.append([ref,firstName,secondName,firBegin,firEnd,secBegin,secEnd])
            elif (max(int(group[j][8]),int(group[j][9])) < min(int(group[i][8]),int(group[i][9]))):
                ref = group[i][1]; firstName = group[j][0]; secondName = group[i][0]
                firBegin=group[j][8];firEnd=group[j][9]
                secBegin=group[i][8];secEnd=group[i][9]
                rosetta.append([ref,firstName,secondName,firBegin,firEnd,secBegin,secEnd])
            else:
                continue
    return rosetta

def rosetta_stone(blastFile,organism1,taxID1,organism2,taxID2,gene2refseq):
    """
    This functions detects rosetta stone pairs in the blast result.

    * blastFile: fileanme of tabular blast output.
    """
    # # (1) change first 2 columns into ID, extract top hit
    IDblast = blastName2ID(blastFile)
    # # (2) extract cho, human from gene2refseq
    org1ref = extract_from_gene2ref(gene2refseq,taxID1,organism1,columnNum=[2,6,7])
    org2ref = extract_from_gene2ref(gene2refseq,taxID2,organism2,columnNum=[2,6,7])
    # # (3) replace protein ID with gene ID
    IDmap = prIDMap2geneIDMap(IDblast,org1ref,org2ref)
    # # (4) sort file by 2nd column
    sortFile = IDmap[:-3] + 'sort.txt'
    cmd = ('sort -k2,2 -n {input} > {output}').format(input=IDmap,output=sortFile)
    subprocess.call(cmd,shell=True)
    os.remove(IDblast)

    # # (5) now come to the parsing rosetta stone pairs
    filename = sortFile
    res = open(filename,'r')
    inter = 'inter.txt'
    interOut = open(inter,'w')
    outputFile = filename[:-16] + 'rosetta.txt'
    output = open(outputFile,'w')
    # combine lines with same 2 columns.
    id_pair = res.readline()[:-1].split('\t')
    # start from second line
    for line in res:
        line = line[:-1]
        item = line.split('\t')
        # should merge
        if id_pair[0] == item[0] and id_pair[1] == item[1]:
            id_pair[8] = str(min(int(id_pair[8]),int(id_pair[9]),int(item[8]),int(item[9])))
            id_pair[9] = str(max(int(id_pair[8]),int(id_pair[9]),int(item[8]),int(item[9])))
        else:
            interOut.write('\t'.join(id_pair) + '\n')
            id_pair = item
    interOut.write('\t'.join(id_pair) + '\n')
    interOut.close()
    res.close()
    # now interOut has unique first 2 columns of blast tabular results
    res = open(inter,'r')
    group = [res.readline()[:-1].split('\t')] # group stores lines with same reference
    for line in res:
        item = line[:-1].split('\t')
        if item[1] == group[-1][1]:
            group.append(item)
        else:
            # whether to do rosetta pair detection
            if len(group) > 1:
                rosetta = rosetta_pair(group)
                # output to file
                if rosetta != []:
                    for pair in rosetta:
                        output.write('\t'.join(pair) + '\n')
            # there is no rosetta pairs
            group = [item]
    if len(group) > 1:
                rosetta = rosetta_pair(group)
                # output to file
                if rosetta != []:
                    for pair in rosetta:
                        output.write('\t'.join(pair) + '\n')

    output.close()
    res.close()
    return outputFile
blastFile = '/data/shangzhong/CHO2Human/2wayBlastPresult/human2cho.txt'
gene2refseq = '/data/shangzhong/CHO2Human/2wayBlastPresult/141026gene2refseq.gz'
rosetta = rosetta_stone(blastFile,'cho',10029,'human',9606,gene2refseq)


text:
@font-face {
  font-family: 'OpenDyslexic';
  src: url('../lib/font/opendyslexic/opendyslexic3.ttf');
  src: url('../lib/font/opendyslexic/opendyslexic3.ttf?#iefix') format('embedded-opentype'), url('../lib/font/opendyslexic/opendyslexic3.ttf') format('ttf'), url('../lib/font/opendyslexic/opendyslexic3.ttf') format('ttf');
}


text:
package com.twitter.finagle.filter

import com.twitter.finagle._
import com.twitter.finagle.builder.{ClientBuilder, ServerBuilder}
import com.twitter.finagle.integration.{IntegrationBase, StringCodec}
import com.twitter.util.{Await, Future, Monitor, Promise, Return, Throw}
import java.net.InetSocketAddress
import java.util.logging.{Level, Logger, StreamHandler}
import org.mockito.Matchers
import org.specs.SpecificationWithJUnit
import org.specs.mock.Mockito

class MonitorFilterSpec extends SpecificationWithJUnit with IntegrationBase with Mockito {
  class MockMonitor extends Monitor {
    def handle(cause: Throwable) = false
  }
  val monitor = spy(new MockMonitor)

  "MonitorFilter" should {
    val monitor = spy(new MockMonitor)
    val underlying = mock[Service[Int, Int]]
    underlying.close(any) returns Future.Done
    val reply = new Promise[Int]
    underlying(any) returns reply
    val service = new MonitorFilter(monitor) andThen underlying
    val exc = new RuntimeException

    "report Future.exception" in {
      val f = service(123)
      f.poll must beNone

      reply() = Throw(exc)
      f.poll must beSome(Throw(exc))
      there was one(monitor).handle(exc)
    }

    "report raw service exception" in {
      underlying(any) throws exc
      val f = service(123)
      f.poll must beSome(Throw(exc))
      there was one(monitor).handle(exc)
    }
  }

  class MockSourcedException(underlying: Throwable, name: String)
    extends RuntimeException(underlying) with SourcedException {
    def this(name:String) = this(null, name)
    serviceName = name
  }

  "MonitorFilter" should {
    val inner = new MockSourcedException("FakeService1")
    val outer = new MockSourcedException(inner, "FakeService2")

    val mockLogger = spy(Logger.getLogger("MockServer"))
    // add handler to redirect and mute output, so that it doesn't show up in the console during a test run.
    mockLogger.setUseParentHandlers(false)
    mockLogger.addHandler(new StreamHandler())

    "when attached to a server, report source for sourced exceptions" in {
      val address = new InetSocketAddress(0)
      val service = mock[Service[String, String]]
      service.close(any) returns Future.Done
      val server = ServerBuilder()
        .codec(StringCodec)
        .name("MockServer")
        .bindTo(address)
        .monitor((_, _) => monitor)
        .logger(mockLogger)
        .build(service)

      // We cannot mock "service" directly, because we are testing an internal filter defined in the ServerBuilder
      // that sits on top of "service". Therefore we need to create a client to initiates the requests.
      val client = ClientBuilder()
        .codec(StringCodec)
        .hosts(Seq(server.localAddress))
        .hostConnectionLimit(1)
        .build()

      service(any) throws outer // make server service throw the mock exception

      try {
        val f = Await.result(client("123"))
      } catch {
        case e: ChannelException => // deliberately empty. Server exception comes back as ChannelClosedException
      }

      there was no(monitor).handle(inner)
      there was one(monitor).handle(outer)
      there was one(mockLogger).log(
        Matchers.eq(Level.SEVERE),
        Matchers.eq("A server service FakeService2 on behalf of FakeService1 threw an exception"),
        Matchers.eq(outer))
    }

    "when attached to a client, report source for sourced exceptions" in {
      // mock channel to mock the service provided by a server
      val preparedFactory = mock[ServiceFactory[String, String]]
      val preparedServicePromise = new Promise[Service[String, String]]
      preparedFactory() returns preparedServicePromise
      preparedFactory.close(any) returns Future.Done
      preparedFactory.map(Matchers.any()) returns
        preparedFactory.asInstanceOf[ServiceFactory[Any, Nothing]]

      val m = new MockChannel
      m.codec.prepareConnFactory(any) returns preparedFactory

      val client = m.clientBuilder
        .monitor(_ => monitor)
        .logger(mockLogger)
        .build()

      val requestFuture = client("123")

      requestFuture.isDefined must beFalse
      val mockService = new Service[String, String] {
        def apply(request: String): Future[String] = Future.exception(outer)
      }

      preparedServicePromise() = Return(mockService)
      requestFuture.poll must beSome(Throw(outer))

      there was no(monitor).handle(inner)
      there was one(monitor).handle(outer)
    }
  }
}


text:
package com.giffing.bucket4j.spring.boot.starter.examples.webflux;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class WebfluxApplication {

	public static void main(String[] args) {
		SpringApplication.run(WebfluxApplication.class, args);
	}

}


text:
using System.Collections.Generic;

namespace Umbraco.Web.Trees
{
    public interface ISearchableTree
    {
        IEnumerable<SearchResultItem> Search(string searchText);
    }
}


text:
package org.brandonhaynes.pipegen.runtime.directory;

import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import org.brandonhaynes.pipegen.configuration.Direction;

import java.util.Map;
import java.util.concurrent.BlockingDeque;

public class ProductionWorkerDirectory implements WorkerDirectory {
    private final Map<String, BlockingDeque<WorkerDirectoryEntry>> entries = Maps.newConcurrentMap();

    public WorkerDirectoryEntry add(String systemName, Direction direction,
                                    String hostname, int port) {
        WorkerDirectoryEntry entry = new WorkerDirectoryEntry(systemName, direction, hostname, port);
        add(entry);
        return entry;
    }

    public void add(WorkerDirectoryEntry importer) {
        try {
            getQueue(importer.getSystemName()).putFirst(importer);
        } catch(InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public WorkerDirectoryEntry pop(String systemName) {
        try {
            return getQueue(systemName).takeFirst();
        } catch(InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private BlockingDeque<WorkerDirectoryEntry> getQueue(String systemName) {
        if(!entries.containsKey(systemName))
            entries.put(systemName, Queues.newLinkedBlockingDeque());
        return entries.get(systemName);
    }
}


text:
"""
Functions Package : All testcases about main functions in PFW :
    - listing functions
    - help function
    - status function
    - export/import functions
    - get/set parameter functions
    - synchronization functions
"""


text:
package de.qucosa.metsdisseminator.repository;

/**
 * Encapsulate a checksum hash value together with the algorithm that produced the hash
 * in an unmodifiable object.
 */
public class Checksum {

    private final String algorithm;
    private final String hashvalue;

    /**
     * Create a new checksum.
     *
     * @param algorithm Name of the algorithm used.
     * @param hashvalue Produced hash value.
     */
    public Checksum(String algorithm, String hashvalue) {
        this.algorithm = algorithm;
        this.hashvalue = hashvalue;
    }

    /**
     * Return the algorithm name.
     *
     * @return Algorithm name
     */
    public String algorithm() {
        return algorithm;
    }

    /**
     * Return the hash value.
     *
     * @return Hash value
     */
    public String hashvalue() {
        return hashvalue;
    }
}


text:
import {bindAction} from '../../util';
import {buildTree, flattenTree} from '../util';

declare var Polymer: any;

export function main() {
  const rootEl: any = document.querySelector('binary-tree');

  function destroyDom() {
    while (rootEl.firstChild) rootEl.removeChild(rootEl.firstChild);
  }

  function createDom() {
    const flatTree = flattenTree(buildTree(), []);
    for (var i = 0; i < flatTree.length; i++) {
      const el: any = document.createElement('tree-leaf');
      el.data = flatTree[i];
      rootEl.appendChild(el);
    }
  }

  bindAction('#destroyDom', destroyDom);
  bindAction('#createDom', createDom);
}


text:
module Lev

  class ErrorTransferer

    def self.transfer(source, target_routine, input_mapper, fail_if_errors=false)
      case source
      when ActiveRecord::Base, Lev::Paramifier
        source.errors.each do |error|
          target_routine.nonfatal_error(
            code: error.type,
            data: {
              model: source,
              attribute: error.attribute
            },
            kind: :activerecord,
            message: error.message,
            offending_inputs: input_mapper.map(error.attribute)
          )
        end
      when Lev::Errors
        source.each do |error|
          target_routine.nonfatal_error(
            code: error.code,
            data: error.data,
            kind: error.kind,
            message: error.message,
            offending_inputs: input_mapper.map(error.offending_inputs)
          )
        end
      else
        raise Exception
      end

      # We add nonfatal errors above and then have this call here so that all
      # errors can be transferred before we freak out.
      throw :fatal_errors_encountered if target_routine.errors? && fail_if_errors
    end

  end

end