<commit_before>/* global confirm */
'use strict'

var $ = require('jquery')
var Web3 = require('web3')
var EventManager = require('../lib/eventManager')
var EthJSVM = require('ethereumjs-vm')
var ethUtil = require('ethereumjs-util')
var StateManager = require('ethereumjs-vm/lib/stateManager')

var injectedProvider

var web3
if (typeof window.web3 !== 'undefined') {
  injectedProvider = window.web3.currentProvider
  web3 = new Web3(injectedProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}

/*
  extend vm state manager and instanciate VM
*/

class StateManagerCommonStorageDump extends StateManager {
  constructor (arg) {
    super(arg)
    this.keyHashes = {}
  }

  putContractStorage (address, key, value, cb) {
    this.keyHashes[ethUtil.sha3(key)] = ethUtil.bufferToHex(key)
    super.putContractStorage(address, key, value, cb)
  }

  dumpStorage (address, cb) {
    var self = this
    this._getStorageTrie(address, function (err, trie) {
      if (err) {
        return cb(err)
      }
      var storage = {}
      var stream = trie.createReadStream()
      stream.on('data', function (val) {
        storage[self.keyHashes[val.key]] = val.value.toString('hex')
      })
      stream.on('end', function () {
        cb(storage)
      })
    })
  }
}

var stateManager = new StateManagerCommonStorageDump({})
var vm = new EthJSVM({
  enableHomestead: true,
  activatePrecompiles: true
})

vm.stateManager = stateManager
vm.blockchain = stateManager.blockchain
vm.trie = stateManager.trie
vm.stateManager.checkpoint()

/*
  trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
  var self = this
  this.event = new EventManager()
  var executionContext = injectedProvider ? 'injected' : 'vm'

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return web3
  }

  this.vm = function () {
    return vm
  }

  this.setEndPointUrl = function (url) {
    $web3endpoint.val(url)
  }

  this.setContext = function (context) {
    executionContext = context
    executionContextChange(context)
    setExecutionContextRadio()
  }

  var $injectedToggle = $('#injected-mode')
  var $vmToggle = $('#vm-mode')
  var $web3Toggle = $('#web3-mode')
  var $web3endpoint = $('#web3Endpoint')

  if (web3.providers && web3.currentProvider instanceof web3.providers.IpcProvider) {
    $web3endpoint.val('ipc')
  }

  setExecutionContextRadio()

  $injectedToggle.on('change', executionContextUIChange)
  $vmToggle.on('change', executionContextUIChange)
  $web3Toggle.on('change', executionContextUIChange)
  $web3endpoint.on('change', function () {
    setProviderFromEndpoint()
    if (executionContext === 'web3') {
      self.event.trigger('web3EndpointChanged')
    }
  })

  function executionContextUIChange (ev) {
    executionContextChange(ev.target.value)
  }

  function executionContextChange (context) {
    if (context === 'web3' && !confirm('Are you sure you want to connect to a local ethereum node?')) {
      setExecutionContextRadio()
    } else if (context === 'injected' && injectedProvider === undefined) {
      setExecutionContextRadio()
    } else {
      if (context === 'web3') {
        executionContext = context
        setProviderFromEndpoint()
        self.event.trigger('contextChanged', ['web3'])
      } else if (context === 'injected') {
        executionContext = context
        web3.setProvider(injectedProvider)
        self.event.trigger('contextChanged', ['injected'])
      } else if (context === 'vm') {
        executionContext = context
        vm.stateManager.revert(function () {
          vm.stateManager.checkpoint()
        })
        self.event.trigger('contextChanged', ['vm'])
      }
    }
  }

  function setProviderFromEndpoint () {
    var endpoint = $web3endpoint.val()
    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
  }

  function setExecutionContextRadio () {
    if (executionContext === 'injected') {
      $injectedToggle.get(0).checked = true
    } else if (executionContext === 'vm') {
      $vmToggle.get(0).checked = true
    } else if (executionContext === 'web3') {
      $web3Toggle.get(0).checked = true
    }
  }
}

module.exports = ExecutionContext
<commit_msg>add note<commit_after>/* global confirm */
'use strict'

var $ = require('jquery')
var Web3 = require('web3')
var EventManager = require('../lib/eventManager')
var EthJSVM = require('ethereumjs-vm')
var ethUtil = require('ethereumjs-util')
var StateManager = require('ethereumjs-vm/lib/stateManager')

var injectedProvider

var web3
if (typeof window.web3 !== 'undefined') {
  injectedProvider = window.web3.currentProvider
  web3 = new Web3(injectedProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}

/*
  extend vm state manager and instanciate VM
*/

class StateManagerCommonStorageDump extends StateManager {
  constructor (arg) {
    super(arg)
    this.keyHashes = {}
  }

  putContractStorage (address, key, value, cb) {
    this.keyHashes[ethUtil.sha3(key)] = ethUtil.bufferToHex(key)
    super.putContractStorage(address, key, value, cb)
  }

  dumpStorage (address, cb) {
    var self = this
    this._getStorageTrie(address, function (err, trie) {
      if (err) {
        return cb(err)
      }
      var storage = {}
      var stream = trie.createReadStream()
      stream.on('data', function (val) {
        storage[self.keyHashes[val.key]] = val.value.toString('hex')
      })
      stream.on('end', function () {
        cb(storage)
      })
    })
  }
}

var stateManager = new StateManagerCommonStorageDump({})
var vm = new EthJSVM({
  enableHomestead: true,
  activatePrecompiles: true
})

// FIXME: move state manager in EthJSVM ctr
vm.stateManager = stateManager
vm.blockchain = stateManager.blockchain
vm.trie = stateManager.trie
vm.stateManager.checkpoint()

/*
  trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
  var self = this
  this.event = new EventManager()
  var executionContext = injectedProvider ? 'injected' : 'vm'

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return web3
  }

  this.vm = function () {
    return vm
  }

  this.setEndPointUrl = function (url) {
    $web3endpoint.val(url)
  }

  this.setContext = function (context) {
    executionContext = context
    executionContextChange(context)
    setExecutionContextRadio()
  }

  var $injectedToggle = $('#injected-mode')
  var $vmToggle = $('#vm-mode')
  var $web3Toggle = $('#web3-mode')
  var $web3endpoint = $('#web3Endpoint')

  if (web3.providers && web3.currentProvider instanceof web3.providers.IpcProvider) {
    $web3endpoint.val('ipc')
  }

  setExecutionContextRadio()

  $injectedToggle.on('change', executionContextUIChange)
  $vmToggle.on('change', executionContextUIChange)
  $web3Toggle.on('change', executionContextUIChange)
  $web3endpoint.on('change', function () {
    setProviderFromEndpoint()
    if (executionContext === 'web3') {
      self.event.trigger('web3EndpointChanged')
    }
  })

  function executionContextUIChange (ev) {
    executionContextChange(ev.target.value)
  }

  function executionContextChange (context) {
    if (context === 'web3' && !confirm('Are you sure you want to connect to a local ethereum node?')) {
      setExecutionContextRadio()
    } else if (context === 'injected' && injectedProvider === undefined) {
      setExecutionContextRadio()
    } else {
      if (context === 'web3') {
        executionContext = context
        setProviderFromEndpoint()
        self.event.trigger('contextChanged', ['web3'])
      } else if (context === 'injected') {
        executionContext = context
        web3.setProvider(injectedProvider)
        self.event.trigger('contextChanged', ['injected'])
      } else if (context === 'vm') {
        executionContext = context
        vm.stateManager.revert(function () {
          vm.stateManager.checkpoint()
        })
        self.event.trigger('contextChanged', ['vm'])
      }
    }
  }

  function setProviderFromEndpoint () {
    var endpoint = $web3endpoint.val()
    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
  }

  function setExecutionContextRadio () {
    if (executionContext === 'injected') {
      $injectedToggle.get(0).checked = true
    } else if (executionContext === 'vm') {
      $vmToggle.get(0).checked = true
    } else if (executionContext === 'web3') {
      $web3Toggle.get(0).checked = true
    }
  }
}

module.exports = ExecutionContext
<|endoftext|>


<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: mschwartz
 * Date: 9/11/13
 * Time: 11:25 AM
 * To change this template use File | Settings | File Templates.
 */

var File = require('File'),
    Hogan = require('hogan');

function TemplateManager( path ) {
	var templates = {},
	    template_path = path;

    if (!template_path.endsWith('/')) {
        template_path += '/';
    }
    return new JavaAdapter(org.mozilla.javascript.NativeObject, {
        get : sync(function( name, start ) {
            if (String(name) === 'stackText') {
                return undefined;
            }
            var path = template_path + name + '.hbs',
                t = templates[path];
            if (!t) {
                t = templates[path] = {
                    path     : path,
                    file     : new File(path),
                    modified : 0
                };
            }
            var f = t.file;
            if (!f.isFile()) {
                throw new Error('View ' + path + ' not found');
            }
            var modified = f.lastModified();
            if (modified > t.modified) {
                t.template = Hogan.compile(f.readAll());
                t.modified = modified;
            }
            return t.template;
        }, templates)
    });
}

module.exports = TemplateManager;

<commit_msg>fix proxy<commit_after>/**
 * Created with JetBrains WebStorm.
 * User: mschwartz
 * Date: 9/11/13
 * Time: 11:25 AM
 * To change this template use File | Settings | File Templates.
 */

/*global require, JSAdapter */
var File = require('File'),
    Hogan = require('hogan');

function TemplateManager( path ) {
	var templates = {},
	    template_path = path;

    if (!template_path.endsWith('/')) {
        template_path += '/';
    }
    if (NASHORN) {
        return JSAdapter() {
            __get__: sync(function(name) {
                if (String(name) === 'stackText') {
                    return undefined;
                }
                var path = template_path + name + '.hbs',
                    t    = templates[path];
                if (!t) {
                    t = templates[path] = {
                        path     : path,
                        file     : new File(path),
                        modified : 0
                    };
                }
                var f = t.file;
                if (!f.isFile()) {
                    throw new Error('View ' + path + ' not found');
                }
                var modified = f.lastModified();
                if (modified > t.modified) {
                    t.template = Hogan.compile(f.readAll());
                    t.modified = modified;
                }
                return t.template;
            }, templates);
        };
    }
    else {

        return new JavaAdapter(org.mozilla.javascript.NativeObject, {
            get : sync(function (name, start) {
                if (String(name) === 'stackText') {
                    return undefined;
                }
                var path = template_path + name + '.hbs',
                    t    = templates[path];
                if (!t) {
                    t = templates[path] = {
                        path     : path,
                        file     : new File(path),
                        modified : 0
                    };
                }
                var f = t.file;
                if (!f.isFile()) {
                    throw new Error('View ' + path + ' not found');
                }
                var modified = f.lastModified();
                if (modified > t.modified) {
                    t.template = Hogan.compile(f.readAll());
                    t.modified = modified;
                }
                return t.template;
            }, templates)
        });
    }
}

module.exports = TemplateManager;

<|endoftext|>


<commit_before>'use strict';

var metal = require('gulp-metal');

var options = {
	bundleCssFileName: 'dragDrop.css',
	bundleFileName: 'dragDrop.js',
	globalName: 'metal',
	mainBuildJsTasks: ['build:globals'],
	moduleName: 'metal-drag-drop',
	testSaucelabsBrowsers: {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_chrome_57: {
			base: 'SauceLabs',
			browserName: 'chrome',
			version: '57'
		},
		sl_safari_8: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '8'
		},
		sl_safari_9: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '9'
		},
		sl_safari_10: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '10'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_firefox_53: {
			base: 'SauceLabs',
			browserName: 'firefox',
			version: '53'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_edge_20: {
			base: 'SauceLabs',
			browserName: 'microsoftedge',
			platform: 'Windows 10',
			version: '13'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '9.2'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	},
	noSoy: true
};

metal.registerTasks(options);
<commit_msg>Replace Safari 8 with 11, update mobile Safari from 9 to 10<commit_after>'use strict';

var metal = require('gulp-metal');

var options = {
	bundleCssFileName: 'dragDrop.css',
	bundleFileName: 'dragDrop.js',
	globalName: 'metal',
	mainBuildJsTasks: ['build:globals'],
	moduleName: 'metal-drag-drop',
	testSaucelabsBrowsers: {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_chrome_57: {
			base: 'SauceLabs',
			browserName: 'chrome',
			version: '57'
		},
		sl_safari_9: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '9'
		},
		sl_safari_10: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '10'
		},
		sl_safari_11: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '11'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_firefox_53: {
			base: 'SauceLabs',
			browserName: 'firefox',
			version: '53'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_edge_20: {
			base: 'SauceLabs',
			browserName: 'microsoftedge',
			platform: 'Windows 10',
			version: '13'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'Safari',
			device: 'iPhone 7',
			platform: 'iOS',
			version: '10.3'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	},
	noSoy: true
};

metal.registerTasks(options);
<|endoftext|>


<commit_before>/*jslint node: true*/

//First we call the packages we need.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var bugsnag = require("bugsnag");
bugsnag.register("9d5907a30dcfaf8806e542fbf61cf623");
var legacy = require('legacy-encoding');

//Here I am creating the singleton connection to the MongoDb server.
//This connection will be used in all the controllers and middleware in the app.
//mongoDbConnection(function(db) {});

var os = require('os');
console.log(os.platform());
console.log(os.type());

console.log(os.hostname());
console.log(os.arch());
console.log(os.release());

var interfaces = os.networkInterfaces();
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}

console.log(addresses[0]);
app.use(bodyParser.json());
//Here I am placing the cron jobs
//var cron = require("./cronjobs");
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");
    next();
});
//In order to disable to flags for chromium
//open /Users/anestis/Downloads Chromium.app --args –allow-file-access-from-files -disable-web-security

// configure app to use bodyParser()
// this will let us get the data from a POST
//This is an express middleware
//It handles the data sent before sending them to the routes.

app.get('/printServer', function(req, res) {
    console.log("/printServer was just called");
    //res.json is used usually when I want to return data from an API
    res.json({
        message: 'Live'
    });
});

app.get('/getPrinters', function(req, res) {
    console.log("/printServer was just called");
    //res.json is used usually when I want to return data from an API
    var printer = require("printer");
    var util = require('util');
    console.log("installed printers:\n" + util.inspect(printer.getPrinters(), {
        colors: true,
        depth: 10
    }));

    res.json({
        message: printer.getPrinters()
    });
});

app.post('/printOrder', function(req, res) {
    var data = req.body;
    //json parameters: printer, printerBrand, printerCodepage, print_barcode, barcodeTopBottom, order_id, store_id, order_details, auto_cutter
    console.log("/print was just called");

    var printBarcode = function(print_barcode, barcodeTopBottom, order_id, store_id, printerBrand) {
        var str = "";
        var tempOrderId = "";
        var tempCount = "";
        var tempRes = "";
        var i = 0;
        if (printerBrand == "Star TSP-100 Series") {
            str += "\r\n"; //New line command! Important otherwise barcode after that will not work!
            str += "\x1B\x1D\x61\x01"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
            str += "\x1B\x62\x04\x01\x05\x60";
            tempOrderId = order_id;
            tempCount = store_id;
            tempRes = tempOrderId.substr(tempCount.length);
            i = 0;
            while (tempRes.charAt(i) === 0) {
                i++;
            }
            tempRes = tempRes.substr(i);
            //applet.append("-W00000159Q");
            str += "--" + tempRes + ".";
            str += "\x1E";
            str += "*** " + order_id + " ***\r\n";
            str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
        } else {
            str += "\r\n"; //New line command! Important otherwise barcode after that will not work!
            str += "\x1B\x61\x01"; // Centering
            str += "\x1D\x48\x00";
            str += "\x1D\x68\x60"; //Barcode height to 70 dots default is 165. The value must not ralate to other actions
            str += "\x1D\x6B\x04";
            tempOrderId = order_id;
            tempCount = store_id;
            tempRes = tempOrderId.substr(tempCount.length);
            i = 0;
            while (tempRes.charAt(i) === 0) {
                i++;
            }
            tempRes = tempRes.substr(i);
            //applet.append("-W00000159Q");
            str += "--" + tempRes + ".";
            str += "\x00";
            str += "*** " + order_id + " ***\r\n";
            str += '\x1B\x21\x00';
        }

        //Resettinh styling!
        if (printerBrand == "Star TSP-100 Series") {
            str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
        } else {
            str += "\x1B\x21\x00"; // Commands to reset the styling.
        }
        return str;
    };

    //It should accept more than one printers as input.
    var str = "\x1B\x40";

    if (data.printerBrand == "Star TSP-100 Series" && data.printerCodepage == 'CP869') {
        str += "\x1B\x1D\x74\x11"; // This sets the code page to CP869
    } else if (data.printerBrand == "Star TSP-100 Series" && data.printerCodepage == 'CP737') {
        str += "\x1B\x1D\x74\x0F"; // This sets the code page to CP737
    } else if (data.printerBrand == "Casio" && data.printerCodepage == 'CP737') {
        //This is a hardware dependent command to "Cancel Kanji character mode".
        //This command can be used only for the Japanese, Simplified Chinese, Traditional Chinese, and Korean models.
        //My model is usung as default Simplified Chinese.
        //This command should be executed again after printer resets or powers down.
        //If Kanji mode is canceled, the printer processes a character code as a 1-byte code of alphanumeric Katakana characters.
        str += "\x1B\x74\x18"; // This sets the code page to CP737 Decimal (27 64 27 116 24)
    } else if ((data.printerBrand == "Xprinter" || data.printerBrand == "OCOM") && data.printerCodepage == 'CP737') {
        //This is a hardware dependent command to "Cancel Kanji character mode".
        //This command can be used only for the Japanese, Simplified Chinese, Traditional Chinese, and Korean models.
        //My model is usung as default Simplified Chinese.
        //This command should be executed again after printer resets or powers down.
        //If Kanji mode is canceled, the printer processes a character code as a 1-byte code of alphanumeric Katakana characters.
        str += "\x1C\x2E";
        str += "\x1B\x74\x18"; // This sets the code page to CP737 Decimal (27 64 27 116 24)
    }

    //Resettinh styling!
    if (data.printerBrand == "Star TSP-100 Series") {
        str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
    } else {
        str += "\x1B\x21\x00"; // Commands to reset the styling.
    }

    //Checking to see if there is a barcode to print at the top
    if ((data.print_barcode == "1") && (data.barcodeTopBottom == "0")) {
        str += printBarcode(data.print_barcode, data.barcodeTopBottom, data.order_id, data.store_id, data.printerBrand);
    }

    str += data.order_details;
    //str += "Anestis Domvris τεσταρω τα Ελληνικά γράμματα!";

    //Checking to see if there is a barcode to print at the bottom
    if ((data.print_barcode == "1") && (data.barcodeTopBottom == "1")) {
        str += printBarcode(data.print_barcode, data.barcodeTopBottom, data.order_id, data.store_id, data.printerBrand);
    }

    //Resettinh styling!
    if (data.printerBrand == "Star TSP-100 Series") {
        str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
    } else {
        str += "\x1B\x21\x00"; // Commands to reset the styling.
    }

    //Preparing for cut!
    str += "\r\n";
    str += "\r\n";
    str += "\r\n";
    str += "\r\n";

    str += "\x1B\x40";
    if (data.auto_cutter == "1") {
        // Cut receipt
        if (data.printerBrand == "Star TSP-100 Series") {
            str += "\x1B\x64\x00";
        } else if (data.printerBrand == "OCOM") {
            str += "\x1D\x56\x42\x18";
        } else {
            str += "\x1B\x69";
        }
    }

    //str += "Lets see Greek: φψΩ Ελληνικά Γράμματα ΕΠΙΤΕΛΟΥΣ περισσότερα πολλά πολλά!!!!!! \n\n\n\nThis Awsome Tool!!!\r\n\x1B\x61\x01\x1D\x48\x00\x1D\x68\x60\x1D\x6B\x04 9000002345.\x00***90000002345****\n\n\n\x1B\x2A\x00\x30\x00\x01\x02\x04\x08\x10\x20\x40\x80\x80\x40\x20\x10\x08\x04\x02\x01\x01\x02\x04\x08\x10\x20\x40\x80\x80\x40\x20\x10\x08\x04\x02\x01\x01\x02\x04\x08\x10\x20\x40\x80\x80\x40\x20\x10\x08\x04\x02\x01\n\n\x1D\x56\x42\x18";

    //The barcode doesn't accept --
    var buffer = legacy.encode(str, 'cp737', {
        'mode': 'html'
    });

    //res.json is used usually when I want to return data from an API
    var printer = require("printer");

    printer.printDirect({
        data: buffer,
        printer: data.printer, // printer name
        type: 'RAW', // type: RAW, TEXT, PDF, JPEG, .. depends on platform
        success: function(jobID) {
            console.log("sent to printer with ID: " + jobID);
            res.json({
                message: str
            });
        },
        error: function(err) {
            res.json({
                message: err
            });
        }
    });
});

//API to check the version of the server.

app.get('/testError', function(req, res) {
    console.log("/testError was just called");
    //res.json is used usually when I want to return data from an API
    //throw new Error('something bad happened');
    var fs = require('fs');

    fs.readFile('somefile.txt', function(err, data) {
        if (err) throw err;
        console.log(data);
    });
});

var port;
var portfinder = require('portfinder');
portfinder.basePort = 4950;
portfinder.getPort(function(err, cleanPort) {
    //
    // `port` is guarenteed to be a free port
    // in this scope.
    //
    port = cleanPort;
    app.listen(port, function() {
        console.log("Node app is running at localhost:" + port);
    });

});
<commit_msg>chnages<commit_after>/*jslint node: true*/

//First we call the packages we need.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var bugsnag = require("bugsnag");
bugsnag.register("9d5907a30dcfaf8806e542fbf61cf623");
var legacy = require('legacy-encoding');

//Here I am creating the singleton connection to the MongoDb server.
//This connection will be used in all the controllers and middleware in the app.
//mongoDbConnection(function(db) {});

var os = require('os');
console.log(os.platform());
console.log(os.type());

console.log(os.hostname());
console.log(os.arch());
console.log(os.release());

var interfaces = os.networkInterfaces();
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}

console.log(addresses[0]);
app.use(bodyParser.json());
//Here I am placing the cron jobs
//var cron = require("./cronjobs");
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");
    next();
});
//In order to disable to flags for chromium
//open /Users/anestis/Downloads Chromium.app --args –allow-file-access-from-files -disable-web-security

// configure app to use bodyParser()
// this will let us get the data from a POST
//This is an express middleware
//It handles the data sent before sending them to the routes.

app.get('/printServer', function(req, res) {
    console.log("/printServer was just called");
    //res.json is used usually when I want to return data from an API
    res.json({
        message: 'Live'
    });
});

app.get('/getPrinters', function(req, res) {
    console.log("/printServer was just called");
    //res.json is used usually when I want to return data from an API
    var printer = require("printer");
    var util = require('util');
    console.log("installed printers:\n" + util.inspect(printer.getPrinters(), {
        colors: true,
        depth: 10
    }));

    res.json({
        message: printer.getPrinters()
    });
});

app.post('/printOrder', function(req, res) {
    var data = req.body;
    //json parameters: printer, printerBrand, printerCodepage, print_barcode, barcodeTopBottom, order_id, store_id, order_details, auto_cutter
    console.log("/print was just called");

    var printBarcode = function(print_barcode, barcodeTopBottom, order_id, store_id, printerBrand) {
        var str = "";
        var tempOrderId = "";
        var tempCount = "";
        var tempRes = "";
        var i = 0;
        if (printerBrand == "Star TSP-100 Series") {
            str += "\r\n"; //New line command! Important otherwise barcode after that will not work!
            str += "\x1B\x1D\x61\x01"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
            str += "\x1B\x62\x04\x01\x05\x60";
            tempOrderId = order_id;
            tempCount = store_id;
            tempRes = tempOrderId.substr(tempCount.length);
            i = 0;
            while (tempRes.charAt(i) === 0) {
                i++;
            }
            tempRes = tempRes.substr(i);
            //applet.append("-W00000159Q");
            str += "--" + tempRes + ".";
            str += "\x1E";
            str += "*** " + order_id + " ***\r\n";
            str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
        } else {
            str += "\r\n"; //New line command! Important otherwise barcode after that will not work!
            str += "\x1B\x61\x01"; // Centering
            str += "\x1D\x48\x00";
            str += "\x1D\x68\x60"; //Barcode height to 70 dots default is 165. The value must not ralate to other actions
            str += "\x1D\x6B\x04";
            tempOrderId = order_id;
            tempCount = store_id;
            tempRes = tempOrderId.substr(tempCount.length);
            i = 0;
            while (tempRes.charAt(i) === 0) {
                i++;
            }
            tempRes = tempRes.substr(i);
            //applet.append("-W00000159Q");
            str += "--" + tempRes + ".";
            str += "\x00";
            str += "*** " + order_id + " ***\r\n";
            str += "\x1B\x21\x00";
        }

        //Resettinh styling!
        if (printerBrand == "Star TSP-100 Series") {
            str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
        } else {
            str += "\x1B\x21\x00"; // Commands to reset the styling.
        }
        return str;
    };

    //It should accept more than one printers as input.
    var str = "\x1B\x40";

    if (data.printerBrand == "Star TSP-100 Series" && data.printerCodepage == "CP869") {
        str += "\x1B\x1D\x74\x11"; // This sets the code page to CP869
    } else if (data.printerBrand == "Star TSP-100 Series" && data.printerCodepage == "CP737") {
        str += "\x1B\x1D\x74\x0F"; // This sets the code page to CP737
    } else if (data.printerBrand == "Casio" && data.printerCodepage == "CP737") {
        //This is a hardware dependent command to "Cancel Kanji character mode".
        //This command can be used only for the Japanese, Simplified Chinese, Traditional Chinese, and Korean models.
        //My model is usung as default Simplified Chinese.
        //This command should be executed again after printer resets or powers down.
        //If Kanji mode is canceled, the printer processes a character code as a 1-byte code of alphanumeric Katakana characters.
        str += "\x1B\x74\x18"; // This sets the code page to CP737 Decimal (27 64 27 116 24)
    } else if ((data.printerBrand == "Xprinter" || data.printerBrand == "OCOM") && data.printerCodepage == "CP737") {
        //This is a hardware dependent command to "Cancel Kanji character mode".
        //This command can be used only for the Japanese, Simplified Chinese, Traditional Chinese, and Korean models.
        //My model is usung as default Simplified Chinese.
        //This command should be executed again after printer resets or powers down.
        //If Kanji mode is canceled, the printer processes a character code as a 1-byte code of alphanumeric Katakana characters.
        str += "\x1C\x2E";
        str += "\x1B\x74\x18"; // This sets the code page to CP737 Decimal (27 64 27 116 24)
    }

    //Resettinh styling!
    if (data.printerBrand == "Star TSP-100 Series") {
        str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
    } else {
        str += "\x1B\x21\x00"; // Commands to reset the styling.
    }

    //Checking to see if there is a barcode to print at the top
    if ((data.print_barcode == "1") && (data.barcodeTopBottom == "0")) {
        str += printBarcode(data.print_barcode, data.barcodeTopBottom, data.order_id, data.store_id, data.printerBrand);
    }

    str += data.order_details;
    //str += "Anestis Domvris τεσταρω τα Ελληνικά γράμματα!";

    //Checking to see if there is a barcode to print at the bottom
    if ((data.print_barcode == "1") && (data.barcodeTopBottom == "1")) {
        str += printBarcode(data.print_barcode, data.barcodeTopBottom, data.order_id, data.store_id, data.printerBrand);
    }

    //Resettinh styling!
    if (data.printerBrand == "Star TSP-100 Series") {
        str += "\x1B\x1D\x61\x00"; // Centering 1B 1D 61 01 for STAR center 00 for left and 02 for right
    } else {
        str += "\x1B\x21\x00"; // Commands to reset the styling.
    }

    //Preparing for cut!
    str += "\r\n";
    str += "\r\n";
    str += "\r\n";
    str += "\r\n";

    str += "\x1B\x40";
    if (data.auto_cutter == "1") {
        // Cut receipt
        if (data.printerBrand == "Star TSP-100 Series") {
            str += "\x1B\x64\x00";
        } else if (data.printerBrand == "OCOM") {
            str += "\x1D\x56\x42\x18";
        } else {
            str += "\x1B\x69";
        }
    }

    //str += "Lets see Greek: φψΩ Ελληνικά Γράμματα ΕΠΙΤΕΛΟΥΣ περισσότερα πολλά πολλά!!!!!! \n\n\n\nThis Awsome Tool!!!\r\n\x1B\x61\x01\x1D\x48\x00\x1D\x68\x60\x1D\x6B\x04 9000002345.\x00***90000002345****\n\n\n\x1B\x2A\x00\x30\x00\x01\x02\x04\x08\x10\x20\x40\x80\x80\x40\x20\x10\x08\x04\x02\x01\x01\x02\x04\x08\x10\x20\x40\x80\x80\x40\x20\x10\x08\x04\x02\x01\x01\x02\x04\x08\x10\x20\x40\x80\x80\x40\x20\x10\x08\x04\x02\x01\n\n\x1D\x56\x42\x18";

    //The barcode doesn't accept --
    var buffer = legacy.encode(str, 'cp737', {
        'mode': 'html'
    });

    //res.json is used usually when I want to return data from an API
    var printer = require("printer");

    printer.printDirect({
        data: buffer,
        printer: data.printer, // printer name
        type: 'RAW', // type: RAW, TEXT, PDF, JPEG, .. depends on platform
        success: function(jobID) {
            console.log("sent to printer with ID: " + jobID);
            res.json({
                message: str
            });
        },
        error: function(err) {
            res.json({
                message: err
            });
        }
    });
});

//API to check the version of the server.

app.get('/testError', function(req, res) {
    console.log("/testError was just called");
    //res.json is used usually when I want to return data from an API
    //throw new Error('something bad happened');
    var fs = require('fs');

    fs.readFile('somefile.txt', function(err, data) {
        if (err) throw err;
        console.log(data);
    });
});

var port;
var portfinder = require('portfinder');
portfinder.basePort = 4950;
portfinder.getPort(function(err, cleanPort) {
    //
    // `port` is guarenteed to be a free port
    // in this scope.
    //
    port = cleanPort;
    app.listen(port, function() {
        console.log("Node app is running at localhost:" + port);
    });

});
<|endoftext|>


<commit_before>'use strict';

module.exports = (function() {
  function processNode(node) {
    removeEmptyRulesets(node);
    mergeAdjacentWhitespace(node);
  }

  function removeEmptyRulesets(stylesheet) {
    stylesheet.forEach('ruleset', function(ruleset, i) {
      var block = ruleset.first('block');
      processNode(block);
      if (isEmptyBlock(block)) stylesheet.remove(i);
    });
  }

  /**
   * Removing ruleset nodes from tree may result in two adjacent whitespace
   * nodes which is not correct AST:
   * [space, ruleset, space] => [space, space]
   * To ensure correctness of further processing we should merge such nodes
   * into one:
   * [space, space] => [space]
   */
  function mergeAdjacentWhitespace(node) {
    var i = node.content.length - 1;
    while (i-- > 0) {
      if (node.get(i).is('space') && node.get(i + 1).is('space')) {
        node.get(i).content += node.get(i + 1).content;
        node.remove(i + 1);
      }
    }
  }

  /**
   * Block is considered empty when it has nothing but spaces.
   */
  function isEmptyBlock(node) {
    if (!node.length) return true;

    return !node.content.some(function(node) {
      return !node.is('space');
    });
  }

  return {
    name: 'remove-empty-rulesets',

    runBefore: 'block-indent',

    syntax: ['css', 'less', 'sass', 'scss'],

    accepts: {
      boolean: [true]
    },

    /**
     * Remove rulesets with no declarations.
     *
     * @param {String} ast
     */
    process: function(ast) {
      processNode(ast);
    },

    detectDefault: true,

    /**
     * Detects the value of an option at the tree node.
     * This option is treated as `true` by default, but any trailing space
     * would invalidate it.
     *
     * @param {node} ast
     */
    detect: function(ast) {
      let detected = [];

      ast.traverse(function(node) {
        if (!node.is('atrulers') && !node.is('block')) return;

        if (node.length === 0 ||
            (node.length === 1 && node.first().is('space'))) {
          detected.push(false);
        }
      });

      return detected;
    }
  };
})();
<commit_msg>[options] Fix remove-empty-rulesets<commit_after>'use strict';

module.exports = (function() {
  function processNode(node) {
    removeEmptyRulesets(node);
    mergeAdjacentWhitespace(node);
  }

  function removeEmptyRulesets(stylesheet) {
    stylesheet.forEach('ruleset', function(ruleset, i) {
      var block = ruleset.first('block');
      processNode(block);
      if (isEmptyBlock(block)) stylesheet.removeChild(i);
    });
  }

  /**
   * Removing ruleset nodes from tree may result in two adjacent whitespace
   * nodes which is not correct AST:
   * [space, ruleset, space] => [space, space]
   * To ensure correctness of further processing we should merge such nodes
   * into one:
   * [space, space] => [space]
   */
  function mergeAdjacentWhitespace(node) {
    var i = node.content.length - 1;
    while (i-- > 0) {
      if (node.get(i).is('space') && node.get(i + 1).is('space')) {
        node.get(i).content += node.get(i + 1).content;
        node.removeChild(i + 1);
      }
    }
  }

  /**
   * Block is considered empty when it has nothing but spaces.
   */
  function isEmptyBlock(node) {
    if (!node.length) return true;

    return !node.content.some(function(node) {
      return !node.is('space');
    });
  }

  return {
    name: 'remove-empty-rulesets',

    runBefore: 'block-indent',

    syntax: ['css', 'less', 'sass', 'scss'],

    accepts: {
      boolean: [true]
    },

    /**
     * Remove rulesets with no declarations.
     *
     * @param {String} ast
     */
    process: function(ast) {
      processNode(ast);
    },

    detectDefault: true,

    /**
     * Detects the value of an option at the tree node.
     * This option is treated as `true` by default, but any trailing space
     * would invalidate it.
     *
     * @param {node} ast
     */
    detect: function(ast) {
      let detected = [];

      ast.traverse(function(node) {
        if (!node.is('atrulers') && !node.is('block')) return;

        if (node.length === 0 ||
            (node.length === 1 && node.first().is('space'))) {
          detected.push(false);
        }
      });

      return detected;
    }
  };
})();
<|endoftext|>


<commit_before>function isostring (value) {
  return new Date(parseInt(value, 10)).toISOString()
}

function format (date, format) {
  const separators = [',', '.', '-', '/', ' ', '|', '_']
  const months = new Map([
    ['Jan', '01'],
    ['Feb', '02'],
    ['Mar', '03'],
    ['Apr', '04'],
    ['May', '05'],
    ['Jun', '06'],
    ['Jul', '07'],
    ['Aug', '08'],
    ['Sep', '09'],
    ['Oct', '10'],
    ['Nov', '11'],
    ['Dec', '12']
  ])

  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return 'Invalid Date'

  date = [
    { period: 'YYYY', value: date.getFullYear() },
    { period: 'MM', value: months.get(date.toDateString().substr(4, 3)) },
    { period: 'DD', value: date.getDate() }
  ]

  if (!format) return date[2].value + '-' + date[1].value + '-' + date[0].value
  const separator = separators.find(separator => format.includes(separator))

  if (!separator) {
    const part = date.find(date => date.period === format)
    return part ? part.value.toString() : 'Invalid Format'
  }

  format = format.split(separator)
  for (let i = 0; i < date.length; i++) {
    for (let j = 0; j < format.length; j++) {
      const index = format.indexOf(date[i].period)
      if (index === -1) {
        date.splice(i, 1)
        i--
      } else if (index !== i) {
        const copyDate = date[i]
        date[i] = date[index]
        date[index] = copyDate
      }
    }
  }

  let stringDate = ''
  date.forEach((element, index) => {
    if (index === date.length - 1) {
      stringDate += element.value
    } else {
      stringDate += element.value + separator
    }
  })
  return stringDate
}

function day (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getDate()
}

function weekday (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getDay()
}

function month (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getMonth()
}

function year (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getFullYear()
}

function prettydate (date, localization = 'en-En') {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()

  const year = date.getFullYear()
  let month = date.toLocaleString(localization, { month: 'long' })
  let weekday = date.toLocaleString(localization, { weekday: 'long' })
  let day = String(date.getDate())

  if (localization === 'en-En') {
    if (day === '1' || day === '21') {
      day += 'st'
    } else if (day === '2' || day === '22') {
      day += 'nd'
    } else if (day === '3' || day === '23') {
      day += 'rd'
    } else {
      day += 'th'
    }
    return `${weekday}, ${day} of ${month} ${year}`
  }
  if (localization === 'pl-Pl') {
    const weekdays = new Map([
      ['Mon', 'poniedziałek'],
      ['Tue', 'wtorek'],
      ['Wed', 'środa'],
      ['Thu', 'czwartek'],
      ['Fri', 'piątek'],
      ['Sat', 'sobota'],
      ['Sun', 'niedziela']
    ])
    const months = new Map([
      ['M01', 'stycznia'],
      ['M02', 'lutego'],
      ['M03', 'marca'],
      ['M04', 'kwietnia'],
      ['M05', 'maja'],
      ['M06', 'czerwca'],
      ['M07', 'lipca'],
      ['M08', 'sierpnia'],
      ['M09', 'września'],
      ['M10', 'października'],
      ['M11', 'listopada'],
      ['M12', 'grudnia']
    ])
    weekday = weekdays.get(weekday)
    month = months.get(month)
    return `${weekday}, ${day} ${month} ${year}`
  }
  throw new Error(`${localization} localization is not supported.`)
}

module.exports = function(pattern, date) {

};

function method(key) {
  return ({
    YYYY: ['getFullYear', 4],
    YY: ['getFullYear', 2],
    // getMonth is zero-based, thus the extra increment field
    MM: ['getMonth', 2, 1],
    DD: ['getDate', 2],
    HH: ['getHours', 2],
    mm: ['getMinutes', 2],
    ss: ['getSeconds', 2],
    ms: ['getMilliseconds', 3]
  })[key];
}

function timestamp (date, pattern = 'YYYY-MM-DD') {
  function method(key) {
    return ({
      YYYY: ['getFullYear', 4],
      YY: ['getFullYear', 2],
      MM: ['getMonth', 2, 1],
      DD: ['getDate', 2],
      HH: ['getHours', 2],
      mm: ['getMinutes', 2],
      ss: ['getSeconds', 2],
      ms: ['getMilliseconds', 3]
    })[key]
  }
  function assign() {
    var regex = /(?=(YYYY|YY|MM|DD|HH|mm|ss|ms))\1([:\/]*)/
    var match = regex.exec(pattern)

    if (match) {
      var increment = method(match[1])
      var val = '00' + String(date[increment[0]]() + (increment[2] || 0))
      var res = val.slice(-increment[1]) + (match[2] || '')
      pattern = pattern.replace(match[0], res)
      assign()
    }
  }

  assign(pattern)
  return pattern
}

module.exports = {
  isostring,
  format,
  day,
  weekday,
  month,
  year,
  prettydate,
  timestamp
}
<commit_msg>Fixed spec<commit_after>function isostring (value) {
  return new Date(parseInt(value, 10)).toISOString()
}

function format (date, format) {
  const separators = [',', '.', '-', '/', ' ', '|', '_']
  const months = new Map([
    ['Jan', '01'],
    ['Feb', '02'],
    ['Mar', '03'],
    ['Apr', '04'],
    ['May', '05'],
    ['Jun', '06'],
    ['Jul', '07'],
    ['Aug', '08'],
    ['Sep', '09'],
    ['Oct', '10'],
    ['Nov', '11'],
    ['Dec', '12']
  ])

  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return 'Invalid Date'

  date = [
    { period: 'YYYY', value: date.getFullYear() },
    { period: 'MM', value: months.get(date.toDateString().substr(4, 3)) },
    { period: 'DD', value: date.getDate() }
  ]

  if (!format) return date[2].value + '-' + date[1].value + '-' + date[0].value
  const separator = separators.find(separator => format.includes(separator))

  if (!separator) {
    const part = date.find(date => date.period === format)
    return part ? part.value.toString() : 'Invalid Format'
  }

  format = format.split(separator)
  for (let i = 0; i < date.length; i++) {
    for (let j = 0; j < format.length; j++) {
      const index = format.indexOf(date[i].period)
      if (index === -1) {
        date.splice(i, 1)
        i--
      } else if (index !== i) {
        const copyDate = date[i]
        date[i] = date[index]
        date[index] = copyDate
      }
    }
  }

  let stringDate = ''
  date.forEach((element, index) => {
    if (index === date.length - 1) {
      stringDate += element.value
    } else {
      stringDate += element.value + separator
    }
  })
  return stringDate
}

function day (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getDate()
}

function weekday (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getDay()
}

function month (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getMonth()
}

function year (date) {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()
  return date.getFullYear()
}

function prettydate (date, localization = 'en-En') {
  if (Object.prototype.toString.call(date) !== '[object Date]') date = new Date(date)
  if (!Number(date)) return date.toDateString()

  const year = date.getFullYear()
  let month = date.toLocaleString(localization, { month: 'long' })
  let weekday = date.toLocaleString(localization, { weekday: 'long' })
  let day = String(date.getDate())

  if (localization === 'en-En') {
    if (day === '1' || day === '21') {
      day += 'st'
    } else if (day === '2' || day === '22') {
      day += 'nd'
    } else if (day === '3' || day === '23') {
      day += 'rd'
    } else {
      day += 'th'
    }
    return `${weekday}, ${day} of ${month} ${year}`
  }
  if (localization === 'pl-Pl') {
    const weekdays = new Map([
      ['Monday', 'poniedziałek'],
      ['Tuesday', 'wtorek'],
      ['Wednesday', 'środa'],
      ['Thursday', 'czwartek'],
      ['Friday', 'piątek'],
      ['Saturday', 'sobota'],
      ['Sunday', 'niedziela']
    ])
    const months = new Map([
      ['January', 'stycznia'],
      ['February', 'lutego'],
      ['March', 'marca'],
      ['April', 'kwietnia'],
      ['May', 'maja'],
      ['June', 'czerwca'],
      ['July', 'lipca'],
      ['August', 'sierpnia'],
      ['September', 'września'],
      ['October', 'października'],
      ['November', 'listopada'],
      ['December', 'grudnia']
    ])
    weekday = weekdays.get(weekday)
    month = months.get(month)
    return `${weekday}, ${day} ${month} ${year}`
  }
  throw new Error(`${localization} localization is not supported.`)
}

function timestamp (date, pattern = 'YYYY-MM-DD') {
  function method(key) {
    return ({
      YYYY: ['getFullYear', 4],
      YY: ['getFullYear', 2],
      MM: ['getMonth', 2, 1],
      DD: ['getDate', 2],
      HH: ['getHours', 2],
      mm: ['getMinutes', 2],
      ss: ['getSeconds', 2],
      ms: ['getMilliseconds', 3]
    })[key]
  }
  function assign() {
    var regex = /(?=(YYYY|YY|MM|DD|HH|mm|ss|ms))\1([:\/]*)/
    var match = regex.exec(pattern)

    if (match) {
      var increment = method(match[1])
      var val = '00' + String(date[increment[0]]() + (increment[2] || 0))
      var res = val.slice(-increment[1]) + (match[2] || '')
      pattern = pattern.replace(match[0], res)
      assign()
    }
  }

  assign(pattern)
  return pattern
}

module.exports = {
  isostring,
  format,
  day,
  weekday,
  month,
  year,
  prettydate,
  timestamp
}
<|endoftext|>


<commit_before>'use strict';

const net = require('net');
const binding = require('bindings')('abstract_socket.node');

const socket  = binding.socket;
const bind    = binding.bind;
const connect = binding.connect;
const close   = binding.close;

function errnoException(errorno, syscall) {
    // TODO: having the errno message here would be nice
    const e = new Error(syscall + ' ' + errorno);
    e.errno = e.code = errorno;
    e.syscall = syscall;
    return e;
}

class AbstractSocketServer extends net.Server {
    constructor(listener) {
        super(listener);
    }

    listen(name, listener) {
        let err = socket();
        if (err < 0) {
            this.emit(errnoException(err, 'socket'));
        }

        const handle = {fd: err};

        err = bind(err, name);
        if (err < 0) {
            close(handle.fd);
            this.emit(errnoException(err, 'bind'));
        }
        super.listen(handle, listener);
    }
}

exports.createServer = function(listener) {
    return new AbstractSocketServer(listener);
};

exports.connect = exports.createConnection = function(name, connectListener) {
    let err = socket();
    if (err < 0) {
        throw errnoException(err, 'socket');
    }

    const options = {fd: err, readable: true, writable: true};

    // yes, connect is synchronous, so sue me
    err = connect(err, name);
    if (err < 0) {
        close(options.fd);
        throw errnoException(err, 'connect');
    }

    const sock = new net.Socket(options);
    setImmediate(() => connectListener(sock));
    return sock;
};

<commit_msg>Client emits error instead of throwing.<commit_after>'use strict';

const net = require('net');
const binding = require('bindings')('abstract_socket.node');

const socket  = binding.socket;
const bind    = binding.bind;
const connect = binding.connect;
const close   = binding.close;

function errnoException(errorno, syscall) {
    // TODO: having the errno message here would be nice
    const e = new Error(syscall + ' ' + errorno);
    e.errno = e.code = errorno;
    e.syscall = syscall;
    return e;
}

class AbstractSocketServer extends net.Server {
    constructor(listener) {
        super(listener);
    }

    listen(name, listener) {
        let err = socket();
        if (err < 0) {
            this.emit(errnoException(err, 'socket'));
        }

        const handle = {fd: err};

        err = bind(err, name);
        if (err < 0) {
            close(handle.fd);
            this.emit(errnoException(err, 'bind'));
        }
        super.listen(handle, listener);
    }
}

exports.createServer = function(listener) {
    return new AbstractSocketServer(listener);
};

exports.connect = exports.createConnection = function(name, connectListener) {
    const defaultOptions = {
        readable: true,
        writable: true
    };

    let err = socket();
    if (err < 0) {
        const sock = new net.Socket(defaultOptions);
        setImmediate(() => sock.emit('error', errnoException(err, 'socket')));
        return sock;
    }

    const options = Object.assign({fd: err}, defaultOptions);

    // yes, connect is synchronous, so sue me
    err = connect(err, name);
    if (err < 0) {
        close(options.fd);
        const sock = new net.Socket(defaultOptions);
        setImmediate(() => sock.emit('error', errnoException(err, 'connect')));
        return sock;
    }

    const sock = new net.Socket(options);
    setImmediate(() => connectListener(sock));
    return sock;
};

<|endoftext|>


<commit_before>$(function() {
  var once = false;

  var img = "";
  // RAILS 3.0 USERS -> Please delete the above line and uncomment the bottom line
  // ensure that the image directory matches
  // var img = "";

  var navbar = $(".pagination.alpha a");
  // Pick the handler list: just a quick check for the jQuery version (see here: http://bugs.jquery.com/ticket/10589)
  var handlers = navbar.data ? navbar.data('events') : jQuery._data(navbar[0], 'events');

  if (!handlers || -1 !== $.inArray(onNavbarClick, handlers.click)) {
      $(document).on("click", ".pagination.alpha a", onNavbarClick);
  }

  function onNavbarClick(e) {
      e.preventDefault();
      var url = location.href,
      letter = $(this).data("letter");
      if (/letter/.test(url)) {
          url = url.replace(/letter=[^&]*/, "letter=" + letter);
      }
      else {
          if (/\?/.test(url)) {
              url += "&letter=" + letter;
          }
          else {
              url += "?letter=" + letter;
          }
      }
      $(".pagination").html(img);
      //$.load(url + " #pagination_table");
      $.get(url, function(result) {
          $(".pagination").html($(".pagination", result));
          $("#pagination_table").html($("#pagination_table", result));
      });
      history.pushState(null, document.title, url);
  }

   // let navigate the browser throught the ajax history
  $(window).bind("popstate", function() {
    if (once) {
      $(".pagination").html(img);
      $.get(location.href, function(result) {
        $(".pagination").html($(".pagination", result));
          $("#pagination_table").html($("#pagination_table", result));
        });
      } else {
        once = true;
      }
  });

});
<commit_msg>Corrected miscoded jQuery<commit_after>$(function() {
  var once = false;

  var img = "";
  // RAILS 3.0 USERS -> Please delete the above line and uncomment the bottom line
  // ensure that the image directory matches
  // var img = "";

  var navbar = $(".pagination.alpha a");
  // Pick the handler list: just a quick check for the jQuery version (see here: http://bugs.jquery.com/ticket/10589)
  var handlers = navbar.data ? navbar.data('events') : jQuery._data(navbar[0], 'events');

  if (!handlers || -1 !== $.inArray(onNavbarClick, handlers.click)) {
      $(document).on("click", ".pagination.alpha a", onNavbarClick);
  }

  function onNavbarClick(e) {
      e.preventDefault();
      var url = location.href,
      letter = $(this).data("letter");
      if (/letter/.test(url)) {
          url = url.replace(/letter=[^&]*/, "letter=" + letter);
      }
      else {
          if (/\?/.test(url)) {
              url += "&letter=" + letter;
          }
          else {
              url += "?letter=" + letter;
          }
      }
      $(".pagination").html(img);
      //$.load(url + " #pagination_table");
      $.get(url, function(result) {
          $(".pagination").html($(".pagination", result).html());
          $("#pagination_table").html($("#pagination_table", result).html());
      });
      history.pushState(null, document.title, url);
  }

   // let navigate the browser throught the ajax history
  $(window).bind("popstate", function() {
    if (once) {
      $(".pagination").html(img);
      $.get(location.href, function(result) {
        $(".pagination").html($(".pagination", result));
          $("#pagination_table").html($("#pagination_table", result));
        });
      } else {
        once = true;
      }
  });

});
<|endoftext|>


<commit_before>/*eslint-env node*/

const fs = require('fs');
const gulp = require('gulp');
const runSequence = require('run-sequence');
const useref = require('gulp-useref');
const cleanCSS = require('gulp-clean-css');
const rename = require('gulp-rename');
const concat = require('gulp-concat');
const babelMinify = require('babel-minify');
const child_process = require('child_process');
const merge = require('merge-stream');
const zip = require('gulp-zip');
var packageJson = JSON.parse(fs.readFileSync('./package.json'));

function minifyJs(fileName) {
	const content = fs.readFileSync(fileName, 'utf8');
	const minifiedContent = babelMinify(content).code;
	fs.writeFileSync(fileName, minifiedContent);
	console.log(
		`[${fileName}]: ${content.length}kb -> ${minifiedContent.length}kb`
	);
}
gulp.task('runWebpack', function() {
	return child_process.execSync('yarn run build');
});

gulp.task('copyFiles', function() {
	return merge(
		gulp
			.src('src/lib/codemirror/theme/*')
			.pipe(gulp.dest('app/lib/codemirror/theme')),
		gulp
			.src('src/lib/codemirror/mode/**/*')
			.pipe(gulp.dest('app/lib/codemirror/mode')),
		gulp.src('src/lib/transpilers/*').pipe(gulp.dest('app/lib/transpilers')),
		gulp.src('src/lib/screenlog.js').pipe(gulp.dest('app/lib')),
		gulp.src('icons/*').pipe(gulp.dest('app/icons')),
		gulp
			.src([
				'src/preview.html',
				'src/detached-window.js',
				'src/icon-48.png',
				'src/icon-128.png',
				'src/patreon.png',
				'manifest.json'
			])
			.pipe(gulp.dest('app')),

		gulp
			.src('build/bundle.*.js')
			.pipe(rename('script.js'))
			.pipe(gulp.dest('app')),
		gulp
			.src('build/vendor.*.js')
			.pipe(rename('vendor.js'))
			.pipe(gulp.dest('app')),

		// Following CSS are copied to build/ folder where they'll be referenced by
		// useRef plugin to concat into one.
		gulp
			.src('src/lib/codemirror/lib/codemirror.css')
			.pipe(gulp.dest('build/lib/codemirror/lib')),
		gulp
			.src('src/lib/codemirror/addon/hint/show-hint.css')
			.pipe(gulp.dest('build/lib/codemirror/addon/hint')),
		gulp
			.src('src/lib/codemirror/addon/fold/foldgutter.css')
			.pipe(gulp.dest('build/lib/codemirror/addon/fold')),
		gulp
			.src('src/lib/codemirror/addon/dialog/dialog.css')
			.pipe(gulp.dest('build/lib/codemirror/addon/dialog')),
		gulp.src('src/lib/hint.min.css').pipe(gulp.dest('build/lib')),
		gulp.src('src/lib/inlet.css').pipe(gulp.dest('build/lib')),
		gulp.src('src/style.css').pipe(gulp.dest('build')),

		gulp
			.src([
				'src/FiraCode.ttf',
				'src/FixedSys.ttf',
				'src/Inconsolata.ttf',
				'src/Monoid.ttf'
			])
			.pipe(gulp.dest('app'))
	);
});

gulp.task('useRef', function() {
	return gulp
		.src('build/index.html')
		.pipe(useref())
		.pipe(gulp.dest('app'));
});

gulp.task('concatSwRegistration', function() {
	gulp
		.src(['src/service-worker-registration.js', 'app/script.js'])
		.pipe(concat('script.js'))
		.pipe(gulp.dest('app'));
});

gulp.task('minify', function() {
	minifyJs('app/script.js');
	minifyJs('app/vendor.js');
	minifyJs('app/lib/screenlog.js');

	gulp
		.src('app/*.css')
		.pipe(
			cleanCSS(
				{
					debug: true
				},
				details => {
					console.log(`${details.name}: ${details.stats.originalSize}`);
					console.log(`${details.name}: ${details.stats.minifiedSize}`);
				}
			)
		)
		.pipe(gulp.dest('app'));
});

gulp.task('fixIndex', function() {
	var contents = fs.readFileSync('build/index.html', 'utf8');
	// Replace hashed-filename script tags with unhashed ones
	contents = contents.replace(
		/\<\!\-\- SCRIPT-TAGS \-\-\>[\S\s]*?\<\!\-\- END-SCRIPT-TAGS \-\-\>/,
		'<script defer src="vendor.js"></script><script defer src="script.js"></script>'
	);

	// vendor.hash.js gets created outside our markers, so remove it
	contents = contents.replace(
		/\<script src="\/vendor\.[\S\s]*?\<\/script\>/,
		''
	);

	fs.writeFileSync('build/index.html', contents, 'utf8');
});

gulp.task('generate-service-worker', function(callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`,

			// has to be increased to around 2.8mb for sass.worker.js
			maximumFileSizeToCacheInBytes: 2900000
		},
		callback
	);
});

gulp.task('packageExtension', function() {
	child_process.execSync('cp -R app extension/');
	child_process.execSync('cp src/manifest.json extension');
	child_process.execSync('cp src/options.js extension');
	child_process.execSync('cp src/options.html extension');
	child_process.execSync('cp src/eventPage.js extension');
	child_process.execSync('cp src/icon-16.png extension');
	child_process.execSync(
		'rm -rf extension/service-worker.js extension/partials'
	);
	return merge(
		gulp
			.src('build/bundle.*.js')
			.pipe(rename('script.js'))
			.pipe(gulp.dest('extension')),
		gulp
			.src('build/vendor.*.js')
			.pipe(rename('vendor.js'))
			.pipe(gulp.dest('extension')),

		gulp
			.src('extension/*')
			.pipe(zip(`extension-${packageJson.version}.zip`))
			.pipe(gulp.dest('./'))
	);
});

gulp.task('cleanup', function() {
	return child_process.execSync('rm -rf build');
});

gulp.task('release', function(callback) {
	runSequence(
		'runWebpack',
		'copyFiles',
		'fixIndex',
		'useRef',
		'concatSwRegistration',
		'minify',
		'generate-service-worker',
		'packageExtension',
		'cleanup',
		function(error) {
			if (error) {
				console.log(error.message);
			} else {
				console.log('RELEASE FINISHED SUCCESSFULLY');
			}
			callback(error);
		}
	);
});

// gulp.task('default', ['generate-service-worker']);
<commit_msg>gulpfile: fix zip task pattern<commit_after>/*eslint-env node*/

const fs = require('fs');
const gulp = require('gulp');
const runSequence = require('run-sequence');
const useref = require('gulp-useref');
const cleanCSS = require('gulp-clean-css');
const rename = require('gulp-rename');
const concat = require('gulp-concat');
const babelMinify = require('babel-minify');
const child_process = require('child_process');
const merge = require('merge-stream');
const zip = require('gulp-zip');
var packageJson = JSON.parse(fs.readFileSync('./package.json'));

function minifyJs(fileName) {
	const content = fs.readFileSync(fileName, 'utf8');
	const minifiedContent = babelMinify(content).code;
	fs.writeFileSync(fileName, minifiedContent);
	console.log(
		`[${fileName}]: ${content.length}kb -> ${minifiedContent.length}kb`
	);
}
gulp.task('runWebpack', function() {
	return child_process.execSync('yarn run build');
});

gulp.task('copyFiles', function() {
	return merge(
		gulp
			.src('src/lib/codemirror/theme/*')
			.pipe(gulp.dest('app/lib/codemirror/theme')),
		gulp
			.src('src/lib/codemirror/mode/**/*')
			.pipe(gulp.dest('app/lib/codemirror/mode')),
		gulp.src('src/lib/transpilers/*').pipe(gulp.dest('app/lib/transpilers')),
		gulp.src('src/lib/screenlog.js').pipe(gulp.dest('app/lib')),
		gulp.src('icons/*').pipe(gulp.dest('app/icons')),
		gulp
			.src([
				'src/preview.html',
				'src/detached-window.js',
				'src/icon-48.png',
				'src/icon-128.png',
				'src/patreon.png',
				'manifest.json'
			])
			.pipe(gulp.dest('app')),

		gulp
			.src('build/bundle.*.js')
			.pipe(rename('script.js'))
			.pipe(gulp.dest('app')),
		gulp
			.src('build/vendor.*.js')
			.pipe(rename('vendor.js'))
			.pipe(gulp.dest('app')),

		// Following CSS are copied to build/ folder where they'll be referenced by
		// useRef plugin to concat into one.
		gulp
			.src('src/lib/codemirror/lib/codemirror.css')
			.pipe(gulp.dest('build/lib/codemirror/lib')),
		gulp
			.src('src/lib/codemirror/addon/hint/show-hint.css')
			.pipe(gulp.dest('build/lib/codemirror/addon/hint')),
		gulp
			.src('src/lib/codemirror/addon/fold/foldgutter.css')
			.pipe(gulp.dest('build/lib/codemirror/addon/fold')),
		gulp
			.src('src/lib/codemirror/addon/dialog/dialog.css')
			.pipe(gulp.dest('build/lib/codemirror/addon/dialog')),
		gulp.src('src/lib/hint.min.css').pipe(gulp.dest('build/lib')),
		gulp.src('src/lib/inlet.css').pipe(gulp.dest('build/lib')),
		gulp.src('src/style.css').pipe(gulp.dest('build')),

		gulp
			.src([
				'src/FiraCode.ttf',
				'src/FixedSys.ttf',
				'src/Inconsolata.ttf',
				'src/Monoid.ttf'
			])
			.pipe(gulp.dest('app'))
	);
});

gulp.task('useRef', function() {
	return gulp
		.src('build/index.html')
		.pipe(useref())
		.pipe(gulp.dest('app'));
});

gulp.task('concatSwRegistration', function() {
	gulp
		.src(['src/service-worker-registration.js', 'app/script.js'])
		.pipe(concat('script.js'))
		.pipe(gulp.dest('app'));
});

gulp.task('minify', function() {
	minifyJs('app/script.js');
	minifyJs('app/vendor.js');
	minifyJs('app/lib/screenlog.js');

	gulp
		.src('app/*.css')
		.pipe(
			cleanCSS(
				{
					debug: true
				},
				details => {
					console.log(`${details.name}: ${details.stats.originalSize}`);
					console.log(`${details.name}: ${details.stats.minifiedSize}`);
				}
			)
		)
		.pipe(gulp.dest('app'));
});

gulp.task('fixIndex', function() {
	var contents = fs.readFileSync('build/index.html', 'utf8');
	// Replace hashed-filename script tags with unhashed ones
	contents = contents.replace(
		/\<\!\-\- SCRIPT-TAGS \-\-\>[\S\s]*?\<\!\-\- END-SCRIPT-TAGS \-\-\>/,
		'<script defer src="vendor.js"></script><script defer src="script.js"></script>'
	);

	// vendor.hash.js gets created outside our markers, so remove it
	contents = contents.replace(
		/\<script src="\/vendor\.[\S\s]*?\<\/script\>/,
		''
	);

	fs.writeFileSync('build/index.html', contents, 'utf8');
});

gulp.task('generate-service-worker', function(callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`,

			// has to be increased to around 2.8mb for sass.worker.js
			maximumFileSizeToCacheInBytes: 2900000
		},
		callback
	);
});

gulp.task('packageExtension', function() {
	child_process.execSync('cp -R app extension/');
	child_process.execSync('cp src/manifest.json extension');
	child_process.execSync('cp src/options.js extension');
	child_process.execSync('cp src/options.html extension');
	child_process.execSync('cp src/eventPage.js extension');
	child_process.execSync('cp src/icon-16.png extension');
	child_process.execSync(
		'rm -rf extension/service-worker.js extension/partials'
	);
	return merge(
		gulp
			.src('build/bundle.*.js')
			.pipe(rename('script.js'))
			.pipe(gulp.dest('extension')),
		gulp
			.src('build/vendor.*.js')
			.pipe(rename('vendor.js'))
			.pipe(gulp.dest('extension')),

		gulp
			.src('extension/**/*')
			.pipe(zip(`extension-${packageJson.version}.zip`))
			.pipe(gulp.dest('./'))
	);
});

gulp.task('cleanup', function() {
	return child_process.execSync('rm -rf build');
});

gulp.task('release', function(callback) {
	runSequence(
		'runWebpack',
		'copyFiles',
		'fixIndex',
		'useRef',
		'concatSwRegistration',
		'minify',
		'generate-service-worker',
		'packageExtension',
		'cleanup',
		function(error) {
			if (error) {
				console.log(error.message);
			} else {
				console.log('RELEASE FINISHED SUCCESSFULLY');
			}
			callback(error);
		}
	);
});

// gulp.task('default', ['generate-service-worker']);
<|endoftext|>


<commit_before>var parse = require('./parse')

/**
 * Is date in the leap year?
 * @param {date|string} dirtyDate
 * @returns {boolean}
 */
var isLeapYear = function(dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return new Date(year, 1, 29).getMonth() == 1
}

module.exports = isLeapYear

<commit_msg>Make `isLeapYear` faster (closes #81)<commit_after>var parse = require('./parse')

/**
 * Is date in the leap year?
 * @param {date|string} dirtyDate
 * @returns {boolean}
 */
var isLeapYear = function(dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0
}

module.exports = isLeapYear

<|endoftext|>


<commit_before>const expect = require('chai').expect;
const ValidatorHelper = require('../dist/src/validator-helper').default;

describe('#ValidatorHelper test', function(){

	describe('#validateSchema', function () {

		it('expected result dont have error if notification is valid',function () {
			let notification = {
				title : 'Ey',
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			let result = ValidatorHelper.validateSchema('notification', notification);
			expect(result.error).to.be.null;
		});

		it('expected result have error if notification is not valid',function () {
			let notification = {
				title : 15262728,
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			let result = ValidatorHelper.validateSchema('notification', notification);
			expect(result.error).to.not.be.null;
		});
	});

	describe('#validateNotification', function () {

		it('expected result dont have error if notification is valid',function () {
			let notification = {
				title : 'Ey',
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			let result = ValidatorHelper.validateNotification(notification);
			expect(result.error).to.be.null;
		});

		it('expected result have error if notification is not valid',function () {
			let notification = {
				title : 15262728,
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			let result = ValidatorHelper.validateNotification('notification', notification);
			expect(result.error).to.not.be.null;
		});
	});

});<commit_msg>test for validate message<commit_after>const expect = require('chai').expect;
const ValidatorHelper = require('../dist/src/validator-helper').default;

describe('#ValidatorHelper test', function(){

	describe('#validateSchema', function () {

		it('expected result dont have error if notification is valid',function () {
			let notification = {
				title : 'Ey',
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			let result = ValidatorHelper.validateSchema('notification', notification);
			expect(result.error).to.be.null;
		});

		it('expected result have error if notification is not valid',function () {
			let notification = {
				title : 15262728,
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			let result = ValidatorHelper.validateSchema('notification', notification);
			expect(result.error).to.not.be.null;
		});
	});

	describe('#validateNotification', function () {
		let notification = {}

		beforeEach(function () {
			notification = {
				title : 'Ey',
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
		});

		it('expected result dont have error if notification is valid',function () {
			let result = ValidatorHelper.validateNotification(notification);
			expect(result.error).to.be.null;
		});

		it('expected result have error if notification is not valid',function () {
			notification.title = 15262728;
			let result = ValidatorHelper.validateNotification('notification', notification);
			expect(result.error).to.not.be.null;
		});
	});

	describe('#validateMessage', function () {

		let message = {}

		beforeEach(function () {
			message.notification = {
				title : 'Ey',
				body : 'Make push notifications great again',
				sound : 'cielitolindo'
			};
			message.to = '/topics/testing';
		});

		it('expected result dont have error if notification is valid',function () {
			let result = ValidatorHelper.validateMessage(message);
			expect(result.error).to.be.null;
		});

	});

});<|endoftext|>