<commit_before>var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var tilelive = require('tilelive');
var yaml = require('js-yaml');

var tm = require('../lib/tm');
var middleware = require('../lib/middleware');
var style = require('../lib/style');
var source = require('../lib/source');
var mockOauth = require('./fixtures-oauth/mapbox');

describe('middleware', function() {
    var tmppath = '/tmp/tm2-test-' + +new Date;
    before(function(done) {
        tm.config({
            db: path.join(tmppath, 'app.db'),
            cache: path.join(tmppath, 'cache'),
            // fonts: path.join(tmppath, 'fonts'), maybe?
            mapboxauth: 'http://localhost:3001'
        }, done);
    });
    after(function(done) {
        try { fs.unlinkSync(path.join(tmppath, 'app.db')); } catch(err) {}
        try { fs.rmdirSync(path.join(tmppath, 'cache')); } catch(err) {}
        try { fs.rmdirSync(tmppath); } catch(err) {}
        done();
    });

    describe('history', function() {
        var sourceId = 'tmsource://' + path.resolve(path.dirname(__filename), './fixtures-localsource');
        var styleId = 'tmstyle://' + path.resolve(path.dirname(__filename), './fixtures-localsource');

        after(function(done) {
            tm.history('source', sourceId, true);
            tm.history('style', styleId, true);
            done();
        });
        it('loads history', function(done) {
            this.timeout(10000);
            var req = {};
            middleware.history(req, {}, function() {
                assert(req.history, 'has history');
                assert(req.history.source, 'history object includes a source');
                assert(req.history.source['mapbox:///mapbox.mapbox-streets-v4'], 'default source is listed');
                done();
            });
        });
        it('gets style/source info', function(done) {
            var sourceDoc = require('./fixtures-localsource/data.yml');
            var styleDoc = require('./fixtures-localsource/project.yml');
            tm.history('source', sourceId);
            tm.history('style', styleId);

            var req = {};
            middleware.history(req, {}, function() {
                var sourceInfo = req.history.source[sourceId];
                var styleInfo = req.history.style[styleId];
                assert.equal(sourceDoc.attribution, sourceInfo.attribution, 'source info was loaded');
                assert.equal(styleDoc.mtime, styleInfo.mtime, 'style info was loaded');
                done();
            });
        });
        it('removes dead source/styles', function(done) {
            tm.history('source', 'foo');
            tm.history('style', 'bar');
            var req = {};
            middleware.history(req, {}, function() {
                assert(!req.history.source.foo, 'source `foo` was removed');
                if (req.history.style) assert(!req.history.style.bar, 'style `bar` was removed');
                done();
            });
        });
    });

    describe('writeStyle', function() {
        var tmpId = '/tmp/tm2-perm-' + (+new Date);
        after(function(done) {
            setTimeout(function() {
                ['project.xml','project.yml','a.mss','.thumb.png'].forEach(function(file) {
                    try { fs.unlinkSync(tmpId + '/' + file) } catch(err) {};
                });
                try { fs.rmdirSync(tmpId) } catch(err) {};
                done();
            }, 250);
        });
        it('makes tmp styles', function(done) {
            var req = { body: {} };
            middleware.writeStyle(req, {}, function() {
                assert(req.style, 'appends style to req');
                assert(tm.tmpid('tmstyle:', req.style.data.id), 'creates a valid tmp id');
                var history = tm.history();
                if (history.style) {
                    assert(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
                }

                style.info('tmstyle://' + path.dirname(require.resolve('tm2-default-style')), function(err, defaultInfo) {
                    delete req.style.data.id;
                    delete req.style.data.mtime;
                    delete req.style.data._tmp;
                    delete req.style.data.background;
                    delete defaultInfo.id;
                    delete defaultInfo.mtime;

                    assert.deepEqual(req.style.data, defaultInfo, 'mimics default style');
                    done();
                });
            });
        });
        it('makes persistent styles', function(done) {
            var data = {
                id:'tmstyle://' + tmpId,
                name:'tmp-1234',
                source:'mapbox:///mapbox.mapbox-streets-v2',
                styles:{ 'a.mss': '#water { polygon-fill:#fff }' }
            };
            var req = { body: data };
            middleware.writeStyle(req, {}, function() {
                assert(req.style, 'appends style to req');
                assert(!tm.tmpid('tmstyle:', req.style.data.id), 'does not create a tmp id');
                assert(tm.history().style.indexOf(req.style.data.id) !== -1, 'writes to history');
                assert.equal(req.style.data.name, data.name, 'has correct info');
                assert.ok(/maxzoom: 22/.test(fs.readFileSync(tmpId + '/project.yml', 'utf8')), 'saves project.yml');
                assert.equal(data.styles['a.mss'], fs.readFileSync(tmpId + '/a.mss', 'utf8'), 'saves a.mss');
                done();
            });
        });
        // @TODO: testing this requires some work on source.invalidate
        // it('invalidates source if req._recache', function() {
        //     done();
        // });
    });

    describe('loadStyle', function() {
        it('loads a tmp style', function(done) {
            var writeReq = { body: {} };
            middleware.writeStyle(writeReq, {}, function() {
                var req = { query: { id: writeReq.style.data.id } };
                middleware.loadStyle(req, {}, function() {
                    assert(req.style, 'appends style to req');
                    assert.equal(req.style.data.id, writeReq.style.data.id, 'has the correct id');
                    var history = tm.history();
                    if (history.style) {
                        assert(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
                    }
                    done();
                });
            });
        });
        it('loads a persistent style', function(done) {
            var styleId = 'tmstyle://' + path.resolve(path.dirname(__filename), './fixtures-localsource');
            var styleDoc = require('./fixtures-localsource/project.yml');
            var req = { query: { id: styleId } };
            middleware.loadStyle(req, {}, function() {
                assert(req.style, 'appends style to req');
                assert.equal(req.style.data.id, styleId, 'has the correct id');
                assert(tm.history().style.indexOf(req.style.data.id) !== -1, 'writes to history');
                assert.equal(req.style.data.mtime, styleDoc.mtime, 'style info was loaded');
                done();
            });
        });
    });

    describe('writeSource', function() {
        var tmpId = '/tmp/tm2-perm-' + (+new Date);
        after(function(done) {
            setTimeout(function() {
                ['data.xml', 'data.yml'].forEach(function(file) {
                    try { fs.unlinkSync(tmpId + '/' + file) } catch(err) {};
                });
                try { fs.rmdirSync(tmpId) } catch(err) {};
                done();
            }, 250);
        });
        it('makes tmp sources', function(done) {
            var req = { body: {} };
            middleware.writeSource(req, {}, function() {
                assert(req.source, 'appends source to req');
                assert(source.tmpid(req.source.data.id), 'creates a valid tmp id');
                var history = tm.history();
                if (history.source) {
                    assert(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
                }
                done();
            });
        });
        it('makes persistent sources', function(done) {
            var data = {
                id: 'tmsource://' + tmpId,
                name: 'Test source',
                attribution: '© John Doe 2013.',
                minzoom: 0,
                maxzoom: 6,
                Layer: [ {
                    id: 'box',
                    name: 'box',
                    description: '',
                    srs: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over',
                    properties: {
                        'buffer-size': 0,
                        minzoom: 0,
                        maxzoom: 6
                    },
                    Datasource: {
                        file: __dirname + '/fixtures-localsource/10m-900913-bounding-box.shp',
                        type: 'shape'
                    }
                } ]
            };
            var req = { body: data };
            middleware.writeSource(req, {}, function() {
                var s = req.source;
                assert(s, 'appends source to req');
                assert(!source.tmpid(s.data.id), 'does not creates a tmp id');
                var history = tm.history();
                if (history.source) {
                    assert(history.source.indexOf(s.data.id) !== -1, 'writes to history');
                }
                assert.deepEqual(s.data, data, 'has the right data');
                done();
            });
        });
    });

    describe('loadSource', function() {
        it('loads a tmp source', function(done) {
            var writeReq = { body: {} };
            middleware.writeSource(writeReq, {}, function() {
                var req = { query: { id: writeReq.source.data.id } };
                middleware.loadSource(req, {}, function() {
                    assert(req.source, 'appends source to req');
                    assert.equal(req.source.data.id, writeReq.source.data.id, 'has the correct id');
                    var history = tm.history();
                    if (history.source) {
                        assert(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
                    }
                    done();
                });
            });
        });
        it('loads a persistent source', function(done) {
            var sourceId = 'tmsource://' + path.resolve(path.dirname(__filename), './fixtures-localsource');
            var sourceDoc = require('./fixtures-localsource/data.yml');
            var req = { query: { id: sourceId } };
            middleware.loadSource(req, {}, function() {
                assert(req.source, 'appends source to req');
                assert.equal(req.source.data.id, sourceId, 'has the correct id');
                assert(tm.history().source.indexOf(req.source.data.id) !== -1, 'writes to history');
                assert.equal(req.source.data.name, sourceDoc.name, 'has the correct name');
                assert.equal(req.source.data.attribution, sourceDoc.attribution, 'has the correct attribution');
                assert.equal(req.source.data.minzoom, sourceDoc.minzoom, 'has the correct minzoom');
                assert.equal(req.source.data.maxzoom, sourceDoc.maxzoom, 'has the correct maxzoom');
                assert.deepEqual(req.source.data.Layer[0].Datasource, sourceDoc.Layer[0].Datasource, 'has the correct Layer');
                done();
            });
        });
    });

    describe('auth', function() {
        it('redirects unauthenticated requests', function(done) {
            function redirectedTo(path) {
                assert.equal('/authorize', path);
                done();
            }
            middleware.auth({}, { redirect: redirectedTo }, function() {
                assert.fail('did not redirect');
                done();
            });
        });
        it('passes through authenticated requests', function(done) {
            tm.db.set('oauth', {
                account: 'test',
                accesstoken: '12345678'
            });
            function redirectedTo(path) {
                assert.fail('redirected authenticated request');
                done();
            }
            middleware.auth({}, {redirect: redirectedTo}, function(err) {
                assert(!err);
                done();
            });
        });
    });

    describe('basemap', function() {
        before(function(done) {
            tm.db.set('oauth', {
                account: 'test',
                accesstoken: '12345678'
            });
            mockOauth.start(done);
        });
        after(function(done) {
            mockOauth.stop(done);
        });
        it('appends a basemap to req', function(done) {
            var req = {};
            middleware.basemap(req, {}, function(err) {
                assert(req.basemap);
                done();
            });
        });
        it('error when unauthenticated', function(done) {
            tm.db.rm('oauth');
            middleware.basemap({}, {}, function(err) {
                assert(err);
                done();
            });
        });
    });

    describe('exporting', function() {
        it('passes through', function(done) {
            middleware.exporting({}, {}, function(err) {
                assert.ifError(err);
                done();
            });
        });
        // @TODO test cases where copytask has been started.
        // Requires fixes for copytask pause/cancel.
    });
});
<commit_msg>Fix history info loading assertions.<commit_after>var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var tilelive = require('tilelive');
var yaml = require('js-yaml');

var tm = require('../lib/tm');
var middleware = require('../lib/middleware');
var style = require('../lib/style');
var source = require('../lib/source');
var mockOauth = require('./fixtures-oauth/mapbox');

describe('middleware', function() {
    var tmppath = '/tmp/tm2-test-' + +new Date;
    before(function(done) {
        tm.config({
            db: path.join(tmppath, 'app.db'),
            cache: path.join(tmppath, 'cache'),
            // fonts: path.join(tmppath, 'fonts'), maybe?
            mapboxauth: 'http://localhost:3001'
        }, done);
    });
    after(function(done) {
        try { fs.unlinkSync(path.join(tmppath, 'app.db')); } catch(err) {}
        try { fs.rmdirSync(path.join(tmppath, 'cache')); } catch(err) {}
        try { fs.rmdirSync(tmppath); } catch(err) {}
        done();
    });

    describe('history', function() {
        var sourceId = 'tmsource://' + path.resolve(path.dirname(__filename), './fixtures-localsource');
        var styleId = 'tmstyle://' + path.resolve(path.dirname(__filename), './fixtures-localsource');

        after(function(done) {
            tm.history('source', sourceId, true);
            tm.history('style', styleId, true);
            done();
        });
        it('loads history', function(done) {
            this.timeout(10000);
            var req = {};
            middleware.history(req, {}, function() {
                assert(req.history, 'has history');
                assert(req.history.source, 'history object includes a source');
                assert(req.history.source['mapbox:///mapbox.mapbox-streets-v4'], 'default source is listed');
                done();
            });
        });
        it('gets style/source info', function(done) {
            tm.history('source', sourceId);
            tm.history('style', styleId);

            var req = {};
            middleware.history(req, {}, function() {
                var sourceInfo = req.history.source[sourceId];
                var styleInfo = req.history.style[styleId];
                assert.equal('Test source', sourceInfo.name, 'source info was loaded');
                assert.equal('Test style', styleInfo.name, 'style info was loaded');
                done();
            });
        });
        it('removes dead source/styles', function(done) {
            tm.history('source', 'foo');
            tm.history('style', 'bar');
            var req = {};
            middleware.history(req, {}, function() {
                assert(!req.history.source.foo, 'source `foo` was removed');
                if (req.history.style) assert(!req.history.style.bar, 'style `bar` was removed');
                done();
            });
        });
    });

    describe('writeStyle', function() {
        var tmpId = '/tmp/tm2-perm-' + (+new Date);
        after(function(done) {
            setTimeout(function() {
                ['project.xml','project.yml','a.mss','.thumb.png'].forEach(function(file) {
                    try { fs.unlinkSync(tmpId + '/' + file) } catch(err) {};
                });
                try { fs.rmdirSync(tmpId) } catch(err) {};
                done();
            }, 250);
        });
        it('makes tmp styles', function(done) {
            var req = { body: {} };
            middleware.writeStyle(req, {}, function() {
                assert(req.style, 'appends style to req');
                assert(tm.tmpid('tmstyle:', req.style.data.id), 'creates a valid tmp id');
                var history = tm.history();
                if (history.style) {
                    assert(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
                }

                style.info('tmstyle://' + path.dirname(require.resolve('tm2-default-style')), function(err, defaultInfo) {
                    delete req.style.data.id;
                    delete req.style.data.mtime;
                    delete req.style.data._tmp;
                    delete req.style.data.background;
                    delete defaultInfo.id;
                    delete defaultInfo.mtime;

                    assert.deepEqual(req.style.data, defaultInfo, 'mimics default style');
                    done();
                });
            });
        });
        it('makes persistent styles', function(done) {
            var data = {
                id:'tmstyle://' + tmpId,
                name:'tmp-1234',
                source:'mapbox:///mapbox.mapbox-streets-v2',
                styles:{ 'a.mss': '#water { polygon-fill:#fff }' }
            };
            var req = { body: data };
            middleware.writeStyle(req, {}, function() {
                assert(req.style, 'appends style to req');
                assert(!tm.tmpid('tmstyle:', req.style.data.id), 'does not create a tmp id');
                assert(tm.history().style.indexOf(req.style.data.id) !== -1, 'writes to history');
                assert.equal(req.style.data.name, data.name, 'has correct info');
                assert.ok(/maxzoom: 22/.test(fs.readFileSync(tmpId + '/project.yml', 'utf8')), 'saves project.yml');
                assert.equal(data.styles['a.mss'], fs.readFileSync(tmpId + '/a.mss', 'utf8'), 'saves a.mss');
                done();
            });
        });
        // @TODO: testing this requires some work on source.invalidate
        // it('invalidates source if req._recache', function() {
        //     done();
        // });
    });

    describe('loadStyle', function() {
        it('loads a tmp style', function(done) {
            var writeReq = { body: {} };
            middleware.writeStyle(writeReq, {}, function() {
                var req = { query: { id: writeReq.style.data.id } };
                middleware.loadStyle(req, {}, function() {
                    assert(req.style, 'appends style to req');
                    assert.equal(req.style.data.id, writeReq.style.data.id, 'has the correct id');
                    var history = tm.history();
                    if (history.style) {
                        assert(history.style.indexOf(req.style.data.id) === -1, 'does not write to history');
                    }
                    done();
                });
            });
        });
        it('loads a persistent style', function(done) {
            var styleId = 'tmstyle://' + path.resolve(path.dirname(__filename), './fixtures-localsource');
            var styleDoc = require('./fixtures-localsource/project.yml');
            var req = { query: { id: styleId } };
            middleware.loadStyle(req, {}, function() {
                assert(req.style, 'appends style to req');
                assert.equal(req.style.data.id, styleId, 'has the correct id');
                assert(tm.history().style.indexOf(req.style.data.id) !== -1, 'writes to history');
                assert.equal(req.style.data.mtime, styleDoc.mtime, 'style info was loaded');
                done();
            });
        });
    });

    describe('writeSource', function() {
        var tmpId = '/tmp/tm2-perm-' + (+new Date);
        after(function(done) {
            setTimeout(function() {
                ['data.xml', 'data.yml'].forEach(function(file) {
                    try { fs.unlinkSync(tmpId + '/' + file) } catch(err) {};
                });
                try { fs.rmdirSync(tmpId) } catch(err) {};
                done();
            }, 250);
        });
        it('makes tmp sources', function(done) {
            var req = { body: {} };
            middleware.writeSource(req, {}, function() {
                assert(req.source, 'appends source to req');
                assert(source.tmpid(req.source.data.id), 'creates a valid tmp id');
                var history = tm.history();
                if (history.source) {
                    assert(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
                }
                done();
            });
        });
        it('makes persistent sources', function(done) {
            var data = {
                id: 'tmsource://' + tmpId,
                name: 'Test source',
                attribution: '© John Doe 2013.',
                minzoom: 0,
                maxzoom: 6,
                Layer: [ {
                    id: 'box',
                    name: 'box',
                    description: '',
                    srs: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over',
                    properties: {
                        'buffer-size': 0,
                        minzoom: 0,
                        maxzoom: 6
                    },
                    Datasource: {
                        file: __dirname + '/fixtures-localsource/10m-900913-bounding-box.shp',
                        type: 'shape'
                    }
                } ]
            };
            var req = { body: data };
            middleware.writeSource(req, {}, function() {
                var s = req.source;
                assert(s, 'appends source to req');
                assert(!source.tmpid(s.data.id), 'does not creates a tmp id');
                var history = tm.history();
                if (history.source) {
                    assert(history.source.indexOf(s.data.id) !== -1, 'writes to history');
                }
                assert.deepEqual(s.data, data, 'has the right data');
                done();
            });
        });
    });

    describe('loadSource', function() {
        it('loads a tmp source', function(done) {
            var writeReq = { body: {} };
            middleware.writeSource(writeReq, {}, function() {
                var req = { query: { id: writeReq.source.data.id } };
                middleware.loadSource(req, {}, function() {
                    assert(req.source, 'appends source to req');
                    assert.equal(req.source.data.id, writeReq.source.data.id, 'has the correct id');
                    var history = tm.history();
                    if (history.source) {
                        assert(history.source.indexOf(req.source.data.id) === -1, 'does not write to history');
                    }
                    done();
                });
            });
        });
        it('loads a persistent source', function(done) {
            var sourceId = 'tmsource://' + path.resolve(path.dirname(__filename), './fixtures-localsource');
            var sourceDoc = require('./fixtures-localsource/data.yml');
            var req = { query: { id: sourceId } };
            middleware.loadSource(req, {}, function() {
                assert(req.source, 'appends source to req');
                assert.equal(req.source.data.id, sourceId, 'has the correct id');
                assert(tm.history().source.indexOf(req.source.data.id) !== -1, 'writes to history');
                assert.equal(req.source.data.name, sourceDoc.name, 'has the correct name');
                assert.equal(req.source.data.attribution, sourceDoc.attribution, 'has the correct attribution');
                assert.equal(req.source.data.minzoom, sourceDoc.minzoom, 'has the correct minzoom');
                assert.equal(req.source.data.maxzoom, sourceDoc.maxzoom, 'has the correct maxzoom');
                assert.deepEqual(req.source.data.Layer[0].Datasource, sourceDoc.Layer[0].Datasource, 'has the correct Layer');
                done();
            });
        });
    });

    describe('auth', function() {
        it('redirects unauthenticated requests', function(done) {
            function redirectedTo(path) {
                assert.equal('/authorize', path);
                done();
            }
            middleware.auth({}, { redirect: redirectedTo }, function() {
                assert.fail('did not redirect');
                done();
            });
        });
        it('passes through authenticated requests', function(done) {
            tm.db.set('oauth', {
                account: 'test',
                accesstoken: '12345678'
            });
            function redirectedTo(path) {
                assert.fail('redirected authenticated request');
                done();
            }
            middleware.auth({}, {redirect: redirectedTo}, function(err) {
                assert(!err);
                done();
            });
        });
    });

    describe('basemap', function() {
        before(function(done) {
            tm.db.set('oauth', {
                account: 'test',
                accesstoken: '12345678'
            });
            mockOauth.start(done);
        });
        after(function(done) {
            mockOauth.stop(done);
        });
        it('appends a basemap to req', function(done) {
            var req = {};
            middleware.basemap(req, {}, function(err) {
                assert(req.basemap);
                done();
            });
        });
        it('error when unauthenticated', function(done) {
            tm.db.rm('oauth');
            middleware.basemap({}, {}, function(err) {
                assert(err);
                done();
            });
        });
    });

    describe('exporting', function() {
        it('passes through', function(done) {
            middleware.exporting({}, {}, function(err) {
                assert.ifError(err);
                done();
            });
        });
        // @TODO test cases where copytask has been started.
        // Requires fixes for copytask pause/cancel.
    });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Indiegala Display Platform
// @namespace   lalle.se
// @author      lalle
// @match       https://www.indiegala.com/trades*
// @match       https://www.indiegala.com/giveaway*
// @require     http://code.jquery.com/jquery-1.11.2.min.js
// @require     https://cdn.jsdelivr.net/simplestorage/0.2.1/simpleStorage.min.js
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==

$("head link:last")
.after("<link rel=stylesheet type=text/css href=https://steamstore-a.akamaihd.net/public/css/v6/store.css>")
.after("");

function setPlatformSpan(node, steamlink) {
    if (!steamlink.length) {
      return;
    }
    var platformhtml = "";
    if (simpleStorage.canUse()) {
      if(simpleStorage.hasKey(steamlink)) {
        platformhtml = simpleStorage.get(steamlink);
      }
    } else {
      console.warn("Unable to use local storage. Retrieving steam platform will be slow!");
    }

    if (platformhtml.length)  {
      node.append("" + platformhtml + "");
    }
    else {
      GM_xmlhttpRequest({
        method: "GET",
        url: steamlink,
        onload: function(response) {
          var platform = $(response.responseText).find("div.game_area_purchase_platform");
          if (platform.length) {
            if (simpleStorage.canUse())  {
              simpleStorage.set(steamlink, platform.html(), {TTL: 2592000000})
            }
            node.append("" + platform.html() + "");
          }
        }
      });
    }
}

function getSteamLink(trade) {
  var gameImg = trade.find("img:first");
  var steamapp = gameImg.attr("src").replace("http://cdn.akamai.steamstatic.com/steam/apps/", "").replace("/header.jpg", "");
  var steamlink = "http://store.steampowered.com/app/" + steamapp + "/";
  return steamlink;
}

$("div.trade-cont").each(function () {
  var trade = $(this);
  var steamlink = getSteamLink(trade);
  //setPlatformSpan(trade.find("div.trade-type"), steamlink);
  setPlatformSpan(trade.find("div.trade_img"), steamlink);
});

$("div.trade-img-cont").each(function() {
  var trade = $(this);
  var steamlink = getSteamLink(trade);
  setPlatformSpan(trade, steamlink);
});
<commit_msg>Change position<commit_after>// ==UserScript==
// @name        Indiegala Display Platform
// @namespace   lalle.se
// @author      lalle
// @match       https://www.indiegala.com/trades*
// @match       https://www.indiegala.com/giveaway*
// @require     http://code.jquery.com/jquery-1.11.2.min.js
// @require     https://cdn.jsdelivr.net/simplestorage/0.2.1/simpleStorage.min.js
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==

$("head link:last")
.after("<link rel=stylesheet type=text/css href=https://steamstore-a.akamaihd.net/public/css/v6/store.css>")
.after("");

function setPlatformSpan(node, steamlink) {
    if (!steamlink.length) {
      return;
    }
    var platformhtml = "";
    if (simpleStorage.canUse()) {
      if(simpleStorage.hasKey(steamlink)) {
        platformhtml = simpleStorage.get(steamlink);
      }
    } else {
      console.warn("Unable to use local storage. Retrieving steam platform will be slow!");
    }

    if (platformhtml.length)  {
      node.append("" + platformhtml + "");
    }
    else {
      GM_xmlhttpRequest({
        method: "GET",
        url: steamlink,
        onload: function(response) {
          var platform = $(response.responseText).find("div.game_area_purchase_platform");
          if (platform.length) {
            if (simpleStorage.canUse())  {
              simpleStorage.set(steamlink, platform.html(), {TTL: 2592000000})
            }
            node.append("" + platform.html() + "");
          }
        }
      });
    }
}

function getSteamLink(trade) {
  var gameImg = trade.find("img:first");
  var steamapp = gameImg.attr("src").replace("http://cdn.akamai.steamstatic.com/steam/apps/", "").replace("/header.jpg", "");
  var steamlink = "http://store.steampowered.com/app/" + steamapp + "/";
  return steamlink;
}

$("div.trade-cont").each(function () {
  var trade = $(this);
  var steamlink = getSteamLink(trade);
  setPlatformSpan(trade.find("div.trade_img"), steamlink);
});

$("div.trade-img-cont").each(function() {
  var trade = $(this);
  var steamlink = getSteamLink(trade);
  setPlatformSpan(trade, steamlink);
});
<|endoftext|>


<commit_before>var websocket = require('websocket-stream')
, bricoleur = require('./_brico')
, id = null
, host = window.location.host.replace('www.','')
, ws = websocket('ws://'+host)

var brico = new bricoleur()
ws.pipe(brico.in)
brico.out.pipe(ws)
<commit_msg>update __clnt<commit_after>var websocket = require('websocket-stream')
, bricoleur = require('./_brico')
, id = null
, host = window.location.host.replace('www.','')
, ws = websocket('ws://'+host)

// need to get key and user
var brico = new bricoleur()
ws.pipe(brico.in)
brico.out.pipe(ws)
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Indiegala Display Platform
// @namespace   lalle.se
// @author      lalle
// @match       https://www.indiegala.com/trades*
// @match       https://www.indiegala.com/giveaways/detail*
// @require     http://code.jquery.com/jquery-1.11.2.min.js
// @require     https://cdn.jsdelivr.net/simplestorage/0.2.1/simpleStorage.min.js
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==

$("head link:last")
    .after("<link rel=stylesheet type=text/css href=https://steamstore-a.akamaihd.net/public/css/v6/store.css>")
    .after("");

function setPlatformSpan(node, steamlink) {
    if (!steamlink.length) {
        return;
    }
    var platformhtml = "";
    if (simpleStorage.canUse()) {
        if(simpleStorage.hasKey(steamlink)) {
            platformhtml = simpleStorage.get(steamlink);
        }
    } else {
        console.warn("Unable to use local storage. Retrieving steam platform will be slow!");
    }

    console.log("platformhtml: " + platformhtml);

    if (platformhtml !== undefined && platformhtml.length)  {
        node.append("" + platformhtml + "");
    }
    else {
        GM_xmlhttpRequest({
            method: "GET",
            url: steamlink,
            onload: function(response) {
                var platform = $(response.responseText).find("div.game_area_purchase_platform");
                if (platform.length) {
                    if (simpleStorage.canUse())  {
                        simpleStorage.set(steamlink, platform.html(), {TTL: 2592000000});
                    }
                    node.append("" + platform.html() + "");
                }
            }
        });
    }
}

function getSteamImgLink(trade) {
    var gameImg = trade.find("img:first");
    var steamapp = gameImg.attr("src").replace("http://cdn.akamai.steamstatic.com/steam/apps/", "").replace("/header.jpg", "");
    var steamlink = "http://store.steampowered.com/app/" + steamapp + "/";
    return steamlink;
}

function getSteamLink(pNode){
    var linkNode = pNode.find("a.steam-link");
    var steamLink = linkNode.attr("href");
    return steamLink;
}

$("div.trade-cont").each(function () {
    var trade = $(this);
    var steamlink = getSteaImgmLink(trade);
    setPlatformSpan(trade.find("div.trade_img").find("p:first"), steamlink);
});

$("div.trade-img-cont").each(function() {
    var trade = $(this);
    var steamlink = getSteamImgLink(trade);
    setPlatformSpan(trade, steamlink);
});

$("section.ticket-cont").each(function() {
    var giveaway = $(this);
    var steamlink = getSteamLink(giveaway);
    var appendNode = giveaway.find("div.game-img-cont");
    setPlatformSpan(appendNode, steamlink);
});
<commit_msg>Fix method spelling error<commit_after>// ==UserScript==
// @name        Indiegala Display Platform
// @namespace   lalle.se
// @author      lalle
// @match       https://www.indiegala.com/trades*
// @match       https://www.indiegala.com/giveaways/detail*
// @require     http://code.jquery.com/jquery-1.11.2.min.js
// @require     https://cdn.jsdelivr.net/simplestorage/0.2.1/simpleStorage.min.js
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==

$("head link:last")
    .after("<link rel=stylesheet type=text/css href=https://steamstore-a.akamaihd.net/public/css/v6/store.css>")
    .after("");

function setPlatformSpan(node, steamlink) {
    if (!steamlink.length) {
        return;
    }
    var platformhtml = "";
    if (simpleStorage.canUse()) {
        if(simpleStorage.hasKey(steamlink)) {
            platformhtml = simpleStorage.get(steamlink);
        }
    } else {
        console.warn("Unable to use local storage. Retrieving steam platform will be slow!");
    }

    if (platformhtml !== undefined && platformhtml.length)  {
        node.append("" + platformhtml + "");
    }
    else {
        GM_xmlhttpRequest({
            method: "GET",
            url: steamlink,
            onload: function(response) {
                var platform = $(response.responseText).find("div.game_area_purchase_platform");
                if (platform.length) {
                    if (simpleStorage.canUse())  {
                        simpleStorage.set(steamlink, platform.html(), {TTL: 2592000000});
                    }
                    node.append("" + platform.html() + "");
                }
            }
        });
    }
}

function getSteamImgLink(trade) {
    var gameImg = trade.find("img:first");
    var steamapp = gameImg.attr("src").replace("http://cdn.akamai.steamstatic.com/steam/apps/", "").replace("/header.jpg", "");
    var steamlink = "http://store.steampowered.com/app/" + steamapp + "/";
    return steamlink;
}

function getSteamLink(pNode){
    var linkNode = pNode.find("a.steam-link");
    var steamLink = linkNode.attr("href");
    return steamLink;
}

$("div.trade-cont").each(function () {
    var trade = $(this);
    var steamlink = getSteamImgLink(trade);
    setPlatformSpan(trade.find("div.trade_img").find("p:first"), steamlink);
});

$("div.trade-img-cont").each(function() {
    var trade = $(this);
    var steamlink = getSteamImgLink(trade);
    setPlatformSpan(trade, steamlink);
});

$("section.ticket-cont").each(function() {
    var giveaway = $(this);
    var steamlink = getSteamLink(giveaway);
    var appendNode = giveaway.find("div.game-img-cont");
    setPlatformSpan(appendNode, steamlink);
});
<|endoftext|>


<commit_before>var telepath = require('tele')
, stream = require('stream')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  telepath(this)

  // detect if scope is client or browser
  if (global.process && global.process.title==='node') self.scope = 'server'
  if (!global.process) self.scope = 'client'

  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta==='module_map') { // add map
      map = data[self.scope]
      self.build()
    }
  }

  this.build = function () { // load modules
    if (!map) throw new Error('no map')
    for (key in map) {
    }
  }

  // ----------------------------------------------------
  this.addConnection = function (key) {
    self[key] = {}
    var s = self[key]

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk)
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}
<commit_msg>fixed fudly comment in brico<commit_after>var telepath = require('tele')
, stream = require('stream')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title==='node') self.scope = 'server'
  if (!global.process) self.scope = 'client'

  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta==='module_map') { // add map
      map = data[self.scope]
      self.build()
    }
  }

  this.build = function () { // load modules
    if (!map) throw new Error('no map')
    for (key in map) {
    }
  }

  // ----------------------------------------------------
  this.addConnection = function (key) {
    self[key] = {}
    var s = self[key]

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk)
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}
<|endoftext|>


<commit_before>var sqlite3 = require('..');
var assert = require('assert');
var fs = require('fs');
var helper = require('./support/helper');

describe('open/close', function() {
    before(function() {
        helper.ensureExists('test/tmp');
    });

    describe('open and close non-existant database', function() {
        before(function() {
            helper.deleteFile('test/tmp/test_create.db');
        });

        var db;
        it('should open the database', function(done) {
            db = new sqlite3.Database('test/tmp/test_create.db', done);
        });

        it('should close the database', function(done) {
            db.close(done);
        });

        it('should have created the file', function() {
            assert.fileExists('test/tmp/test_create.db');
        });

        after(function() {
            helper.deleteFile('test/tmp/test_create.db');
        });
    });

    describe('open and close non-existant shared database', function() {
        before(function() {
            helper.deleteFile('test/tmp/test_create_shared.db');
        });

        var db;
        it('should open the database', function(done) {
            db = new sqlite3.Database('file:./test/tmp/test_create_shared.db', sqlite3.OPEN_URI | sqlite3.OPEN_SHAREDCACHE | sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, done);
        });

        it('should close the database', function(done) {
            db.close(done);
        });

        it('should have created the file', function() {
            assert.fileExists('test/tmp/test_create_shared.db');
        });

        after(function() {
            helper.deleteFile('test/tmp/test_create_shared.db');
        });
    });

    describe('open and close shared memory database', function() {

        var db1;
        var db2;

        it('should open the first database', function(done) {
            db1 = new sqlite3.Database('file:./test/tmp/test_memory.db?mode=memory', sqlite3.OPEN_URI | sqlite3.OPEN_SHAREDCACHE | sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, done);
        });

        it('should open the second database', function(done) {
            db2 = new sqlite3.Database('file:./test/tmp/test_memory.db?mode=memory', sqlite3.OPEN_URI | sqlite3.OPEN_SHAREDCACHE | sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, done);
        });

        it('first database should set the user_version', function(done) {
            db1.exec('PRAGMA user_version=42', done);
        });

        it('second database should get the user_version', function(done) {
            db2.get('PRAGMA user_version', function(err, row) {
                if (err) throw err;
                assert.equal(row.user_version, 42);
                done();
            });
        });

        it('should close the first database', function(done) {
            db1.close(done);
        });

        it('should close the second database', function(done) {
            db2.close(done);
        });
    });

    it('should not be unable to open an inaccessible database', function(done) {
        // NOTE: test assumes that the user is not allowed to create new files
        // in /usr/bin.
        var db = new sqlite3.Database('/test/tmp/directory-does-not-exist/test.db', function(err) {
            if (err && err.errno === sqlite3.CANTOPEN) {
                done();
            } else if (err) {
                done(err);
            } else {
                done('Opened database that should be inaccessible');
            }
        });
    });

    describe('creating database without create flag', function() {
        before(function() {
            helper.deleteFile('test/tmp/test_readonly.db');
        });

        it('should fail to open the database', function(done) {
            new sqlite3.Database('tmp/test_readonly.db', sqlite3.OPEN_READONLY, function(err) {
                if (err && err.errno === sqlite3.CANTOPEN) {
                    done();
                } else if (err) {
                    done(err);
                } else {
                    done('Created database without create flag');
                }
            });
        });

        it('should not have created the file', function() {
            assert.fileDoesNotExist('test/tmp/test_readonly.db');
        });

        after(function() {
            helper.deleteFile('test/tmp/test_readonly.db');
        });
    });

    describe('open and close memory database queuing', function() {
        var db;
        it('should open the database', function(done) {
            db = new sqlite3.Database(':memory:', done);
        });

        it('should close the database', function(done) {
            db.close(done);
        });

        it('shouldn\'t close the database again', function(done) {
            db.close(function(err) {
                assert.ok(err, 'No error object received on second close');
                assert.ok(err.errno === sqlite3.MISUSE);
                done();
            });
        });
    });

    describe('closing with unfinalized statements', function(done) {
        var completed = false;
        var completedSecond = false;
        var closed = false;

        var db;
        before(function() {
            db = new sqlite3.Database(':memory:', done);
        });

        it('should create a table', function(done) {
            db.run("CREATE TABLE foo (id INT, num INT)", done);
        });

        var stmt;
        it('should prepare/run a statement', function(done) {
            stmt = db.prepare('INSERT INTO foo VALUES (?, ?)');
            stmt.run(1, 2, done);
        });

        it('should fail to close the database', function(done) {
            db.close(function(err) {
                assert.ok(err.message,
                    "SQLITE_BUSY: unable to close due to unfinalised statements");
                done();
            });
        });

        it('should succeed to close the database after finalizing', function(done) {
            stmt.run(3, 4, function() {
                stmt.finalize();
                db.close(done);
            });
        });
    });
});
<commit_msg>test shared memory database on sqlite version >= 3.8 only<commit_after>var sqlite3 = require('..');
var assert = require('assert');
var fs = require('fs');
var helper = require('./support/helper');

describe('open/close', function() {
    before(function() {
        helper.ensureExists('test/tmp');
    });

    describe('open and close non-existant database', function() {
        before(function() {
            helper.deleteFile('test/tmp/test_create.db');
        });

        var db;
        it('should open the database', function(done) {
            db = new sqlite3.Database('test/tmp/test_create.db', done);
        });

        it('should close the database', function(done) {
            db.close(done);
        });

        it('should have created the file', function() {
            assert.fileExists('test/tmp/test_create.db');
        });

        after(function() {
            helper.deleteFile('test/tmp/test_create.db');
        });
    });

    describe('open and close non-existant shared database', function() {
        before(function() {
            helper.deleteFile('test/tmp/test_create_shared.db');
        });

        var db;
        it('should open the database', function(done) {
            db = new sqlite3.Database('file:./test/tmp/test_create_shared.db', sqlite3.OPEN_URI | sqlite3.OPEN_SHAREDCACHE | sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, done);
        });

        it('should close the database', function(done) {
            db.close(done);
        });

        it('should have created the file', function() {
            assert.fileExists('test/tmp/test_create_shared.db');
        });

        after(function() {
            helper.deleteFile('test/tmp/test_create_shared.db');
        });
    });

    (sqlite3.VERSION_NUMBER < 3008000 ? describe.skip : describe)('open and close shared memory database', function() {

        var db1;
        var db2;

        it('should open the first database', function(done) {
            db1 = new sqlite3.Database('file:./test/tmp/test_memory.db?mode=memory', sqlite3.OPEN_URI | sqlite3.OPEN_SHAREDCACHE | sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, done);
        });

        it('should open the second database', function(done) {
            db2 = new sqlite3.Database('file:./test/tmp/test_memory.db?mode=memory', sqlite3.OPEN_URI | sqlite3.OPEN_SHAREDCACHE | sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, done);
        });

        it('first database should set the user_version', function(done) {
            db1.exec('PRAGMA user_version=42', done);
        });

        it('second database should get the user_version', function(done) {
            db2.get('PRAGMA user_version', function(err, row) {
                if (err) throw err;
                assert.equal(row.user_version, 42);
                done();
            });
        });

        it('should close the first database', function(done) {
            db1.close(done);
        });

        it('should close the second database', function(done) {
            db2.close(done);
        });
    });

    it('should not be unable to open an inaccessible database', function(done) {
        // NOTE: test assumes that the user is not allowed to create new files
        // in /usr/bin.
        var db = new sqlite3.Database('/test/tmp/directory-does-not-exist/test.db', function(err) {
            if (err && err.errno === sqlite3.CANTOPEN) {
                done();
            } else if (err) {
                done(err);
            } else {
                done('Opened database that should be inaccessible');
            }
        });
    });

    describe('creating database without create flag', function() {
        before(function() {
            helper.deleteFile('test/tmp/test_readonly.db');
        });

        it('should fail to open the database', function(done) {
            new sqlite3.Database('tmp/test_readonly.db', sqlite3.OPEN_READONLY, function(err) {
                if (err && err.errno === sqlite3.CANTOPEN) {
                    done();
                } else if (err) {
                    done(err);
                } else {
                    done('Created database without create flag');
                }
            });
        });

        it('should not have created the file', function() {
            assert.fileDoesNotExist('test/tmp/test_readonly.db');
        });

        after(function() {
            helper.deleteFile('test/tmp/test_readonly.db');
        });
    });

    describe('open and close memory database queuing', function() {
        var db;
        it('should open the database', function(done) {
            db = new sqlite3.Database(':memory:', done);
        });

        it('should close the database', function(done) {
            db.close(done);
        });

        it('shouldn\'t close the database again', function(done) {
            db.close(function(err) {
                assert.ok(err, 'No error object received on second close');
                assert.ok(err.errno === sqlite3.MISUSE);
                done();
            });
        });
    });

    describe('closing with unfinalized statements', function(done) {
        var completed = false;
        var completedSecond = false;
        var closed = false;

        var db;
        before(function() {
            db = new sqlite3.Database(':memory:', done);
        });

        it('should create a table', function(done) {
            db.run("CREATE TABLE foo (id INT, num INT)", done);
        });

        var stmt;
        it('should prepare/run a statement', function(done) {
            stmt = db.prepare('INSERT INTO foo VALUES (?, ?)');
            stmt.run(1, 2, done);
        });

        it('should fail to close the database', function(done) {
            db.close(function(err) {
                assert.ok(err.message,
                    "SQLITE_BUSY: unable to close due to unfinalised statements");
                done();
            });
        });

        it('should succeed to close the database after finalizing', function(done) {
            stmt.run(3, 4, function() {
                stmt.finalize();
                db.close(done);
            });
        });
    });
});
<|endoftext|>


<commit_before>
const PATH = require("path");
const ASSERT = require("assert");
const WAITFOR = require("waitfor");
const GLOB = require("glob");
const FS = require("fs-extra");
const PACKAGE_INSIGHT = require("../lib/package-insight");

const MODE = "test";
//const MODE = "write";

describe('packageinsight', function() {

	it('should export `parse()`', function() {
		ASSERT(typeof PACKAGE_INSIGHT.parse === "function");
	});

	it('should export `parseDescriptor()`', function() {
		ASSERT(typeof PACKAGE_INSIGHT.parseDescriptor === "function");
	});

	describe('`parseDescriptor()`', function() {

		it('should parse various', function(done) {

			function getFiles(callback) {
				var rules = [
					"npm/*.package.json",
					"commonjs/*.package.json",
					"component/*.component.json"
				];
				var files = [];
				var waitfor = WAITFOR.serial(function(err) {
					if (err) return callback(err);
					return callback(null, files);
				});
				rules.forEach(function(rule) {
					waitfor(function(done) {
						return GLOB(rule, {
					        cwd: PATH.join(__dirname, "assets")
					    }, function (err, paths) {
					        if (err) return done(err);
					        files = files.concat(paths);
					        return done(null);
					    });
					});
				});
			}

			return getFiles(function(err, files) {
				if (err) return done(err);

				var waitfor = WAITFOR.serial(done);
				files.forEach(function(file) {
					waitfor(function(done) {
						var options = {};
						if (/\.component\.json$/.test(file)) {
							options.type = "component";
						}
						return PACKAGE_INSIGHT.parseDescriptor(PATH.join(__dirname, "assets", file), options, function(err, descriptor) {
							if (err) return done(err);

							try {

								ASSERT(typeof descriptor === "object");

								if (descriptor.errors.length > 0) {
									descriptor.errors.forEach(function(error) {
										var err = new Error("Got '" + error[0] + "' error '" + error[1] + "' for file '" + PATH.join("assets", file) + "'");
										err.stack = error[2];
										throw err;
									});
								}

								if (MODE === "test") {
									ASSERT.deepEqual(
										descriptor,
										JSON.parse(FS.readFileSync(PATH.join(__dirname, "assets", file.replace(/(\.json)$/, ".insight$1"))))
									);
								} else
								if (MODE === "write") {
									FS.writeFileSync(PATH.join(__dirname, "assets", file.replace(/(\.json)$/, ".insight$1")), JSON.stringify(descriptor, null, 4));
								} else {
									throw new Error("Unknown `MODE`");
								}

								return done(null);
							} catch(err) {
								return done(err);
							}
						});
					});
				});
			});
		});
	});

});<commit_msg>name fix<commit_after>
const PATH = require("path");
const ASSERT = require("assert");
const WAITFOR = require("waitfor");
const GLOB = require("glob");
const FS = require("fs-extra");
const PACKAGE_INSIGHT = require("../lib/package-insight");

const MODE = "test";
//const MODE = "write";

describe('package-insight', function() {

	it('should export `parse()`', function() {
		ASSERT(typeof PACKAGE_INSIGHT.parse === "function");
	});

	it('should export `parseDescriptor()`', function() {
		ASSERT(typeof PACKAGE_INSIGHT.parseDescriptor === "function");
	});

	describe('`parseDescriptor()`', function() {

		it('should parse various', function(done) {

			function getFiles(callback) {
				var rules = [
					"npm/*.package.json",
					"commonjs/*.package.json",
					"component/*.component.json"
				];
				var files = [];
				var waitfor = WAITFOR.serial(function(err) {
					if (err) return callback(err);
					return callback(null, files);
				});
				rules.forEach(function(rule) {
					waitfor(function(done) {
						return GLOB(rule, {
					        cwd: PATH.join(__dirname, "assets")
					    }, function (err, paths) {
					        if (err) return done(err);
					        files = files.concat(paths);
					        return done(null);
					    });
					});
				});
			}

			return getFiles(function(err, files) {
				if (err) return done(err);

				var waitfor = WAITFOR.serial(done);
				files.forEach(function(file) {
					waitfor(function(done) {
						var options = {};
						if (/\.component\.json$/.test(file)) {
							options.type = "component";
						}
						return PACKAGE_INSIGHT.parseDescriptor(PATH.join(__dirname, "assets", file), options, function(err, descriptor) {
							if (err) return done(err);

							try {

								ASSERT(typeof descriptor === "object");

								if (descriptor.errors.length > 0) {
									descriptor.errors.forEach(function(error) {
										var err = new Error("Got '" + error[0] + "' error '" + error[1] + "' for file '" + PATH.join("assets", file) + "'");
										err.stack = error[2];
										throw err;
									});
								}

								if (MODE === "test") {
									ASSERT.deepEqual(
										descriptor,
										JSON.parse(FS.readFileSync(PATH.join(__dirname, "assets", file.replace(/(\.json)$/, ".insight$1"))))
									);
								} else
								if (MODE === "write") {
									FS.writeFileSync(PATH.join(__dirname, "assets", file.replace(/(\.json)$/, ".insight$1")), JSON.stringify(descriptor, null, 4));
								} else {
									throw new Error("Unknown `MODE`");
								}

								return done(null);
							} catch(err) {
								return done(err);
							}
						});
					});
				});
			});
		});
	});

});<|endoftext|>


<commit_before>// specify env file path within the dotenv require module
require('dotenv').config({path: 'path_to_file.env'});
var fetch = require('isomorphic-fetch');
var express = require('express');
var app = express();

// set variables with API call URL
var weatherURL = `http://api.openweathermap.org/data/2.5/weather?units=imperial&APPID=${process.env.WEATHER_KEY}`;
var forecastURL = `http://api.openweathermap.org/data/2.5/forecast?units=imperial&APPID=${process.env.WEATHER_KEY}`;
var twitchURL = `https://api.twitch.tv/kraken/channels/`;

// enable CORS for cross-browser support
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    next();
});

// populate express get methods for JSON fetch
app.get('/weather/:lat/:lon', function (req, res) {
    fetch(`${weatherURL}&lat=${req.params.lat}&lon=${req.params.lon}`)
        .then(response => response.json())
        .then(weather => res.send(weather))
        .catch(error => res.send(error))
});
app.get('/forecast/:lat/:lon', function (req, res) {
    fetch(`${forecastURL}&lat=${req.params.lat}&lon=${req.params.lon}`)
        .then(response => response.json())
        .then(forecast => res.send(forecast))
        .catch(error => res.send(error))
});
app.get('/channels/:channel', function (req, res) {
    fetch(`${twitchURL}${req.params.channel}?client_id=${process.env.TWITCH_KEY}`)
        .then(response => response.json())
        .then(stream => res.send(stream))
        .catch(error => res.send(error))
});

// verify server is running
app.listen(11646, function () {
    console.log("I'm alive! Call me at 11646!");
});
<commit_msg>add stream parameter<commit_after>// specify env file path within the dotenv require module
require('dotenv').config({path: 'keys.env'});
var fetch = require('isomorphic-fetch');
var express = require('express');
var app = express();

// set variables with API call URL
var weatherURL = `http://api.openweathermap.org/data/2.5/weather?units=imperial&APPID=${process.env.WEATHER_KEY}`;
var forecastURL = `http://api.openweathermap.org/data/2.5/forecast?units=imperial&APPID=${process.env.WEATHER_KEY}`;
var twitchURL = `https://api.twitch.tv/kraken/channels/`;
var twitchURLStreams = 'https://api.twitch.tv/kraken/streams/';

// enable CORS for cross-browser support
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    next();
});

// populate express get methods for JSON fetch
app.get('/weather/:lat/:lon', function (req, res) {
    fetch(`${weatherURL}&lat=${req.params.lat}&lon=${req.params.lon}`)
        .then(response => response.json())
        .then(weather => res.send(weather))
        .catch(error => res.send(error))
});
app.get('/forecast/:lat/:lon', function (req, res) {
    fetch(`${forecastURL}&lat=${req.params.lat}&lon=${req.params.lon}`)
        .then(response => response.json())
        .then(forecast => res.send(forecast))
        .catch(error => res.send(error))
});
app.get('/channels/:channel', function (req, res) {
    fetch(`${twitchURL}${req.params.channel}?client_id=${process.env.TWITCH_KEY}`)
        .then(response => response.json())
        .then(stream => res.send(stream))
        .catch(error => res.send(error))
});
app.get('/streams/:stream', function (req, res) {
    fetch(`${twitchURLStreams}${req.params.stream}?client_id=${process.env.TWITCH_KEY}`)
        .then(response => response.json())
        .then(stream => res.send(stream))
        .catch(error => res.send(error))
});

// verify server is running
app.listen(11646, function () {
    console.log("I'm alive! Call me at 11646!");
});
<|endoftext|>


<commit_before>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseFloat(n));  let total = numArray.reduce( (p,c) => (p/c|0)); client.channels.get('377290228207190018').reply(`${p} / ${c} = `+total); }

    message.delete();

  };<commit_msg><commit_after>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseFloat(n));  let total = numArray.reduce( (p,c) => (p/c|0)); client.channels.get('377290228207190018').reply(get.p + "/" + total); }

    message.delete();

  };<|endoftext|>


<commit_before>exports.names = ['.mymostmehed'];
exports.hidden = true;
exports.enabled = false;
exports.matchStart = false;
exports.handler = function (data) {
    //db.all('SELECT author, title, sum_down FROM (SELECT songid, sum(downvotes) as sum_down FROM PLAYS WHERE userid = ? GROUP BY songid ORDER BY sum(downvotes) DESC LIMIT 3) a INNER JOIN SONGS ON a.songid = SONGS.id', [data.from.id], function (error, rows) {
    //    if (rows.length > 0) {
    //        bot.sendChat("Least popular songs you've played: " + rows.map(function (row) {
    //            return row['author'] + ' - ' + row['title'] + ' (-' + row['sum_down'] + ')';
    //        }).join(' • '));
    //    } else {
    //        bot.sendChat("You haven't played anything in this room!");
    //    }
    //});
};

<commit_msg>Update mymostmehed.js<commit_after>exports.names = ['!mymostmehed'];
exports.hidden = true;
exports.enabled = false;
exports.matchStart = false;
exports.handler = function (data) {
    //db.all('SELECT author, title, sum_down FROM (SELECT songid, sum(downvotes) as sum_down FROM PLAYS WHERE userid = ? GROUP BY songid ORDER BY sum(downvotes) DESC LIMIT 3) a INNER JOIN SONGS ON a.songid = SONGS.id', [data.from.id], function (error, rows) {
    //    if (rows.length > 0) {
    //        bot.sendChat("Least popular songs you've played: " + rows.map(function (row) {
    //            return row['author'] + ' - ' + row['title'] + ' (-' + row['sum_down'] + ')';
    //        }).join(' • '));
    //    } else {
    //        bot.sendChat("You haven't played anything in this room!");
    //    }
    //});
};

<|endoftext|>


<commit_before>(function (context) {
  "use strict";

  var TheGraph = context.TheGraph;

  var positions = {
    n4IconX: 0,
    n4IconY: -52,
    n4LabelX: 0,
    n4LabelY: -35,
    s4IconX: 0,
    s4IconY: 52,
    s4LabelX: 0,
    s4LabelY: 35,
    e4IconX: 45,
    e4IconY: -5,
    e4LabelX: 45,
    e4LabelY: 15,
    w4IconX: -45,
    w4IconY: -5,
    w4LabelX: -45,
    w4LabelY: 15
  };

  TheGraph.Menu = React.createClass({
    radius: 72,
    getInitialState: function() {
      // Use these in CSS for cursor and hover, and to attach listeners
      return {
        n4tappable: (this.props.menu.n4 && this.props.menu.n4.action),
        s4tappable: (this.props.menu.s4 && this.props.menu.s4.action),
        e4tappable: (this.props.menu.e4 && this.props.menu.e4.action),
        w4tappable: (this.props.menu.w4 && this.props.menu.w4.action),
      };
    },
    onTapN4: function () {
      var options = this.props.options;
      this.props.menu.n4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    onTapS4: function () {
      var options = this.props.options;
      this.props.menu.s4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    onTapE4: function () {
      var options = this.props.options;
      this.props.menu.e4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    onTapW4: function () {
      var options = this.props.options;
      this.props.menu.w4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    componentDidMount: function () {
      if (this.state.n4tappable) {
        this.refs.n4.getDOMNode().addEventListener("pointerup", this.onTapN4);
      }
      if (this.state.s4tappable) {
        this.refs.s4.getDOMNode().addEventListener("pointerup", this.onTapS4);
      }
      if (this.state.e4tappable) {
        this.refs.e4.getDOMNode().addEventListener("pointerup", this.onTapE4);
      }
      if (this.state.w4tappable) {
        this.refs.w4.getDOMNode().addEventListener("pointerup", this.onTapW4);
      }

      // Prevent context menu
      this.getDOMNode().addEventListener("contextmenu", function (event) {
        event.stopPropagation();
        event.preventDefault();
      }, false);
    },
    renderSlice: function (direction) {
      var children = [
        React.DOM.path({
          className: "context-arc context-node-info-bg",
          d: TheGraph.arcs[direction]
        }),
      ];
      if (this.props.menu[direction]) {
        var slice = this.props.menu[direction];
        if (slice.icon) {
          children.push(
            React.DOM.text({
              className: "icon context-icon context-node-info-icon",
              x: positions[direction+"IconX"],
              y: positions[direction+"IconY"],
              children: TheGraph.FONT_AWESOME[ slice.icon ]
            })
          );
        }
        if (slice.label) {
          children.push(
            React.DOM.text({
              className: "context-arc-label",
              x: positions[direction+"IconX"],
              y: positions[direction+"IconY"],
              children: slice.label
            })
          );
        }
        if (slice.iconLabel) {
          children.push(
            React.DOM.text({
              className: "context-arc-icon-label",
              x: positions[direction+"LabelX"],
              y: positions[direction+"LabelY"],
              children: slice.iconLabel
            })
          );
        }
      }
      return React.DOM.g(
        {
          ref: direction,
          className: "context-slice context-node-info" + (this.state[direction+"tappable"] ? " click" : ""),
          children: children
        }
      );
    },
    render: function() {
      var menu = this.props.menu;
      var options = this.props.options;
      var x = this.props.x !== undefined ? this.props.x : options.x;
      var y = this.props.y !== undefined ? this.props.y : options.y;

      var children = [
        // Directional slices
        this.renderSlice("n4"),
        this.renderSlice("s4"),
        this.renderSlice("e4"),
        this.renderSlice("w4"),
        // Outline and X
        React.DOM.path({
          className: "context-circle-x",
          d: "M -51 -51 L 51 51 M -51 51 L 51 -51"
        }),
        React.DOM.circle({
          className: "context-circle",
          r: this.radius
        }),
      ];
      // Menu label
      if (this.props.label || menu.icon) {
        children.push(
          React.DOM.text({
            className: "context-node-label",
            x: 0,
            y: 0 - this.radius - 15,
            children: (this.props.label ? this.props.label : menu.label)
          })
        );
      }
      // Middle icon
      if (this.props.icon || menu.icon) {
        var iconColor = (this.props.iconColor!==undefined ? this.props.iconColor : menu.iconColor);
        var iconStyle = "";
        if (iconColor) {
          iconStyle = " fill route"+iconColor;
        }
        children.push(
          React.DOM.rect({
            className: "context-node-rect",
            x: -24,
            y: -24,
            width: 48,
            height: 48,
            rx: TheGraph.nodeRadius,
            ry: TheGraph.nodeRadius
          }),
          React.DOM.text({
            className: "icon context-node-icon"+iconStyle,
            children: TheGraph.FONT_AWESOME[ (this.props.icon ? this.props.icon : menu.icon) ]
          })
        );
      }
      return React.DOM.g({
        className: "context-menu",
        transform: "translate("+x+","+y+")",
        children: children
      });
    }
  });

  TheGraph.ModalBG = React.createClass({
    componentDidMount: function () {
      var domNode = this.getDOMNode();
      var rectNode = this.refs.rect.getDOMNode();

      // Right-click on another item will show its menu
      domNode.addEventListener("pointerdown", function (event) {
        // Only if outside of menu
        if (event.target===rectNode) {
          this.hideModal();
        }
      }.bind(this));
    },
    hideModal: function (event) {
      this.props.triggerHideContext();
    },
    render: function () {
      return React.DOM.g(
        {},
        React.DOM.rect({
          ref: "rect",
          className: "context-modal-bg",
          width: this.props.width,
          height: this.props.height
        }),
        this.props.children
      );
    }
  });

})(this);
<commit_msg>Some safeties, refs noflo/noflo-ui#209<commit_after>(function (context) {
  "use strict";

  var TheGraph = context.TheGraph;

  var positions = {
    n4IconX: 0,
    n4IconY: -52,
    n4LabelX: 0,
    n4LabelY: -35,
    s4IconX: 0,
    s4IconY: 52,
    s4LabelX: 0,
    s4LabelY: 35,
    e4IconX: 45,
    e4IconY: -5,
    e4LabelX: 45,
    e4LabelY: 15,
    w4IconX: -45,
    w4IconY: -5,
    w4LabelX: -45,
    w4LabelY: 15
  };

  TheGraph.Menu = React.createClass({
    radius: 72,
    getInitialState: function() {
      // Use these in CSS for cursor and hover, and to attach listeners
      return {
        n4tappable: (this.props.menu.n4 && this.props.menu.n4.action),
        s4tappable: (this.props.menu.s4 && this.props.menu.s4.action),
        e4tappable: (this.props.menu.e4 && this.props.menu.e4.action),
        w4tappable: (this.props.menu.w4 && this.props.menu.w4.action),
      };
    },
    onTapN4: function () {
      var options = this.props.options;
      this.props.menu.n4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    onTapS4: function () {
      var options = this.props.options;
      this.props.menu.s4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    onTapE4: function () {
      var options = this.props.options;
      this.props.menu.e4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    onTapW4: function () {
      var options = this.props.options;
      this.props.menu.w4.action(options.graph, options.itemKey, options.item);
      this.props.triggerHideContext();
    },
    componentDidMount: function () {
      if (this.state.n4tappable) {
        this.refs.n4.getDOMNode().addEventListener("pointerup", this.onTapN4);
      }
      if (this.state.s4tappable) {
        this.refs.s4.getDOMNode().addEventListener("pointerup", this.onTapS4);
      }
      if (this.state.e4tappable) {
        this.refs.e4.getDOMNode().addEventListener("pointerup", this.onTapE4);
      }
      if (this.state.w4tappable) {
        this.refs.w4.getDOMNode().addEventListener("pointerup", this.onTapW4);
      }

      // Prevent context menu
      this.getDOMNode().addEventListener("contextmenu", function (event) {
        if (event) {
          event.stopPropagation();
          event.preventDefault();
        }
      }, false);
    },
    renderSlice: function (direction) {
      var children = [
        React.DOM.path({
          className: "context-arc context-node-info-bg",
          d: TheGraph.arcs[direction]
        }),
      ];
      if (this.props.menu[direction]) {
        var slice = this.props.menu[direction];
        if (slice.icon) {
          children.push(
            React.DOM.text({
              className: "icon context-icon context-node-info-icon",
              x: positions[direction+"IconX"],
              y: positions[direction+"IconY"],
              children: TheGraph.FONT_AWESOME[ slice.icon ]
            })
          );
        }
        if (slice.label) {
          children.push(
            React.DOM.text({
              className: "context-arc-label",
              x: positions[direction+"IconX"],
              y: positions[direction+"IconY"],
              children: slice.label
            })
          );
        }
        if (slice.iconLabel) {
          children.push(
            React.DOM.text({
              className: "context-arc-icon-label",
              x: positions[direction+"LabelX"],
              y: positions[direction+"LabelY"],
              children: slice.iconLabel
            })
          );
        }
      }
      return React.DOM.g(
        {
          ref: direction,
          className: "context-slice context-node-info" + (this.state[direction+"tappable"] ? " click" : ""),
          children: children
        }
      );
    },
    render: function() {
      var menu = this.props.menu;
      var options = this.props.options;
      var x = this.props.x !== undefined ? this.props.x : options.x;
      var y = this.props.y !== undefined ? this.props.y : options.y;

      var children = [
        // Directional slices
        this.renderSlice("n4"),
        this.renderSlice("s4"),
        this.renderSlice("e4"),
        this.renderSlice("w4"),
        // Outline and X
        React.DOM.path({
          className: "context-circle-x",
          d: "M -51 -51 L 51 51 M -51 51 L 51 -51"
        }),
        React.DOM.circle({
          className: "context-circle",
          r: this.radius
        }),
      ];
      // Menu label
      if (this.props.label || menu.icon) {
        children.push(
          React.DOM.text({
            className: "context-node-label",
            x: 0,
            y: 0 - this.radius - 15,
            children: (this.props.label ? this.props.label : menu.label)
          })
        );
      }
      // Middle icon
      if (this.props.icon || menu.icon) {
        var iconColor = (this.props.iconColor!==undefined ? this.props.iconColor : menu.iconColor);
        var iconStyle = "";
        if (iconColor) {
          iconStyle = " fill route"+iconColor;
        }
        children.push(
          React.DOM.rect({
            className: "context-node-rect",
            x: -24,
            y: -24,
            width: 48,
            height: 48,
            rx: TheGraph.nodeRadius,
            ry: TheGraph.nodeRadius
          }),
          React.DOM.text({
            className: "icon context-node-icon"+iconStyle,
            children: TheGraph.FONT_AWESOME[ (this.props.icon ? this.props.icon : menu.icon) ]
          })
        );
      }
      return React.DOM.g({
        className: "context-menu",
        transform: "translate("+x+","+y+")",
        children: children
      });
    }
  });

  TheGraph.ModalBG = React.createClass({
    componentDidMount: function () {
      var domNode = this.getDOMNode();
      var rectNode = this.refs.rect.getDOMNode();

      // Right-click on another item will show its menu
      domNode.addEventListener("pointerdown", function (event) {
        // Only if outside of menu
        if (event && event.target===rectNode) {
          this.hideModal();
        }
      }.bind(this));
    },
    hideModal: function (event) {
      this.props.triggerHideContext();
    },
    render: function () {
      return React.DOM.g(
        {},
        React.DOM.rect({
          ref: "rect",
          className: "context-modal-bg",
          width: this.props.width,
          height: this.props.height
        }),
        this.props.children
      );
    }
  });

})(this);
<|endoftext|>


<commit_before>window.profiles = {

    'Baroque Works (pre-v4.0)': {
        description: 'Stats of non-Fighter units reduced by 90%',
        thumb: 462,
        atk: function(p) { return !p.class.has('Fighter') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Fighter') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Fighter') ? 0.1 : 1; }
    },

    'Baroque Works': {
        description: 'ATK of Slasher and Strikers units reduced by 85%, HP and RCV by 80%',
        thumb: 462,
        atk: function(p) { return p.class.isWeakened('Slasher','Striker') ? 0.15 : 1; },
        hp: function(p)  { return p.class.isWeakened('Slasher','Striker') ? 0.20 : 1; },
        rcv: function(p) { return p.class.isWeakened('Slasher','Striker') ? 0.20 : 1; }
    },

    'Prisoner Crocodile (pre-v4.0)': {
        description: 'Stats of non-Striker units reduced by 90%',
        thumb: 510,
        atk: function(p) { return !p.class.has('Striker') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Striker') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Striker') ? 0.1 : 1; }
    },

    'Jailer Domino (pre-v4.0)': {
        description: 'Stats of non-Shooter units reduced by 90%',
        thumb: 538,
        atk: function(p) { return !p.class.has('Shooter') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Shooter') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Shooter') ? 0.1 : 1; }
    },

    'Jailer Domino': {
        description: 'Stats of non-Shooter, non-Booster, non-Powerup units reduced by 90%',
        thumb: 538,
        atk: function(p) { return p.class.has('Shooter') || p.class.has('Booster') || p.class.has('PowerUp') ? 0.1 : 1; },
        hp: function(p)  { return p.class.has('Shooter') || p.class.has('Booster') || p.class.has('PowerUp') ? 0.1 : 1; },
        rcv: function(p) { return p.class.has('Shooter') || p.class.has('Booster') || p.class.has('PowerUp') ? 0.1 : 1; }
    },

    'Chief Guard Sadi-chan (pre-v4.0)': {
        description: 'Stats of non-Slasher units reduced by 90%',
        thumb: 550,
        atk: function(p) { return !p.class.has('Slasher') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Slasher') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Slasher') ? 0.1 : 1; }
    },

    'Skypiea Warriors': {
        // Note: The debuff is applied to normal attacks but not to specials
        description: 'Stats of characters whose homeland is not a sky island reduced by 20%',
        thumb: 583,
        atk: function(p) {
            var id = p.number + 1,
                matching = ((id > 463 && id < 497) || (id > 539 && id < 547 ) ||
                    [ 313, 314, 503, 504, 581, 582, 583, 584 ].indexOf(id) != -1);
            return !matching ? 0.8 : 1;
        },
        hp: function(p) {
            var id = p.number + 1,
                matching = ((id > 463 && id < 497) || (id > 539 && id < 547 ) ||
                    [ 313, 314, 503, 504, 581, 582, 583, 584 ].indexOf(id) != -1);
            return !matching ? 0.8 : 1;
        },
        rcv: function(p) {
            var id = p.number + 1,
                matching = ((id > 463 && id < 497) || (id > 539 && id < 547 ) ||
                    [ 313, 314, 503, 504, 581, 582, 583, 584 ].indexOf(id) != -1);
            return !matching ? 0.8 : 1;
        }
    },

    'Skypiea Warriors, Last Round': {
        // Note: The debuff is applied to normal attacks but not to specials
        // Note 2: The 50% reduction is applied to enemy's defense as well, for whatever reason
        description: 'Stats of characters whose homeland is not a sky island reduced by 20%, ATK of PSY characters reduced by 50%',
        thumb: 583,
        atk: function(p) {
            var result = window.profiles['Skypiea Warriors'].atk(p);
            return (p.type == 'PSY' ? 0.5 : 1) * result;
        },
        hp: function(p) { return window.profiles['Skypiea Warriors'].hp(p); },
        rcv: function(p) { return window.profiles['Skypiea Warriors'].rcv(p); },
    },

    'Hancock\'s Bonus (Aokiji\'s Island)': {
        description: 'Orb effects amplified by 1.10x',
        thumb: 415,
        orb: function(p) { return p.orb == 2.0 ? 1.1 : (p.orb == 0.5 ? 10/11 : 1); }
    }

};
<commit_msg>added new profile, fixed older one<commit_after>window.profiles = {

    'Baroque Works (pre-v4.0)': {
        description: 'Stats of non-Fighter units reduced by 90%',
        thumb: 462,
        atk: function(p) { return !p.class.has('Fighter') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Fighter') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Fighter') ? 0.1 : 1; }
    },

    'Baroque Works': {
        description: 'ATK of Slasher and Strikers units reduced by 85%, HP and RCV by 80%',
        thumb: 462,
        atk: function(p) { return p.class.isWeakened('Slasher','Striker') ? 0.15 : 1; },
        hp: function(p)  { return p.class.isWeakened('Slasher','Striker') ? 0.20 : 1; },
        rcv: function(p) { return p.class.isWeakened('Slasher','Striker') ? 0.20 : 1; }
    },

    'Prisoner Crocodile (pre-v4.0)': {
        description: 'Stats of non-Striker units reduced by 90%',
        thumb: 510,
        atk: function(p) { return !p.class.has('Striker') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Striker') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Striker') ? 0.1 : 1; }
    },

    'Prisoner Crocodile)': {
        description: 'Stats of non-Striker, non-Booster, non-Evolver units reduced by 90%',
        thumb: 510,
        atk: function(p) { return p.class.has('Striker') || p.class.has('Booster') || p.class.has('Evolver') ? 1 : 0.1; },
        hp: function(p)  { return p.class.has('Striker') || p.class.has('Booster') || p.class.has('Evolver') ? 1 : 0.1; },
        rcv: function(p) { return p.class.has('Striker') || p.class.has('Booster') || p.class.has('Evolver') ? 1 : 0.1; }
    },

    'Jailer Domino (pre-v4.0)': {
        description: 'Stats of non-Shooter units reduced by 90%',
        thumb: 538,
        atk: function(p) { return !p.class.has('Shooter') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Shooter') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Shooter') ? 0.1 : 1; }
    },

    'Jailer Domino': {
        description: 'Stats of non-Shooter, non-Booster, non-Evolver units reduced by 90%',
        thumb: 538,
        atk: function(p) { return p.class.has('Shooter') || p.class.has('Booster') || p.class.has('Evolver') ? 1 : 0.1; },
        hp: function(p)  { return p.class.has('Shooter') || p.class.has('Booster') || p.class.has('Evolver') ? 1 : 0.1; },
        rcv: function(p) { return p.class.has('Shooter') || p.class.has('Booster') || p.class.has('Evolver') ? 1 : 0.1; }
    },

    'Chief Guard Sadi-chan (pre-v4.0)': {
        description: 'Stats of non-Slasher units reduced by 90%',
        thumb: 550,
        atk: function(p) { return !p.class.has('Slasher') ? 0.1 : 1; },
        hp: function(p)  { return !p.class.has('Slasher') ? 0.1 : 1; },
        rcv: function(p) { return !p.class.has('Slasher') ? 0.1 : 1; }
    },

    'Skypiea Warriors': {
        // Note: The debuff is applied to normal attacks but not to specials
        description: 'Stats of characters whose homeland is not a sky island reduced by 20%',
        thumb: 583,
        atk: function(p) {
            var id = p.number + 1,
                matching = ((id > 463 && id < 497) || (id > 539 && id < 547 ) ||
                    [ 313, 314, 503, 504, 581, 582, 583, 584 ].indexOf(id) != -1);
            return !matching ? 0.8 : 1;
        },
        hp: function(p) {
            var id = p.number + 1,
                matching = ((id > 463 && id < 497) || (id > 539 && id < 547 ) ||
                    [ 313, 314, 503, 504, 581, 582, 583, 584 ].indexOf(id) != -1);
            return !matching ? 0.8 : 1;
        },
        rcv: function(p) {
            var id = p.number + 1,
                matching = ((id > 463 && id < 497) || (id > 539 && id < 547 ) ||
                    [ 313, 314, 503, 504, 581, 582, 583, 584 ].indexOf(id) != -1);
            return !matching ? 0.8 : 1;
        }
    },

    'Skypiea Warriors, Last Round': {
        // Note: The debuff is applied to normal attacks but not to specials
        // Note 2: The 50% reduction is applied to enemy's defense as well, for whatever reason
        description: 'Stats of characters whose homeland is not a sky island reduced by 20%, ATK of PSY characters reduced by 50%',
        thumb: 583,
        atk: function(p) {
            var result = window.profiles['Skypiea Warriors'].atk(p);
            return (p.type == 'PSY' ? 0.5 : 1) * result;
        },
        hp: function(p) { return window.profiles['Skypiea Warriors'].hp(p); },
        rcv: function(p) { return window.profiles['Skypiea Warriors'].rcv(p); },
    },

    'Hancock\'s Bonus (Aokiji\'s Island)': {
        description: 'Orb effects amplified by 1.10x',
        thumb: 415,
        orb: function(p) { return p.orb == 2.0 ? 1.1 : (p.orb == 0.5 ? 10/11 : 1); }
    }

};
<|endoftext|>


<commit_before>import { displayError, displayInfo, displaySuccess } from 'modules/scripts/display'
import * as services from 'server/services/all'

const SHUTDOWN_TIMEOUT = 3000

let shutdown = false
const callbacks = [() => services.disconnect()]

/**
 * terminator === the termination handler
 * Terminate server on receipt of the specified signal.
 * @param {string} signal  Signal to terminate on.
 */
function terminator(signal) {
  if (typeof signal === 'string') {
    displayInfo(`Received ${signal}.`)
  }

  // At the first SIGTERM, we try to shutdown the service gracefully
  if ((signal === 'SIGTERM' || signal === 'SIGINT') && !shutdown) {
    displayInfo('Shutdown server gracefully...')
    displayInfo(`${SHUTDOWN_TIMEOUT}ms before killing it.`)
    const timer = setTimeout(() => {
      displayError('Force shutdown')
      terminator()
    }, SHUTDOWN_TIMEOUT)
    Promise.all(callbacks.map(callback => callback())).then(() => {
      clearTimeout(timer)
      displaySuccess('Node server stopped.')
    })
    shutdown = true
    return
  }

  process.exit(1) // eslint-disable-line no-process-exit
}

function handleKillSignals() {
  //  Process on exit and signals.
  process.on('exit', () => {
    displaySuccess('Node server stopped.')
  })

  // Removed 'SIGPIPE' from the list - bugz 852598.
  ;[
    'SIGHUP',
    'SIGINT',
    'SIGQUIT',
    'SIGILL',
    'SIGTRAP',
    'SIGABRT',
    'SIGBUS',
    'SIGFPE',
    'SIGUSR1',
    'SIGSEGV',
    'SIGUSR2',
    'SIGTERM',
  ].forEach(signal => {
    process.on(signal, () => {
      terminator(signal)
    })
  })
}

export function addCloseCallback(callback) {
  callbacks.push(callback)
}

export default handleKillSignals
<commit_msg>fix(js): fix leak in dev mode<commit_after>import { displayError, displayInfo, displaySuccess } from 'modules/scripts/display'
import * as services from 'server/services/all'

const SHUTDOWN_TIMEOUT = 3000

let shutdown = false
const callbacks = [() => services.disconnect()]

/**
 * terminator === the termination handler
 * Terminate server on receipt of the specified signal.
 * @param {string} signal  Signal to terminate on.
 */
function terminator(signal) {
  if (typeof signal === 'string') {
    displayInfo(`Received ${signal}.`)
  }

  // At the first SIGTERM, we try to shutdown the service gracefully
  if ((signal === 'SIGTERM' || signal === 'SIGINT') && !shutdown) {
    displayInfo('Shutdown server gracefully...')
    displayInfo(`${SHUTDOWN_TIMEOUT}ms before killing it.`)
    const timer = setTimeout(() => {
      displayError('Force shutdown')
      terminator()
    }, SHUTDOWN_TIMEOUT)
    Promise.all(callbacks.map(callback => callback())).then(() => {
      clearTimeout(timer)
      process.exit(0)
    })
    shutdown = true
    return
  }

  process.exit(1)
}

function handleKillSignals() {
  //  Process on exit and signals.
  process.on('exit', () => {
    displaySuccess('Node server stopped.')
  })

  // Removed 'SIGPIPE' from the list - bugz 852598.
  ;[
    'SIGHUP',
    'SIGINT',
    'SIGQUIT',
    'SIGILL',
    'SIGTRAP',
    'SIGABRT',
    'SIGBUS',
    'SIGFPE',
    'SIGUSR1',
    'SIGSEGV',
    'SIGUSR2',
    'SIGTERM',
  ].forEach(signal => {
    process.on(signal, () => {
      terminator(signal)
    })
  })
}

export function addCloseCallback(callback) {
  callbacks.push(callback)
}

export default handleKillSignals
<|endoftext|>