<commit_before>/*
JavaScript misc library.
https://github.com/mas3/javascript-mas

The MIT License (MIT)

Copyright (c) 2013 MASUDA Takashi

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 * @namespace
 */
var mas = {};

mas.dateLocales = {
    en: {
        ddd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        dddd: [
            'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
            'Saturday'],
        MMM: [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'],
        MMMM: [
            'January', 'February', 'March', 'April', 'May', 'June', 'July',
            'August', 'September', 'October', 'November', 'December'],
        tt: ['AM', 'PM']
    },
    ja: {
        ddd: ['日', '月', '火', '水', '木', '金', '土'],
        dddd: [
            '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日',
            '土曜日'],
        MMM: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
        MMMM: [
            '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月',
            '10月', '11月', '12月'],
        tt: ['午前', '午後']
    }
};

/**
 * Returns the smallest integer greater than or equal to a value.
 * @param  {Number} val value.
 * @param  {Number} [precision=0] number of fractional digits.
 * @return {Number} rounded up value.
 */
mas.ceil = function (val, precision) {
    precision = precision || 0;
    return Math.ceil(val * Math.pow(10, precision)) / Math.pow(10, precision);
};

/**
 * Date Formatting.
 * @param  {Date} date date.
 * @param  {String} format format string.
 * @param  {String} [lang='en'] language.
 * @return {String} formatted string.
 * @example
 * mas.dateFormat(date, "yyyy-MM-dd HH:mm:ss");
 * // Format:
 * //   d    Day of month(1-31)
 * //   dd   Day of month(01-31)
 * //   ddd  Day name(abbreviated)
 * //   dddd Day name(full)
 * //   H    Hours(0-23)
 * //   HH   Hours(01-23)
 * //   h    Hours(1-12)
 * //   hh   Hours(01-12)
 * //   M    Month of year(1-12)
 * //   MM   Month of year(01-12)
 * //   MMM  Month name(abbreviated)
 * //   MMMM Month name(full)
 * //   m    Minutes(0-59)
 * //   mm   Minutes(00-59)
 * //   s    Seconds(0-59)
 * //   ss   Seconds(00-59)
 * //   t    AM/PM(first character)
 * //   tt   AM/PM
 * //   yy   Year(00-99)
 * //   yyyy Year
 */
mas.dateFormat = function (date, format, lang) {
    var dateLocale = mas.dateLocales[lang] || mas.dateLocales.en,
        pad = function (val, length) { return mas.lpad(val, length, '0'); },
        f;

    f = {
        d: function (date) { return date.getDate() + ""; },
        dd: function (date) { return pad(date.getDate(), 2); },
        ddd: function (date, lang) { return dateLocale.ddd[date.getDay()]; },
        dddd: function (date, lang) { return dateLocale.dddd[date.getDay()]; },
        H: function (date) { return date.getHours() + ""; },
        HH: function (date) { return pad(date.getHours(), 2); },
        h: function (date) { return (date.getHours() % 12 || 12) + ""; },
        hh: function (date) { return pad(f.h(date), 2); },
        M: function (date) { return date.getMonth() + 1 + ""; },
        MM: function (date) { return pad(date.getMonth() + 1, 2); },
        MMM: function (date, lang) { return dateLocale.MMM[date.getMonth()]; },
        MMMM: function (date, lang) {
                return dateLocale.MMMM[date.getMonth()];
            },
        m: function (date) { return date.getMinutes() + ""; },
        mm: function (date) {return pad(date.getMinutes(), 2); },
        s: function (date) { return date.getSeconds() + ""; },
        ss: function (date) {return pad(date.getSeconds(), 2); },
        t: function (date, lang) { return f.tt(date, lang).charAt(0); },
        tt: function (date, lang) {
                return dateLocale.tt[date.getHours() < 12 ? 0 : 1];
            },
        yy: function (date) {
               return pad(Math.abs(date.getFullYear() % 100), 2);
            },
        yyyy: function (date) { return date.getFullYear() + ""; }
    };

    return format.replace(
        /(dddd|ddd|dd|d|HH|H|hh|h|MMMM|MMM|MM|M|mm|m|ss|s|tt|t|yyyy|yy)/g,
        function () {
            var specifier = arguments[1];
            return f[specifier](date, lang) || specifier;
        });
};

/**
 * Returns the largest integer less than or equal to a value.
 * @param  {Number} val value.
 * @param  {Number} [precision=0] number of fractional digits.
 * @return {Number} rounded down value.
 */
mas.floor = function (val, precision) {
    precision = precision || 0;
    return Math.floor(val * Math.pow(10, precision)) / Math.pow(10, precision);
};

/**
 * Replaces each format item in values.
 * @param  {String} format format string.
 * @param  {...*} var_args replace values.
 * @return {String} replaced string.
 * @example
 * mas.format("{0} = {1}", key, value);
 */
mas.format = function (format, var_args) {
    var items = arguments;
    return format.replace(/\{([0-9]+)\}/g, function () {
        var replaceString = items[+arguments[1] + 1];
        if (mas.isBlank(replaceString)) {
            return "";
        }
        return replaceString;
    });
};

/**
 * Indicates whether the specified value is blank(undefined or null or
 * empty string).
 * @param  {String} val value.
 * @return {String} true if the val parameter is blank; otherwise, false.
 */
mas.isBlank = function (val) {
    return val === undefined || val === null || val === "";
};

/**
 * Browser language.
 * @return {String} 2 character language code.
 */
mas.language = function () {
    return (
        navigator.browserLanguage ||
        navigator.language ||
        navigator.userLanguage).substr(0,2);
};

/**
 * Pad a string with a set of characters from the left side.
 * @param  {String} val base value.
 * @param  {String} paddedLength number of characters.
 * @param  {String} [padChar= SPACE] pad character.
 * @return {String} padded value.
 */
mas.lpad = function (val, paddedLength, padChar) {
    var str = val + "",
        length = str.length,
        i;
    if (length >= paddedLength) {
        return str;
    }
    if (mas.isBlank(padChar)) {
        padChar = ' ';
    }
    for (i = length; i < paddedLength; i++) {
        str = padChar + str;
    }
    return str;
};

/**
 * Rounds a value.
 * @param  {Number} val value.
 * @param  {Number} [precision=0] number of fractional digits.
 * @return {Number} rounded value.
 */
mas.round = function (val, precision) {
    precision = precision || 0;
    return Math.round(val * Math.pow(10, precision)) / Math.pow(10, precision);
};
<commit_msg>Refactoring dateFormat method.<commit_after>/*
JavaScript misc library.
https://github.com/mas3/javascript-mas

The MIT License (MIT)

Copyright (c) 2013 MASUDA Takashi

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 * @namespace
 */
var mas = {};

mas.dateLocales = {
    en: {
        ddd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        dddd: [
            'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
            'Saturday'],
        MMM: [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'],
        MMMM: [
            'January', 'February', 'March', 'April', 'May', 'June', 'July',
            'August', 'September', 'October', 'November', 'December'],
        tt: ['AM', 'PM']
    },
    ja: {
        ddd: ['日', '月', '火', '水', '木', '金', '土'],
        dddd: [
            '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日',
            '土曜日'],
        MMM: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
        MMMM: [
            '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月',
            '10月', '11月', '12月'],
        tt: ['午前', '午後']
    }
};

/**
 * Returns the smallest integer greater than or equal to a value.
 * @param  {Number} val value.
 * @param  {Number} [precision=0] number of fractional digits.
 * @return {Number} rounded up value.
 */
mas.ceil = function (val, precision) {
    precision = precision || 0;
    return Math.ceil(val * Math.pow(10, precision)) / Math.pow(10, precision);
};

/**
 * Date Formatting.
 * @param  {Date} date date.
 * @param  {String} format format string.
 * @param  {String} [lang='en'] language.
 * @return {String} formatted string.
 * @example
 * mas.dateFormat(date, "yyyy-MM-dd HH:mm:ss");
 * // Format:
 * //   d    Day of month(1-31)
 * //   dd   Day of month(01-31)
 * //   ddd  Day name(abbreviated)
 * //   dddd Day name(full)
 * //   H    Hours(0-23)
 * //   HH   Hours(01-23)
 * //   h    Hours(1-12)
 * //   hh   Hours(01-12)
 * //   M    Month of year(1-12)
 * //   MM   Month of year(01-12)
 * //   MMM  Month name(abbreviated)
 * //   MMMM Month name(full)
 * //   m    Minutes(0-59)
 * //   mm   Minutes(00-59)
 * //   s    Seconds(0-59)
 * //   ss   Seconds(00-59)
 * //   t    AM/PM(first character)
 * //   tt   AM/PM
 * //   yy   Year(00-99)
 * //   yyyy Year
 */
mas.dateFormat = function (date, format, lang) {
    var dateLocale = mas.dateLocales[lang] || mas.dateLocales.en,
        pad = function (val, length) { return mas.lpad(val, length, '0'); },
        f;

    f = {
        d: function (date) { return date.getDate() + ""; },
        dd: function (date) { return pad(date.getDate(), 2); },
        ddd: function (date, lang) { return dateLocale.ddd[date.getDay()]; },
        dddd: function (date, lang) { return dateLocale.dddd[date.getDay()]; },
        H: function (date) { return date.getHours() + ""; },
        HH: function (date) { return pad(date.getHours(), 2); },
        h: function (date) { return (date.getHours() % 12 || 12) + ""; },
        hh: function (date) { return pad(f.h(date), 2); },
        M: function (date) { return date.getMonth() + 1 + ""; },
        MM: function (date) { return pad(date.getMonth() + 1, 2); },
        MMM: function (date, lang) { return dateLocale.MMM[date.getMonth()]; },
        MMMM: function (date, lang) {
                return dateLocale.MMMM[date.getMonth()];
            },
        m: function (date) { return date.getMinutes() + ""; },
        mm: function (date) {return pad(date.getMinutes(), 2); },
        s: function (date) { return date.getSeconds() + ""; },
        ss: function (date) {return pad(date.getSeconds(), 2); },
        t: function (date, lang) { return f.tt(date, lang).charAt(0); },
        tt: function (date, lang) {
                return dateLocale.tt[date.getHours() < 12 ? 0 : 1];
            },
        yy: function (date) {
               return pad(Math.abs(date.getFullYear() % 100), 2);
            },
        yyyy: function (date) { return date.getFullYear() + ""; }
    };

    return format.replace(
        /(dddd|ddd|dd|d|HH|H|hh|h|MMMM|MMM|MM|M|mm|m|ss|s|tt|t|yyyy|yy)/g,
        function (specifier) {
            return f[specifier](date, lang) || specifier;
        });
};

/**
 * Returns the largest integer less than or equal to a value.
 * @param  {Number} val value.
 * @param  {Number} [precision=0] number of fractional digits.
 * @return {Number} rounded down value.
 */
mas.floor = function (val, precision) {
    precision = precision || 0;
    return Math.floor(val * Math.pow(10, precision)) / Math.pow(10, precision);
};

/**
 * Replaces each format item in values.
 * @param  {String} format format string.
 * @param  {...*} var_args replace values.
 * @return {String} replaced string.
 * @example
 * mas.format("{0} = {1}", key, value);
 */
mas.format = function (format, var_args) {
    var items = arguments;
    return format.replace(/\{([0-9]+)\}/g, function () {
        var replaceString = items[+arguments[1] + 1];
        if (mas.isBlank(replaceString)) {
            return "";
        }
        return replaceString;
    });
};

/**
 * Indicates whether the specified value is blank(undefined or null or
 * empty string).
 * @param  {String} val value.
 * @return {String} true if the val parameter is blank; otherwise, false.
 */
mas.isBlank = function (val) {
    return val === undefined || val === null || val === "";
};

/**
 * Browser language.
 * @return {String} 2 character language code.
 */
mas.language = function () {
    return (
        navigator.browserLanguage ||
        navigator.language ||
        navigator.userLanguage).substr(0,2);
};

/**
 * Pad a string with a set of characters from the left side.
 * @param  {String} val base value.
 * @param  {String} paddedLength number of characters.
 * @param  {String} [padChar= SPACE] pad character.
 * @return {String} padded value.
 */
mas.lpad = function (val, paddedLength, padChar) {
    var str = val + "",
        length = str.length,
        i;
    if (length >= paddedLength) {
        return str;
    }
    if (mas.isBlank(padChar)) {
        padChar = ' ';
    }
    for (i = length; i < paddedLength; i++) {
        str = padChar + str;
    }
    return str;
};

/**
 * Rounds a value.
 * @param  {Number} val value.
 * @param  {Number} [precision=0] number of fractional digits.
 * @return {Number} rounded value.
 */
mas.round = function (val, precision) {
    precision = precision || 0;
    return Math.round(val * Math.pow(10, precision)) / Math.pow(10, precision);
};
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-guess-player-levels@breunigs
// @name           IITC plugin: guess player level
// @version        0.4.3.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Tries to determine player levels from the data available in the current view
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

function wrapper() {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.guessPlayerLevels = function() {};

window.plugin.guessPlayerLevels.setupCallback = function() {
  $('#toolbox').append(' Guess player levels');
  addHook('portalAdded', window.plugin.guessPlayerLevels.extractPortalData);
}

// This function is intended to be called by other plugins
window.plugin.guessPlayerLevels.fetchLevelByPlayer = function(guid) {
  return(window.localStorage['level-' + guid]);
}

window.plugin.guessPlayerLevels._nameToGuidCache = {};

window.plugin.guessPlayerLevels.setLevelTitle = function(dom) {
  // expects dom node with nick in its child text node

  var el = $(dom);
  var nick = el.text();
  var guid = window.playerNameToGuid(nick);
  var level = guid ? localStorage['level-'+guid] : null;

  var text;
  if (level) {
    text = 'Min player level: ' + level;
    if(level < window.MAX_XM_PER_LEVEL.length - 1) text += ' (guessed)';
  } else {
    text = 'Min player level unknown';
  }
  window.setupTooltips(el);

  /*
  This code looks hacky but since we are a little late within the mouseenter so
  we need to improvise a little. The open method doesn't open the tooltip directly.
  It starts the whole opening procedure (including the timeout etc) and is normally
  started by the mousemove event of the enhanced element.
  */
  el.addClass('help') // Add the "Help Mouse Cursor"
    .attr('title', text) // Set the title for the jquery tooltip
    .tooltip('open') // Start the "open" method
    .attr('title', null);  // And remove the title to prevent the browsers tooltip
}

window.plugin.guessPlayerLevels.setupChatNickHelper = function() {
  $(window).delegate('.nickname', 'mouseenter', function() {
    window.plugin.guessPlayerLevels.setLevelTitle(this);
  });
}

window.plugin.guessPlayerLevels.extractPortalData = function(data) {
  var r = data.portal.options.details.resonatorArray.resonators;
  $.each(r, function(ind, reso) {
    if(!reso) return true;
    var p = 'level-'+reso.ownerGuid;
    var l = reso.level;
    if(!window.localStorage[p] || window.localStorage[p] < l)
      window.localStorage[p] = l;
  });
}

window.plugin.guessPlayerLevels.guess = function() {
  var playersRes = {};
  var playersEnl = {};
  $.each(window.portals, function(ind, portal) {
    var r = portal.options.details.resonatorArray.resonators;
    $.each(r, function(ind, reso) {
      if(!reso) return true;
      var lvl = localStorage['level-' + reso.ownerGuid];
      var nick = getPlayerName(reso.ownerGuid);
      if(portal.options.team === TEAM_ENL)
        playersEnl[nick] = lvl;
      else
        playersRes[nick] = lvl;
    });
  });

  var s = 'Players have at least the following level:\n\n';
  s += 'Resistance:\t   \tEnlightened:\t\n';

  var namesR = plugin.guessPlayerLevels.sort(playersRes);
  var namesE = plugin.guessPlayerLevels.sort(playersEnl);
  var totallvlR = 0;
  var totallvlE = 0;
  var max = Math.max(namesR.length, namesE.length);
  for(var i = 0; i < max; i++) {
    var nickR = namesR[i];
    var lvlR = playersRes[nickR];
    var lineR = nickR ? nickR + ':\t' + lvlR : '\t';
    if(!isNaN(parseInt(lvlR)))
        totallvlR += parseInt(lvlR);

    var nickE = namesE[i];
    var lvlE = playersEnl[nickE];
    var lineE = nickE ? nickE + ':\t' + lvlE : '\t';
    if(!isNaN(parseInt(lvlE)))
        totallvlE += parseInt(lvlE);

    s += '\n'+lineR + '\t' + lineE + '\n';
  }
  s += '\nTotal level :\t'+totallvlR+'\tTotal level :\t'+totallvlE;
  s += '\nTotal player:\t'+namesR.length+'\tTotal player:\t'+namesE.length;
  var averageR = 0, averageE = 0;
  if (namesR.length > 0)  averageR = (totallvlR/namesR.length);
  if (namesE.length > 0)  averageE = (totallvlE/namesE.length);
  s += '\nAverage level:\t'+averageR.toFixed(2)+'\tAverage level:\t'+averageE.toFixed(2);
  s += '\n\nIf there are some unresolved names, simply try again.'
  //console.log(s);
  dialog({
    text: s,
    title: 'Player levels: R' + averageR.toFixed(2) + ', E' + averageE.toFixed(2)
  });

  //run the name resolving process
  resolvePlayerNames();
}

window.plugin.guessPlayerLevels.sort = function(playerHash) {
  return Object.keys(playerHash).sort(function(a, b) {
    if(playerHash[a] < playerHash[b]) return 1;
    if(playerHash[a] > playerHash[b]) return -1;

    if (a.toLowerCase()  b.toLowerCase()) return 1;
    return 0;
  });
}

var setup =  function() {
  window.plugin.guessPlayerLevels.setupCallback();
  window.plugin.guessPlayerLevels.setupChatNickHelper();
}

// PLUGIN END //////////////////////////////////////////////////////////

if(window.iitcLoaded && typeof setup === 'function') {
  setup();
} else {
  if(window.bootPlugins)
    window.bootPlugins.push(setup);
  else
    window.bootPlugins = [setup];
}
} // wrapper end
// inject code into site context
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);
<commit_msg>guess player levels - set an id to prevent mulitple instances being opened - pass in a width, overriding the default 300px<commit_after>// ==UserScript==
// @id             iitc-plugin-guess-player-levels@breunigs
// @name           IITC plugin: guess player level
// @version        0.4.4.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Tries to determine player levels from the data available in the current view
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

function wrapper() {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.guessPlayerLevels = function() {};

window.plugin.guessPlayerLevels.setupCallback = function() {
  $('#toolbox').append(' Guess player levels');
  addHook('portalAdded', window.plugin.guessPlayerLevels.extractPortalData);
}

// This function is intended to be called by other plugins
window.plugin.guessPlayerLevels.fetchLevelByPlayer = function(guid) {
  return(window.localStorage['level-' + guid]);
}

window.plugin.guessPlayerLevels._nameToGuidCache = {};

window.plugin.guessPlayerLevels.setLevelTitle = function(dom) {
  // expects dom node with nick in its child text node

  var el = $(dom);
  var nick = el.text();
  var guid = window.playerNameToGuid(nick);
  var level = guid ? localStorage['level-'+guid] : null;

  var text;
  if (level) {
    text = 'Min player level: ' + level;
    if(level < window.MAX_XM_PER_LEVEL.length - 1) text += ' (guessed)';
  } else {
    text = 'Min player level unknown';
  }
  window.setupTooltips(el);

  /*
  This code looks hacky but since we are a little late within the mouseenter so
  we need to improvise a little. The open method doesn't open the tooltip directly.
  It starts the whole opening procedure (including the timeout etc) and is normally
  started by the mousemove event of the enhanced element.
  */
  el.addClass('help') // Add the "Help Mouse Cursor"
    .attr('title', text) // Set the title for the jquery tooltip
    .tooltip('open') // Start the "open" method
    .attr('title', null);  // And remove the title to prevent the browsers tooltip
}

window.plugin.guessPlayerLevels.setupChatNickHelper = function() {
  $(window).delegate('.nickname', 'mouseenter', function() {
    window.plugin.guessPlayerLevels.setLevelTitle(this);
  });
}

window.plugin.guessPlayerLevels.extractPortalData = function(data) {
  var r = data.portal.options.details.resonatorArray.resonators;
  $.each(r, function(ind, reso) {
    if(!reso) return true;
    var p = 'level-'+reso.ownerGuid;
    var l = reso.level;
    if(!window.localStorage[p] || window.localStorage[p] < l)
      window.localStorage[p] = l;
  });
}

window.plugin.guessPlayerLevels.guess = function() {
  var playersRes = {};
  var playersEnl = {};
  $.each(window.portals, function(ind, portal) {
    var r = portal.options.details.resonatorArray.resonators;
    $.each(r, function(ind, reso) {
      if(!reso) return true;
      var lvl = localStorage['level-' + reso.ownerGuid];
      var nick = getPlayerName(reso.ownerGuid);
      if(portal.options.team === TEAM_ENL)
        playersEnl[nick] = lvl;
      else
        playersRes[nick] = lvl;
    });
  });

  var s = 'Players have at least the following level:\n\n';
  s += 'Resistance:\t   \tEnlightened:\t\n';

  var namesR = plugin.guessPlayerLevels.sort(playersRes);
  var namesE = plugin.guessPlayerLevels.sort(playersEnl);
  var totallvlR = 0;
  var totallvlE = 0;
  var max = Math.max(namesR.length, namesE.length);
  for(var i = 0; i < max; i++) {
    var nickR = namesR[i];
    var lvlR = playersRes[nickR];
    var lineR = nickR ? nickR + ':\t' + lvlR : '\t';
    if(!isNaN(parseInt(lvlR)))
        totallvlR += parseInt(lvlR);

    var nickE = namesE[i];
    var lvlE = playersEnl[nickE];
    var lineE = nickE ? nickE + ':\t' + lvlE : '\t';
    if(!isNaN(parseInt(lvlE)))
        totallvlE += parseInt(lvlE);

    s += '\n'+lineR + '\t' + lineE + '\n';
  }
  s += '\nTotal level :\t'+totallvlR+'\tTotal level :\t'+totallvlE;
  s += '\nTotal player:\t'+namesR.length+'\tTotal player:\t'+namesE.length;
  var averageR = 0, averageE = 0;
  if (namesR.length > 0)  averageR = (totallvlR/namesR.length);
  if (namesE.length > 0)  averageE = (totallvlE/namesE.length);
  s += '\nAverage level:\t'+averageR.toFixed(2)+'\tAverage level:\t'+averageE.toFixed(2);
  s += '\n\nIf there are some unresolved names, simply try again.'
  //console.log(s);
  dialog({
    text: s,
    title: 'Player levels: R' + averageR.toFixed(2) + ', E' + averageE.toFixed(2),
    id: 'guess-player-levels',
    width: 350,
  });

  //run the name resolving process
  resolvePlayerNames();
}

window.plugin.guessPlayerLevels.sort = function(playerHash) {
  return Object.keys(playerHash).sort(function(a, b) {
    if(playerHash[a] < playerHash[b]) return 1;
    if(playerHash[a] > playerHash[b]) return -1;

    if (a.toLowerCase()  b.toLowerCase()) return 1;
    return 0;
  });
}

var setup =  function() {
  window.plugin.guessPlayerLevels.setupCallback();
  window.plugin.guessPlayerLevels.setupChatNickHelper();
}

// PLUGIN END //////////////////////////////////////////////////////////

if(window.iitcLoaded && typeof setup === 'function') {
  setup();
} else {
  if(window.bootPlugins)
    window.bootPlugins.push(setup);
  else
    window.bootPlugins = [setup];
}
} // wrapper end
// inject code into site context
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);
<|endoftext|>


<commit_before>;(function($, global, $multifile)
{
  if ( !global.FileReader )
    return;

  $multifile.templateCb = function(file)
  {
    var $tmpl = $('
 \
      x \
       \
       \

')
      , fr = new FileReader();
    $tmpl.find('span.filename').text(file.name);
    fr.onload = $multifile.fileReaderCb($tmpl, file);
    fr.readAsDataURL(file);
    return $tmpl;
  };

  $multifile.image_filter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;

  $multifile.fileReaderCb = function($tmpl, file_obj)
  {
    return function(event)
    {
      if ( $multifile.image_filter.test(file_obj.type) )
        $tmpl.find('img.multifile_preview')
          .attr('src', event.target.result);
    };
  };

})(jQuery, this, $.fn.multifile);
<commit_msg>make preview plugin more extensible by wrapping the templateCb instead of overriding it.<commit_after>;(function($, global, multifile_plugin)
{
  var _parent_templateCb = multifile_plugin.templateCb;

  if ( !global.FileReader )
    return;

  multifile_plugin.templateCb = function(file)
  {
    return multifile_plugin.fileReaderCb(_parent_templateCb, file);
  };

  multifile_plugin.image_filter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;

  multifile_plugin.fileReaderCb = function(templateCb, file)
  {
    var fr = new FileReader()
      , $tmpl = templateCb(file)
      , $img;
    fr.onload = function(event)
    {
      if ( multifile_plugin.image_filter.test(file.type) )
      {
        $img = $('').attr({
          'class': 'multifile_preview',
          'src': event.target.result
          });
        $tmpl.append($img);
      }
    };
    fr.readAsDataURL(file);
    return $tmpl;
  };

})(jQuery, this, $.fn.multifile);
<|endoftext|>


<commit_before>var EventEmitter = (function() {
    function EventEmitter() {
        this.events = {};
        this.on = this.bind;
        this.emit = this.trigger;
    }

    EventEmitter.prototype.bind = function(name, handler, context) {
        var event,
            events;
        this.events[name] = this.events[name] || [];
        events = this.events[name];
        event = {
            handler: handler,
            context: context
        };
        events.push(event);
        return this;
    };

    EventEmitter.prototype.trigger = function(/*name, param1, param2...*/) {
        var name = arguments[0],
            events = this.events[name] || [],
            params = Array.prototype.slice.call(arguments, 1);
        for(var i = 0, iLen = events.length; i < iLen; i++) {
            events[i].handler.apply(events[i].context || this, params);
        }
        return this;
    };

    EventEmitter.prototype.removeEvent = function(name, handler) {
        var events = this.events[name] || [];
        if(arguments.length === 0) {
            this.removeAllEvents();
            return this;
        }
        if(arguments.length === 1) {
            this.removeAllEvents(name);
            return this;
        }
        for(var i = 0, iLen = events.length; i < iLen; i++) {
            if(events[i].handler == handler) {
                events[i] = null;
            }
        }
        return this;
    };

    EventEmitter.prototype.removeAllEvents = function(name) {
        if(name) {
            this.events[name] = [];
        } else {
            this.events = {};
        }
        return this;
    };

    return EventEmitter;
})();
<commit_msg>add EventEmitter.once<commit_after>var EventEmitter = (function() {
    function EventEmitter() {
        this.events = {};
        this.on = this.bind;
        this.emit = this.trigger;
    }

    EventEmitter.prototype.bind = function(name, handler, context) {
        var event,
            events;
        this.events[name] = this.events[name] || [];
        events = this.events[name];
        event = {
            handler: handler,
            context: context
        };
        events.push(event);
        return this;
    };

    EventEmitter.prototype.once = function(name, handler, context) {
        var self = this;
        function temp() {
            self.removeEvent(name, temp);
            handler.call(this);
        }
        handler._remove = temp;
        this.bind(name, temp);
    };

    EventEmitter.prototype.trigger = function(/*name, param1, param2...*/) {
        var name = arguments[0],
            events = this.events[name] || [],
            params = Array.prototype.slice.call(arguments, 1);
        for(var i = 0, iLen = events.length; i < iLen; i++) {
            events[i].handler.apply(events[i].context || this, params);
        }
        return this;
    };

    EventEmitter.prototype.removeEvent = function(name, handler) {
        var events = this.events[name] || [];
        if(arguments.length === 0) {
            this.events = {};
            return this;
        }
        if(arguments.length === 1) {
            events = [];
            this.removeAllEvents(name);
            return this;
        }
        for(var i = 0, iLen = events.length; i < iLen; i++) {
            if(events[i].handler == handler || events[i].handler._remove == handler) {
                events.splice(i, 1)
            }
        }
        return this;
    };

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


<commit_before>/**
 * @preserve EventEmitter v1.0.0
 *
 * Copyright 2011, Oliver Caldwell (flowdev.co.uk)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * https://github.com/Wolfy87/Listen
 */

// Initialise the class
function EventEmitter() {}

// Initialise the storage variables
EventEmitter.prototype._events = {};
EventEmitter.prototype._listeners = [];

/**
 * Adds a listener for a specified event
 *
 * @param {String} name Name of the event
 * @param {Function} listener Run when the event is emitted
 * @param {Boolan} once If true, the listener will only be run once, use EventEmitter.once instead, this is mainly for internal use
 */
EventEmitter.prototype.addListener = function(name, listener, once) {
	// Grab the index of the listener
	var index = this._listeners.length;

	// Add the listener
	this._listeners.push({
		listener: listener,
		once: (once) ? true : false
	});

	// Add the event to the events object if required
	if(typeof this._events[name] === 'undefined') {
		this._events[name] = [];
	}

	// Add the listeners index to the event
	this._events[name].push(index);
};

/**
 * Adds a listener for a specified event (alias of EventEmitter.addListener)
 *
 * @param {String} name Name of the event
 * @param {Function} listener Run when the event is emitted
 * @param {Boolan} once If true, the listener will only be run once, use EventEmitter.once instead, this is mainly for internal use
 */
EventEmitter.prototype.on = EventEmitter.prototype.addListener;

/**
 * Adds a listener for a specified event that will only be called once
 *
 * @param {String} name Name of the event
 * @param {Function} listener Run when the event is emitted
 */
EventEmitter.prototype.once = function(name, listener) {
	this.addListener(name, listener, true);
};

/**
 * Removes a listener for a specified event
 *
 * @param {String} name Name of the event
 * @param {Function} listener Reference to the listener function
 */
EventEmitter.prototype.removeListener = function(name, listener) {
	// Initialise any required variables
	var i = null,
		indexes = null;

	// Make sure the event exists
	if(this._events[name] instanceof Array) {
		// Grab the listeners indexes
		indexes = this._events[name];

		// Loop through all of the indexes
		for(i = 0; i < indexes.length; i++) {
			// Check if we have found the listener
			if(this._listeners[indexes[i]].listener === listener) {
				// It is, remove it and return
				this._events[name].splice(i, 1);
			}
		}
	}
};

/**
 * Removes all the listeners for a specified event
 *
 * @param {String} name Name of the event
 */
EventEmitter.prototype.removeAllListeners = function(name) {

};

/**
 * Sets the max number of listeners before a message is displayed
 * If it is set to 0 then there is no limit
 *
 * @param {Number} n Max number of listeners before a message is displayed
 */
EventEmitter.prototype.setMaxListeners = function(n) {

};

/**
 * Returns an array of listeners for the specified event
 *
 * @param {String} name Name of the event
 * @returns {Array} An array of the assigned listeners
 */
EventEmitter.prototype.listeners = function(name) {

};

/**
 * Emits the specified event with optional arguments
 *
 * @param {String} name Name of the event to be emitted
 * @param {Mixed} An argument to be passed to the listeners, you can have as many of these as you want
 */
EventEmitter.prototype.emit = function(name) {

};
<commit_msg>Added the code for the removeAllListeners function<commit_after>/**
 * @preserve EventEmitter v1.0.0
 *
 * Copyright 2011, Oliver Caldwell (flowdev.co.uk)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * https://github.com/Wolfy87/Listen
 */

// Initialise the class
function EventEmitter() {}

// Initialise the storage variables
EventEmitter.prototype._events = {};
EventEmitter.prototype._listeners = [];

/**
 * Adds a listener for a specified event
 *
 * @param {String} name Name of the event
 * @param {Function} listener Run when the event is emitted
 * @param {Boolan} once If true, the listener will only be run once, use EventEmitter.once instead, this is mainly for internal use
 */
EventEmitter.prototype.addListener = function(name, listener, once) {
	// Grab the index of the listener
	var index = this._listeners.length;

	// Add the listener
	this._listeners.push({
		listener: listener,
		once: (once) ? true : false
	});

	// Add the event to the events object if required
	if(typeof this._events[name] === 'undefined') {
		this._events[name] = [];
	}

	// Add the listeners index to the event
	this._events[name].push(index);
};

/**
 * Adds a listener for a specified event (alias of EventEmitter.addListener)
 *
 * @param {String} name Name of the event
 * @param {Function} listener Run when the event is emitted
 * @param {Boolan} once If true, the listener will only be run once, use EventEmitter.once instead, this is mainly for internal use
 */
EventEmitter.prototype.on = EventEmitter.prototype.addListener;

/**
 * Adds a listener for a specified event that will only be called once
 *
 * @param {String} name Name of the event
 * @param {Function} listener Run when the event is emitted
 */
EventEmitter.prototype.once = function(name, listener) {
	this.addListener(name, listener, true);
};

/**
 * Removes a listener for a specified event
 *
 * @param {String} name Name of the event
 * @param {Function} listener Reference to the listener function
 */
EventEmitter.prototype.removeListener = function(name, listener) {
	// Initialise any required variables
	var i = null,
		indexes = null;

	// Make sure the event exists
	if(this._events[name] instanceof Array) {
		// Grab the listeners indexes
		indexes = this._events[name];

		// Loop through all of the indexes
		for(i = 0; i < indexes.length; i++) {
			// Check if we have found the listener
			if(this._listeners[indexes[i]].listener === listener) {
				// It is, remove it and return
				this._events[name].splice(i, 1);
			}
		}
	}
};

/**
 * Removes all the listeners for a specified event
 *
 * @param {String} name Name of the event
 */
EventEmitter.prototype.removeAllListeners = function(name) {
	this._events[name] = [];
};

/**
 * Sets the max number of listeners before a message is displayed
 * If it is set to 0 then there is no limit
 *
 * @param {Number} n Max number of listeners before a message is displayed
 */
EventEmitter.prototype.setMaxListeners = function(n) {

};

/**
 * Returns an array of listeners for the specified event
 *
 * @param {String} name Name of the event
 * @returns {Array} An array of the assigned listeners
 */
EventEmitter.prototype.listeners = function(name) {

};

/**
 * Emits the specified event with optional arguments
 *
 * @param {String} name Name of the event to be emitted
 * @param {Mixed} An argument to be passed to the listeners, you can have as many of these as you want
 */
EventEmitter.prototype.emit = function(name) {

};
<|endoftext|>


<commit_before>define([], function() {

  'use strict';

  function ByteSource() {
  }

  function ByteSourceFromBlob(blob) {
    this.blob = blob;
  }
  (function(proto) {
    proto.slice = function() {
      return new ByteSourceFromBlob(this.blob.slice.apply(this.blob, arguments));
    };
    proto.read = function(reader) {
      var fr = new FileReader();
      fr.addEventListener('load', function() {
        if (typeof reader.onbytes === 'function') {
          reader.onbytes(new Uint8Array(fr.result));
        }
        if (typeof reader.oncomplete === 'function') {
          reader.oncomplete();
        }
      });
      fr.addEventListener('error', function(e) {
        console.error(e.error);
      });
      fr.readAsArrayBuffer(this.blob);
    };
  })(ByteSourceFromBlob.prototype = new ByteSource);

  ByteSource.FromBlob = ByteSourceFromBlob;

  ByteSource.from = function(src) {
    if (src instanceof ByteSource) return src;
    if (src instanceof Blob) return new ByteSourceFromBlob(src);
    if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) return new ByteSourceFromBlob(new Blob([src]));
    throw new TypeError('value not supported for creating ByteSource: ' + (typeof src === 'object' ? src : typeof src));
  };

  return ByteSource;

});
<commit_msg>Add getURL() method that returns a Promise<commit_after>define([], function() {

  'use strict';

  function ByteSource() {
  }

  function ByteSourceFromBlob(blob) {
    this.blob = blob;
  }
  (function(proto) {
    proto.slice = function() {
      return new ByteSourceFromBlob(this.blob.slice.apply(this.blob, arguments));
    };
    proto.read = function(reader) {
      var fr = new FileReader();
      fr.addEventListener('load', function() {
        if (typeof reader.onbytes === 'function') {
          reader.onbytes(new Uint8Array(fr.result));
        }
        if (typeof reader.oncomplete === 'function') {
          reader.oncomplete();
        }
      });
      fr.addEventListener('error', function(e) {
        console.error(e.error);
      });
      fr.readAsArrayBuffer(this.blob);
    };
    proto.getURL = function() {
      return Promise.resolve(URL.createObjectURL(this.blob));
    };
  })(ByteSourceFromBlob.prototype = new ByteSource);

  ByteSource.FromBlob = ByteSourceFromBlob;

  ByteSource.from = function(src) {
    if (src instanceof ByteSource) return src;
    if (src instanceof Blob) return new ByteSourceFromBlob(src);
    if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) return new ByteSourceFromBlob(new Blob([src]));
    throw new TypeError('value not supported for creating ByteSource: ' + (typeof src === 'object' ? src : typeof src));
  };

  return ByteSource;

});
<|endoftext|>


<commit_before>import { takeEvery, delay } from 'redux-saga'
import { fork, join, put, race, take, call } from 'redux-saga/effects'
import Path from 'path'
import fs from 'graceful-fs'
import * as actions from '../actions/files.js'
import * as constants from '../constants/files.js'
import { List } from 'immutable'
import BigNumber from 'bignumber.js'
import { ls, uploadDirectory, sendError, allowancePeriod, readableFilesize, siadCall, readdirRecursive, parseDownloads, parseUploads } from './helpers.js'

// Query siad for the state of the wallet.
// dispatch `unlocked` in receiveWalletLockstate
function* getWalletLockstateSaga() {
	try {
		const response = yield siadCall('/wallet')
		yield put(actions.receiveWalletLockstate(response.unlocked))
	} catch (e) {
		console.error('error fetching wallet lock state: ' + e.toString())
	}
}

// Query siad for the sync state of the wallet.
function* getWalletSyncstateSaga() {
	try {
		const response = yield siadCall('/consensus')
		yield put(actions.setWalletSyncstate(response.synced))
	} catch (e) {
		console.error('error fetching wallet sync state: ' + e.toString())
	}
}

// Query siad for the user's files.
function* getFilesSaga() {
	try {
		const response = yield siadCall('/renter/files')
		const files = List(response.files)
		yield put(actions.receiveFiles(files))
	} catch (e) {
		console.error('error fetching files: ' + e.toString())
	}
}

function* getStorageEstimateSaga(action) {
	try {
		const response = yield siadCall('/renter/prices')
		if (response.storageterabytemonth === '0') {
			yield put(actions.setStorageEstimate('No Hosts'))
			return
		}
		const estimate = new BigNumber(SiaAPI.siacoinsToHastings(action.funds)).dividedBy(response.storageterabytemonth).times(1e12)

		yield put(actions.setStorageEstimate('~' + readableFilesize(estimate.toPrecision(1))))
	} catch (e) {
		console.error(e)
	}
}

// Get the renter's current allowance and spending.
function* getAllowanceSaga() {
	try {
		const response = yield siadCall('/renter')
		const allowance = SiaAPI.hastingsToSiacoins(response.settings.allowance.funds)

		// compute allowance spending. Set the spending to zero if it is negative,
		// since negative spending is confusing to the user.
		let spending = allowance.minus(SiaAPI.hastingsToSiacoins(response.financialmetrics.unspent))
		if (spending.isNegative()) {
			spending = new BigNumber(0)
		}

		yield put(actions.receiveAllowance(allowance.round(0).toString()))
		yield put(actions.receiveSpending(spending.round(0).toString()))
	} catch (e) {
		console.error('error getting allowance: ' + e.toString())
	}
}

// Set the user's renter allowance.
function* setAllowanceSaga(action) {
	try {
		const newAllowance = SiaAPI.siacoinsToHastings(action.funds)
		yield put(actions.closeAllowanceDialog())
		yield siadCall({
			url: '/renter',
			method: 'POST',
			timeout: 7.2e6, // 120 minute timeout for setting allowance
			qs: {
				funds: newAllowance.toString(),
				period: allowancePeriod,
			},
		})
		yield put(actions.setAllowanceCompleted())
	} catch (e) {
		sendError(e)
		yield put(actions.setAllowanceCompleted())
		yield put(actions.closeAllowanceDialog())
	}
}

// Query Siad for the current wallet balance.
function* getWalletBalanceSaga() {
	try {
		const response = yield siadCall('/wallet')
		const confirmedBalance = SiaAPI.hastingsToSiacoins(response.confirmedsiacoinbalance).round(2).toString()
		yield put(actions.receiveWalletBalance(confirmedBalance))
	} catch (e) {
		console.error('error fetching wallet balance: ' + e.toString())
	}
}

// UploadFileSaga uploads a file to the Sia network.
// action.siapath: the working directory to upload the file to
// action.source: the path to the file to upload.
// The full siapath is computed as Path.join(action.siapath, Path.basename(action.source))
function* uploadFileSaga(action) {
	try {
		const filename = Path.basename(action.source)
		const destpath = Path.posix.join(action.siapath, filename)
		yield siadCall({
			url: '/renter/upload/' + encodeURI(destpath),
			timeout: 20000, // 20 second timeout for upload calls
			method: 'POST',
			qs: {
				source: action.source,
			},
		})
	} catch (e) {
		sendError(e)
	}
}

// uploadFolderSaga uploads a folder to the Sia network.
// action.source: the source path of the folder
// action.siapath: the working directory to upload the folder inside
function *uploadFolderSaga(action) {
	try {
		const files = readdirRecursive(action.source)
		const uploads = uploadDirectory(action.source, files, action.siapath)
		for (const upload in uploads.toArray()) {
			yield put(uploads.get(upload))
		}
	} catch (e) {
		sendError(e)
	}
}

function* downloadFileSaga(action) {
	try {
		if (action.file.type === 'file') {
			yield siadCall({
				url: '/renter/download/' + encodeURI(action.file.siapath),
				timeout: 6e8,
				method: 'GET',
				qs: {
					destination: action.downloadpath,
				},
			})
		}
		if (action.file.type === 'directory') {
			fs.mkdirSync(action.downloadpath)
			const response = yield siadCall('/renter/files')
			const siafiles = ls(List(response.files), action.file.siapath)
			for (const siafile in siafiles.toArray()) {
				const file = siafiles.get(siafile)
				yield put(actions.downloadFile(file, Path.join(action.downloadpath, file.name)))
				yield new Promise((resolve) => setTimeout(resolve, 300))
			}
		}
	} catch (e) {
		sendError(e)
	}
}

function* getDownloadsSaga() {
	try {
		const response = yield siadCall('/renter/downloads')
		const downloads = parseDownloads(response.downloads)
		yield put(actions.receiveDownloads(downloads))
	} catch (e) {
		console.error('error fetching downloads: ' + e.toString())
	}
}

function* getUploadsSaga() {
	try {
		const response = yield siadCall('/renter/files')
		const uploads = parseUploads(response.files)
		yield put(actions.receiveUploads(uploads))
	} catch (e) {
		console.error('error fetching uploads: ' + e.toString())
	}
}

function* deleteFileSaga(action) {
	try {
		if (action.file.type === 'file') {
			yield siadCall({
				url: '/renter/delete/' + encodeURI(action.file.siapath),
				timeout: 3.6e6, // 60 minute timeout for deleting files
				method: 'POST',
			})
		}
		if (action.file.type === 'directory') {
			const response = yield siadCall('/renter/files')
			const siafiles = ls(List(response.files), action.file.siapath)
			for (const siafile in siafiles.toArray()) {
				const file = siafiles.get(siafile)
				yield put(actions.deleteFile(file))
			}
		}
		yield put(actions.getFiles())
	} catch (e) {
		sendError(e)
	}
}

function* getContractCountSaga() {
	try {
		const response = yield siadCall('/renter/contracts')
		yield put(actions.setContractCount(response.contracts.length))
	} catch (e) {
		console.error('error getting contract count: ' + e.toString())
	}
}

function* renameFileSaga(action) {
	try {
		if (action.file.type === 'file') {
			yield siadCall({
				url: '/renter/rename/' + encodeURI(action.file.siapath),
				method: 'POST',
				qs: {
					newsiapath: action.newsiapath,
				},
			})
			yield put(actions.getFiles())
		}
		if (action.file.type === 'directory') {
			const directorypath = action.file.siapath
			const response = yield siadCall('/renter/files')
			const siafiles = ls(List(response.files), directorypath)
			for (const i in siafiles.toArray()) {
				const file = siafiles.get(i)
				const newfilepath = Path.posix.join(action.newsiapath, file.siapath.split(directorypath)[1])
				yield put(actions.renameFile(file, newfilepath))
			}
		}
		yield put(actions.hideRenameDialog())
	} catch (e) {
		sendError(e)
	}
}

export function* dataFetcher() {
	while (true) {
		let tasks = []
		tasks = tasks.concat(yield fork(getDownloadsSaga))
		tasks = tasks.concat(yield fork(getFilesSaga))
		tasks = tasks.concat(yield fork(getUploadsSaga))
		tasks = tasks.concat(yield fork(getContractCountSaga))
		tasks = tasks.concat(yield fork(getWalletBalanceSaga))
		tasks = tasks.concat(yield fork(getWalletSyncstateSaga))
		tasks = tasks.concat(yield fork(getAllowanceSaga))

		yield join(...tasks)
		yield race({
			task: call(delay, 8000),
			cancel: take(constants.FETCH_DATA),
		})
	}
}
export function* watchSetAllowance() {
	yield *takeEvery(constants.SET_ALLOWANCE, setAllowanceSaga)
}
export function* watchGetAllowance() {
	yield *takeEvery(constants.GET_ALLOWANCE, getAllowanceSaga)
}
export function* watchGetDownloads() {
	yield *takeEvery(constants.GET_DOWNLOADS, getDownloadsSaga)
}
export function* watchGetUploads() {
	yield *takeEvery(constants.GET_UPLOADS, getUploadsSaga)
}
export function* watchGetWalletLockstate() {
	yield *takeEvery(constants.GET_WALLET_LOCKSTATE, getWalletLockstateSaga)
}
export function* watchGetFiles() {
	yield *takeEvery(constants.GET_FILES, getFilesSaga)
}
export function* watchDeleteFile() {
	yield *takeEvery(constants.DELETE_FILE, deleteFileSaga)
}
export function* watchGetWalletBalance() {
	yield *takeEvery(constants.GET_WALLET_BALANCE, getWalletBalanceSaga)
}
export function* watchUploadFolder() {
	yield *takeEvery(constants.UPLOAD_FOLDER, uploadFolderSaga)
}
export function* watchGetContractCount() {
	yield *takeEvery(constants.GET_CONTRACT_COUNT, getContractCountSaga)
}
export function* watchUploadFile() {
	yield *takeEvery(constants.UPLOAD_FILE, uploadFileSaga)
}
export function* watchDownloadFile() {
	yield *takeEvery(constants.DOWNLOAD_FILE, downloadFileSaga)
}
export function* watchRenameFile() {
	yield *takeEvery(constants.RENAME_FILE, renameFileSaga)
}
export function* watchGetStorageEstimate() {
	yield *takeEvery(constants.GET_STORAGE_ESTIMATE, getStorageEstimateSaga)
}
export function* watchGetWalletSyncstate() {
	yield *takeEvery(constants.GET_WALLET_SYNCSTATE, getWalletSyncstateSaga)
}
<commit_msg>add missing lockstate polling to files plugin<commit_after>import { takeEvery, delay } from 'redux-saga'
import { fork, join, put, race, take, call } from 'redux-saga/effects'
import Path from 'path'
import fs from 'graceful-fs'
import * as actions from '../actions/files.js'
import * as constants from '../constants/files.js'
import { List } from 'immutable'
import BigNumber from 'bignumber.js'
import { ls, uploadDirectory, sendError, allowancePeriod, readableFilesize, siadCall, readdirRecursive, parseDownloads, parseUploads } from './helpers.js'

// Query siad for the state of the wallet.
// dispatch `unlocked` in receiveWalletLockstate
function* getWalletLockstateSaga() {
	try {
		const response = yield siadCall('/wallet')
		yield put(actions.receiveWalletLockstate(response.unlocked))
	} catch (e) {
		console.error('error fetching wallet lock state: ' + e.toString())
	}
}

// Query siad for the sync state of the wallet.
function* getWalletSyncstateSaga() {
	try {
		const response = yield siadCall('/consensus')
		yield put(actions.setWalletSyncstate(response.synced))
	} catch (e) {
		console.error('error fetching wallet sync state: ' + e.toString())
	}
}

// Query siad for the user's files.
function* getFilesSaga() {
	try {
		const response = yield siadCall('/renter/files')
		const files = List(response.files)
		yield put(actions.receiveFiles(files))
	} catch (e) {
		console.error('error fetching files: ' + e.toString())
	}
}

function* getStorageEstimateSaga(action) {
	try {
		const response = yield siadCall('/renter/prices')
		if (response.storageterabytemonth === '0') {
			yield put(actions.setStorageEstimate('No Hosts'))
			return
		}
		const estimate = new BigNumber(SiaAPI.siacoinsToHastings(action.funds)).dividedBy(response.storageterabytemonth).times(1e12)

		yield put(actions.setStorageEstimate('~' + readableFilesize(estimate.toPrecision(1))))
	} catch (e) {
		console.error(e)
	}
}

// Get the renter's current allowance and spending.
function* getAllowanceSaga() {
	try {
		const response = yield siadCall('/renter')
		const allowance = SiaAPI.hastingsToSiacoins(response.settings.allowance.funds)

		// compute allowance spending. Set the spending to zero if it is negative,
		// since negative spending is confusing to the user.
		let spending = allowance.minus(SiaAPI.hastingsToSiacoins(response.financialmetrics.unspent))
		if (spending.isNegative()) {
			spending = new BigNumber(0)
		}

		yield put(actions.receiveAllowance(allowance.round(0).toString()))
		yield put(actions.receiveSpending(spending.round(0).toString()))
	} catch (e) {
		console.error('error getting allowance: ' + e.toString())
	}
}

// Set the user's renter allowance.
function* setAllowanceSaga(action) {
	try {
		const newAllowance = SiaAPI.siacoinsToHastings(action.funds)
		yield put(actions.closeAllowanceDialog())
		yield siadCall({
			url: '/renter',
			method: 'POST',
			timeout: 7.2e6, // 120 minute timeout for setting allowance
			qs: {
				funds: newAllowance.toString(),
				period: allowancePeriod,
			},
		})
		yield put(actions.setAllowanceCompleted())
	} catch (e) {
		sendError(e)
		yield put(actions.setAllowanceCompleted())
		yield put(actions.closeAllowanceDialog())
	}
}

// Query Siad for the current wallet balance.
function* getWalletBalanceSaga() {
	try {
		const response = yield siadCall('/wallet')
		const confirmedBalance = SiaAPI.hastingsToSiacoins(response.confirmedsiacoinbalance).round(2).toString()
		yield put(actions.receiveWalletBalance(confirmedBalance))
	} catch (e) {
		console.error('error fetching wallet balance: ' + e.toString())
	}
}

// UploadFileSaga uploads a file to the Sia network.
// action.siapath: the working directory to upload the file to
// action.source: the path to the file to upload.
// The full siapath is computed as Path.join(action.siapath, Path.basename(action.source))
function* uploadFileSaga(action) {
	try {
		const filename = Path.basename(action.source)
		const destpath = Path.posix.join(action.siapath, filename)
		yield siadCall({
			url: '/renter/upload/' + encodeURI(destpath),
			timeout: 20000, // 20 second timeout for upload calls
			method: 'POST',
			qs: {
				source: action.source,
			},
		})
	} catch (e) {
		sendError(e)
	}
}

// uploadFolderSaga uploads a folder to the Sia network.
// action.source: the source path of the folder
// action.siapath: the working directory to upload the folder inside
function *uploadFolderSaga(action) {
	try {
		const files = readdirRecursive(action.source)
		const uploads = uploadDirectory(action.source, files, action.siapath)
		for (const upload in uploads.toArray()) {
			yield put(uploads.get(upload))
		}
	} catch (e) {
		sendError(e)
	}
}

function* downloadFileSaga(action) {
	try {
		if (action.file.type === 'file') {
			yield siadCall({
				url: '/renter/download/' + encodeURI(action.file.siapath),
				timeout: 6e8,
				method: 'GET',
				qs: {
					destination: action.downloadpath,
				},
			})
		}
		if (action.file.type === 'directory') {
			fs.mkdirSync(action.downloadpath)
			const response = yield siadCall('/renter/files')
			const siafiles = ls(List(response.files), action.file.siapath)
			for (const siafile in siafiles.toArray()) {
				const file = siafiles.get(siafile)
				yield put(actions.downloadFile(file, Path.join(action.downloadpath, file.name)))
				yield new Promise((resolve) => setTimeout(resolve, 300))
			}
		}
	} catch (e) {
		sendError(e)
	}
}

function* getDownloadsSaga() {
	try {
		const response = yield siadCall('/renter/downloads')
		const downloads = parseDownloads(response.downloads)
		yield put(actions.receiveDownloads(downloads))
	} catch (e) {
		console.error('error fetching downloads: ' + e.toString())
	}
}

function* getUploadsSaga() {
	try {
		const response = yield siadCall('/renter/files')
		const uploads = parseUploads(response.files)
		yield put(actions.receiveUploads(uploads))
	} catch (e) {
		console.error('error fetching uploads: ' + e.toString())
	}
}

function* deleteFileSaga(action) {
	try {
		if (action.file.type === 'file') {
			yield siadCall({
				url: '/renter/delete/' + encodeURI(action.file.siapath),
				timeout: 3.6e6, // 60 minute timeout for deleting files
				method: 'POST',
			})
		}
		if (action.file.type === 'directory') {
			const response = yield siadCall('/renter/files')
			const siafiles = ls(List(response.files), action.file.siapath)
			for (const siafile in siafiles.toArray()) {
				const file = siafiles.get(siafile)
				yield put(actions.deleteFile(file))
			}
		}
		yield put(actions.getFiles())
	} catch (e) {
		sendError(e)
	}
}

function* getContractCountSaga() {
	try {
		const response = yield siadCall('/renter/contracts')
		yield put(actions.setContractCount(response.contracts.length))
	} catch (e) {
		console.error('error getting contract count: ' + e.toString())
	}
}

function* renameFileSaga(action) {
	try {
		if (action.file.type === 'file') {
			yield siadCall({
				url: '/renter/rename/' + encodeURI(action.file.siapath),
				method: 'POST',
				qs: {
					newsiapath: action.newsiapath,
				},
			})
			yield put(actions.getFiles())
		}
		if (action.file.type === 'directory') {
			const directorypath = action.file.siapath
			const response = yield siadCall('/renter/files')
			const siafiles = ls(List(response.files), directorypath)
			for (const i in siafiles.toArray()) {
				const file = siafiles.get(i)
				const newfilepath = Path.posix.join(action.newsiapath, file.siapath.split(directorypath)[1])
				yield put(actions.renameFile(file, newfilepath))
			}
		}
		yield put(actions.hideRenameDialog())
	} catch (e) {
		sendError(e)
	}
}

export function* dataFetcher() {
	while (true) {
		let tasks = []
		tasks = tasks.concat(yield fork(getDownloadsSaga))
		tasks = tasks.concat(yield fork(getFilesSaga))
		tasks = tasks.concat(yield fork(getUploadsSaga))
		tasks = tasks.concat(yield fork(getContractCountSaga))
		tasks = tasks.concat(yield fork(getWalletBalanceSaga))
		tasks = tasks.concat(yield fork(getWalletSyncstateSaga))
		tasks = tasks.concat(yield fork(getWalletLockstateSaga))
		tasks = tasks.concat(yield fork(getAllowanceSaga))

		yield join(...tasks)
		yield race({
			task: call(delay, 8000),
			cancel: take(constants.FETCH_DATA),
		})
	}
}
export function* watchSetAllowance() {
	yield *takeEvery(constants.SET_ALLOWANCE, setAllowanceSaga)
}
export function* watchGetAllowance() {
	yield *takeEvery(constants.GET_ALLOWANCE, getAllowanceSaga)
}
export function* watchGetDownloads() {
	yield *takeEvery(constants.GET_DOWNLOADS, getDownloadsSaga)
}
export function* watchGetUploads() {
	yield *takeEvery(constants.GET_UPLOADS, getUploadsSaga)
}
export function* watchGetWalletLockstate() {
	yield *takeEvery(constants.GET_WALLET_LOCKSTATE, getWalletLockstateSaga)
}
export function* watchGetFiles() {
	yield *takeEvery(constants.GET_FILES, getFilesSaga)
}
export function* watchDeleteFile() {
	yield *takeEvery(constants.DELETE_FILE, deleteFileSaga)
}
export function* watchGetWalletBalance() {
	yield *takeEvery(constants.GET_WALLET_BALANCE, getWalletBalanceSaga)
}
export function* watchUploadFolder() {
	yield *takeEvery(constants.UPLOAD_FOLDER, uploadFolderSaga)
}
export function* watchGetContractCount() {
	yield *takeEvery(constants.GET_CONTRACT_COUNT, getContractCountSaga)
}
export function* watchUploadFile() {
	yield *takeEvery(constants.UPLOAD_FILE, uploadFileSaga)
}
export function* watchDownloadFile() {
	yield *takeEvery(constants.DOWNLOAD_FILE, downloadFileSaga)
}
export function* watchRenameFile() {
	yield *takeEvery(constants.RENAME_FILE, renameFileSaga)
}
export function* watchGetStorageEstimate() {
	yield *takeEvery(constants.GET_STORAGE_ESTIMATE, getStorageEstimateSaga)
}
export function* watchGetWalletSyncstate() {
	yield *takeEvery(constants.GET_WALLET_SYNCSTATE, getWalletSyncstateSaga)
}
<|endoftext|>


<commit_before>/**
 * @class  	Geo
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 * Provide useful method for geolocation events
 *
 */

/**
 * * **accuracy**: Accuracy of Geo. Must be one of `"ACCURACY_HIGH"`, `"ACCURACY_LOW"`
 * * **useGoogleForGeocode**: Tell to use Google Services instead of Titanium geocoding services.
 * @type {Object}
 */
var config = _.extend({
	accuracy: "ACCURACY_HIGH",
	useGoogleForGeocode: true,
}, Alloy.CFG.geo);
exports.config = config;

function checkForServices() {
	return !!Ti.Geolocation.locationServicesEnabled;
}

/**
 * Alert the user that Location is off
 */
function enableServicesAlert(){
	if (OS_IOS) {
		require('T/util').alert(L('geo_error_title'), L('geo_error_msg'));
	} else {
		require('T/util').simpleAlert(L('geo_error_title'));
	}
}
exports.enableServicesAlert = enableServicesAlert;

/**
 * @deprecated: Use `@getPosition` instead.
 * @param {Function} callback
 */
function localize(callback) {
	Ti.API.warn("[DEPRECATED] The use of 'Geo.localize' is deprecated, use 'Geo.getPosition' instead!");
	getCurrentPosition({
		success: function(e){
			callback({ coords: e });
		},
		error: callback
	});
}
exports.localize = localize;

function decorateRequest(request) {
	if (request.decorated) return request;

	if (request.error===undefined) {
		request.error = function(e) {
			if (e.servicesDisabled) {
				enableServicesAlert();
			} else {
				require('T/util').simpleAlert(L('geo_error_title'));
			}
		};
	}

	request.decorated = true;
	return request;
}

/**
 * Get the current GPS coordinates of user using `Ti.Geolocation.getCurrentPosition`
 *
 * A `geo.start` event is fired at start, and a `geo.end` event is fired on end
 *
 * @param {Object} opt Dictionary for this request
 */
function getCurrentPosition(request) {
	request = decorateRequest(request);

	if (false===checkForServices()) {
		if (_.isFunction(request.error)) request.error({ servicesDisabled: true });
		return;
	}

	if (!request.silent) Ti.App.fireEvent('geo.start');

	Ti.Geolocation.getCurrentPosition(function(e){
		if (!request.silent) Ti.App.fireEvent('geo.end');

		if (e.error) {
			if (_.isFunction(request.error)) request.error({});
			return;
		}

		if (!_.isObject(e.coords)) {
			if (_.isFunction(request.error)) request.error({});
			return;
		}

		if (_.isFunction(request.success)) request.success(e.coords);
	});
}
exports.getCurrentPosition = getCurrentPosition;

/**
 * Open Apple Maps on iOS, Google Maps on Android and route from user location to defined location
 *
 * @param  {Number} lat  	Desination latitude
 * @param  {Number} lng  	Destination longitude
 * @param  {String} [mode] GPS mode used (walking,driving)
 */
function startNavigator(lat, lng, mode) {
	getCurrentPosition({
		success: function(g) {
			var D = OS_IOS ? "http://maps.apple.com/" : "https://maps.google.com/maps/";
			Ti.Platform.openURL(D + require('T/util').buildQuery({
				directionsmode: mode || 'walking',
				saddr: g.latitude + "," + g.longitude,
				daddr: lat + "," + lng
			}));
		}
	});
}
exports.startNavigator = startNavigator;

/**
 * Return the coordinates of an address
 *
 * If some errors occurs, the callback in invoked
 * anyway with `{ error: true, success: false }`
 *
 * @param  {String}   address 	The address to geocode
 * @param  {Function} cb      	The callback
 */
function geocode(address, cb) {
	if (config.useGoogleForGeocode) {

		require('T/net').send({
			url: 'http://maps.googleapis.com/maps/api/geocode/json',
			cache: false,
			data: {
				address: address,
				sensor: 'false'
			},
			mime: 'json',
			success: function(res){

				if (res.status!='OK' || !res.results.length) {
					cb({ error: true });
				} else {
					cb({
						success: true,
						latitude: res.results[0].geometry.location.lat,
						longitude: res.results[0].geometry.location.lng
					});
				}

			},
			error: function(err){
				Ti.API.error("Geo: "+err);
				cb({ error: true });
			}
		});

	} else {

		Ti.Geolocation.forwardGeocoder(address, function(res){

			if (!res.success) {
				cb({ error: true });
			} else {
				cb({
					success: true,
					latitude: res.latitude,
					longitude: res.longitude
				});
			}

		});
	}
}
exports.geocode = geocode;

/**
 * Return the address with the specified coordinates
 *
 * If some errors occurs, the callback in invoked
 * anyway with `{ error: true, success: false }`
 *
 * @param  {Number}   lat 	The latitude of the address
 * @param  {Number}   lng 	The longitude of the address
 * @param  {Function} cb  The callback
 */
function reverseGeocode(lat, lng, cb) {
	if (!lat || !lng) {
		return cb({ error: true });
	}

	if (config.useGoogleForGeocode) {

		require('T/net').send({
			url: 'http://maps.googleapis.com/maps/api/geocode/json',
			noCache: true,
			data: {
				latlng: lat+','+lng,
				sensor: 'false'
			},
			mime: 'json',
			success: function(res){

				if (res.status!='OK' || !res.results.length) {
					cb({ error: true });
				} else {
					cb({
						success: true,
						address: res.results[0].formatted_address,
						results: res.results
					});
				}

			},
			error: function(err){
				Ti.API.error("Geo: "+err);
				cb({ error: true });
			}
		});

	} else {

		Ti.Geolocation.reverseGeocoder(lat, lng, function(res){

			if (!res.success || !res.places || !res.places.length) {
				cb({ error: true });
			} else {
				cb({
					success: true,
					address: res.places[0].address,
					results: res.places
				});
			}

		});
	}
}
exports.reverseGeocode = reverseGeocode;

(function init(){

	Ti.Geolocation.purpose = L('geo_purpose');
	Ti.Geolocation.accuracy = Ti.Geolocation[config.accuracy];

})();
<commit_msg>Deprecation<commit_after>/**
 * @class  	Geo
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 * Provide useful method for geolocation events
 *
 */

/**
 * * **accuracy**: Accuracy of Geo. Must be one of `"ACCURACY_HIGH"`, `"ACCURACY_LOW"`
 * * **useGoogleForGeocode**: Tell to use Google Services instead of Titanium geocoding services.
 * @type {Object}
 */
var config = _.extend({
	accuracy: "ACCURACY_HIGH",
	useGoogleForGeocode: true,
}, Alloy.CFG.geo);
exports.config = config;

function checkForServices() {
	return !!Ti.Geolocation.locationServicesEnabled;
}

/**
 * Alert the user that Location is off
 */
function enableServicesAlert(){
	if (OS_IOS) {
		require('T/util').alert(L('geo_error_title'), L('geo_error_msg'));
	} else {
		require('T/util').simpleAlert(L('geo_error_title'));
	}
}
exports.enableServicesAlert = enableServicesAlert;

/**
 * @method localize
 * @deprecated 1.3.0 Use {@link getPosition} instead.
 * @param {Function} callback
 */
function localize(callback) {
	Ti.API.warn("[DEPRECATED] The use of 'Geo.localize' is deprecated, use 'Geo.getPosition' instead!");
	getCurrentPosition({
		success: function(e){
			callback({ coords: e });
		},
		error: callback
	});
}
exports.localize = localize;

function decorateRequest(request) {
	if (request.decorated) return request;

	if (request.error===undefined) {
		request.error = function(e) {
			if (e.servicesDisabled) {
				enableServicesAlert();
			} else {
				require('T/util').simpleAlert(L('geo_error_title'));
			}
		};
	}

	request.decorated = true;
	return request;
}

/**
 * Get the current GPS coordinates of user using `Ti.Geolocation.getCurrentPosition`
 *
 * A `geo.start` event is fired at start, and a `geo.end` event is fired on end
 *
 * @param {Object} opt Dictionary for this request
 */
function getCurrentPosition(request) {
	request = decorateRequest(request);

	if (false===checkForServices()) {
		if (_.isFunction(request.error)) request.error({ servicesDisabled: true });
		return;
	}

	if (!request.silent) Ti.App.fireEvent('geo.start');

	Ti.Geolocation.getCurrentPosition(function(e){
		if (!request.silent) Ti.App.fireEvent('geo.end');

		if (e.error) {
			if (_.isFunction(request.error)) request.error({});
			return;
		}

		if (!_.isObject(e.coords)) {
			if (_.isFunction(request.error)) request.error({});
			return;
		}

		if (_.isFunction(request.success)) request.success(e.coords);
	});
}
exports.getCurrentPosition = getCurrentPosition;

/**
 * Open Apple Maps on iOS, Google Maps on Android and route from user location to defined location
 *
 * @param  {Number} lat  	Desination latitude
 * @param  {Number} lng  	Destination longitude
 * @param  {String} [mode] GPS mode used (walking,driving)
 */
function startNavigator(lat, lng, mode) {
	getCurrentPosition({
		success: function(g) {
			var D = OS_IOS ? "http://maps.apple.com/" : "https://maps.google.com/maps/";
			Ti.Platform.openURL(D + require('T/util').buildQuery({
				directionsmode: mode || 'walking',
				saddr: g.latitude + "," + g.longitude,
				daddr: lat + "," + lng
			}));
		}
	});
}
exports.startNavigator = startNavigator;

/**
 * Return the coordinates of an address
 *
 * If some errors occurs, the callback in invoked
 * anyway with `{ error: true, success: false }`
 *
 * @param  {String}   address 	The address to geocode
 * @param  {Function} cb      	The callback
 */
function geocode(address, cb) {
	if (config.useGoogleForGeocode) {

		require('T/net').send({
			url: 'http://maps.googleapis.com/maps/api/geocode/json',
			cache: false,
			data: {
				address: address,
				sensor: 'false'
			},
			mime: 'json',
			success: function(res){

				if (res.status!='OK' || !res.results.length) {
					cb({ error: true });
				} else {
					cb({
						success: true,
						latitude: res.results[0].geometry.location.lat,
						longitude: res.results[0].geometry.location.lng
					});
				}

			},
			error: function(err){
				Ti.API.error("Geo: "+err);
				cb({ error: true });
			}
		});

	} else {

		Ti.Geolocation.forwardGeocoder(address, function(res){

			if (!res.success) {
				cb({ error: true });
			} else {
				cb({
					success: true,
					latitude: res.latitude,
					longitude: res.longitude
				});
			}

		});
	}
}
exports.geocode = geocode;

/**
 * Return the address with the specified coordinates
 *
 * If some errors occurs, the callback in invoked
 * anyway with `{ error: true, success: false }`
 *
 * @param  {Number}   lat 	The latitude of the address
 * @param  {Number}   lng 	The longitude of the address
 * @param  {Function} cb  The callback
 */
function reverseGeocode(lat, lng, cb) {
	if (!lat || !lng) {
		return cb({ error: true });
	}

	if (config.useGoogleForGeocode) {

		require('T/net').send({
			url: 'http://maps.googleapis.com/maps/api/geocode/json',
			noCache: true,
			data: {
				latlng: lat+','+lng,
				sensor: 'false'
			},
			mime: 'json',
			success: function(res){

				if (res.status!='OK' || !res.results.length) {
					cb({ error: true });
				} else {
					cb({
						success: true,
						address: res.results[0].formatted_address,
						results: res.results
					});
				}

			},
			error: function(err){
				Ti.API.error("Geo: "+err);
				cb({ error: true });
			}
		});

	} else {

		Ti.Geolocation.reverseGeocoder(lat, lng, function(res){

			if (!res.success || !res.places || !res.places.length) {
				cb({ error: true });
			} else {
				cb({
					success: true,
					address: res.places[0].address,
					results: res.places
				});
			}

		});
	}
}
exports.reverseGeocode = reverseGeocode;

(function init(){

	Ti.Geolocation.purpose = L('geo_purpose');
	Ti.Geolocation.accuracy = Ti.Geolocation[config.accuracy];

})();
<|endoftext|>


<commit_before>
/**
* @license jspm-git
* Copyright (c) 2014 Tauren Mills, contributors
* jspm endpoint for Git Repositories
* License: MIT
*/

'use strict';

var exec = require('child_process').exec;
var path = require('path');
var Promise = require('rsvp').Promise;
var rimraf = require('rimraf');
var ncp = require('ncp').ncp;
var fs = require('fs');
var temp = require('temp');
var semver = require('semver');
var urljoin = require('url-join');

var logging = false;
var vPrefixVersions = [];

var logMsg = function(msg) {
  if (logging) {
    console.log(new Date() + ': ' + msg);
  }
};

var createGitUrl = function(basepath, repo, reposuffix) {
  return urljoin(basepath, repo + reposuffix);
};

var getGitVersion = function() {
  return new Promise(function(resolve, reject) {
    exec('git --version', null, function(err, stdout, stderr) {
      var versionArr;
      if (err) {
        logMsg('Error while reading our the Git version: ' + stderr);
        reject(stderr);
      } else {
        versionArr = stdout.match(/\d.\d.\d/);
        if (versionArr.length === 1) {
          resolve(versionArr[0]);
        } else {
          logMsg('Error while parsing the Git version');
          reject();
        }
      }
    });
  });
};

var cloneGitRepo = function(repoDir, branch, url, execOpt) {
  return getGitVersion().
  then(function(gitVersion) {
    return new Promise(function(resolve, reject) {
      var command;
      // Parameter --single-branch is only supported from Git version 1.7.10 upwards
      if (semver.lt(gitVersion, '1.7.10')) {
        command = 'git clone -b ' + branch + ' --depth 1 ' + url + ' ' + repoDir;
      } else {
        command = 'git clone -b ' + branch + ' --depth 1 --single-branch ' + url + ' ' + repoDir;
      }
      exec(command, execOpt, function(err, stdout, stderr) {
        if (err) {
          logMsg('Error while cloning the git branch: ' + stderr);
          rimraf(repoDir, function() {
            reject(stderr);
          });
        } else {
          resolve();
        }
      });
    });
  });
};

var exportGitRepo = function(repoDir, branch, url, execOpt) {
  return cloneGitRepo(repoDir, branch, url, execOpt).
  then(function() {
    return new Promise(function(resolve, reject) {
      // Remove the .git folder
      rimraf(path.join(repoDir, '.git'), function(err) {
        if (err) {
          logMsg('Error while removing the .git folder: ' + err);
          reject(err);
        } else {
          resolve();
        }
      });
    });
  });
};

var readPackageJSON = function(repoDir) {

  return new Promise(function(resolve, reject) {
    fs.readFile(path.join(repoDir, 'package.json'), 'utf8', function (err, data) {
      if (err) {
        logMsg('Warn: No package.json found');
        resolve({});
      } else {
        try {
          resolve(JSON.parse(data));
        } catch (err) {
          logMsg('Error while parsing package.json: ' + err);
          reject(err);
        }
      }
    });
  });
};

var moveRepoToOutDir = function(repoDir, outDir) {

  return new Promise(function(resolve, reject) {
    ncp(repoDir, outDir, {'stopOnErr': true}, function(err) {
      if (err) {
        logMsg('Error while moving repo to outDir: ' + err);
        // Make sure the the outDir gets removed
        rimraf(outDir, function() {
          reject(err);
        });
      } else {
        rimraf(repoDir, function() {
          resolve();
        });
      }
    });
  });
};

var createTempDir = function() {

  return new Promise(function(resolve, reject) {
    temp.mkdir('jspm-git-', function(err, tempDirPath) {
      if (err) {
        reject();
      } else {
        resolve(tempDirPath);
      }
    });
  });
};

var GitLocation = function(options) {

  logging = options.log === false ? false : true;

  this.execOpt = {
    cwd: options.tmpDir,
    timeout: options.timeout * 1000,
    killSignal: 'SIGKILL'
  };

  if (typeof options.reposuffix !== 'string') {
    options.reposuffix = '.git';
  }

  this.options = options;
};

// static configuration function
GitLocation.configure = function(config, ui) {

  return Promise.resolve(ui.input('Enter the base URL of your git server e.g. https://code.mycompany.com/git/', null))
  .then(function(baseurl) {
    if (!baseurl || baseurl === '') {
      ui.log('warn', 'Invalid base URL was entered');
      return Promise.reject();
    }
    config.baseurl = baseurl;
  })
  .then(function() {
    return Promise.resolve(ui.confirm('Would you like to use the default git repository suffix (.git)?', true))
    .then(function(usedefaultsuffix) {
      if(usedefaultsuffix) {
        // Leave the reposuffix config empty in order to use the default configuration of the endpoint
        return;
      }
      return Promise.resolve(ui.confirm('Would you like to set an empty git repository suffix?', false))
      .then(function(setemptysuffix) {
        if (setemptysuffix) {
          // Set an empty repository suffix
          config.reposuffix = '';
          return;
        }
        return Promise.resolve(ui.input('Enter the git repository suffix', '.git'))
        .then(function(reposuffix) {
          // Use the entered suffix for the endpoint
          config.reposuffix = reposuffix;
        });
      });
    });
  })
  .then(function() {
    return config;
  });
};

GitLocation.prototype = {

  parse: function(name) {
    var parts = name.split('/');
    var packageName = parts.splice(0, 2).join('/');
    return {
      package: packageName,
      path: parts.join('/')
    };
  },

  // return values
  // { versions: { versionhash } }
  // { redirect: 'newrepo' }
  // { notfound: true }
  lookup: function(repo) {
    var self = this;
    return new Promise(function(resolve, reject) {

      var versions, cancel,
          url = createGitUrl(self.options.baseurl, repo, self.options.reposuffix);

      exec('git ls-remote ' + url + ' refs/tags/* refs/heads/*', self.execOpt, function(err, stdout, stderr) {
        if (cancel)
          return;

        if (err) {
          if ((err + '').indexOf('Repository not found') == -1) {
            cancel = true;
            reject(stderr);
          }
          return;
        }

        versions = {};
        var refs = stdout.split('\n');
        for (var i = 0; i < refs.length; i++) {
          if (!refs[i])
            continue;

          var hash = refs[i].substr(0, refs[i].indexOf('\t'));
          var refName = refs[i].substr(hash.length + 1);
          var version;

          if (refName.substr(0, 11) == 'refs/heads/')
            version = '#' + refName.substr(11);

          else if (refName.substr(0, 10) == 'refs/tags/') {
            if (refName.substr(refName.length - 3, 3) == '^{}')
              version = refName.substr(10, refName.length - 13);
            else
              version = refName.substr(10);

            if (version.substr(0, 1) == 'v' && semver.valid(version.substr(1))) {
              version = version.substr(1);
              // note when we remove a "v" which versions we need to add it back to
              // to work out the tag version again
              vPrefixVersions.push(repo + '@' + version);
            }
          }

          versions[version] = hash;
        }

        resolve({ versions: versions });
      });
    });
  },

  // always an exact version
  // assumed that this is run after getVersions so the repo exists
  download: function(repo, version, hash, outDir) {

    var url, tempRepoDir, packageJSONData, self = this;

    if (vPrefixVersions.indexOf(repo + '@' + version) != -1) {
      version = 'v' + version;
    }

    // Automatically track and cleanup files at exit
    temp.track();

    url = createGitUrl(this.options.baseurl, repo, this.options.reposuffix);

    return createTempDir().then(function(tempDir) {
      tempRepoDir = tempDir;
      return exportGitRepo(tempRepoDir, version, url, self.execOpt);
    }).then(function() {
      return readPackageJSON(tempRepoDir);
    }).then(function(data) {
      packageJSONData = data;
      return moveRepoToOutDir(tempRepoDir, outDir);
    }).then(function() {
      return packageJSONData;
    });
  }
};

module.exports = GitLocation;
<commit_msg>Added dispose function as defined in the endpoint API<commit_after>
/**
* @license jspm-git
* Copyright (c) 2014 Tauren Mills, contributors
* jspm endpoint for Git Repositories
* License: MIT
*/

'use strict';

var exec = require('child_process').exec;
var path = require('path');
var Promise = require('rsvp').Promise;
var rimraf = require('rimraf');
var ncp = require('ncp').ncp;
var fs = require('fs');
var temp = require('temp');
var semver = require('semver');
var urljoin = require('url-join');

var logging = false;
var vPrefixVersions = [];

var logMsg = function(msg) {
  if (logging) {
    console.log(new Date() + ': ' + msg);
  }
};

var createGitUrl = function(basepath, repo, reposuffix) {
  return urljoin(basepath, repo + reposuffix);
};

var getGitVersion = function() {
  return new Promise(function(resolve, reject) {
    exec('git --version', null, function(err, stdout, stderr) {
      var versionArr;
      if (err) {
        logMsg('Error while reading our the Git version: ' + stderr);
        reject(stderr);
      } else {
        versionArr = stdout.match(/\d.\d.\d/);
        if (versionArr.length === 1) {
          resolve(versionArr[0]);
        } else {
          logMsg('Error while parsing the Git version');
          reject();
        }
      }
    });
  });
};

var cloneGitRepo = function(repoDir, branch, url, execOpt) {
  return getGitVersion().
  then(function(gitVersion) {
    return new Promise(function(resolve, reject) {
      var command;
      // Parameter --single-branch is only supported from Git version 1.7.10 upwards
      if (semver.lt(gitVersion, '1.7.10')) {
        command = 'git clone -b ' + branch + ' --depth 1 ' + url + ' ' + repoDir;
      } else {
        command = 'git clone -b ' + branch + ' --depth 1 --single-branch ' + url + ' ' + repoDir;
      }
      exec(command, execOpt, function(err, stdout, stderr) {
        if (err) {
          logMsg('Error while cloning the git branch: ' + stderr);
          rimraf(repoDir, function() {
            reject(stderr);
          });
        } else {
          resolve();
        }
      });
    });
  });
};

var exportGitRepo = function(repoDir, branch, url, execOpt) {
  return cloneGitRepo(repoDir, branch, url, execOpt).
  then(function() {
    return new Promise(function(resolve, reject) {
      // Remove the .git folder
      rimraf(path.join(repoDir, '.git'), function(err) {
        if (err) {
          logMsg('Error while removing the .git folder: ' + err);
          reject(err);
        } else {
          resolve();
        }
      });
    });
  });
};

var readPackageJSON = function(repoDir) {

  return new Promise(function(resolve, reject) {
    fs.readFile(path.join(repoDir, 'package.json'), 'utf8', function (err, data) {
      if (err) {
        logMsg('Warn: No package.json found');
        resolve({});
      } else {
        try {
          resolve(JSON.parse(data));
        } catch (err) {
          logMsg('Error while parsing package.json: ' + err);
          reject(err);
        }
      }
    });
  });
};

var moveRepoToOutDir = function(repoDir, outDir) {

  return new Promise(function(resolve, reject) {
    ncp(repoDir, outDir, {'stopOnErr': true}, function(err) {
      if (err) {
        logMsg('Error while moving repo to outDir: ' + err);
        // Make sure the the outDir gets removed
        rimraf(outDir, function() {
          reject(err);
        });
      } else {
        rimraf(repoDir, function() {
          resolve();
        });
      }
    });
  });
};

var createTempDir = function() {

  return new Promise(function(resolve, reject) {
    temp.mkdir('jspm-git-', function(err, tempDirPath) {
      if (err) {
        reject();
      } else {
        resolve(tempDirPath);
      }
    });
  });
};

var GitLocation = function(options) {

  logging = options.log === false ? false : true;

  this.execOpt = {
    cwd: options.tmpDir,
    timeout: options.timeout * 1000,
    killSignal: 'SIGKILL'
  };

  if (typeof options.reposuffix !== 'string') {
    options.reposuffix = '.git';
  }

  this.options = options;
};

// static configuration function
GitLocation.configure = function(config, ui) {

  return Promise.resolve(ui.input('Enter the base URL of your git server e.g. https://code.mycompany.com/git/', null))
  .then(function(baseurl) {
    if (!baseurl || baseurl === '') {
      ui.log('warn', 'Invalid base URL was entered');
      return Promise.reject();
    }
    config.baseurl = baseurl;
  })
  .then(function() {
    return Promise.resolve(ui.confirm('Would you like to use the default git repository suffix (.git)?', true))
    .then(function(usedefaultsuffix) {
      if(usedefaultsuffix) {
        // Leave the reposuffix config empty in order to use the default configuration of the endpoint
        return;
      }
      return Promise.resolve(ui.confirm('Would you like to set an empty git repository suffix?', false))
      .then(function(setemptysuffix) {
        if (setemptysuffix) {
          // Set an empty repository suffix
          config.reposuffix = '';
          return;
        }
        return Promise.resolve(ui.input('Enter the git repository suffix', '.git'))
        .then(function(reposuffix) {
          // Use the entered suffix for the endpoint
          config.reposuffix = reposuffix;
        });
      });
    });
  })
  .then(function() {
    return config;
  });
};

GitLocation.prototype = {

  parse: function(name) {
    var parts = name.split('/');
    var packageName = parts.splice(0, 2).join('/');
    return {
      package: packageName,
      path: parts.join('/')
    };
  },

  // return values
  // { versions: { versionhash } }
  // { redirect: 'newrepo' }
  // { notfound: true }
  lookup: function(repo) {
    var self = this;
    return new Promise(function(resolve, reject) {

      var versions, cancel,
          url = createGitUrl(self.options.baseurl, repo, self.options.reposuffix);

      exec('git ls-remote ' + url + ' refs/tags/* refs/heads/*', self.execOpt, function(err, stdout, stderr) {
        if (cancel)
          return;

        if (err) {
          if ((err + '').indexOf('Repository not found') == -1) {
            cancel = true;
            reject(stderr);
          }
          return;
        }

        versions = {};
        var refs = stdout.split('\n');
        for (var i = 0; i < refs.length; i++) {
          if (!refs[i])
            continue;

          var hash = refs[i].substr(0, refs[i].indexOf('\t'));
          var refName = refs[i].substr(hash.length + 1);
          var version;

          if (refName.substr(0, 11) == 'refs/heads/')
            version = '#' + refName.substr(11);

          else if (refName.substr(0, 10) == 'refs/tags/') {
            if (refName.substr(refName.length - 3, 3) == '^{}')
              version = refName.substr(10, refName.length - 13);
            else
              version = refName.substr(10);

            if (version.substr(0, 1) == 'v' && semver.valid(version.substr(1))) {
              version = version.substr(1);
              // note when we remove a "v" which versions we need to add it back to
              // to work out the tag version again
              vPrefixVersions.push(repo + '@' + version);
            }
          }

          versions[version] = hash;
        }

        resolve({ versions: versions });
      });
    });
  },

  // always an exact version
  // assumed that this is run after getVersions so the repo exists
  download: function(repo, version, hash, outDir) {

    var url, tempRepoDir, packageJSONData, self = this;

    if (vPrefixVersions.indexOf(repo + '@' + version) != -1) {
      version = 'v' + version;
    }

    // Automatically track and cleanup files at exit
    temp.track();

    url = createGitUrl(this.options.baseurl, repo, this.options.reposuffix);

    return createTempDir().then(function(tempDir) {
      tempRepoDir = tempDir;
      return exportGitRepo(tempRepoDir, version, url, self.execOpt);
    }).then(function() {
      return readPackageJSON(tempRepoDir);
    }).then(function(data) {
      packageJSONData = data;
      return moveRepoToOutDir(tempRepoDir, outDir);
    }).then(function() {
      return packageJSONData;
    });
  },

  // sync function to clean up any tmp files / store save caches etc
  dispose: function() {

    // temp folder that has been created during download will be automaically
    // removed at exit due the call of temp.track();
  }
};

module.exports = GitLocation;
<|endoftext|>


<commit_before>'use strict';

var nouns = [
  'cat',
  'dog',
  'mouse',
  'house'
];
var firstNoun = '';
var secondNoun = '';
var metaphor = '';

var numberOfNouns = nouns.length;
var nounIndex1 = 0;
var nounIndex2 = 0;

// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function generateMetaphor(nouns) {
  nounIndex1 = getRandomInt(0, numberOfNouns);
  nounIndex2 = getRandomInt(0, numberOfNouns);

  firstNoun = nouns[nounIndex1];
  secondNoun = nouns[nounIndex2];

  metaphor = firstNoun + ' is a ' + secondNoun + '.';
  console.log(metaphor);
}

generateMetaphor(nouns);
<commit_msg>Capitalize first noun<commit_after>'use strict';

var nouns = [
  'cat',
  'dog',
  'mouse',
  'house'
];
var firstNoun = '';
var secondNoun = '';
var metaphor = '';

var numberOfNouns = nouns.length;
var nounIndex1 = 0;
var nounIndex2 = 0;

// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function generateMetaphor(nouns) {
  nounIndex1 = getRandomInt(0, numberOfNouns);
  nounIndex2 = getRandomInt(0, numberOfNouns);

  firstNoun = capitalizeFirstLetter(nouns[nounIndex1]);
  secondNoun = nouns[nounIndex2];

  metaphor = firstNoun + ' is a ' + secondNoun + '.';
  console.log(metaphor);
}

generateMetaphor(nouns);
<|endoftext|>


<commit_before>'use strict';

const reGenLiInput = require('./li-input')
    , validateNumeric = require('./validate-numeric')
    ;

module.exports = React => {
    const $ = React.createElement;
    const genLiInput = reGenLiInput(React);
    return () => config => {
        const schema = config.schema
            , path = config.path
            , updateState = config.updateState;

        let onChange;
        if (typeof updateState === 'function') {
            const body = { $set: '' };
            const spec = {
                data: path.reduceRight((p, k) => ({ [k]: p }), body)
            };
            onChange = function (event) {
                const val = event.target.value;
                body.$set = Number(val) || val;
                updateState(spec);
            };
        }

        const LiInput = genLiInput({
            schema: schema,
            path: path,
            itype: 'number',
            min: schema.minimum,
            max: schema.maximum,
            onChange: onChange,
            updateState: updateState,
            validate: validateNumeric
        });

        return function Num (props) {
            return $(LiInput(props), props);
        };
    };
};
<commit_msg>fixed number widget for val=0<commit_after>'use strict';

const reGenLiInput = require('./li-input')
    , validateNumeric = require('./validate-numeric')
    ;

module.exports = React => {
    const $ = React.createElement;
    const genLiInput = reGenLiInput(React);
    return () => config => {
        const schema = config.schema
            , path = config.path
            , updateState = config.updateState;

        let onChange;
        if (typeof updateState === 'function') {
            const body = { $set: '' };
            const spec = {
                data: path.reduceRight((p, k) => ({ [k]: p }), body)
            };
            onChange = function (event) {
                const val = event.target.value;
                body.$set = isNaN(val) ? val : Number(val);
                updateState(spec);
            };
        }

        const LiInput = genLiInput({
            schema: schema,
            path: path,
            itype: 'number',
            min: schema.minimum,
            max: schema.maximum,
            onChange: onChange,
            updateState: updateState,
            validate: validateNumeric
        });

        return function Num (props) {
            return $(LiInput(props), props);
        };
    };
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var server = require("http").createServer(app);
var io = require('socket.io').listen(server);
var arDrone = require('ar-drone');
var arDroneConstants = require('ar-drone/lib/constants');
var client  = arDrone.createClient();
// var index = require('./index.ejs');

require('ar-drone-png-stream')(client, { port: 8080 });

app.get('/', function(req, res){
  res.sendfile('index.html');
});

//Whenever someone connects this gets executed
io.on('connection', function(socket){
  console.log('A user connected');

  //Whenever someone disconnects this piece of code executed
  socket.on('disconnect', function () {
    console.log('A user disconnected');
  });

});

server.listen(3000, function(){
  console.log('listening on *:3000');
});

    // app.set('port', process.env.PORT || 3000);
    // app.set('views', __dirname + '/views');
    // app.set('view engine', 'ejs', { pretty: true });
    // app.get('/', function(req, res){
    //   res.sendfile('index.ejs');
    // });
    //
    // server.listen(3000, function(){
    //   console.log('listening on *:3000');
    // });

    // app.use(express.favicon());
    // app.use(express.logger('dev'));
    // app.use(app.router);
    // app.use(express.static(path.join(__dirname, 'public')));
    // app.use("/components", express.static(path.join(__dirname, 'bower_components')));
    // app.use(require('express-jquery')('/jquery.js'));

    // app.use('/', index);

    // png = client.getPngStream();
    // png.on('data', function(){
    //
    // });

// io.sockets.on('connection', function (socket) {
  // socket.emit('event', { message: 'Welcome to cockpit :-)' });
// });

// server.listen(app.get('port'), function() {
//   console.log('AR. Drone WebFlight is listening on port ' + app.get('port'));
// });
<commit_msg>onscreen buttons working to control drone<commit_after>var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var server = require("http").createServer(app);
var io = require('socket.io').listen(server);
var arDrone = require('ar-drone');
var arDroneConstants = require('ar-drone/lib/constants');
var client  = arDrone.createClient();
// var index = require('./index.ejs');

require('ar-drone-png-stream')(client, { port: 8080 });

app.get('/', function(req, res){
  res.sendfile('index.html');
});

//Whenever someone connects this gets executed
io.on('connection', function(socket){
  console.log('A user connected');
  socket.on('takeOff', function () {
    client.takeoff();
    console.log('APP Takeoff');
  });
  socket.on('land', function () {
    client.land();
    console.log('App land');
  });
  socket.on('turnLeft', function () {
    client.clockwise(-0.25);
    console.log('App left');
  });
  socket.on('turnRight', function () {
    client.clockwise(-0.25);
    console.log('App right');
  });
  socket.on('streamVideo', function () {
    console.log('App video');
  });

  //Whenever someone disconnects this piece of code executed
  socket.on('disconnect', function () {
    console.log('A user disconnected');
  });

});

server.listen(3000, function(){
  console.log('listening on *:3000');
});

    // app.set('port', process.env.PORT || 3000);
    // app.set('views', __dirname + '/views');
    // app.set('view engine', 'ejs', { pretty: true });
    // app.get('/', function(req, res){
    //   res.sendfile('index.ejs');
    // });
    //
    // server.listen(3000, function(){
    //   console.log('listening on *:3000');
    // });

    // app.use(express.favicon());
    // app.use(express.logger('dev'));
    // app.use(app.router);
    // app.use(express.static(path.join(__dirname, 'public')));
    // app.use("/components", express.static(path.join(__dirname, 'bower_components')));
    // app.use(require('express-jquery')('/jquery.js'));

    // app.use('/', index);

    // png = client.getPngStream();
    // png.on('data', function(){
    //
    // });

// io.sockets.on('connection', function (socket) {
  // socket.emit('event', { message: 'Welcome to cockpit :-)' });
// });

// server.listen(app.get('port'), function() {
//   console.log('AR. Drone WebFlight is listening on port ' + app.get('port'));
// });
<|endoftext|>