<commit_before>/**
 * Listens for the app launching then creates the window
 *
 * @see http://developer.chrome.com/apps/app.runtime.html
 * @see http://developer.chrome.com/apps/app.window.html
 */

/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* global chrome */

// things to store:
// username/pw, remember me checkbox for: tidepool
// information for individual devices is stored by device ID
// default server
// timezone

var contexts = [ 'page' ];

var contextMenus = [
  {
    type: 'normal',
    id: 'MENUROOT',
    title: 'Server',
    contexts: contexts
  },
  {
    type: 'radio',
    id: 'Local',
    title: 'Local',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Development',
    title: 'Development',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Staging',
    title: 'Staging',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Integration',
    title: 'Integration',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Production',
    title: 'Production',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: true
  }
];

function setServer(window, info) {
  var serverdata = {
    Local: {
      API_URL: 'http://localhost:8009',
      UPLOAD_URL: 'http://localhost:9122',
      DATA_URL: 'http://localhost:8077',
      BLIP_URL: 'http://localhost:3000'
    },
    Development: {
      API_URL: 'https://dev-api.tidepool.org',
      UPLOAD_URL: 'https://dev-uploads.tidepool.org',
      DATA_URL: 'https://dev-api.tidepool.org/dataservices',
      BLIP_URL: 'https://dev-blip.tidepool.org'
    },
    Staging: {
      API_URL: 'https://stg-api.tidepool.org',
      UPLOAD_URL: 'https://stg-uploads.tidepool.org',
      DATA_URL: 'https://stg-api.tidepool.org/dataservices',
      BLIP_URL: 'https://stg-blip.tidepool.org'
    },
    Integration: {
      API_URL: 'https://int-api.tidepool.org',
      UPLOAD_URL: 'https://int-uploads.tidepool.org',
      DATA_URL: 'https://int-api.tidepool.org/dataservices',
      BLIP_URL: 'https://int-blip.tidepool.org'
    },
    Production: {
      API_URL: 'https://api.tidepool.org',
      UPLOAD_URL: 'https://uploads.tidepool.org',
      DATA_URL: 'https://api.tidepool.org/dataservices',
      BLIP_URL: 'https://blip.tidepool.org'
    }
  };

  console.log('will use', info.menuItemId, 'server');
  var serverinfo = serverdata[info.menuItemId];
  window.api.setHosts(serverinfo);
}

chrome.app.runtime.onLaunched.addListener(function(launchData) {
  // launchData.url, if it exists, contains the link clicked on by
  // the user in blip. We could use it for login if we wanted to.
  console.log('launchData: ', launchData);
  var token = null;
  if (launchData.id && launchData.id === 'open_uploader') {
    var pat = /^[^?]+\?(.*)/;
    var query = launchData.url.match(pat)[1];
    if (query) {
      var parms = query.split('&');
      for (var p=0; p<parms.length; ++p) {
        var s = parms[p].split('=');
        console.log(s);
        if (s[0] === 'token') {
          token = s[1];
          break;
        }
      }
    }
    if (token) {
      console.log('got a token ', token);
      // now save the token where we can use it
    }
  }

  // Center window on screen.
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = 650;
  var height = 710;

  chrome.app.window.create('index.html', {
    id: 'tidepoolUniversalUploader',
    innerBounds: {
      width: width,
      height: height,
      left: Math.round((screenWidth-width)/2),
      top: Math.round((screenHeight-height)/2),
      minWidth: width,
      minHeight: height
    }
  }, function(createdWindow) {
    for (var i=0; i<contextMenus.length; ++i) {
      // In version 42 of Chrome, the create call throws an exception when the
      // app is reloaded after being closed (but Chrome itself continues to run).
      // I can't find anything wrong with the code or a way to prevent the
      // exception from occurring.
      // However, catching the exception and ignoring it allows things to
      // proceed, and the app still seems to be working properly -- the menu
      // items still work, etc.
      try {
        chrome.contextMenus.create(contextMenus[i], function()
          {
            var err = chrome.runtime.lastError;
            if (err) {
              console.log('Error creating menu item #', i, ', "', err, '"');
            }
          });
      } catch (exception) {
        // Leaving this here and commented out because it seems to be a bug
        // in Chrome that's causing the exception.
        // console.log('Caught exception in case ', i);
      }
    }

    var menucb = setServer.bind(null, createdWindow.contentWindow);
    chrome.contextMenus.onClicked.addListener(menucb);

    createdWindow.show();
    createdWindow.contentWindow.localSave = function() {};
    createdWindow.contentWindow.localLoad = function() {};
  });
});
<commit_msg>ensure screen width/height is >=0<commit_after>/**
 * Listens for the app launching then creates the window
 *
 * @see http://developer.chrome.com/apps/app.runtime.html
 * @see http://developer.chrome.com/apps/app.window.html
 */

/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* global chrome */

// things to store:
// username/pw, remember me checkbox for: tidepool
// information for individual devices is stored by device ID
// default server
// timezone

var contexts = [ 'page' ];

var contextMenus = [
  {
    type: 'normal',
    id: 'MENUROOT',
    title: 'Server',
    contexts: contexts
  },
  {
    type: 'radio',
    id: 'Local',
    title: 'Local',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Development',
    title: 'Development',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Staging',
    title: 'Staging',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Integration',
    title: 'Integration',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: false
  },
  {
    type: 'radio',
    id: 'Production',
    title: 'Production',
    contexts: contexts,
    parentId: 'MENUROOT',
    checked: true
  }
];

function setServer(window, info) {
  var serverdata = {
    Local: {
      API_URL: 'http://localhost:8009',
      UPLOAD_URL: 'http://localhost:9122',
      DATA_URL: 'http://localhost:8077',
      BLIP_URL: 'http://localhost:3000'
    },
    Development: {
      API_URL: 'https://dev-api.tidepool.org',
      UPLOAD_URL: 'https://dev-uploads.tidepool.org',
      DATA_URL: 'https://dev-api.tidepool.org/dataservices',
      BLIP_URL: 'https://dev-blip.tidepool.org'
    },
    Staging: {
      API_URL: 'https://stg-api.tidepool.org',
      UPLOAD_URL: 'https://stg-uploads.tidepool.org',
      DATA_URL: 'https://stg-api.tidepool.org/dataservices',
      BLIP_URL: 'https://stg-blip.tidepool.org'
    },
    Integration: {
      API_URL: 'https://int-api.tidepool.org',
      UPLOAD_URL: 'https://int-uploads.tidepool.org',
      DATA_URL: 'https://int-api.tidepool.org/dataservices',
      BLIP_URL: 'https://int-blip.tidepool.org'
    },
    Production: {
      API_URL: 'https://api.tidepool.org',
      UPLOAD_URL: 'https://uploads.tidepool.org',
      DATA_URL: 'https://api.tidepool.org/dataservices',
      BLIP_URL: 'https://blip.tidepool.org'
    }
  };

  console.log('will use', info.menuItemId, 'server');
  var serverinfo = serverdata[info.menuItemId];
  window.api.setHosts(serverinfo);
}

chrome.app.runtime.onLaunched.addListener(function(launchData) {
  // launchData.url, if it exists, contains the link clicked on by
  // the user in blip. We could use it for login if we wanted to.
  console.log('launchData: ', launchData);
  var token = null;
  if (launchData.id && launchData.id === 'open_uploader') {
    var pat = /^[^?]+\?(.*)/;
    var query = launchData.url.match(pat)[1];
    if (query) {
      var parms = query.split('&');
      for (var p=0; p<parms.length; ++p) {
        var s = parms[p].split('=');
        console.log(s);
        if (s[0] === 'token') {
          token = s[1];
          break;
        }
      }
    }
    if (token) {
      console.log('got a token ', token);
      // now save the token where we can use it
    }
  }

  // Center window on screen.
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = 650;
  var height = 710;

  chrome.app.window.create('index.html', {
    id: 'tidepoolUniversalUploader',
    innerBounds: {
      width: width,
      height: height,
      left: Math.max(Math.round((screenWidth-width)/2),0) ,
      top: Math.max(Math.round((screenHeight-height)/2),0),
      minWidth: width,
      minHeight: height
    }
  }, function(createdWindow) {
    for (var i=0; i<contextMenus.length; ++i) {
      // In version 42 of Chrome, the create call throws an exception when the
      // app is reloaded after being closed (but Chrome itself continues to run).
      // I can't find anything wrong with the code or a way to prevent the
      // exception from occurring.
      // However, catching the exception and ignoring it allows things to
      // proceed, and the app still seems to be working properly -- the menu
      // items still work, etc.
      try {
        chrome.contextMenus.create(contextMenus[i], function()
          {
            var err = chrome.runtime.lastError;
            if (err) {
              console.log('Error creating menu item #', i, ', "', err, '"');
            }
          });
      } catch (exception) {
        // Leaving this here and commented out because it seems to be a bug
        // in Chrome that's causing the exception.
        // console.log('Caught exception in case ', i);
      }
    }

    var menucb = setServer.bind(null, createdWindow.contentWindow);
    chrome.contextMenus.onClicked.addListener(menucb);

    createdWindow.show();
    createdWindow.contentWindow.localSave = function() {};
    createdWindow.contentWindow.localLoad = function() {};
  });
});
<|endoftext|>


<commit_before><commit_msg>exprimenting with express.static<commit_after><|endoftext|>


<commit_before><commit_msg>disable morgan<commit_after><|endoftext|>


<commit_before>"use strict";

const mongoose = require('mongoose');
const Show = require('../../show');

module.exports = function(scheduleSchema, options) {

    scheduleSchema.add({
        version: Number,
        actual: Boolean
    });

    /**
     * Make a snapshot and save it to local variable.
     */
    scheduleSchema.post('init', function(doc) {
        if (!doc.actual) {
            return;
        }
        doc.snapshot = makeSnapshot(doc);
    });

    /**
     * Increment version if existing snapshot differs from new state.
     * Instruct post-save hook to create a revision if so.
     */
    scheduleSchema.pre('save', function(next) {
        const snapshot = this.snapshot;
        const snapshotIsEmpty = !snapshot || (snapshot.version === 1 && !snapshot.shows.length);
        if (snapshotIsEmpty) {
            return next();
        }
        const noChanges = scheduleEqualsToSnapshot(this, snapshot);
        if (noChanges) {
            return next();
        }
        this.createRevision = true;
        this.version++;
        next();
    });

    /**
     * Create a revision if snapshot is available and this.createRevision set to true.
     */
    scheduleSchema.post('save', function(doc) {
        if (!this.snapshot || !this.createRevision) {
            return;
        }
        this.constructor.createRevision(this.snapshot, function (err, revision) { /* nothing to do */ });
        delete this.createRevision;
        this.snapshot = makeSnapshot(doc);
    });

    /**
     * Find actual schedule by given month and year.
     *
     * @param {Number} month
     * @param {Number} year
     * @param {Function} callback
     * @return {Query|*}
     */
    scheduleSchema.statics.findByMonthAndYear = function(month, year, callback) {
        return this.findOne({ month: month, year: year, actual: true }, callback);
    };

    /**
     * Create actual schedule for given month and year.
     *
     * @param {Number} month
     * @param {Number} year
     *
     * @return {Object}
     */
    scheduleSchema.statics.createForMonthAndYear = function(month, year) {
        let schedule = parentCreateForMonthAndYear.call(this, month, year);
        schedule.version = 1;
        schedule.actual = true;
        return schedule;
    };
    const parentCreateForMonthAndYear = scheduleSchema.statics.createForMonthAndYear;

    /**
     * Update 'updated' field with current date if actual is true.
     */
    scheduleSchema.methods.updateUpdated = function() {
        if (this.actual) {
            this.updated = new Date();
        }
    };

    /**
     * Make plain object snapshot from the schedule.
     * Remove fields that are not relevant.
     *
     * @param {Object} schedule
     *
     * @return {Object}
     */
    function makeSnapshot(schedule) {
        return schedule.toObject({
            depopulate: true,
            virtuals: false,
            getters: false,
            versionKey: false,
            transform: function (doc, ret, options) {
                delete ret._id;
                if (ret.theatre) {
                    ret.theatre = String(ret.theatre);
                }
                if (ret.scene) {
                    ret.scene = String(ret.scene);
                }
                if (ret.play) {
                    ret.play = String(ret.play);
                }
            }
        });
    }

    /**
     * Compare given schedule with the snapshot.
     * Return TRUE if they are equal, FALSE otherwise.
     *
     * @param {Object} schedule
     * @param {Object} snapshot
     *
     * @return {Boolean}
     */
    function scheduleEqualsToSnapshot(schedule, snapshot) {
        const currentSnapshot = this.makeSnapshot(schedule);
        if (!snapshot.shows || !currentSnapshot.shows) {
            return false;
        }

        if (snapshot.shows.length !== currentSnapshot.shows.length) {
            return false;
        }

        const allShowsEqual = snapshot.shows.reduce(function (result, show) {
            if (!result) {
                return false;
            }
            const sameShowIndex = currentSnapshot.shows.findIndex(currentShow => Show.sameShows(show, currentShow));
            return sameShowIndex >= 0;
        }, true);
        if (!allShowsEqual) {
            return false;
        }

        return true;
    }

    /**
     * Create a non-actual schedule revision from a snapshot.
     *
     * @param {Object} snapshot
     * @param {Function} callback
     */
    function createRevision(snapshot, callback) {
        const Schedule = mongoose.model('Schedule');
        delete snapshot._id;
        snapshot.actual = false;
        let revision = new Schedule(snapshot);
        revision.save(function (err) {
            if (err) return callback(err);
            callback(null, revision);
        });
    }
};<commit_msg>Replace undefined this with schedule in versioned schedule plugin.<commit_after>"use strict";

const mongoose = require('mongoose');
const Show = require('../../show');

module.exports = function(scheduleSchema, options) {

    scheduleSchema.add({
        version: Number,
        actual: Boolean
    });

    /**
     * Make a snapshot and save it to local variable.
     */
    scheduleSchema.post('init', function(doc) {
        if (!doc.actual) {
            return;
        }
        doc.snapshot = makeSnapshot(doc);
    });

    /**
     * Increment version if existing snapshot differs from new state.
     * Instruct post-save hook to create a revision if so.
     */
    scheduleSchema.pre('save', function(next) {
        const snapshot = this.snapshot;
        const snapshotIsEmpty = !snapshot || (snapshot.version === 1 && !snapshot.shows.length);
        if (snapshotIsEmpty) {
            return next();
        }
        const noChanges = scheduleEqualsToSnapshot(this, snapshot);
        if (noChanges) {
            return next();
        }
        this.createRevision = true;
        this.version++;
        next();
    });

    /**
     * Create a revision if snapshot is available and this.createRevision set to true.
     */
    scheduleSchema.post('save', function(doc) {
        if (!this.snapshot || !this.createRevision) {
            return;
        }
        this.constructor.createRevision(this.snapshot, function (err, revision) { /* nothing to do */ });
        delete this.createRevision;
        this.snapshot = makeSnapshot(doc);
    });

    /**
     * Find actual schedule by given month and year.
     *
     * @param {Number} month
     * @param {Number} year
     * @param {Function} callback
     * @return {Query|*}
     */
    scheduleSchema.statics.findByMonthAndYear = function(month, year, callback) {
        return this.findOne({ month: month, year: year, actual: true }, callback);
    };

    /**
     * Create actual schedule for given month and year.
     *
     * @param {Number} month
     * @param {Number} year
     *
     * @return {Object}
     */
    scheduleSchema.statics.createForMonthAndYear = function(month, year) {
        let schedule = parentCreateForMonthAndYear.call(this, month, year);
        schedule.version = 1;
        schedule.actual = true;
        return schedule;
    };
    const parentCreateForMonthAndYear = scheduleSchema.statics.createForMonthAndYear;

    /**
     * Update 'updated' field with current date if actual is true.
     */
    scheduleSchema.methods.updateUpdated = function() {
        if (this.actual) {
            this.updated = new Date();
        }
    };

    /**
     * Make plain object snapshot from the schedule.
     * Remove fields that are not relevant.
     *
     * @param {Object} schedule
     *
     * @return {Object}
     */
    function makeSnapshot(schedule) {
        return schedule.toObject({
            depopulate: true,
            virtuals: false,
            getters: false,
            versionKey: false,
            transform: function (doc, ret, options) {
                delete ret._id;
                if (ret.theatre) {
                    ret.theatre = String(ret.theatre);
                }
                if (ret.scene) {
                    ret.scene = String(ret.scene);
                }
                if (ret.play) {
                    ret.play = String(ret.play);
                }
            }
        });
    }

    /**
     * Compare given schedule with the snapshot.
     * Return TRUE if they are equal, FALSE otherwise.
     *
     * @param {Object} schedule
     * @param {Object} snapshot
     *
     * @return {Boolean}
     */
    function scheduleEqualsToSnapshot(schedule, snapshot) {
        const currentSnapshot = schedule.makeSnapshot(schedule);
        if (!snapshot.shows || !currentSnapshot.shows) {
            return false;
        }

        if (snapshot.shows.length !== currentSnapshot.shows.length) {
            return false;
        }

        const allShowsEqual = snapshot.shows.reduce(function (result, show) {
            if (!result) {
                return false;
            }
            const sameShowIndex = currentSnapshot.shows.findIndex(currentShow => Show.sameShows(show, currentShow));
            return sameShowIndex >= 0;
        }, true);
        if (!allShowsEqual) {
            return false;
        }

        return true;
    }

    /**
     * Create a non-actual schedule revision from a snapshot.
     *
     * @param {Object} snapshot
     * @param {Function} callback
     */
    function createRevision(snapshot, callback) {
        const Schedule = mongoose.model('Schedule');
        delete snapshot._id;
        snapshot.actual = false;
        let revision = new Schedule(snapshot);
        revision.save(function (err) {
            if (err) return callback(err);
            callback(null, revision);
        });
    }
};<|endoftext|>


<commit_before>const utils = require('../utils');
const fsm = require('./fsm');
const scope = require('./scope');

class WordTokenizer {
   process(text) {
      let output = [];
      let new_word = true;
      text.split('').forEach((ch) => {
         if (utils.common_stops.indexOf(ch) < 0) {
            if (new_word) {
               output.push(ch);
               new_word = false;
            } else {
               output.push(output.pop() + ch);
            }
         } else {
            output.push(ch);
            new_word = true;
         }
      });
      return output.map((x) => {
         return { token: x, tag: null };
      });
   }
}

class SymbolTokenizer {
   // merge like 'a' '_' 'b' => 'a_b'
   constructor(connectors) {
      this.connectors = connectors || ['_'];
   }

   process(input) {
      let output = [];
      let in_word = false;
      input.forEach((x) => {
         if (!x.tag && (utils.contains(this.connectors, x.token) || !utils.contains(utils.common_stops, x.token))) {
            if (in_word) {
               utils.last(output).token += x.token;
            } else {
               in_word = true;
               output.push({ token: x.token, tag: x.tag });
            }
         } else {
            in_word = false;
            output.push({ token: x.token, tag: x.tag });
         }
      });
      return output;
   }
}

class CTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.CPrecompileScope().process(tokens);
      tokens = new scope.CScope().process(tokens);
      return tokens;
   }
}

class ObjectiveCTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      // tokens = new scope.CPrecompileScope().process(tokens);
      tokens = new scope.ObjectiveCScope().process(tokens);
      return tokens;
   }
}

class GoTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"', '`']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.GoScope().process(tokens);
      return tokens;
   }
}

const i_decorator_java = require('./decorator/java');
class JavaTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.JavaScope().process(tokens);
      let info = i_decorator_java.decorate(tokens);
      tokens.push({
         tag: utils.TAG_COMMENT,
         token: '',
         info: info
      });
      return tokens;
   }
}

class CsharpTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('csharp_raw_string', '@"'.split(''), '"', true, utils.TAG_STRING).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true),
         new fsm.FeatureInvisible(
            [
               ['#', 'region'], ['#', 'endregion'], ['#', 'define'], ['#', 'if'], ['#', 'else'],
               ['#', 'elif'], ['#', 'endif'], ['#', 'line'], ['#', 'error'], ['#', 'warning'], ['#', 'undef']
            ], [['\n'], ['\r']]
         )
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      // declare symbol with @name -> (usage) like @if -> (@if), @a -> (a, @a)
      tokens = new SymbolTokenizer(['_', '@', '#']).process(tokens);
      // csharp use [] for attribute (annotation), e.g. [Condition("DEBUG")]
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.CsharpScope().process(tokens);
      return tokens;
   }
}

class JavaScriptTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      new fsm.FeatureCommonString(['/']).merge_feature_as_regex(this.parser, ['return'], (x, env) => {
         // avoid ambigous with /*  */ and //
         let ch = env.input[env.input_i+1];
         if (ch && ch.token === '/') return false;
         if (ch && ch.token === '*') return false;
         return true;
      });
      this.features = [
         new fsm.FeatureCommonString(['\'', '"', '`']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer(['_', '$']).process(tokens);
      console.log(JSON.stringify(tokens, null, 3));
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.JavaScriptScope().process(tokens);
      return tokens;
   }
}

class PythonTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('python_style_line_comment', '#', '\n', false).set_flag_n_eq_r()
      ];
      this.features[0].merge_feature_as_python_doc_to(this.parser);
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.PythonLambdaScope().process(tokens);
      tokens = new scope.PythonScope().process(tokens);
      return tokens;
   }
}

const i_decorator_ruby = require('./decorator/ruby');
class RubyTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      new fsm.FeatureCommonString(['\'', '"', '`']).merge_feature_as_ruby_expandable_string_to(this.parser);
      new fsm.FeatureCommonString(['/']).merge_feature_as_regex(
         this.parser, ['return', 'if', 'while', 'until', 'unless', 'while', 'else', 'elsif']
      );
      this.features = [
         new fsm.FeatureCommonComment('ruby_style_line_comment', '#', '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureRubyHereDocString(),
         new fsm.FeatureRubyPercentString(),
         new fsm.FeatureDolarSign(),
         new fsm.FeatureCommonComment('ruby_multiline_comment', ['=', 'begin'], ['\n', '=', 'end'], true).set_flag_n_eq_r(),
         new fsm.FeatureRubyENDDoc()
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer(['_', '@']).process(tokens);
      tokens = new scope.RubyScope().process(tokens);
      let info = i_decorator_ruby.decorate(tokens);
      tokens.push({
         tag: utils.TAG_COMMENT,
         token: '',
         info: info
      });
      return tokens;
   }
}

module.exports = {
   WordTokenizer,
   SymbolTokenizer,
   CTokenizer,
   ObjectiveCTokenizer,
   JavaTokenizer,
   CsharpTokenizer,
   GoTokenizer,
   PythonTokenizer,
   JavaScriptTokenizer,
   RubyTokenizer
};<commit_msg>minor fix: do not print info in lib function<commit_after>const utils = require('../utils');
const fsm = require('./fsm');
const scope = require('./scope');

class WordTokenizer {
   process(text) {
      let output = [];
      let new_word = true;
      text.split('').forEach((ch) => {
         if (utils.common_stops.indexOf(ch) < 0) {
            if (new_word) {
               output.push(ch);
               new_word = false;
            } else {
               output.push(output.pop() + ch);
            }
         } else {
            output.push(ch);
            new_word = true;
         }
      });
      return output.map((x) => {
         return { token: x, tag: null };
      });
   }
}

class SymbolTokenizer {
   // merge like 'a' '_' 'b' => 'a_b'
   constructor(connectors) {
      this.connectors = connectors || ['_'];
   }

   process(input) {
      let output = [];
      let in_word = false;
      input.forEach((x) => {
         if (!x.tag && (utils.contains(this.connectors, x.token) || !utils.contains(utils.common_stops, x.token))) {
            if (in_word) {
               utils.last(output).token += x.token;
            } else {
               in_word = true;
               output.push({ token: x.token, tag: x.tag });
            }
         } else {
            in_word = false;
            output.push({ token: x.token, tag: x.tag });
         }
      });
      return output;
   }
}

class CTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.CPrecompileScope().process(tokens);
      tokens = new scope.CScope().process(tokens);
      return tokens;
   }
}

class ObjectiveCTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      // tokens = new scope.CPrecompileScope().process(tokens);
      tokens = new scope.ObjectiveCScope().process(tokens);
      return tokens;
   }
}

class GoTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"', '`']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.GoScope().process(tokens);
      return tokens;
   }
}

const i_decorator_java = require('./decorator/java');
class JavaTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.JavaScope().process(tokens);
      let info = i_decorator_java.decorate(tokens);
      tokens.push({
         tag: utils.TAG_COMMENT,
         token: '',
         info: info
      });
      return tokens;
   }
}

class CsharpTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('csharp_raw_string', '@"'.split(''), '"', true, utils.TAG_STRING).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true),
         new fsm.FeatureInvisible(
            [
               ['#', 'region'], ['#', 'endregion'], ['#', 'define'], ['#', 'if'], ['#', 'else'],
               ['#', 'elif'], ['#', 'endif'], ['#', 'line'], ['#', 'error'], ['#', 'warning'], ['#', 'undef']
            ], [['\n'], ['\r']]
         )
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      // declare symbol with @name -> (usage) like @if -> (@if), @a -> (a, @a)
      tokens = new SymbolTokenizer(['_', '@', '#']).process(tokens);
      // csharp use [] for attribute (annotation), e.g. [Condition("DEBUG")]
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.CsharpScope().process(tokens);
      return tokens;
   }
}

class JavaScriptTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      new fsm.FeatureCommonString(['/']).merge_feature_as_regex(this.parser, ['return'], (x, env) => {
         // avoid ambigous with /*  */ and //
         let ch = env.input[env.input_i+1];
         if (ch && ch.token === '/') return false;
         if (ch && ch.token === '*') return false;
         return true;
      });
      this.features = [
         new fsm.FeatureCommonString(['\'', '"', '`']),
         new fsm.FeatureCommonComment('c_style_line_comment', '//'.split(''), '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureCommonComment('c_style_multiline_comment', '/*'.split(''), '*/'.split(''), true)
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer(['_', '$']).process(tokens);
      tokens = new scope.BracketScope().process(tokens);
      tokens = new scope.JavaScriptScope().process(tokens);
      return tokens;
   }
}

class PythonTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      this.features = [
         new fsm.FeatureCommonString(['\'', '"']),
         new fsm.FeatureCommonComment('python_style_line_comment', '#', '\n', false).set_flag_n_eq_r()
      ];
      this.features[0].merge_feature_as_python_doc_to(this.parser);
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer().process(tokens);
      tokens = new scope.PythonLambdaScope().process(tokens);
      tokens = new scope.PythonScope().process(tokens);
      return tokens;
   }
}

const i_decorator_ruby = require('./decorator/ruby');
class RubyTokenizer {
   constructor() {
      this.parser = new fsm.FeatureRoot();
      new fsm.FeatureCommonString(['\'', '"', '`']).merge_feature_as_ruby_expandable_string_to(this.parser);
      new fsm.FeatureCommonString(['/']).merge_feature_as_regex(
         this.parser, ['return', 'if', 'while', 'until', 'unless', 'while', 'else', 'elsif']
      );
      this.features = [
         new fsm.FeatureCommonComment('ruby_style_line_comment', '#', '\n', false).set_flag_n_eq_r(),
         new fsm.FeatureRubyHereDocString(),
         new fsm.FeatureRubyPercentString(),
         new fsm.FeatureDolarSign(),
         new fsm.FeatureCommonComment('ruby_multiline_comment', ['=', 'begin'], ['\n', '=', 'end'], true).set_flag_n_eq_r(),
         new fsm.FeatureRubyENDDoc()
      ];
      this.features.forEach((f) => {
         f.merge_feature_to(this.parser);
      });
   }

   process(text) {
      let input = new WordTokenizer().process(text);
      let tokens = this.parser.process(input);
      tokens = new SymbolTokenizer(['_', '@']).process(tokens);
      tokens = new scope.RubyScope().process(tokens);
      let info = i_decorator_ruby.decorate(tokens);
      tokens.push({
         tag: utils.TAG_COMMENT,
         token: '',
         info: info
      });
      return tokens;
   }
}

module.exports = {
   WordTokenizer,
   SymbolTokenizer,
   CTokenizer,
   ObjectiveCTokenizer,
   JavaTokenizer,
   CsharpTokenizer,
   GoTokenizer,
   PythonTokenizer,
   JavaScriptTokenizer,
   RubyTokenizer
};<|endoftext|>


<commit_before>const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 1170, height: 770, frame: false})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  console.log(event);
  console.log(error);
  event.preventDefault()
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<commit_msg>SSL errors<commit_after>const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 1170, height: 770, frame: false})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

var ignoredDomains[]

app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  if (true) {
    // Verification logic.
    event.preventDefault()
    callback(true)
  } else {
    callback(false)
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<|endoftext|>


<commit_before><commit_msg>Update formats.js<commit_after><|endoftext|>


<commit_before>var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

require('./menu.js')(app)

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // if (process.platform != 'darwin')
  app.quit();
});

// Functions for Spawning our Cousin Processes
var sys = require('sys')
var spawn = require('child_process').spawn;
function logSpawn(spawn, name) {
  spawn.stdout.on('data', function (data) {
    data = data + ""
    data = data.replace(/(\r\n|\n|\r)$/gm,"");
    console.log('[' + name + '] ' + data);
  });
  spawn.stderr.on('data', function (data) {
    data = data + ""
    data = data.replace(/(\r\n|\n|\r)$/gm,"");
    console.log('[' + name + '] ERROR: ' + data);
  });
  spawn.on('close', function (code) {
    data = data + ""
    data = data.replace(/(\r\n|\n|\r)$/gm,"");
    console.log('[' + name + '] Exited with Code ' + code);
  });
}

// app.commandLine.appendSwitch("host-rules", "MAP * 127.0.0.1");

var debug = true;
var go = {};

app.on('will-finish-launching', function() {
  // Launch Go Server
  if(debug) {
    go = spawn("go", ["run", __dirname + "/go/src/melange/server/server.go"], {
      env: {
        "GOPATH": __dirname + '/go',
        "GOROOT": process.env["GOROOT"],
        "PATH": process.env["PATH"],
        "CWD": process.cwd,
        "MLGBASE": __dirname,
      },
    });
    logSpawn(go, "PLUGIN");
  } else {
      go = spawn("server/bin/melange");
      logSpawn(go, "PLUGIN");
  }
});

global["__dirname"] = __dirname

// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    "width": 800,
    "height": 600,
    "title": "Melange",
    "frame": false,
    "min-width": 769,
    "min-height": 600,
  });

  // and load the index.html of the app.
  // mainWindow.loadUrl('http://app.melange.127.0.0.1.xip.io:9001/Index.html#startup');
  mainWindow.loadUrl("file://" + __dirname + "/loading.html");

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });

  mainWindow.focus();
});

app.on('will-quit', function() {
  console.log("Will Quit Fired");
  go.kill('SIGKILL')
});
<commit_msg>Fix Accidental Error in Main.js<commit_after>var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

require('./menu.js')(app)

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // if (process.platform != 'darwin')
  app.quit();
});

// Functions for Spawning our Cousin Processes
var sys = require('sys')
var spawn = require('child_process').spawn;
function logSpawn(spawn, name) {
  spawn.stdout.on('data', function (data) {
    data = data + ""
    data = data.replace(/(\r\n|\n|\r)$/gm,"");
    console.log('[' + name + '] ' + data);
  });
  spawn.stderr.on('data', function (data) {
    data = data + ""
    data = data.replace(/(\r\n|\n|\r)$/gm,"");
    console.log('[' + name + '] ERROR: ' + data);
  });
  spawn.on('close', function (code) {
    console.log('[' + name + '] Exited with Code ' + code);
  });
}

// app.commandLine.appendSwitch("host-rules", "MAP * 127.0.0.1");

var debug = true;
var go = {};

app.on('will-finish-launching', function() {
  // Launch Go Server
  if(debug) {
    go = spawn("go", ["run", __dirname + "/go/src/melange/server/server.go"], {
      env: {
        "GOPATH": __dirname + '/go',
        "GOROOT": process.env["GOROOT"],
        "PATH": process.env["PATH"],
        "CWD": process.cwd,
        "MLGBASE": __dirname,
      },
    });
    logSpawn(go, "PLUGIN");
  } else {
      go = spawn("server/bin/melange");
      logSpawn(go, "PLUGIN");
  }
});

global["__dirname"] = __dirname

// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    "width": 800,
    "height": 600,
    "title": "Melange",
    "frame": false,
    "min-width": 769,
    "min-height": 600,
  });

  // and load the index.html of the app.
  // mainWindow.loadUrl('http://app.melange.127.0.0.1.xip.io:9001/Index.html#startup');
  mainWindow.loadUrl("file://" + __dirname + "/loading.html");

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });

  mainWindow.focus();
});

app.on('will-quit', function() {
  console.log("Will Quit Fired");
  go.kill('SIGKILL')
});
<|endoftext|>


<commit_before>import React from 'react'
import FilterMenu from './FilterMenu'
import Button from './Button'
import FormDialog from './FormDialog'
import FieldRenderer from './forms/FieldRenderer'
import { connect } from 'react-redux'
import { getFileMetadata, directUpload } from '../shared/fileUploader'
import graphql from '../graphql/client'
import { CREATE_DIRECT_UPLOAD, IMPORT_CONTACTS } from '../graphql/mutations'
import { successMessage } from '../actions/status_messages'

import serialize from 'form-serialize'

function optionsForFilter () {
  const options = [
    /*{
      title: 'Create User',
      description: 'Created user',
      // icon: <ArchiveIcon/>,
      id: 'create-user',
      state: 'create-user'
    },
    {
      title: 'Create Lead',
      description: 'Adds a lead',
      // icon: <BlockIcon/>,
      id: 'create-lead',
      state: 'create-lead'
    },*/

    {
      title: 'Import CSV',
      description: 'Imports CSV',
      // icon: <UnsubscribeIcon/>,
      id: 'import-csv',
      state: 'import-csv'
    }
  ]

  return options
}

function toggleButton (clickHandler) {
  return (

      <Button
        onClick={clickHandler}>
        Create Users & Leads
      </Button>

  )
}

function ContactManager ({ app, current_user, dispatch }) {
  const [open, setOpen] = React.useState(null)
  const [selectedItem, setSelectedItem] = React.useState(null)
  const [csv, setCSV] = React.useState(null)

  const [enableForm, setEnableForm] = React.useState(null)

  const formRef = React.useRef()

  function formDefinitions () {
    return [

      {
        id: 'import-user',
        name: 'import_type',
        type: 'radio',
        label: 'import user',
        value: 'user'
      },

      {
        id: 'import-lead',
        name: 'import_type',
        type: 'radio',
        label: 'import lead',
        value: 'lead'
      },

      {
        name: 'csv',
        type: 'upload',
        accept: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        handler: (file) => uploadHandler(file, 'csv'),
        grid: { xs: 'w-full', sm: 'w-1/3' }
      }
    ]
  };

  function formDefinitionsForUser () {
    return [
      {
        name: 'activeMessenger',
        label: I18n.t('definitions.settings.active_messenger.label'),
        hint: I18n.t('definitions.settings.active_messenger.hint'),
        type: 'bool',
        grid: { xs: 'w-full', sm: 'w-full' }
      },

      {
        name: 'enableArticlesOnWidget',
        label: I18n.t('definitions.settings.enable_articles.label'),
        hint: I18n.t('definitions.settings.enable_articles.hint'),
        type: 'bool',
        grid: { xs: 'w-full', sm: 'w-full' }
      }
    ]
  }

  function submitHandler (e) {
    console.log('sends:;', enableForm)

    graphql(IMPORT_CONTACTS, {
      appKey: app.key,
      appParams: { ...enableForm, email: current_user.email }
    }, {
      success: (data) => {
        setSelectedItem(null)
        dispatch(
          successMessage(
            'Processing file import, you will be notified the status soon'
          )
        )
      },
      error: () => {}
    })
  }

  function handleCreateForm (e) {
    switch (e.state) {
      case 'import-csv':
        setSelectedItem(e.state)
        break
      default:
        break
    }
  }

  function closeHandler () {
    setSelectedItem(null)
  }

  function enableSubmit (data) {
    setEnableForm(data)
  }

  function renderForm () {
    switch (selectedItem) {
      case 'import-csv':
        return <CsvUploader enableSubmit={enableSubmit}/>
      default:
        break
    }
  }

  function renderFormFor (definitions) {
    return definitions.map((field, i) => {
      return (
        <div
          key={`field-${field.name}-${i}`}
          // className={`${gridClasses(field)} py-2 pr-2`}
          {...field.gridProps}
        >
          <FieldRenderer
            {...field}
            // namespace={'doorkeeper_application'}
            data={field}
            props={{
              data: {} // data
            }}
            errors={{}}
            // errors={errors}
          />

      )
    })
  }

  return (

      <FilterMenu
        options={optionsForFilter()}
        value={null}
        filterHandler={(e) => handleCreateForm(e)}
        triggerButton={toggleButton}
        position={'right'}
      />

      {selectedItem && (
        <FormDialog
          open={selectedItem}
          handleClose={closeHandler}
          titleContent={'Import contacts'}
          formComponent={
            renderForm()
          }
          dialogButtons={
            <React.Fragment>
              {enableForm &&
								<Button
								  onClick={submitHandler}
								  className="ml-2"
								  variant="success">
								  {I18n.t('common.submit')}
								</Button>
              }
              <Button
                onClick={() => setSelectedItem(null)}
                variant="outlined">
                {I18n.t('common.cancel')}
              </Button>
            </React.Fragment>
          }
        ></FormDialog>
      )}

  )
}

function CsvUploader ({ handleSubmit, enableSubmit }) {
  const formRef = React.useRef()

  function uploadHandler (file, kind) {
    getFileMetadata(file).then((input) => {
      graphql(CREATE_DIRECT_UPLOAD, input, {
        success: (data) => {
          const {
            signedBlobId,
            headers,
            url,
            serviceUrl
          } = data.createDirectUpload.directUpload

          directUpload(url, JSON.parse(headers), file).then(() => {
            // setFile({ signedBlobId })
            const data = serialize(formRef.current, { hash: true, empty: true })
            data.file = signedBlobId
            submitHandler(data)
          })
        },
        error: (error) => {
          console.log('error on signing blob', error)
        }
      })
    })
  };

  function submitHandler (data) {
    enableSubmit(data)
  }

  return

    <form
      name="create-repo"
      onSubmit={
        (d) => console.log(d)
        // updateApp
      }
      ref={formRef}
    >

        You can upload a csv or excel file in order to import contacts

        <fieldset className="mt-6">
          <legend className="text-base font-medium text-gray-900">
          Import Type
          </legend>

					Choose what kind of contacts you will import

              <input id="leads"
                name="contact_type"
                type="radio"
                value="leads"
                className="form-radio h-4 w-4 text-indigo-600 transition duration-150 ease-in-out"
              />

                Leads

              <input id="users"
                name="contact_type"
                type="radio"
                value={'users'}
                className="form-radio h-4 w-4 text-indigo-600 transition duration-150 ease-in-out"
              />

                Users

            <FileUpload onChange={(file) => uploadHandler(file, 'csv')}/>

        </fieldset>

    </form>

}

function FileUpload ({ onChange }) {
  return

      <svg className="w-8 h-8" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
        <path d="M16.88 9.1A4 4 0 0 1 16 17H5a5 5 0 0 1-1-9.9V7a3 3 0 0 1 4.52-2.59A4.98 4.98 0 0 1 17 8c0 .38-.04.74-.12 1.1zM11 11h3l-4-4-4 4h3v3h2v-3z" />
      </svg>
      Select a file
      <input
        type='file'
        className="hidden"
        onChange={(e) => onChange(e.currentTarget.files[0])}
        accept={'.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'}
      />

}

function mapStateToProps (state) {
  const { app, current_user } = state
  return {
    app,
    current_user
  }
}

export default connect(mapStateToProps)(ContactManager)
<commit_msg>set uploader progress<commit_after>import React from 'react'
import FilterMenu from './FilterMenu'
import Button from './Button'
import FormDialog from './FormDialog'
import Progress from './Progress'

import FieldRenderer from './forms/FieldRenderer'
import { connect } from 'react-redux'
import { getFileMetadata, directUpload } from '../shared/fileUploader'
import graphql from '../graphql/client'
import { CREATE_DIRECT_UPLOAD, IMPORT_CONTACTS } from '../graphql/mutations'
import { successMessage } from '../actions/status_messages'

import serialize from 'form-serialize'

function optionsForFilter () {
  const options = [
    /*{
      title: 'Create User',
      description: 'Created user',
      // icon: <ArchiveIcon/>,
      id: 'create-user',
      state: 'create-user'
    },
    {
      title: 'Create Lead',
      description: 'Adds a lead',
      // icon: <BlockIcon/>,
      id: 'create-lead',
      state: 'create-lead'
    },*/

    {
      title: 'Import CSV',
      description: 'Imports CSV',
      // icon: <UnsubscribeIcon/>,
      id: 'import-csv',
      state: 'import-csv'
    }
  ]

  return options
}

function toggleButton (clickHandler) {
  return (

      <Button
        onClick={clickHandler}>
        Create Users & Leads
      </Button>

  )
}

function ContactManager ({ app, current_user, dispatch }) {
  const [open, setOpen] = React.useState(null)
  const [selectedItem, setSelectedItem] = React.useState(null)
  const [csv, setCSV] = React.useState(null)

  const [enableForm, setEnableForm] = React.useState(null)

  const formRef = React.useRef()

  function formDefinitions () {
    return [

      {
        id: 'import-user',
        name: 'import_type',
        type: 'radio',
        label: 'import user',
        value: 'user'
      },

      {
        id: 'import-lead',
        name: 'import_type',
        type: 'radio',
        label: 'import lead',
        value: 'lead'
      },

      {
        name: 'csv',
        type: 'upload',
        accept: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        handler: (file) => uploadHandler(file, 'csv'),
        grid: { xs: 'w-full', sm: 'w-1/3' }
      }
    ]
  };

  function formDefinitionsForUser () {
    return [
      {
        name: 'activeMessenger',
        label: I18n.t('definitions.settings.active_messenger.label'),
        hint: I18n.t('definitions.settings.active_messenger.hint'),
        type: 'bool',
        grid: { xs: 'w-full', sm: 'w-full' }
      },

      {
        name: 'enableArticlesOnWidget',
        label: I18n.t('definitions.settings.enable_articles.label'),
        hint: I18n.t('definitions.settings.enable_articles.hint'),
        type: 'bool',
        grid: { xs: 'w-full', sm: 'w-full' }
      }
    ]
  }

  function submitHandler (e) {
    console.log('sends:;', enableForm)

    graphql(IMPORT_CONTACTS, {
      appKey: app.key,
      appParams: { ...enableForm, email: current_user.email }
    }, {
      success: (data) => {
        setSelectedItem(null)
        dispatch(
          successMessage(
            'Processing file import, you will be notified the status soon'
          )
        )
      },
      error: () => {}
    })
  }

  function handleCreateForm (e) {
    switch (e.state) {
      case 'import-csv':
        setSelectedItem(e.state)
        break
      default:
        break
    }
  }

  function closeHandler () {
    setSelectedItem(null)
  }

  function enableSubmit (data) {
    setEnableForm(data)
  }

  function renderForm () {
    switch (selectedItem) {
      case 'import-csv':
        return <CsvUploader enableSubmit={enableSubmit}/>
      default:
        break
    }
  }

  function renderFormFor (definitions) {
    return definitions.map((field, i) => {
      return (
        <div
          key={`field-${field.name}-${i}`}
          // className={`${gridClasses(field)} py-2 pr-2`}
          {...field.gridProps}
        >
          <FieldRenderer
            {...field}
            // namespace={'doorkeeper_application'}
            data={field}
            props={{
              data: {} // data
            }}
            errors={{}}
            // errors={errors}
          />

      )
    })
  }

  return (

      <FilterMenu
        options={optionsForFilter()}
        value={null}
        filterHandler={(e) => handleCreateForm(e)}
        triggerButton={toggleButton}
        position={'right'}
      />

      {selectedItem && (
        <FormDialog
          open={selectedItem}
          handleClose={closeHandler}
          titleContent={'Import contacts'}
          formComponent={
            renderForm()
          }
          dialogButtons={
            <React.Fragment>
              {enableForm &&
								<Button
								  onClick={submitHandler}
								  className="ml-2"
								  variant="success">
								  {I18n.t('common.submit')}
								</Button>
              }
              <Button
                onClick={() => setSelectedItem(null)}
                variant="outlined">
                {I18n.t('common.cancel')}
              </Button>
            </React.Fragment>
          }
        ></FormDialog>
      )}

  )
}

function CsvUploader ({ handleSubmit, enableSubmit }) {
  const formRef = React.useRef()
  const [loading, setLoading] = React.useState(false);

  function uploadHandler (file, kind) {
    setLoading(true)
    getFileMetadata(file).then((input) => {
      graphql(CREATE_DIRECT_UPLOAD, input, {
        success: (data) => {
          const {
            signedBlobId,
            headers,
            url,
            serviceUrl
          } = data.createDirectUpload.directUpload

          directUpload(url, JSON.parse(headers), file).then(() => {
            // setFile({ signedBlobId })
            const data = serialize(formRef.current, { hash: true, empty: true })
            data.file = signedBlobId
            submitHandler(data)
            setLoading(false)
          })
        },
        error: (error) => {
          setLoading(false)
          console.log('error on signing blob', error)
        }
      })
    })
  };

  function submitHandler (data) {
    enableSubmit(data)
  }

  return

    <form
      name="create-repo"
      onSubmit={
        (d) => console.log(d)
        // updateApp
      }
      ref={formRef}
    >

        You can upload a csv or excel file in order to import contacts

        <fieldset className="mt-6">
          <legend className="text-base font-medium text-gray-900">
          Import Type
          </legend>

					Choose what kind of contacts you will import

              <input id="leads"
                name="contact_type"
                type="radio"
                value="leads"
                defaultChecked={true}
                className="form-radio h-4 w-4 text-indigo-600 transition duration-150 ease-in-out"
              />

                Leads

              <input id="users"
                name="contact_type"
                type="radio"
                value={'users'}
                className="form-radio h-4 w-4 text-indigo-600 transition duration-150 ease-in-out"
              />

                Users

            <FileUpload
              onChange={(file) => uploadHandler(file, 'csv')}
              loading={loading}
            />

        </fieldset>

    </form>

}

function FileUpload ({ onChange, loading }) {
  return

      <svg className="w-8 h-8" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
        <path d="M16.88 9.1A4 4 0 0 1 16 17H5a5 5 0 0 1-1-9.9V7a3 3 0 0 1 4.52-2.59A4.98 4.98 0 0 1 17 8c0 .38-.04.74-.12 1.1zM11 11h3l-4-4-4 4h3v3h2v-3z" />
      </svg>
      {
        loading && <Progress size={8} />
      }

      Select a file
      <input
        type='file'
        className="hidden"
        onChange={(e) => onChange(e.currentTarget.files[0])}
        accept={'.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'}
      />

}

function mapStateToProps (state) {
  const { app, current_user } = state
  return {
    app,
    current_user
  }
}

export default connect(mapStateToProps)(ContactManager)
<|endoftext|>


<commit_before>// used tutorial here: http://www.w3schools.com/howto/howto_js_dropdown.asp

// when the user clicks the button for the dropdown menu to appear/disappear
function dropit(){
  document.getElementById("dropOptions").classList.toggle("show");
}

// read hash and adjust accordingly on page load
window.onload = function(){
 if(location.hash){
   hashSelect(location.hash.substring(1));
 }
};

// close the dropdown menu if the user clicks outside it
window.onclick = function(e){
  if(!e.target.matches('.dropdownButton')){
    var items = document.getElementsByClassName("dropdown-content");
    for(i=0;i<items.length;i++){
      var openDropdown = items[i];
      if(openDropdown.classList.contains('show')){
        openDropdown.classList.remove('show');
      }
    }
  }
};

// creates link objects for the dropdown
function prep(){
  var dropdown = document.getElementById('dropOptions');

  var option;
  for (var i in l10n){
    option = document.createElement('a');
    option.dataset.locale = i;
    option.onclick = function(){languageSelect(this)};
    option.innerHTML = l10n[i].language;
    dropdown.appendChild(option);
  }
}

// so that we can select a language according to a URL hash
function hashSelect(hash){
  if(l10n[hash]){
    var locale = l10n[hash];
    document.getElementById('dropButton').innerHTML = l10n[hash].language + " ▾"; // set the button text to the selected option
    document.getElementById('translatorCredit').innerHTML = locale.translator ? locale.translator : l10n['en'].translator;
    document.getElementById('standardDescription').innerHTML = locale.standard ? locale.standard : l10n['en'].standard;
    document.getElementById('uniqueDescription').innerHTML = locale.unique ? locale.unique : l10n['en'].unique;
    document.getElementById('curatorString').innerHTML = locale.curators ? locale.curators : l10n['en'].curators;
  }
}

// when the user selects an option from the dropdown menu
function languageSelect(l){
  var locale = l10n[l.getAttribute('data-locale')];
  document.getElementById('dropButton').innerHTML = l.innerHTML + " ▾"; // set the button text to the selected option
  document.getElementById('translatorCredit').innerHTML = locale.translator ? locale.translator : l10n['en'].translator;
  document.getElementById('standardDescription').innerHTML = locale.standard ? locale.standard : l10n['en'].standard;
  document.getElementById('uniqueDescription').innerHTML = locale.unique ? locale.unique : l10n['en'].unique;
  document.getElementById('curatorString').innerHTML = locale.curators ? locale.curators : l10n['en'].curators;
}
<commit_msg>Improve hash code (#26)<commit_after>// used tutorial here: http://www.w3schools.com/howto/howto_js_dropdown.asp

// when the user clicks the button for the dropdown menu to appear/disappear
function dropit(){
  document.getElementById("dropOptions").classList.toggle("show");
}

// read hash and adjust accordingly on page load
window.onload = function(){
 if(location.hash){
   langSelect(location.hash.substring(1));
 }
};

// close the dropdown menu if the user clicks outside it
window.onclick = function(e){
  if(!e.target.matches('.dropdownButton')){
    var items = document.getElementsByClassName("dropdown-content");
    for(i=0;i<items.length;i++){
      var openDropdown = items[i];
      if(openDropdown.classList.contains('show')){
        openDropdown.classList.remove('show');
      }
    }
  }
};

// creates link objects for the dropdown
function prep(){
  var dropdown = document.getElementById('dropOptions');

  var option;
  for (var i in l10n){
    option = document.createElement('a');
    option.dataset.locale = i;
    option.onclick = function(){
        var lang = this.getAttribute('data-locale');
        location.hash = lang;
        langSelect(lang);
    };
    option.innerHTML = l10n[i].language;
    dropdown.appendChild(option);
  }
}

// switch language according to its two-letter code
function langSelect(hash){
  if(l10n[hash]){
    var locale = l10n[hash];
    document.getElementById('dropButton').innerHTML = l10n[hash].language + " ▾"; // set the button text to the selected option
    document.getElementById('translatorCredit').innerHTML = locale.translator ? locale.translator : l10n['en'].translator;
    document.getElementById('standardDescription').innerHTML = locale.standard ? locale.standard : l10n['en'].standard;
    document.getElementById('uniqueDescription').innerHTML = locale.unique ? locale.unique : l10n['en'].unique;
    document.getElementById('curatorString').innerHTML = locale.curators ? locale.curators : l10n['en'].curators;
  }
}
<|endoftext|>


<commit_before>const {app, BrowserWindow, ipcMain, dialog} = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs')
const per = require('./persistance')

let win

const createWindow = function() {

    win = new BrowserWindow({width: 1024, height: 768})

    win.loadURL(url.format({
      pathname: path.join(__dirname, 'src/index.html'),
      protocol: 'file:',
      slashes: true
    }))

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

    console.log("BrowserWindow created")
}

app.on('ready', function(){
    per.init(function(err){
	if(err){
	    console.log("Error initializing persistance..")
	    console.log(err)
	    console.log("Terminating the main process")
	    app.quit()
	}else{
	    console.log("creating BrowserWindow")
	    createWindow()
	}
    })
})

app.on('window-all-closed', () => {
    app.quit()
})

const addCourse = function(event, arg){
    per.saveCourse(arg, function(err, id){
	if(err){
	    console.log("Failed to save course")
	    console.log(err)
	}
	event.sender.send('add-course', id)
    })
}

const getCourse = function(event, arg){
    per.getCourse({_id:arg}, function(err, doc){
	if (err){
	    console.log("Failed to get course")
	    console.log(err)
	}
	event.sender.send('get-course', doc)
    })
}

const getCourses = function(event, arg){
    per.getCourses({}, function(err, docs){
	if (err){
	    console.log("Failed to get course")
	    console.log(err)
	}
	event.sender.send('get-courses', docs)
    })
}

const getStudents = function(event, arg){
    per.getStudents({courseID:arg}, function(err, docs){
	if (err){
	    console.log("Failed to get students for courseID : ", arg)
	    console.log(err)
	}
	event.sender.send('get-students', docs)
    })
}

const addStudent = function(event, arg){
    per.saveStudent(arg, function(err, id){
	if(err){
	    console.log("Failed to save student")
	    console.log(err)
	}
	event.sender.send('add-student', id)
    })
}

const addTxn = function(event, arg){
    per.saveTxn(arg, function(err, id){
	if(err){
	    console.log("Failed to save transaction")
	    console.log(err)
	}
	event.sender.send('add-txn', id)
    })
}

const getTxns = function(event, arg){
    per.getTxns({_id:arg}, function(err, docs){
	if (err){
	    console.log("Failed to get transactions for studentID : ", arg)
	    console.log(err)
	}
	event.sender.send('get-txns', docs)
    })
}

const getCourseSummary = function(event, arg){
    per.getCourseSummary({_id:arg}, function(err, docs){
	if (err){
	    console.log("Failed to get transaction summary for course : ", arg)
	    console.log(err)
	}
	event.sender.send('get-course-summary', docs)
    })
}

const printPDF = function(event) {
    const dialogOptions = {
	title: "Where to save PDF",
	filters: [{name : 'pdf', extensions: ['pdf']}]
    }
    dialog.showSaveDialog(dialogOptions, function(filePath){
	if(filePath){
	    const wind = BrowserWindow.fromWebContents(event.sender)
	    wind.webContents.printToPDF({}, function (error, data) {
    		if (error) throw error
    		fs.writeFile(filePath, data, function (error) {
      		    if (error) throw error
    		})
	    })
	}
    })
}

ipcMain.on('add-course', addCourse)
ipcMain.on('get-course', getCourse)
ipcMain.on('get-courses', getCourses)
ipcMain.on('get-students', getStudents)
ipcMain.on('add-student', addStudent)
ipcMain.on('add-txn', addTxn)
ipcMain.on('get-txns', getTxns)
ipcMain.on('get-course-summary', getCourseSummary)
ipcMain.on('print-to-pdf', printPDF)
<commit_msg>Remove callback hell<commit_after>const {app, BrowserWindow, ipcMain, dialog} = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs')
const per = require('./persistance')

let win

const createWindow = function() {

    win = new BrowserWindow({width: 1024, height: 768})

    win.loadURL(url.format({
      pathname: path.join(__dirname, 'src/index.html'),
      protocol: 'file:',
      slashes: true
    }))

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

    console.log("BrowserWindow created")
}

app.on('ready', function(){
    per.init(function(err){
	if(err){
	    console.log("Error initializing persistance..")
	    console.log(err)
	    console.log("Terminating the main process")
	    app.quit()
	}else{
	    console.log("creating BrowserWindow")
	    createWindow()
	}
    })
})

app.on('window-all-closed', () => {
    app.quit()
})

const addCourse = function(event, arg){
    per.saveCourse(arg, function(err, id){
	if(err){
	    console.log("Failed to save course")
	    console.log(err)
	}
	event.sender.send('add-course', id)
    })
}

const getCourse = function(event, arg){
    per.getCourse({_id:arg}, function(err, doc){
	if (err){
	    console.log("Failed to get course")
	    console.log(err)
	}
	event.sender.send('get-course', doc)
    })
}

const getCourses = function(event, arg){
    per.getCourses({}, function(err, docs){
	if (err){
	    console.log("Failed to get course")
	    console.log(err)
	}
	event.sender.send('get-courses', docs)
    })
}

const getStudents = function(event, arg){
    per.getStudents({courseID:arg}, function(err, docs){
	if (err){
	    console.log("Failed to get students for courseID : ", arg)
	    console.log(err)
	}
	event.sender.send('get-students', docs)
    })
}

const addStudent = function(event, arg){
    per.saveStudent(arg, function(err, id){
	if(err){
	    console.log("Failed to save student")
	    console.log(err)
	}
	event.sender.send('add-student', id)
    })
}

const addTxn = function(event, arg){
    per.saveTxn(arg, function(err, id){
	if(err){
	    console.log("Failed to save transaction")
	    console.log(err)
	}
	event.sender.send('add-txn', id)
    })
}

const getTxns = function(event, arg){
    per.getTxns({_id:arg}, function(err, docs){
	if (err){
	    console.log("Failed to get transactions for studentID : ", arg)
	    console.log(err)
	}
	event.sender.send('get-txns', docs)
    })
}

const getCourseSummary = function(event, arg){
    per.getCourseSummary({_id:arg}, function(err, docs){
	if (err){
	    console.log("Failed to get transaction summary for course : ", arg)
	    console.log(err)
	}
	event.sender.send('get-course-summary', docs)
    })
}

const showSaveDialog = function(dialogOptions,cb){
    dialog.showSaveDialog(dialogOptions, function(filePath){
	if(filePath) cb(filePath)
    })
}

const writeToFile = function(filePath, data){
    fs.writeFile(filePath, data, function (error) {
	if (error) throw error
    })
}

const generatePDF = function(win, options, cb){
    const wind = BrowserWindow.fromWebContents(win)
    wind.webContents.printToPDF(options, cb)
}

const printPDF = function(event) {
    const dialogOptions = {
	title: "Where to save PDF",
	filters: [{name : 'pdf', extensions: ['pdf']}]
    }
    showSaveDialog(dialogOptions,function(filePath){
	generatePDF(event.sender, {}, function (error, data) {
    	    if (error) throw error
	    writeToFile(filePath, data)
	})
    })
}

ipcMain.on('add-course', addCourse)
ipcMain.on('get-course', getCourse)
ipcMain.on('get-courses', getCourses)
ipcMain.on('get-students', getStudents)
ipcMain.on('add-student', addStudent)
ipcMain.on('add-txn', addTxn)
ipcMain.on('get-txns', getTxns)
ipcMain.on('get-course-summary', getCourseSummary)
ipcMain.on('print-to-pdf', printPDF)
<|endoftext|>


<commit_before>import request from 'superagent'

// Constants

export const REQUEST_FETCH_MOBILIZATIONS = 'REQUEST_FETCH_MOBILIZATIONS'
export const SUCCESS_FETCH_MOBILIZATIONS = 'SUCCESS_FETCH_MOBILIZATIONS'
export const FAILURE_FETCH_MOBILIZATIONS = 'FAILURE_FETCH_MOBILIZATIONS'

export const SET_CURRENT_MOBILIZATION = 'SET_CURRENT_MOBILIZATION'
export const SUCCESS_ADD_MOBILIZATION = 'SUCCESS_ADD_MOBILIZATION'
export const SUCCESS_EDIT_MOBILIZATION = 'SUCCESS_EDIT_MOBILIZATION'

export const PROGRESS_UPLOAD_FACEBOOK_IMAGE = 'PROGRESS_UPLOAD_FACEBOOK_IMAGE'
export const FINISH_UPLOAD_FACEBOOK_IMAGE = 'FINISH_UPLOAD_FACEBOOK_IMAGE'

// Actions
// TODO: Buscar uma maneira mais clara de fazer isso

export const fetchMobilizations = (queryFilter = {}) => ({
  types: [
    REQUEST_FETCH_MOBILIZATIONS,
    SUCCESS_FETCH_MOBILIZATIONS,
    FAILURE_FETCH_MOBILIZATIONS
  ],
  promise: () => new Promise((resolve, reject) => {
    request
      .get(`${process.env.API_URL}/mobilizations`)
      .send(queryFilter)
      .end((err, res) => {
        if (err || !res.ok) reject(err || res.body)
        else resolve(res.body)
      })
  })
})

const addMobilizationSuccess = mobilization => ({ type: SUCCESS_ADD_MOBILIZATION, mobilization })
export const addMobilization = (mobilization, next = null) => (dispatch, getState, request) =>
  request.addMobilization(mobilization, getState().auth.credentials)
    .then(response => {
        const { data: newMobilization } = response
        dispatch(addMobilizationSuccess(newMobilization))
        // TODO: Update react-router and install react-router-redux to make only a push in history.
        // See: https://github.com/reactjs/react-router-redux#pushlocation-replacelocation-gonumber-goback-goforward
        next && typeof next === 'function' && next(newMobilization)
        Promise.resolve()
    })
    .catch(error => Promise.reject({ _error: `Response ${error}` }))

export const setCurrentMobilizationId = currentId => ({
  type: SET_CURRENT_MOBILIZATION,
  currentId: parseInt(currentId, 10)
})

const editMobilizationSuccess = mobilization => ({ type: SUCCESS_EDIT_MOBILIZATION, mobilization })
export const editMobilization = (mobilization, next = null) => (dispatch, getState, request) =>
  request.editMobilization(mobilization, getState().auth.credentials)
    .then(response => {
      const { data: updatedMobilization } = response
      dispatch(editMobilizationSuccess(updatedMobilization))
      next && typeof next === 'function' && next(updatedMobilization)
      return Promise.resolve()
    })
    .catch(error => Promise.reject({ _error: `Response ${error}` }))

export const mobilizationsIsLoaded = state => state.mobilization.loaded
export const progressUploadFacebookImage = () => ({ type: PROGRESS_UPLOAD_FACEBOOK_IMAGE })
export const finishUploadFacebookImage = () => ({ type: FINISH_UPLOAD_FACEBOOK_IMAGE })
<commit_msg>Fix mobilization actions. #154<commit_after>import request from 'superagent'

// Constants

export const REQUEST_FETCH_MOBILIZATIONS = 'REQUEST_FETCH_MOBILIZATIONS'
export const SUCCESS_FETCH_MOBILIZATIONS = 'SUCCESS_FETCH_MOBILIZATIONS'
export const FAILURE_FETCH_MOBILIZATIONS = 'FAILURE_FETCH_MOBILIZATIONS'

export const SET_CURRENT_MOBILIZATION = 'SET_CURRENT_MOBILIZATION'
export const SUCCESS_ADD_MOBILIZATION = 'SUCCESS_ADD_MOBILIZATION'
export const SUCCESS_EDIT_MOBILIZATION = 'SUCCESS_EDIT_MOBILIZATION'

export const PROGRESS_UPLOAD_FACEBOOK_IMAGE = 'PROGRESS_UPLOAD_FACEBOOK_IMAGE'
export const FINISH_UPLOAD_FACEBOOK_IMAGE = 'FINISH_UPLOAD_FACEBOOK_IMAGE'

// Actions
// TODO: Buscar uma maneira mais clara de fazer isso

export const fetchMobilizations = (queryFilter = {}) => ({
  types: [
    REQUEST_FETCH_MOBILIZATIONS,
    SUCCESS_FETCH_MOBILIZATIONS,
    FAILURE_FETCH_MOBILIZATIONS
  ],
  promise: () => new Promise((resolve, reject) => {
    request
      .get(`${process.env.API_URL}/mobilizations`)
      .send(queryFilter)
      .end((err, res) => {
        if (err || !res.ok) reject(err || res.body)
        else resolve(res.body)
      })
  })
})

const addMobilizationSuccess = mobilization => ({ type: SUCCESS_ADD_MOBILIZATION, mobilization })
export const addMobilization = (mobilization, next = null) => (dispatch, getState, request) =>
  dispatch => request.addMobilization(mobilization, getState().auth.credentials)
    .then(response => {
        const { data: newMobilization } = response
        dispatch(addMobilizationSuccess(newMobilization))
        // TODO: Update react-router and install react-router-redux to make only a push in history.
        // See: https://github.com/reactjs/react-router-redux#pushlocation-replacelocation-gonumber-goback-goforward
        next && typeof next === 'function' && next(newMobilization)
    })
    .catch(error => Promise.reject({ _error: `Response ${error}` }))

export const setCurrentMobilizationId = currentId => ({
  type: SET_CURRENT_MOBILIZATION,
  currentId: parseInt(currentId, 10)
})

const editMobilizationSuccess = mobilization => ({ type: SUCCESS_EDIT_MOBILIZATION, mobilization })
export const editMobilization = (mobilization, next = null) => (dispatch, getState, request) =>
  dispatch => request.editMobilization(mobilization, getState().auth.credentials)
    .then(response => {
      const { data: updatedMobilization } = response
      dispatch(editMobilizationSuccess(updatedMobilization))
      next && typeof next === 'function' && next(updatedMobilization)
    })
    .catch(error => Promise.reject({ _error: `Response ${error}` }))

export const mobilizationsIsLoaded = state => state.mobilization.loaded
export const progressUploadFacebookImage = () => ({ type: PROGRESS_UPLOAD_FACEBOOK_IMAGE })
export const finishUploadFacebookImage = () => ({ type: FINISH_UPLOAD_FACEBOOK_IMAGE })
<|endoftext|>


<commit_before><commit_msg>bug fix<commit_after><|endoftext|>


<commit_before>$(function() {
  $(".collapse-link").on("click", function(e) {
    e.preventDefault();
    $(this).next(".collapse").toggle(300, function(test) {
      if ($(this).css("display") == "block") {
        $(this).addClass("in");
        $(this).prev(".collapse-link").find(".fa").removeClass("fa-caret-right").addClass("fa-caret-down");
      } else {
        $(this).removeClass("in");
        $(this).prev(".collapse-link").find(".fa").removeClass("fa-caret-down").addClass("fa-caret-right");
      }
    });
  });

  var csrftoken = $('meta[name=csrf-token]').attr('content');

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
    }
  });

  $(".create-alert .btn").on("click", function(e) {

    var q = $(this).data('q'),
    committee_id = $(this).data('committee') || "",
    content_type = $(this).data('type');

    $.post(
      '/user/saved-search/',
      {
        q: q,
        committee_id: committee_id,
        content_type: content_type
      }
    ).done(function(resp) {
      $('.create-alert').addClass('hidden');
      $('.remove-alert').removeClass('hidden').find('.btn').data('id', resp.id);
      ga('send', 'event', 'user', 'add-search-alert');
    });
  });

  $(".remove-alert .btn").on("click", function(e) {

    var id = $(this).data('id') || "";

    $.post(
      '/user/saved-search/' + id + '/delete'
    ).always(function(resp) {
      $('.remove-alert').addClass('hidden').find('.btn').data('id', '');
      $('.create-alert').removeClass('hidden');
      ga('send', 'event', 'user', 'remove-search-alert');
    });
  });

  $(".chosen").chosen({width: "100%"});
  $('[title]').tooltip();
});

// handle 404 page
$(function() {
  if ($('#page-404').length > 0) {
    ga('send', 'event', '404', document.location.pathname, document.referrer);
  }
});

$(function() {
  // show more buttons on home page
  $('.show-more').on('click', function() {
    var $btn = $(this);
    var $target = $btn.prev();

    if ($target.hasClass('expanded')) {
      $target.removeClass('expanded');
      $btn.removeClass('show-less');
      $btn.text('Show more');
    } else {
      $target.addClass('expanded');
      $btn.addClass('show-less');
      $btn.text('Show less');
      if ($target.hasClass('feature-cards')) {
      	ga('send', 'event', 'featured', 'show-more');
      } else {
      	switch ($target.parent().attr('class').replace('subsection', '').trim()) {
      		case 'committee-meetings':
      			ga('send', 'event', 'committee-meetings', 'show-more');
      			break;
      		case 'bills':
      			ga('send', 'event', 'bills', 'show-more');
      			break;
      		case 'questions':
      			ga('send', 'event', 'questions', 'show-more');
      			break;
      	}
      }
    }
  });
});

// user creation form
$('form[name=register_user_form]').on('submit', function() {
  $(this).find('input[type=submit]').prop('disabled', true);
});

$(function() {
  var initialised = false;
  var initialise = function() {
    SC.initialize({
      client_id: $('#soundcloud-container').data('soundcloud-id')
    });
  };
  var $audioLinks = $('a.audio');

  $audioLinks.each(function(i, a) {
    a = $(a);
    if (a.data('soundcloud-uri')) {
      var uri = a.data('soundcloud-uri');
      console.log('registering click');
      a.on('click', function(e) {
        console.log('clicked');
        if (!initialised) initialise();
        SC.oEmbed(uri, {
          element: document.getElementById('soundcloud-container'),
          maxheight: 166,
          show_comments: false,
          auto_play: false,
        });
        return false;
      });
    }

    // Convert first link to soundcloud embed
    var firstUri = $audioLinks.first().data('soundcloud-uri');

    if(firstUri) {
      SC.oEmbed(firstUri, {
        element: document.getElementById('soundcloud-container'),
        maxheight: 166,
        show_comments: false,
        auto_play: false,
      });
    }
  });
});

$(function() {
  $(".page-share.facebook").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.facebook.com/sharer/sharer.php?u="+window.location.href,
      "share", "width=600, height=400, scrollbars=no");
  });

  $(".page-share.twitter").on("click", function(e) {
    e.preventDefault();
    window.open("https://twitter.com/intent/tweet?&url="+window.location.href,
      "share", "width=600, height=400, scrollbars=no");
  });

  $(".page-share.linkedin").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.linkedin.com/shareArticle?mini=true&source=PMG&url="+window.location.href,
      "share", "width=600, height=400, scrollbars=no");
  });
});<commit_msg>analytics on share button<commit_after>$(function() {
  $(".collapse-link").on("click", function(e) {
    e.preventDefault();
    $(this).next(".collapse").toggle(300, function(test) {
      if ($(this).css("display") == "block") {
        $(this).addClass("in");
        $(this).prev(".collapse-link").find(".fa").removeClass("fa-caret-right").addClass("fa-caret-down");
      } else {
        $(this).removeClass("in");
        $(this).prev(".collapse-link").find(".fa").removeClass("fa-caret-down").addClass("fa-caret-right");
      }
    });
  });

  var csrftoken = $('meta[name=csrf-token]').attr('content');

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
    }
  });

  $(".create-alert .btn").on("click", function(e) {

    var q = $(this).data('q'),
    committee_id = $(this).data('committee') || "",
    content_type = $(this).data('type');

    $.post(
      '/user/saved-search/',
      {
        q: q,
        committee_id: committee_id,
        content_type: content_type
      }
    ).done(function(resp) {
      $('.create-alert').addClass('hidden');
      $('.remove-alert').removeClass('hidden').find('.btn').data('id', resp.id);
      ga('send', 'event', 'user', 'add-search-alert');
    });
  });

  $(".remove-alert .btn").on("click", function(e) {

    var id = $(this).data('id') || "";

    $.post(
      '/user/saved-search/' + id + '/delete'
    ).always(function(resp) {
      $('.remove-alert').addClass('hidden').find('.btn').data('id', '');
      $('.create-alert').removeClass('hidden');
      ga('send', 'event', 'user', 'remove-search-alert');
    });
  });

  $(".chosen").chosen({width: "100%"});
  $('[title]').tooltip();
});

// handle 404 page
$(function() {
  if ($('#page-404').length > 0) {
    ga('send', 'event', '404', document.location.pathname, document.referrer);
  }
});

$(function() {
  // show more buttons on home page
  $('.show-more').on('click', function() {
    var $btn = $(this);
    var $target = $btn.prev();

    if ($target.hasClass('expanded')) {
      $target.removeClass('expanded');
      $btn.removeClass('show-less');
      $btn.text('Show more');
    } else {
      $target.addClass('expanded');
      $btn.addClass('show-less');
      $btn.text('Show less');
      if ($target.hasClass('feature-cards')) {
      	ga('send', 'event', 'featured', 'show-more');
      } else {
      	switch ($target.parent().attr('class').replace('subsection', '').trim()) {
      		case 'committee-meetings':
      			ga('send', 'event', 'committee-meetings', 'show-more');
      			break;
      		case 'bills':
      			ga('send', 'event', 'bills', 'show-more');
      			break;
      		case 'questions':
      			ga('send', 'event', 'questions', 'show-more');
      			break;
      	}
      }
    }
  });
});

// user creation form
$('form[name=register_user_form]').on('submit', function() {
  $(this).find('input[type=submit]').prop('disabled', true);
});

$(function() {
  var initialised = false;
  var initialise = function() {
    SC.initialize({
      client_id: $('#soundcloud-container').data('soundcloud-id')
    });
  };
  var $audioLinks = $('a.audio');

  $audioLinks.each(function(i, a) {
    a = $(a);
    if (a.data('soundcloud-uri')) {
      var uri = a.data('soundcloud-uri');
      console.log('registering click');
      a.on('click', function(e) {
        console.log('clicked');
        if (!initialised) initialise();
        SC.oEmbed(uri, {
          element: document.getElementById('soundcloud-container'),
          maxheight: 166,
          show_comments: false,
          auto_play: false,
        });
        return false;
      });
    }

    // Convert first link to soundcloud embed
    var firstUri = $audioLinks.first().data('soundcloud-uri');

    if(firstUri) {
      SC.oEmbed(firstUri, {
        element: document.getElementById('soundcloud-container'),
        maxheight: 166,
        show_comments: false,
        auto_play: false,
      });
    }
  });
});

$(function() {
  $(".page-share.facebook").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.facebook.com/sharer/sharer.php?u="+window.location.href,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'facebook', 'share', url);
  });

  $(".page-share.twitter").on("click", function(e) {
    e.preventDefault();
    window.open("https://twitter.com/intent/tweet?&url="+window.location.href,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'twitter', 'share', url);
  });

  $(".page-share.linkedin").on("click", function(e) {
    e.preventDefault();
    window.open("https://www.linkedin.com/shareArticle?mini=true&source=PMG&url="+window.location.href,
      "share", "width=600, height=400, scrollbars=no");
      ga('send', 'social', 'linkedin', 'share', url);
  });
});<|endoftext|>