<commit_before>var fs = require('fs');
var path = require('path');
var SVGO = require('svgo');

// Initialize what will be used for automatic text measurement.
var Canvas = require('canvas');
var canvasElement = new Canvas(0, 0);   // Width and height are irrelevant.
var canvasContext = canvasElement.getContext('2d');
var CanvasFont = Canvas.Font;
var color = require('chromath');
try {
  var opensans = new CanvasFont('Verdana',
      path.join(__dirname, 'Verdana.ttf'));
  canvasContext.addFont(opensans);
} catch(e) {}
canvasContext.font = '11px Verdana, "DejaVu Sans"';

// Template crafting action below.
var dot = require('dot');
var colorscheme = require(path.join(__dirname, 'colorscheme.json'));
var template = fs.readFileSync(path.join(__dirname, 'template.svg'));
var imageTemplate = dot.template(''+template);

function optimize(string, callback) {
  var svgo = new SVGO();
  svgo.optimize(string, callback);
}

function makeImage(data, cb) {
   data.colorscheme = data.colorscheme.split(",");
  if (data.colorscheme) {
    data.colorA =  color.websafe(data.colorscheme[0]).toString();
	if(data.colorscheme.length > 1){
		data.colorB =  color.websafe(data.colorscheme[1]).toString();
	}else{
		data.colorB =  color.websafe(data.colorscheme[0]).toString();
	}
  }
  data.widths = [
    (canvasContext.measureText(data.text[0]).width|0) + 10,
    (canvasContext.measureText(data.text[1]).width|0) + 10,
  ];
  var result = imageTemplate(data);
  // Run the SVG through SVGO.
  optimize(result, function(object) { cb(object.data); });
}

module.exports = makeImage;
<commit_msg>My brain hurts from this<commit_after>var fs = require('fs');
var path = require('path');
var SVGO = require('svgo');

// Initialize what will be used for automatic text measurement.
var Canvas = require('canvas');
var canvasElement = new Canvas(0, 0);   // Width and height are irrelevant.
var canvasContext = canvasElement.getContext('2d');
var CanvasFont = Canvas.Font;
var color = require('chromath');
try {
  var opensans = new CanvasFont('Verdana',
      path.join(__dirname, 'Verdana.ttf'));
  canvasContext.addFont(opensans);
} catch(e) {}
canvasContext.font = '11px Verdana, "DejaVu Sans"';

// Template crafting action below.
var dot = require('dot');
var colorscheme = require(path.join(__dirname, 'colorscheme.json'));
var template = fs.readFileSync(path.join(__dirname, 'template.svg'));
var imageTemplate = dot.template(''+template);

function optimize(string, callback) {
  var svgo = new SVGO();
  svgo.optimize(string, callback);
}

function makeImage(data, cb) {
   data.colorscheme = data.colorscheme.split(",");
  if (data.colorscheme) {
    data.colorA =  color.additive(data.colorscheme[0]).toString();
	if(data.colorscheme.length > 1){
		data.colorB =  color.additive(data.colorscheme[1]).toString();
	}else{
		data.colorB =  color.additive(data.colorscheme[0]).toString();
	}
  }
  data.widths = [
    (canvasContext.measureText(data.text[0]).width|0) + 10,
    (canvasContext.measureText(data.text[1]).width|0) + 10,
  ];
  var result = imageTemplate(data);
  // Run the SVG through SVGO.
  optimize(result, function(object) { cb(object.data); });
}

module.exports = makeImage;
<|endoftext|>


<commit_before>/* @flow strict-local */
import * as typing_status from '@zulip/shared/js/typing_status';

import type { Dispatch, GetState, Narrow } from '../types';
import * as api from '../api';
import { PRESENCE_RESPONSE } from '../actionConstants';
import { getAuth, tryGetAuth } from '../selectors';
import { isPrivateOrGroupNarrow, caseNarrowPartial } from '../utils/narrow';
import { getAllUsersByEmail } from './userSelectors';

export const reportPresence = (isActive: boolean = true, newUserInput: boolean = false) => async (
  dispatch: Dispatch,
  getState: GetState,
) => {
  const auth = tryGetAuth(getState());
  if (!auth) {
    return; // not logged in
  }

  const response = await api.reportPresence(auth, isActive, newUserInput);
  dispatch({
    type: PRESENCE_RESPONSE,
    presence: response.presences,
    serverTimestamp: response.server_timestamp,
  });
};

const typingWorker = auth => ({
  get_current_time: () => new Date().getTime(),

  notify_server_start: (user_ids_array: number[]) => {
    api.typing(auth, JSON.stringify(user_ids_array), 'start');
  },

  notify_server_stop: (user_ids_array: number[]) => {
    api.typing(auth, JSON.stringify(user_ids_array), 'stop');
  },
});

export const sendTypingStart = (narrow: Narrow) => async (
  dispatch: Dispatch,
  getState: GetState,
) => {
  if (!isPrivateOrGroupNarrow(narrow)) {
    return;
  }

  const usersByEmail = getAllUsersByEmail(getState());
  const recipientIds = caseNarrowPartial(narrow, {
    pm: email => [email],
    groupPm: emails => emails,
  }).map(email => {
    const user = usersByEmail.get(email);
    if (!user) {
      throw new Error('unknown user');
    }
    return user.user_id;
  });

  const auth = getAuth(getState());
  typing_status.update(typingWorker(auth), recipientIds);
};

// TODO call this on more than send: blur, navigate away,
//   delete all contents, etc.
export const sendTypingStop = (narrow: Narrow) => async (
  dispatch: Dispatch,
  getState: GetState,
) => {
  if (!isPrivateOrGroupNarrow(narrow)) {
    return;
  }

  const auth = getAuth(getState());
  typing_status.update(typingWorker(auth), null);
};
<commit_msg>typing status: Use recipients format based on server version.<commit_after>/* @flow strict-local */
import * as typing_status from '@zulip/shared/js/typing_status';

import type { Auth, Dispatch, GetState, GlobalState, Narrow } from '../types';
import * as api from '../api';
import { PRESENCE_RESPONSE } from '../actionConstants';
import { getAuth, tryGetAuth, getServerVersion } from '../selectors';
import { isPrivateOrGroupNarrow, caseNarrowPartial } from '../utils/narrow';
import { getAllUsersByEmail, getUserForId } from './userSelectors';
import { ZulipVersion } from '../utils/zulipVersion';

export const reportPresence = (isActive: boolean = true, newUserInput: boolean = false) => async (
  dispatch: Dispatch,
  getState: GetState,
) => {
  const auth = tryGetAuth(getState());
  if (!auth) {
    return; // not logged in
  }

  const response = await api.reportPresence(auth, isActive, newUserInput);
  dispatch({
    type: PRESENCE_RESPONSE,
    presence: response.presences,
    serverTimestamp: response.server_timestamp,
  });
};

const typingWorker = (state: GlobalState) => {
  const auth: Auth = getAuth(state);
  const serverVersion: ZulipVersion | void = getServerVersion(state);

  // User ID arrays are only supported in server versions >= 2.0.0-rc1
  // (zulip/zulip@2f634f8c0). For versions before this, email arrays
  // are used. If current server version is undetermined, user ID
  // arrays are optimistically used.
  let useEmailArrays: boolean;
  if (serverVersion === undefined) {
    useEmailArrays = false;
  } else {
    useEmailArrays = !serverVersion.isAtLeast(new ZulipVersion('2.0.0-rc1'));
  }

  const getRecipients = user_ids_array => {
    if (useEmailArrays) {
      return JSON.stringify(user_ids_array.map(userId => getUserForId(state, userId).email));
    }
    return JSON.stringify(user_ids_array);
  };

  return {
    get_current_time: () => new Date().getTime(),

    notify_server_start: (user_ids_array: number[]) => {
      api.typing(auth, getRecipients(user_ids_array), 'start');
    },

    notify_server_stop: (user_ids_array: number[]) => {
      api.typing(auth, getRecipients(user_ids_array), 'stop');
    },
  };
};

export const sendTypingStart = (narrow: Narrow) => async (
  dispatch: Dispatch,
  getState: GetState,
) => {
  if (!isPrivateOrGroupNarrow(narrow)) {
    return;
  }

  const usersByEmail = getAllUsersByEmail(getState());
  const recipientIds = caseNarrowPartial(narrow, {
    pm: email => [email],
    groupPm: emails => emails,
  }).map(email => {
    const user = usersByEmail.get(email);
    if (!user) {
      throw new Error('unknown user');
    }
    return user.user_id;
  });
  typing_status.update(typingWorker(getState()), recipientIds);
};

// TODO call this on more than send: blur, navigate away,
//   delete all contents, etc.
export const sendTypingStop = (narrow: Narrow) => async (
  dispatch: Dispatch,
  getState: GetState,
) => {
  if (!isPrivateOrGroupNarrow(narrow)) {
    return;
  }

  typing_status.update(typingWorker(getState()), null);
};
<|endoftext|>


<commit_before>var jsface = require('jsface'),
    fs     = require('fs'),
    Errors = require('./ErrorHandler'),
    _und   = require('underscore');
var mkdirp = require('mkdirp');

/**
 * @name Helpers
 * @namespace
 * @classdesc Helper class with useful methods used throughout Newman
 */
var Importer = jsface.Class({
    $singleton: true,

    importFile: function(filePath) {
        var jsonObj = JSON.parse(fs.readFileSync(filePath, 'utf8'));
        var collections = jsonObj.collections;
        var environments = jsonObj.environments;
        var globals = jsonObj.globals;
        var i;

        if(!collections instanceof Array) {
            Errors.parseError("Collections must be an array...aborting");
        }
        if(!environments instanceof Array) {
            Errors.parseError("Environments must be an array...aborting");
        }
        if(!globals instanceof Array) {
            Errors.parseError("Globals must be an array...aborting");
        }

        var numC = collections.length;
        var numE = environments.length;
        var numG = globals.length;

        mkdirp.sync('data/collections');
        mkdirp.sync('data/environments');
        mkdirp.sync('data/globals');

        for(i=0;i<numC;i++) {
            this._saveCollection(collections[i]);
        }

        for(i=0;i<numE;i++) {
            this._saveEnvironment(environments[i]);
        }

        this._saveGlobal(globals);
    },

    _saveCollection: function(thisCollection) {
        var collectionName = thisCollection.name;
        if(collectionName==null || collectionName=="") {
            collectionName = thisCollection.id;
        }
        var collectionString = JSON.stringify(thisCollection);

        fs.writeFile('data/collections/'+collectionName+".json", collectionString, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Collection ('+collectionName+') saved');
        });
    },

    _saveEnvironment: function(environment) {
        var envName = environment.name;
        if(envName==null || envName=="") {
            envName = environment.id;
        }
        var envString = JSON.stringify(environment);

        fs.writeFile('data/environments/'+envName+".json", envString, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Environment ('+envName+') saved');
        });
    },

    _saveGlobal: function(globals) {
        var globalName = "global_"+(new Date().getTime())+".json";
        fs.writeFile('data/globals/'+globalName+".json", JSON.stringify(globals), function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Global ('+globalName+') saved');
        });
    }

});

module.exports = Importer;
<commit_msg>Fixing travis<commit_after>var jsface = require('jsface'),
    fs     = require('fs'),
    Errors = require('./ErrorHandler'),
    mkdirp = require('mkdirp');

/**
 * @name Helpers
 * @namespace
 * @classdesc Helper class with useful methods used throughout Newman
 */
var Importer = jsface.Class({
    $singleton: true,

    importFile: function(filePath) {
        var jsonObj = JSON.parse(fs.readFileSync(filePath, 'utf8'));
        var collections = jsonObj.collections;
        var environments = jsonObj.environments;
        var globals = jsonObj.globals;
        var i;

        if(!collections instanceof Array) {
            Errors.parseError("Collections must be an array...aborting");
        }
        if(!environments instanceof Array) {
            Errors.parseError("Environments must be an array...aborting");
        }
        if(!globals instanceof Array) {
            Errors.parseError("Globals must be an array...aborting");
        }

        var numC = collections.length;
        var numE = environments.length;

        mkdirp.sync('data/collections');
        mkdirp.sync('data/environments');
        mkdirp.sync('data/globals');

        for(i=0;i<numC;i++) {
            this._saveCollection(collections[i]);
        }

        for(i=0;i<numE;i++) {
            this._saveEnvironment(environments[i]);
        }

        this._saveGlobal(globals);
    },

    _saveCollection: function(thisCollection) {
        var collectionName = thisCollection.name;
        if(collectionName===null || collectionName==="") {
            collectionName = thisCollection.id;
        }
        var collectionString = JSON.stringify(thisCollection);

        fs.writeFile('data/collections/'+collectionName+".json", collectionString, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Collection ('+collectionName+') saved');
        });
    },

    _saveEnvironment: function(environment) {
        var envName = environment.name;
        if(envName===null || envName==="") {
            envName = environment.id;
        }
        var envString = JSON.stringify(environment);

        fs.writeFile('data/environments/'+envName+".json", envString, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Environment ('+envName+') saved');
        });
    },

    _saveGlobal: function(globals) {
        var globalName = "global_"+(new Date().getTime())+".json";
        fs.writeFile('data/globals/'+globalName+".json", JSON.stringify(globals), function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Global ('+globalName+') saved');
        });
    }

});

module.exports = Importer;
<|endoftext|>


<commit_before>'use strict'

function probeSocket(uri, callback, errcallback){
    var probews;
    probews = new WebSocket(uri);

    probews.onmessage= function(evt){
        callback(evt);
        probews.close();
    }

    probews.onerror = function(evt){
        errcallback(evt);
        probews.close();
    }

}

function nodo(info, callback){
    var uri = "wss://"+info+":1370/ws/probe/";
    probeSocket(uri, function(evt){
        var i = info;
        var cadena = "
";
        cadena += "
"+i+"
";
        cadena += "<input class='deploy' type='checkbox'></input>"
        cadena += "
";
        callback(cadena);
    }, function(evt){
        var i = info;
        var probeuri = "https://"+i+":1370/";
        var cadena = "
";
        cadena += "
"+i+"
";
        cadena += "
Error en la creación del socket. Click aquí para resolver
"
        cadena += "<input class='deploy' type='checkbox'></input>"
        cadena += "
";
        callback(cadena);
    });

}

$(document).ready(function() {

    $("#listanodos").on('click', "input[type=checkbox]", function(){
        $(this).closest(".node").toggleClass("chosen").toggleClass("not-chosen");
    });

    $("#list").delegate('.delete-buton', 'click', function(){
        var index = $(this).parent().index();

        $(this).parent().fadeOut(400, function(){
            $(this).remove();
            files_to_upload.splice(index, 1);
        });
    });

    $('#list').delegate('input[name=polo]', 'click', function(){
        if($(this).is(':checked')){
            $(this).siblings('input[name=idpolo]').prop('disabled', false);
            $(this).siblings('.polo.alert-warning').show(400);
        }else{
            $(this).siblings('input[name=idpolo]').prop('disabled', true);
            $(this).siblings('.polo.alert-warning').hide(400);
        }
    });

    $('#list').delegate('input[name=tomcat]', 'click', function(){
        if($(this).is(':checked')){
            $(this).siblings('.warning.alert-warning').show(400);
            $(this).siblings('input[name=folder]').prop('disabled', true);
            $(this).siblings('input[name=folder]').prop('placeholder', 'Default Tomcat directory');
        }else{
            $(this).siblings('.warning.alert-warning').hide(400);
            $(this).siblings('input[name=folder]').prop('disabled', false);
            $(this).siblings('input[name=folder]').prop('placeholder', 'Deployment folder');
        }
    });
});

//http://hayageek.com/drag-and-drop-file-upload-jquery/

function sendFileToServer(formData, status) {

    var uploadURL = "/upload/"; //Upload URL
    var extraData = {}; //Extra Data.
    var jqXHR = $.ajax({
        xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                xhrobj.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position;
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                    }

                    status.setProgress(percent);
                }, false);
            }
            return xhrobj;
        },
        url: uploadURL,
        type: "POST",
        contentType: false,
        processData: false,
        cache: false,
        data: formData,
        beforeSend:function(data){
            $(".alert.alert-success").hide();
        },
        success: function(data) {
            status.setProgress(100);
            $(".alert.alert-success").show();
            $(".alert.alert-success").text("File upload done");
        }
    });
}

function createStatusbar(obj){
    this.obj = $(obj);
    this.setProgress = function(progress){
        obj.attr("aria-valuenow", progress);
        obj.css("width",progress + "%");
        obj.html(progress + "%");
    }
}

function handleFileUpload(files, obj) {
    for (var i = 0; i < files.length; i++) {

        files[i].command = $(".upload-item").eq(i).find("input[name=command]").val();
        //files[i].folder = $(".upload-item").eq(i).find("input[name=folder]").val();
        files[i].polo = $(".upload-item").eq(i).find("input[name=polo]").is(':checked');
        if(files[i].polo){
            files[i].identifier = $(".upload-item").eq(i).find("input[name=idpolo").val();
        }

        if($(".upload-item").eq(i).find("input[name=tomcat]").is(':checked')){
            files[i].tomcat = true

        }else{
            files[i].tomcat = false
            files[i].folder = $(".upload-item").eq(i).find("input[name=folder]").val();
        }

        files[i].overwrite = $(".upload-item").eq(i).find("input[name=overwrite]").is(':checked');

        var fd = new FormData();
        fd.append('file', files[i].file);
        fd.append('command', files[i].command);
        fd.append('folder', files[i].folder);
        if(files[i].tomcat === true)
            fd.append('tomcat', files[i].tomcat);
        fd.append('overwrite', files[i].overwrite);
        var cadena = "";
        var ips = $(".chosen").children(".ip")
        var j = i;

        if(ips.length > 0){
            ips.each(function(index){

                cadena += $(this).html() + ",";
                var ip = $(this).html();

                /*createSocket(ip,*/

                (function(){

                    if(index >= ips.length - 1){

                        fd.append('nodes', cadena);

                        var status = new createStatusbar($(".progress-bar").eq(j));
                        createTabs(ip);
                        sendFileToServer(fd, status);
                    }
                })();
            });

        }
    }
}

var fileCount = 0;

function addToList(file){
    var filename = file.name;

    var other= '
<button style="width:10%;" class="btn btn-danger delete-buton pull-right">

</button>'
    var header_filename = '
'+filename+'

'
    var buttons = '<input type="text" name="command" placeholder="Command" maxlength="300"/>
<input type="text" placeholder="Deployment folder" name="folder" maxlength="300"/>
Deploy in Polo?<input type="checkbox" value="polo" name="polo"/><input type="text" name="idpolo" placeholder="Identifier" maxlength="40" disabled="true"/>
The service will be registered permanently. Use the language-specific binding to perform a temporary registry on execution time.
'
    var labels = '

Deploy in Tomcat?<input type="checkbox" value="tomcat" name="tomcat"/>
The service will be installed on the Tomcat deployment directory after validating the format of the archive. If no instance of Tomcat is installed on the server, it won\'t be installed.
'
    labels += '

Overwrite file if it exists?<input type="checkbox" value="overwrite" name="overwrite" checked/>
'
    var str = "
"
    str += '
'+filename+'
';
    str += '

0%

'
    str += '<input class="pull-right" type="checkbox" value="polo" name="polo"></input>Deploy in polo?<input type="text" name="command" placeholder="Command" maxlength="300"></input>';
    str +='

<input type="text" placeholder="Deployment folder" name="folder" maxlength="300"></input><button class="btn btn-danger delete-buton pull-right">Delete</button>'
    str += "
"

    str = other + header_filename + buttons + labels;
    $("#list").append(str);
}

var files_to_upload;

$(document).ready(function() {

    files_to_upload = new Array();

    var obj = $("#dragandrophandler");
    obj.on('dragenter', function(e) {
        e.stopPropagation();
        e.preventDefault();
        $(this).css('border', '2px solid #0B85A1');
    });
    obj.on('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
    });
    obj.on('drop', function(e) {

        $(this).css('border', '2px dotted #0B85A1');
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        for (var i = 0; i < files.length; i++) {
            files_to_upload.push({file: files[i]});
            fileCount++;
            addToList(files[i]);
        }
    });

    $(document).on('dragenter', function(e) {
        e.stopPropagation();
        e.preventDefault();
    });
    $(document).on('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        obj.css('border', '2px dotted #0B85A1');
    });
    $(document).on('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
    });

    $("#uploadbutton").on('click', function(e){
        handleFileUpload(files_to_upload, obj);
    });

    //from http://www.jacklmoore.com/notes/jquery-tabs/
    $("ul.tabs").each(function() {
        var $active, $content, $links = $(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
        $active.addClass('active');

        $content = $($active[0].hash);

        // Hide the remaining content
        $links.not($active).each(function() {
            $(this.hash).hide();
        });

        // Bind the click event handler
        $(this).on('click', 'a', function(e) {
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active = $(this);
            $content = $(this.hash);

            // Make the tab active.
            $active.addClass('active');
            $content.show();

            // Prevent the anchor's default click action
            //e.preventDefault();
        });
    });
});

<commit_msg>Fix progress bar<commit_after>'use strict'

function probeSocket(uri, callback, errcallback){
    var probews;
    probews = new WebSocket(uri);

    probews.onmessage= function(evt){
        callback(evt);
        probews.close();
    }

    probews.onerror = function(evt){
        errcallback(evt);
        probews.close();
    }

}

function nodo(info, callback){
    var uri = "wss://"+info+":1370/ws/probe/";
    probeSocket(uri, function(evt){
        var i = info;
        var cadena = "
";
        cadena += "
"+i+"
";
        cadena += "<input class='deploy' type='checkbox'></input>"
        cadena += "
";
        callback(cadena);
    }, function(evt){
        var i = info;
        var probeuri = "https://"+i+":1370/";
        var cadena = "
";
        cadena += "
"+i+"
";
        cadena += "
Error en la creación del socket. Click aquí para resolver
"
        cadena += "<input class='deploy' type='checkbox'></input>"
        cadena += "
";
        callback(cadena);
    });

}

$(document).ready(function() {

    $("#listanodos").on('click', "input[type=checkbox]", function(){
        $(this).closest(".node").toggleClass("chosen").toggleClass("not-chosen");
    });

    $("#list").delegate('.delete-buton', 'click', function(){
        var index = $(this).parent().index();

        $(this).parent().fadeOut(400, function(){
            $(this).remove();
            files_to_upload.splice(index, 1);
        });
    });

    $('#list').delegate('input[name=polo]', 'click', function(){
        if($(this).is(':checked')){
            $(this).siblings('input[name=idpolo]').prop('disabled', false);
            $(this).siblings('.polo.alert-warning').show(400);
        }else{
            $(this).siblings('input[name=idpolo]').prop('disabled', true);
            $(this).siblings('.polo.alert-warning').hide(400);
        }
    });

    $('#list').delegate('input[name=tomcat]', 'click', function(){
        if($(this).is(':checked')){
            $(this).siblings('.warning.alert-warning').show(400);
            $(this).siblings('input[name=folder]').prop('disabled', true);
            $(this).siblings('input[name=folder]').prop('placeholder', 'Default Tomcat directory');
        }else{
            $(this).siblings('.warning.alert-warning').hide(400);
            $(this).siblings('input[name=folder]').prop('disabled', false);
            $(this).siblings('input[name=folder]').prop('placeholder', 'Deployment folder');
        }
    });
});

//http://hayageek.com/drag-and-drop-file-upload-jquery/

function sendFileToServer(formData, status) {

    var uploadURL = "/upload/"; //Upload URL
    var extraData = {}; //Extra Data.
    var jqXHR = $.ajax({
        xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                xhrobj.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position;
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                    }

                    status.setProgress(percent);
                }, false);
            }
            return xhrobj;
        },
        url: uploadURL,
        type: "POST",
        contentType: false,
        processData: false,
        cache: false,
        data: formData,
        beforeSend:function(data){
            $(".alert.alert-success").hide();
        },
        success: function(data) {
            status.setProgress(100);
            $(".alert.alert-success").show();
            $(".alert.alert-success").text("File upload done");
        }
    });
}

function createStatusbar(obj){
    this.obj = $(obj);
    this.setProgress = function(progress){
        obj.attr("aria-valuenow", progress);
        obj.css("width",progress + "%");
        obj.html(progress + "%");
    }
}

function handleFileUpload(files, obj) {
    for (var i = 0; i < files.length; i++) {

        files[i].command = $(".upload-item").eq(i).find("input[name=command]").val();
        //files[i].folder = $(".upload-item").eq(i).find("input[name=folder]").val();
        files[i].polo = $(".upload-item").eq(i).find("input[name=polo]").is(':checked');
        if(files[i].polo){
            files[i].identifier = $(".upload-item").eq(i).find("input[name=idpolo").val();
        }

        if($(".upload-item").eq(i).find("input[name=tomcat]").is(':checked')){
            files[i].tomcat = true

        }else{
            files[i].tomcat = false
            files[i].folder = $(".upload-item").eq(i).find("input[name=folder]").val();
        }

        files[i].overwrite = $(".upload-item").eq(i).find("input[name=overwrite]").is(':checked');

        var fd = new FormData();
        fd.append('file', files[i].file);
        fd.append('command', files[i].command);
        fd.append('folder', files[i].folder);
        if(files[i].tomcat === true)
            fd.append('tomcat', files[i].tomcat);
        fd.append('overwrite', files[i].overwrite);
        var cadena = "";
        var ips = $(".chosen").children(".ip")
        var j = i;

        if(ips.length > 0){
            ips.each(function(index){

                cadena += $(this).html() + ",";
                var ip = $(this).html();

                /*createSocket(ip,*/

                (function(){

                    if(index >= ips.length - 1){

                        fd.append('nodes', cadena);

                        var status = new createStatusbar($(".progress-bar").eq(j));
                        createTabs(ip);
                        sendFileToServer(fd, status);
                    }
                })();
            });

        }
    }
}

var fileCount = 0;

function addToList(file){
    var filename = file.name;

    var other= '
<button style="width:10%;" class="btn btn-danger delete-buton pull-right">

</button>'
    var header_filename = '
'+filename+'

'
    var buttons = '<input type="text" name="command" placeholder="Command" maxlength="300"/>
<input type="text" placeholder="Deployment folder" name="folder" maxlength="300"/>
Deploy in Polo?<input type="checkbox" value="polo" name="polo"/><input type="text" name="idpolo" placeholder="Identifier" maxlength="40" disabled="true"/>
The service will be registered permanently. Use the language-specific binding to perform a temporary registry on execution time.
'
    var labels = '

Deploy in Tomcat?<input type="checkbox" value="tomcat" name="tomcat"/>
The service will be installed on the Tomcat deployment directory after validating the format of the archive. If no instance of Tomcat is installed on the server, it won\'t be installed.
'
    labels += '

Overwrite file if it exists?<input type="checkbox" value="overwrite" name="overwrite" checked/>
'

    var str = other + header_filename + buttons + labels;
    $("#list").append(str);
}

var files_to_upload;

$(document).ready(function() {

    files_to_upload = new Array();

    var obj = $("#dragandrophandler");
    obj.on('dragenter', function(e) {
        e.stopPropagation();
        e.preventDefault();
        $(this).css('border', '2px solid #0B85A1');
    });
    obj.on('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
    });
    obj.on('drop', function(e) {

        $(this).css('border', '2px dotted #0B85A1');
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        for (var i = 0; i < files.length; i++) {
            files_to_upload.push({file: files[i]});
            fileCount++;
            addToList(files[i]);
        }
    });

    $(document).on('dragenter', function(e) {
        e.stopPropagation();
        e.preventDefault();
    });
    $(document).on('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        obj.css('border', '2px dotted #0B85A1');
    });
    $(document).on('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
    });

    $("#uploadbutton").on('click', function(e){
        handleFileUpload(files_to_upload, obj);
    });

    //from http://www.jacklmoore.com/notes/jquery-tabs/
    $("ul.tabs").each(function() {
        var $active, $content, $links = $(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
        $active.addClass('active');

        $content = $($active[0].hash);

        // Hide the remaining content
        $links.not($active).each(function() {
            $(this.hash).hide();
        });

        // Bind the click event handler
        $(this).on('click', 'a', function(e) {
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active = $(this);
            $content = $(this.hash);

            // Make the tab active.
            $active.addClass('active');
            $content.show();

            // Prevent the anchor's default click action
            //e.preventDefault();
        });
    });
});

<|endoftext|>


<commit_before>/* @flow */

// $FlowIssue base-react
import React, {Component} from '../base-react'
import path from 'path'
import commonStyles from '../styles/common'
import type {Styled} from '../styles/common'

import type {HeaderProps} from './header.render.types'

export default class HeaderRender extends Component {
  props: HeaderProps & Styled;

  render (): ReactElement {
    return (

        <img style={styles.logo} src={`file:///${path.resolve('../react-native/react/images/service/keybase.png')}`}/>

{this.props.reason}

 this.props.onClose()}>

    )
  }
}

HeaderRender.propTypes = {
  reason: React.PropTypes.string.isRequired,
  onClose: React.PropTypes.func.isRequired,
  style: React.PropTypes.object.isRequired
}

const styles = {
  container: {
    ...commonStyles.flexBoxRow,
    ...commonStyles.windowDragging,
    paddingLeft: 15,
    paddingRight: 9,
    alignItems: 'center'
  },
  logo: {
    width: 22,
    height: 22,
    marginRight: 7
  },
  reason: {
    color: '#20C0EF',
    flex: 1
  },
  close: {
    ...commonStyles.clickable,
    ...commonStyles.windowDraggingClickable,
    color: '#D0D4DA'
  }
}
<commit_msg>Electron path should be absolute<commit_after>/* @flow */

// $FlowIssue base-react
import React, {Component} from '../base-react'
import path from 'path'
import commonStyles from '../styles/common'
import type {Styled} from '../styles/common'

import type {HeaderProps} from './header.render.types'

export default class HeaderRender extends Component {
  props: HeaderProps & Styled;

  render (): ReactElement {
    return (

        <img style={styles.logo} src={`file://${path.resolve(__dirname, '..', 'images', 'service' , 'keybase.png')}`}/>

{this.props.reason}

 this.props.onClose()}>

    )
  }
}

HeaderRender.propTypes = {
  reason: React.PropTypes.string.isRequired,
  onClose: React.PropTypes.func.isRequired,
  style: React.PropTypes.object.isRequired
}

const styles = {
  container: {
    ...commonStyles.flexBoxRow,
    ...commonStyles.windowDragging,
    paddingLeft: 15,
    paddingRight: 9,
    alignItems: 'center'
  },
  logo: {
    width: 22,
    height: 22,
    marginRight: 7
  },
  reason: {
    color: '#20C0EF',
    flex: 1
  },
  close: {
    ...commonStyles.clickable,
    ...commonStyles.windowDraggingClickable,
    color: '#D0D4DA'
  }
}
<|endoftext|>


<commit_before>var DataDownloadTab = (function() {

    var _rawDataObj = {},
        _rawStatObj = {},
        _isRendered = false;

    var strs = {
        alt_freq: "",
        alt_type: "",
        case_affected: "",
        case_matrix: ""
    };

    var calc_alt_freq = function() {
            strs.alt_freq = "GENE_SYMBOL" + "\t" + "NUM_CASES_ALTERED" + "\t" + "PERCENT_CASES_ALTERED" + "\n";
            $.each(_rawStatObj, function(key, value) {
                strs.alt_freq += key + "\t" + value.total_alter_num + "\t" + value.percent + "%" + "\n";
            });
        },
        calc_alt_type = function() {
            strs.alt_type = "Case ID" + "\t";
            $.each(Object.keys(_rawStatObj), function(index, val) {
                strs.alt_type += val + "\t";
            });
            strs.alt_type += "\n";
            $.each(_rawDataObj, function(outer_index, outer_obj) {
                strs.alt_type += outer_obj.key + "\t";
                $.each(outer_obj.values, function(inner_key, inner_obj) {
                    if (Object.keys(inner_obj).length === 2) {
                        strs.alt_type += "  " + "\t";
                    } else {
                        strs.alt_type += "altered" + "\t";
                    }
                });
                strs.alt_type += "\n";
            });
        },
        calc_case_affected = function() {
            $.each(_rawDataObj, function(outer_index, outer_obj) {
                $.each(outer_obj.values, function(inner_index, inner_obj) {
                    if (Object.keys(inner_obj).length !== 2) {
                        strs.case_affected += outer_obj.key + "\n";
                        return false;
                    }
                });
            });
        },
        calc_case_matrix = function() {
            $.each(_rawDataObj, function(outer_index, outer_obj) {
                var _affected = false;
                $.each(outer_obj.values, function(inner_index, inner_obj) {
                    if (Object.keys(inner_obj).length !== 2) {
                        _affected = true;
                        return false;
                    }

                });
                if (_affected) strs.case_matrix += outer_obj.key + "\t" + "1" + "\n";
                else strs.case_matrix += outer_obj.key + "\t" + "0" + "\n";
            });
        };

    function processData() {
        calc_alt_freq();
        calc_alt_type();
        calc_case_affected();
        calc_case_matrix();
    }

    function renderDownloadLinks() {
        $("#data_downlonad_links_li").append();
    }

    function renderTextareas() {
        $("#text_area_gene_alteration_freq").append(strs.alt_freq);
        $("#text_area_gene_alteration_type").append(strs.alt_type);
        $("#text_area_case_affected").append(strs.case_affected);
        $("#text_area_case_matrix").append(strs.case_matrix);
    }

    return {
        setInput: function(_inputData) {
            _rawDataObj = _inputData;
        },
        setStat: function(_inputData) {
            _rawStatObj = _inputData;
        },
        init: function() {
            processData();
            renderDownloadLinks();
            renderTextareas();
            _isRendered = true;
        },
        isRendered: function() {
            return _isRendered;
        }
    };

}());

$(document).ready( function() {

    //Sign up getting oncoprint data
    PortalDataCollManager.subscribeOncoprint(function() {
        DataDownloadTab.setInput(PortalDataColl.getOncoprintData());
    });
    PortalDataCollManager.subscribeOncoprintStat(function() {
        DataDownloadTab.setStat(PortalDataColl.getOncoprintStat());
    });

});

//Bind tab clicking event listener
$("#tabs").bind("tabsactivate", function(event, ui) {
    if (ui.newTab.text().trim().toLowerCase() === "download") {
        if (!DataDownloadTab.isRendered()) {
            DataDownloadTab.init();
        }
    }
});
if ($("#data_download").is(":visible")) {
    if (!DataDownloadTab.isRendered()) {
        DataDownloadTab.init();
    }
}
<commit_msg>sorted the samples by narual/original order<commit_after>var DataDownloadTab = (function() {

    var _rawDataObj = [],
        _rawStatObj = {};

    var data = [],
        stat = {};

    var _isRendered = false;

    var strs = {
        alt_freq: "",
        alt_type: "",
        case_affected: "",
        case_matrix: ""
    };

    var calc_alt_freq = function() {
            strs.alt_freq = "GENE_SYMBOL" + "\t" + "NUM_CASES_ALTERED" + "\t" + "PERCENT_CASES_ALTERED" + "\n";
            $.each(stat, function(key, value) {
                strs.alt_freq += key + "\t" + value.total_alter_num + "\t" + value.percent + "%" + "\n";
            });
        },
        calc_alt_type = function() {
            strs.alt_type = "Case ID" + "\t";
            $.each(Object.keys(stat), function(index, val) {
                strs.alt_type += val + "\t";
            });
            strs.alt_type += "\n";
            $.each(data, function(outer_index, outer_obj) {
                strs.alt_type += outer_obj.key + "\t";
                $.each(outer_obj.values, function(inner_key, inner_obj) {
                    if (Object.keys(inner_obj).length === 2) {
                        strs.alt_type += "  " + "\t";
                    } else {
                        strs.alt_type += "altered" + "\t";
                    }
                });
                strs.alt_type += "\n";
            });
        },
        calc_case_affected = function() {
            $.each(data, function(outer_index, outer_obj) {
                $.each(outer_obj.values, function(inner_index, inner_obj) {
                    if (Object.keys(inner_obj).length !== 2) {
                        strs.case_affected += outer_obj.key + "\n";
                        return false;
                    }
                });
            });
        },
        calc_case_matrix = function() {
            $.each(data, function(outer_index, outer_obj) {
                var _affected = false;
                $.each(outer_obj.values, function(inner_index, inner_obj) {
                    if (Object.keys(inner_obj).length !== 2) {
                        _affected = true;
                        return false;
                    }

                });
                if (_affected) strs.case_matrix += outer_obj.key + "\t" + "1" + "\n";
                else strs.case_matrix += outer_obj.key + "\t" + "0" + "\n";
            });
        };

    function processData() {
        //sort the data arra by original sample order
        $.each(window.PortalGlobals.getSampleIds(), function(index, sampleId) {
            $.grep(_rawDataObj, function( n, i ) {
                if (n.key === sampleId) {
                    data.push(n);
                }
            });
        });
        //set status object
        stat = _rawStatObj;

        //Calculation and configuration of the textarea strings
        calc_alt_freq();
        calc_alt_type();
        calc_case_affected();
        calc_case_matrix();
    }

    function renderDownloadLinks() {
        $("#data_downlonad_links_li").append();
    }

    function renderTextareas() {
        $("#text_area_gene_alteration_freq").append(strs.alt_freq);
        $("#text_area_gene_alteration_type").append(strs.alt_type);
        $("#text_area_case_affected").append(strs.case_affected);
        $("#text_area_case_matrix").append(strs.case_matrix);
    }

    return {
        setInput: function(_inputData) {
            _rawDataObj = _inputData;
        },
        setStat: function(_inputData) {
            _rawStatObj = _inputData;
        },
        init: function() {
            processData();
            renderDownloadLinks();
            renderTextareas();
            _isRendered = true;
        },
        isRendered: function() {
            return _isRendered;
        }
    };

}());

$(document).ready( function() {

    //Sign up getting oncoprint data
    PortalDataCollManager.subscribeOncoprint(function() {
        DataDownloadTab.setInput(PortalDataColl.getOncoprintData());
    });
    PortalDataCollManager.subscribeOncoprintStat(function() {
        DataDownloadTab.setStat(PortalDataColl.getOncoprintStat());
    });

});

//Bind tab clicking event listener
$("#tabs").bind("tabsactivate", function(event, ui) {
    if (ui.newTab.text().trim().toLowerCase() === "download") {
        if (!DataDownloadTab.isRendered()) {
            DataDownloadTab.init();
        }
    }
});
if ($("#data_download").is(":visible")) {
    if (!DataDownloadTab.isRendered()) {
        DataDownloadTab.init();
    }
}
<|endoftext|>


<commit_before>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function CB(id) {
    this.btServiceIds = ['ae0e019cef7511e981b42a2ae2dbcce4'];

    this._id = id;
    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._position = 0;
    this._stepsPerUnit = 1;
    this._backlash = 0;
    this._lastDirection = 0;
}

util.inherits(CB, EventEmitter);

CB.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('CB(' + self._id + '): connecting via BLE');
        setTimeout(function(){
            btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
                if (services && services[0]) {
                    services[0].discoverCharacteristics([], function(err, characteristics) {
                        //console.log("characteristics:", characteristics);
                        self._writeCh = null;
                        self._readCh = null;
                        self._dev = null;
                        for (var i = 0; i < characteristics.length; i++) {
                            ch = characteristics[i];
                            //console.log("ch.uuid", ch.uuid);
                            //console.log("ch", ch);
                            if (ch.uuid == "ae0e0408ef7511e981b42a2ae2dbcce4") {
                                self._writeCh = ch;
                            } else if (ch.uuid == "ae0e055cef7511e981b42a2ae2dbcce4") {
                                self._readCh = ch;
                            }
                        }
                        if (self._writeCh && self._readCh) {
                            var failures = 0;
                            var first = true;
                            var tryRead = function() {
                                if(failures > 5) {
                                    btPeripheral.disconnect();
                                    console.log("CB(" + self._id + "): reading failed, disconnecting");
                                    if (first && callback) callback(false);
                                }
                                try {
                                    //console.log("CB(" + self._id + "): subscribing...");
                                    if(first) {
                                        self._readCh.read(function(){
                                            console.log("CB(" + self._id + "): read requested");
                                            self._dev = btPeripheral;
                                            self._dev.connected = true;
                                            self.connected = true;
                                            self._dev.type = "bt";
                                            console.log("CB(" + self._id + "): connected!");
                                            self._init();
                                            if (callback) callback(true);
                                        });
                                        first = false;
                                    }
                                    //if(self.connected) setTimeout(tryRead, 100);
                                    self._readCh.on('data', function(data, isNotification) {
                                        console.log("CB(" + self._id + "): data read:", data);
                                        self._parseIncoming(data);
                                    });
                                } catch(err3) {
                                    btPeripheral.disconnect();
                                    console.log("CB(" + self._id + "): exception while connecting: ", err3);
                                    if (first && callback) callback(false);
                                }

                            }
                            tryRead();
                        } else {
                            console.log("CB(" + self._id + "): couldn't locate characteristics, disconnecting... ", err);
                            btPeripheral.disconnect();
                            if (callback) callback(false);
                        }
                    });
                } else {
                    console.log("CB(" + self._id + "): couldn't locate services, disconnecting... ", err2);
                    btPeripheral.disconnect();
                    if (callback) callback(false);
                }

            });
        }, 1000);

        btPeripheral.once('disconnect', function() {
            console.log("CB(" + self._id + "): disconnected");
            self._dev = null;
            self.connected = false;
            //clearInterval(self.statusIntervalHandle);
            self.emit("status", self.getStatus());
        });

    });
}

CB.prototype._init = function() {
    var self = this;
    self._writeCh.write(new Buffer("S\n"));
    self.emit("status", self.getStatus());
}

CB.prototype._parseIncoming = function(data) {
    if(data.length != 5) return;

    this._moving = data.readUInt8(0) & 0x01;
    this._position = data.readUInt32LE(1);

    console.log("CB(" + this._id + "): moving: ", this._moving, ", position:", this._position);
}

CB.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        this._moving = false;
        console.log("CB(" + this._id + "): connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("CB(" + this._id + "): invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

CB.prototype.disconnect = function() {
    console.log("CB(" + this._id + "): disconnecting...");
    if (this._dev && this._dev.connected) {
        this.connected = false;
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

CB.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: (this._dev && this._dev.connected) ? true : false,
        connectionType: type,
        position: this._position / this._stepsPerUnit,
        backlash: this._backlash,
        moving: this._moving
    }
}

CB.prototype.disable = function(motor) {
    this._enabled = false;
}

CB.prototype.enable = function(motor) {
    this._enabled = true;
}

CB.prototype.move = function(motor, amount, callback) {
    if (this._moving) {
        if (callback) callback("CB(" + this._id + "): motor already running");
        return console.log("CB(" + this._id + "): motor already running");
    }

    var steps = Math.round(amount * this._stepsPerUnit);

    console.log("CB(" + this._id + "): moving motor", steps, "steps");
    if(!this._enabled) this.enable();

    this._moving = true;

    var self = this;
    self._writeCh.write(new Buffer('M' + steps.toString()), function(err) {
        self._moving = true;
        if (!err) {
            var n = 0;
            var check = function() {
                setTimeout(function() {
                    if(self._moving || self._moving === undefined) {
                        n++;
                        if(n > 500) {
                            console.log("CB(" + self._id + "): ERROR: timed out waiting for move");
                            if (callback) callback("timeout");
                            self._moving = false;
                        } else {
                            check(); // keep checking until stop
                        }
                    } else {
                        console.log("CB(" + self._id + "): position:", self._position);
                        if (callback) callback(null, self._position / self._stepsPerUnit);
                    }
                }, 300);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

CB.prototype.constantMove = function(motor, speed, callback) {
    console.log("CB(" + this._id + "): moving motor at speed ", speed, "%");
    if(!this._enabled) this.enable();

    var self = this;

    self._constantSpeed = speed;

    if(self._watchdog) {
        clearTimeout(self._watchdog);
        self._watchdog = null;
    }
    if(self._moveTimer) {
        clearTimeout(self._moveTimer);
        self._moveTimer = null;
    }
    if(speed) {
        self._watchdog = setTimeout(function(){
            console.log("CB(" + self._id + "): stopping via watchdog");
            self._constantSpeed = 0;
            clearTimeout(self._moveTimer);
            self._moveTimer = null;
        }, 3000);
    }

    var sendMove = function() {
        if(self._constantSpeed) {
            self.move(motor, self._constantSpeed, function() {
                if (callback) callback(null, self._position / self._stepsPerUnit);
                if(speed) {
                    self._moveTimer = setTimeout(function() {
                        sendMove();
                    }, 100);
                }
            });
        } else {
            if (callback) callback(null, self._position / self._stepsPerUnit);
        }
    }
    sendMove();
}

CB.prototype.resetMotorPosition = function(motor, callback) {
    this.setMotorPosition(motor, 0, callback);
}

CB.prototype.setMotorPosition = function(motor, position, callback) {
    var self = this;
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            if(!position) position = 0;
            self._position = Math.round(position);
            self._writeCh.write(new Buffer('P' + self._position.toString()));
            if (callback) callback();
        }
    }
    check();
}

CB.prototype.setMotorBacklash = function(motor, backlash, callback) {
    this._backlash = backlash;
    if (callback) callback(this._backlash);
}

CB.prototype.getMotorBacklash = function(motor, callback) {
    if (callback) callback(this._backlash);
}

module.exports = CB;
<commit_msg>motion testing<commit_after>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function CB(id) {
    this.btServiceIds = ['ae0e019cef7511e981b42a2ae2dbcce4'];

    this._id = id;
    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._position = 0;
    this._stepsPerUnit = 1;
    this._backlash = 0;
    this._lastDirection = 0;
}

util.inherits(CB, EventEmitter);

CB.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('CB(' + self._id + '): connecting via BLE');
        setTimeout(function(){
            btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
                if (services && services[0]) {
                    services[0].discoverCharacteristics([], function(err, characteristics) {
                        //console.log("characteristics:", characteristics);
                        self._writeCh = null;
                        self._readCh = null;
                        self._dev = null;
                        for (var i = 0; i < characteristics.length; i++) {
                            ch = characteristics[i];
                            //console.log("ch.uuid", ch.uuid);
                            //console.log("ch", ch);
                            if (ch.uuid == "ae0e0408ef7511e981b42a2ae2dbcce4") {
                                self._writeCh = ch;
                            } else if (ch.uuid == "ae0e055cef7511e981b42a2ae2dbcce4") {
                                self._readCh = ch;
                            }
                        }
                        if (self._writeCh && self._readCh) {
                            var failures = 0;
                            var first = true;
                            var tryRead = function() {
                                if(failures > 5) {
                                    btPeripheral.disconnect();
                                    console.log("CB(" + self._id + "): reading failed, disconnecting");
                                    if (first && callback) callback(false);
                                }
                                try {
                                    //console.log("CB(" + self._id + "): subscribing...");
                                    if(first) {
                                        self._readCh.subscribe(function(){
                                            console.log("CB(" + self._id + "): read requested");
                                            self._dev = btPeripheral;
                                            self._dev.connected = true;
                                            self.connected = true;
                                            self._dev.type = "bt";
                                            console.log("CB(" + self._id + "): connected!");
                                            self._init();
                                            if (callback) callback(true);
                                        });
                                        first = false;
                                    }
                                    //if(self.connected) setTimeout(tryRead, 100);
                                    self._readCh.on('data', function(data, isNotification) {
                                        console.log("CB(" + self._id + "): data read:", data);
                                        self._parseIncoming(data);
                                    });
                                } catch(err3) {
                                    btPeripheral.disconnect();
                                    console.log("CB(" + self._id + "): exception while connecting: ", err3);
                                    if (first && callback) callback(false);
                                }

                            }
                            tryRead();
                        } else {
                            console.log("CB(" + self._id + "): couldn't locate characteristics, disconnecting... ", err);
                            btPeripheral.disconnect();
                            if (callback) callback(false);
                        }
                    });
                } else {
                    console.log("CB(" + self._id + "): couldn't locate services, disconnecting... ", err2);
                    btPeripheral.disconnect();
                    if (callback) callback(false);
                }

            });
        }, 1000);

        btPeripheral.once('disconnect', function() {
            console.log("CB(" + self._id + "): disconnected");
            self._dev = null;
            self.connected = false;
            //clearInterval(self.statusIntervalHandle);
            self.emit("status", self.getStatus());
        });

    });
}

CB.prototype._init = function() {
    var self = this;
    self._writeCh.write(new Buffer("S\n"));
    self.emit("status", self.getStatus());
}

CB.prototype._parseIncoming = function(data) {
    if(data.length != 5) return;

    this._moving = data.readUInt8(0) & 0x01;
    this._position = data.readUInt32LE(1);

    console.log("CB(" + this._id + "): moving: ", this._moving, ", position:", this._position);
}

CB.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        this._moving = false;
        console.log("CB(" + this._id + "): connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("CB(" + this._id + "): invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

CB.prototype.disconnect = function() {
    console.log("CB(" + this._id + "): disconnecting...");
    if (this._dev && this._dev.connected) {
        this.connected = false;
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

CB.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: (this._dev && this._dev.connected) ? true : false,
        connectionType: type,
        position: this._position / this._stepsPerUnit,
        backlash: this._backlash,
        moving: this._moving
    }
}

CB.prototype.disable = function(motor) {
    this._enabled = false;
}

CB.prototype.enable = function(motor) {
    this._enabled = true;
}

CB.prototype.move = function(motor, amount, callback) {
    if (this._moving) {
        if (callback) callback("CB(" + this._id + "): motor already running");
        return console.log("CB(" + this._id + "): motor already running");
    }

    var steps = Math.round(amount * this._stepsPerUnit);

    console.log("CB(" + this._id + "): moving motor", steps, "steps");
    if(!this._enabled) this.enable();

    this._moving = true;

    var self = this;
    self._writeCh.write(new Buffer('M' + steps.toString()), function(err) {
        self._moving = true;
        if (!err) {
            var n = 0;
            var check = function() {
                setTimeout(function() {
                    if(self._moving || self._moving === undefined) {
                        n++;
                        if(n > 500) {
                            console.log("CB(" + self._id + "): ERROR: timed out waiting for move");
                            if (callback) callback("timeout");
                            self._moving = false;
                        } else {
                            check(); // keep checking until stop
                        }
                    } else {
                        console.log("CB(" + self._id + "): position:", self._position);
                        if (callback) callback(null, self._position / self._stepsPerUnit);
                    }
                }, 300);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

CB.prototype.constantMove = function(motor, speed, callback) {
    console.log("CB(" + this._id + "): moving motor at speed ", speed, "%");
    if(!this._enabled) this.enable();

    var self = this;

    self._constantSpeed = speed;

    if(self._watchdog) {
        clearTimeout(self._watchdog);
        self._watchdog = null;
    }
    if(self._moveTimer) {
        clearTimeout(self._moveTimer);
        self._moveTimer = null;
    }
    if(speed) {
        self._watchdog = setTimeout(function(){
            console.log("CB(" + self._id + "): stopping via watchdog");
            self._constantSpeed = 0;
            clearTimeout(self._moveTimer);
            self._moveTimer = null;
        }, 3000);
    }

    var sendMove = function() {
        if(self._constantSpeed) {
            self.move(motor, self._constantSpeed, function() {
                if (callback) callback(null, self._position / self._stepsPerUnit);
                if(speed) {
                    self._moveTimer = setTimeout(function() {
                        sendMove();
                    }, 100);
                }
            });
        } else {
            if (callback) callback(null, self._position / self._stepsPerUnit);
        }
    }
    sendMove();
}

CB.prototype.resetMotorPosition = function(motor, callback) {
    this.setMotorPosition(motor, 0, callback);
}

CB.prototype.setMotorPosition = function(motor, position, callback) {
    var self = this;
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            if(!position) position = 0;
            self._position = Math.round(position);
            self._writeCh.write(new Buffer('P' + self._position.toString()));
            if (callback) callback();
        }
    }
    check();
}

CB.prototype.setMotorBacklash = function(motor, backlash, callback) {
    this._backlash = backlash;
    if (callback) callback(this._backlash);
}

CB.prototype.getMotorBacklash = function(motor, callback) {
    if (callback) callback(this._backlash);
}

module.exports = CB;
<|endoftext|>


<commit_before>const alasql = require('alasql');

const stringConcat = function stringConcat(...stringToConcat) {
  let fullString = '';
  for (let index = 0; index < stringToConcat.length; index+=1) {
    fullString += stringToConcat[index];
  }
  return fullString;
};

const sqlCommands = function sqlCommands() {
  this.getFullTableData = function getFullTableData(tableName) {
    return alasql(stringConcat('SELECT * FROM ', tableName));
  };

  this.createTable = function createTable(sqlStatement) {
    alasql(sqlStatement);
  };

  this.deleteTable = function deleteTable(tableName) {
    alasql(stringConcat('DROP TABLE ', tableName));
  };
};
<commit_msg>Add cleanTable function into sqlCommands.js<commit_after>const alasql = require('alasql');

const stringConcat = function stringConcat(...stringToConcat) {
  let fullString = '';
  for (let index = 0; index < stringToConcat.length; index+=1) {
    fullString += stringToConcat[index];
  }
  return fullString;
};

const sqlCommands = function sqlCommands() {
  this.getFullTableData = function getFullTableData(tableName) {
    return alasql(stringConcat('SELECT * FROM ', tableName));
  };

  this.createTable = function createTable(sqlStatement) {
    alasql(sqlStatement);
  };

  this.deleteTable = function deleteTable(tableName) {
    alasql(stringConcat('DROP TABLE ', tableName));
  };

  this.cleanTable = function cleanTable(tableName) {
    alasql(stringConcat('DELETE * FROM ', tableName));
  };
};
<|endoftext|>


<commit_before>import Rx from 'rx'
const merge = Rx.Observable.merge
const of = Rx.Observable.of
const scase = Rx.Observable.case

import { exists, getExtension, getNameAndExtension, isValidFile, isEmpty } from './utils'

import { equals, cond, T, always } from 'ramda'
import { combineLatestObj } from './obsUtils'
import { mergeData } from './modelUtils'
import assign from 'fast.js/object/assign' // faster object.assign

import { postProcessParsedData } from './parseUtils'

function getParser (extension) {
  return lazyLoad(extension)
}

function lazyLoad (moduleNamePath) {
  let obs = new Rx.ReplaySubject(1)
  // let waitForChunk = require('dynamic?' + moduleNamePath)

  // require("bundle?lazy!usco-ctm-parser")(function(module) {
  // const requireStr = `bundle?lazy!./node_modules/${moduleNamePath}`
  // const requireStr = `bundle?lazy!./`
  // let req = require.context("./node-modules", true, /^\.\/.*\.jade$/)
  // const requireStr = `bundle?lazy!./node_modules/${moduleNamePath}/lib/ctm-parser.js`

  // var req = require.context('../../node_modules', true, /^\.\/.*\.js$/)

  /* require.ensure(['usco-ctm-parser'], function(require) {
    //require('usco-ctm-parser')
    let module = require(moduleNamePath)
    console.log("dynamic load of module",module)
    //obs.onNext(module)
  })*/
  /* require(requireStr)(function(module) {
    // now you can use the b-module
    console.log("dynamic load of module",module)
    obs.onNext(module)
  })*/
  // System.import('usco-ctm-parser').then(module=>console.log("module",module))

  // FIXME: awfull, horrible horrrible horrible
  // NOTE : chunk names can be specified like this : &name=stl-parser
  switch (moduleNamePath) {
    case 'stl':
      require('bundle?lazy!usco-stl-parser')(module => obs.onNext(module))
      break
    case 'ctm':
      require('bundle?lazy!usco-ctm-parser')(module => obs.onNext(module))
      break
    case 'obj':
      require('bundle?lazy!usco-obj-parser')(module => obs.onNext(module))
      break
    case '3mf':
      require('bundle?lazy!usco-3mf-parser')(module => obs.onNext(module))
      break
  }
  return obs
}

// this functions extracts data recieved from sources, adds error handling etc
function fetch (sources, sourceNames = ['http', 'desktop']) {
  const chosenSources = sourceNames
    .map(function (name) {
      return sources[name]
    })

  const fetched$ = merge(...chosenSources)
    .filter(res$ => res$.request.type === 'resource') // only responses we deal with are resources
    .flatMap(data => {
      const responseWrapper$ = data.catch(e => {
        console.log('caught error in fetching data', e)
        return Rx.Observable.empty()
      })
      const request$ = of(data.request)
      const response$ = responseWrapper$.pluck('response')
      const progress$ = responseWrapper$.pluck('progress')

      return combineLatestObj({response$, request$, progress$})
    })
    .share()
  return fetched$
}

// parse the data extracted from a fetched data observable
function parse (fetched$) {
  const parseBase$ = fetched$
    .filter(data => (data.response !== undefined && data.progress === undefined))
    // .distinctUntilChanged(d=>d.request.uri,equals)
    .shareReplay(1)

  const parsed$ = parseBase$
    .flatMap(function (data) {
      const {uri, id, flags} = data.request // extract uri & id if any
      const {name, ext} = getNameAndExtension(uri)

      // pack up the data, the parser etc nicely
      const data$ = of({uri, id, rawData: data.response, ext, name, flags})
      const parser$ = getParser(ext).pluck('default') // FIXME: for now workaround for es6 modules & babel
      return combineLatestObj({data$, parser$})
    })
    // actual parsing part
    .flatMap(function ({data, parser}) {
      const {rawData, uri, ext, name, id, flags} = data
      const parseOptions = {useWorker: true}

      const parsedObs$ = parser(rawData, parseOptions)
        .doOnError(e => console.log('error in parse', e))

      const parsedData$ = parsedObs$
        .filter(e => e.progress === undefined) // seperate out progress data
        .map(postProcessParsedData)
        // .tap(e=>console.log("parsedData",e))

      const progress$ = parsedObs$
        .filter(e => e.progress !== undefined) // keep ONLY progress data
        .pluck('progress')
        .distinctUntilChanged()
        .startWith(0)

      const meta$ = of({uri, ext, name, id, flags})

      // throw new Error("eeeelkj")

      return combineLatestObj({meta$, data: parsedData$, progress$})
    })
    .shareReplay(1)

  return parsed$
}

// helper function to output combine fetch & parse data
function computeCombinedProgress (fetched$, parsed$) {
  const fetchToParseRatio = 0.95

  function preProcess (selector, data$) {
    return data$
      .map(selector)
      // .distinctUntilChanged()
      .filter(d => exists(d.progress))
  }

  // we merge fetch information with parse information
  const progress$ = merge(
    preProcess(f => ({id: f.request.uri, progress: f.progress}), fetched$)
      .map(e => ({id: e.id, fetched: e.progress * fetchToParseRatio}))

    , preProcess(f => ({id: f.meta.uri, progress: f.progress}), parsed$)
      .map(e => ({id: e.id, parsed: e.progress * (1 - fetchToParseRatio)}))
  )

  const combinedProgress$ = progress$.scan(function (combined, entry) {
    const fetched = entry.fetched || fetchToParseRatio
    const parsed = entry.parsed || 0
    const progress = fetched + parsed

    combined.entries[entry.id] = progress

    let totalProgress = Object.keys(combined.entries)
      .reduce(function (acc, cur) {
        return acc + combined.entries[cur]
      }, 0)

    totalProgress /= Object.keys(combined.entries).length
    combined.totalProgress = totalProgress

    return combined
  }, {entries: {}, totalProgress: 0})
    .pluck('totalProgress')
    .distinctUntilChanged(null, equals)
    .debounce(10)

  return combinedProgress$
}

export function resources (sources) {
  const fetched$ = fetch(sources)
  const parsed$ = parse(fetched$)
  const combinedProgress$ = computeCombinedProgress(fetched$, parsed$)

  parsed$.catch(function (error) {
    console.log('error in parse', error)
  })

  return {combinedProgress$, parsed$}
}

/* const fn = cond([
  [equals(0),   always('water freezes at 0°C')],
  [equals(100), always('water boils at 100°C')],
  [T,           temp => 'nothing special happens at ' + temp + '°C']
])

console.log( fn(0) ) //=> 'water freezes at 0°C'
console.log( fn(50) ) //=> 'nothing special happens at 50°C'
console.log( fn(100) ) //=> 'water boils at 100°C'*/
<commit_msg>feat(assetManager): added better handling (ie throwing errors) for unsuported formats<commit_after>import Rx from 'rx'
const merge = Rx.Observable.merge
const of = Rx.Observable.of
const scase = Rx.Observable.case

import { exists, getExtension, getNameAndExtension, isValidFile, isEmpty } from './utils'

import { equals, cond, T, always } from 'ramda'
import { combineLatestObj } from './obsUtils'
import { mergeData } from './modelUtils'
import assign from 'fast.js/object/assign' // faster object.assign

import { postProcessParsedData } from './parseUtils'

function getParser (extension) {
  return lazyLoad(extension)
}

function lazyLoad (moduleNamePath) {
  let obs = new Rx.ReplaySubject(1)
  // let waitForChunk = require('dynamic?' + moduleNamePath)

  // require("bundle?lazy!usco-ctm-parser")(function(module) {
  // const requireStr = `bundle?lazy!./node_modules/${moduleNamePath}`
  // const requireStr = `bundle?lazy!./`
  // let req = require.context("./node-modules", true, /^\.\/.*\.jade$/)
  // const requireStr = `bundle?lazy!./node_modules/${moduleNamePath}/lib/ctm-parser.js`

  // var req = require.context('../../node_modules', true, /^\.\/.*\.js$/)

  /* require.ensure(['usco-ctm-parser'], function(require) {
    //require('usco-ctm-parser')
    let module = require(moduleNamePath)
    console.log("dynamic load of module",module)
    //obs.onNext(module)
  })*/
  /* require(requireStr)(function(module) {
    // now you can use the b-module
    console.log("dynamic load of module",module)
    obs.onNext(module)
  })*/
  // System.import('usco-ctm-parser').then(module=>console.log("module",module))

  // FIXME: awfull, horrible horrrible horrible
  // NOTE : chunk names can be specified like this : &name=stl-parser
  switch (moduleNamePath) {
    case 'stl':
      require('bundle?lazy!usco-stl-parser')(module => obs.onNext(module))
      break
    case 'ctm':
      require('bundle?lazy!usco-ctm-parser')(module => obs.onNext(module))
      break
    case 'obj':
      require('bundle?lazy!usco-obj-parser')(module => obs.onNext(module))
      break
    case '3mf':
      require('bundle?lazy!usco-3mf-parser')(module => obs.onNext(module))
      break
    /*case 'gcode':
      require('bundle?lazy!usco-3mf-parser')(module => obs.onNext(module))
      break*/
    default:
      obs.onError(`No parser for "${moduleNamePath}" format`)
  }
  return obs
}

// this functions extracts data recieved from sources, adds error handling etc
function fetch (sources, sourceNames = ['http', 'desktop']) {
  const chosenSources = sourceNames
    .map(function (name) {
      return sources[name]
    })

  const fetched$ = merge(...chosenSources)
    .filter(res$ => res$.request.type === 'resource') // only responses we deal with are resources
    .flatMap(data => {
      const responseWrapper$ = data.catch(e => {
        console.log('caught error in fetching data', e)
        return Rx.Observable.empty()
      })
      const request$ = of(data.request)
      const response$ = responseWrapper$.pluck('response')
      const progress$ = responseWrapper$.pluck('progress')

      return combineLatestObj({response$, request$, progress$})
    })
    .share()
  return fetched$
}

// parse the data extracted from a fetched data observable
function parse (fetched$) {
  const parseBase$ = fetched$
    .filter(data => (data.response !== undefined && data.progress === undefined))
    // .distinctUntilChanged(d=>d.request.uri,equals)
    .shareReplay(1)

  const parsed$ = parseBase$
    .flatMap(function (data) {
      const {uri, id, flags} = data.request // extract uri & id if any
      const {name, ext} = getNameAndExtension(uri)

      console.log('here')
      // pack up the data, the parser etc nicely
      const data$ = of({uri, id, rawData: data.response, ext, name, flags})
      const parser$ = getParser(ext).pluck('default') // FIXME: for now workaround for es6 modules & babel
        .tap(e=>console.log('parser',e))
      return combineLatestObj({data$, parser$})
    })
    // actual parsing part
    .flatMap(function ({data, parser}) {
      const {rawData, uri, ext, name, id, flags} = data
      const parseOptions = {useWorker: true}

      const parsedObs$ = parser(rawData, parseOptions)
        .doOnError(e => console.log('error in parse', e))

      const parsedData$ = parsedObs$
        .filter(e => e.progress === undefined) // seperate out progress data
        .map(postProcessParsedData)
        // .tap(e=>console.log("parsedData",e))

      const progress$ = parsedObs$
        .filter(e => e.progress !== undefined) // keep ONLY progress data
        .pluck('progress')
        .distinctUntilChanged()
        .startWith(0)

      const meta$ = of({uri, ext, name, id, flags})

      return combineLatestObj({meta$, data: parsedData$, progress$})
    })
    .shareReplay(1)

  return parsed$
}

// helper function to output combine fetch & parse data
function computeCombinedProgress (fetched$, parsed$) {
  const fetchToParseRatio = 0.95

  function preProcess (selector, data$) {
    return data$
      .map(selector)
      // .distinctUntilChanged()
      .filter(d => exists(d.progress))
  }

  // we merge fetch information with parse information
  const progress$ = merge(
    preProcess(f => ({id: f.request.uri, progress: f.progress}), fetched$)
      .map(e => ({id: e.id, fetched: e.progress * fetchToParseRatio}))

    , preProcess(f => ({id: f.meta.uri, progress: f.progress}), parsed$)
      .map(e => ({id: e.id, parsed: e.progress * (1 - fetchToParseRatio)}))
  )

  const combinedProgress$ = progress$.scan(function (combined, entry) {
    const fetched = entry.fetched || fetchToParseRatio
    const parsed = entry.parsed || 0
    const progress = fetched + parsed

    combined.entries[entry.id] = progress

    let totalProgress = Object.keys(combined.entries)
      .reduce(function (acc, cur) {
        return acc + combined.entries[cur]
      }, 0)

    totalProgress /= Object.keys(combined.entries).length
    combined.totalProgress = totalProgress

    return combined
  }, {entries: {}, totalProgress: 0})
    .pluck('totalProgress')
    .distinctUntilChanged(null, equals)
    .debounce(10)

  return combinedProgress$
}

export function resources (sources) {
  const fetched$ = fetch(sources)//.tap(e=>console.log('fetched',e))
  const parsed$ = parse(fetched$)
  const combinedProgress$ = computeCombinedProgress(fetched$, parsed$)

  parsed$.catch(function (error) {
    console.log('error in parse', error)
  })

  return {combinedProgress$, parsed$}
}

/* const fn = cond([
  [equals(0),   always('water freezes at 0°C')],
  [equals(100), always('water boils at 100°C')],
  [T,           temp => 'nothing special happens at ' + temp + '°C']
])

console.log( fn(0) ) //=> 'water freezes at 0°C'
console.log( fn(50) ) //=> 'nothing special happens at 50°C'
console.log( fn(100) ) //=> 'water boils at 100°C'*/
<|endoftext|>


<commit_before>const eventManager = {
  list: new Map(),

  on(event, callback) {
    this.list.has(event) || this.list.set(event, []);

    this.list.get(event).push(callback);

    return this;
  },

  off(event) {
    this.list.delete(event);
    return this;
  },

  emit(event, ...args) {
    if (!this.list.has(event)) {
      return false;
    }
    this.list
      .get(event)
      .forEach(callback => setTimeout(() => callback.call(null, ...args), 0));

    return true;
  }
};

export default eventManager;
<commit_msg>Call to emit is not defered anymore<commit_after>const eventManager = {
  list: new Map(),

  on(event, callback) {
    this.list.has(event) || this.list.set(event, []);
    this.list.get(event).push(callback);

    return this;
  },

  off(event) {
    this.list.delete(event);
    return this;
  },

  emit(event, ...args) {
    if (!this.list.has(event)) {
      return false;
    }

    this.list
      .get(event)
      .forEach(callback => callback.call(null, ...args));

    return true;
  }
};

export default eventManager;
<|endoftext|>


<commit_before>import WarningTextEnum from '../enums/WarningTextEnum';

let GeneralUtils = {
  isPromise: (value) => {
    return value && (typeof value.then === 'function');
  },
  serializeFunction: (fn) => {
    return encodeURI(fn.toString());
  },
  deSerializeFunction: (fn) => {
    return decodeURI(fn);
  },
  serializeError: (error) => {
    let i, err = {},
      errProps = [ 'name', 'message', 'stack', 'custom' ];

    if (error instanceof Error) {
      for (i = errProps.length - 1; i >= 0; i--) {
        err[errProps[i]] = error[errProps[i]];
      }
      return err;
    }

    return err;
  },
  deSerializeError: (error) => {
    let i, fakeError = new Error('');

    if (!error) {
      return new Error('');
    }

    let props = Object.keys(error);

    for (i = 0; i < props.length; i++) {
      fakeError[props[i]] = error[props[i]];
    }

    return fakeError;
  },
  /**
   * Stringify Object
   * @param  {String} data
   * @param  {String} err  - Message to be thrown if not valid object
   * @return {Object}      - stringified json
   */
  stringifyJson: function (data, err) {
    err = err || WarningTextEnum.INVALID_JSON;
    try {
      data = JSON.stringify(data);
    } catch (e) {
      console.warn(err);
    }

    return data;
  },
  /**
   * Parse sringified data
   * @param  {String} data
   * @param  {String} err  - Message to be thrown if not valid json
   * @return {Object}      - parsed json
   */
  parseJson: function (data, err) {
    let jsonParsedData;

    err = err || WarningTextEnum.PARSE_JSON;
    try {
      jsonParsedData = JSON.parse(data);
    } catch (e) {
      console.warn(err);
    }

    return jsonParsedData;
  }
};

export default GeneralUtils;
<commit_msg>checking typeof, only functions allowed to be serialized and desrialized<commit_after>import WarningTextEnum from '../enums/WarningTextEnum';

let GeneralUtils = {
  isPromise: (value) => {
    return value && (typeof value.then === 'function');
  },
  serializeFunction: (fn) => {
    if (!fn || typeof fn !== 'function') { return false; }

    return encodeURI(fn.toString());
  },
  deSerializeFunction: (fn) => {
    if (!fn || typeof fn !== 'string') { return false; }

    return decodeURI(fn);
  },
  serializeError: (error) => {
    let i, err = {},
      errProps = [ 'name', 'message', 'stack', 'custom' ];

    if (error instanceof Error) {
      for (i = errProps.length - 1; i >= 0; i--) {
        err[errProps[i]] = error[errProps[i]];
      }
      return err;
    }

    return err;
  },
  deSerializeError: (error) => {
    let i, fakeError = new Error('');

    if (!error) {
      return fakeError;
    }

    let props = Object.keys(error);

    for (i = 0; i < props.length; i++) {
      fakeError[props[i]] = error[props[i]];
    }

    return fakeError;
  },
  /**
   * Stringify Object
   * @param  {String} data
   * @param  {String} err  - Message to be thrown if not valid object
   * @return {Object}      - stringified json
   */
  stringifyJson: function (data, err) {
    err = err || WarningTextEnum.INVALID_JSON;
    try {
      data = JSON.stringify(data);
    } catch (e) {
      console.warn(err);
    }

    return data;
  },
  /**
   * Parse sringified data
   * @param  {String} data
   * @param  {String} err  - Message to be thrown if not valid json
   * @return {Object}      - parsed json
   */
  parseJson: function (data, err) {
    let jsonParsedData;

    err = err || WarningTextEnum.PARSE_JSON;
    try {
      jsonParsedData = JSON.parse(data);
    } catch (e) {
      console.warn(err);
    }

    return jsonParsedData;
  }
};

export default GeneralUtils;
<|endoftext|>


<commit_before>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import electron from 'electron';

const _isProduction = !/node_modules[\\/]electron[\\/]/.test(
  // $FlowFixMe: execPath exists, but is not in electron API spec
  electron.remote.process.execPath,
);

export default function isProduction(): boolean {
  return _isProduction;
}
<commit_msg>Log to infinity_analytics_dev scribe cat in non-prod<commit_after>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import electron from 'electron';

const _isProduction = !/node_modules[\\/]electron[\\/]/.test(
  // $FlowFixMe: execPath exists, but is not in electron API spec
  process.execPath || electron.remote.process.execPath,
);

export default function isProduction(): boolean {
  return _isProduction;
}
<|endoftext|>