<commit_before>var test = require('tape');
var nlp = require('./lib/nlp');
var str_test = require('./lib/fns').str_test;

test('==Value==', function(T) {

  T.test('to_ordinal:', function(t) {
    [
      [11, '11th'],
      [5, '5th'],
      [22, '22nd'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).to_ordinal();
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('number:', function(t) {
    [
      ['five hundred feet', 500],
      ['fifty square feet', 50],
      ['90 hertz', 90],
      ['5 six-ounce containers', 5],
      ['twelve 2-gram containers', 12],
      ['thirty-seven forever-21 stores', 37],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).number;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('unit:', function(t) {
    [
      ['five hundred feet', 'feet'],
      ['fifty hertz', 'hertz'],
      ['100 dollars', 'dollar'],
      ['$100', 'dollar'],
      ['¥2.5', 'yen'],
      ['€3,000,100', 'euro'],
      ['EUR 9.99', 'eur'],
      ['5 g', 'g'],
      ['3 grams', 'gram'],
      ['2 inches', 'inch'],
      ['2 in', 'in'],
      ['5 g sugar', 'g'],
      ['10 grams of sugar', 'gram'],
      ['fifty inches of snow', 'inch'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).unit;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('measurement:', function(t) {
    [
      ['five hundred feet', 'Distance'],
      ['100 kilometers', 'Distance'],
      ['fifty hertz', 'Frequency'],
      ['59 thousand $', 'Money'],
      ['100 mb', 'Data'],
      ['50 руб', 'Money'],
      ['EUR 9.99', 'Money'],
      ['100 dollars', 'Money'],
      ['256 bitcoins', 'Money'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).measurement;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('of_what:', function(t) {
    [
      ['nine kg', 'kg'],
      ['5 kg of copper', 'copper'],
      ['many of these stories', 'many of these stories'],
      ['room full of beautiful creatures', 'full of beautiful creatures'],
      ['boxes of bags of food', 'boxes of bags of food'],
      ['5 boxes of water', 'boxes of water'],
      ['6 of kids', 'kids'],
      ['10 kids', 'kids'],
      ['just nothing', 'just nothing'],
      ['EUR 77', 'eur'],
      ['kg', 'kg']
    ].forEach(function (a) {
      var str = nlp.value(a[0]).of_what;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('to_text:', function(t) {
    [
      // [-5, 'negative five'],
      [5, 'five'],
      [15, 'fifteen'],
      [10, 'ten'],
      [20, 'twenty'],
      [75, 'seventy five'],
      [97, 'ninety seven'],
      [111, 'one hundred and eleven'],
      [175, 'one hundred and seventy five'],
      [900, 'nine hundred'],
      [1175, 'one thousand one hundred and seventy five'],
      [2000, 'two thousand'],
      [2100, 'two thousand one hundred'],
      [2102, 'two thousand one hundred and two'],
      [70000, 'seventy thousand'],
      [72000, 'seventy two thousand'],
      [900000, 'nine hundred thousand'],
      [900001, 'nine hundred thousand and one'],
      [900200, 'nine hundred thousand two hundred'],
      [900205, 'nine hundred thousand two hundred and five'],
      [7900205, 'seven million nine hundred thousand two hundred and five'],
      [90000000, 'ninety million'],
      [900000000, 'nine hundred million'],
      [900000080, 'nine hundred million and eighty'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).textual();
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('to_number:', function(t) {
    [
      ['twenty two thousand five hundred', 22500],
      ['two thousand five hundred and sixty', 2560],
      ['a hundred and two', 102],
      ['a hundred', 100],
      ['seven', 7],
      ['seven grand', 7000],
      ['104', 104],
      ['13 thousand', 13000],
      ['17,983', 17983],
      ['nine hundred', 900],
      ['twenty one hundred', 2100],
      ['twenty one', 21],
      ['seventy two', 72],
      ['two hundred two', 202],
      ['one thousand one', 1001],
      ['minus five hundred', -500],
      ['minus fifteen', -15],
      ['five hundred million', 500000000],
      ['$12.03', 12.03],
      ['$12', 12],
      ['5 hundred', 500],
      ['5.2 thousand', 5200],
      ['million', 1000000],
      ['hundred one', 101],
      ['minus fifty', -50],
      ['twenty thousand', 20000],
      ['four point six', 4.6],
      ['nine hundred point five', 900.5],
      ['sixteen hundred sixteen point eight', 1616.8],
      ['four point seven nine', 4.79],
      ['four point sixteen', 4.16],
      ['twenty first', 21],
      ['fifty ninth', 59],
      ['nine hundred fiftieth', 950],
      ['five thousand nine hundred fiftieth', 5950],
      ['six hundred and fifty nine', 659],
      ['six hundred and fifty nine thousand', 659000],
      [950, 950],
      [999999950, 999999950],
      [8080999999950, 8080999999950],
      ['fifteen million and two', 15000002],
      ['six hundred and eighteen', 618],
      ['two hundred thousand', 200000],
      ['six million ninety', 6000090],
      ['twenty-two hundred', 2200],
      ['minus 70', -70],
      ['minus eight', -8],
      ['minus 8 hundred', -800],
      ['twenty-seven hundred', 2700],
      ['minus eight thousand two hundred', -8200],
      ['twenty-five', 25],
      ['half a million', 500000],
      ['five hundred eighteen', 518],
      ['eighty eight point nine nine', 88.99],
      ['minus eighty eight point nine nine', -88.99],
      ['1/2', 1 / 2],
      ['-1/5', -1 / 5],
      ['-1 1/10', -1 - 1 / 10],
      ['1 1/20', 1 + 1 / 20],
      ['1/2 million', 500000],
      ['1 1/2 million', 1500000],
      ['negative five', -5],
      ['negative hundred', -100],
      ['12:32', null],
      ['123-1231', null],
      ['seven eleven', null],
      ['ten-four', null],
      ['one seven', null],
      ['one ten', null],
      ['one twelve', null],
      ['one thirty', null],
      ['nine fifty', null],
      ['five six', null],
      ['nine seventy', null],
      ['nine two hundred', null],
      ['ten one', null],
      ['twelve one', null],
      ['seventy five two', null],
      ['two hundred three hundred', null],
      ['sixty fifteen hundred', null],
      ['one twenty', null],
      ['twenty five twenty', null],
    // ['', null],
    // [null, null],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).number;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

});
<commit_msg>fix test<commit_after>var test = require('tape');
var nlp = require('./lib/nlp');
var str_test = require('./lib/fns').str_test;

test('==Value==', function(T) {

  T.test('to_ordinal:', function(t) {
    [
      [11, '11th'],
      [5, '5th'],
      [22, '22nd'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).to_ordinal();
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('number:', function(t) {
    [
      ['five hundred feet', 500],
      ['fifty square feet', 50],
      ['90 hertz', 90],
      ['5 six-ounce containers', 5],
      ['twelve 2-gram containers', 12],
      ['thirty-seven forever-21 stores', 37],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).number;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('unit:', function(t) {
    [
      ['five hundred feet', 'feet'],
      ['fifty hertz', 'hertz'],
      ['100 dollars', 'dollars'],
      ['$100', 'dollar'],
      ['¥2.5', 'yen'],
      ['€3,000,100', 'euro'],
      ['EUR 9.99', 'eur'],
      ['5 g', 'g'],
      ['3 grams', 'gram'],
      ['2 inches', 'inch'],
      ['2 in', 'in'],
      ['5 g sugar', 'g'],
      ['10 grams of sugar', 'gram'],
      ['fifty inches of snow', 'inch'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).unit;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('measurement:', function(t) {
    [
      ['five hundred feet', 'Distance'],
      ['100 kilometers', 'Distance'],
      ['fifty hertz', 'Frequency'],
      ['59 thousand $', 'Money'],
      ['100 mb', 'Data'],
      ['50 руб', 'Money'],
      ['EUR 9.99', 'Money'],
      ['100 dollars', 'Money'],
      ['256 bitcoins', 'Money'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).measurement;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('of_what:', function(t) {
    [
      ['nine kg', 'kg'],
      ['5 kg of copper', 'copper'],
      ['many of these stories', 'many of these stories'],
      ['room full of beautiful creatures', 'full of beautiful creatures'],
      ['boxes of bags of food', 'boxes of bags of food'],
      ['5 boxes of water', 'boxes of water'],
      ['6 of kids', 'kids'],
      ['10 kids', 'kids'],
      ['just nothing', 'just nothing'],
      ['EUR 77', 'eur'],
      ['kg', 'kg']
    ].forEach(function (a) {
      var str = nlp.value(a[0]).of_what;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('to_text:', function(t) {
    [
      // [-5, 'negative five'],
      [5, 'five'],
      [15, 'fifteen'],
      [10, 'ten'],
      [20, 'twenty'],
      [75, 'seventy five'],
      [97, 'ninety seven'],
      [111, 'one hundred and eleven'],
      [175, 'one hundred and seventy five'],
      [900, 'nine hundred'],
      [1175, 'one thousand one hundred and seventy five'],
      [2000, 'two thousand'],
      [2100, 'two thousand one hundred'],
      [2102, 'two thousand one hundred and two'],
      [70000, 'seventy thousand'],
      [72000, 'seventy two thousand'],
      [900000, 'nine hundred thousand'],
      [900001, 'nine hundred thousand and one'],
      [900200, 'nine hundred thousand two hundred'],
      [900205, 'nine hundred thousand two hundred and five'],
      [7900205, 'seven million nine hundred thousand two hundred and five'],
      [90000000, 'ninety million'],
      [900000000, 'nine hundred million'],
      [900000080, 'nine hundred million and eighty'],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).textual();
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

  T.test('to_number:', function(t) {
    [
      ['twenty two thousand five hundred', 22500],
      ['two thousand five hundred and sixty', 2560],
      ['a hundred and two', 102],
      ['a hundred', 100],
      ['seven', 7],
      ['seven grand', 7000],
      ['104', 104],
      ['13 thousand', 13000],
      ['17,983', 17983],
      ['nine hundred', 900],
      ['twenty one hundred', 2100],
      ['twenty one', 21],
      ['seventy two', 72],
      ['two hundred two', 202],
      ['one thousand one', 1001],
      ['minus five hundred', -500],
      ['minus fifteen', -15],
      ['five hundred million', 500000000],
      ['$12.03', 12.03],
      ['$12', 12],
      ['5 hundred', 500],
      ['5.2 thousand', 5200],
      ['million', 1000000],
      ['hundred one', 101],
      ['minus fifty', -50],
      ['twenty thousand', 20000],
      ['four point six', 4.6],
      ['nine hundred point five', 900.5],
      ['sixteen hundred sixteen point eight', 1616.8],
      ['four point seven nine', 4.79],
      ['four point sixteen', 4.16],
      ['twenty first', 21],
      ['fifty ninth', 59],
      ['nine hundred fiftieth', 950],
      ['five thousand nine hundred fiftieth', 5950],
      ['six hundred and fifty nine', 659],
      ['six hundred and fifty nine thousand', 659000],
      [950, 950],
      [999999950, 999999950],
      [8080999999950, 8080999999950],
      ['fifteen million and two', 15000002],
      ['six hundred and eighteen', 618],
      ['two hundred thousand', 200000],
      ['six million ninety', 6000090],
      ['twenty-two hundred', 2200],
      ['minus 70', -70],
      ['minus eight', -8],
      ['minus 8 hundred', -800],
      ['twenty-seven hundred', 2700],
      ['minus eight thousand two hundred', -8200],
      ['twenty-five', 25],
      ['half a million', 500000],
      ['five hundred eighteen', 518],
      ['eighty eight point nine nine', 88.99],
      ['minus eighty eight point nine nine', -88.99],
      ['1/2', 1 / 2],
      ['-1/5', -1 / 5],
      ['-1 1/10', -1 - 1 / 10],
      ['1 1/20', 1 + 1 / 20],
      ['1/2 million', 500000],
      ['1 1/2 million', 1500000],
      ['negative five', -5],
      ['negative hundred', -100],
      ['12:32', null],
      ['123-1231', null],
      ['seven eleven', null],
      ['ten-four', null],
      ['one seven', null],
      ['one ten', null],
      ['one twelve', null],
      ['one thirty', null],
      ['nine fifty', null],
      ['five six', null],
      ['nine seventy', null],
      ['nine two hundred', null],
      ['ten one', null],
      ['twelve one', null],
      ['seventy five two', null],
      ['two hundred three hundred', null],
      ['sixty fifteen hundred', null],
      ['one twenty', null],
      ['twenty five twenty', null],
    // ['', null],
    // [null, null],
    ].forEach(function (a) {
      var str = nlp.value(a[0]).number;
      str_test(str, a[0], a[1], t);
    });
    t.end();
  });

});
<|endoftext|>


<commit_before>/**
 *
 * syncthing adapter
 *
 *
 *  file io-package.json comments:
 *
 *  {
 *      "common": {
 *          "name":         "syncthing",                  // name has to be set and has to be equal to adapters folder name and main file name excluding extension
 *          "version":      "0.0.0",                    // use "Semantic Versioning"! see http://semver.org/
 *          "title":        "Node.js syncthing Adapter",  // Adapter title shown in User Interfaces
 *          "authors":  [                               // Array of authord
 *              "name <mail@syncthing.com>"
 *          ]
 *          "desc":         "syncthing adapter",          // Adapter description shown in User Interfaces. Can be a language object {de:"...",ru:"..."} or a string
 *          "platform":     "Javascript/Node.js",       // possible values "javascript", "javascript/Node.js" - more coming
 *          "mode":         "daemon",                   // possible values "daemon", "schedule", "subscribe"
 *          "schedule":     "0 0 * * *"                 // cron-style schedule. Only needed if mode=schedule
 *          "loglevel":     "info"                      // Adapters Log Level
 *      },
 *      "native": {                                     // the native object is available via adapter.config in your adapters code - use it for configuration
 *          "syncthingurl": "",
 *          "syncthingapikey": "",
 *          "syncthingfolderid" : ""
 *      }
 *  }
 *
 */

/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";

// you have to require the utils module and call adapter function
var utils =    require(__dirname + '/lib/utils'); // Get common adapter utils

// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.syncthing.0
var adapter = utils.adapter('syncthing');

// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
    try {
        adapter.log.info('cleaned everything up...');
        callback();
    } catch (e) {
        callback();
    }
});

// is called if a subscribed object changes
adapter.on('objectChange', function (id, obj) {
    // Warning, obj can be null if it was deleted
    adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj));
});

// is called if a subscribed state changes
adapter.on('stateChange', function (id, state) {
    // Warning, state can be null if it was deleted
    adapter.log.info('stateChange ' + id + ' ' + JSON.stringify(state));

    // you can use the ack flag to detect if it is status (true) or command (false)
    if (state && !state.ack) {
        adapter.log.info('ack is not set!');
    }
});

// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', function (obj) {
    if (typeof obj == 'object' && obj.message) {
        if (obj.command == 'send') {
            // e.g. send email or pushover or whatever
            console.log('send command');

            // Send response in callback if required
            if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
        }
    }
});

// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', function () {
    main();
});

function main() {

    // The adapters config (in the instance object everything under the attribute "native") is accessible via
    // adapter.config:
    adapter.log.info('config syncthingurl: ' + adapter.config.syncthingurl);
    adapter.log.info('config syncthingapikey: ' + adapter.config.syncthingapikey);
    adapter.log.info('config syncthingfolderid: ' + adapter.config.syncthingfolderid);

    /**
     *      For every state in the system there has to be also an object of type state
     *      Here a simple syncthing for a boolean variable named "testVariable"
     *      Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
     */

    adapter.setObject('testVariable', {
        type: 'state',
        common: {
            name: 'testVariable',
            type: 'boolean',
            role: 'indicator'
        },
        native: {}
    });

    // in this syncthing all states changes inside the adapters namespace are subscribed
    adapter.subscribeStates('*');

    /**
     *   setState examples
     *   you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
     */

    // the variable testVariable is set to true as command (ack=false)
    adapter.setState('testVariable', true);

    // same thing, but the value is flagged "ack"
    // ack should be always set to true if the value is received from or acknowledged from the target system
    adapter.setState('testVariable', {val: true, ack: true});

    // same thing, but the state is deleted after 30s (getState will return null afterwards)
    adapter.setState('testVariable', {val: true, ack: true, expire: 30});

    // examples for the checkPassword/checkGroup functions
    adapter.checkPassword('admin', 'iobroker', function (res) {
        console.log('check user admin pw ioboker: ' + res);
    });

    adapter.checkGroup('admin', 'admin', function (res) {
        console.log('check group user admin group admin: ' + res);
    });

}
<commit_msg>Update<commit_after>/**
 *
 * syncthing adapter
 *
 *
 *  file io-package.json comments:
 *
 *  {
 *      "common": {
 *          "name":         "syncthing",                  // name has to be set and has to be equal to adapters folder name and main file name excluding extension
 *          "version":      "0.0.0",                    // use "Semantic Versioning"! see http://semver.org/
 *          "title":        "Node.js syncthing Adapter",  // Adapter title shown in User Interfaces
 *          "authors":  [                               // Array of authord
 *              "name <mail@syncthing.com>"
 *          ]
 *          "desc":         "syncthing adapter",          // Adapter description shown in User Interfaces. Can be a language object {de:"...",ru:"..."} or a string
 *          "platform":     "Javascript/Node.js",       // possible values "javascript", "javascript/Node.js" - more coming
 *          "mode":         "daemon",                   // possible values "daemon", "schedule", "subscribe"
 *          "schedule":     "0 0 * * *"                 // cron-style schedule. Only needed if mode=schedule
 *          "loglevel":     "info"                      // Adapters Log Level
 *      },
 *      "native": {                                     // the native object is available via adapter.config in your adapters code - use it for configuration
 *          "syncthingurl": "",
 *          "syncthingapikey": "",
 *          "syncthingfolderid" : ""
 *      }
 *  }
 *
 */

/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";

// you have to require the utils module and call adapter function
var utils =    require(__dirname + '/lib/utils'); // Get common adapter utils

// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.syncthing.0
var adapter = utils.adapter('syncthing');

// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
    try {
        adapter.log.info('cleaned everything up...');
        callback();
    } catch (e) {
        callback();
    }
});

// is called if a subscribed object changes
adapter.on('objectChange', function (id, obj) {
    // Warning, obj can be null if it was deleted
    adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj));
});

// is called if a subscribed state changes
adapter.on('stateChange', function (id, state) {
    // Warning, state can be null if it was deleted
    adapter.log.info('stateChange ' + id + ' ' + JSON.stringify(state));

    // you can use the ack flag to detect if it is status (true) or command (false)
    if (state && !state.ack) {
        adapter.log.info('ack is not set!');
    }
});

// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', function (obj) {
    if (typeof obj == 'object' && obj.message) {
        if (obj.command == 'send') {
            // e.g. send email or pushover or whatever
            console.log('send command');

            // Send response in callback if required
            if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
        }
    }
});

// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', function () {
    main();
});

function main() {

    // The adapters config (in the instance object everything under the attribute "native") is accessible via
    // adapter.config:
    adapter.log.info('config syncthingurl: ' + adapter.config.syncthingurl);
    adapter.log.info('config syncthingapikey: ' + adapter.config.syncthingapikey);
    adapter.log.info('config syncthingfolderid: ' + adapter.config.syncthingfolderid);

    /**
     *      For every state in the system there has to be also an object of type state
     *      Here a simple syncthing for a boolean variable named "testVariable"
     *      Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
     */

    adapter.setObject('testVariable', {
        type: 'state',
        common: {
            name: 'testVariable',
            type: 'boolean',
            role: 'indicator'
        },
        native: {}
    });

    adapter.setObject('folderState', {
        type: 'state',
        common: {
            name: 'folderState',
            type: 'string',
            role: 'indicator'
        },
        native: {}
    });

    adapter.setObject('folderStateChange', {
        type: 'state',
        common: {
            name: 'folderStateChange',
            type: 'string',
            role: 'indicator'
        },
        native: {}
    });

    adapter.setObject('folderLocalBytes', {
        type: 'state',
        common: {
            name: 'folderLocalBytes',
            type: 'number',
            role: 'indicator'
        },
        native: {}
    });

    adapter.setObject('folderGlobalBytes', {
        type: 'state',
        common: {
            name: 'folderLocalBytes',
            type: 'number',
            role: 'indicator'
        },
        native: {}
    });

    // in this syncthing all states changes inside the adapters namespace are subscribed
    adapter.subscribeStates('*');

    /**
     *   setState examples
     *   you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
     */

    // the variable testVariable is set to true as command (ack=false)
    adapter.setState('testVariable', true);

    // same thing, but the value is flagged "ack"
    // ack should be always set to true if the value is received from or acknowledged from the target system
    adapter.setState('testVariable', {val: true, ack: true});

    // same thing, but the state is deleted after 30s (getState will return null afterwards)
    adapter.setState('testVariable', {val: true, ack: true, expire: 30});

    // examples for the checkPassword/checkGroup functions
    adapter.checkPassword('admin', 'iobroker', function (res) {
        console.log('check user admin pw ioboker: ' + res);
    });

    adapter.checkGroup('admin', 'admin', function (res) {
        console.log('check group user admin group admin: ' + res);
    });

}
<|endoftext|>


<commit_before>const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
const Menu = electron.Menu;
const path = require('path');
const os = require('os');
const autoUpdater = electron.autoUpdater;
//electron.crashReporter.start();

var platform = os.platform() + '_' + os.arch();
var version = app.getVersion();

var mainWindow = null;
var procStarted = false;
var subpy = null;
var mainAddr;

try {
  autoUpdater.setFeedURL('https://pokemon-go-updater.mike.ai/update/'+platform+'/'+version);
} catch (e) {}

autoUpdater.on('update-downloaded', function(){
  mainWindow.webContents.send('update-ready');
});

// Setup menu bar
var template = [{
    label: "Application",
    submenu: [{
        label: "About Application",
        selector: "orderFrontStandardAboutPanel:"
    }, {
        type: "separator"
    }, {
        label: "Quit",
        accelerator: "Command+Q",
        click: function() {
            app.quit();
        }
    }]
}, {
    label: "Edit",
    submenu: [{
        label: "Undo",
        accelerator: "CmdOrCtrl+Z",
        selector: "undo:"
    }, {
        label: "Redo",
        accelerator: "Shift+CmdOrCtrl+Z",
        selector: "redo:"
    }, {
        type: "separator"
    }, {
        label: "Cut",
        accelerator: "CmdOrCtrl+X",
        selector: "cut:"
    }, {
        label: "Copy",
        accelerator: "CmdOrCtrl+C",
        selector: "copy:"
    }, {
        label: "Paste",
        accelerator: "CmdOrCtrl+V",
        selector: "paste:"
    }, {
        label: "Select All",
        accelerator: "CmdOrCtrl+A",
        selector: "selectAll:"
    }]
},
{
    label: "Tools",
    submenu: [
      {
        label: "Refresh",
        accelerator: "CmdOrCtrl+R",
        click(item, focusedWindow) {
          if (focusedWindow) focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
        click(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.webContents.toggleDevTools();
        }
      }
    ]
  }];

app.on('window-all-closed', function() {
  if (subpy && subpy.pid) {
    killProcess(subpy.pid);
  }
  app.quit();
});

app.on('ready', function() {

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow = new BrowserWindow({width: 800, height: 600, minWidth: 700, minHeight: 500});
  mainWindow.loadURL('file://' + __dirname + '/login.html');

  var template = [{
      label: "Application",
      submenu: [{
          label: "About Application",
          selector: "orderFrontStandardAboutPanel:"
      }, {
          type: "separator"
      }, {
          label: "Quit",
          accelerator: "Command+Q",
          click: function() {
              app.quit();
          }
      }]
  }, {
      label: "Edit",
      submenu: [{
          label: "Undo",
          accelerator: "CmdOrCtrl+Z",
          selector: "undo:"
      }, {
          label: "Redo",
          accelerator: "Shift+CmdOrCtrl+Z",
          selector: "redo:"
      }, {
          type: "separator"
      }, {
          label: "Cut",
          accelerator: "CmdOrCtrl+X",
          selector: "cut:"
      }, {
          label: "Copy",
          accelerator: "CmdOrCtrl+C",
          selector: "copy:"
      }, {
          label: "Paste",
          accelerator: "CmdOrCtrl+V",
          selector: "paste:"
      }, {
          label: "Select All",
          accelerator: "CmdOrCtrl+A",
          selector: "selectAll:"
      }]
  }];

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow.on('closed', function() {
    mainWindow = null;
    if (subpy && subpy.pid) {
      killProcess(subpy.pid);
    }
  });
});

function logData(str){
  console.log(str);
  // if(mainWindow){
  //   mainWindow.webContents.executeJavaScript('console.log(unescape("'+escape(str)+'"))');
  // }
}

function killProcess(pid) {
  try {
    process.kill(-pid, 'SIGINT');
  } catch (e) {
    process.kill(pid, 'SIGINT');
  }
}

ipcMain.on('startPython', function(event, auth, code, lat, long) {
  if (!procStarted) {
    logData('Starting Python process...');
    startPython(auth, code, lat, long);
  }
  procStarted = true;
});

ipcMain.on('getServer', function(event) {
  event.sender.send('server-up', mainAddr);
});

ipcMain.on('installUpdate', function(event) {
  autoUpdater.quitAndInstall();
});

function startPython(auth, code, lat, long) {

  mainWindow.loadURL('file://' + __dirname + '/main.html');
  //mainWindow.openDevTools();

  // Find open port
  var portfinder = require('portfinder');
  portfinder.getPort(function (err, port) {

    logData('Got open port: ' + port);

    // Run python web server
    var cmdLine = [
      './example.py',
      '--auth_service',
      auth,
      '--token',
      code,
      '--location',
      lat + ',' + long,
      '--auto_refresh',
      '10',
      '--step-limit',
      '7',
      //'--display-pokestop',
      '--display-gym',
      '--port',
      port,
      '--parent_pid',
      process.pid
    ];
    // console.log(cmdLine);
    logData('Maps path: ' + path.join(__dirname, 'map'));
    logData('python ' + cmdLine.join(' '))

    var pythonCmd = 'python';
    if (os.platform() == 'win32') {
      pythonCmd = path.join(__dirname, 'pywin', 'python.exe');
    }

    subpy = require('child_process').spawn(pythonCmd, cmdLine, {
      cwd: path.join(__dirname, 'map'),
      detached: true
    });

    subpy.stdout.on('data', (data) => {
      logData(`Python: ${data}`);
    });
    subpy.stderr.on('data', (data) => {
      logData(`Python: ${data}`);
    });

    var rq = require('request-promise');
    mainAddr = 'http://localhost:' + port;

    var openWindow = function(){
      mainWindow.webContents.send('server-up', mainAddr);
      mainWindow.webContents.executeJavaScript(
        'serverUp("'+mainAddr+'")');
      mainWindow.on('closed', function() {
        mainWindow = null;
        if (subpy && subpy.pid) {
          killProcess(subpy.pid);
        }
        procStarted = false;
      });
    };

    var startUp = function(){
      rq(mainAddr)
        .then(function(htmlString){
          logData('server started!');
          openWindow();
        })
        .catch(function(err){
          //console.log('waiting for the server start...');
          startUp();
        });
    };

    startUp();

  });

};
<commit_msg>Messed up the merge<commit_after>const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
const Menu = electron.Menu;
const path = require('path');
const os = require('os');
const autoUpdater = electron.autoUpdater;
//electron.crashReporter.start();

var platform = os.platform() + '_' + os.arch();
var version = app.getVersion();

var mainWindow = null;
var procStarted = false;
var subpy = null;
var mainAddr;

try {
  autoUpdater.setFeedURL('https://pokemon-go-updater.mike.ai/update/'+platform+'/'+version);
} catch (e) {}

autoUpdater.on('update-downloaded', function(){
  mainWindow.webContents.send('update-ready');
});

// Setup menu bar
var template = [{
    label: "Application",
    submenu: [{
        label: "About Application",
        selector: "orderFrontStandardAboutPanel:"
    }, {
        type: "separator"
    }, {
        label: "Quit",
        accelerator: "Command+Q",
        click: function() {
            app.quit();
        }
    }]
}, {
    label: "Edit",
    submenu: [{
        label: "Undo",
        accelerator: "CmdOrCtrl+Z",
        selector: "undo:"
    }, {
        label: "Redo",
        accelerator: "Shift+CmdOrCtrl+Z",
        selector: "redo:"
    }, {
        type: "separator"
    }, {
        label: "Cut",
        accelerator: "CmdOrCtrl+X",
        selector: "cut:"
    }, {
        label: "Copy",
        accelerator: "CmdOrCtrl+C",
        selector: "copy:"
    }, {
        label: "Paste",
        accelerator: "CmdOrCtrl+V",
        selector: "paste:"
    }, {
        label: "Select All",
        accelerator: "CmdOrCtrl+A",
        selector: "selectAll:"
    }]
},
{
    label: "Tools",
    submenu: [
      {
        label: "Refresh",
        accelerator: "CmdOrCtrl+R",
        click(item, focusedWindow) {
          if (focusedWindow) focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
        click(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.webContents.toggleDevTools();
        }
      }
    ]
}
];

app.on('window-all-closed', function() {
  if (subpy && subpy.pid) {
    killProcess(subpy.pid);
  }
  app.quit();
});

app.on('ready', function() {

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));

  mainWindow = new BrowserWindow({width: 800, height: 600, minWidth: 700, minHeight: 500});
  mainWindow.loadURL('file://' + __dirname + '/login.html');

  mainWindow.on('closed', function() {
    mainWindow = null;
    if (subpy && subpy.pid) {
      killProcess(subpy.pid);
    }
  });
});

function logData(str){
  console.log(str);
  // if(mainWindow){
  //   mainWindow.webContents.executeJavaScript('console.log(unescape("'+escape(str)+'"))');
  // }
}

function killProcess(pid) {
  try {
    process.kill(-pid, 'SIGINT');
  } catch (e) {
    process.kill(pid, 'SIGINT');
  }
}

ipcMain.on('startPython', function(event, auth, code, lat, long) {
  if (!procStarted) {
    logData('Starting Python process...');
    startPython(auth, code, lat, long);
  }
  procStarted = true;
});

ipcMain.on('getServer', function(event) {
  event.sender.send('server-up', mainAddr);
});

ipcMain.on('installUpdate', function(event) {
  autoUpdater.quitAndInstall();
});

function startPython(auth, code, lat, long) {

  mainWindow.loadURL('file://' + __dirname + '/main.html');
  //mainWindow.openDevTools();

  // Find open port
  var portfinder = require('portfinder');
  portfinder.getPort(function (err, port) {

    logData('Got open port: ' + port);

    // Run python web server
    var cmdLine = [
      './example.py',
      '--auth_service',
      auth,
      '--token',
      code,
      '--location',
      lat + ',' + long,
      '--auto_refresh',
      '10',
      '--step-limit',
      '7',
      //'--display-pokestop',
      '--display-gym',
      '--port',
      port,
      '--parent_pid',
      process.pid
    ];
    // console.log(cmdLine);
    logData('Maps path: ' + path.join(__dirname, 'map'));
    logData('python ' + cmdLine.join(' '))

    var pythonCmd = 'python';
    if (os.platform() == 'win32') {
      pythonCmd = path.join(__dirname, 'pywin', 'python.exe');
    }

    subpy = require('child_process').spawn(pythonCmd, cmdLine, {
      cwd: path.join(__dirname, 'map'),
      detached: true
    });

    subpy.stdout.on('data', (data) => {
      logData(`Python: ${data}`);
    });
    subpy.stderr.on('data', (data) => {
      logData(`Python: ${data}`);
    });

    var rq = require('request-promise');
    mainAddr = 'http://localhost:' + port;

    var openWindow = function(){
      mainWindow.webContents.send('server-up', mainAddr);
      mainWindow.webContents.executeJavaScript(
        'serverUp("'+mainAddr+'")');
      mainWindow.on('closed', function() {
        mainWindow = null;
        if (subpy && subpy.pid) {
          killProcess(subpy.pid);
        }
        procStarted = false;
      });
    };

    var startUp = function(){
      rq(mainAddr)
        .then(function(htmlString){
          logData('server started!');
          openWindow();
        })
        .catch(function(err){
          //console.log('waiting for the server start...');
          startUp();
        });
    };

    startUp();

  });

};
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>add back local static routing<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, crashReporter, shell } from 'electron';

let menu;
let template;
let mainWindow = null;

crashReporter.start();

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')();
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', () => {

  const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize];
  mainWindow = new BrowserWindow({width,height});

  mainWindow.loadURL(`file://${__dirname}/app/app.html`);
  mainWindow.openDevTools();

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(null);
  }
});
<commit_msg>Set specific values for width and height on mian Browser Window<commit_after>import { app, BrowserWindow, Menu, crashReporter, shell } from 'electron';

let menu;
let template;
let mainWindow = null;

crashReporter.start();

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')();
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    show: false,
    frame: false,
    width: 1920,
    height: 1080
  });

  mainWindow.loadURL(`file://${__dirname}/app/app.html`);
  mainWindow.openDevTools();

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(null);
  }
});
<|endoftext|>


<commit_before>/**
 * Your eyes will thank me
 * Sleepy mode.
 */

var d = document.documentElement,
    t = document.querySelectorAll(".js-toggle-lights")[0],
    l = document.querySelectorAll(".site-description")[0],
    m = localStorage.getItem("nightmode"),
    l1 = "Ubuntu experience.",
    l2 = "Ubuntu experience. Sleep mode.";

if(m == "true") {
  d.classList.add("night-mode");
  l.textContent = l2;
}

t.addEventListener("click", function(){
  if(d.classList.contains("night-mode")) {
    d.classList.remove("night-mode");
    localStorage.setItem("nightmode", "false");
    l.textContent = l1;
  } else {
    d.classList.add("night-mode");
    localStorage.setItem("nightmode", "true");
    l.textContent = l2;
  }
});

/**
 * Timing is everything
 */

function timeAgo(time){
    var units = [
    { name: "second", limit: 60, in_seconds: 1 },
    { name: "minute", limit: 3600, in_seconds: 60 },
    { name: "hour", limit: 86400, in_seconds: 3600 },
    { name: "day", limit: 604800, in_seconds: 86400 },
    { name: "week", limit: 2629743, in_seconds: 604800 },
    { name: "month", limit: 31556926, in_seconds: 2629743 },
    { name: "year", limit: null, in_seconds: 31556926 }
    ];
    var diff = (new Date() - new Date(time*1000)) / 1000;
    if (diff < 5) return "now";
    var i = 0;
    var unit = null;

    while ((unit = units[i++]) !== null) {
      if (diff < unit.limit || !unit.limit){
        diff = Math.floor(diff / unit.in_seconds);
        return diff + " " + unit.name + (diff>1 ? "s" : "") + " ago";
      }
    }
}

function toTimestamp(dateString){
  dateString = dateString.split('-').join('/');

  var date = new Date(dateString);
  valid = !isNaN(date.valueOf());

  if(valid === true){
      date = (date.getTime() / 1000).toFixed(0);
      date = timeAgo(date);
  }else{
      date = dateString;
  }
  return date;
}

/**
 * In Real Life
 * Quantified Self
 */

if (sessionStorage.irl) {
        document.getElementById('irl').innerHTML = sessionStorage.irl;
} else {
      var al = function(data) {
            var activity = parseInt(data.googlefit.steps);
            if(activity > 10) activity = "I've made " + activity.toLocaleString() + " steps today and"; else activity = "I'm either sleeping or working. Most likely <s>working</s> sleeping.";
            var irl = activity + " I spent over " + data.health.age.days.toLocaleString() + " days on Earth, my heart beat rate is " + data.googlefit.heartRate.bpm + " bpm measured " + timeAgo(data.googlefit.heartRate.timestamp) + ".";
            document.getElementById('irl').innerHTML = irl;
            sessionStorage.irl = irl;
      };

        var alt = document.createElement('script'); alt.type = 'text/javascript'; alt.async = true;
        alt.src = "http://track.andreiluca.com/api/?callback=al";
        var s = document.getElementsByTagName('script')[0];
        // s.parentNode.insertBefore(alt, s);
        document.body.appendChild(alt);
};

/**
 * Jekyll Search
 * https://github.com/christian-fei/Simple-Jekyll-Search
 */

!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=function(){function receivedResponse(xhr){return 200==xhr.status&&4==xhr.readyState}function handleResponse(xhr,callback){xhr.onreadystatechange=function(){if(receivedResponse(xhr))try{callback(null,JSON.parse(xhr.responseText))}catch(err){callback(err,null)}}}var self=this;self.load=function(location,callback){var xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");xhr.open("GET",location,!0),handleResponse(xhr,callback),xhr.send()}}},{}],2:[function(require,module,exports){function FuzzySearchStrategy(){function createFuzzyRegExpFromString(string){return new RegExp(string.split("").join(".*?"),"gi")}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),!!string.match(createFuzzyRegExpFromString(crit)))}}module.exports=new FuzzySearchStrategy},{}],3:[function(require,module,exports){function LiteralSearchStrategy(){function doMatch(string,crit){return string.toLowerCase().indexOf(crit.toLowerCase())>=0}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),doMatch(string,crit))}}module.exports=new LiteralSearchStrategy},{}],4:[function(require,module,exports){module.exports=function(){function findMatches(store,crit,strategy){for(var data=store.get(),i=0;i<data.length&&matches.length<limit;i++)findMatchesInObject(data[i],crit,strategy);return matches}function findMatchesInObject(obj,crit,strategy){for(var key in obj)if(strategy.matches(obj[key],crit)){matches.push(obj);break}}function getSearchStrategy(){return fuzzy?fuzzySearchStrategy:literalSearchStrategy}var self=this,matches=[],fuzzy=!1,limit=10,fuzzySearchStrategy=require("./SearchStrategies/fuzzy"),literalSearchStrategy=require("./SearchStrategies/literal");self.setFuzzy=function(_fuzzy){fuzzy=!!_fuzzy},self.setLimit=function(_limit){limit=parseInt(_limit,10)||limit},self.search=function(data,crit){return crit?(matches.length=0,findMatches(data,crit,getSearchStrategy())):[]}}},{"./SearchStrategies/fuzzy":2,"./SearchStrategies/literal":3}],5:[function(require,module,exports){module.exports=function(_store){function isObject(obj){return!!obj&&"[object Object]"==Object.prototype.toString.call(obj)}function isArray(obj){return!!obj&&"[object Array]"==Object.prototype.toString.call(obj)}function addObject(data){return store.push(data),data}function addArray(data){for(var added=[],i=0;i<data.length;i++)isObject(data[i])&&added.push(addObject(data[i]));return added}var self=this,store=[];isArray(_store)&&addArray(_store),self.clear=function(){return store.length=0,store},self.get=function(){return store},self.put=function(data){return isObject(data)?addObject(data):isArray(data)?addArray(data):void 0}}},{}],6:[function(require,module,exports){module.exports=function(){var self=this,templatePattern=/\{(.*?)\}/g;self.setTemplatePattern=function(newTemplatePattern){templatePattern=newTemplatePattern},self.render=function(t,data){return t.replace(templatePattern,function(match,prop){return data[prop]||match})}}},{}],7:[function(require,module,exports){!function(window,document,undefined){"use strict";function initWithJSON(json){store.put(opt.json),registerInput()}function initWithURL(url){jsonLoader.load(url,function(err,json){err?throwError("failed to get JSON ("+url+")"):(store.put(json),registerInput())})}function throwError(message){throw new Error("SimpleJekyllSearch --- "+message)}function validateOptions(_opt){for(var i=0;i<requiredOptions.length;i++){var req=requiredOptions[i];_opt[req]||throwError("You must specify a "+req)}}function assignOptions(_opt){for(var option in opt)opt[option]=_opt[option]||opt[option]}function isJSON(json){try{return json instanceof Object&&JSON.parse(JSON.stringify(json))}catch(e){return!1}}function emptyResultsContainer(){opt.resultsContainer.innerHTML=""}function appendToResultsContainer(text){opt.resultsContainer.innerHTML+=text}function registerInput(){opt.searchInput.addEventListener("keyup",function(e){return 0==e.target.value.length?void emptyResultsContainer():void render(searcher.search(store,e.target.value))})}function render(results){if(emptyResultsContainer(),0==results.length)return appendToResultsContainer(opt.noResultsText);for(var i=0;i<results.length;i++){results[i]['date'] = toTimestamp(results[i]['date']);appendToResultsContainer(templater.render(opt.searchResultTemplate,results[i]))}}var Searcher=require("./Searcher"),Templater=require("./Templater"),Store=require("./Store"),JSONLoader=require("./JSONLoader"),searcher=new Searcher,templater=new Templater,store=new Store,jsonLoader=new JSONLoader,requiredOptions=["searchInput","resultsContainer","json"],opt={searchInput:null,resultsContainer:null,json:[],searchResultTemplate:'
{title}
',noResultsText:"No results found",limit:5,fuzzy:1};window.SimpleJekyllSearch=function(_opt){validateOptions(_opt),assignOptions(_opt),isJSON(opt.json)?initWithJSON(opt.json):initWithURL(opt.json)}}(window,document)},{"./JSONLoader":1,"./Searcher":4,"./Store":5,"./Templater":6}]},{},[7]);

SimpleJekyllSearch({
        searchInput: document.getElementById('search-input'),
        resultsContainer: document.getElementById('search-results'),
        json: '/api.json',
        searchResultTemplate: '
{title} {date}
',
        noResultsText: '

',
        limit: 10,
        fuzzy: true,
});

// var s1 = document.getElementById("search-input");
// s1.focus();

/**
 * Toggles
 */

function toggl(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block') e.style.display = 'none';
       else e.style.display = 'block';
}<commit_msg>Json.api<commit_after>/**
 * Your eyes will thank me
 * Sleepy mode.
 */

var d = document.documentElement,
    t = document.querySelectorAll(".js-toggle-lights")[0],
    l = document.querySelectorAll(".site-description")[0],
    m = localStorage.getItem("nightmode"),
    l1 = "Ubuntu experience.",
    l2 = "Ubuntu experience. Sleep mode.";

if(m == "true") {
  d.classList.add("night-mode");
  l.textContent = l2;
}

t.addEventListener("click", function(){
  if(d.classList.contains("night-mode")) {
    d.classList.remove("night-mode");
    localStorage.setItem("nightmode", "false");
    l.textContent = l1;
  } else {
    d.classList.add("night-mode");
    localStorage.setItem("nightmode", "true");
    l.textContent = l2;
  }
});

/**
 * Timing is everything
 */

function timeAgo(time){
    var units = [
    { name: "second", limit: 60, in_seconds: 1 },
    { name: "minute", limit: 3600, in_seconds: 60 },
    { name: "hour", limit: 86400, in_seconds: 3600 },
    { name: "day", limit: 604800, in_seconds: 86400 },
    { name: "week", limit: 2629743, in_seconds: 604800 },
    { name: "month", limit: 31556926, in_seconds: 2629743 },
    { name: "year", limit: null, in_seconds: 31556926 }
    ];
    var diff = (new Date() - new Date(time*1000)) / 1000;
    if (diff < 5) return "now";
    var i = 0;
    var unit = null;

    while ((unit = units[i++]) !== null) {
      if (diff < unit.limit || !unit.limit){
        diff = Math.floor(diff / unit.in_seconds);
        return diff + " " + unit.name + (diff>1 ? "s" : "") + " ago";
      }
    }
}

function toTimestamp(dateString){
  dateString = dateString.split('-').join('/');

  var date = new Date(dateString);
  valid = !isNaN(date.valueOf());

  if(valid === true){
      date = (date.getTime() / 1000).toFixed(0);
      date = timeAgo(date);
  }else{
      date = dateString;
  }
  return date;
}

/**
 * In Real Life
 * Quantified Self
 */

if (sessionStorage.irl) {
        document.getElementById('irl').innerHTML = sessionStorage.irl;
} else {
      var al = function(data) {
            var activity = parseInt(data.googlefit.steps);
            if(activity > 10) activity = "I've made " + activity.toLocaleString() + " steps today and"; else activity = "I'm either sleeping or working. Most likely <s>working</s> sleeping.";
            var irl = activity + " I spent over " + data.health.age.days.toLocaleString() + " days on Earth, my heart beat rate is " + data.googlefit.heartRate.bpm + " bpm measured " + timeAgo(data.googlefit.heartRate.timestamp) + ".";
            document.getElementById('irl').innerHTML = irl;
            sessionStorage.irl = irl;
      };

        var alt = document.createElement('script'); alt.type = 'text/javascript'; alt.async = true;
        alt.src = "http://track.andreiluca.com/api/?callback=al";
        var s = document.getElementsByTagName('script')[0];
        // s.parentNode.insertBefore(alt, s);
        document.body.appendChild(alt);
};

/**
 * Jekyll Search
 * https://github.com/christian-fei/Simple-Jekyll-Search
 */

!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=function(){function receivedResponse(xhr){return 200==xhr.status&&4==xhr.readyState}function handleResponse(xhr,callback){xhr.onreadystatechange=function(){if(receivedResponse(xhr))try{callback(null,JSON.parse(xhr.responseText))}catch(err){callback(err,null)}}}var self=this;self.load=function(location,callback){var xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");xhr.open("GET",location,!0),handleResponse(xhr,callback),xhr.send()}}},{}],2:[function(require,module,exports){function FuzzySearchStrategy(){function createFuzzyRegExpFromString(string){return new RegExp(string.split("").join(".*?"),"gi")}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),!!string.match(createFuzzyRegExpFromString(crit)))}}module.exports=new FuzzySearchStrategy},{}],3:[function(require,module,exports){function LiteralSearchStrategy(){function doMatch(string,crit){return string.toLowerCase().indexOf(crit.toLowerCase())>=0}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),doMatch(string,crit))}}module.exports=new LiteralSearchStrategy},{}],4:[function(require,module,exports){module.exports=function(){function findMatches(store,crit,strategy){for(var data=store.get(),i=0;i<data.length&&matches.length<limit;i++)findMatchesInObject(data[i],crit,strategy);return matches}function findMatchesInObject(obj,crit,strategy){for(var key in obj)if(strategy.matches(obj[key],crit)){matches.push(obj);break}}function getSearchStrategy(){return fuzzy?fuzzySearchStrategy:literalSearchStrategy}var self=this,matches=[],fuzzy=!1,limit=10,fuzzySearchStrategy=require("./SearchStrategies/fuzzy"),literalSearchStrategy=require("./SearchStrategies/literal");self.setFuzzy=function(_fuzzy){fuzzy=!!_fuzzy},self.setLimit=function(_limit){limit=parseInt(_limit,10)||limit},self.search=function(data,crit){return crit?(matches.length=0,findMatches(data,crit,getSearchStrategy())):[]}}},{"./SearchStrategies/fuzzy":2,"./SearchStrategies/literal":3}],5:[function(require,module,exports){module.exports=function(_store){function isObject(obj){return!!obj&&"[object Object]"==Object.prototype.toString.call(obj)}function isArray(obj){return!!obj&&"[object Array]"==Object.prototype.toString.call(obj)}function addObject(data){return store.push(data),data}function addArray(data){for(var added=[],i=0;i<data.length;i++)isObject(data[i])&&added.push(addObject(data[i]));return added}var self=this,store=[];isArray(_store)&&addArray(_store),self.clear=function(){return store.length=0,store},self.get=function(){return store},self.put=function(data){return isObject(data)?addObject(data):isArray(data)?addArray(data):void 0}}},{}],6:[function(require,module,exports){module.exports=function(){var self=this,templatePattern=/\{(.*?)\}/g;self.setTemplatePattern=function(newTemplatePattern){templatePattern=newTemplatePattern},self.render=function(t,data){return t.replace(templatePattern,function(match,prop){return data[prop]||match})}}},{}],7:[function(require,module,exports){!function(window,document,undefined){"use strict";function initWithJSON(json){store.put(opt.json),registerInput()}function initWithURL(url){jsonLoader.load(url,function(err,json){err?throwError("failed to get JSON ("+url+")"):(store.put(json),registerInput())})}function throwError(message){throw new Error("SimpleJekyllSearch --- "+message)}function validateOptions(_opt){for(var i=0;i<requiredOptions.length;i++){var req=requiredOptions[i];_opt[req]||throwError("You must specify a "+req)}}function assignOptions(_opt){for(var option in opt)opt[option]=_opt[option]||opt[option]}function isJSON(json){try{return json instanceof Object&&JSON.parse(JSON.stringify(json))}catch(e){return!1}}function emptyResultsContainer(){opt.resultsContainer.innerHTML=""}function appendToResultsContainer(text){opt.resultsContainer.innerHTML+=text}function registerInput(){opt.searchInput.addEventListener("keyup",function(e){return 0==e.target.value.length?void emptyResultsContainer():void render(searcher.search(store,e.target.value))})}function render(results){if(emptyResultsContainer(),0==results.length)return appendToResultsContainer(opt.noResultsText);for(var i=0;i<results.length;i++){results[i]['date'] = toTimestamp(results[i]['date']);appendToResultsContainer(templater.render(opt.searchResultTemplate,results[i]))}}var Searcher=require("./Searcher"),Templater=require("./Templater"),Store=require("./Store"),JSONLoader=require("./JSONLoader"),searcher=new Searcher,templater=new Templater,store=new Store,jsonLoader=new JSONLoader,requiredOptions=["searchInput","resultsContainer","json"],opt={searchInput:null,resultsContainer:null,json:[],searchResultTemplate:'
{title}
',noResultsText:"No results found",limit:5,fuzzy:1};window.SimpleJekyllSearch=function(_opt){validateOptions(_opt),assignOptions(_opt),isJSON(opt.json)?initWithJSON(opt.json):initWithURL(opt.json)}}(window,document)},{"./JSONLoader":1,"./Searcher":4,"./Store":5,"./Templater":6}]},{},[7]);

SimpleJekyllSearch({
        searchInput: document.getElementById('search-input'),
        resultsContainer: document.getElementById('search-results'),
        json: '/search.json',
        searchResultTemplate: '
{title} {date}
',
        noResultsText: '

',
        limit: 10,
        fuzzy: true,
});

// var s1 = document.getElementById("search-input");
// s1.focus();

/**
 * Toggles
 */

function toggl(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block') e.style.display = 'none';
       else e.style.display = 'block';
}<|endoftext|>


<commit_before>var resizer = function() {
  "use strict";
  var offsetHeight = document.querySelector('.menubar').offsetHeight;

  var fl = document.querySelector('.filelist');
  fl.style.height = (window.innerHeight - offsetHeight) + "px";

  var ep = document.querySelector('.editpanel');
  ep.style.height = (window.innerHeight - offsetHeight) + "px";
  ep.style.width = (window.innerWidth - fl.offsetWidth) + "px";

  var ed = document.querySelector('#editor');
  if (ed) {
    ed.style.height = (window.innerHeight - offsetHeight) + "px";
  }
};

window.onload = function () {
  "use strict";
  /* add event resize listener */
  window.onresize = resizer;
  window.onresize();

  var fileListManager = new FileListManager(function (file) {
		if (file.name.toLowerCase().endsWith('.bmp')) {
		// 	var imageViewerElm = document.getElementById('image_viewer');
		// 	while (imageViewerElm.firstChild) {
		// 		imageViewerElm.removeChild(imageViewerElm.firstChild);
		// 	}
		// 	var myArray = file.asUint8Array();
		// 	var blob = new Blob([myArray], {'type': 'image/bmp'});
		// 	var imageUrl = URL.createObjectURL(blob); //different prefixes for different vendors
		// 	var img = new Image();
		// 	img.src = imageUrl;
		// 	imageViewerElm.appendChild(img);
		} else if (file.name.toLowerCase().endsWith('.png')) {
		// 	var imageViewerElm = document.getElementById('image_viewer');
		// 	while (imageViewerElm.firstChild) {
		// 		imageViewerElm.removeChild(imageViewerElm.firstChild);
		// 	}
		// 	var myArray = file.asUint8Array();
		// 	var blob = new Blob([myArray], {'type': 'image/png'});
		// 	var imageUrl = URL.createObjectURL(blob); //different prefixes for different vendors
		// 	var img = new Image();
		// 	img.src = imageUrl;
		// 	imageViewerElm.appendChild(img);
		} else if (file.name.endsWith('.xml') ||
		               file.name.endsWith('.rels')) {
			var editor = ace.edit("editor");
			editor.getSession().setValue(vkbeautify.xml(file.asText(), -1), 4);
		} else {
			alert('Not support!');
		}
    Editor.renderer.onResize(true);
  });

  /* add event input file listener */
  var inputObject = new InputObject(function(file) {
    fileListManager.open(file,
      function (element) {
        var fileListElm = document.querySelector('.filelist');
        while (fileListElm.firstChild) {
          fileListElm.removeChild(fileListElm.firstChild);
        }
        document.querySelector('.filelist').appendChild(element);
      },
      function (/*error*/) {
        console.log("Error!");
      }
    );
  })
};
<commit_msg>add String.prototype.endsWith polyfill<commit_after>var resizer = function() {
  "use strict";
  var offsetHeight = document.querySelector('.menubar').offsetHeight;

  var fl = document.querySelector('.filelist');
  fl.style.height = (window.innerHeight - offsetHeight) + "px";

  var ep = document.querySelector('.editpanel');
  ep.style.height = (window.innerHeight - offsetHeight) + "px";
  ep.style.width = (window.innerWidth - fl.offsetWidth) + "px";

  var ed = document.querySelector('#editor');
  if (ed) {
    ed.style.height = (window.innerHeight - offsetHeight) + "px";
  }
};

window.onload = function () {
  "use strict";

  if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
  }

  /* add event resize listener */
  window.onresize = resizer;
  window.onresize();

  var fileListManager = new FileListManager(function (file) {
		if (file.name.toLowerCase().endsWith('.bmp')) {
		// 	var imageViewerElm = document.getElementById('image_viewer');
		// 	while (imageViewerElm.firstChild) {
		// 		imageViewerElm.removeChild(imageViewerElm.firstChild);
		// 	}
		// 	var myArray = file.asUint8Array();
		// 	var blob = new Blob([myArray], {'type': 'image/bmp'});
		// 	var imageUrl = URL.createObjectURL(blob); //different prefixes for different vendors
		// 	var img = new Image();
		// 	img.src = imageUrl;
		// 	imageViewerElm.appendChild(img);
		} else if (file.name.toLowerCase().endsWith('.png')) {
		// 	var imageViewerElm = document.getElementById('image_viewer');
		// 	while (imageViewerElm.firstChild) {
		// 		imageViewerElm.removeChild(imageViewerElm.firstChild);
		// 	}
		// 	var myArray = file.asUint8Array();
		// 	var blob = new Blob([myArray], {'type': 'image/png'});
		// 	var imageUrl = URL.createObjectURL(blob); //different prefixes for different vendors
		// 	var img = new Image();
		// 	img.src = imageUrl;
		// 	imageViewerElm.appendChild(img);
		} else if (file.name.endsWith('.xml') ||
		               file.name.endsWith('.rels')) {
			var editor = ace.edit("editor");
			editor.getSession().setValue(vkbeautify.xml(file.asText(), -1), 4);
		} else {
			alert('Not support!');
		}
    Editor.renderer.onResize(true);
  });

  /* add event input file listener */
  var inputObject = new InputObject(function(file) {
    fileListManager.open(file,
      function (element) {
        var fileListElm = document.querySelector('.filelist');
        while (fileListElm.firstChild) {
          fileListElm.removeChild(fileListElm.firstChild);
        }
        document.querySelector('.filelist').appendChild(element);
      },
      function (/*error*/) {
        console.log("Error!");
      }
    );
  })
};
<|endoftext|>


<commit_before>var React = require('react-native');

var {
View,
Text,
Component,
AsyncStorage,
StyleSheet,
Image,
PanResponder,
Animated,
MapView,
TouchableOpacity,
Linking
} = React;

const DELTA = 0.003021;

class RestaurantInfo extends Component {

  renderBackButton() {
    return (
      <TouchableOpacity
        onPress={this.goBack.bind(this)}
      >
        <Text style={styles.backButton}> {'< Back'} </Text>
      </TouchableOpacity>)
  }

  goBack() {
    this.props.navigator.pop();
  }

  render() {
    var restaurant = this.props.restaurant;
    console.log(restaurant)
    if(restaurant) {
      if(restaurant.website){
        var website = <TouchableOpacity onPress={ () => { Linking.openURL(restaurant.website)}}><Text style={styles.websiteButton}>Go To Webpage</Text></TouchableOpacity>;
      }
      var splitAddress=restaurant.address.split(", ");
      var streetAddress = splitAddress[0];
      var city = splitAddress[1];
      var stateAndZip = splitAddress[2];
      var content = (
        <View style={styles.container}>
           <Image
            style={styles.logo}
            source={require('../thumbnails/logohighreswhite_720.png')}
          />
          <Text style={styles.title}>{restaurant.name}</Text>
          <MapView
            style={styles.map}
            showUserLocation={true}
            region={{
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              latitudeDelta: DELTA,
              longitudeDelta: DELTA,
            }}
            onPress={ () => { Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}
            annotations={[{
              animateDrop: true,
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              title: restaurant.address,
            }]}
          />
          {website}
          <Text style={styles.directions} onPress={()=>{Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}>Directions</Text>
          {<TouchableOpacity onPress={()=>{Linking.openURL("tel:" + restaurant.phone)}}>
            <Text style={styles.phoneNumber}>{restaurant.phone}</Text>
          </TouchableOpacity>}
          <Text style={styles.content}>{city}, {stateAndZip}</Text>
          {this.renderBackButton()}
        </View>);
    } else {
      var content = 'NOTHING';
    }

    return (<View style={styles.container}>
          {content}
        </View>)
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#300030',
  },
  title: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
    marginBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 10
  },
  content: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
  },
  map: {
    width: 350,
    height: 310,
    marginBottom: 5,
  },
  logo: {
    // marginTop: 10,
    marginBottom: 10,
    height: 100,
    width: 150
  },
  backButton: {
    color: 'white',
    marginRight: 310,
    fontWeight: 'bold',
  },
  websiteButton: {
    textAlign: 'center',
    color: 'white',
    marginBottom: 2,
    marginTop: 7,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
  },
  directions: {
    textAlign: 'center',
    color: 'white',
    marginBottom: 2,
    marginTop: 2,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
  },
  phoneNumber: {
    textDecorationLine: 'underline',
    color: 'white',
    paddingBottom: 4,
    marginTop: 4
  }
})

module.exports = RestaurantInfo;
<commit_msg>Add webpage and directions button on one row.<commit_after>var React = require('react-native');

var {
View,
Text,
Component,
AsyncStorage,
StyleSheet,
Image,
PanResponder,
Animated,
MapView,
TouchableOpacity,
Linking
} = React;

const DELTA = 0.003021;

class RestaurantInfo extends Component {

  renderBackButton() {
    return (
      <TouchableOpacity
        onPress={this.goBack.bind(this)}
      >
        <Text style={styles.backButton}> {'< Back'} </Text>
      </TouchableOpacity>)
  }

  goBack() {
    this.props.navigator.pop();
  }

  render() {
    var restaurant = this.props.restaurant;
    console.log(restaurant)
    if(restaurant) {
      if(restaurant.website){
        var website = <TouchableOpacity onPress={ () => { Linking.openURL(restaurant.website)}}><Text style={styles.websiteButton}>Go To Webpage</Text></TouchableOpacity>;
      }
      var splitAddress=restaurant.address.split(", ");
      var streetAddress = splitAddress[0];
      var city = splitAddress[1];
      var stateAndZip = splitAddress[2];
      var content = (
        <View style={styles.container}>
           <Image
            style={styles.logo}
            source={require('../thumbnails/logohighreswhite_720.png')}
          />
          <Text style={styles.title}>{restaurant.name}</Text>
          <MapView
            style={styles.map}
            showUserLocation={true}
            region={{
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              latitudeDelta: DELTA,
              longitudeDelta: DELTA,
            }}
            onPress={ () => { Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}
            annotations={[{
              animateDrop: true,
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              title: restaurant.address,
            }]}
          />
          <View style={styles.something}>
            {website}
            <Text style={styles.directions} onPress={()=>{Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}>Directions</Text>
          </View>
          {<TouchableOpacity onPress={()=>{Linking.openURL("tel:" + restaurant.phone)}}>
            <Text style={styles.phoneNumber}>{restaurant.phone}</Text>
          </TouchableOpacity>}
          <Text style={styles.content}>{city}, {stateAndZip}</Text>
          {this.renderBackButton()}
        </View>);
    } else {
      var content = 'NOTHING';
    }

    return (<View style={styles.container}>
          {content}
        </View>)
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#300030',
  },
  title: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
    marginBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 10
  },
  content: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
  },
  map: {
    width: 350,
    height: 310,
    marginBottom: 5,
  },
  logo: {
    // marginTop: 10,
    marginBottom: 10,
    height: 100,
    width: 150
  },
  backButton: {
    color: 'white',
    marginRight: 310,
    fontWeight: 'bold',
  },
  websiteButton: {
    flex: 1,
    textAlign: 'center',
    color: 'white',
    marginBottom: 2,
    marginTop: 7,
    marginLeft: 10,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
  },
  directions: {
    textAlign: 'center',
    color: 'white',
    marginBottom: 2,
    marginTop: 7,
    marginLeft: 10,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
    paddingLeft: 25,
    paddingRight: 25
  },
  phoneNumber: {
    textDecorationLine: 'underline',
    color: 'white',
    paddingBottom: 4,
    marginTop: 4
  },
  something: {
    flexDirection: 'row'
  }
})

module.exports = RestaurantInfo;
<|endoftext|>