<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const ccxt = require ('ccxt');

//  ---------------------------------------------------------------------------

module.exports = class bitvavo extends ccxt.bitvavo {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'watchOrderBook': true,
            },
            'urls': {
                'api': {
                    'ws': 'wss://ws.bitvavo.com/v2',
                },
            },
            'options': {
                'tradesLimit': 1000,
                'ordersLimit': 1000,
                'OHLCVLimit': 1000,
            },
        });
    }

    async watchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const name = 'book';
        const messageHash = name + '@' + market['id'];
        const url = this.urls['api']['ws'];
        const request = {
            'action': 'subscribe',
            'channels': [
                {
                    'name': name,
                    'markets': [
                        market['id'],
                    ],
                },
            ],
        };
        const subscription = {
            'messageHash': messageHash,
            'name': name,
            'symbol': symbol,
            'marketId': market['id'],
            'method': this.handleOrderBookSubscription,
            'limit': limit,
            'params': params,
        };
        const message = this.extend (request, params);
        const future = this.watch (url, messageHash, message, messageHash, subscription);
        return await this.after (future, this.limitOrderBook, symbol, limit, params);
    }

    handleDelta (bookside, delta) {
        const price = this.safeFloat (delta, 0);
        const amount = this.safeFloat (delta, 1);
        bookside.store (price, amount);
    }

    handleDeltas (bookside, deltas) {
        for (let i = 0; i < deltas.length; i++) {
            this.handleDelta (bookside, deltas[i]);
        }
    }

    handleOrderBookMessage (client, message, orderbook) {
        //
        //     {
        //         event: 'book',
        //         market: 'BTC-EUR',
        //         nonce: 36947383,
        //         bids: [
        //             [ '8477.8', '0' ]
        //         ],
        //         asks: [
        //             [ '8550.9', '0' ]
        //         ]
        //     }
        //
        const nonce = this.safeInteger (message, 'nonce');
        if (nonce > orderbook['nonce']) {
            this.handleDeltas (orderbook['asks'], this.safeValue (message, 'asks', []));
            this.handleDeltas (orderbook['bids'], this.safeValue (message, 'bids', []));
            orderbook['nonce'] = nonce;
        }
        return orderbook;
    }

    handleOrderBook (client, message) {
        //
        //     {
        //         event: 'book',
        //         market: 'BTC-EUR',
        //         nonce: 36729561,
        //         bids: [
        //             [ '8513.3', '0' ],
        //             [ '8518.8', '0.64236203' ],
        //             [ '8513.6', '0.32435481' ],
        //         ],
        //         asks: []
        //     }
        //
        const event = this.safeString (message, 'event');
        const marketId = this.safeString (message, 'market');
        let market = undefined;
        let symbol = undefined;
        if (marketId !== undefined) {
            if (marketId in this.markets_by_id) {
                market = this.markets_by_id[marketId];
                symbol = market['symbol'];
            }
        }
        const messageHash = event + '@' + market['id'];
        const orderbook = this.safeValue (this.orderbooks, symbol);
        if (orderbook === undefined) {
            return;
        }
        if (orderbook['nonce'] === undefined) {
            const subscription = this.safeValue (client.subscriptions, messageHash, {});
            const watchingOrderBookSnapshot = this.safeValue (subscription, 'watchingOrderBookSnapshot');
            if (watchingOrderBookSnapshot === undefined) {
                subscription['watchingOrderBookSnapshot'] = true;
                client.subscriptions[messageHash] = subscription;
                const options = this.safeValue (this.options, 'watchOrderBookSnapshot', {});
                const delay = this.safeInteger (options, 'delay', this.rateLimit);
                // fetch the snapshot in a separate async call after a warmup delay
                this.delay (delay, this.watchOrderBookSnapshot, client, message, subscription);
            }
            orderbook.cache.push (message);
        } else {
            this.handleOrderBookMessage (client, message, orderbook);
            client.resolve (orderbook, messageHash);
        }
    }

    async watchOrderBookSnapshot (client, message, subscription) {
        const symbol = this.safeString (subscription, 'symbol');
        const limit = this.safeInteger (subscription, 'limit');
        const params = this.safeValue (subscription, 'params');
        const marketId = this.safeString (subscription, 'marketId');
        const name = 'getBook';
        const messageHash = name + '@' + marketId;
        const url = this.urls['api']['ws'];
        const request = {
            'action': name,
            'market': marketId,
        };
        const future = this.watch (url, messageHash, request, messageHash, subscription);
        return await this.after (future, this.limitOrderBook, symbol, limit, params);
    }

    handleOrderBookSnapshot (client, message) {
        //
        //     {
        //         action: 'getBook',
        //         response: {
        //             market: 'BTC-EUR',
        //             nonce: 36946120,
        //             bids: [
        //                 [ '8494.9', '0.24399521' ],
        //                 [ '8494.8', '0.34884085' ],
        //                 [ '8493.9', '0.14535128' ],
        //             ],
        //             asks: [
        //                 [ '8495', '0.46982463' ],
        //                 [ '8495.1', '0.12178267' ],
        //                 [ '8496.2', '0.21924143' ],
        //             ]
        //         }
        //     }
        //
        const response = this.safeValue (message, 'response');
        if (response === undefined) {
            return message;
        }
        const marketId = this.safeString (response, 'market');
        let symbol = undefined;
        if (marketId in this.markets_by_id) {
            const market = this.markets_by_id[marketId];
            symbol = market['symbol'];
        }
        const name = 'book';
        const messageHash = name + '@' + marketId;
        const orderbook = this.orderbooks[symbol];
        const snapshot = this.parseOrderBook (response);
        snapshot['nonce'] = this.safeInteger (response, 'nonce');
        orderbook.reset (snapshot);
        // unroll the accumulated deltas
        const messages = orderbook.cache;
        for (let i = 0; i < messages.length; i++) {
            const message = messages[i];
            this.handleOrderBookMessage (client, message, orderbook);
        }
        this.orderbooks[symbol] = orderbook;
        client.resolve (orderbook, messageHash);
    }

    handleOrderBookSubscription (client, message, subscription) {
        const symbol = this.safeString (subscription, 'symbol');
        const limit = this.safeInteger (subscription, 'limit');
        if (symbol in this.orderbooks) {
            delete this.orderbooks[symbol];
        }
        this.orderbooks[symbol] = this.orderBook ({}, limit);
    }

    handleOrderBookSubscriptions (client, message, marketIds) {
        const name = 'book';
        for (let i = 0; i < marketIds.length; i++) {
            const marketId = this.safeString (marketIds, i);
            const messageHash = name + '@' + marketId;
            const subscription = this.safeValue (client.subscriptions, messageHash);
            const method = this.safeValue (subscription, 'method');
            if (method !== undefined) {
                method.call (this, client, message, subscription);
            }
        }
    }

    handleSubscriptionStatus (client, message) {
        //
        //     {
        //         event: 'subscribed',
        //         subscriptions: {
        //             book: [ 'BTC-EUR' ]
        //         }
        //     }
        //
        const subscriptions = this.safeValue (message, 'subscriptions', {});
        const methods = {
            'book': this.handleOrderBookSubscriptions,
            // 'trade': this.handleTrade,
            // 'kline': this.handleOHLCV,
            // '24hrTicker': this.handleTicker,
            // 'outboundAccountInfo': this.handleBalance,
            // 'executionReport': this.handleOrder,
        };
        const names = Object.keys (subscriptions);
        for (let i = 0; i < names.length; i++) {
            const name = names[i];
            const method = this.safeValue (methods, name);
            const subscription = this.safeValue (subscriptions, name);
            if (method !== undefined) {
                method.call (this, client, message, subscription);
            }
        }
        return message;
    }

    signMessage (client, messageHash, message, params = {}) {
        // todo: implement signMessage
        return message;
    }

    handleMessage (client, message) {
        //
        //     {
        //         event: 'subscribed',
        //         subscriptions: {
        //             book: [ 'BTC-EUR' ]
        //         }
        //     }
        //
        //
        //     {
        //         event: 'book',
        //         market: 'BTC-EUR',
        //         nonce: 36729561,
        //         bids: [
        //             [ '8513.3', '0' ],
        //             [ '8518.8', '0.64236203' ],
        //             [ '8513.6', '0.32435481' ],
        //         ],
        //         asks: []
        //     }
        //
        //     {
        //         action: 'getBook',
        //         response: {
        //             market: 'BTC-EUR',
        //             nonce: 36946120,
        //             bids: [
        //                 [ '8494.9', '0.24399521' ],
        //                 [ '8494.8', '0.34884085' ],
        //                 [ '8493.9', '0.14535128' ],
        //             ],
        //             asks: [
        //                 [ '8495', '0.46982463' ],
        //                 [ '8495.1', '0.12178267' ],
        //                 [ '8496.2', '0.21924143' ],
        //             ]
        //         }
        //     }
        //
        const methods = {
            'subscribed': this.handleSubscriptionStatus,
            'book': this.handleOrderBook,
            'getBook': this.handleOrderBookSnapshot,
            // 'trade': this.handleTrade,
            // 'kline': this.handleOHLCV,
            // '24hrTicker': this.handleTicker,
            // 'outboundAccountInfo': this.handleBalance,
            // 'executionReport': this.handleOrder,
        };
        const event = this.safeString (message, 'event');
        let method = this.safeValue (methods, event);
        if (method === undefined) {
            const action = this.safeString (message, 'action');
            method = this.safeValue (methods, action);
            if (method === undefined) {
                const util = require ('util');
                console.log ('handleMessage', util.inspect (message, { showHidden: false, depth: null }));
                process.exit ();
                return message;
            } else {
                return method.call (this, client, message);
            }
        } else {
            return method.call (this, client, message);
        }
    }
};
<commit_msg>bitvavo watchOrderBook<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const ccxt = require ('ccxt');

//  ---------------------------------------------------------------------------

module.exports = class bitvavo extends ccxt.bitvavo {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'watchOrderBook': true,
            },
            'urls': {
                'api': {
                    'ws': 'wss://ws.bitvavo.com/v2',
                },
            },
            'options': {
                'tradesLimit': 1000,
                'ordersLimit': 1000,
                'OHLCVLimit': 1000,
            },
        });
    }

    async watchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const name = 'book';
        const messageHash = name + '@' + market['id'];
        const url = this.urls['api']['ws'];
        const request = {
            'action': 'subscribe',
            'channels': [
                {
                    'name': name,
                    'markets': [
                        market['id'],
                    ],
                },
            ],
        };
        const subscription = {
            'messageHash': messageHash,
            'name': name,
            'symbol': symbol,
            'marketId': market['id'],
            'method': this.handleOrderBookSubscription,
            'limit': limit,
            'params': params,
        };
        const message = this.extend (request, params);
        const future = this.watch (url, messageHash, message, messageHash, subscription);
        return await this.after (future, this.limitOrderBook, symbol, limit, params);
    }

    handleDelta (bookside, delta) {
        const price = this.safeFloat (delta, 0);
        const amount = this.safeFloat (delta, 1);
        bookside.store (price, amount);
    }

    handleDeltas (bookside, deltas) {
        for (let i = 0; i < deltas.length; i++) {
            this.handleDelta (bookside, deltas[i]);
        }
    }

    handleOrderBookMessage (client, message, orderbook) {
        //
        //     {
        //         event: 'book',
        //         market: 'BTC-EUR',
        //         nonce: 36947383,
        //         bids: [
        //             [ '8477.8', '0' ]
        //         ],
        //         asks: [
        //             [ '8550.9', '0' ]
        //         ]
        //     }
        //
        const nonce = this.safeInteger (message, 'nonce');
        if (nonce > orderbook['nonce']) {
            this.handleDeltas (orderbook['asks'], this.safeValue (message, 'asks', []));
            this.handleDeltas (orderbook['bids'], this.safeValue (message, 'bids', []));
            orderbook['nonce'] = nonce;
        }
        return orderbook;
    }

    handleOrderBook (client, message) {
        //
        //     {
        //         event: 'book',
        //         market: 'BTC-EUR',
        //         nonce: 36729561,
        //         bids: [
        //             [ '8513.3', '0' ],
        //             [ '8518.8', '0.64236203' ],
        //             [ '8513.6', '0.32435481' ],
        //         ],
        //         asks: []
        //     }
        //
        const event = this.safeString (message, 'event');
        const marketId = this.safeString (message, 'market');
        let market = undefined;
        let symbol = undefined;
        if (marketId !== undefined) {
            if (marketId in this.markets_by_id) {
                market = this.markets_by_id[marketId];
                symbol = market['symbol'];
            }
        }
        const messageHash = event + '@' + market['id'];
        const orderbook = this.safeValue (this.orderbooks, symbol);
        if (orderbook === undefined) {
            return;
        }
        if (orderbook['nonce'] === undefined) {
            const subscription = this.safeValue (client.subscriptions, messageHash, {});
            const watchingOrderBookSnapshot = this.safeValue (subscription, 'watchingOrderBookSnapshot');
            if (watchingOrderBookSnapshot === undefined) {
                subscription['watchingOrderBookSnapshot'] = true;
                client.subscriptions[messageHash] = subscription;
                const options = this.safeValue (this.options, 'watchOrderBookSnapshot', {});
                const delay = this.safeInteger (options, 'delay', this.rateLimit);
                // fetch the snapshot in a separate async call after a warmup delay
                this.delay (delay, this.watchOrderBookSnapshot, client, message, subscription);
            }
            orderbook.cache.push (message);
        } else {
            this.handleOrderBookMessage (client, message, orderbook);
            client.resolve (orderbook, messageHash);
        }
    }

    async watchOrderBookSnapshot (client, message, subscription) {
        const symbol = this.safeString (subscription, 'symbol');
        const limit = this.safeInteger (subscription, 'limit');
        const params = this.safeValue (subscription, 'params');
        const marketId = this.safeString (subscription, 'marketId');
        const name = 'getBook';
        const messageHash = name + '@' + marketId;
        const url = this.urls['api']['ws'];
        const request = {
            'action': name,
            'market': marketId,
        };
        const future = this.watch (url, messageHash, request, messageHash, subscription);
        return await this.after (future, this.limitOrderBook, symbol, limit, params);
    }

    handleOrderBookSnapshot (client, message) {
        //
        //     {
        //         action: 'getBook',
        //         response: {
        //             market: 'BTC-EUR',
        //             nonce: 36946120,
        //             bids: [
        //                 [ '8494.9', '0.24399521' ],
        //                 [ '8494.8', '0.34884085' ],
        //                 [ '8493.9', '0.14535128' ],
        //             ],
        //             asks: [
        //                 [ '8495', '0.46982463' ],
        //                 [ '8495.1', '0.12178267' ],
        //                 [ '8496.2', '0.21924143' ],
        //             ]
        //         }
        //     }
        //
        const response = this.safeValue (message, 'response');
        if (response === undefined) {
            return message;
        }
        const marketId = this.safeString (response, 'market');
        let symbol = undefined;
        if (marketId in this.markets_by_id) {
            const market = this.markets_by_id[marketId];
            symbol = market['symbol'];
        }
        const name = 'book';
        const messageHash = name + '@' + marketId;
        const orderbook = this.orderbooks[symbol];
        const snapshot = this.parseOrderBook (response);
        snapshot['nonce'] = this.safeInteger (response, 'nonce');
        orderbook.reset (snapshot);
        // unroll the accumulated deltas
        const messages = orderbook.cache;
        for (let i = 0; i < messages.length; i++) {
            const message = messages[i];
            this.handleOrderBookMessage (client, message, orderbook);
        }
        this.orderbooks[symbol] = orderbook;
        client.resolve (orderbook, messageHash);
    }

    handleOrderBookSubscription (client, message, subscription) {
        const symbol = this.safeString (subscription, 'symbol');
        const limit = this.safeInteger (subscription, 'limit');
        if (symbol in this.orderbooks) {
            delete this.orderbooks[symbol];
        }
        this.orderbooks[symbol] = this.orderBook ({}, limit);
    }

    handleOrderBookSubscriptions (client, message, marketIds) {
        const name = 'book';
        for (let i = 0; i < marketIds.length; i++) {
            const marketId = this.safeString (marketIds, i);
            if (marketId in this.markets_by_id) {
                const market = this.markets_by_id[marketId];
                const symbol = market['symbol'];
                const messageHash = name + '@' + marketId;
                if (!(symbol in this.orderbooks)) {
                    const subscription = this.safeValue (client.subscriptions, messageHash);
                    const method = this.safeValue (subscription, 'method');
                    if (method !== undefined) {
                        method.call (this, client, message, subscription);
                    }
                }
            }
        }
    }

    handleSubscriptionStatus (client, message) {
        //
        //     {
        //         event: 'subscribed',
        //         subscriptions: {
        //             book: [ 'BTC-EUR' ]
        //         }
        //     }
        //
        const subscriptions = this.safeValue (message, 'subscriptions', {});
        const methods = {
            'book': this.handleOrderBookSubscriptions,
            // 'trade': this.handleTrade,
            // 'kline': this.handleOHLCV,
            // 'outboundAccountInfo': this.handleBalance,
            // 'executionReport': this.handleOrder,
        };
        const names = Object.keys (subscriptions);
        for (let i = 0; i < names.length; i++) {
            const name = names[i];
            const method = this.safeValue (methods, name);
            if (method !== undefined) {
                const subscription = this.safeValue (subscriptions, name);
                method.call (this, client, message, subscription);
            }
        }
        return message;
    }

    signMessage (client, messageHash, message, params = {}) {
        // todo: implement signMessage
        return message;
    }

    handleMessage (client, message) {
        //
        //     {
        //         event: 'subscribed',
        //         subscriptions: {
        //             book: [ 'BTC-EUR' ]
        //         }
        //     }
        //
        //
        //     {
        //         event: 'book',
        //         market: 'BTC-EUR',
        //         nonce: 36729561,
        //         bids: [
        //             [ '8513.3', '0' ],
        //             [ '8518.8', '0.64236203' ],
        //             [ '8513.6', '0.32435481' ],
        //         ],
        //         asks: []
        //     }
        //
        //     {
        //         action: 'getBook',
        //         response: {
        //             market: 'BTC-EUR',
        //             nonce: 36946120,
        //             bids: [
        //                 [ '8494.9', '0.24399521' ],
        //                 [ '8494.8', '0.34884085' ],
        //                 [ '8493.9', '0.14535128' ],
        //             ],
        //             asks: [
        //                 [ '8495', '0.46982463' ],
        //                 [ '8495.1', '0.12178267' ],
        //                 [ '8496.2', '0.21924143' ],
        //             ]
        //         }
        //     }
        //
        const methods = {
            'subscribed': this.handleSubscriptionStatus,
            'book': this.handleOrderBook,
            'getBook': this.handleOrderBookSnapshot,
            // 'trade': this.handleTrade,
            // 'kline': this.handleOHLCV,
            'ticker24h': this.handleTicker,
            // 'outboundAccountInfo': this.handleBalance,
            // 'executionReport': this.handleOrder,
        };
        const event = this.safeString (message, 'event');
        let method = this.safeValue (methods, event);
        if (method === undefined) {
            const action = this.safeString (message, 'action');
            method = this.safeValue (methods, action);
            if (method === undefined) {
                const util = require ('util');
                console.log ('handleMessage', util.inspect (message, { showHidden: false, depth: null }));
                process.exit ();
                return message;
            } else {
                return method.call (this, client, message);
            }
        } else {
            return method.call (this, client, message);
        }
    }
};
<|endoftext|>


<commit_before>// Set of the hostnames that are going to be blocked
var blocklistSet = new Set();
var whitelistSet =new Set();
const disconnectJSON = require('../data/disconnect.json');
const disconnectEntitylist = require('../data/disconnectEntitylist.json');
var {allHosts, canonicalizeHost} = require('../js/canonicalize.js');

parseJason();
//parseDisconnectEntity();

chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
    // do the blocking

    var areWeCancelling; // boolean checking blocking status
    var assetAdHost = canonicalizeHost(parseURI(details.url).hostname);

    if(isAd(details.url)) {
    	areWeCancelling = true;
    	console.log("bitch we be blockin " + assetAdHost);
    }

    return {cancel: areWeCancelling};
},{urls:["*://*/*"]}, ["blocking", "requestHeaders"]);

/*
* By Francesco
*
* Edited by Boris Pallres
* @returns true if it is an ad.
*/
function isAd(url) {
  // if url is something like ads.click.com then you would get all the hosts.. click.com
  var getHostAd = allHosts(parseURI(url).hostname);
  console.log("Before "+parseURI(url).hostname);
  console.log("After "+ getHostAd );

  if(whitelistSet.has(getHostAd)){
    //return false;
  }

for (var host in getHostAd){
 	if(blocklistSet.has(getHostAd[host])) {
		return true;
	}
}
return false;

}

function parseURI(url) {
    var match = url.match(/^((https|http)?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
    return match && {
        protocol: match[1],
        host: match[2],
        hostname: match[3],
        port: match[4],
        pathname: match[5],
        search: match[6],
        hash: match[7]
    }
}// end parse url

function parseJason(){

//delete disconnectJSON.categories['Content']
//delete disconnectJSON.categories['Legacy Disconnect']
//delete disconnectJSON.categories['Legacy Content']
	// parse our disconnect JSON into a set where we only include the hostname and subdomain urls
    for(var category in disconnectJSON.categories) {
      //  Advertising, Content ,Analytics, Social, Disconnect
	    for(var network in disconnectJSON.categories[category]) {
 	        for(var hostname in disconnectJSON.categories[category][network]) {
             // 2leep.com , 33Across , 4INFO ,4mads ...... and so on
	            blocklistSet.add(hostname); // add to the set
	            for(var subDomain in disconnectJSON.categories[category][network][hostname]) {
                // gets the subdomain as http://2leep.com/ , http://33across.com/ , http://www.4info.com/
	                for(var entitySubDomain in disconnectJSON.categories[category][network][hostname][subDomain]) {
                    // gets wierd random numbers
	                     blocklistSet.add(disconnectJSON.categories[category][network][hostname][subDomain][entitySubDomain]);
	                }
	            }
	        }
	      }
    }

}// end parse Jason

/*
function parseDisconnectEntity(){

  for(var network in disconnectEntitylist) {
     for(var type in disconnectEntitylist[network]) {
        for(var resources in disconnectEntitylist[network][type]) {
          whitelistSet.add(disconnectEntitylist[network][type][resources]);
        }

    }
  }

}
*/
<commit_msg>Fixed Jason. Poor Jason dude<commit_after>// Set of the hostnames that are going to be blocked
var blocklistSet = new Set();
var whitelistSet =new Set();
const disconnectJSON = require('../data/disconnect.json');
const disconnectEntitylist = require('../data/disconnectEntitylist.json');
var {allHosts, canonicalizeHost} = require('../js/canonicalize.js');

parseJSON();
//parseDisconnectEntity();

chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
    // do the blocking

    var areWeCancelling; // boolean checking blocking status
    var assetAdHost = canonicalizeHost(parseURI(details.url).hostname);

    if(isAd(details.url)) {
    	areWeCancelling = true;
    	console.log("bitch we be blockin " + assetAdHost);
    }

    return {cancel: areWeCancelling};
},{urls:["*://*/*"]}, ["blocking", "requestHeaders"]);

/*
* By Francesco
*
* Edited by Boris Pallres
* @returns true if it is an ad.
*/
function isAd(url) {
  // if url is something like ads.click.com then you would get all the hosts.. click.com
  var getHostAd = allHosts(parseURI(url).hostname);
  console.log("Before "+parseURI(url).hostname);
  console.log("After "+ getHostAd );

  if(whitelistSet.has(getHostAd)){
    //return false;
  }

for (var host in getHostAd){
 	if(blocklistSet.has(getHostAd[host])) {
		return true;
	}
}
return false;

}

function parseURI(url) {
    var match = url.match(/^((https|http)?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
    return match && {
        protocol: match[1],
        host: match[2],
        hostname: match[3],
        port: match[4],
        pathname: match[5],
        search: match[6],
        hash: match[7]
    }
}// end parse url

function parseJSON(){

//delete disconnectJSON.categories['Content']
//delete disconnectJSON.categories['Legacy Disconnect']
//delete disconnectJSON.categories['Legacy Content']
	// parse our disconnect JSON into a set where we only include the hostname and subdomain urls
    for(var category in disconnectJSON.categories) {
      //  Advertising, Content ,Analytics, Social, Disconnect
	    for(var network in disconnectJSON.categories[category]) {
 	        for(var hostname in disconnectJSON.categories[category][network]) {
             // 2leep.com , 33Across , 4INFO ,4mads ...... and so on
	            blocklistSet.add(hostname); // add to the set
	            for(var subDomain in disconnectJSON.categories[category][network][hostname]) {
                // gets the subdomain as http://2leep.com/ , http://33across.com/ , http://www.4info.com/
	                for(var entitySubDomain in disconnectJSON.categories[category][network][hostname][subDomain]) {
                    // gets wierd random numbers
	                     blocklistSet.add(disconnectJSON.categories[category][network][hostname][subDomain][entitySubDomain]);
	                }
	            }
	        }
	      }
    }

}// end parse Jason

/*
function parseDisconnectEntity(){

  for(var network in disconnectEntitylist) {
     for(var type in disconnectEntitylist[network]) {
        for(var resources in disconnectEntitylist[network][type]) {
          whitelistSet.add(disconnectEntitylist[network][type][resources]);
        }

    }
  }

}
*/
<|endoftext|>


<commit_before>/*
		=========================================================================================
 		*
		*	BrowserJS
 		*
 		=========================================================================================
		*----------------------------------------------------------------------------------------
 		*
 		*	lets you know which browser you're using as well as if it's a mobile device and touch enabled
 		*
 		=========================================================================================
		*
		*   author          >>  Christopher Miles
		*
		*   site            >>  http://ChristopherMil.es
		*   github          >>  http://github.com/creatologist
		*
		=========================================================================================
*/

//===============================================================================================
//-----------------------------------------------------------------------------------------------

var Browser = function() {

	this.userAgent = navigator.userAgent;
	this.ua = this.userAgent.toLowerCase();

	if ( window.orientation != undefined ) this.mobile = true;
	else this.mobile = false;

	if ( 'ontouchstart' in window || 'onmsgesturechange' in window ) this.touch = true;
	else this.touch = false;

	this.name = null;
	this.version = null;

	this.device = false;

	// work on later
	/*this.os = {
		name			: null,
		version			: null,
		versionFull		: null
	};*/

	this.ielt9 = false;

	this.deviceDetected = function( name ) {
		this.device = {
			name			: name,
			osVersion 		: null,
			osVersionFull 	: null
		};
	};

	if ( this.ua.indexOf( 'iphone' ) != -1 ) {
		this.deviceDetected( 'iphone' );
	} else if ( this.ua.indexOf( 'ipad' ) != -1 ) {
		this.deviceDetected( 'ipad' );
	} else if ( this.ua.indexOf( 'android' ) != -1 ) {
		this.deviceDetected( 'android' );
		if ( this.ua.indexOf( 'version/' ) != -1 ) this.device.osVersion = this.ua.split( 'version/' )[1].split( '.' )[0];
		if ( this.ua.indexOf( 'android ' ) != -1 ) this.device.osVersionFull = this.ua.split( 'android ' )[1].split( ';' )[0];
	}

	// iphone + ipad - full os version ie: 7.0.3
	if ( this.device !== null && ( this.device.name == 'iphone' || this.device.name == 'ipad' ) ) {
		if ( this.ua.indexOf( 'version/' ) != -1 ) this.device.osVersion = this.ua.split( 'version/' )[1].split( '.' )[0];
		if ( this.userAgent.indexOf( ' OS ' ) ) {
			if ( this.userAgent.indexOf( ' like ' ) ) this.device.osVersionFull = this.userAgent.split( ' OS ' )[1].split( ( ' like ' ) )[0].split( '_' ).join( '.' );
		}
	}

	this.name = this.ua.match( /android/gi );
	if ( this.name == null ) this.name = this.ua.match( /chrome/gi );
	if ( this.name == null ) this.name = this.ua.match( /safari/gi );
	if ( this.name == null ) this.name = this.ua.match( /firefox/gi );
	if ( this.name == null ) this.name = this.ua.match( /msie/gi );

	if ( this.name && this.name instanceof Array ) this.name = this.name[0];

	switch( this.name ) {
		case 'android':
			if ( this.ua.indexOf( 'version/' ) != -1 ) this.version = this.ua.split( 'version/' )[1].split( '.' )[0];
			if ( this.ua.indexOf( 'android ' ) != -1 ) {
				this.fullVersion = this.ua.split( 'android ' )[1].split( ';' )[0];
			}
			break;
		case 'chrome':
			if ( this.ua.indexOf( 'chrome/' ) != -1 ) this.version = this.ua.split( 'chrome/' )[1].split( '.' )[0];
			break;
		case 'safari':
			if ( this.ua.indexOf( 'crios/' ) != -1 ) {
				// ios Chrome app
				this.name = 'chrome';
				this.version = this.ua.split( 'crios/' )[1].split( '.' )[0];
			} else if ( this.ua.indexOf( 'version/' ) != -1 ) {
				this.version = this.ua.split( 'version/' )[1].split( '.' )[0];
			}
			break;
		case 'firefox':
			if ( this.ua.indexOf( 'firefox/' ) != -1 ) this.version = this.ua.split( 'firefox/' )[1].split( '.' )[0];
			break;
		case 'msie':
			this.name = 'ie';
			if ( this.ua.indexOf( 'msie ' ) != -1 ) this.version = this.ua.split( 'msie ' )[1].split( '.' )[0];
			else if ( this.ua.indexOf( 'msie/' ) != -1 ) this.version = this.ua.split( 'msie/' )[1].split( '.' )[0];

				if ( this.version < 9 ) this.ielt9 = true;
				break;
	}

	if ( this.device && this.device.osVersion ) this.device.osVersion = Number( this.device.osVersion );
	if ( this.version ) this.version = Number( this.version );

	delete( this.ua );
	delete( this.userAgent );
	delete( this.deviceDetected );

};<commit_msg>updates<commit_after>/*
		=========================================================================================
 		*
		*	BrowserJS
 		*
 		=========================================================================================
		*----------------------------------------------------------------------------------------
 		*
 		*	lets you know which browser you're using as well as if it's a mobile device and touch enabled
 		*
 		=========================================================================================
		*
		*   author          >>  Christopher Miles
		*
		*   site            >>  http://ChristopherMil.es
		*   github          >>  http://github.com/creatologist
		*
		=========================================================================================
*/

//===============================================================================================
//-----------------------------------------------------------------------------------------------

var Browser = function() {

	this.userAgent = navigator.userAgent;
	this.ua = this.userAgent.toLowerCase();

	this.name = null;
	this.version = null;

	if ( window.orientation != undefined ) this.mobile = true;
	else this.mobile = false;

	if ( 'ontouchstart' in window || 'onmsgesturechange' in window ) this.touch = true;
	else this.touch = false;

	this.osDetected = function( name ) {
		// work on later - ie: Mac OSX 10.8.5
		this.os = {
			name			: name,
			version			: null,
			versionFull		: null
		};
	};

	this.deviceDetected = function( name ) {
		this.device = {
			name			: name,
			osVersion 		: null,
			osVersionFull 	: null
		};
	};

	if ( this.ua.indexOf( 'iphone' ) != -1 ) {
		this.deviceDetected( 'iphone' );
	} else if ( this.ua.indexOf( 'ipad' ) != -1 ) {
		this.deviceDetected( 'ipad' );
	} else if ( this.ua.indexOf( 'android' ) != -1 ) {
		this.deviceDetected( 'android' );
		if ( this.ua.indexOf( 'version/' ) != -1 ) this.device.osVersion = this.ua.split( 'version/' )[1].split( '.' )[0];
		if ( this.ua.indexOf( 'android ' ) != -1 ) this.device.osVersionFull = this.ua.split( 'android ' )[1].split( ';' )[0];
	}

	// iphone + ipad - full os version ie: 7.0.3
	if ( this.device && ( this.device.name == 'iphone' || this.device.name == 'ipad' ) ) {
		if ( this.ua.indexOf( 'version/' ) != -1 ) this.device.osVersion = this.ua.split( 'version/' )[1].split( '.' )[0];
		if ( this.userAgent.indexOf( ' OS ' ) ) {
			if ( this.userAgent.indexOf( ' like ' ) ) this.device.osVersionFull = this.userAgent.split( ' OS ' )[1].split( ( ' like ' ) )[0].split( '_' ).join( '.' );
		}
	}

	this.ielt9 = false;

	this.name = this.ua.match( /android/gi );
	if ( this.name == null ) this.name = this.ua.match( /chrome/gi );
	if ( this.name == null ) this.name = this.ua.match( /safari/gi );
	if ( this.name == null ) this.name = this.ua.match( /firefox/gi );
	if ( this.name == null ) this.name = this.ua.match( /msie/gi );

	if ( this.name && this.name instanceof Array ) this.name = this.name[0];

	switch( this.name ) {
		case 'android':
			if ( this.ua.indexOf( 'version/' ) != -1 ) this.version = this.ua.split( 'version/' )[1].split( '.' )[0];
			if ( this.ua.indexOf( 'android ' ) != -1 ) {
				this.fullVersion = this.ua.split( 'android ' )[1].split( ';' )[0];
			}
			break;
		case 'chrome':
			if ( this.ua.indexOf( 'chrome/' ) != -1 ) this.version = this.ua.split( 'chrome/' )[1].split( '.' )[0];
			break;
		case 'safari':
			if ( this.ua.indexOf( 'crios/' ) != -1 ) {
				// ios Chrome app
				this.name = 'chrome';
				this.version = this.ua.split( 'crios/' )[1].split( '.' )[0];
			} else if ( this.ua.indexOf( 'version/' ) != -1 ) {
				this.version = this.ua.split( 'version/' )[1].split( '.' )[0];
			}
			break;
		case 'firefox':
			if ( this.ua.indexOf( 'firefox/' ) != -1 ) this.version = this.ua.split( 'firefox/' )[1].split( '.' )[0];
			break;
		case 'msie':
			this.name = 'ie';
			if ( this.ua.indexOf( 'msie ' ) != -1 ) this.version = this.ua.split( 'msie ' )[1].split( '.' )[0];
			else if ( this.ua.indexOf( 'msie/' ) != -1 ) this.version = this.ua.split( 'msie/' )[1].split( '.' )[0];

				if ( this.version < 9 ) this.ielt9 = true;
				break;
	}

	if ( this.device && this.device.osVersion ) this.device.osVersion = Number( this.device.osVersion );
	if ( this.version ) this.version = Number( this.version );

	delete( this.ua );
	delete( this.userAgent );
	delete( this.deviceDetected );
	delete( this.osDetected );

};<|endoftext|>


<commit_before>var firstChecked = false;
var secondChecked = false;
var thirdChecked = false;

var firstAnswer = "sorsa";
var secondAnswer = "sorsa";
var thirdAnswer = "sorsa";

var words_raw = '{"words":[{"fi":"Lyödä, iskeä","eng1":"strike","eng2":"struck","eng3":"struck"},{"fi":"Lyödä, osua","eng1":"hit","eng2":"hit","eng3":"hit"},{"fi":"Lyödä Vetoa","eng1":"bet","eng2":"bet","eng3":"bet"},{"fi":"Lyödä, voittaa","eng1":"beat","eng2":"beat","eng3":"beaten"},{"fi":"Lähettää","eng1":"send","eng2":"sent","eng3":"sent"},{"fi":"Lähteä","eng1":"leave","eng2":"left","eng3":"left"},{"fi":"Löytää","eng1":"find","eng2":"found","eng3":"found"},{"fi":"Maata, olla","eng1":"lie","eng2":"lay","eng3":"lain"},{"fi":"Maksaa","eng1":"pay","eng2":"paid","eng3":"paid"},{"fi":"Maksaa, olla hintana","eng1":"cost","eng2":"cost","eng3":"cost"},{"fi":"Menettää","eng1":"lose","eng2":"lost","eng3":"lost"},{"fi":"Mennä","eng1":"go","eng2":"went","eng3":"gone"},{"fi":"Myydä","eng1":"sell","eng2":"sold","eng3":"sold"},{"fi":"Nousta","eng1":"rise","eng2":"rose","eng3":"risen"},{"fi":"Nukkua","eng1":"sleep","eng2":"slept","eng3":"slept"}]}'
var UsedWords = [];

//Word Checkers
	function CheckWord1() {
		var value = document.getElementById("1").value;
			if (value.toLowerCase() == firstAnswer.toLowerCase()) {
			$("#1").css('border-color', '#26A65B');
			firstChecked = true;
			document.getElementById("2").focus();
		} else if(value == "") {
			$("#1").css('border-color', '#1abc9c');
			firstChecked = false;
		}
		else{
			$("#1").css('border-color', '#c0392b');
			firstChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord2() {
		var value = document.getElementById("2").value;
			if (value.toLowerCase() == secondAnswer.toLowerCase()) {
			$("#2").css('border-color', '#26A65B');
			secondChecked = true;
			document.getElementById("3").focus();
		} else if(value == "") {
			$("#2").css('border-color', '#1abc9c');
			secondChecked = false;
		}
		else{
			$("#2").css('border-color', '#c0392b');
			secondChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord3() {
		var value = document.getElementById("3").value;
			if (value.toLowerCase() == thirdAnswer.toLowerCase()) {
			$("#3").css('border-color', '#26A65B');
			thirdChecked = true;
		} else if(value == "") {
			$("#3").css('border-color', '#1abc9c');
			thirdChecked = false;
		}
		else{
			$("#3").css('border-color', '#c0392b');
			thirdChecked = false;
		};
		CheckAnswers();
	}

//TODO: Improve this function
//Retrieve a new word
function GetRandomInt() {
	var isOk = false;
	var num = 30;
	while (isOk == false) {
		num = Math.floor((Math.random() * 15) + 1);
		var passed = 0;
		if(UsedWords.length != 0) {
			for (var i = 0; i < UsedWords.length; i++) {

				if (num == UsedWords[i]) {
					num = Math.floor((Math.random() * 15) + 1);
					i = 0;
				}
				else
				{
					passed++;
				}
			};
		}
		else isOk = true;

		if(passed == UsedWords.length) isOk = true;
	}
	UsedWords.push(num);
	return num;
}

//Self Explanatory
function CheckAnswers() {
	if (firstChecked == true && secondChecked == true && thirdChecked == true) {
		ProceedToNext()
	}
}

function ProceedToNext() {
	//Flash Background
	$("body").css('background-color', '#27ae60');

	//Clear Boxes
	document.getElementById("1").value = "";
	document.getElementById("2").value = "";
	document.getElementById("3").value = "";

	//Reset Vars
	firstChecked = false;
	secondChecked = false;
	thirdChecked = false;

	if(UsedWords.length != 15) {
		//Start Again
		onStart();
	}
	else
	{
		//redirect to winning site
		/TODO: Make some fancy js thingy
		instead of loading a different site/
		window.location.replace("win.html");
	}
}

function showAnswers() {
	var button = document.getElementById("btn");
	if (button.innerHTML == "Nyt en kyllä tiedä")
	{
		document.getElementById("1").value = firstAnswer;
		document.getElementById("2").value = secondAnswer;
		document.getElementById("3").value = thirdAnswer;

		button.innerHTML = "Seuraava Kysymys";

	}
	else
	{
		button.innerHTML = "Nyt en kyllä tiedä";
		ProceedToNext();
	}

}

//Gets run on startup
function onStart() {
	document.getElementById("1").focus();
	words = JSON.parse(words_raw);
	var index = GetRandomInt();
	index--;
	$("#fi-txt").text(words.words[index].fi)
	$("#counter").text(UsedWords.length-1 + "/15 Suoritettu")
	firstAnswer = words.words[index].eng1
	secondAnswer = words.words[index].eng2
	thirdAnswer = words.words[index].eng3
}

//Wait for site to load
jQuery(document).ready(onStart);<commit_msg>Rewrote GetRandomInt() to be more reliable and efficient.<commit_after>var firstChecked = false;
var secondChecked = false;
var thirdChecked = false;

var firstAnswer = "sorsa";
var secondAnswer = "sorsa";
var thirdAnswer = "sorsa";

var words_raw = '{"words":[{"fi":"Lyödä, iskeä","eng1":"strike","eng2":"struck","eng3":"struck"},{"fi":"Lyödä, osua","eng1":"hit","eng2":"hit","eng3":"hit"},{"fi":"Lyödä Vetoa","eng1":"bet","eng2":"bet","eng3":"bet"},{"fi":"Lyödä, voittaa","eng1":"beat","eng2":"beat","eng3":"beaten"},{"fi":"Lähettää","eng1":"send","eng2":"sent","eng3":"sent"},{"fi":"Lähteä","eng1":"leave","eng2":"left","eng3":"left"},{"fi":"Löytää","eng1":"find","eng2":"found","eng3":"found"},{"fi":"Maata, olla","eng1":"lie","eng2":"lay","eng3":"lain"},{"fi":"Maksaa","eng1":"pay","eng2":"paid","eng3":"paid"},{"fi":"Maksaa, olla hintana","eng1":"cost","eng2":"cost","eng3":"cost"},{"fi":"Menettää","eng1":"lose","eng2":"lost","eng3":"lost"},{"fi":"Mennä","eng1":"go","eng2":"went","eng3":"gone"},{"fi":"Myydä","eng1":"sell","eng2":"sold","eng3":"sold"},{"fi":"Nousta","eng1":"rise","eng2":"rose","eng3":"risen"},{"fi":"Nukkua","eng1":"sleep","eng2":"slept","eng3":"slept"}]}'
var words;
var UsedWords = [];
var WordCount = 0;

//Word Checkers
	function CheckWord1() {
		var value = document.getElementById("1").value;
			if (value.toLowerCase() == firstAnswer.toLowerCase()) {
			$("#1").css('border-color', '#26A65B');
			firstChecked = true;
			document.getElementById("2").focus();
		} else if(value == "") {
			$("#1").css('border-color', '#1abc9c');
			firstChecked = false;
		}
		else{
			$("#1").css('border-color', '#c0392b');
			firstChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord2() {
		var value = document.getElementById("2").value;
			if (value.toLowerCase() == secondAnswer.toLowerCase()) {
			$("#2").css('border-color', '#26A65B');
			secondChecked = true;
			document.getElementById("3").focus();
		} else if(value == "") {
			$("#2").css('border-color', '#1abc9c');
			secondChecked = false;
		}
		else{
			$("#2").css('border-color', '#c0392b');
			secondChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord3() {
		var value = document.getElementById("3").value;
			if (value.toLowerCase() == thirdAnswer.toLowerCase()) {
			$("#3").css('border-color', '#26A65B');
			thirdChecked = true;
		} else if(value == "") {
			$("#3").css('border-color', '#1abc9c');
			thirdChecked = false;
		}
		else{
			$("#3").css('border-color', '#c0392b');
			thirdChecked = false;
		};
		CheckAnswers();
	}

//Retrieve a new word
function GetRandomInt() {
	num = Math.floor((Math.random() * words.words.length) + 1);
	words.words.splice(num, 1);
	WordCount++;
	return num;

}

//Self Explanatory
function CheckAnswers() {
	if (firstChecked == true && secondChecked == true && thirdChecked == true) {
		ProceedToNext()
	}
}

function ProceedToNext() {
	//Flash Background
	$("body").css('background-color', '#27ae60');

	//Clear Boxes
	document.getElementById("1").value = "";
	document.getElementById("2").value = "";
	document.getElementById("3").value = "";

	//Reset Vars
	firstChecked = false;
	secondChecked = false;
	thirdChecked = false;

	if(WordCount != 14) {
		//Start Again
		onStart();
	}
	else
	{
		//redirect to winning site
		/*TODO: Make some fancy js thingy
		instead of loading a different site*/
		window.location.replace("win.html");
	}
}

function showAnswers() {
	var button = document.getElementById("btn");
	if (button.innerHTML == "Nyt en kyllä tiedä")
	{
		document.getElementById("1").value = firstAnswer;
		document.getElementById("2").value = secondAnswer;
		document.getElementById("3").value = thirdAnswer;

		button.innerHTML = "Seuraava Kysymys";

	}
	else
	{
		button.innerHTML = "Nyt en kyllä tiedä";
		ProceedToNext();
	}

}

//Gets ran on startup
function onStart() {
	document.getElementById("1").focus();
	words = JSON.parse(words_raw);
	var index = GetRandomInt();
	index--;
	$("#fi-txt").text(words.words[index].fi)
	$("#counter").text(WordCount + "/15 Suoritettu")
	firstAnswer = words.words[index].eng1
	secondAnswer = words.words[index].eng2
	thirdAnswer = words.words[index].eng3
}

//Wait for site to load
jQuery(document).ready(function($) {
	onStart();
	WordCount--;
	$("#counter").text(WordCount + "/15 Suoritettu")
});<|endoftext|>


<commit_before><commit_msg>fix(classes): lint<commit_after><|endoftext|>


<commit_before>var senateData;
var perfStart;

function getRegExpString(senator) {
  var title = '(Senator|Sen\\.|Congressman|Congresswoman)';
  var optionalQuote = '(\'|")?';
  var wildCardMiddle = optionalQuote + '(\\w*)(\\.)?' + optionalQuote;
  var upToTwoWildCardMiddles = '\\s*' + wildCardMiddle + '\\s*' + wildCardMiddle + '\\s*';
  var firstLast = '\\b' + senator.firstName + '\\b' + upToTwoWildCardMiddles + '\\b' + senator.lastName + '\\b';
  var lastFirst = '\\b' + senator.lastName + ',\\b' + senator.firstName + '\\b';
  var titleLast = '\\b' + title + '\\s*' + senator.lastName + '\\b';
  var nicknames = '';
  var regExpString = '';

  function getNicknameString (nickname, lastName) {
    return '|\\b' + nickname + '\\b' + upToTwoWildCardMiddles + '\\b' + lastName + '\\b|\\b' + lastName + '\\b,\\b' + nickname + '\\b';
  }

  if (senator.nicknames) {
    if (Array.isArray(senator.nicknames)) {
      for (var i = 0; i < senator.nicknames.length; i++) {
        nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
      }
    } else if (typeof senator.nicknames === 'string') {
      nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
    }
  }

  regExpString += title + '?' + '(' + firstLast + nicknames + ')|' + titleLast + '|' + lastFirst;

  return regExpString;
}

function getLastNamesRegExp() {
  var lastNamesRegExpArr = [];

  for (var i = 0; i < senateData.length; i++) {
    lastNamesRegExpArr.push('\\b' + senateData[i].lastName + '\\b');
  }

  return new RegExp(lastNamesRegExpArr.join('|'), 'ig');
}

function scan(markContext) {
  var lastNamesRegExp = getLastNamesRegExp();
  var lastNames = document.body.innerText.match(lastNamesRegExp);

  if (lastNames) {
    var foundLastNames = _.uniq(lastNames);
    var foundLastNamesRegExpArr = [];
    var foundLastNamesRegExp;

    for (var i = 0; i < senateData.length; i++) {
      if (foundLastNames.indexOf(senateData[i].lastName) > -1) {
        var senatorRegEx = '(' + getRegExpString(senateData[i]) + ')';
        foundLastNamesRegExpArr.push(senatorRegEx);
      }
    }

    if (foundLastNamesRegExpArr.length) {
      foundLastNamesRegExp = new RegExp(foundLastNamesRegExpArr.join('|'), 'ig');

      markContext.markRegExp(foundLastNamesRegExp, {
        element: 'span',
        className: 'dial-congress',
        done: function(x) {
          var perfEnd = performance.now();
          var perfTime = Math.round(perfEnd - perfStart) / 1000;
          console.log('Dial Congress scan of DOM complete: ' + perfTime + ' seconds');
          console.log('Congress critters found: ' + x);
        }
      });

      bindHoverEvents();
    }
  }
}

function bindHoverEvents() {
  $marks = $('.dial-congress');
  $marks.on('mouseenter', matchSenatorToMark);
}

function matchSenatorToMark(e) {
  var $el = $(e.target);
  var text = $el.text();

  for(var i = 0; i < senateData.length; i++) {
    var regExp = new RegExp(getRegExpString(senateData[i]), 'ig');

    if (text.match(regExp)) {
      buildTooltip($el, senateData[i]);
      $el.off('mouseenter', matchSenatorToMark);
      break;
    }
  }
}

function buildTooltip($el, senator) {
  track({
    eventName: 'tooltip-built',
    congressman: senator.firstName + ' ' + senator.lastName,
    text: $el.text()
  });

  $el.attr('title', senator.party + '/' + senator.state + ': ' + senator.phone);

  $el.tooltipster({
    functionReady: function() {
      track({
        eventName: 'tooltip-hover',
        congressman: senator.firstName + ' ' + senator.lastName,
        text: $el.text()
      });
    },
    interactive: true,
    theme: ['tooltipster-noir', 'tooltipster-noir-customized']
  });

  $el.tooltipster('open');
}

function watchForDOMChanges() {
  // don't scan more than once every 2 seconds
  // var debouncedScan = _.debounce(scan, 2000, true);

  // Fire on mutations
  // thx: https://davidwalsh.name/mutationobserver-api
  var observer = new MutationObserver(function(mutations) {
    // TODO: We could just scan added nodes from childList...

    mutations.forEach(function(mutation) {
      if (mutation.addedNodes.length) {
        mutation.addedNodes.forEach(function(node) {
          var nodeContext = new Mark(node);

          perfStart = performance.now();
          scan(nodeContext);
        })
      }
    });

    // perfStart = performance.now();
    // debouncedScan();
  });

  // Notify me of everything!
  var observerConfig = {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true
  };

  // Node, config
  // In this case we'll listen to all changes to body and child nodes
  var targetNode = document.body;
  observer.observe(targetNode, observerConfig);
}

function track(data) {
  chrome.runtime.sendMessage(data, function(response) {
    // console.log('message received', response);
  });
}

$(document).ready(function() {
  $.when(
    $.get(chrome.extension.getURL('js/senate.json'), function(data) {
      senateData = JSON.parse(data);
    })
  ).then(function() {
    var bodyMarkContext = new Mark(document.body);

    perfStart = performance.now();
    scan(bodyMarkContext);

    watchForDOMChanges();
  });

});
<commit_msg>Restrict mutation observations<commit_after>var senateData;
var perfStart;

function getRegExpString(senator) {
  var title = '(Senator|Sen\\.|Congressman|Congresswoman)';
  var optionalQuote = '(\'|")?';
  var wildCardMiddle = optionalQuote + '(\\w*)(\\.)?' + optionalQuote;
  var upToTwoWildCardMiddles = '\\s*' + wildCardMiddle + '\\s*' + wildCardMiddle + '\\s*';
  var firstLast = '\\b' + senator.firstName + '\\b' + upToTwoWildCardMiddles + '\\b' + senator.lastName + '\\b';
  var lastFirst = '\\b' + senator.lastName + ',\\b' + senator.firstName + '\\b';
  var titleLast = '\\b' + title + '\\s*' + senator.lastName + '\\b';
  var nicknames = '';
  var regExpString = '';

  function getNicknameString (nickname, lastName) {
    return '|\\b' + nickname + '\\b' + upToTwoWildCardMiddles + '\\b' + lastName + '\\b|\\b' + lastName + '\\b,\\b' + nickname + '\\b';
  }

  if (senator.nicknames) {
    if (Array.isArray(senator.nicknames)) {
      for (var i = 0; i < senator.nicknames.length; i++) {
        nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
      }
    } else if (typeof senator.nicknames === 'string') {
      nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
    }
  }

  regExpString += title + '?' + '(' + firstLast + nicknames + ')|' + titleLast + '|' + lastFirst;

  return regExpString;
}

function getLastNamesRegExp() {
  var lastNamesRegExpArr = [];

  for (var i = 0; i < senateData.length; i++) {
    lastNamesRegExpArr.push('\\b' + senateData[i].lastName + '\\b');
  }

  return new RegExp(lastNamesRegExpArr.join('|'), 'ig');
}

function scan(markContext) {
  var lastNamesRegExp = getLastNamesRegExp();
  var lastNames = document.body.innerText.match(lastNamesRegExp);

  if (lastNames) {
    var foundLastNames = _.uniq(lastNames);
    var foundLastNamesRegExpArr = [];
    var foundLastNamesRegExp;

    for (var i = 0; i < senateData.length; i++) {
      if (foundLastNames.indexOf(senateData[i].lastName) > -1) {
        var senatorRegEx = '(' + getRegExpString(senateData[i]) + ')';
        foundLastNamesRegExpArr.push(senatorRegEx);
      }
    }

    if (foundLastNamesRegExpArr.length) {
      foundLastNamesRegExp = new RegExp(foundLastNamesRegExpArr.join('|'), 'ig');

      markContext.markRegExp(foundLastNamesRegExp, {
        element: 'span',
        className: 'dial-congress',
        done: function(x) {
          var perfEnd = performance.now();
          var perfTime = Math.round(perfEnd - perfStart) / 1000;
          console.log('Dial Congress scan of DOM complete: ' + perfTime + ' seconds');
          console.log('Congress critters found: ' + x);
        }
      });

      bindHoverEvents();
    }
  }
}

function bindHoverEvents() {
  $marks = $('.dial-congress');
  $marks.on('mouseenter', matchSenatorToMark);
}

function matchSenatorToMark(e) {
  var $el = $(e.target);
  var text = $el.text();

  for(var i = 0; i < senateData.length; i++) {
    var regExp = new RegExp(getRegExpString(senateData[i]), 'ig');

    if (text.match(regExp)) {
      buildTooltip($el, senateData[i]);
      $el.off('mouseenter', matchSenatorToMark);
      break;
    }
  }
}

function buildTooltip($el, senator) {
  track({
    eventName: 'tooltip-built',
    congressman: senator.firstName + ' ' + senator.lastName,
    text: $el.text()
  });

  $el.attr('title', senator.party + '/' + senator.state + ': ' + senator.phone);

  $el.tooltipster({
    functionReady: function() {
      track({
        eventName: 'tooltip-hover',
        congressman: senator.firstName + ' ' + senator.lastName,
        text: $el.text()
      });
    },
    interactive: true,
    theme: ['tooltipster-noir', 'tooltipster-noir-customized']
  });

  $el.tooltipster('open');
}

function watchForDOMChanges() {
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.addedNodes.length) {
        mutation.addedNodes.forEach(function(node) {
          var $node = $(node);

          if (!$node.hasClass('tooltipster-base') && !$node.is(':empty')) {
            var nodeContext = new Mark(node);

            perfStart = performance.now();
            scan(nodeContext);
          }
        })
      }
    });
  });

  var observerConfig = {
    childList: true,
    subtree: true
  };

  var targetNode = document.body;
  observer.observe(targetNode, observerConfig);
}

function track(data) {
  chrome.runtime.sendMessage(data, function(response) {
    // console.log('message received', response);
  });
}

$(document).ready(function() {
  $.when(
    $.get(chrome.extension.getURL('js/senate.json'), function(data) {
      senateData = JSON.parse(data);
    })
  ).then(function() {
    var bodyMarkContext = new Mark(document.body);

    perfStart = performance.now();
    scan(bodyMarkContext);

    watchForDOMChanges();
  });

});
<|endoftext|>


<commit_before>var options = [];
var optionsGet = 'options';
var showFileSize = '';
var displayBlock = $('<div>').appendTo('body');
	displayBlock.css({
		position: 'fixed',
		padding: '1px',
		zIndex: '9999',
		display: 'none',
		fontFamily: 'Consolas, "Lucida Console", "Courier New", Courier, monospace',
	});

chrome.extension.sendRequest(optionsGet, function(response) {
	displayBlock.css({
		color: response[0],
		fontSize: response[1] + 'px',
		lineHeight: response[1] + 'px',
		backgroundColor: response[2],
		border: '1px solid ' + response[3],
		borderRadius: response[4] + 'px'
	});
	showFileSize = response[5];
	switch (response[6]) {
		case 'topLeft':
			displayBlock.css({
				top: '1px',
				left: '1px'
			})
			break
		case 'topRight':
			displayBlock.css({
				top: '1px',
				right: '1px'
			})
			break
		case 'bottomLeft':
			displayBlock.css({
				bottom: '1px',
				left: '1px'
			})
			break
		case 'bottomRight':
			displayBlock.css({
				bottom: '1px',
				right: '1px'
			})
	}
});

$(document).on('mouseenter', 'img', function() {
	var image = this;
	var imageSource = this.src;

	if (showFileSize == 'on') {
		var requestSize = $.ajax({
			type: 'HEAD',
			url: imageSource,
			success: function() {
				var fileSizeBytes = requestSize.getResponseHeader('Content-length');

				function updateBlock(context) {
					displayBlock.text(image.width + 'x' + image.height + ' | ' + context);
					if (image.width != image.naturalWidth || image.height != image.naturalHeight) {
						displayBlock.text(image.width + 'x' + image.height + ' (' + image.naturalWidth + 'x' + image.naturalHeight + ')' + ' | ' + context);
					}
				}

				if (fileSizeBytes == null) {
					return;
				} else if (fileSizeBytes < 1024) {
					updateBlock(fileSizeBytes + ' B');
				} else if (fileSizeBytes / 1024 < 1024) {
					updateBlock((fileSizeBytes / 1024).toFixed(2) + ' KiB');
				} else {
					updateBlock((fileSizeBytes / 1048576).toFixed(2) + ' MiB');
				}
			}
		});
	}

	displayBlock.text(this.width + 'x' + this.height);
	if (this.width != this.naturalWidth || this.height != this.naturalHeight) {
		displayBlock.text(this.width + 'x' + this.height + ' (' + this.naturalWidth + 'x' + this.naturalHeight + ')');
	}
	$(displayBlock).fadeIn(70);
});

$(document).on('mouseleave', 'img', function() {
	$(displayBlock).fadeOut(10);
});<commit_msg>Minor formatting improvements: Terminate statements with semicolons.<commit_after>var options = [];
var optionsGet = 'options';
var showFileSize = '';
var displayBlock = $('<div>').appendTo('body');
	displayBlock.css({
		position: 'fixed',
		padding: '1px',
		zIndex: '9999',
		display: 'none',
		fontFamily: 'Consolas, "Lucida Console", "Courier New", Courier, monospace',
	});

chrome.extension.sendRequest(optionsGet, function(response) {
	displayBlock.css({
		color: response[0],
		fontSize: response[1] + 'px',
		lineHeight: response[1] + 'px',
		backgroundColor: response[2],
		border: '1px solid ' + response[3],
		borderRadius: response[4] + 'px'
	});
	showFileSize = response[5];
	switch (response[6]) {
		case 'topLeft':
			displayBlock.css({
				top: '1px',
				left: '1px'
			});
			break;
		case 'topRight':
			displayBlock.css({
				top: '1px',
				right: '1px'
			});
			break;
		case 'bottomLeft':
			displayBlock.css({
				bottom: '1px',
				left: '1px'
			});
			break;
		case 'bottomRight':
			displayBlock.css({
				bottom: '1px',
				right: '1px'
			});
			break;
	}
});

$(document).on('mouseenter', 'img', function() {
	var image = this;
	var imageSource = this.src;

	if (showFileSize == 'on') {
		var requestSize = $.ajax({
			type: 'HEAD',
			url: imageSource,
			success: function() {
				var fileSizeBytes = requestSize.getResponseHeader('Content-length');

				function updateBlock(context) {
					displayBlock.text(image.width + 'x' + image.height + ' | ' + context);
					if (image.width != image.naturalWidth || image.height != image.naturalHeight) {
						displayBlock.text(image.width + 'x' + image.height + ' (' + image.naturalWidth + 'x' + image.naturalHeight + ')' + ' | ' + context);
					}
				}

				if (fileSizeBytes == null) {
					return;
				} else if (fileSizeBytes < 1024) {
					updateBlock(fileSizeBytes + ' B');
				} else if (fileSizeBytes / 1024 < 1024) {
					updateBlock((fileSizeBytes / 1024).toFixed(2) + ' KiB');
				} else {
					updateBlock((fileSizeBytes / 1048576).toFixed(2) + ' MiB');
				}
			}
		});
	}

	displayBlock.text(this.width + 'x' + this.height);
	if (this.width != this.naturalWidth || this.height != this.naturalHeight) {
		displayBlock.text(this.width + 'x' + this.height + ' (' + this.naturalWidth + 'x' + this.naturalHeight + ')');
	}
	$(displayBlock).fadeIn(70);
});

$(document).on('mouseleave', 'img', function() {
	$(displayBlock).fadeOut(10);
});<|endoftext|>


<commit_before>var mark;
var senateData;
var perfStart;

function getRegExpString(senator) {
  var title = '(Senator|Sen\\.|Congressman|Congresswoman)';
  var optionalQuote = '(\'|")?';
  var wildCardMiddle = optionalQuote + '(\\w*)(\\.)?' + optionalQuote;
  var upToTwoWildCardMiddles = '\\s*' + wildCardMiddle + '\\s*' + wildCardMiddle + '\\s*';
  var firstLast = '\\b' + senator.firstName + '\\b' + upToTwoWildCardMiddles + '\\b' + senator.lastName + '\\b';
  var lastFirst = '\\b' + senator.lastName + ',\\b' + senator.firstName + '\\b';
  var titleLast = '\\b' + title + '\\s*' + senator.lastName + '\\b';
  var nicknames = '';
  var regExpString = '';

  function getNicknameString (nickname, lastName) {
    return '|\\b' + nickname + '\\b' + upToTwoWildCardMiddles + '\\b' + lastName + '\\b|\\b' + lastName + '\\b,\\b' + nickname + '\\b';
  }

  if (senator.nicknames) {
    if (Array.isArray(senator.nicknames)) {
      for (var i = 0; i < senator.nicknames.length; i++) {
        nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
      }
    } else if (typeof senator.nicknames === 'string') {
      nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
    }
  }

  regExpString += title + '?' + '(' + firstLast + nicknames + ')|' + titleLast + '|' + lastFirst;

  return regExpString;
}

function getLastNamesRegExp() {
  var lastNamesRegExpString = '';

  for (var i = 0; i < senateData.length; i++) {
    var divider = lastNamesRegExpString.length == 0 ? '' : '|';
    lastNamesRegExpString += divider + '\\b' + senateData[i].lastName + '\\b';
  }

  return new RegExp(lastNamesRegExpString, 'ig');
}

function scan() {
  var lastNamesRegExp = getLastNamesRegExp();
  var foundLastNames = dedupeArray(document.body.innerText.match(lastNamesRegExp));
  var foundLastNamesRegExpString = '';

  for (var i = 0; i < senateData.length; i++) {
    if (foundLastNames.indexOf(senateData[i].lastName) > -1) {
      var divider = foundLastNamesRegExpString.length == 0 ? '' : '|';
      var senatorRegEx = getRegExpString(senateData[i]);
      foundLastNamesRegExpString += divider + '(' + senatorRegEx + ')';
    }
  }

  var foundLastNamesRegExp = new RegExp(foundLastNamesRegExpString, 'ig');

  mark.markRegExp(foundLastNamesRegExp, {
    element: 'span',
    className: 'dial-congress',
    done: function(x) {
      var perfEnd = performance.now();
      var perfTime = Math.round(perfEnd - perfStart) / 1000;
      console.log('Dial Congress scan of DOM complete: ' + perfTime + ' seconds');
      console.log('Congress critters found: ' + x);
    }
  });

  bindHoverEvents();
}

function bindHoverEvents() {
  $marks = $('.dial-congress');
  $marks.on('mouseenter', matchSenatorToMark);
}

function matchSenatorToMark(e) {
  var $el = $(e.target);
  var text = $el.text();

  for(var i = 0; i < senateData.length; i++) {
    var regExp = new RegExp(getRegExpString(senateData[i]), 'ig');

    if (text.match(regExp)) {
      buildTooltip($el, senateData[i]);
      $el.off('mouseenter', matchSenatorToMark);
      break;
    }
  }
}

function buildTooltip($el, senator) {
  track({
    eventName: 'tooltip-built',
    congressman: senator.firstName + ' ' + senator.lastName,
    text: $el.text()
  });

  $el.attr('title', senator.party + '/' + senator.state + ': ' + senator.phone);

  $el.tooltipster({
    functionReady: function() {
      track({
        eventName: 'tooltip-hover',
        congressman: senator.firstName + ' ' + senator.lastName,
        text: $el.text()
      });
    },
    interactive: true,
    theme: ['tooltipster-noir', 'tooltipster-noir-customized']
  });

  $el.tooltipster('open');
}

function track(data) {
  chrome.runtime.sendMessage(data, function(response) {
    // console.log('message received', response);
  });
}

function dedupeArray(a) {
  var seen = {};
  var out = [];
  var len = a.length;
  var j = 0;
  for(var i = 0; i < len; i++) {
    var item = a[i];
    if(seen[item] !== 1) {
      seen[item] = 1;
      out[j++] = item;
    }
  }
  return out;
}

$(document).ready(function() {
  $.when(
    $.get(chrome.extension.getURL('js/senate.json'), function(data) {
      senateData = JSON.parse(data);
    })
  ).then(function() {
    perfStart = performance.now();
    mark = new Mark(document.body);
    scan();
  });
});
<commit_msg>Replace divider logic with array buffer<commit_after>var mark;
var senateData;
var perfStart;

function getRegExpString(senator) {
  var title = '(Senator|Sen\\.|Congressman|Congresswoman)';
  var optionalQuote = '(\'|")?';
  var wildCardMiddle = optionalQuote + '(\\w*)(\\.)?' + optionalQuote;
  var upToTwoWildCardMiddles = '\\s*' + wildCardMiddle + '\\s*' + wildCardMiddle + '\\s*';
  var firstLast = '\\b' + senator.firstName + '\\b' + upToTwoWildCardMiddles + '\\b' + senator.lastName + '\\b';
  var lastFirst = '\\b' + senator.lastName + ',\\b' + senator.firstName + '\\b';
  var titleLast = '\\b' + title + '\\s*' + senator.lastName + '\\b';
  var nicknames = '';
  var regExpString = '';

  function getNicknameString (nickname, lastName) {
    return '|\\b' + nickname + '\\b' + upToTwoWildCardMiddles + '\\b' + lastName + '\\b|\\b' + lastName + '\\b,\\b' + nickname + '\\b';
  }

  if (senator.nicknames) {
    if (Array.isArray(senator.nicknames)) {
      for (var i = 0; i < senator.nicknames.length; i++) {
        nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
      }
    } else if (typeof senator.nicknames === 'string') {
      nicknames += getNicknameString(senator.nicknames[i], senator.lastName);
    }
  }

  regExpString += title + '?' + '(' + firstLast + nicknames + ')|' + titleLast + '|' + lastFirst;

  return regExpString;
}

function getLastNamesRegExp() {
  var lastNamesRegExpArr = [];

  for (var i = 0; i < senateData.length; i++) {
    lastNamesRegExpArr.push('\\b' + senateData[i].lastName + '\\b');
  }

  return new RegExp(lastNamesRegExpArr.join('|'), 'ig');
}

function scan() {
  var lastNamesRegExp = getLastNamesRegExp();
  var foundLastNames = dedupeArray(document.body.innerText.match(lastNamesRegExp));
  var foundLastNamesRegExpArr = [];
  var foundLastNamesRegExp;

  for (var i = 0; i < senateData.length; i++) {
    if (foundLastNames.indexOf(senateData[i].lastName) > -1) {
      var senatorRegEx = '(' + getRegExpString(senateData[i]) + ')';
      foundLastNamesRegExpArr.push(senatorRegEx);
    }
  }

  if (foundLastNamesRegExpArr.length) {
    foundLastNamesRegExp = new RegExp(foundLastNamesRegExpArr.join('|'), 'ig');

    mark.markRegExp(foundLastNamesRegExp, {
      element: 'span',
      className: 'dial-congress',
      done: function(x) {
        var perfEnd = performance.now();
        var perfTime = Math.round(perfEnd - perfStart) / 1000;
        console.log('Dial Congress scan of DOM complete: ' + perfTime + ' seconds');
        console.log('Congress critters found: ' + x);
      }
    });

    bindHoverEvents();
  }
}

function bindHoverEvents() {
  $marks = $('.dial-congress');
  $marks.on('mouseenter', matchSenatorToMark);
}

function matchSenatorToMark(e) {
  var $el = $(e.target);
  var text = $el.text();

  for(var i = 0; i < senateData.length; i++) {
    var regExp = new RegExp(getRegExpString(senateData[i]), 'ig');

    if (text.match(regExp)) {
      buildTooltip($el, senateData[i]);
      $el.off('mouseenter', matchSenatorToMark);
      break;
    }
  }
}

function buildTooltip($el, senator) {
  track({
    eventName: 'tooltip-built',
    congressman: senator.firstName + ' ' + senator.lastName,
    text: $el.text()
  });

  $el.attr('title', senator.party + '/' + senator.state + ': ' + senator.phone);

  $el.tooltipster({
    functionReady: function() {
      track({
        eventName: 'tooltip-hover',
        congressman: senator.firstName + ' ' + senator.lastName,
        text: $el.text()
      });
    },
    interactive: true,
    theme: ['tooltipster-noir', 'tooltipster-noir-customized']
  });

  $el.tooltipster('open');
}

function track(data) {
  chrome.runtime.sendMessage(data, function(response) {
    // console.log('message received', response);
  });
}

function dedupeArray(a) {
  var seen = {};
  var out = [];
  var len = a.length;
  var j = 0;
  for(var i = 0; i < len; i++) {
    var item = a[i];
    if(seen[item] !== 1) {
      seen[item] = 1;
      out[j++] = item;
    }
  }
  return out;
}

$(document).ready(function() {
  $.when(
    $.get(chrome.extension.getURL('js/senate.json'), function(data) {
      senateData = JSON.parse(data);
    })
  ).then(function() {
    perfStart = performance.now();
    mark = new Mark(document.body);
    scan();
  });
});
<|endoftext|>


<commit_before>function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = 'expires=' + d.toGMTString();
    document.cookie = cname+'='+cvalue+'; '+expires;
}

function getCookie(cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}

function checkCookie() {
    var user = getCookie('username');
    if (user == '') {
        nameFormOPen();
    } else {
        nameFormDone = true;
        userCard.innerHTML = user;
        if(userCard.offsetWidth > 200) {
            userCard.classList.remove('usersName');
            userCard.classList.add('usersIcon');
            userCard.innerHTML = '&#xE7FD';
            document.querySelector('.nameCard').innerHTML = user + '

&#xE888';
            nameSmall = true;
        }
    }
}
<commit_msg>error check2<commit_after>function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = 'expires=' + d.toGMTString();
    document.cookie = cname+'='+cvalue+'; '+expires;
}

function getCookie(cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}

function checkCookie() {
    var user = getCookie('username');
    if (user == '') {
        nameFormOPen();
    } else {
        //nameFormDone = true;
        userCard.innerHTML = user;
        if(userCard.offsetWidth > 200) {
            userCard.classList.remove('usersName');
            userCard.classList.add('usersIcon');
            userCard.innerHTML = '&#xE7FD';
            document.querySelector('.nameCard').innerHTML = user + '

&#xE888';
            nameSmall = true;
        }
    }
}
<|endoftext|>


<commit_before>
function Dungeon(scene, player, map) {
	var self = this;
	this.width = map.map[0].length;
	this.depth = map.map.length;
	this.mesh = undefined;
	this.monsters = [];
	this.objects = [];
	var dummy_material = new THREE.MeshBasicMaterial({color: 0x000000});

	map.gridSize *= UNIT;

	var materials = {};
	for (var tex in map.blocks) {
		if (!map.blocks.hasOwnProperty(tex)) continue;
		var floor_mat = map.blocks[tex].floor ? cache.getMaterial(map.blocks[tex].floor) : dummy_material;
		var wall_mat = map.blocks[tex].wall ? cache.getMaterial(map.blocks[tex].wall) : dummy_material;
		var ceiling_mat = map.blocks[tex].ceiling ? cache.getMaterial(map.blocks[tex].ceiling) : dummy_material;
		materials[tex] = [
			wall_mat, // right
			wall_mat, // left
			ceiling_mat, // top
			floor_mat, // bottom
			wall_mat, // back
			wall_mat  // front
		];
	}

	function getCell(x, z) {
		if (x < 0 || x >= map.map[0].length) return "#";
		else if (z < 0 || z >= map.map.length) return "#";
		return map.map[z][x];
	}

	function getObjectHandler(x, y, z, def) {
		return function(geom) {
			if (!def) def = {};
			var obj;
			if (def.collision) {
				var material = Physijs.createMaterial(
					geom.materials[0], 0.7, 0.2); // friction, restition
				if (def.collision == "plane")
					obj = new Physijs.PlaneMesh(geom, material, def.mass);
				else if (def.collision == "box")
					obj = new Physijs.BoxMesh(geom, material, def.mass);
				else if (def.collision == "sphere")
					obj = new Physijs.SphereMesh(geom, material, def.mass);
				else if (def.collision == "cylinder")
					obj = new Physijs.CylinderMesh(geom, material, def.mass);
				else if (def.collision == "cone")
					obj = new Physijs.ConeMesh(geom, material, def.mass);
				else if (def.collision == "convex")
					obj = new Physijs.ConvexMesh(geom, material, def.mass);
				else throw "Unsupported collision mesh type " + def.collision;
				self.objects.push(obj);
			} else {
				obj = new THREE.Mesh(geom, def.faceMaterial ? new THREE.MeshFaceMaterial() : geom.materials[0]);
			}
			// Auto-height
			if (y === null) {
				if (geom.boundingBox)
					y = 2 * (geom.boundingBox.max.y - geom.boundingBox.min.y) + 0.001;
				else if (geom.boundingSphere)
					y = geom.boundingSphere.radius + 0.001;
				else
					y = 0;
			}
			obj.position.set(x, y, z);
			if (!def.noShadows) {
				obj.castShadow = true;
				obj.receiveShadow = true;
			}
			scene.add(obj);
		};
	}

	function getBlockGeometry(materials, sides) {
		return function() {
			return new BlockGeometry(map.gridSize, map.roomHeight, map.gridSize,
				1, 1, 1, materials, sides);
		};
	}

	var cell, cell2, px, nx, pz, nz, py;
	var ambientLight = new THREE.AmbientLight(0xaaaaaa);
	scene.add(ambientLight);

	player.light = new THREE.PointLight(0x88bbff, 1, map.gridSize * 2);
	scene.add(player.light);
	player.shadow = new THREE.SpotLight(player.light.color, player.light.intensity, player.light.distance);
	player.shadow.angle = Math.PI / 4;
	player.shadow.onlyShadow = true;
	player.shadow.castShadow = true;
	player.shadow.shadowCameraNear = 0.1 * UNIT;
	player.shadow.shadowCameraFar = 10 * UNIT;
	player.shadow.shadowCameraFov = 60;
	player.shadow.shadowBias = -0.0002;
	player.shadow.shadowDarkness = 0.3;
	player.shadow.shadowMapWidth = 1024;
	player.shadow.shadowMapHeight = 1024;
	player.shadow.shadowCameraVisible = false;
	scene.add(player.shadow);

	// TODO: Set player rotation
	player.position.set(map.start[0] * map.gridSize, map.roomHeight, map.start[1] * map.gridSize);

	var geometry = new THREE.Geometry(), light, light2, light_body, obj;
	var sphere = new THREE.SphereGeometry(0.05 * UNIT, 16, 8);

	for (var z = 0; z < this.depth; z++) {
		for (var x = 0; x < this.width; x++) {
			px = nx = pz = nz = py = 0;
			cell = getCell(x, z);
			// TODO: Remove hard coded "#", determine wall from block definitions
			if (cell == "#") {
				cell2 = getCell(x + 1, z);
				px = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x - 1, z);
				nx = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z + 1);
				pz = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z - 1);
				nz = cell2 != "#" ? 1 : 0;
			} else {
				py = 1;
			}
			var sides = { px: px, nx: nx, py: py, ny: true, pz: pz, nz: nz };
			var cube = cache.getGeometry(cell + "-" + JSON.stringify(sides), getBlockGeometry(materials[cell], sides));
			this.mesh = new THREE.Mesh(cube);
			this.mesh.position.x = x * map.gridSize;
			this.mesh.position.y = map.roomHeight;
			this.mesh.position.z = z * map.gridSize;
			THREE.GeometryUtils.merge(geometry, this.mesh);
			// Collision body for walls
			if (cell == "#") {
				var wallbody = new Physijs.BoxMesh(cube, dummy_material, 0);
				wallbody.position.copy(this.mesh.position);
				wallbody.visible = false;
				scene.add(wallbody);
			}
			// Light
			if (cell == "*") {
				// Actual light
				light = new THREE.PointLight(0xffffaa, 1, 2 * map.gridSize);
				light.position.set(this.mesh.position.x, this.mesh.position.y, this.mesh.position.z);
				scene.add(light);
				lightManager.addLight(light);
				// Shadow casting light
				light2 = new THREE.SpotLight(0xffffaa, light.intensity, light.distance);
				light2.position = light.position; //set(light.position.x, light.position.y, light.position.z);
				light2.target.position.set(light2.position.x, light2.position.y - 1, light2.position.z);
				light2.angle = Math.PI / 2;
				light2.castShadow = true;
				light2.onlyShadow = true;
				light2.shadowCameraNear = 0.1 * UNIT;
				light2.shadowCameraFar = 10 * UNIT;
				light2.shadowCameraFov = 100;
				light2.shadowBias = -0.0002;
				light2.shadowDarkness = 0.3;
				light2.shadowMapWidth = 256;
				light2.shadowMapHeight = 256;
				//light2.shadowCameraVisible = true;
				scene.add(light2);
				lightManager.addShadow(light2);
				// Debug body
				if (DEBUG) {
					light_body = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({ color: 0xffffaa }));
					light_body.position = light.position;
					scene.add(light_body);
				}
			// Objects
			} else if (map.objects[cell]) {
				obj = map.objects[cell];
				cache.loadModel("assets/models/" + obj.name + "/" + obj.name + ".js",
					getObjectHandler(x * map.gridSize, null, z * map.gridSize, obj));
			}
		}
	}
	geometry.computeTangents();
	this.mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
	this.mesh.castShadow = true;
	this.mesh.receiveShadow = true;
	scene.add(this.mesh);

	// Physics plane
	var ground_material = Physijs.createMaterial(dummy_material,
		0.9, // high friction
		0.0 // low restitution
	);
	ground_material.visible = false;
	var ground_plane = new Physijs.BoxMesh(
		new THREE.CubeGeometry(map.gridSize * this.width, 1, map.gridSize * this.depth),
		ground_material,
		0 // mass
	);
	ground_plane.position = new THREE.Vector3(map.gridSize * this.width * 0.5, 1, map.gridSize * this.depth * 0.5);
	scene.add(ground_plane);

	// Weapon
	cache.loadModel("assets/models/knife/knife.js", function(geometry) {
		player.rhand = new THREE.Mesh(geometry, geometry.materials[0]);
		//player.rhand.castShadow = true;
		player.rhand.receiveShadow = true;
		scene.add(player.rhand);
	});

	// Items
	//cache.loadModel("assets/models/items/health.js",
	//	getObjectHandler(player.position.x, 2, player.position.z, { faceMaterial: true, noShadows: true }));
	//cache.loadModel("assets/models/items/mana.js",
	//	getObjectHandler(player.position.x + 1, 2, player.position.z, { faceMaterial: true, noShadows: true }));

	// Monster
	cache.loadModel("assets/models/shdw3/shdw3.js", function(geometry) {
		geometry.computeMorphNormals();
		var colorMap = geometry.morphColors[ 0 ];
		for (var i = 0; i < colorMap.colors.length; ++i) {
			geometry.faces[i].color = colorMap.colors[i];
		}

		var material = new THREE.MeshPhongMaterial({
			color: 0x222222, specular: 0xffffff, shininess: 10,
			morphTargets: true, morphNormals: true, vertexColors: THREE.FaceColors,
			shading: THREE.SmoothShading, perPixel: true
		});

		var monster = new Physijs.CylinderMesh(
			new THREE.CylinderGeometry(0.4 * UNIT, 0.4 * UNIT, 2 * UNIT),
			dummy_material, 100000
		);
		monster.visible = false;
		monster.position.set(player.position.x + 4, player.position.y - 0.8, player.position.z);
		self.monsters.push(monster);

		monster.mesh = new THREE.MorphAnimMesh(geometry, material);
		monster.mesh.speed = 0.4;
		monster.mesh.duration = 2000;
		monster.mesh.time = 600 * Math.random();
		monster.mesh.castShadow = true;
		monster.mesh.receiveShadow = true;
		monster.add(monster.mesh);
		scene.add(monster);
		monster.setAngularFactor({ x: 0, y: 0, z: 0 });
	});

}
<commit_msg>Refactor ground plane creation.<commit_after>
function Dungeon(scene, player, map) {
	var self = this;
	this.width = map.map[0].length;
	this.depth = map.map.length;
	this.mesh = undefined;
	this.monsters = [];
	this.objects = [];
	var dummy_material = new THREE.MeshBasicMaterial({color: 0x000000});

	map.gridSize *= UNIT;

	var materials = {};
	for (var tex in map.blocks) {
		if (!map.blocks.hasOwnProperty(tex)) continue;
		var floor_mat = map.blocks[tex].floor ? cache.getMaterial(map.blocks[tex].floor) : dummy_material;
		var wall_mat = map.blocks[tex].wall ? cache.getMaterial(map.blocks[tex].wall) : dummy_material;
		var ceiling_mat = map.blocks[tex].ceiling ? cache.getMaterial(map.blocks[tex].ceiling) : dummy_material;
		materials[tex] = [
			wall_mat, // right
			wall_mat, // left
			ceiling_mat, // top
			floor_mat, // bottom
			wall_mat, // back
			wall_mat  // front
		];
	}

	function getCell(x, z) {
		if (x < 0 || x >= map.map[0].length) return "#";
		else if (z < 0 || z >= map.map.length) return "#";
		return map.map[z][x];
	}

	function getObjectHandler(x, y, z, def) {
		return function(geom) {
			if (!def) def = {};
			var obj;
			if (def.collision) {
				var material = Physijs.createMaterial(
					geom.materials[0], 0.7, 0.2); // friction, restition
				if (def.collision == "plane")
					obj = new Physijs.PlaneMesh(geom, material, def.mass);
				else if (def.collision == "box")
					obj = new Physijs.BoxMesh(geom, material, def.mass);
				else if (def.collision == "sphere")
					obj = new Physijs.SphereMesh(geom, material, def.mass);
				else if (def.collision == "cylinder")
					obj = new Physijs.CylinderMesh(geom, material, def.mass);
				else if (def.collision == "cone")
					obj = new Physijs.ConeMesh(geom, material, def.mass);
				else if (def.collision == "convex")
					obj = new Physijs.ConvexMesh(geom, material, def.mass);
				else throw "Unsupported collision mesh type " + def.collision;
				self.objects.push(obj);
			} else {
				obj = new THREE.Mesh(geom, def.faceMaterial ? new THREE.MeshFaceMaterial() : geom.materials[0]);
			}
			// Auto-height
			if (y === null) {
				if (geom.boundingBox)
					y = 2 * (geom.boundingBox.max.y - geom.boundingBox.min.y) + 0.001;
				else if (geom.boundingSphere)
					y = geom.boundingSphere.radius + 0.001;
				else
					y = 0;
			}
			obj.position.set(x, y, z);
			if (!def.noShadows) {
				obj.castShadow = true;
				obj.receiveShadow = true;
			}
			scene.add(obj);
		};
	}

	function getBlockGeometry(materials, sides) {
		return function() {
			return new BlockGeometry(map.gridSize, map.roomHeight, map.gridSize,
				1, 1, 1, materials, sides);
		};
	}

	var cell, cell2, px, nx, pz, nz, py;
	var ambientLight = new THREE.AmbientLight(0xaaaaaa);
	scene.add(ambientLight);

	player.light = new THREE.PointLight(0x88bbff, 1, map.gridSize * 2);
	scene.add(player.light);
	player.shadow = new THREE.SpotLight(player.light.color, player.light.intensity, player.light.distance);
	player.shadow.angle = Math.PI / 4;
	player.shadow.onlyShadow = true;
	player.shadow.castShadow = true;
	player.shadow.shadowCameraNear = 0.1 * UNIT;
	player.shadow.shadowCameraFar = 10 * UNIT;
	player.shadow.shadowCameraFov = 60;
	player.shadow.shadowBias = -0.0002;
	player.shadow.shadowDarkness = 0.3;
	player.shadow.shadowMapWidth = 1024;
	player.shadow.shadowMapHeight = 1024;
	player.shadow.shadowCameraVisible = false;
	scene.add(player.shadow);

	// TODO: Set player rotation
	player.position.set(map.start[0] * map.gridSize, map.roomHeight, map.start[1] * map.gridSize);

	var geometry = new THREE.Geometry(), light, light2, light_body, obj;
	var sphere = new THREE.SphereGeometry(0.05 * UNIT, 16, 8);

	for (var z = 0; z < this.depth; z++) {
		for (var x = 0; x < this.width; x++) {
			px = nx = pz = nz = py = 0;
			cell = getCell(x, z);
			// TODO: Remove hard coded "#", determine wall from block definitions
			if (cell == "#") {
				cell2 = getCell(x + 1, z);
				px = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x - 1, z);
				nx = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z + 1);
				pz = cell2 != "#" ? 1 : 0;
				cell2 = getCell(x, z - 1);
				nz = cell2 != "#" ? 1 : 0;
			} else {
				py = 1;
			}
			var sides = { px: px, nx: nx, py: py, ny: true, pz: pz, nz: nz };
			var cube = cache.getGeometry(cell + "-" + JSON.stringify(sides), getBlockGeometry(materials[cell], sides));
			this.mesh = new THREE.Mesh(cube);
			this.mesh.position.x = x * map.gridSize;
			this.mesh.position.y = map.roomHeight;
			this.mesh.position.z = z * map.gridSize;
			THREE.GeometryUtils.merge(geometry, this.mesh);
			// Collision body for walls
			if (cell == "#") {
				var wallbody = new Physijs.BoxMesh(cube, dummy_material, 0);
				wallbody.position.copy(this.mesh.position);
				wallbody.visible = false;
				scene.add(wallbody);
			}
			// Light
			if (cell == "*") {
				// Actual light
				light = new THREE.PointLight(0xffffaa, 1, 2 * map.gridSize);
				light.position.set(this.mesh.position.x, this.mesh.position.y, this.mesh.position.z);
				scene.add(light);
				lightManager.addLight(light);
				// Shadow casting light
				light2 = new THREE.SpotLight(0xffffaa, light.intensity, light.distance);
				light2.position = light.position; //set(light.position.x, light.position.y, light.position.z);
				light2.target.position.set(light2.position.x, light2.position.y - 1, light2.position.z);
				light2.angle = Math.PI / 2;
				light2.castShadow = true;
				light2.onlyShadow = true;
				light2.shadowCameraNear = 0.1 * UNIT;
				light2.shadowCameraFar = 10 * UNIT;
				light2.shadowCameraFov = 100;
				light2.shadowBias = -0.0002;
				light2.shadowDarkness = 0.3;
				light2.shadowMapWidth = 256;
				light2.shadowMapHeight = 256;
				//light2.shadowCameraVisible = true;
				scene.add(light2);
				lightManager.addShadow(light2);
				// Debug body
				if (DEBUG) {
					light_body = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({ color: 0xffffaa }));
					light_body.position = light.position;
					scene.add(light_body);
				}
			// Objects
			} else if (map.objects[cell]) {
				obj = map.objects[cell];
				cache.loadModel("assets/models/" + obj.name + "/" + obj.name + ".js",
					getObjectHandler(x * map.gridSize, null, z * map.gridSize, obj));
			}
		}
	}
	geometry.computeTangents();
	this.mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
	this.mesh.castShadow = true;
	this.mesh.receiveShadow = true;
	scene.add(this.mesh);

	// Physics plane
	var ground_plane = new Physijs.BoxMesh(
		new THREE.CubeGeometry(map.gridSize * this.width, 1, map.gridSize * this.depth),
		Physijs.createMaterial(dummy_material, 0.9, 0.0), // friction, restitution
		0 // mass
	);
	ground_plane.position = new THREE.Vector3(map.gridSize * this.width * 0.5, 1, map.gridSize * this.depth * 0.5);
	ground_plane.visible = false;
	scene.add(ground_plane);

	// Weapon
	cache.loadModel("assets/models/knife/knife.js", function(geometry) {
		player.rhand = new THREE.Mesh(geometry, geometry.materials[0]);
		//player.rhand.castShadow = true;
		player.rhand.receiveShadow = true;
		scene.add(player.rhand);
	});

	// Items
	//cache.loadModel("assets/models/items/health.js",
	//	getObjectHandler(player.position.x, 2, player.position.z, { faceMaterial: true, noShadows: true }));
	//cache.loadModel("assets/models/items/mana.js",
	//	getObjectHandler(player.position.x + 1, 2, player.position.z, { faceMaterial: true, noShadows: true }));

	// Monster
	cache.loadModel("assets/models/shdw3/shdw3.js", function(geometry) {
		geometry.computeMorphNormals();
		var colorMap = geometry.morphColors[ 0 ];
		for (var i = 0; i < colorMap.colors.length; ++i) {
			geometry.faces[i].color = colorMap.colors[i];
		}

		var material = new THREE.MeshPhongMaterial({
			color: 0x222222, specular: 0xffffff, shininess: 10,
			morphTargets: true, morphNormals: true, vertexColors: THREE.FaceColors,
			shading: THREE.SmoothShading, perPixel: true
		});

		var monster = new Physijs.CylinderMesh(
			new THREE.CylinderGeometry(0.4 * UNIT, 0.4 * UNIT, 2 * UNIT),
			dummy_material, 100000
		);
		monster.visible = false;
		monster.position.set(player.position.x + 4, player.position.y - 0.8, player.position.z);
		self.monsters.push(monster);

		monster.mesh = new THREE.MorphAnimMesh(geometry, material);
		monster.mesh.speed = 0.4;
		monster.mesh.duration = 2000;
		monster.mesh.time = 600 * Math.random();
		monster.mesh.castShadow = true;
		monster.mesh.receiveShadow = true;
		monster.add(monster.mesh);
		scene.add(monster);
		monster.setAngularFactor({ x: 0, y: 0, z: 0 });
	});

}
<|endoftext|>


<commit_before>module.exports = test

function test (a) {
  var res = fib(a)
  //console.log(res)
  console.log('done')
}

function fib(num){
  var a = 1
  var b = 0
  var temp

  while (num >= 0){
    temp = a
    a = a + b
    b = temp
    num--
  }

  return b
}

test(parseInt(process.argv[2]))
<commit_msg>Avoid crashing Number.MAX_VALUE<commit_after>module.exports = test

function test (a) {
  var res = fib(a)
  console.log(res)
  console.log('done')
}

function fib(num){
  var a = 1
  var b = 0
  var temp

  while (num >= 0) {
    temp = a
    a = a + b
    b = temp
    num--
    if (num % 1470 === 0) { // avoid crashing Number.MAX_VALUE
      a = 1
      b = 0
    }
  }

  return b
}

test(parseInt(process.argv[2]))
<|endoftext|>