<commit_before>function formatn(n) {
    if (n < 1e-3 || n > 1e4) {
        return n.toExponential(parseFloat(n.toPrecision(3)));
    } else {
        return n.toPrecision(3);
    }
}

function Fft(elem, host, port, udpport, rearrange_halves, mean_window_size, x_axis_min, x_axis_max, y_axis_min, y_axis_max) {
    this._host = host;
    this._port = port;
    this._udpport = udpport;
    this._rearrange_halves = rearrange_halves;
    this._mean_window_size = mean_window_size;
    this._mean_window = [];
    this._x_min = undefined;
    this._x_max = undefined;
    this._x_axis_min = x_axis_min;
    this._x_axis_max = x_axis_max;
    this._y_min = undefined;
    this._y_max = undefined;
    this._y_axis_min = y_axis_min;
    this._y_axis_max = y_axis_max;
    this._elem = d3.select(elem);
    this._total_width = $(elem).width();
    this._total_height = $(elem).height();
    this._margin = {top: 20, right: 20, bottom: 30, left: 50};
    this._graph_width = this._total_width
        - this._margin.left - this._margin.right;
    this._graph_height = this._total_height
        - this._margin.top - this._margin.bottom;
    this._chart = this._elem.append("svg")
        .attr("width", this._total_width)
        .attr("height", this._total_height)
        .append("g")
        .attr("transform", "translate(" + this._margin.left + "," + this._margin.top + ")");
    this._svgxaxis = this._chart.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + this._graph_height + ")");
    this._svgyaxis = this._chart.append("g")
        .attr("class", "axis");
    this._update_x_range(0,1024);
    this._update_y_range(-128, 127);
    this._fftline = d3.svg.line()
        .x(function(d, i) { return this._sx(i); })
        .y(function(d) { return this._graph_height - this._sy(d); });
    this._fftpath = this._chart.append("svg:path")
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-width", "1.5px");
    return this;
}

Fft.prototype._push_data = function(data) {
    this._mean_window.push(data);
    while (this._mean_window.length > this._mean_window_size) {
        this._mean_window.shift();
    }
}

Fft.prototype._get_window_mean = function() {
    var min_size = -1;
    for (var i = 0; i < this._mean_window.length; i++) {
        if (min_size == -1 || this._mean_window[i].length < min_size) {
            min_size = this._mean_window[i].length;
        }
    }
    mean = new Int8Array(min_size);
    for (var x = 0; x < min_size; x++) {
        var m = 0.0;
        for (var i = 0; i < this._mean_window.length; i++) {
            m = m + this._mean_window[i][x];
        }
        mean[x] = m / this._mean_window.length;
    }
    return mean;
}

Fft.prototype._update_x_range = function(x_min, x_max) {
    if (x_min != this._x_min || x_max != this._x_max) {
        this._x_min = x_min;
        this._x_max = x_max;
        this._sx = d3.scale.linear()
            .domain([x_min, x_max])
            .rangeRound([0, this._graph_width]);
        this.x_axis(this._x_axis_min, this._x_axis_max);
    }
}

Fft.prototype.x_axis = function(x_axis_min, x_axis_max) {
    this._x_axis_min = x_axis_min;
    this._x_axis_max = x_axis_max;
    this._xaxis = d3.svg.axis()
        .scale(this._sx)
        .orient("bottom")
        .tickValues([]);
    if (this._x_axis_max - this._x_axis_min > 0 && this._x_max - this._x_min > 0) {
        a = (this._x_axis_min - this._x_axis_max) / (this._x_min - this._x_max);
        b = (this._x_axis_max * this._x_min - this._x_axis_min * this._x_max) / (this._x_min - this._x_max);
        this._xaxis.tickValues([this._x_min, (this._x_max - this._x_min)/2, this._x_max])
            .tickFormat(function(d) { return formatn(a * d + b); });
    }
    this._svgxaxis.call(this._xaxis);
}

Fft.prototype._update_y_range = function(y_min, y_max) {
    if (y_min != this._y_min || y_max != this._y_max) {
        this._y_min = y_min;
        this._y_max = y_max;
        this._sy = d3.scale.linear()
            .domain([y_min, y_max])
            .rangeRound([0, this._graph_height]);
        this.y_axis(this._y_axis_min, this._y_axis_max);
    }
}

Fft.prototype.y_axis = function(y_axis_min, y_axis_max) {
    this._y_axis_min = y_axis_min;
    this._y_axis_max = y_axis_max;
    this._yaxis = d3.svg.axis()
        .scale(this._sy)
        .orient("left")
        .tickValues([]);
    if (this._y_axis_max - this._y_axis_min > 0 && this._y_max - this._y_min > 0) {
        a = (this._y_axis_max - this._y_axis_min) / (this._y_min - this._y_max);
        b = (this._y_axis_min * this._y_min - this._y_axis_max * this._y_max) / (this._y_min - this._y_max);
        this._yaxis.tickValues([this._y_min, (this._y_max - this._y_min)/2, this._y_max])
            .tickFormat(function(d) { return formatn(a * d + b); });
    }
    this._svgyaxis.call(this._yaxis);
}

function get_rearranged_fft(fft) {
    var rearranged = new Int8Array(fft.length);
    middle = Math.floor(fft.length / 2);
    rearranged.set(fft.subarray(middle, fft.length), 0);
    rearranged.set(fft.subarray(0, middle), middle);
    return rearranged;
}

Fft.prototype.start = function() {
    this._ws = new WebSocket("ws://" + this._host + ":" + this._port + "/fftws/" + this._udpport);
    this._ws.binaryType = "arraybuffer";
    this._ws.onopen = function() { console.log("fft websocket opened"); };
    this._ws.onclose = function() { console.log("fft websocket closed"); };
    var self = this;
    this._ws.onmessage = function(evt) {
        if (evt.data instanceof ArrayBuffer) {
            fft = new Int8Array(evt.data);
            self._push_data(fft);
            mean = self._get_window_mean();
            if (self._rearrange_halves) {
                mean = get_rearranged_fft(mean);
            }
            self._update_x_range(0, mean.length);
            self._fftpath.attr("d", self._fftline(mean));
        }
    };
    this._keepalive = setInterval(function() {
        self._ws.send("ping");
    }, 60000);
}

Fft.prototype.stop = function() {
    clearInterval(this._keepalive);
    this._ws.close();
}

Fft.prototype.clear = function() {
    this._fftpath.attr("d", null);
}
<commit_msg>fix buggy case in number formating<commit_after>function formatn(n) {
    if (n < 1e-3 || n > 1e4) {
        return parseFloat(n.toPrecision(3)).toExponential();
    } else {
        return n.toPrecision(3);
    }
}

function Fft(elem, host, port, udpport, rearrange_halves, mean_window_size, x_axis_min, x_axis_max, y_axis_min, y_axis_max) {
    this._host = host;
    this._port = port;
    this._udpport = udpport;
    this._rearrange_halves = rearrange_halves;
    this._mean_window_size = mean_window_size;
    this._mean_window = [];
    this._x_min = undefined;
    this._x_max = undefined;
    this._x_axis_min = x_axis_min;
    this._x_axis_max = x_axis_max;
    this._y_min = undefined;
    this._y_max = undefined;
    this._y_axis_min = y_axis_min;
    this._y_axis_max = y_axis_max;
    this._elem = d3.select(elem);
    this._total_width = $(elem).width();
    this._total_height = $(elem).height();
    this._margin = {top: 20, right: 20, bottom: 30, left: 50};
    this._graph_width = this._total_width
        - this._margin.left - this._margin.right;
    this._graph_height = this._total_height
        - this._margin.top - this._margin.bottom;
    this._chart = this._elem.append("svg")
        .attr("width", this._total_width)
        .attr("height", this._total_height)
        .append("g")
        .attr("transform", "translate(" + this._margin.left + "," + this._margin.top + ")");
    this._svgxaxis = this._chart.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + this._graph_height + ")");
    this._svgyaxis = this._chart.append("g")
        .attr("class", "axis");
    this._update_x_range(0,1024);
    this._update_y_range(-128, 127);
    this._fftline = d3.svg.line()
        .x(function(d, i) { return this._sx(i); })
        .y(function(d) { return this._graph_height - this._sy(d); });
    this._fftpath = this._chart.append("svg:path")
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-width", "1.5px");
    return this;
}

Fft.prototype._push_data = function(data) {
    this._mean_window.push(data);
    while (this._mean_window.length > this._mean_window_size) {
        this._mean_window.shift();
    }
}

Fft.prototype._get_window_mean = function() {
    var min_size = -1;
    for (var i = 0; i < this._mean_window.length; i++) {
        if (min_size == -1 || this._mean_window[i].length < min_size) {
            min_size = this._mean_window[i].length;
        }
    }
    mean = new Int8Array(min_size);
    for (var x = 0; x < min_size; x++) {
        var m = 0.0;
        for (var i = 0; i < this._mean_window.length; i++) {
            m = m + this._mean_window[i][x];
        }
        mean[x] = m / this._mean_window.length;
    }
    return mean;
}

Fft.prototype._update_x_range = function(x_min, x_max) {
    if (x_min != this._x_min || x_max != this._x_max) {
        this._x_min = x_min;
        this._x_max = x_max;
        this._sx = d3.scale.linear()
            .domain([x_min, x_max])
            .rangeRound([0, this._graph_width]);
        this.x_axis(this._x_axis_min, this._x_axis_max);
    }
}

Fft.prototype.x_axis = function(x_axis_min, x_axis_max) {
    this._x_axis_min = x_axis_min;
    this._x_axis_max = x_axis_max;
    this._xaxis = d3.svg.axis()
        .scale(this._sx)
        .orient("bottom")
        .tickValues([]);
    if (this._x_axis_max - this._x_axis_min > 0 && this._x_max - this._x_min > 0) {
        a = (this._x_axis_min - this._x_axis_max) / (this._x_min - this._x_max);
        b = (this._x_axis_max * this._x_min - this._x_axis_min * this._x_max) / (this._x_min - this._x_max);
        this._xaxis.tickValues([this._x_min, (this._x_max - this._x_min)/2, this._x_max])
            .tickFormat(function(d) { return formatn(a * d + b); });
    }
    this._svgxaxis.call(this._xaxis);
}

Fft.prototype._update_y_range = function(y_min, y_max) {
    if (y_min != this._y_min || y_max != this._y_max) {
        this._y_min = y_min;
        this._y_max = y_max;
        this._sy = d3.scale.linear()
            .domain([y_min, y_max])
            .rangeRound([0, this._graph_height]);
        this.y_axis(this._y_axis_min, this._y_axis_max);
    }
}

Fft.prototype.y_axis = function(y_axis_min, y_axis_max) {
    this._y_axis_min = y_axis_min;
    this._y_axis_max = y_axis_max;
    this._yaxis = d3.svg.axis()
        .scale(this._sy)
        .orient("left")
        .tickValues([]);
    if (this._y_axis_max - this._y_axis_min > 0 && this._y_max - this._y_min > 0) {
        a = (this._y_axis_max - this._y_axis_min) / (this._y_min - this._y_max);
        b = (this._y_axis_min * this._y_min - this._y_axis_max * this._y_max) / (this._y_min - this._y_max);
        this._yaxis.tickValues([this._y_min, (this._y_max - this._y_min)/2, this._y_max])
            .tickFormat(function(d) { return formatn(a * d + b); });
    }
    this._svgyaxis.call(this._yaxis);
}

function get_rearranged_fft(fft) {
    var rearranged = new Int8Array(fft.length);
    middle = Math.floor(fft.length / 2);
    rearranged.set(fft.subarray(middle, fft.length), 0);
    rearranged.set(fft.subarray(0, middle), middle);
    return rearranged;
}

Fft.prototype.start = function() {
    this._ws = new WebSocket("ws://" + this._host + ":" + this._port + "/fftws/" + this._udpport);
    this._ws.binaryType = "arraybuffer";
    this._ws.onopen = function() { console.log("fft websocket opened"); };
    this._ws.onclose = function() { console.log("fft websocket closed"); };
    var self = this;
    this._ws.onmessage = function(evt) {
        if (evt.data instanceof ArrayBuffer) {
            fft = new Int8Array(evt.data);
            self._push_data(fft);
            mean = self._get_window_mean();
            if (self._rearrange_halves) {
                mean = get_rearranged_fft(mean);
            }
            self._update_x_range(0, mean.length);
            self._fftpath.attr("d", self._fftline(mean));
        }
    };
    this._keepalive = setInterval(function() {
        self._ws.send("ping");
    }, 60000);
}

Fft.prototype.stop = function() {
    clearInterval(this._keepalive);
    this._ws.close();
}

Fft.prototype.clear = function() {
    this._fftpath.attr("d", null);
}
<|endoftext|>


<commit_before>Meteor.publish('messages', function () {
  return Messages.find();
});<commit_msg>Autopublish all useful info about all users.<commit_after>Meteor.publish('messages', function () {
  return Messages.find();
});

Meteor.publish(null, function () {
  return Meteor.users.find({}, {
    fields: {
      username: 1,
      profile: 1
    }
  });
});
<|endoftext|>


<commit_before>import RavenLogger from 'ember-cli-sentry/services/raven';
import config from 'travis/config/environment';

export default RavenLogger.extend({
  benignErrors: [
    'TransitionAborted',
    'UnrecognizedURLError',
    'not found',
    'returned a 403',
    'returned a 404',
    'operation failed',
    'operation was aborted'
  ],

  unhandledPromiseErrorMessage: '',

  captureException(/* error */) {
    this._super(...arguments);
  },

  logException(e) {
    // eslint-disable-next-line
    console.log('Caught an exception:', e);

    if (!this.ignoreError(e)) {
      this.captureException(e);
    }
  },

  captureMessage(/* message */) {
    return this._super(...arguments);
  },

  enableGlobalErrorCatching() {
    return this._super(...arguments);
  },

  ignoreError(error) {
    if (!this.shouldReportError()) {
      return true;
    } else {
      let { message } = error;
      return this.get('benignErrors').any(error => message.includes(error));
    }
  },

  callRaven(/* methodName, ...optional */) {
    return this._super(...arguments);
  },

  shouldReportError() {
    // Sentry recommends only reporting a small subset of the actual
    // frontend errors. This can get *very* noisy otherwise.
    if (config.enterprise || config.sentry.development) {
      return false;
    } else {
      let sampleRate = 10;
      return (Math.random() * 100 <= sampleRate);
    }
  }
});
<commit_msg>Only ignore benign errors that have a message (#1122)<commit_after>import RavenLogger from 'ember-cli-sentry/services/raven';
import config from 'travis/config/environment';

export default RavenLogger.extend({
  benignErrors: [
    'TransitionAborted',
    'UnrecognizedURLError',
    'not found',
    'returned a 403',
    'returned a 404',
    'operation failed',
    'operation was aborted'
  ],

  unhandledPromiseErrorMessage: '',

  captureException(/* error */) {
    this._super(...arguments);
  },

  logException(e) {
    // eslint-disable-next-line
    console.log('Caught an exception:', e);

    if (!this.ignoreError(e)) {
      this.captureException(e);
    }
  },

  captureMessage(/* message */) {
    return this._super(...arguments);
  },

  enableGlobalErrorCatching() {
    return this._super(...arguments);
  },

  ignoreError(error) {
    if (!this.shouldReportError()) {
      return true;
    } else {
      const message = error.message;
      if (message) {
        return this.get('benignErrors').any(error => message.includes(error));
      } else {
        return false;
      }
    }
  },

  callRaven(/* methodName, ...optional */) {
    return this._super(...arguments);
  },

  shouldReportError() {
    // Sentry recommends only reporting a small subset of the actual
    // frontend errors. This can get *very* noisy otherwise.
    if (config.enterprise || config.sentry.development) {
      return false;
    } else {
      let sampleRate = 10;
      return (Math.random() * 100 <= sampleRate);
    }
  }
});
<|endoftext|>


<commit_before>//
// PagerMon - reader.js
// 2017-06-04
// Author: Dave McKenzie
//
// Description: Takes output of multimon-ng and pushes to PagerMon server
//
// Usage: Invoke via a shell script, ideally
// 		If not, just pipe multimon's output to it
//
// Example: reader.sh
//

// CONFIG
// create config file if it does not exist, and set defaults
var fs = require('fs');
var conf_defaults = require('./config/default.json');
var conf_file = './config/config.json';
if( ! fs.existsSync(conf_file) ) {
    fs.writeFileSync( conf_file, JSON.stringify(conf_defaults,null, 2) );
    console.log('created config file - set your api key in '+conf_file);
    return;
}
// load the config file
var nconf = require('nconf');
    nconf.file({file: conf_file});
    nconf.load();

var hostname = nconf.get('hostname');
var apikey = nconf.get('apikey');
var identifier = nconf.get('identifier');

var uri = hostname+"/api/messages";

var http = require('http');
var request = require('request');
require('request').debug = true;
var rp = require('request-promise-native');
var moment = require('moment');

var colors = require('colors/safe');
colors.setTheme({
  success: ['white', 'bold', 'bgBlue'],
  error: ['red', 'bold', 'bgwhite']
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    terminal: true
});

rl.on('line', (line) => {
  //console.log(`Received: ${line.trim()}`);
  var time = moment().format("YYYY-MM-DD HH:mm:ss");
  var datetime = moment().unix();
  var address;
  var message;
  var trimMessage;
  // TODO: pad address with zeros for better address matching
//  if (line.indexOf('POCSAG512: Address:') > -1) {
  if (/^POCSAG(\d+): Address: /.test(line) ) {
  	address = line.match(/POCSAG(\d+): Address:(.*?)Function/)[2].trim();
    if (line.indexOf('Alpha:') > -1) {
    	message = line.match(/Alpha:(.*?)$/)[1].trim();
    	trimMessage = message.replace(/<[A-Za-z]{3}>/g,'').replace(/Ä/g,'[').replace(/Ü/g,']');
    } else if (line.indexOf('Numeric:') > -1) {
        message = line.match(/Numeric:(.*?)$/)[1].trim();
        trimMessage = message.replace(/<[A-Za-z]{3}>/g,'').replace(/Ä/g,'[').replace(/Ü/g,']');
    } else {
    	message = false;
    	trimMessage = '';
    }
  } else if (line.indexOf('FLEX: ') > -1) {
    address = line.match(/FLEX:.*?\[(\d*?)\] /)[1].trim();
      if (line.match( / [0-9]{4}\/[0-9]\/F\/. / )) {
       if (line.match( /( ALN | GPN | NUM)/ )) {
        frag = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
        message = false;
        trimMessage = '';
       }
      }
      if (line.match( /1600\/2\/C\/A/ )) {
       if (line.match( /( ALN | GPN | NUM)/ )) {
          message = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
          trimMessage = frag+message;
          }
        }
      if (line.match( /1600\/2\/K\/A/ )) {
        if (line.match( /( ALN | GPN | NUM)/ )) {
        message = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
        trimMessage = message;
        }
       }
    }

  // filter out most false hits
  // if too much junk data, make sure '-p' option isn't enabled in multimon
  if (address.length > 4 && message) {
    var padAddress = padDigits(address,7);
  	console.log(colors.red(time+': ')+colors.yellow(padAddress+': ')+colors.success(trimMessage));
  	// now send the message
  	var options = {
  		method: 'POST',
  		uri: uri,
  		headers: {
  			'X-Requested-With': 'XMLHttpRequest',
  			apikey: apikey
  		},
  		form: {
  			address: padAddress,
  			message: trimMessage,
  			datetime: datetime,
  			source: identifier
  		}
  	};
  	rp(options)
  	    .then(function (body) {
  	    //    console.log(colors.success('Message delivered. ID: '+body));
  	    })
  	    .catch(function (err) {
  	        console.log(colors.yellow('Message failed to deliver. '+err));
  	    });
  } else {
  	console.log(colors.red(time+': ')+colors.grey(line));
  }

}).on('close', () => {
  console.log('Input died!');
});

var padDigits = function(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};
<commit_msg>clean up<commit_after>//
// PagerMon - reader.js
// 2017-06-04
// Author: Dave McKenzie
//
// Description: Takes output of multimon-ng and pushes to PagerMon server
//
// Usage: Invoke via a shell script, ideally
// 		If not, just pipe multimon's output to it
//
// Example: reader.sh
//

// CONFIG
// create config file if it does not exist, and set defaults
var fs = require('fs');
var conf_defaults = require('./config/default.json');
var conf_file = './config/config.json';
if( ! fs.existsSync(conf_file) ) {
    fs.writeFileSync( conf_file, JSON.stringify(conf_defaults,null, 2) );
    console.log('created config file - set your api key in '+conf_file);
    return;
}
// load the config file
var nconf = require('nconf');
    nconf.file({file: conf_file});
    nconf.load();

var hostname = nconf.get('hostname');
var apikey = nconf.get('apikey');
var identifier = nconf.get('identifier');

var uri = hostname+"/api/messages";

var http = require('http');
var request = require('request');
require('request').debug = true;
var rp = require('request-promise-native');
var moment = require('moment');

var colors = require('colors/safe');
colors.setTheme({
  success: ['white', 'bold', 'bgBlue'],
  error: ['red', 'bold', 'bgwhite']
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    terminal: true
});

var frag;

rl.on('line', (line) => {
  //console.log(`Received: ${line.trim()}`);
  var time = moment().format("YYYY-MM-DD HH:mm:ss");
  var datetime = moment().unix();
  var address;
  var message;
  var trimMessage;
  // TODO: pad address with zeros for better address matching
//  if (line.indexOf('POCSAG512: Address:') > -1) {
  if (/^POCSAG(\d+): Address: /.test(line) ) {
  	address = line.match(/POCSAG(\d+): Address:(.*?)Function/)[2].trim();
    if (line.indexOf('Alpha:') > -1) {
    	message = line.match(/Alpha:(.*?)$/)[1].trim();
    	trimMessage = message.replace(/<[A-Za-z]{3}>/g,'').replace(/Ä/g,'[').replace(/Ü/g,']');
    } else if (line.indexOf('Numeric:') > -1) {
      message = line.match(/Numeric:(.*?)$/)[1].trim();
      trimMessage = message.replace(/<[A-Za-z]{3}>/g,'').replace(/Ä/g,'[').replace(/Ü/g,']');
    } else {
    	message = false;
    	trimMessage = '';
    }
  } else if (line.indexOf('FLEX: ') > -1) {
    address = line.match(/FLEX:.*?\[(\d*?)\] /)[1].trim();
    if (line.match( /( ALN | GPN | NUM)/ )) {
      if (line.match( / [0-9]{4}\/[0-9]\/F\/. / )) {
        // message is fragmented, hold onto it for next line
        frag = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
        message = false;
        trimMessage = '';
      } else if (line.match( / [0-9]{4}\/[0-9]\/C\/. / )) {
        // message is a completion of the last fragmented message
        message = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
        trimMessage = frag+message;
      } else if (line.match( / [0-9]{4}\/[0-9]\/K\/. / )) {
        // message is a full message
        message = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
        trimMessage = message;
      } else {
        // message doesn't have the KFC flags, treat as full message
        message = line.match(/FLEX:.*?\[\d*\] ... (.*?)$/)[1].trim();
        trimMessage = message;
      }
    }
  } else {
    address = '';
    message = false;
    trimMessage = '';
  }

  // filter out most false hits
  // if too much junk data, make sure '-p' option isn't enabled in multimon
  if (address.length > 4 && message) {
    var padAddress = padDigits(address,7);
  	console.log(colors.red(time+': ')+colors.yellow(padAddress+': ')+colors.success(trimMessage));
  	// now send the message
  	var options = {
  		method: 'POST',
  		uri: uri,
  		headers: {
  			'X-Requested-With': 'XMLHttpRequest',
  			apikey: apikey
  		},
  		form: {
  			address: padAddress,
  			message: trimMessage,
  			datetime: datetime,
  			source: identifier
  		}
  	};
  	rp(options)
  	    .then(function (body) {
  	    //    console.log(colors.success('Message delivered. ID: '+body));
  	    })
  	    .catch(function (err) {
  	        console.log(colors.yellow('Message failed to deliver. '+err));
  	    });
  } else {
  	console.log(colors.red(time+': ')+colors.grey(line));
  }

}).on('close', () => {
  console.log('Input died!');
});

var padDigits = function(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import redux from 'npm:redux';
import reducers from '../reducers/index';
import enhancers from '../enhancers/index';
import optional from '../reducers/optional';
import middlewareConfig from '../middleware/index';

const { assert, isArray, K } = Ember;

// Handle "classic" middleware exports (i.e. an array), as well as the hash option
const extractMiddlewareConfig = (mc) => {
  assert(
    'Middleware must either be an array, or a hash containing a `middleware` property',
    isArray(mc) || mc.middleware
  );
  return isArray(mc) ? { middleware: mc } : mc;
}

// Destructure the middleware array and the setup thunk into two different variables
const { middleware, setup = K } = extractMiddlewareConfig(middlewareConfig);

var { createStore, applyMiddleware, combineReducers, compose } = redux;
var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore);

export default Ember.Service.extend({
  init() {
    this.store = createStoreWithMiddleware(optional(combineReducers(reducers)));
    setup(this.store);
    this._super(...arguments);
  },
  getState() {
    return this.store.getState();
  },
  dispatch(action) {
    return this.store.dispatch(action);
  },
  subscribe(func) {
    return this.store.subscribe(func);
  }
});
<commit_msg>[REFACTOR]: remove Ember.K in favor of () => {}<commit_after>import Ember from 'ember';
import redux from 'npm:redux';
import reducers from '../reducers/index';
import enhancers from '../enhancers/index';
import optional from '../reducers/optional';
import middlewareConfig from '../middleware/index';

const { assert, isArray } = Ember;

// Handle "classic" middleware exports (i.e. an array), as well as the hash option
const extractMiddlewareConfig = (mc) => {
  assert(
    'Middleware must either be an array, or a hash containing a `middleware` property',
    isArray(mc) || mc.middleware
  );
  return isArray(mc) ? { middleware: mc } : mc;
}

// Destructure the middleware array and the setup thunk into two different variables
const { middleware, setup = () => {} } = extractMiddlewareConfig(middlewareConfig);

var { createStore, applyMiddleware, combineReducers, compose } = redux;
var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore);

export default Ember.Service.extend({
  init() {
    this.store = createStoreWithMiddleware(optional(combineReducers(reducers)));
    setup(this.store);
    this._super(...arguments);
  },
  getState() {
    return this.store.getState();
  },
  dispatch(action) {
    return this.store.dispatch(action);
  },
  subscribe(func) {
    return this.store.subscribe(func);
  }
});
<|endoftext|>


<commit_before>"use strict";

const path = require("path");

const zmq = require("zmq");

const subscriber = zmq.socket("sub");
const requester = zmq.socket("req");

const Hapi = require("hapi");
const web = new Hapi.Server();

web.connection({
    host: "0.0.0.0",
    port: Number(process.env.PORT || 8080)
});

const socketio = require("socket.io");
const io = socketio(web.listener);

web.route([
    { method: "GET", path: "/", handler: { view: "index.html" } },
    { method: "GET", path: "/{file*}", handler: { directory: { path: __dirname } } },
    { method: "GET", path: "/styles/{file*}", handler: { directory: { path: path.join(__dirname, "styles") } } },
    { method: "GET", path: "/scripts/{file*}", handler: { directory: { path: path.join(__dirname, "scripts") } } }
]);

web.views({
    engines: { html: require("handlebars") },
    path: path.join(__dirname, "templates")
});

//--------------------------
//-- ZeroMQ related code. --
//--------------------------

// 1. TCP based PUB-SUB.

// Subscribe on all messages.
subscriber.subscribe("");

// Handle each message individually - filtering by type.
subscriber.on("message", function (data) {
    let message = JSON.parse(data);

    if (message.type === "transaction") {
        console.info("Received transaction: %j,", message);
        io.emit("transaction", message);
    }
});

// Connecting to socket.
subscriber.connect(process.env.PUBLISHER_ADDRESS || "tcp://localhost:9002");

// 2. TCP based REQ-REP.

// Handling response individually.
requester.on("message", function (data) {
    console.info("Received response: %s", data);
});

// Connecting to socket.
requester.connect(process.env.REQUESTER_ADDRESS || "tcp://localhost:10020");

// Handling events from 'socket.io'.
io.on("connection", function (socket) {
    socket.on("start", function () {
        requester.send("toggle-state:start");
    });

    socket.on("stop", function () {
        requester.send("toggle-state:stop");
    });

    socket.on("coordinates-changed", function (result) {
        requester.send("coordinates-changed:" + JSON.stringify(result));
    });

    socket.on("disconnect", function () {
        console.info("User disconnected.");
    });
});

// Starting the web service.
web.start();

<commit_msg>Handling OS signals properly.<commit_after>"use strict";

const path = require("path");

const zmq = require("zmq");

const subscriber = zmq.socket("sub");
const requester = zmq.socket("req");

const Hapi = require("hapi");
const web = new Hapi.Server();

web.connection({
    host: "0.0.0.0",
    port: Number(process.env.PORT || 8080)
});

const socketio = require("socket.io");
const io = socketio(web.listener);

web.route([
    { method: "GET", path: "/", handler: { view: "index.html" } },
    { method: "GET", path: "/{file*}", handler: { directory: { path: __dirname } } },
    { method: "GET", path: "/styles/{file*}", handler: { directory: { path: path.join(__dirname, "styles") } } },
    { method: "GET", path: "/scripts/{file*}", handler: { directory: { path: path.join(__dirname, "scripts") } } }
]);

web.views({
    engines: { html: require("handlebars") },
    path: path.join(__dirname, "templates")
});

//--------------------------
//-- ZeroMQ related code. --
//--------------------------

// 1. TCP based PUB-SUB.

// Subscribe on all messages.
subscriber.subscribe("");

// Handle each message individually - filtering by type.
subscriber.on("message", function (data) {
    let message = JSON.parse(data);

    if (message.type === "transaction") {
        console.info("Received transaction: %j,", message);
        io.emit("transaction", message);
    }
});

// Connecting to socket.
subscriber.connect(process.env.PUBLISHER_ADDRESS || "tcp://localhost:9002");

// 2. TCP based REQ-REP.

// Handling response individually.
requester.on("message", function (data) {
    console.info("Received response: %s", data);
});

// Connecting to socket.
requester.connect(process.env.REQUESTER_ADDRESS || "tcp://localhost:10020");

// Handling events from 'socket.io'.
io.on("connection", function (socket) {
    socket.on("start", function () {
        requester.send("toggle-state:start");
    });

    socket.on("stop", function () {
        requester.send("toggle-state:stop");
    });

    socket.on("coordinates-changed", function (result) {
        requester.send("coordinates-changed:" + JSON.stringify(result));
    });

    socket.on("disconnect", function () {
        console.info("User disconnected.");
    });
});

// Starting the web service.
web.start();

// Handling OS signals properly.
process.on("SIGTERM", function () {
    console.info("Shutting down...");

    web.stop();

    requester.close();
    subscriber.close();

    process.exit(0);
});
<|endoftext|>


<commit_before>const Router = require('express').Router
const bodyParser = require('body-parser')

module.exports = (app) => {
  var verifyToken = app.config.slack.verifyToken
  var router = Router()

  router.post('/joke', bodyParser.json(), (req, res) => {
    if (req.body.token !== verifyToken) {
      return res.sendStatus(401)
    }

    app.jokes.random((err, joke) => {
      if (err) {
        app.log.error(err.message)
      }

      res.json({
        response_type: 'in_channel',
        text: joke || app.messages('NO_JOKE')
      })
    })
  })

  return router
}
<commit_msg>adding get handler for command<commit_after>const Router = require('express').Router
const bodyParser = require('body-parser')

module.exports = (app) => {
  var verifyToken = app.config.slack.verifyToken
  var router = Router()

  router.get('/joke', (req, res) => {
    res.sendStatus(200)
  })

  router.post('/joke', bodyParser.json(), (req, res) => {
    if (req.body.token !== verifyToken) {
      return res.sendStatus(401)
    }

    app.jokes.random((err, joke) => {
      if (err) {
        app.log.error(err.message)
      }

      res.json({
        response_type: 'in_channel',
        text: joke || app.messages('NO_JOKE')
      })
    })
  })

  return router
}
<|endoftext|>


<commit_before>

var app =  angular.module('WordcountApp', [])

  app.controller('WordcountController', ['$scope', '$log', '$http', '$timeout',
    function($scope, $log, $http, $timeout) {

    $scope.submitButtonText = 'Submit';
    $scope.loading = false;
    $scope.urlerror = false;

    $scope.getResults = function() {

      $log.log('test');

      // get the URL from the input
      var userInput = $scope.url;

      // fire the API request
      var fd = new FormData();
        fd.append('file', userInput);
        $http.post('/upload', fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(results) {
          $log.log(results);
          getWordCount(results);
          $scope.wordcounts = null;
          $scope.loading = true;
          $scope.submitButtonText = 'Loading...';
          $scope.urlerror = false;
        })
        .error(function(error) {
          $log.log(error);
        });

    };

    function getWordCount(jobID) {

      var timeout = '';

      var poller = function() {
        // fire another request
        $http.get('/results/'+jobID).
          success(function(data, status, headers, config) {
            if(status === 202) {
              $log.log(data, status);
            } else if (status === 200){
              $log.log(data);
              $scope.loading = false;
              $scope.submitButtonText = "Submit";
              $scope.wordcounts = data;
              $timeout.cancel(timeout);
              return false;
            }
            // continue to call the poller() function every 2 seconds
            // until the timeout is cancelled
            timeout = $timeout(poller, 2000);
          }).
          error(function(error) {
            $log.log(error);
            $scope.loading = false;
            $scope.submitButtonText = "Submit";
            $scope.urlerror = true;
          });
      };

      poller();

    }

  }])

  app.directive('wordCountChart', ['$parse', function ($parse) {
    return {
      restrict: 'E',
      replace: true,
      template: '

',
      link: function (scope) {
        scope.$watch('wordcounts', function() {
          d3.select('#chart').selectAll('*').remove();
          var data = scope.wordcounts;
          for (var word in data) {
            d3.select('#chart')
              .append('div')
              .selectAll('div')
              .data(word[0])
              .enter()
              .append('div')
              .style('width', function() {
                return (data[word] * 20) + 'px';
              })
              .text(function(d){
                return word;
              });
          }
        }, true);
      }
     };
  }]);
<commit_msg>form data stuff<commit_after>

var app =  angular.module('WordcountApp', [])

  app.controller('WordcountController', ['$scope', '$log', '$http', '$timeout',
    function($scope, $log, $http, $timeout) {

    $scope.submitButtonText = 'Submit';
    $scope.loading = false;
    $scope.urlerror = false;

    $scope.getResults = function() {

      $log.log('test');

      // get the URL from the input
      var userInput = $scope.url;

      // fire the API request
      var fd = new FormData();
        fd.append('files[]', userInput);
        $http.post('/upload', fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(results) {
          $log.log(results);
          getWordCount(results);
          $scope.wordcounts = null;
          $scope.loading = true;
          $scope.submitButtonText = 'Loading...';
          $scope.urlerror = false;
        })
        .error(function(error) {
          $log.log(error);
        });

    };

    function getWordCount(jobID) {

      var timeout = '';

      var poller = function() {
        // fire another request
        $http.get('/results/'+jobID).
          success(function(data, status, headers, config) {
            if(status === 202) {
              $log.log(data, status);
            } else if (status === 200){
              $log.log(data);
              $scope.loading = false;
              $scope.submitButtonText = "Submit";
              $scope.wordcounts = data;
              $timeout.cancel(timeout);
              return false;
            }
            // continue to call the poller() function every 2 seconds
            // until the timeout is cancelled
            timeout = $timeout(poller, 2000);
          }).
          error(function(error) {
            $log.log(error);
            $scope.loading = false;
            $scope.submitButtonText = "Submit";
            $scope.urlerror = true;
          });
      };

      poller();

    }

  }])

  app.directive('wordCountChart', ['$parse', function ($parse) {
    return {
      restrict: 'E',
      replace: true,
      template: '

',
      link: function (scope) {
        scope.$watch('wordcounts', function() {
          d3.select('#chart').selectAll('*').remove();
          var data = scope.wordcounts;
          for (var word in data) {
            d3.select('#chart')
              .append('div')
              .selectAll('div')
              .data(word[0])
              .enter()
              .append('div')
              .style('width', function() {
                return (data[word] * 20) + 'px';
              })
              .text(function(d){
                return word;
              });
          }
        }, true);
      }
     };
  }]);
<|endoftext|>


<commit_before>describe('Jasmine run', function() {
  it('should pass', function () {
    expect(true).toBe(true);
  });

  it('should fail', function () {

    expect(jasmine.Ajax).toBeDefined();
  })
});

describe('GridData', function () {
  var gd = new app.GridData();

  beforeEach(function() {
    jasmine.Ajax.install();

  });

  afterEach(function() {
    jasmine.Ajax.uninstall();
  });

  it('should request url with passed docId', function () {
    gd.fetch('23801');
    expect(jasmine.Ajax.requests.mostRecent().url).toMatch('//iac.tender.pro/demo/company_23801.json');
  });

  it('should return Promise', function () {
    var req = gd.fetch('23801');
    expect($.isFunction(req.then)).toBe(true);
  });

  it('should not request anything if no docId passed', function () {
    gd.fetch(null);
    expect(jasmine.Ajax.requests.count()).toBe(0);
  });

  it('returned Promise should be rejected if no docId passed', function () {
    var spy = jasmine.createSpy();
    var resp = gd.fetch(null);
    resp.fail(spy);
    expect(spy).toHaveBeenCalled();
  });

  it('should unwrap first element from returned array', function () {
    var response = [
      { id: '1234' }
    ],
      doneFn = jasmine.createSpy();

    var req = gd.fetch('23081');

    jasmine.Ajax.requests.mostRecent().respondWith({
      "status": 200,
      "responseText": JSON.stringify(response)
    });

    req.then(doneFn);
    expect(doneFn).toHaveBeenCalledWith(response[0]);
  });
});

describe('Grid component', function () {
  // component's markup
  var rootHtml = '
 \

 \

 \

',
    rootElem = $(rootHtml),
    gridData = new app.GridData(),
    fetchDfd;

  beforeEach(function () {
    fetchDfd = $.Deferred();
    // mock call for url parameter
    spyOn(app.utils, 'getUrlParam').and.returnValue('23801');

    // mock loading template, and serve it from html2js cache immediately
    spyOn(app.utils.tmpl, 'loadTemplate').and.callFake(function (url) {
      var dfd = $.Deferred();
      dfd.resolve($(window.__html__[url]));
      return dfd.promise();
    });

    // mock response from GridData.fetch
    spyOn(gridData, 'fetch').and.returnValue(fetchDfd.promise());
  });

  it('should instantiate', function () {
    var grid = new app.Grid(rootElem, gridData, app.utils);
  });

  it('should render "p.error" message and no table when there is no data', function () {
    fetchDfd.resolve(null);
    var grid = new app.Grid(rootElem, gridData, app.utils);
    expect(rootElem.find('p.error').length).toBe(1);
    expect(rootElem.find('table').length).toBe(0);
  });

  it('should render table with passed data', function () {
    fetchDfd.resolve({
      id: '1234',
      name: 'Some Name'
    });
    var grid = new app.Grid(rootElem, gridData, app.utils);

    expect(rootElem.find('table').length).toBe(1);
    expect(rootElem.find("th:contains('ID')").length).toBe(1);
    expect(rootElem.find("th:contains('NAME')").length).toBe(1);
    expect(rootElem.find("td:contains('1234')").length).toBe(1);
    expect(rootElem.find("td:contains('Some Name')").length).toBe(1);
  });

  it('should render array field as comma separated string', function () {
    fetchDfd.resolve({
      location: ["Россия","Приволжский","Казань"]
    });

    var grid = new app.Grid(rootElem, gridData, app.utils);

    expect(rootElem.find('td:contains("Россия, Приволжский, Казань")').length).toBe(1);
  });

});
<commit_msg>Test file cleanup<commit_after>/**
 * Test suites for main application components: app.Grid and app.GridData
 */

describe('GridData', function () {
  var gd = new app.GridData();

  beforeEach(function() {
    jasmine.Ajax.install();

  });

  afterEach(function() {
    jasmine.Ajax.uninstall();
  });

  it('should request url with passed docId', function () {
    gd.fetch('23801');
    expect(jasmine.Ajax.requests.mostRecent().url).toMatch('//iac.tender.pro/demo/company_23801.json');
  });

  it('should return Promise', function () {
    var req = gd.fetch('23801');
    expect($.isFunction(req.then)).toBe(true);
  });

  it('should not request anything if no docId passed', function () {
    gd.fetch(null);
    expect(jasmine.Ajax.requests.count()).toBe(0);
  });

  it('returned Promise should be rejected if no docId passed', function () {
    var spy = jasmine.createSpy();
    var resp = gd.fetch(null);
    resp.fail(spy);
    expect(spy).toHaveBeenCalled();
  });

  it('should unwrap first element from returned array', function () {
    var response = [
      { id: '1234' }
    ],
      doneFn = jasmine.createSpy();

    var req = gd.fetch('23081');

    jasmine.Ajax.requests.mostRecent().respondWith({
      "status": 200,
      "responseText": JSON.stringify(response)
    });

    req.then(doneFn);
    expect(doneFn).toHaveBeenCalledWith(response[0]);
  });
});

describe('Grid component', function () {
  // component's markup
  var rootHtml = '
 \

 \

 \

',
    rootElem,
    gridData = new app.GridData(),
    fetchDfd;

  beforeEach(function () {
    rootElem = $(rootHtml);
    fetchDfd = $.Deferred();
    // mock call for url parameter
    spyOn(app.utils, 'getUrlParam').and.returnValue('23801');

    // mock loading template, and serve it from html2js cache immediately
    spyOn(app.utils.tmpl, 'loadTemplate').and.callFake(function (url) {
      var dfd = $.Deferred();
      dfd.resolve($(window.__html__[url]));
      return dfd.promise();
    });

    // mock response from GridData.fetch
    spyOn(gridData, 'fetch').and.returnValue(fetchDfd.promise());
  });

  it('should instantiate', function () {
    var grid = new app.Grid(rootElem, gridData, app.utils);
  });

  it('should render "p.error" message and no table when there is no data', function () {
    fetchDfd.resolve(null);
    var grid = new app.Grid(rootElem, gridData, app.utils);
    expect(rootElem.find('p.error').length).toBe(1);
    expect(rootElem.find('table').length).toBe(0);
  });

  it('should render table with passed data', function () {
    fetchDfd.resolve({
      id: '1234',
      name: 'Some Name'
    });
    var grid = new app.Grid(rootElem, gridData, app.utils);

    expect(rootElem.find('table').length).toBe(1);
    expect(rootElem.find("th:contains('ID')").length).toBe(1);
    expect(rootElem.find("th:contains('NAME')").length).toBe(1);
    expect(rootElem.find("td:contains('1234')").length).toBe(1);
    expect(rootElem.find("td:contains('Some Name')").length).toBe(1);
  });

  it('should render array field as comma separated string', function () {
    fetchDfd.resolve({
      location: ["Россия","Приволжский","Казань"]
    });

    var grid = new app.Grid(rootElem, gridData, app.utils);

    expect(rootElem.find('td:contains("Россия, Приволжский, Казань")').length).toBe(1);
  });

});
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.util.linefeed = '\n';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readYAML('../config/config.yml'),

        watch: {
            options: {
                spawn: false,
                livereload: true
            },
            scripts: {
                files: [
                    'sass/*.scss',
                    'sass/nav/*.scss',
                    'sass/modules/*.scss'
                ],
                tasks: [
                    'sass'
                ]
            },
            js: {
                files: [
                    'lib/bolt/*.js'
                ],
                tasks: [
                    'uglify:bolt'
                ]
            }
        },

        sass: {
            dist: {
                options: {
                    outputStyle: 'compressed',
                    includePaths: [
                        'node_modules/bootstrap-sass/assets/stylesheets/',
                        'node_modules/font-awesome/scss/'
                    ],
                    lineNumbers: false,
                    unixNewlines: true,
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED CSS files!\n" +
                            " * Do not edit these files, because all changes will be lost.\n" +
                            " * You can edit ../scss/app.scss & ../scss/app-old-ie.scss, and run 'grunt' to generate this file.\n" +
                            " */\n",
                    precision: 5
                },
                files: {
                    'css/bolt-old-ie.css': 'sass/app-old-ie.scss',
                    'css/bolt.css': 'sass/app.scss'
                }
            }

        },

        copy: {
            main: {
                // Includes files within path
                files: [{
                    expand: true,
                    flatten: true,
                    src: [
                        'node_modules/font-awesome/fonts/*'
                    ],
                    filter: 'isFile',
                    dest: 'fonts/'
                }]
            }
        },

        concat: {
        },

        cssmin: {
            lib: {
                options: {
                    compatibility: 'ie8',
                    relativeTo: './css/',
                    target: './css/'
                },
                files: {
                    'css/lib.css': [
                        'lib/jquery-ui-1.10.3/jquery-ui.custom.min.css',
                        'lib/magnific-popup-0.9.9/magnific-popup.css',
                        'lib/select2-3.5.1/select2.css',
                        'lib/jquery.fileupload-5.26/jquery.fileupload-ui.css'
                    ]
                }
            }
        },

        uglify: {
            jquery_catchpaste: {
                options: {
                    preserveComments: 'some'
                },
                files: {
                    'lib/jquery-catchpaste-1.0.0p/jquery-catchpaste.min.js': [
                        'lib/jquery-catchpaste-1.0.0p/jquery-catchpaste.js'
                    ]
                }
            },
            jquery_tagcloud: {
                options: {
                    preserveComments: 'some'
                },
                files: {
                    'lib/jquery-tagcloud/jquery-tagcloud.min.js': [
                        'lib/jquery-tagcloud/jquery-tagcloud.js'
                    ]
                }
            },
            jquery_hotkeys: {
                options: {
                    preserveComments: 'some'
                },
                files: {
                    'lib/jquery-hotkeys/jquery-hotkeys.min.js': [
                        'lib/jquery-hotkeys/jquery-hotkeys.js'
                    ]
                }
            },
            jquery_watchchanges: {
                options: {
                    preserveComments: 'some'
                },
                files: {
                    'lib/jquery-watchchanges/jquery-watchchanges.min.js': [
                        'lib/jquery-watchchanges/jquery-watchchanges.js'
                    ]
                }
            },
            jquery_cookie: {
                options: {
                    preserveComments: 'some'
                },
                files: {
                    'lib/jquery-cookie-1.4.0/jquery-cookie.min.js': [
                        'lib/jquery-cookie-1.4.0/jquery-cookie.js'
                    ]
                }
            },
            jquery_formatdatetime: {
                options: {
                    preserveComments: 'some'
                },
                files: {
                    'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.min.js': [
                        'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.js'
                    ]
                }
            },
            bootstrap_file_input: {
                files: {
                    'lib/bootstrap-file-input/bootstrap-file-input.min.js': [
                        'lib/bootstrap-file-input/bootstrap-file-input.js'
                    ]
                }
            },
            bootstrap: {
                files: {
                    'lib/bootstrap-sass.generated/bootstrap.min.js': [
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/button.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/transition.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/popover.js'
                    ]
                }
            },
            bolt: {
                options: {
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED JS files!\n" +
                            " * You can edit files in <js/src/*.js> and run 'grunt' to generate this file.\n" +
                            " */",
                    sourceMap: true
                },
                files: {
                    'js/bolt.min.js': [
                        'lib/bolt/console.js',
                        'lib/bolt/fnc-helpers.js',
                        'lib/bolt/activity.js',
                        'lib/bolt/bind-fileupload.js',
                        'lib/bolt/make-uri-slug.js',
                        'lib/bolt/video-embed.js',
                        'lib/bolt/geolocation.js',
                        'lib/bolt/upload-files.js',
                        'lib/bolt/obj-sidebar.js',
                        'lib/bolt/obj-navpopups.js',
                        'lib/bolt/obj-moments.js',
                        'lib/bolt/obj-files.js',
                        'lib/bolt/obj-stack.js',
                        'lib/bolt/obj-folders.js',
                        'lib/bolt/obj-datetime.js',
                        'lib/bolt/extend.js',
                        'lib/bolt/init.js',
                        'lib/bolt/start.js'
                    ]
                }
            }
        },

        jshint: {
            options: {
                browser: true,          // Defines globals exposed by modern browsers
                curly: true,            // Always put curly braces around blocks
                devel: true,            // Defines globals that are usually used for logging/debugging
                immed: true,            // Prohibits the use of immediate function invocations without parentheses
                indent: 4,              // Tab width
                latedef: true,          // Prohibits the use of a variable before it was defined
                maxlen: 120,            // Maximum length of a line
                noarg: true,            // Prohibits the use of arguments.caller and arguments.callee
                nonbsp: true,           // Warns about "non-breaking whitespace" characters
                singleGroups: true,     // Prohibits the use of the grouping operator for single-expression statements
                undef: true,            // Prohibits the use of undeclared variables
                globals: {
                    // Bolt
                    bolt: true,                 // src/console.js
                    FilelistHolder: true,       // src/upload-files.js
                    Files: true,                // src/obj-files.js
                    Folders: true,              // src/obj-folders.js
                    init: true,                 // src/init.js
                    Moments: true,              // src/obj-moments.js
                    Navpopups: true,            // src/obj-navpopups.js
                    Sidebar: true,              // src/obj-sidebar.js
                    Stack: true,                // src/obj-stack.js
                    site: true,                 // src/extend.js/extend.twig
                    baseurl: true,              // src/extend.js/extend.twig
                    // Bolt global functions
                    bindFileUpload: true,       // src/bindfileuploads.js
                    bindGeolocation: true,      // src/geolocation.js
                    bindVideoEmbed: true,       // src/video-embed.js
                    getSelectedItems: true,     // src/fnc-helpers.js
                    makeUri: true,              // src/make-uri-slug.js
                    makeUriAjax: true,          // src/make-uri-slug.js
                    stopMakeUri: true,          // src/make-uri-slug.js
                    updateLatestActivity: true, // src/activity.js
                    validateContent: true,      // src/fnc-helpers.js
                    // Vendor
                    $: true,                    // jQuery
                    _: true,                    // underscore.js
                    Backbone: true,             // backbone.min.js
                    bootbox: true,              // bootbox.min.js
                    CKEDITOR: true,             // ckeditor.js
                    CodeMirror: true,           // ckeditor.js
                    google: true,               // Google
                    jQuery: true,               // jQuery
                    moment: true,               // moment.min.js
                    UAParser: true              // ua-parser.min.js
                }
            },
            src: ['lib/bolt/*.js']
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', ['sass', 'jshint', 'uglify', 'cssmin', 'watch']);

};
<commit_msg>Simplyify definition of lib uglifying<commit_after>module.exports = function(grunt) {
    grunt.util.linefeed = '\n';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readYAML('../config/config.yml'),

        watch: {
            options: {
                spawn: false,
                livereload: true
            },
            scripts: {
                files: [
                    'sass/*.scss',
                    'sass/nav/*.scss',
                    'sass/modules/*.scss'
                ],
                tasks: [
                    'sass'
                ]
            },
            js: {
                files: [
                    'lib/bolt/*.js'
                ],
                tasks: [
                    'uglify:bolt'
                ]
            }
        },

        sass: {
            dist: {
                options: {
                    outputStyle: 'compressed',
                    includePaths: [
                        'node_modules/bootstrap-sass/assets/stylesheets/',
                        'node_modules/font-awesome/scss/'
                    ],
                    lineNumbers: false,
                    unixNewlines: true,
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED CSS files!\n" +
                            " * Do not edit these files, because all changes will be lost.\n" +
                            " * You can edit ../scss/app.scss & ../scss/app-old-ie.scss, and run 'grunt' to generate this file.\n" +
                            " */\n",
                    precision: 5
                },
                files: {
                    'css/bolt-old-ie.css': 'sass/app-old-ie.scss',
                    'css/bolt.css': 'sass/app.scss'
                }
            }

        },

        copy: {
            main: {
                // Includes files within path
                files: [{
                    expand: true,
                    flatten: true,
                    src: [
                        'node_modules/font-awesome/fonts/*'
                    ],
                    filter: 'isFile',
                    dest: 'fonts/'
                }]
            }
        },

        concat: {
        },

        cssmin: {
            lib: {
                options: {
                    compatibility: 'ie8',
                    relativeTo: './css/',
                    target: './css/'
                },
                files: {
                    'css/lib.css': [
                        'lib/jquery-ui-1.10.3/jquery-ui.custom.min.css',
                        'lib/magnific-popup-0.9.9/magnific-popup.css',
                        'lib/select2-3.5.1/select2.css',
                        'lib/jquery.fileupload-5.26/jquery.fileupload-ui.css'
                    ]
                }
            }
        },

        uglify: {
            lib: {
                options: {
                    preserveComments: 'some'
                },
                files: [{
                    expand: true,
                    ext: '.min.js',
                    src: [
                        'lib/bootstrap-file-input/bootstrap-file-input.js',
                        'lib/jquery-catchpaste-1.0.0p/jquery-catchpaste.js',
                        'lib/jquery-cookie-1.4.0/jquery-cookie.js',
                        'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.js',
                        'lib/jquery-hotkeys/jquery-hotkeys.js',
                        'lib/jquery-tagcloud/jquery-tagcloud.js',
                        'lib/jquery-watchchanges/jquery-watchchanges.js'
                    ]
                }]
            },
            bootstrap: {
                files: {
                    'lib/bootstrap-sass.generated/bootstrap.min.js': [
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/button.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/transition.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/popover.js'
                    ]
                }
            },
            bolt: {
                options: {
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED JS files!\n" +
                            " * You can edit files in <js/src/*.js> and run 'grunt' to generate this file.\n" +
                            " */",
                    sourceMap: true
                },
                files: {
                    'js/bolt.min.js': [
                        'lib/bolt/console.js',
                        'lib/bolt/fnc-helpers.js',
                        'lib/bolt/activity.js',
                        'lib/bolt/bind-fileupload.js',
                        'lib/bolt/make-uri-slug.js',
                        'lib/bolt/video-embed.js',
                        'lib/bolt/geolocation.js',
                        'lib/bolt/upload-files.js',
                        'lib/bolt/obj-sidebar.js',
                        'lib/bolt/obj-navpopups.js',
                        'lib/bolt/obj-moments.js',
                        'lib/bolt/obj-files.js',
                        'lib/bolt/obj-stack.js',
                        'lib/bolt/obj-folders.js',
                        'lib/bolt/obj-datetime.js',
                        'lib/bolt/extend.js',
                        'lib/bolt/init.js',
                        'lib/bolt/start.js'
                    ]
                }
            }
        },

        jshint: {
            options: {
                browser: true,          // Defines globals exposed by modern browsers
                curly: true,            // Always put curly braces around blocks
                devel: true,            // Defines globals that are usually used for logging/debugging
                immed: true,            // Prohibits the use of immediate function invocations without parentheses
                indent: 4,              // Tab width
                latedef: true,          // Prohibits the use of a variable before it was defined
                maxlen: 120,            // Maximum length of a line
                noarg: true,            // Prohibits the use of arguments.caller and arguments.callee
                nonbsp: true,           // Warns about "non-breaking whitespace" characters
                singleGroups: true,     // Prohibits the use of the grouping operator for single-expression statements
                undef: true,            // Prohibits the use of undeclared variables
                globals: {
                    // Bolt
                    bolt: true,                 // src/console.js
                    FilelistHolder: true,       // src/upload-files.js
                    Files: true,                // src/obj-files.js
                    Folders: true,              // src/obj-folders.js
                    init: true,                 // src/init.js
                    Moments: true,              // src/obj-moments.js
                    Navpopups: true,            // src/obj-navpopups.js
                    Sidebar: true,              // src/obj-sidebar.js
                    Stack: true,                // src/obj-stack.js
                    site: true,                 // src/extend.js/extend.twig
                    baseurl: true,              // src/extend.js/extend.twig
                    // Bolt global functions
                    bindFileUpload: true,       // src/bindfileuploads.js
                    bindGeolocation: true,      // src/geolocation.js
                    bindVideoEmbed: true,       // src/video-embed.js
                    getSelectedItems: true,     // src/fnc-helpers.js
                    makeUri: true,              // src/make-uri-slug.js
                    makeUriAjax: true,          // src/make-uri-slug.js
                    stopMakeUri: true,          // src/make-uri-slug.js
                    updateLatestActivity: true, // src/activity.js
                    validateContent: true,      // src/fnc-helpers.js
                    // Vendor
                    $: true,                    // jQuery
                    _: true,                    // underscore.js
                    Backbone: true,             // backbone.min.js
                    bootbox: true,              // bootbox.min.js
                    CKEDITOR: true,             // ckeditor.js
                    CodeMirror: true,           // ckeditor.js
                    google: true,               // Google
                    jQuery: true,               // jQuery
                    moment: true,               // moment.min.js
                    UAParser: true              // ua-parser.min.js
                }
            },
            src: ['lib/bolt/*.js']
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', ['sass', 'jshint', 'uglify', 'cssmin', 'watch']);

};
<|endoftext|>


<commit_before>var _ = require('lodash');
var Cleave = require('../../components/cleave');

var DRAW_COST = 4000;
var XP_PER_WEAPON_1 = 697.5 / 2;
var XP_PER_WEAPON_2 = 1593.32 / 2;
var XP_PER_WEAPON_3 = 3489.34 / 2;
var FUSION_COST_PER_WEAPON_1 = 500;
var FUSION_COST_PER_WEAPON_2 = 800;
var FUSION_COST_PER_WEAPON_3 = 1300;
var PROBABILITY_DRAW_RANK_1 = 82.25;
var PROBABILITY_DRAW_RANK_2 = 12.5;
var PROBABILITY_DRAW_RANK_3 = 5.25;

var REQUIRED_XP = [
    0,
    379,
    834,
    1385,
    2057,
    2884,
    3910,
    5192,
    6808,
    8861,
    11489,
    14625,
    18388,
    22929,
    28439,
    35162,
    43028,
    52270,
    63176,
    76100,
    91480,
    109259,
    129883,
    153889,
    181928,
    214790,
    252472,
    295807,
    345787,
    403597,
    470657,
    547105,
    634474,
    734575,
    849548,
    981931,
    1132186,
    1303326,
    1498169,
    1719315,
];

var p1 = (PROBABILITY_DRAW_RANK_1 / 100);
var p2 = (PROBABILITY_DRAW_RANK_2 / 100);
var p3 = (PROBABILITY_DRAW_RANK_3 / 100);

var expXp1 = p1 * XP_PER_WEAPON_1;
var expXp2 = p2 * XP_PER_WEAPON_2;
var expXp3 = p3 * XP_PER_WEAPON_3;

module.exports = {
    locales: {
        'ja': {
            'XP CALCULATOR': 'XP計算機',
            'CURRENT WEAPON LEVEL': '現在の武器レベル',
            'MAX WEAPON GRADE': '素材の最大ランク',
            'CASH > LEVEL': '所持金 ⇒  到達レベル',
            'CASH': '所持金',
            'LEVEL': 'レベル',
            'LEVEL > COST': '目標レベル ⇒  費用',
            'TARGET LEVEL': '目標レベル',
            'COST': '費用',
        },
    },
    template: require('./template.html'),
    mounted: function () {
        this.$nextTick(function () {
        });
    },
    data: function () {
        return {
        };
    },
    beforeRouteEnter: function (route, redirect, next) {
        next();
    },
    watch: {
        '$route': function (to, from) {
            if (to.name === 'xp') {
                this.$root.title = 'Afterpulse XP Calculator';
            }
        },
    },
    computed: {
        money: {
            get: function () {
                return this.$store.state.xp.money;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'money', value: value});
            },
        },
        currentLevel: {
            get: function () {
                return this.$store.state.xp.currentLevel;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'currentLevel', value: value});
            },
        },
        targetLevel: {
            get: function () {
                return this.$store.state.xp.targetLevel;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'targetLevel', value: value});
            },
        },
        mixRank: {
            get: function () {
                return this.$store.state.xp.mixRank;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'mixRank', value: value});
            },
        },
        expectedXp: function () {
            var result = 0;
            if (this.mixRank === 1) {
                result = expXp1 / (DRAW_COST + FUSION_COST_PER_WEAPON_1);
            }
            if (this.mixRank === 2) {
                result = (expXp1 + expXp2) / (DRAW_COST + p1 * FUSION_COST_PER_WEAPON_1 + p2 * FUSION_COST_PER_WEAPON_2);
            }
            if (this.mixRank === 3) {
                result = (expXp1 + expXp2 + expXp3) / (DRAW_COST + p1 * FUSION_COST_PER_WEAPON_1 + p2 * FUSION_COST_PER_WEAPON_2 + p3 * FUSION_COST_PER_WEAPON_3);
            }
            return (result * this.money) + 1;
        },
        expectedMoney: function () {
            var result = 0;
            if (this.mixRank === 1) {
                result = (DRAW_COST + FUSION_COST_PER_WEAPON_1) / (p1 * XP_PER_WEAPON_1);
            }
            if (this.mixRank === 2) {
                result = (
                    DRAW_COST +
                    (p1 * FUSION_COST_PER_WEAPON_1) +
                    (p2 * FUSION_COST_PER_WEAPON_2)) /
                    (p1 * XP_PER_WEAPON_1 + p2 * XP_PER_WEAPON_2);
            }
            if (this.mixRank === 3) {
                result = (
                    DRAW_COST +
                    (p1 * FUSION_COST_PER_WEAPON_1) +
                    (p2 * FUSION_COST_PER_WEAPON_2) +
                    (p3 * FUSION_COST_PER_WEAPON_3)) /
                    (p1 * XP_PER_WEAPON_1 + p2 * XP_PER_WEAPON_2 + p3 * XP_PER_WEAPON_3);
            }
            return result;
        },
        levelResult: function () {
            var that = this;
            var currentValue = REQUIRED_XP[this.currentLevel - 1];
            var foundIndex = _.findIndex(REQUIRED_XP, function (value, index) {
                return that.expectedXp <= value - currentValue;
            });
            if (_.sum(REQUIRED_XP) < that.expectedXp) {
                return 40;
            }
            if (foundIndex && 0 < foundIndex) {
                return foundIndex;
            }
            if (that.expectedXp <= _.last(REQUIRED_XP)) {
                return this.currentLevel;
            }
            return 40;
        },
        moneyResult: function () {
            var targetValue = REQUIRED_XP[this.targetLevel - 1];
            var currentValue = REQUIRED_XP[this.currentLevel - 1];

            if (this.targetLevel < this.currentLevel) {
                return 0;
            }
            if (40 < this.targetLevel) {
                return 0;
            }
            return Math.floor((targetValue - currentValue) * this.expectedMoney);
        },
    },
    methods: {
    },
    components: {
        Cleave: Cleave,
    },
};
<commit_msg>Revert ":+1: 強化時の武器1個あたりのXPを半分にする"<commit_after>var _ = require('lodash');
var Cleave = require('../../components/cleave');

var DRAW_COST = 4000;
var XP_PER_WEAPON_1 = 697.5;
var XP_PER_WEAPON_2 = 1593.32;
var XP_PER_WEAPON_3 = 3489.34;
var FUSION_COST_PER_WEAPON_1 = 500;
var FUSION_COST_PER_WEAPON_2 = 800;
var FUSION_COST_PER_WEAPON_3 = 1300;
var PROBABILITY_DRAW_RANK_1 = 82.25;
var PROBABILITY_DRAW_RANK_2 = 12.5;
var PROBABILITY_DRAW_RANK_3 = 5.25;

var REQUIRED_XP = [
    0,
    379,
    834,
    1385,
    2057,
    2884,
    3910,
    5192,
    6808,
    8861,
    11489,
    14625,
    18388,
    22929,
    28439,
    35162,
    43028,
    52270,
    63176,
    76100,
    91480,
    109259,
    129883,
    153889,
    181928,
    214790,
    252472,
    295807,
    345787,
    403597,
    470657,
    547105,
    634474,
    734575,
    849548,
    981931,
    1132186,
    1303326,
    1498169,
    1719315,
];

var p1 = (PROBABILITY_DRAW_RANK_1 / 100);
var p2 = (PROBABILITY_DRAW_RANK_2 / 100);
var p3 = (PROBABILITY_DRAW_RANK_3 / 100);

var expXp1 = p1 * XP_PER_WEAPON_1;
var expXp2 = p2 * XP_PER_WEAPON_2;
var expXp3 = p3 * XP_PER_WEAPON_3;

module.exports = {
    locales: {
        'ja': {
            'XP CALCULATOR': 'XP計算機',
            'CURRENT WEAPON LEVEL': '現在の武器レベル',
            'MAX WEAPON GRADE': '素材の最大ランク',
            'CASH > LEVEL': '所持金 ⇒  到達レベル',
            'CASH': '所持金',
            'LEVEL': 'レベル',
            'LEVEL > COST': '目標レベル ⇒  費用',
            'TARGET LEVEL': '目標レベル',
            'COST': '費用',
        },
    },
    template: require('./template.html'),
    mounted: function () {
        this.$nextTick(function () {
        });
    },
    data: function () {
        return {
        };
    },
    beforeRouteEnter: function (route, redirect, next) {
        next();
    },
    watch: {
        '$route': function (to, from) {
            if (to.name === 'xp') {
                this.$root.title = 'Afterpulse XP Calculator';
            }
        },
    },
    computed: {
        money: {
            get: function () {
                return this.$store.state.xp.money;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'money', value: value});
            },
        },
        currentLevel: {
            get: function () {
                return this.$store.state.xp.currentLevel;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'currentLevel', value: value});
            },
        },
        targetLevel: {
            get: function () {
                return this.$store.state.xp.targetLevel;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'targetLevel', value: value});
            },
        },
        mixRank: {
            get: function () {
                return this.$store.state.xp.mixRank;
            },
            set: function (value) {
                this.$store.dispatch('setXPParams', {key: 'mixRank', value: value});
            },
        },
        expectedXp: function () {
            var result = 0;
            if (this.mixRank === 1) {
                result = expXp1 / (DRAW_COST + FUSION_COST_PER_WEAPON_1);
            }
            if (this.mixRank === 2) {
                result = (expXp1 + expXp2) / (DRAW_COST + p1 * FUSION_COST_PER_WEAPON_1 + p2 * FUSION_COST_PER_WEAPON_2);
            }
            if (this.mixRank === 3) {
                result = (expXp1 + expXp2 + expXp3) / (DRAW_COST + p1 * FUSION_COST_PER_WEAPON_1 + p2 * FUSION_COST_PER_WEAPON_2 + p3 * FUSION_COST_PER_WEAPON_3);
            }
            return (result * this.money) + 1;
        },
        expectedMoney: function () {
            var result = 0;
            if (this.mixRank === 1) {
                result = (DRAW_COST + FUSION_COST_PER_WEAPON_1) / (p1 * XP_PER_WEAPON_1);
            }
            if (this.mixRank === 2) {
                result = (
                    DRAW_COST +
                    (p1 * FUSION_COST_PER_WEAPON_1) +
                    (p2 * FUSION_COST_PER_WEAPON_2)) /
                    (p1 * XP_PER_WEAPON_1 + p2 * XP_PER_WEAPON_2);
            }
            if (this.mixRank === 3) {
                result = (
                    DRAW_COST +
                    (p1 * FUSION_COST_PER_WEAPON_1) +
                    (p2 * FUSION_COST_PER_WEAPON_2) +
                    (p3 * FUSION_COST_PER_WEAPON_3)) /
                    (p1 * XP_PER_WEAPON_1 + p2 * XP_PER_WEAPON_2 + p3 * XP_PER_WEAPON_3);
            }
            return result;
        },
        levelResult: function () {
            var that = this;
            var currentValue = REQUIRED_XP[this.currentLevel - 1];
            var foundIndex = _.findIndex(REQUIRED_XP, function (value, index) {
                return that.expectedXp <= value - currentValue;
            });
            if (_.sum(REQUIRED_XP) < that.expectedXp) {
                return 40;
            }
            if (foundIndex && 0 < foundIndex) {
                return foundIndex;
            }
            if (that.expectedXp <= _.last(REQUIRED_XP)) {
                return this.currentLevel;
            }
            return 40;
        },
        moneyResult: function () {
            var targetValue = REQUIRED_XP[this.targetLevel - 1];
            var currentValue = REQUIRED_XP[this.currentLevel - 1];

            if (this.targetLevel < this.currentLevel) {
                return 0;
            }
            if (40 < this.targetLevel) {
                return 0;
            }
            return Math.floor((targetValue - currentValue) * this.expectedMoney);
        },
    },
    methods: {
    },
    components: {
        Cleave: Cleave,
    },
};
<|endoftext|>


<commit_before>'use strict'

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
    main: ['./app/src/main-process/main'],
    renderer: ['./app/src/ui/index'],
    shared: ['./app/src/shared-process/index']
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, '..', 'out'),
    libraryTarget: 'commonjs2'
  },
  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loaders: ['babel', 'ts'],
        include: path.join(__dirname, 'src')
      },
      {
        test: /\.(jpe?g|png|gif|ico)$/,
        loaders: ['file?name=[path][name].[ext]']
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.ts', '.tsx'],
    packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
  },
  target: 'electron',
  plugins: [
    new HtmlWebpackPlugin({
      'template': path.join(__dirname, 'static', 'index.html'),
      'chunks': ['renderer']
    }),
    new HtmlWebpackPlugin({
      'filename': 'shared.html',
      'chunks': ['shared']
    })
  ],
  externals: function (context, request, callback) {
    try {
      // Attempt to resolve the module via Node
      require.resolve(request)
      callback(null, request)
    } catch (e) {
      // Node couldn't find it, so it must be user-aliased
      callback()
    }
  },
  node: {
    __dirname: false,
    __filename: false
  }
}
<commit_msg>Don't treat CSS as external<commit_after>'use strict'

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
    main: ['./app/src/main-process/main'],
    renderer: ['./app/src/ui/index'],
    shared: ['./app/src/shared-process/index']
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, '..', 'out'),
    libraryTarget: 'commonjs2'
  },
  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loaders: ['babel', 'ts'],
        include: path.join(__dirname, 'src')
      },
      {
        test: /\.(jpe?g|png|gif|ico)$/,
        loaders: ['file?name=[path][name].[ext]']
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.ts', '.tsx'],
    packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
  },
  target: 'electron',
  plugins: [
    new HtmlWebpackPlugin({
      'template': path.join(__dirname, 'static', 'index.html'),
      'chunks': ['renderer']
    }),
    new HtmlWebpackPlugin({
      'filename': 'shared.html',
      'chunks': ['shared']
    })
  ],
  externals: function (context, request, callback) {
    try {
      // Attempt to resolve the module via Node
      require.resolve(request)
      if (request.endsWith('.css')) {
        callback()
      } else {
        callback(null, request)
      }
    } catch (e) {
      // Node couldn't find it, so it must be user-aliased
      callback()
    }
  },
  node: {
    __dirname: false,
    __filename: false
  }
}
<|endoftext|>


<commit_before>const path = require('path');
const ip = require('ip');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {mergeConfig, getLibFile} = require('../utils');

module.exports = (env = {}) => {
  const resolvePath = path.resolve.bind(path, __dirname);
  const myIpAddress = ip.address();
  const appServerPort = 5000;
  const devServerPort = 8080;

  const libFile = getLibFile({
    productionOnly: Boolean(env.production),
    verbose: Boolean(env.verbose),
  });

  if (!libFile) {
    process.exit(1);
  }

  const devConfig = {
    logLevel: 'warn',
    reduxLoggerEnabled: false,
    reduxDevToolsEnabled: false,
  };

  if (!env.production && env.extDevConfig) {
    mergeConfig(devConfig, resolvePath('webpack.dev.js'));
  }

  const productionEntry = [
    '../lib/polyfills.js',
    'whatwg-fetch',
    './src/client/index.js',
  ];

  const developmentEntry = [
    '../lib/polyfills.js',
    '../lib/polyfills-extra.js', // Needed when importing cfxnes directly from its source code, not as a bundled library
    'whatwg-fetch',
    './src/client/index.js',
  ];

  const commonRules = [
    {
      sideEffects: false,
    },
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
    },
    {
      test: /\.(svg|woff|woff2|eot|ttf)(\?\S*)?$/,
      loader: 'file-loader?name=[name].[ext]',
    },
    {
      test: /\.hbs$/,
      loader: 'handlebars-loader',
    },
  ];

  const productionRules = [
    ...commonRules,
    {
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader?importLoaders=1', // =1 means postcss-loader
        'postcss-loader',
      ],
    },
  ];

  const developmentRules = [
    ...commonRules,
    {
      test: /\.(js|jsx)$/,
      loader: 'source-map-loader',
      enforce: 'pre',
    },
    {
      test: /\.css$/,
      use: [
        'style-loader',
        'css-loader?importLoaders=1', // =1 means postcss-loader
        'postcss-loader',
      ],
    },
  ];

  const commonPlugins = [
    new webpack.DefinePlugin({
      __DEVELOPMENT__: JSON.stringify(!env.production),
      __REDUX_LOGGER_ENABLED__: devConfig.reduxLoggerEnabled,
      __REDUX_DEVTOOLS_ENABLED__: devConfig.reduxDevToolsEnabled,
      __LOG_LEVEL__: JSON.stringify(env.production ? 'warn' : devConfig.logLevel),
    }),
    new webpack.IgnorePlugin(/^fs$/), // cfxnes.debug.js contains unused required('fs') call
    new CopyPlugin([
      {from: 'src/client/static'},
    ]),
    new HtmlWebpackPlugin({
      inject: false,
      template: 'src/client/index.hbs',
      templateParameters: {
        production: Boolean(env.production),
      },
    }),
  ];

  const productionPlugins = [
    ...commonPlugins,
    new MiniCssExtractPlugin({filename: 'bundle.css'}),
  ];

  const developmentPlugins = [
    ...commonPlugins,
    new webpack.HotModuleReplacementPlugin(),
  ];

  return {
    mode: env.production ? 'production' : 'development',
    context: __dirname,
    entry: env.production
      ? productionEntry
      : developmentEntry,
    output: {
      path: resolvePath('dist/static'),
      pathinfo: !env.production,
      filename: 'bundle.js',
    },
    module: {
      rules: env.production ? productionRules : developmentRules,
    },
    resolve: {
      extensions: ['.js', '.jsx'],
      alias: {
        cfxnes: libFile,
      },
    },
    plugins: env.production ? productionPlugins : developmentPlugins,
    devtool: env.production ? 'nosources-source-map' : 'eval-source-map',
    watch: !env.production,
    watchOptions: {
      poll: 1000,
    },
    performance: {
      hints: false,
    },
    devServer: {
      compress: true,
      historyApiFallback: true,
      host: '0.0.0.0',
      hot: true,
      inline: true,
      open: true,
      openPage: '',
      port: devServerPort,
      proxy: {
        '/api': `http://${myIpAddress}:${appServerPort}`,
      },
      public: `${myIpAddress}:${devServerPort}`,
      useLocalIp: true,
    },
  };
};
<commit_msg>Enable sideEffects in webpack config<commit_after>const path = require('path');
const ip = require('ip');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {mergeConfig, getLibFile} = require('../utils');

module.exports = (env = {}) => {
  const resolvePath = path.resolve.bind(path, __dirname);
  const myIpAddress = ip.address();
  const appServerPort = 5000;
  const devServerPort = 8080;

  const libFile = getLibFile({
    productionOnly: Boolean(env.production),
    verbose: Boolean(env.verbose),
  });

  if (!libFile) {
    process.exit(1);
  }

  const devConfig = {
    logLevel: 'warn',
    reduxLoggerEnabled: false,
    reduxDevToolsEnabled: false,
  };

  if (!env.production && env.extDevConfig) {
    mergeConfig(devConfig, resolvePath('webpack.dev.js'));
  }

  const productionEntry = [
    '../lib/polyfills.js',
    'whatwg-fetch',
    './src/client/index.js',
  ];

  const developmentEntry = [
    '../lib/polyfills.js',
    '../lib/polyfills-extra.js', // Needed when importing cfxnes directly from its source code, not as a bundled library
    'whatwg-fetch',
    './src/client/index.js',
  ];

  const commonRules = [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
    },
    {
      test: /\.(svg|woff|woff2|eot|ttf)(\?\S*)?$/,
      loader: 'file-loader?name=[name].[ext]',
    },
    {
      test: /\.hbs$/,
      loader: 'handlebars-loader',
    },
  ];

  const productionRules = [
    ...commonRules,
    {
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader?importLoaders=1', // =1 means postcss-loader
        'postcss-loader',
      ],
    },
  ];

  const developmentRules = [
    ...commonRules,
    {
      test: /\.(js|jsx)$/,
      loader: 'source-map-loader',
      enforce: 'pre',
    },
    {
      test: /\.css$/,
      use: [
        'style-loader',
        'css-loader?importLoaders=1', // =1 means postcss-loader
        'postcss-loader',
      ],
    },
  ];

  const commonPlugins = [
    new webpack.DefinePlugin({
      __DEVELOPMENT__: JSON.stringify(!env.production),
      __REDUX_LOGGER_ENABLED__: devConfig.reduxLoggerEnabled,
      __REDUX_DEVTOOLS_ENABLED__: devConfig.reduxDevToolsEnabled,
      __LOG_LEVEL__: JSON.stringify(env.production ? 'warn' : devConfig.logLevel),
    }),
    new webpack.IgnorePlugin(/^fs$/), // cfxnes.debug.js contains unused required('fs') call
    new CopyPlugin([
      {from: 'src/client/static'},
    ]),
    new HtmlWebpackPlugin({
      inject: false,
      template: 'src/client/index.hbs',
      templateParameters: {
        production: Boolean(env.production),
      },
    }),
  ];

  const productionPlugins = [
    ...commonPlugins,
    new MiniCssExtractPlugin({filename: 'bundle.css'}),
  ];

  const developmentPlugins = [
    ...commonPlugins,
    new webpack.HotModuleReplacementPlugin(),
  ];

  return {
    mode: env.production ? 'production' : 'development',
    context: __dirname,
    entry: env.production
      ? productionEntry
      : developmentEntry,
    output: {
      path: resolvePath('dist/static'),
      pathinfo: !env.production,
      filename: 'bundle.js',
    },
    module: {
      rules: env.production ? productionRules : developmentRules,
    },
    resolve: {
      extensions: ['.js', '.jsx'],
      alias: {
        cfxnes: libFile,
      },
    },
    plugins: env.production ? productionPlugins : developmentPlugins,
    devtool: env.production ? 'nosources-source-map' : 'eval-source-map',
    watch: !env.production,
    watchOptions: {
      poll: 1000,
    },
    performance: {
      hints: false,
    },
    devServer: {
      compress: true,
      historyApiFallback: true,
      host: '0.0.0.0',
      hot: true,
      inline: true,
      open: true,
      openPage: '',
      port: devServerPort,
      proxy: {
        '/api': `http://${myIpAddress}:${appServerPort}`,
      },
      public: `${myIpAddress}:${devServerPort}`,
      useLocalIp: true,
    },
  };
};
<|endoftext|>


<commit_before>/**
 * Developer: Stepan Burguchev
 * Date: 6/30/2015
 * Copyright: 2009-2015 Comindware®
 *       All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
 *       The copyright notice above does not evidence any
 *       actual or intended publication of such source code.
 */

/* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */

define([
        'module/lib',
        'core/utils/utilsApi',
        'core/services/UrlService',
        './views/DefaultContentView'
    ],
    function (lib, utilsApi, UrlService, DefaultContentView) {
        'use strict';

        return Marionette.Controller.extend({
            constructor: function (options) {
                utilsApi.helpers.ensureOption(options, 'config');
                this.view = new this.contentView();
                utilsApi.helpers.ensureProperty(this.view, 'moduleRegion');
                this.moduleRegion  = this.view.moduleRegion;
                options.region.show(this.view); // <- this can be moved out to routing services after we get rid of old modules
                Marionette.Controller.prototype.constructor.apply(this, arguments);
            },

            leave: function () {
                if (_.isFunction(this.onLeave)) {
                    return this.onLeave();
                }
                return Promise.resolve(true);
            },

            setLoading: function (isLoading) {
                this.view.setModuleLoading(isLoading);
            },

            contentView: DefaultContentView
        });
    });
<commit_msg>demo page fixes<commit_after>/**
 * Developer: Stepan Burguchev
 * Date: 6/30/2015
 * Copyright: 2009-2015 Comindware®
 *       All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
 *       The copyright notice above does not evidence any
 *       actual or intended publication of such source code.
 */

/* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */

define([
        'module/lib',
        'core/utils/utilsApi',
        'core/services/UrlService',
        './views/DefaultContentView'
    ],
    function (lib, utilsApi, UrlService, DefaultContentView) {
        'use strict';

        return Marionette.Controller.extend({
            constructor: function (options) {
                utilsApi.helpers.ensureOption(options, 'config');
                var contentViewOptions = _.result(this, 'contentViewOptions') || {};
                this.view = new this.contentView(contentViewOptions);
                utilsApi.helpers.ensureProperty(this.view, 'moduleRegion');
                this.moduleRegion  = this.view.moduleRegion;
                options.region.show(this.view); // <- this can be moved out to routing services after we get rid of old modules
                Marionette.Controller.prototype.constructor.apply(this, arguments);
            },

            leave: function () {
                if (_.isFunction(this.onLeave)) {
                    return this.onLeave();
                }
                return Promise.resolve(true);
            },

            setLoading: function (isLoading) {
                this.view.setModuleLoading(isLoading);
            },

            contentView: DefaultContentView,

            contentViewOptions: null
        });
    });
<|endoftext|>