<commit_before>/**
 * @license Copyright 2014 Google Inc. All rights reserved.
 * Use of this source code is governed by the Apache license that can be
 * found in the LICENSE file.
 */

/**
 * @constructor
 * @struct
 * @implements {Tool}
 * @param {ToolContext} toolContext
 * @param {function()} callback
 */
function PipetteTool(toolContext, callback) {}

(function() {

  /**
   * Size of pipette cursor image.
   * @const
   */
  var PIPETTE_CURSOR_SIZE = 16;

  /**
   * Pipette tool. Gets the color of the selected pixel on the
   * display canvas and puts it on the color palette.
   * @constructor
   * @struct
   * @implements {Tool}
   * @param {ToolContext} toolContext
   * @param {function()} callback
   */
  function PipetteTool(toolContext, callback) {
    /**
     * @type {HTMLElement}
     */
    this.sourceCanvas = toolContext.sourceCanvas;

    /**
     * @type {CanvasRenderingContext2D}
     */
    this.sourceContext = toolContext.sourceCanvas.getContext('2d');

    /**
     * Called when color is selected.
     * The parameters are the color, the opacity value of the color
     * and whether the mouse has finished moving.
     * Opacity is a value in [0,1].
     * @type {function(string, number, boolean)}
     */
    this.callback = callback;

    /**
     * The selected color.
     * @type {string}
     */
    this.pipetteColor = 'rgb(0, 0, 0)';

    /**
     * The opacity value of the selected color.
     * @type {number}
     */
    this.opacity = 0;

    /**
     * Whether the mouse is being held down for a drag.
     * @type {boolean}
     */
    this.dragging = false;
  };

  /**
   * Gets the color of the selected pixel.
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseDown = function(mouseCoordinates) {
    this.dragging = true;
    this.mouseMove(mouseCoordinates);
  };

  /**
   * Calls callback.
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseUp = function(mouseCoordinates) {
    this.dragging = false;
    this.callback(this.pipetteColor, this.opacity, true);
  };

  /**
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseLeave = function(mouseCoordinates) {
  };

  /**
   * Gets color of pixel under mouse and calls callback.
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseMove = function(mouseCoordinates) {
    // Return if pipette moves outside canvas.
    if (!this.dragging || mouseCoordinates.sourceX > this.sourceCanvas.width ||
        mouseCoordinates.sourceY > this.sourceCanvas.height)
      return;

    var imageData = this.sourceContext.getImageData(
        mouseCoordinates.sourceX, mouseCoordinates.sourceY,
        1, 1);
    // Checks if pixel is valid, else set it to an array of zeros.
    var pixel = imageData.data || [0, 0, 0, 0];
    var pixelColor = 'rgb(' +
        pixel[0] + ', ' +
        pixel[1] + ', ' +
        pixel[2] + ')';
    // Selected colour is stored in variable pipetteColor.
    this.pipetteColor = pixelColor;
    // The opacity, given as a value from 0 to 255,
    // is converted into a value from 0 to 1.
    this.opacity = pixel[3] / 255;
    this.callback(this.pipetteColor, this.opacity, false);
  };

  /**
   * Set cursor guide image.
   * @param {Element} cursorDiv
   * @param {MouseCoordinates} mouseCoordinates
   * @param {number} zoomFactor
   * @return {boolean}
   */
  PipetteTool.prototype.updateCursorGuide = function(
      cursorDiv, mouseCoordinates, zoomFactor) {
    // Set background image to pipette image.
    cursorDiv.style.width = PIPETTE_CURSOR_SIZE + 'px';
    cursorDiv.style.height = PIPETTE_CURSOR_SIZE + 'px';
    cursorDiv.style.backgroundImage = 'url("images/pipette_cursor.png")';

    // Tip of pipette matches mouse co-ordinate.
    cursorDiv.style.left =
        mouseCoordinates.sourceX * zoomFactor + 'px';
    cursorDiv.style.top =
        mouseCoordinates.sourceY * zoomFactor - PIPETTE_CURSOR_SIZE + 'px';
    return true;
  };

  bitmapper.PipetteTool = PipetteTool;
})();
<commit_msg>Fix pipette cursor flickering.<commit_after>/**
 * @license Copyright 2014 Google Inc. All rights reserved.
 * Use of this source code is governed by the Apache license that can be
 * found in the LICENSE file.
 */

/**
 * @constructor
 * @struct
 * @implements {Tool}
 * @param {ToolContext} toolContext
 * @param {function()} callback
 */
function PipetteTool(toolContext, callback) {}

(function() {

  /**
   * Size of pipette cursor image.
   * @const
   */
  var PIPETTE_CURSOR_SIZE = 16;

  /**
   * Pipette tool. Gets the color of the selected pixel on the
   * display canvas and puts it on the color palette.
   * @constructor
   * @struct
   * @implements {Tool}
   * @param {ToolContext} toolContext
   * @param {function()} callback
   */
  function PipetteTool(toolContext, callback) {
    /**
     * @type {HTMLElement}
     */
    this.sourceCanvas = toolContext.sourceCanvas;

    /**
     * @type {CanvasRenderingContext2D}
     */
    this.sourceContext = toolContext.sourceCanvas.getContext('2d');

    /**
     * Called when color is selected.
     * The parameters are the color, the opacity value of the color
     * and whether the mouse has finished moving.
     * Opacity is a value in [0,1].
     * @type {function(string, number, boolean)}
     */
    this.callback = callback;

    /**
     * The selected color.
     * @type {string}
     */
    this.pipetteColor = 'rgb(0, 0, 0)';

    /**
     * The opacity value of the selected color.
     * @type {number}
     */
    this.opacity = 0;

    /**
     * Whether the mouse is being held down for a drag.
     * @type {boolean}
     */
    this.dragging = false;

    /**
     * Pipette cursor image.
     * @type {Element}
     */
    this.pipetteCursorDiv = document.createElement('div');
    this.pipetteCursorDiv.style.width = PIPETTE_CURSOR_SIZE + 'px';
    this.pipetteCursorDiv.style.height = PIPETTE_CURSOR_SIZE + 'px';
    this.pipetteCursorDiv.style.backgroundImage =
        'url("images/pipette_cursor.png")';

  };

  /**
   * Gets the color of the selected pixel.
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseDown = function(mouseCoordinates) {
    this.dragging = true;
    this.mouseMove(mouseCoordinates);
  };

  /**
   * Calls callback.
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseUp = function(mouseCoordinates) {
    this.dragging = false;
    this.callback(this.pipetteColor, this.opacity, true);
  };

  /**
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseLeave = function(mouseCoordinates) {
  };

  /**
   * Gets color of pixel under mouse and calls callback.
   * @param {MouseCoordinates} mouseCoordinates
   */
  PipetteTool.prototype.mouseMove = function(mouseCoordinates) {
    // Return if pipette moves outside canvas.
    if (!this.dragging || mouseCoordinates.sourceX > this.sourceCanvas.width ||
        mouseCoordinates.sourceY > this.sourceCanvas.height)
      return;

    var imageData = this.sourceContext.getImageData(
        mouseCoordinates.sourceX, mouseCoordinates.sourceY,
        1, 1);
    // Checks if pixel is valid, else set it to an array of zeros.
    var pixel = imageData.data || [0, 0, 0, 0];
    var pixelColor = 'rgb(' +
        pixel[0] + ', ' +
        pixel[1] + ', ' +
        pixel[2] + ')';
    // Selected colour is stored in variable pipetteColor.
    this.pipetteColor = pixelColor;
    // The opacity, given as a value from 0 to 255,
    // is converted into a value from 0 to 1.
    this.opacity = pixel[3] / 255;
    this.callback(this.pipetteColor, this.opacity, false);
  };

  /**
   * Set cursor guide image.
   * @param {Element} cursorDiv
   * @param {MouseCoordinates} mouseCoordinates
   * @param {number} zoomFactor
   * @return {boolean}
   */
  PipetteTool.prototype.updateCursorGuide = function(
      cursorDiv, mouseCoordinates, zoomFactor) {
    cursorDiv.appendChild(this.pipetteCursorDiv);
    // Tip of pipette matches mouse co-ordinate.
    cursorDiv.style.left =
        mouseCoordinates.sourceX * zoomFactor + 'px';
    cursorDiv.style.top =
        mouseCoordinates.sourceY * zoomFactor - PIPETTE_CURSOR_SIZE + 'px';
    return true;
  };

  bitmapper.PipetteTool = PipetteTool;
})();
<|endoftext|>


<commit_before>'use strict';

var easyAsync = require('./index.js');

var exampleTask = function(callback){
  console.log('starting task');
  setTimeout(function(){
    console.log('done with task');
    callback();
  }, 1000);
};

var exampleErrorTask = function(callback){
  console.log('starting task');
  setTimeout(function(){
    callback(new Error('BOOM!'));
  }, 1000);
};

/////////////////////////////////////////
// 3 tasks in series, 3 tasks in parallel
/////////////////////////////////////////

easyAsync.start(exampleTask)
.thenStart(exampleTask)
.thenStart(exampleTask)
.thenStart(function() {
  console.log('continuing after tasks in series');
  startParallelWork(); // passes control on to next example
});

// "thenStart" used above for tasks in series,
// "andStart" used below for tasks in parallel.

function startParallelWork() {
  easyAsync.start(exampleTask)
  .andStart(exampleTask)
  .andStart(exampleTask)
  .thenStart(function() {
    console.log('continuing after tasks in parallel');
    startRiskyWork();
  });
}

function startParallelWork() {
  easyAsync.start(exampleTask)
  .andStart(exampleTask)
  .andStart(exampleErrorTask)
  .thenStart(function() {
    console.log('continuing after risky work');
  })
  .onError(function(err){
    console.log('error handler received an error');
    console.error(err);
  });
}

<commit_msg>some lint fixes for example<commit_after>'use strict';

var easyAsync = require('./index.js');

var exampleTask = function (callback) {
  console.log('starting task');
  setTimeout(function () {
    console.log('done with task');
    callback();
  }, 1000);
};

var exampleErrorTask = function (callback) {
  console.log('starting task');
  setTimeout(function () {
    callback(new Error('BOOM!'));
  }, 1000);
};

/////////////////////////////////////////
// 3 tasks in series, 3 tasks in parallel
/////////////////////////////////////////

easyAsync.start(exampleTask)
.thenStart(exampleTask)
.thenStart(exampleTask)
.thenStart(function () {
  console.log('continuing after tasks in series');
  startParallelWork(); // passes control on to next example
});

// "thenStart" used above for tasks in series,
// "andStart" used below for tasks in parallel.

var startParallelWork = function () {
  easyAsync.start(exampleTask)
  .andStart(exampleTask)
  .andStart(exampleTask)
  .thenStart(function () {
    console.log('continuing after tasks in parallel');
    startRiskyWork();
  });
}

var startParallelWork = function () {
  easyAsync.start(exampleTask)
  .andStart(exampleTask)
  .andStart(exampleErrorTask)
  .thenStart(function () {
    console.log('continuing after risky work');
  })
  .onError(function (err) {
    console.log('error handler received an error');
    console.error(err);
  });
}

<|endoftext|>


<commit_before>define(function(require) {
    "use strict";
    var $ = require('jquery');
    var ui = require('jquery-ui');
    var dialog = require('base/js/dialog');
    var lmod_class = require('./lmod.js');
    var utils = require('base/js/utils');

    var base_url = utils.get_body_data("baseUrl");

    var lmod = new lmod_class.Lmod({'base_url' : base_url});
    var search_source = null;

    var lmod_tab_html = $([
        '
',
        '
',
        '
',
        '      <input id="modules" class="form-control input-lg" placeholder="Search available modules..." style="width:100%">',
        '
',
        '
',
        '
',
        '
Loaded module list
',
        '
',
        '
'
    ].join('\n'));

    function refresh_view() {
        $.when(lmod.avail(),
               lmod.list(),
               lmod.savelist())
        .done(function(avail, list, savelist) {
            let avail_set = new Set(avail[0]);
            let modulelist = list[0];
            modulelist.map(function(item){ avail_set.delete(item) });
            modulelist.sort();
            search_source = Array.from(avail_set);
            init_list_view();
            update_list_view(modulelist);
            update_restore_view(savelist[0]);
        });
    }

    async function show_module(module) {
        var data = await lmod.show(module);
        var datalist = data.split('\n');
        var textarea = $('
').text($.trim(datalist.slice(3).join('\n')));
        var dialogform = $('
').append(textarea);
        var path = datalist[1].slice(0, -1);
        dialog.modal({
            title: path,
            body: dialogform,
            default_button: "Ok",
            buttons : {
                "Ok" : {}
            }
        });
    }

    function save_collection(event) {
        var dialog_body = $('
').append(
            $("
").addClass("save-message")
                .text('Enter a new collection name:')
        ).append(
            $("
")
        ).append(
            $('<input/>').attr('type','text').attr('size','25').addClass('form-control').attr('placeholder', 'default')
        );
        var d = dialog.modal({
            title: "Save Collection",
            body: dialog_body,
            keyboard_manager: this.keyboard_manager,
            default_button: "Cancel",
            buttons : {
                "Cancel": {},
                "Save": {
                    class: "btn-primary",
                    click: function () {
                        var name = d.find('input').val();
                        lmod.save(name ? name : 'default').then(refresh_view);
                    }
                }
            },
            open : function () {
                /**
                 * Upon ENTER, click the OK button.
                 */
                d.find('input[type="text"]').keydown(function (event) {
                    if (event.which === keyboard.keycodes.enter) {
                        d.find('.btn-primary').first().click();
                        return false;
                    }
                });
                d.find('input[type="text"]').focus().select();
            }
        });
    }

    function init_list_view() {
        var list = $("#lmod_list");
        list.html("");
        list.append($('
').addClass('row list_header')
                      .append($('
').addClass("col-sm-8").text("Loaded modules"))
                      .append($('
').addClass("col-sm-4 no-padding tree-buttons")
                                        .append($('
').addClass('pull-right')
                                                          .append($('
').attr('id', 'save-button')
                                                                            .addClass('btn-group')
                                                                            .append($('<button>').addClass('btn btn-default btn-xs')
                                                                                .text('Save')
                                                                                .click(save_collection)))
                                                          .append(" ")
                                                          .append($('
').attr('id', 'restore-buttons')
                                                                            .addClass('btn-group')
                                                                            .append($('<button>').addClass('dropdown-toggle btn btn-default btn-xs')
                                                                                .attr("data-toggle", "dropdown")
                                                                                .append($('').text('Restore '))
                                                                                .append($('').addClass('caret')))
                                                                            .append($('
').addClass('dropdown-menu')
                                                                                .attr('id', 'restore-menu'))))));
    }

    function update_restore_view(data) {
        var list = $("#restore-menu");
        data.map(function(item) {
            var li = $('
').attr('id', 'savelist-'+item)
                              .append($('').attr('href', '#')
                                              .text(item))
                              .click(function(e) { lmod.restore(item) });
            list.append(li);
        })
    }

    function update_list_view(data) {
        var list = $("#lmod_list");

        data.map(function(item) {
            var li = $('
').addClass("list_item row");
            var col = $('
').addClass("col-md-12");
            col.append($('').addClass('item_link')
                               .attr('href', "#lmod_list")
                               .text(item)
                               .click(function(e) { show_module(item) }));
            col.append($('
').addClass('item_buttons pull-right')
                                 .append($('<button>').addClass('btn btn-warning btn-xs')
                                                      .text('Unload')
                                                      .click(function(e) { lmod.unload(item) })));
            li.append(col);
            list.append(li);
        });
    }

    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    function load() {
        if (!IPython.notebook_list) return;
        $(".tab-content").append(lmod_tab_html);
        refresh_view();
        $("#tabs").append(
            $('
')
            .append(
                $('')
                .attr('href', '#lmod')
                .attr('data-toggle', 'tab')
                .text('Softwares')
                .click(function (e) {
                    window.history.pushState(null, null, '#lmod');
                })
            )
        );
        $( "#modules" )
        // don't navigate away from the field on tab when selecting an item
        .on( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
        })
        .on('keyup', function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                var modules = split($.trim(event.target.value));
                modules.pop();

                lmod.load(modules).then(refresh_view);
                event.target.value = "";
            }
        })
        .autocomplete({
            minLength: 0,
            source: function( request, response ) {
              // delegate back to autocomplete, but extract the last term
              response( $.ui.autocomplete.filter(
                search_source, extractLast( request.term ) ) );
            },
            focus: function() {
              // prevent value inserted on focus
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push( ui.item.value );
              // add placeholder to get the comma-and-space at the end
              terms.push( "" );
              this.value = terms.join( ", " );
              return false;
            }
        });
    }
    return {
        load_ipython_extension: load
    };
});
<commit_msg>Regroup most of html in a single variable<commit_after>define(function(require) {
    "use strict";
    var $ = require('jquery');
    var ui = require('jquery-ui');
    var dialog = require('base/js/dialog');
    var lmod_class = require('./lmod.js');
    var utils = require('base/js/utils');

    var base_url = utils.get_body_data("baseUrl");

    var lmod = new lmod_class.Lmod({'base_url' : base_url});
    var search_source = null;

    var lmod_tab_html = $([
'
',
'
',
'
',
'            <input id="modules" class="form-control input-lg" placeholder="Search available modules..." style="width:100%">',
'
',
'
',
'
',
'
',
'
Loaded Modules
',
'
',
'
',
'
',
'                        <button class="btn btn-default btn-xs" id="save-button">Save</button>',
'
 ',
'
',
'                        <button class="dropdown-toggle btn btn-default btn-xs" id="restore-buttons">',
'                            Restore ',
'                            ',
'                        </button>',
'
',
'
',
'
',
'
',
'
',
'
',
'
',
    ].join('\n'));

    function refresh_view() {
        $.when(lmod.avail(),
               lmod.list(),
               lmod.savelist())
        .done(function(avail, list, savelist) {
            let avail_set = new Set(avail[0]);
            let modulelist = list[0];
            modulelist.map(function(item){ avail_set.delete(item) });
            modulelist.sort();
            search_source = Array.from(avail_set);
            update_list_view(modulelist);
            update_restore_view(savelist[0]);
        });
    }

    async function show_module(module) {
        var data = await lmod.show(module);
        var datalist = data.split('\n');
        var textarea = $('
').text($.trim(datalist.slice(3).join('\n')));
        var dialogform = $('
').append(textarea);
        var path = datalist[1].slice(0, -1);
        dialog.modal({
            title: path,
            body: dialogform,
            default_button: "Ok",
            buttons : {
                "Ok" : {}
            }
        });
    }

    function save_collection(event) {
        var dialog_body = $('
').append(
            $("
").addClass("save-message")
                .text('Enter a new collection name:')
        ).append(
            $("
")
        ).append(
            $('<input/>').attr('type','text').attr('size','25').addClass('form-control').attr('placeholder', 'default')
        );
        var d = dialog.modal({
            title: "Save Collection",
            body: dialog_body,
            keyboard_manager: this.keyboard_manager,
            default_button: "Cancel",
            buttons : {
                "Cancel": {},
                "Save": {
                    class: "btn-primary",
                    click: function () {
                        var name = d.find('input').val();
                        lmod.save(name ? name : 'default').then(refresh_view);
                    }
                }
            },
            open : function () {
                /**
                 * Upon ENTER, click the OK button.
                 */
                d.find('input[type="text"]').keydown(function (event) {
                    if (event.which === keyboard.keycodes.enter) {
                        d.find('.btn-primary').first().click();
                        return false;
                    }
                });
                d.find('input[type="text"]').focus().select();
            }
        });
    }

    function update_restore_view(data) {
        var list = $("#restore-menu");
        data.map(function(item) {
            var li = $('
').attr('id', 'savelist-'+item)
                              .append($('').attr('href', '#')
                                              .text(item))
                              .click(function(e) { lmod.restore(item) });
            list.append(li);
        })
    }

    function update_list_view(data) {
        $("#list_header").nextAll().remove();
        var list = $("#lmod_list");

        data.map(function(item) {
            var li = $('
').addClass("list_item row");
            var col = $('
').addClass("col-md-12");
            col.append($('').addClass('item_link')
                               .attr('href', "#lmod_list")
                               .text(item)
                               .click(function(e) { show_module(item) }));
            col.append($('
').addClass('item_buttons pull-right')
                                 .append($('<button>').addClass('btn btn-warning btn-xs')
                                                      .text('Unload')
                                                      .click(function(e) { lmod.unload(item) })));
            li.append(col);
            list.append(li);
        });
    }

    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    function load() {
        if (!IPython.notebook_list) return;
        $(".tab-content").append(lmod_tab_html);
        $("#save-button").click(save_collection);
        $("#tabs").append(
            $('
')
            .append(
                $('')
                .attr('href', '#lmod')
                .attr('data-toggle', 'tab')
                .text('Softwares')
                .click(function (e) {
                    window.history.pushState(null, null, '#lmod');
                })
            )
        );
        $( "#modules" )
        // don't navigate away from the field on tab when selecting an item
        .on( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
        })
        .on('keyup', function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                var modules = split($.trim(event.target.value));
                modules.pop();

                lmod.load(modules).then(refresh_view);
                event.target.value = "";
            }
        })
        .autocomplete({
            minLength: 0,
            source: function( request, response ) {
              // delegate back to autocomplete, but extract the last term
              response( $.ui.autocomplete.filter(
                search_source, extractLast( request.term ) ) );
            },
            focus: function() {
              // prevent value inserted on focus
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push( ui.item.value );
              // add placeholder to get the comma-and-space at the end
              terms.push( "" );
              this.value = terms.join( ", " );
              return false;
            }
        });

        refresh_view();
    }
    return {
        load_ipython_extension: load
    };
});
<|endoftext|>


<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: elizasapir
 * Date: 9/10/13
 * Time: 5:58 PM
 * To change this template use File | Settings | File Templates.
 */

/**
 * Cordova kWidget lib
 */
(function(kWidget){ "use strict"
	if( !kWidget ){
		return ;
	}
	var init = function(){

		if ( kWidget.isAndroid() ){
			var executeCordova;
			cordova.define("cordova/plugin/NativeComponentPlugin",
				function(require, exports, module) {
					executeCordova = require("cordova/exec");
					executeCordova( null, null, "cordovaInitialized", [], "NativeComponentPlugin" );
				});
			//This is mandatory for supporting cordova plugins
			if (!window.plugins) {
				window.plugins = {};
			}
			//TODO define new plugin - "OfflineContentPlugin"
			if (!window.plugins.NativeComponentPlugin) {
				window.plugins.NativeComponentPlugin = cordova.require( "cordova/plugin/NativeComponentPlugin" );
			}
		}
		cordova.kWidget = {
			// This element is populated by cordova
			proxyElement: null,
			// callbacks to auth object events go here:
			embed : function( targetId, settings ){
				this.target = document.getElementById( targetId );
				this.target.style.cssText = "background-color:transparent;";
				//kWidget.getIframeRequest( targetId, settings ) - we get it encoded so we decode before encoding whole url again
				this.iframeUrl = kWidget.getIframeUrl() + '?' + decodeURIComponent(kWidget.getIframeRequest( targetId, settings ));
				this.iframeUrl += '#' + JSON.stringify( window.preMwEmbedConfig );
				this.addApi( this.target );
				this.drawPlayer( this.target );
				this.exec( "setIframeUrl", [ this.iframeUrl ], "NativeComponentPlugin" );
				var _this = this;
				window.addEventListener('orientationchange', function(){
					//when we get this event the new dimensions aren't set yet
					if ( kWidget.isAndroid() ){
						setTimeout( function() {
							_this.drawPlayer( _this.target );
						}, 250 );
					}else {
						_this.drawPlayer( _this.target );
					}
				});
			},
			addApi: function( target ){
				target.exec = this.exec;
				target.evaluate = this.evaluate;
				target.sendNotification = this.sendNotification;
				target.addJsListener = this.addJsListener;
				target.asyncEvaluate = this.asyncEvaluate;
				target.setKDPAttribute = this.setKDPAttribute;
				target.removeJsListener = this.removeJsListener;
			},
			exec: function( command, args, pluginName ){
				if( args == undefined || !args ){
					args = [];
				}

				// Supporting HTML5 player version 2.1 and lower
				// Since plugin name was set hardcoded to "NativeComponentPlugin"
				if( pluginName == undefined || !pluginName ){
					pluginName = "NativeComponentPlugin";
				}

				if ( kWidget.isAndroid() ){
					cordova.exec = executeCordova;
				}
				cordova.exec(null, null, pluginName, command, args);
			},
			evaluate:function(){
				this.exec( "evaluate", [ '' ], "NativeComponentPlugin" );
			},
			sendNotification:function( notificationName, notificationData ){
				this.exec( "sendNotification", [ notificationName, JSON.stringify( notificationData ) ], "NativeComponentPlugin" );
			},
			addJsListener: function( notificationName, callbackName ){
				this.exec( "addJsListener", [ notificationName, callbackName ] );
			},
			removeJsListener: function( notificationName, callbackName ){
				this.exec( "removeJsListener", [ notificationName, callbackName ] );
			},
			asyncEvaluate: function( expression, callbackName ) {
				this.exec( "asyncEvaluate", [ expression, callbackName ] );
			},
			setKDPAttribute: function( host, prop, value ) {
				this.exec( "setKDPAttribute", [ host, prop, value ] );
			},
			drawPlayer: function( target ){
				// get target size + position
				var videoElementRect = target.getBoundingClientRect();
				var x = videoElementRect.left;
				var y = videoElementRect.top + document.body.scrollTop;
				var w = videoElementRect.right - videoElementRect.left;
				var h = videoElementRect.bottom - videoElementRect.top;
				this.exec( "drawVideoNativeComponent", [ x, y, w, h ], "NativeComponentPlugin" );
			}
		};
	}
	document.addEventListener( "deviceready", init, false );
})( window.kWidget );<commit_msg>supporting multi plugins on cordova<commit_after>/**
 * Created with JetBrains WebStorm.
 * User: elizasapir
 * Date: 9/10/13
 * Time: 5:58 PM
 * To change this template use File | Settings | File Templates.
 */

/**
 * Cordova kWidget lib
 */
(function(kWidget){ "use strict"
	if( !kWidget ){
		return ;
	}
	var init = function(){

		if ( kWidget.isAndroid() ){
			var executeCordova;
			cordova.define("cordova/plugin/NativeComponentPlugin",
				function(require, exports, module) {
					executeCordova = require("cordova/exec");
					executeCordova( null, null, "cordovaInitialized", [], "NativeComponentPlugin" );
				});
			//This is mandatory for supporting cordova plugins
			if (!window.plugins) {
				window.plugins = {};
			}
			//TODO define new plugin - "OfflineContentPlugin"
			if (!window.plugins.NativeComponentPlugin) {
				window.plugins.NativeComponentPlugin = cordova.require( "cordova/plugin/NativeComponentPlugin" );
			}
		}
		cordova.kWidget = {
			// This element is populated by cordova
			proxyElement: null,
			// callbacks to auth object events go here:
			embed : function( targetId, settings ){
				this.target = document.getElementById( targetId );
				this.target.style.cssText = "background-color:transparent;";
				//kWidget.getIframeRequest( targetId, settings ) - we get it encoded so we decode before encoding whole url again
				this.iframeUrl = kWidget.getIframeUrl() + '?' + decodeURIComponent(kWidget.getIframeRequest( targetId, settings ));
				this.iframeUrl += '#' + JSON.stringify( window.preMwEmbedConfig );
				this.addApi( this.target );
				this.drawPlayer( this.target );
				this.exec( "setIframeUrl", [ this.iframeUrl ], "NativeComponentPlugin" );
				var _this = this;
				window.addEventListener('orientationchange', function(){
					//when we get this event the new dimensions aren't set yet
					if ( kWidget.isAndroid() ){
						setTimeout( function() {
							_this.drawPlayer( _this.target );
						}, 250 );
					}else {
						_this.drawPlayer( _this.target );
					}
				});
			},
			addApi: function( target ){
				target.exec = this.exec;
				target.evaluate = this.evaluate;
				target.sendNotification = this.sendNotification;
				target.addJsListener = this.addJsListener;
				target.asyncEvaluate = this.asyncEvaluate;
				target.setKDPAttribute = this.setKDPAttribute;
				target.removeJsListener = this.removeJsListener;
			},
			exec: function( command, args, pluginName ){
				if( args == undefined || !args ){
					args = [];
				}

				// Supporting HTML5 player version 2.1 and lower
				// Since plugin name was set hardcoded to "NativeComponentPlugin"
				if( pluginName == undefined || !pluginName ){
					pluginName = "NativeComponentPlugin";
				}

				if ( kWidget.isAndroid() ){
					cordova.exec = executeCordova;
				}
				cordova.exec(null, null, pluginName, command, args);
			},
			evaluate:function(){
				this.exec( "evaluate", [ '' ], "NativeComponentPlugin" );
			},
			sendNotification:function( notificationName, notificationData ){
				this.exec( "sendNotification", [ notificationName, JSON.stringify( notificationData ) ], "NativeComponentPlugin" );
			},
			addJsListener: function( notificationName, callbackName ){
				this.exec( "addJsListener", [ notificationName, callbackName ], "NativeComponentPlugin" );
			},
			removeJsListener: function( notificationName, callbackName ){
				this.exec( "removeJsListener", [ notificationName, callbackName ], "NativeComponentPlugin" );
			},
			asyncEvaluate: function( expression, callbackName ) {
				this.exec( "asyncEvaluate", [ expression, callbackName ], "NativeComponentPlugin" );
			},
			setKDPAttribute: function( host, prop, value ) {
				this.exec( "setKDPAttribute", [ host, prop, value ], "NativeComponentPlugin" );
			},
			drawPlayer: function( target ){
				// get target size + position
				var videoElementRect = target.getBoundingClientRect();
				var x = videoElementRect.left;
				var y = videoElementRect.top + document.body.scrollTop;
				var w = videoElementRect.right - videoElementRect.left;
				var h = videoElementRect.bottom - videoElementRect.top;
				this.exec( "drawVideoNativeComponent", [ x, y, w, h ], "NativeComponentPlugin" );
			}
		};
	}
	document.addEventListener( "deviceready", init, false );
})( window.kWidget );<|endoftext|>


<commit_before>(function () { "use strict";

var _ = require('lodash');
var util = require('util');
var assert = require('assert');
var Q = require('q');
var buscomponent = require('./stbuscomponent.js');
var deepupdate = require('./lib/deepupdate.js');
var debug = require('debug')('sotrade:db');
var debugSQL = require('debug')('sotrade:db:SQL');

/**
 * Provides access to a (MySQL) database for storing and fetching information
 *
 * @public
 * @module dbbackend
 */

/**
 * Main object of the {@link module:dbbackend} module
 *
 * @augments module:stbuscomponent~STBusComponent
 *
 * @property {object} dbmod  The node.js module for database connection
 * @property {object} wConnectionPool  A connection pool for connections
 *                                     requiring write access.
 * @property {object} rConnectionPool  A connection pool for connections
 *                                     not requiring write access.
 * @property {int} openConnections  The current count of in-use connections
 * @property {boolean} isShuttingDown  Flag that indicates server shutdown
 *
 * @public
 * @constructor module:dbbackend~Database
 */
function Database () {
	Database.super_.apply(this, arguments);

	this.dbmod = null;
	this.wConnectionPool = null;
	this.rConnectionPool = null;
	this.openConnections = 0;
	this.deadlockCount = 0;
	this.queryCount= 0;
	this.isShuttingDown = false;
	this.writableNodes = [];
	this.id = 0;
}

util.inherits(Database, buscomponent.BusComponent);

Database.prototype._init = function() {
	var self = this;

	debug('Initing database');

	return self.getServerConfig().then(function(cfg) {
		self.dbmod = cfg.dbmod || require('mysql');

		self.wConnectionPool = self.dbmod.createPoolCluster(cfg.db.clusterOptions);
		self.rConnectionPool = self.dbmod.createPoolCluster(cfg.db.clusterOptions);
		self.writableNodes = [];

		for (var i = 0; i < cfg.db.clusterOptions.order.length; ++i) {
			var id = cfg.db.clusterOptions.order[i];
			assert.ok(cfg.db.cluster[id]);
			var opt = deepupdate({}, cfg.db.cluster[id], cfg.db);

			if (opt.ssl === 'default')
				opt.ssl = cfg.ssl || {};

			debug('Create pool node', opt.writable, opt.readable, id);

			if (opt.writable) {
				self.writableNodes.push(id);
				self.wConnectionPool.add(id, opt);
			}

			if (opt.readable)
				self.rConnectionPool.add(id, opt);
		}

		self.wConnectionPool.on('remove', function(nodeId) {
			debug('Connection removed from writing pool!');

			self.writableNodes = _.without(self.writableNodes, nodeId);
			if (self.writableNodes.length == 0)
				self.emitImmediate('change-readability-mode', { readonly: true });
		});

		self.wConnectionPool.on('remove', function() { self.emitError(new Error('DB lost write connection')); });
		self.rConnectionPool.on('remove', function() { self.emitError(new Error('DB lost read connection')); });

		self.inited = true;
		self.openConnections = 0;

		/*
		 * Note: We don't set isShuttingDown = true here.
		 * This happens so we can actually resurrect the database connection
		 * during the shutdown process temporarily, so other components can complete
		 * any remaining work in progress.
		 */
	});
};

Database.prototype.shutdown = buscomponent.listener('localMasterShutdown', function() {
	this.isShuttingDown = true;

	debug('Database shutdown');

	if (this.openConnections == 0) {
		if (this.wConnectionPool) {
			this.wConnectionPool.end();
			this.wConnectionPool = null;
		}

		if (this.rConnectionPool) {
			this.rConnectionPool.end();
			this.rConnectionPool = null;
		}

		this.inited = false;
	}
});

/**
 * Provides some database usage statistics, like deadlock and query counts.
 *
 * @function busreq~dbUsageStatistics
 */
Database.prototype.usageStatistics = buscomponent.provide('dbUsageStatistics', [], function() {
	return {
		deadlockCount: this.deadlockCount,
		queryCount: this.queryCount,
		writableNodes: this.writableNodes.length
	};
});

/**
 * Executes an SQL query on the database.
 * Your local {@link module:qctx~QContext}’s query method
 * invokes this – if available, consider using it in order to map all
 * actions to the current context.
 *
 * @param {string} query  The SQL query
 * @param {Array} args  Parameters to escape and insert into the query
 * @param {boolean} readonly  Indicates whether this query can use the read-only pool
 *
 * @function busreq~dbQuery
 */
Database.prototype._query = buscomponent.provide('dbQuery', ['query', 'args', 'readonly'],
	buscomponent.needsInit(function(query, args, readonly)
{
	var self = this, origArgs = arguments;

	if (typeof readonly !== 'boolean')
		readonly = (query.trim().indexOf('SELECT') == 0);

	return self._getConnection(true, function /* restart */() {
		return self._query.apply(self, origArgs);
	}, readonly).then(function(connection) {
		return connection.query(query, args || []);
	});
}));

/**
 * Returns a database connection (for internal use).
 * Your local {@link module:qctx~QContext}’s getConnection
 * method invokes this – if available, consider using it in order to map
 * all actions to the current context.
 *
 * @param {boolean} autorelease  Whether to release the connection after 1 query
 * @param {function} restart  Callback which will be invoked in case the query resulted in
 *                            a state in which the query/transaction needs to be restarted
 * @param {boolean} readonly  Indicates whether the connection can
 *                            be from the read-only pool
 *
 * @function module:dbbackend~Database#_getConnection
 */
Database.prototype._getConnection = buscomponent.needsInit(function(autorelease, restart, readonly) {
	var self = this;
	var pool = readonly ? self.rConnectionPool : self.wConnectionPool;
	assert.ok(pool);

	return Q.ninvoke(pool, 'getConnection').then(function(conn) {
		self.openConnections++;

		assert.ok(conn);
		var id = self.id++;

		var release = function() {
			self.openConnections--;

			if (self.openConnections == 0 && self.isShuttingDown)
				self.shutdown();

			return conn.release();
		};

		var query = function(q, args) {
			self.queryCount++;

			var rollback = function() {
				if (!readonly)
					conn.query('ROLLBACK; UNLOCK TABLES; SET autocommit = 1');
			};

			var deferred = Q.defer();
			var startTime = Date.now();
			conn.query(q, args, function(err, res) {
				debugSQL(id + '\t' + (q.length > 100 ? q.substr(0, 100) + '…' : q) + ' -> ' + (err ? err.code :
					(res && typeof res.length != 'undefined' ? res.length + ' results' :
					 res && typeof res.affectedRows != 'undefined' ? res.affectedRows + ' updates' : 'OK')) +
					 ' in ' + (Date.now() - startTime) + ' ms');

				if (err && (err.code == 'ER_LOCK_WAIT_TIMEOUT' || err.code == 'ER_LOCK_DEADLOCK')) {
					self.deadlockCount++;
					rollback();

					release();

					return Q().then(restart).then(function(data) {
						deferred.resolve(data);
						return deferred.promise;
					});
				}

				var exception = null;

				if (!err) {
					try {
						deferred.resolve(res);
					} catch (e) {
						exception = e;
					}
				}

				if (err || exception) {
					rollback();

					// make sure that the error event is emitted -> release() will be called in next tick
					Q().then(release).done();

					deferred.reject(err || exception);

					if (err) {
						// query-related error
						var datajson = JSON.stringify(args);
						var querydesc = '<<' + q + '>>' + (datajson.length <= 1024 ? ' with arguments [' + new Buffer(datajson).toString('base64') + ']' : '');

						self.emitError(q ? new Error(
							err + '\nCaused by ' + querydesc
						) : err);
					} else {
						// exception in callback
						self.emitError(exception);
					}
				}

				if (autorelease)
					release();
			});

			return deferred.promise;
		};

		return {
			query: query, release: release
		};
	});
});

/**
 * Returns a database connection (for public use).
 * Your local {@link module:qctx~QContext}’s getConnection
 * method invokes this – if available, consider using it in order to map
 * all actions to the current context.
 *
 * @param {boolean} readonly  Indicates whether the connection can
 *                            be from the read-only pool
 * @param {function} restart  Callback that will be invoked when the current transaction
 *                            needs to be restarted
 *
 * @function busreq~dbGetConection
 */
Database.prototype.getConnection = buscomponent.provide('dbGetConnection',
	['readonly', 'restart'], function(readonly, restart)
{
	var self = this;

	assert.ok(readonly === true || readonly === false);

	return self._getConnection(false, restart, readonly).then(function(cn) {
		return {
			query: function(q, data) {
				data = data || [];

				// emitting self has the sole purpose of it showing up in the bus log
				self.emitImmediate('dbBoundQueryLog', [q, data]);
				return cn.query(q, data);
			},
			release: function() {
				return cn.release();
			}
		};
	});
});

exports.Database = Database;

})();
<commit_msg><commit_after>(function () { "use strict";

var _ = require('lodash');
var util = require('util');
var assert = require('assert');
var Q = require('q');
var buscomponent = require('./stbuscomponent.js');
var deepupdate = require('./lib/deepupdate.js');
var debug = require('debug')('sotrade:db');
var debugSQL = require('debug')('sotrade:db:SQL');

/**
 * Provides access to a (MySQL) database for storing and fetching information
 *
 * @public
 * @module dbbackend
 */

/**
 * Main object of the {@link module:dbbackend} module
 *
 * @augments module:stbuscomponent~STBusComponent
 *
 * @property {object} dbmod  The node.js module for database connection
 * @property {object} wConnectionPool  A connection pool for connections
 *                                     requiring write access.
 * @property {object} rConnectionPool  A connection pool for connections
 *                                     not requiring write access.
 * @property {int} openConnections  The current count of in-use connections
 * @property {boolean} isShuttingDown  Flag that indicates server shutdown
 *
 * @public
 * @constructor module:dbbackend~Database
 */
function Database () {
	Database.super_.apply(this, arguments);

	this.dbmod = null;
	this.wConnectionPool = null;
	this.rConnectionPool = null;
	this.openConnections = 0;
	this.deadlockCount = 0;
	this.queryCount= 0;
	this.isShuttingDown = false;
	this.writableNodes = [];
	this.id = 0;
}

util.inherits(Database, buscomponent.BusComponent);

Database.prototype._init = function() {
	var self = this;

	debug('Initing database');

	return self.getServerConfig().then(function(cfg) {
		self.dbmod = cfg.dbmod || require('mysql');

		self.wConnectionPool = self.dbmod.createPoolCluster(cfg.db.clusterOptions);
		self.rConnectionPool = self.dbmod.createPoolCluster(cfg.db.clusterOptions);
		self.writableNodes = [];

		for (var i = 0; i < cfg.db.clusterOptions.order.length; ++i) {
			var id = cfg.db.clusterOptions.order[i];
			assert.ok(cfg.db.cluster[id]);
			var opt = deepupdate({}, cfg.db.cluster[id], cfg.db);

			if (opt.ssl === 'default')
				opt.ssl = cfg.ssl || {};

			debug('Create pool node', opt.writable, opt.readable, id);

			if (opt.writable) {
				self.writableNodes.push(id);
				self.wConnectionPool.add(id, opt);
			}

			if (opt.readable)
				self.rConnectionPool.add(id, opt);
		}

		self.wConnectionPool.on('remove', function(nodeId) {
			debug('Connection removed from writing pool!');

			self.writableNodes = _.without(self.writableNodes, nodeId);
			if (self.writableNodes.length == 0)
				self.emitImmediate('change-readability-mode', { readonly: true });
		});

		self.wConnectionPool.on('remove', function() { self.emitError(new Error('DB lost write connection')); });
		self.rConnectionPool.on('remove', function() { self.emitError(new Error('DB lost read connection')); });

		self.inited = true;
		self.openConnections = 0;

		/*
		 * Note: We don't set isShuttingDown = true here.
		 * This happens so we can actually resurrect the database connection
		 * during the shutdown process temporarily, so other components can complete
		 * any remaining work in progress.
		 */
	});
};

Database.prototype.shutdown = buscomponent.listener('localMasterShutdown', function() {
	this.isShuttingDown = true;

	debug('Database shutdown');

	if (this.openConnections == 0) {
		if (this.wConnectionPool) {
			this.wConnectionPool.end();
			this.wConnectionPool = null;
		}

		if (this.rConnectionPool) {
			this.rConnectionPool.end();
			this.rConnectionPool = null;
		}

		this.inited = false;
	}
});

/**
 * Provides some database usage statistics, like deadlock and query counts.
 *
 * @function busreq~dbUsageStatistics
 */
Database.prototype.usageStatistics = buscomponent.provide('dbUsageStatistics', [], function() {
	return {
		deadlockCount: this.deadlockCount,
		queryCount: this.queryCount,
		writableNodes: this.writableNodes.length
	};
});

/**
 * Executes an SQL query on the database.
 * Your local {@link module:qctx~QContext}’s query method
 * invokes this – if available, consider using it in order to map all
 * actions to the current context.
 *
 * @param {string} query  The SQL query
 * @param {Array} args  Parameters to escape and insert into the query
 * @param {boolean} readonly  Indicates whether this query can use the read-only pool
 *
 * @function busreq~dbQuery
 */
Database.prototype._query = buscomponent.provide('dbQuery', ['query', 'args', 'readonly'],
	buscomponent.needsInit(function(query, args, readonly)
{
	var self = this, origArgs = arguments;

	if (typeof readonly !== 'boolean')
		readonly = (query.trim().indexOf('SELECT') == 0);

	return self._getConnection(true, function /* restart */() {
		return self._query.apply(self, origArgs);
	}, readonly).then(function(connection) {
		return connection.query(query, args || []);
	});
}));

/**
 * Returns a database connection (for internal use).
 * Your local {@link module:qctx~QContext}’s getConnection
 * method invokes this – if available, consider using it in order to map
 * all actions to the current context.
 *
 * @param {boolean} autorelease  Whether to release the connection after 1 query
 * @param {function} restart  Callback which will be invoked in case the query resulted in
 *                            a state in which the query/transaction needs to be restarted
 * @param {boolean} readonly  Indicates whether the connection can
 *                            be from the read-only pool
 *
 * @function module:dbbackend~Database#_getConnection
 */
Database.prototype._getConnection = buscomponent.needsInit(function(autorelease, restart, readonly) {
	var self = this;
	var pool = readonly ? self.rConnectionPool : self.wConnectionPool;
	assert.ok(pool);

	return Q.ninvoke(pool, 'getConnection').then(function(conn) {
		self.openConnections++;

		assert.ok(conn);
		var id = self.id++;

		var release = function() {
			self.openConnections--;

			if (self.openConnections == 0 && self.isShuttingDown)
				self.shutdown();

			return conn.release();
		};

		var query = function(q, args) {
			self.queryCount++;

			var rollback = function() {
				if (!readonly)
					conn.query('ROLLBACK; UNLOCK TABLES; SET autocommit = 1');
			};

			var deferred = Q.defer();
			var startTime = Date.now();
			conn.query(q, args, function(err, res) {
				debugSQL(id + '\t' + (q.length > 100 ? q.substr(0, 100) + '…' : q) + ' -> ' + (err ? err.code :
					(res && typeof res.length != 'undefined' ? res.length + ' results' :
					 res && typeof res.affectedRows != 'undefined' ? res.affectedRows + ' updates' : 'OK')) +
					 ' in ' + (Date.now() - startTime) + ' ms');

				if (err && (err.code == 'ER_LOCK_WAIT_TIMEOUT' || err.code == 'ER_LOCK_DEADLOCK')) {
					self.deadlockCount++;
					rollback();

					release();

					deferred.resolve(Q().then(restart));
				}

				var exception = null;

				if (!err) {
					try {
						deferred.resolve(res);
					} catch (e) {
						exception = e;
					}
				}

				if (err || exception) {
					rollback();

					// make sure that the error event is emitted -> release() will be called in next tick
					Q().then(release).done();

					deferred.reject(err || exception);

					if (err) {
						// query-related error
						var datajson = JSON.stringify(args);
						var querydesc = '<<' + q + '>>' + (datajson.length <= 1024 ? ' with arguments [' + new Buffer(datajson).toString('base64') + ']' : '');

						self.emitError(q ? new Error(
							err + '\nCaused by ' + querydesc
						) : err);
					} else {
						// exception in callback
						self.emitError(exception);
					}
				}

				if (autorelease)
					release();
			});

			return deferred.promise;
		};

		return {
			query: query, release: release
		};
	});
});

/**
 * Returns a database connection (for public use).
 * Your local {@link module:qctx~QContext}’s getConnection
 * method invokes this – if available, consider using it in order to map
 * all actions to the current context.
 *
 * @param {boolean} readonly  Indicates whether the connection can
 *                            be from the read-only pool
 * @param {function} restart  Callback that will be invoked when the current transaction
 *                            needs to be restarted
 *
 * @function busreq~dbGetConection
 */
Database.prototype.getConnection = buscomponent.provide('dbGetConnection',
	['readonly', 'restart'], function(readonly, restart)
{
	var self = this;

	assert.ok(readonly === true || readonly === false);

	return self._getConnection(false, restart, readonly).then(function(cn) {
		return {
			query: function(q, data) {
				data = data || [];

				// emitting self has the sole purpose of it showing up in the bus log
				self.emitImmediate('dbBoundQueryLog', [q, data]);
				return cn.query(q, data);
			},
			release: function() {
				return cn.release();
			}
		};
	});
});

exports.Database = Database;

})();
<|endoftext|>


<commit_before>var hospitals = null;
var hospitals_loaded = false;

var parks = null;
var parks_loaded = false;

var restaurants = null;
var restaurants_loaded = false;

// convert TWD97 coordinates to LatLng used by Google Map
// http://kuro.tw/posts/2015/06/11/js-note-twd97-convert-to-longitude-and-latitude
function twd97_to_latlng($x, $y) {
  var pow = Math.pow, M_PI = Math.PI;
  var sin = Math.sin, cos = Math.cos, tan = Math.tan;
  var $a = 6378137.0, $b = 6356752.314245;
  var $lng0 = 121 * M_PI / 180, $k0 = 0.9999, $dx = 250000, $dy = 0;
  var $e = pow((1 - pow($b, 2) / pow($a, 2)), 0.5);

  $x -= $dx;
  $y -= $dy;

  var $M = $y / $k0;

  var $mu = $M / ($a * (1.0 - pow($e, 2) / 4.0 - 3 * pow($e, 4) / 64.0 - 5 * pow($e, 6) / 256.0));
  var $e1 = (1.0 - pow((1.0 - pow($e, 2)), 0.5)) / (1.0 + pow((1.0 - pow($e, 2)), 0.5));

  var $J1 = (3 * $e1 / 2 - 27 * pow($e1, 3) / 32.0);
  var $J2 = (21 * pow($e1, 2) / 16 - 55 * pow($e1, 4) / 32.0);
  var $J3 = (151 * pow($e1, 3) / 96.0);
  var $J4 = (1097 * pow($e1, 4) / 512.0);

  var $fp = $mu + $J1 * sin(2 * $mu) + $J2 * sin(4 * $mu) + $J3 * sin(6 * $mu) + $J4 * sin(8 * $mu);

  var $e2 = pow(($e * $a / $b), 2);
  var $C1 = pow($e2 * cos($fp), 2);
  var $T1 = pow(tan($fp), 2);
  var $R1 = $a * (1 - pow($e, 2)) / pow((1 - pow($e, 2) * pow(sin($fp), 2)), (3.0 / 2.0));
  var $N1 = $a / pow((1 - pow($e, 2) * pow(sin($fp), 2)), 0.5);

  var $D = $x / ($N1 * $k0);

  var $Q1 = $N1 * tan($fp) / $R1;
  var $Q2 = (pow($D, 2) / 2.0);
  var $Q3 = (5 + 3 * $T1 + 10 * $C1 - 4 * pow($C1, 2) - 9 * $e2) * pow($D, 4) / 24.0;
  var $Q4 = (61 + 90 * $T1 + 298 * $C1 + 45 * pow($T1, 2) - 3 * pow($C1, 2) - 252 * $e2) * pow($D, 6) / 720.0;
  var $lat = $fp - $Q1 * ($Q2 - $Q3 + $Q4);

  var $Q5 = $D;
  var $Q6 = (1 + 2 * $T1 + $C1) * pow($D, 3) / 6;
  var $Q7 = (5 - 2 * $C1 + 28 * $T1 - 3 * pow($C1, 2) + 8 * $e2 + 24 * pow($T1, 2)) * pow($D, 5) / 120.0;
  var $lng = $lng0 + ($Q5 - $Q6 + $Q7) / cos($fp);

  $lat = ($lat * 180) / M_PI;
  $lng = ($lng * 180) / M_PI;

  return {
    lat: $lat,
    lng: $lng
  };
}

function getJSON(url, callback) {
	$.ajax({
		dataType: "json",
		url: url,
		mimeType: "application/json",
		success: callback
	});
}

// load data of hospitals
function loadHospitals(callback) {
	getJSON("data/hospitals.json", function(data) {
		// the "pos" in the hospitals are in TWD97 format
		for(var i = 0; i < data.length; ++i) {
			var h = data[i];
			if(h.pos) {
				h.pos = twd97_to_latlng(h.pos[0], h.pos[1]);
				// console.log(h.pos);
			}
		}
		hospitals = data;
		callback();
	});
}

// load data of parks in the city
function loadParks(callback) {
	getJSON("data/parks.json", function(data) {
		parks = data;
		callback();
	});
}

// load data of restaurants in the city
function loadRestaurants(callback) {
	getJSON("data/restaurants.json", function(data) {
		restaurants = data;
		callback();
	});
}

var current_marks = null;

function clearMarks() {
	var map = window.map;
	if(current_marks) {
		for(var i = 0; i < current_marks.length; ++i) {
			var mark = current_marks[i];
			mark.setMap(null);
		}
		current_marks = null;
	}
}

function markHospitals() {
	if(hospitals) {
		current_marks = []
		for(var i = 0; i < hospitals.length; ++i) {
			var item = hospitals[i];
			var marker = new google.maps.Marker({
				position: item.pos,
				map: window.map
			});
			current_marks.push(marker);
		}
	}
	else {
		loadHospitals(markHospitals);
	}
}

function markParks() {
	if(parks) {
		for(var i = 0; i < parks.length; ++i) {
			var item = parks[i];

		}
	}
	else {
		loadParks(markParks);
	}
}

function markRestaurants() {
	if(restaurants) {
		for(var i = 0; i < restaurants.length; ++i) {
			var item = restaurants[i];

		}
	}
	else {
		loadRestaurants(markRestaurants);
	}
}

// center the map on current location of the user
function centerOnCurrentLocation(map) {
	// http://stackoverflow.com/questions/17382128/google-maps-api-center-map-on-clients-current-location
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function (position) {
			initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			map.setCenter(initialLocation);
		});
	}
	else {
		alert("Your browser is not supported.");
	}
}

// initilaize Google Map
function initMap() {
	var map = new google.maps.Map(document.getElementById('map'), {
		zoom: 16,
		center: {lat: 25.03, lng: 121.30}
	});
	centerOnCurrentLocation(map);
	window.map = map;
}

// query GeoCode of the specified address and call callback() after it's finished.
function getGeoCode(map, addr, callback) {
	var gc = new google.maps.Geocoder();
	gc.geocode({address: addr}, function(results, status) {
		if(status == google.maps.GeocoderStatus.OK) {
			var pt = results[0].geometry.location;
			callback({lat: pt.lat(), lng: pt.lng()});
		}
	});
}

// move current view to the specified address
function moveToAddress(map, address) {
	getGeoCode(map, address, function(pos) {
		map.setCenter(pos);
	});
}

// add a mark for the address on the map
function markAddress(map, address) {
	getGeoCode(map, address, function(pos) {
	  var marker = new google.maps.Marker({
		position: pos,
		map: map /*,
		icon: image */
	  });
  });
}

function markSites(map, sites) {
	var n = sites.length;
	for(var i = 0; i < n; ++i) {
		var site = sites[i];
		markAddress(map, site.address);
	}
}

var tracked_path = null;
var tracking_id = -1;

function locationChanged(pos) {
	var crd = pos.coords;
	// FIXME: store current time
	tracked_path.push({lat: crd.latitude, lng: crd.longitude});
}

function trackingError(err) {
	console.warn('ERROR(' + err.code + '): ' + err.message);
}

function startTrackingPath() {
	if(tracking_id == -1) {
		if( navigator.geolocation) {
			var options = {
			  enableHighAccuracy: true,
			  timeout: 5000,
			  maximumAge: 0
			};
			tracking_id = navigator.geolocation.watchPosition(locationChanged, trackingError, options);
			tracked_path = new Array();
		}
		else {
			alert("your browser is not supported.");
		}
	}
}

function stopTrackingPath() {
	if( navigator.geolocation) {
		if(tracking_id != -1) {
			navigator.geolocation.clearWatch(tracking_id);
			tracking_id = -1;
		}
		// var crd = tracked_path[tracked_path.length - 1];
		// tracked_path.push({lat: crd.lat + 1.0, lng: crd.lng + 1.0});
	}
	return tracked_path;
}

function createPath(_path) {
	drawPath = new google.maps.Polyline({
		path: _path,
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 8
	});
	return drawPath;
}
<commit_msg>Mark parks on the map.<commit_after>var hospitals = null;
var hospitals_loaded = false;

var parks = null;
var parks_loaded = false;

var restaurants = null;
var restaurants_loaded = false;

// convert TWD97 coordinates to LatLng used by Google Map
// http://kuro.tw/posts/2015/06/11/js-note-twd97-convert-to-longitude-and-latitude
function twd97_to_latlng($x, $y) {
  var pow = Math.pow, M_PI = Math.PI;
  var sin = Math.sin, cos = Math.cos, tan = Math.tan;
  var $a = 6378137.0, $b = 6356752.314245;
  var $lng0 = 121 * M_PI / 180, $k0 = 0.9999, $dx = 250000, $dy = 0;
  var $e = pow((1 - pow($b, 2) / pow($a, 2)), 0.5);

  $x -= $dx;
  $y -= $dy;

  var $M = $y / $k0;

  var $mu = $M / ($a * (1.0 - pow($e, 2) / 4.0 - 3 * pow($e, 4) / 64.0 - 5 * pow($e, 6) / 256.0));
  var $e1 = (1.0 - pow((1.0 - pow($e, 2)), 0.5)) / (1.0 + pow((1.0 - pow($e, 2)), 0.5));

  var $J1 = (3 * $e1 / 2 - 27 * pow($e1, 3) / 32.0);
  var $J2 = (21 * pow($e1, 2) / 16 - 55 * pow($e1, 4) / 32.0);
  var $J3 = (151 * pow($e1, 3) / 96.0);
  var $J4 = (1097 * pow($e1, 4) / 512.0);

  var $fp = $mu + $J1 * sin(2 * $mu) + $J2 * sin(4 * $mu) + $J3 * sin(6 * $mu) + $J4 * sin(8 * $mu);

  var $e2 = pow(($e * $a / $b), 2);
  var $C1 = pow($e2 * cos($fp), 2);
  var $T1 = pow(tan($fp), 2);
  var $R1 = $a * (1 - pow($e, 2)) / pow((1 - pow($e, 2) * pow(sin($fp), 2)), (3.0 / 2.0));
  var $N1 = $a / pow((1 - pow($e, 2) * pow(sin($fp), 2)), 0.5);

  var $D = $x / ($N1 * $k0);

  var $Q1 = $N1 * tan($fp) / $R1;
  var $Q2 = (pow($D, 2) / 2.0);
  var $Q3 = (5 + 3 * $T1 + 10 * $C1 - 4 * pow($C1, 2) - 9 * $e2) * pow($D, 4) / 24.0;
  var $Q4 = (61 + 90 * $T1 + 298 * $C1 + 45 * pow($T1, 2) - 3 * pow($C1, 2) - 252 * $e2) * pow($D, 6) / 720.0;
  var $lat = $fp - $Q1 * ($Q2 - $Q3 + $Q4);

  var $Q5 = $D;
  var $Q6 = (1 + 2 * $T1 + $C1) * pow($D, 3) / 6;
  var $Q7 = (5 - 2 * $C1 + 28 * $T1 - 3 * pow($C1, 2) + 8 * $e2 + 24 * pow($T1, 2)) * pow($D, 5) / 120.0;
  var $lng = $lng0 + ($Q5 - $Q6 + $Q7) / cos($fp);

  $lat = ($lat * 180) / M_PI;
  $lng = ($lng * 180) / M_PI;

  return {
    lat: $lat,
    lng: $lng
  };
}

function getJSON(url, callback) {
	$.ajax({
		dataType: "json",
		url: url,
		mimeType: "application/json",
		success: callback
	});
}

// load data of hospitals
function loadHospitals(callback) {
	getJSON("data/hospitals.json", function(data) {
		// the "pos" in the hospitals are in TWD97 format
		for(var i = 0; i < data.length; ++i) {
			var h = data[i];
			if(h.pos) {
				h.pos = twd97_to_latlng(h.pos[0], h.pos[1]);
				// console.log(h.pos);
			}
		}
		hospitals = data;
		callback();
	});
}

// load data of parks in the city
function loadParks(callback) {
	getJSON("data/parks.json", function(data) {
		for(var i = 0; i < data.length; ++i) {
			var item = data[i];
			item.pos = {lat: parseFloat(item.GTag_latitude), lng: parseFloat(item.GTag_longitude)};
		}
		parks = data;
		callback();
	});
}

// load data of restaurants in the city
function loadRestaurants(callback) {
	getJSON("data/restaurants.json", function(data) {
		restaurants = data;
		callback();
	});
}

var current_marks = null;

function clearMarks() {
	var map = window.map;
	if(current_marks) {
		for(var i = 0; i < current_marks.length; ++i) {
			var mark = current_marks[i];
			mark.setMap(null);
		}
		current_marks = null;
	}
}

function markHospitals() {
	if(hospitals) {
		current_marks = []
		for(var i = 0; i < hospitals.length; ++i) {
			var item = hospitals[i];
			var marker = new google.maps.Marker({
				position: item.pos,
				map: window.map
			});
			current_marks.push(marker);
		}
	}
	else {
		loadHospitals(markHospitals);
	}
}

function markParks() {
	if(parks) {
		current_marks = []
		for(var i = 0; i < parks.length; ++i) {
			var item = parks[i];
			var marker = new google.maps.Marker({
				position: item.pos,
				map: window.map
			});
			current_marks.push(marker);
		}
	}
	else {
		loadParks(markParks);
	}
}

function markRestaurants() {
	if(restaurants) {
		for(var i = 0; i < restaurants.length; ++i) {
			var item = restaurants[i];

		}
	}
	else {
		loadRestaurants(markRestaurants);
	}
}

// center the map on current location of the user
function centerOnCurrentLocation(map) {
	// http://stackoverflow.com/questions/17382128/google-maps-api-center-map-on-clients-current-location
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function (position) {
			initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			map.setCenter(initialLocation);
		});
	}
	else {
		alert("Your browser is not supported.");
	}
}

// initilaize Google Map
function initMap() {
	var map = new google.maps.Map(document.getElementById('map'), {
		zoom: 16,
		center: {lat: 25.03, lng: 121.30}
	});
	centerOnCurrentLocation(map);
	window.map = map;
}

// query GeoCode of the specified address and call callback() after it's finished.
function getGeoCode(map, addr, callback) {
	var gc = new google.maps.Geocoder();
	gc.geocode({address: addr}, function(results, status) {
		if(status == google.maps.GeocoderStatus.OK) {
			var pt = results[0].geometry.location;
			callback({lat: pt.lat(), lng: pt.lng()});
		}
	});
}

// move current view to the specified address
function moveToAddress(map, address) {
	getGeoCode(map, address, function(pos) {
		map.setCenter(pos);
	});
}

// add a mark for the address on the map
function markAddress(map, address) {
	getGeoCode(map, address, function(pos) {
	  var marker = new google.maps.Marker({
		position: pos,
		map: map /*,
		icon: image */
	  });
  });
}

function markSites(map, sites) {
	var n = sites.length;
	for(var i = 0; i < n; ++i) {
		var site = sites[i];
		markAddress(map, site.address);
	}
}

var tracked_path = null;
var tracking_id = -1;

function locationChanged(pos) {
	var crd = pos.coords;
	// FIXME: store current time
	tracked_path.push({lat: crd.latitude, lng: crd.longitude});
}

function trackingError(err) {
	console.warn('ERROR(' + err.code + '): ' + err.message);
}

function startTrackingPath() {
	if(tracking_id == -1) {
		if( navigator.geolocation) {
			var options = {
			  enableHighAccuracy: true,
			  timeout: 5000,
			  maximumAge: 0
			};
			tracking_id = navigator.geolocation.watchPosition(locationChanged, trackingError, options);
			tracked_path = new Array();
		}
		else {
			alert("your browser is not supported.");
		}
	}
}

function stopTrackingPath() {
	if( navigator.geolocation) {
		if(tracking_id != -1) {
			navigator.geolocation.clearWatch(tracking_id);
			tracking_id = -1;
		}
		// var crd = tracked_path[tracked_path.length - 1];
		// tracked_path.push({lat: crd.lat + 1.0, lng: crd.lng + 1.0});
	}
	return tracked_path;
}

function createPath(_path) {
	drawPath = new google.maps.Polyline({
		path: _path,
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 8
	});
	return drawPath;
}
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var Q = require('q');
var moment = require('moment');

require('./db');
var Post = require('mongoose').model('Post');

var reddit = {
    url: 'http://www.reddit.com',
    limit: 100,
    uaString: 'thedigest/0.1 by connyay'
};
var echojs = {
    url: 'http://www.echojs.com',
    limit: 32
};
var hackernews = {
    url: 'http://hnify.herokuapp.com',
    limit: 90
};

var posts = [];

function fetchRedditFeed(subreddit) {
    var deferred = Q.defer();
    var opts = {
        headers: {
            'User-Agent': reddit.uaString
        }
    };
    request(reddit.url + '/r/' + subreddit + '/hot.json?limit=1', opts, function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            data.data.children.forEach(function(post) {
                if (post.data.stickied) {
                    return;
                }
                var data = post.data;
                posts.push({
                    'title': data.title,
                    'source': '/r/' + subreddit,
                    'time': moment(data.created_utc * 1000).fromNow(),
                    'link': data.url,
                    'comment_count': data.num_comments,
                    'comment_link': reddit.url + data.permalink
                });
            });
            deferred.resolve();
        }
    });
    return deferred.promise;
}

function fetchEchoJsFeed(page) {
    var deferred = Q.defer();

    request(echojs.url + '/api/getnews/top/1/1', function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            data.news.forEach(function(post) {
                posts.push({
                    'title': post.title,
                    'source': 'Echo JS',
                    'time': moment(post.ctime * 1000).fromNow(),
                    'link': post.url,
                    'comment_count': post.comments,
                    'comment_link': echojs.url + '/news/' + post.id
                });
            });
            deferred.resolve();
        }
    });
    return deferred.promise;
}

function fetchHackerNewsFeed() {
    var deferred = Q.defer();
    request(hackernews.url + '/get/top?limit=2', function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            data.stories.forEach(function(post) {
                posts.push({
                    'title': post.title,
                    'source': 'HackerNews',
                    'time': post.published_time,
                    'link': post.link,
                    'comment_count': post.num_comments,
                    'comment_link': post.comments_link
                });
            });
            deferred.resolve();
        }
    });
    return deferred.promise;
}

function sortAndStorePosts() {
    var sortedPosts = [],
        category,
        separatedPosts = {
            secondsAgo: [],
            minutesAgo: [],
            hoursAgo: [],
            daysAgo: [],
            weeksAgo: [],
            monthsAgo: [],
            yearsAgo: []
        };

    var categories = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'];
    var length = posts.length;
    for (var i = 0; i < length; i++) {
        var post = posts[i];
        var time = post.time;

        for (var ci = 0; ci < categories.length; ci++) {
            category = categories[ci];
            if (time.indexOf(category) !== -1) {
                separatedPosts[category + 'sAgo'].push(post);
            }
        }
    }
    var sort = function(a, b) {
        var aTime = a.time.match(/\d+/);
        var bTime = b.time.match(/\d+/);
        return parseInt(aTime === null ? 0 : aTime[0]) - parseInt(bTime === null ? 0 : bTime[0]);
    };
    for (category in separatedPosts) {
        separatedPosts[category].sort(sort);
    }

    posts = sortedPosts.concat(separatedPosts.secondsAgo, separatedPosts.minutesAgo, separatedPosts.hoursAgo,
        separatedPosts.daysAgo, separatedPosts.weeksAgo, separatedPosts.monthsAgo,
        separatedPosts.yearsAgo);
}

var deferredList = [];
// Grab Reddit Feeds
['programming', 'technology', 'science', 'webdev', 'blackhat'].forEach(function(subreddit) {
    deferredList.push(fetchRedditFeed(subreddit));
});

// Grab EchoJS feed
// Page 1
deferredList.push(fetchEchoJsFeed(1));
// Page 2
deferredList.push(fetchEchoJsFeed(2));

// Grab HackerNews feed
deferredList.push(fetchHackerNewsFeed());

Q.all(deferredList).then(function() {
    sortAndStorePosts();
    // Wipe out DB
    Post.remove({}, function(err) {
        console.log('collection removed')
    });
    Post.collection.insert(posts, function(err, docs) {

        debugger;
    });
});
<commit_msg>bump limits<commit_after>'use strict';

var request = require('request');
var Q = require('q');
var moment = require('moment');

require('./db');
var Post = require('mongoose').model('Post');

var reddit = {
    url: 'http://www.reddit.com',
    limit: 100,
    uaString: 'thedigest/0.1 by connyay'
};
var echojs = {
    url: 'http://www.echojs.com',
    limit: 32
};
var hackernews = {
    url: 'http://hnify.herokuapp.com',
    limit: 90
};

var posts = [];

function fetchRedditFeed(subreddit) {
    var deferred = Q.defer();
    var opts = {
        headers: {
            'User-Agent': reddit.uaString
        }
    };
    request(reddit.url + '/r/' + subreddit + '/hot.json?limit=' + reddit.limit, opts, function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            data.data.children.forEach(function(post) {
                if (post.data.stickied) {
                    return;
                }
                var data = post.data;
                posts.push({
                    'title': data.title,
                    'source': '/r/' + subreddit,
                    'time': moment(data.created_utc * 1000).fromNow(),
                    'link': data.url,
                    'comment_count': data.num_comments,
                    'comment_link': reddit.url + data.permalink
                });
            });
            deferred.resolve();
        }
    });
    return deferred.promise;
}

function fetchEchoJsFeed(page) {
    var deferred = Q.defer();
    var start = (page === 1) ? 1 : 33;
    request(echojs.url + '/api/getnews/top/' + start + '/' + echojs.limit, function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            data.news.forEach(function(post) {
                posts.push({
                    'title': post.title,
                    'source': 'Echo JS',
                    'time': moment(post.ctime * 1000).fromNow(),
                    'link': post.url,
                    'comment_count': post.comments,
                    'comment_link': echojs.url + '/news/' + post.id
                });
            });
            deferred.resolve();
        }
    });
    return deferred.promise;
}

function fetchHackerNewsFeed() {
    var deferred = Q.defer();
    request(hackernews.url + '/get/top?limit=' + hackernews.limit, function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var data = JSON.parse(body);
            data.stories.forEach(function(post) {
                posts.push({
                    'title': post.title,
                    'source': 'HackerNews',
                    'time': post.published_time,
                    'link': post.link,
                    'comment_count': post.num_comments,
                    'comment_link': post.comments_link
                });
            });
            deferred.resolve();
        }
    });
    return deferred.promise;
}

function sortAndStorePosts() {
    var sortedPosts = [],
        category,
        separatedPosts = {
            secondsAgo: [],
            minutesAgo: [],
            hoursAgo: [],
            daysAgo: [],
            weeksAgo: [],
            monthsAgo: [],
            yearsAgo: []
        };

    var categories = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'];
    var length = posts.length;
    for (var i = 0; i < length; i++) {
        var post = posts[i];
        var time = post.time;

        for (var ci = 0; ci < categories.length; ci++) {
            category = categories[ci];
            if (time.indexOf(category) !== -1) {
                separatedPosts[category + 'sAgo'].push(post);
            }
        }
    }
    var sort = function(a, b) {
        var aTime = a.time.match(/\d+/);
        var bTime = b.time.match(/\d+/);
        return parseInt(aTime === null ? 0 : aTime[0]) - parseInt(bTime === null ? 0 : bTime[0]);
    };
    for (category in separatedPosts) {
        separatedPosts[category].sort(sort);
    }

    posts = sortedPosts.concat(separatedPosts.secondsAgo, separatedPosts.minutesAgo, separatedPosts.hoursAgo,
        separatedPosts.daysAgo, separatedPosts.weeksAgo, separatedPosts.monthsAgo,
        separatedPosts.yearsAgo);
}

var deferredList = [];
// Grab Reddit Feeds
['programming', 'technology', 'science', 'webdev', 'blackhat'].forEach(function(subreddit) {
    deferredList.push(fetchRedditFeed(subreddit));
});

// Grab EchoJS feed
// Page 1
deferredList.push(fetchEchoJsFeed(1));
// Page 2
deferredList.push(fetchEchoJsFeed(2));

// Grab HackerNews feed
deferredList.push(fetchHackerNewsFeed());

Q.all(deferredList).then(function() {
    sortAndStorePosts();
    // Wipe out DB
    Post.collection.remove({}, function(err) {
        if (!err) {
            console.log('Collection dropped.');
        } else {
            console.log('Error dropping collection?');
        }
    });
    Post.collection.insert(posts, function(err, docs) {
        if (!err) {
            console.log('Collection saved! Stored ' + docs.length + ' posts in the DB.');
        } else {
            console.log('Error saving docs?');
        }
    });
});
<|endoftext|>


<commit_before>var hbs = require('handlebars')
var fs = require('fs')
var Github = require('github-api')
var request = require('request')
var btoa =  require('btoa')

module.exports = function(callback) {

  var github = new Github({
    auth: "oauth",
    token: process.env['REPOROBOT_TOKEN']
  })

  var repo = github.getRepo('jlord', 'patchwork')

  if (process.env['CONTRIBUTORS']) {
    fs.readFile( process.env['CONTRIBUTORS'], function (err, data) {
      if (err) return callback(err, "Error reading contribs file for building page.")
      organizeData(data)
    })
  } else {
    console.log("Making request for data...")
    var uri = "http://reporobot.jlord.us/data"
    request({url: uri, json: true}, function (err, res, body) {
      if (err) return callback(err, "Fetching latest data for building page")
      organizeData(JSON.stringify(body))
    })
  }

  function organizeData(data) {
    var everyone = JSON.parse(data)
    var newest = everyone[everyone.length - 1]
    var stats = {featured: newest, everyone: everyone.reverse(), total: everyone.length}
    return getTemplate(stats, everyone)
  }

  function getTemplate(stats, everyone) {
    fs.readFile('template.hbs', function (err, file) {
      if (err) return callback(err, "Error reading template file.")

      file = file.toString()
      var template = hbs.compile(file)
      var HTML = template(stats)
      return writeRepo(HTML, stats, everyone)
    })
  }

  function writeRepo(HTML, stats, everyone) {
    var username = stats.featured.user
    var commitMes = "rebuilt with @" + username + " added\!"
    var baseURL = 'https://api.github.com/repos/'

    var reqHeaders = {
      'User-Agent': 'request',
      'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
    }

    var options = {
      headers: reqHeaders,
      url: baseURL + "jlord/patchwork/contents/index.html",
      json: true,
      body: {
        "branch": "gh-pages",
        "committer": {
          "name": "reporobot",
          "email": "60ebe73fdad8ee59d45c@cloudmailin.net"
        },
        "sha": "",
        "content": btoa(HTML),
        "message": "Rebuilt index with " + username
      }
    }

    request.get(options, function(err, res, body) {
      if (err) return callback(err, "Error fetching SHA")
      options.body.sha = body.sha
      request.put(options, function(err, res, body) {
        if (err) return callback(err, "Error writing new index to Patchwork")
        callback(null, "Rebuilt index with " + username, body)
      })
    })
  }
}
<commit_msg>Just show top 100<commit_after>var hbs = require('handlebars')
var fs = require('fs')
var Github = require('github-api')
var request = require('request')
var btoa =  require('btoa')

module.exports = function(callback) {

  var github = new Github({
    auth: "oauth",
    token: process.env['REPOROBOT_TOKEN']
  })

  var repo = github.getRepo('jlord', 'patchwork')

  if (process.env['CONTRIBUTORS']) {
    fs.readFile( process.env['CONTRIBUTORS'], function (err, data) {
      if (err) return callback(err, "Error reading contribs file for building page.")
      organizeData(data)
    })
  } else {
    console.log("Making request for data...")
    var uri = "http://reporobot.jlord.us/data"
    request({url: uri, json: true}, function (err, res, body) {
      if (err) return callback(err, "Fetching latest data for building page")
      organizeData(JSON.stringify(body))
    })
  }

  function organizeData(data) {
    var everyone = JSON.parse(data)
    var newest = everyone[everyone.length - 1]
    var topHundred = everyone.reverse().slice(0, 100)
    var stats = {featured: newest, everyone: topHundred, total: everyone.length}
    return getTemplate(stats, everyone)
  }

  function getTemplate(stats, everyone) {
    fs.readFile('template.hbs', function (err, file) {
      if (err) return callback(err, "Error reading template file.")

      file = file.toString()
      var template = hbs.compile(file)
      var HTML = template(stats)
      return writeRepo(HTML, stats, everyone)
    })
  }

  function writeRepo(HTML, stats, everyone) {
    var username = stats.featured.user
    var commitMes = "rebuilt with @" + username + " added\!"
    var baseURL = 'https://api.github.com/repos/'

    var reqHeaders = {
      'User-Agent': 'request',
      'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
    }

    var options = {
      headers: reqHeaders,
      url: baseURL + "jlord/patchwork/contents/index.html",
      json: true,
      body: {
        "branch": "gh-pages",
        "committer": {
          "name": "reporobot",
          "email": "60ebe73fdad8ee59d45c@cloudmailin.net"
        },
        "sha": "",
        "content": btoa(HTML),
        "message": "Rebuilt index with " + username
      }
    }

    request.get(options, function(err, res, body) {
      if (err) return callback(err, "Error fetching SHA")
      options.body.sha = body.sha
      request.put(options, function(err, res, body) {
        if (err) return callback(err, "Error writing new index to Patchwork")
        callback(null, "Rebuilt index with " + username, body)
      })
    })
  }
}
<|endoftext|>


<commit_before>const cosmiconfig = require('cosmiconfig');
import { readSync, readFileSync } from 'fs';
import path from 'path';
import { sync as globSync, hasMagic as globHasMagic } from 'glob';

import { SourceMap } from './source_map.js';
import JSONFormatter from './formatters/json_formatter.js';
import TextFormatter from './formatters/text_formatter.js';

export class Configuration {
  /*
    options:
      - configDirectory: path to begin searching for config files
      - format: (required) `text` | `json`
      - rules: [string array] whitelist rules
      - schemaPaths: [string array] file(s) to read schema from
      - customRulePaths: [string array] path to additional custom rules to be loaded
      - stdin: [boolean] pass schema via stdin?
  */
  constructor(options = {}, stdinFd = null) {
    const defaultOptions = { format: 'text', customRulePaths: [] };
    const configOptions = loadOptionsFromConfig(options.configDirectory);

    // TODO Get configs from .graphqlconfig file

    this.options = Object.assign({}, defaultOptions, configOptions, options);
    this.stdinFd = stdinFd;
    this.schema = null;
    this.sourceMap = null;
    this.rules = null;
    this.rulePaths = this.options.customRulePaths.concat(
      path.join(__dirname, 'rules/*.js')
    );
  }

  getSchema() {
    if (this.schema) {
      return this.schema;
    }

    if (this.options.stdin) {
      this.schema = getSchemaFromFileDescriptor(this.stdinFd);
      this.sourceMap = new SourceMap({ stdin: this.schema });
    } else if (this.options.schemaPaths) {
      const expandedPaths = expandPaths(this.options.schemaPaths);
      const segments = getSchemaSegmentsFromFiles(expandedPaths);
      if (Object.keys(segments).length === 0) {
        return null;
      }
      this.sourceMap = new SourceMap(segments);
      this.schema = this.sourceMap.getCombinedSource();
    }

    return this.schema;
  }

  getSchemaSourceMap() {
    if (!this.sourceMap) {
      this.getSchema();
    }

    return this.sourceMap;
  }

  getFormatter() {
    switch (this.options.format) {
      case 'json':
        return JSONFormatter;
      case 'text':
        return TextFormatter;
    }
  }

  getRules() {
    let rules = this.getAllRules();
    let specifiedRules;
    if (this.options.rules && this.options.rules.length > 0) {
      specifiedRules = this.options.rules.map(toUpperCamelCase);
      rules = this.getAllRules().filter(rule => {
        return specifiedRules.indexOf(rule.name) >= 0;
      });
    }

    // DEPRECATED - This code should be removed in v1.0.0.
    if (this.options.only && this.options.only.length > 0) {
      specifiedRules = this.options.only.map(toUpperCamelCase);
      rules = this.getAllRules().filter(rule => {
        return specifiedRules.indexOf(rule.name) >= 0;
      });
    }

    // DEPRECATED - This code should be removed in v1.0.0.
    if (this.options.except && this.options.except.length > 0) {
      specifiedRules = this.options.except.map(toUpperCamelCase);
      rules = this.getAllRules().filter(rule => {
        return specifiedRules.indexOf(rule.name) == -1;
      });
    }

    return rules;
  }

  getAllRules() {
    if (this.rules !== null) {
      return this.rules;
    }

    let expandedPaths = expandPaths(this.rulePaths);
    this.rules = [];
    expandedPaths.map(rulePath => {
      let ruleMap = require(rulePath);
      let rule = Object.keys(ruleMap).map(k => ruleMap[k]);

      if (rule) {
        this.rules = this.rules.concat(rule);
      }
    });

    return this.rules;
  }

  validate() {
    const issues = [];

    const ruleNames = this.getAllRules().map(rule => rule.name);
    let misConfiguredRuleNames = []
      .concat(
        this.options.only || [],
        this.options.except || [],
        this.options.rules || []
      )
      .map(toUpperCamelCase)
      .filter(name => ruleNames.indexOf(name) == -1);

    if (this.getFormatter() == null) {
      issues.push({
        message: `The output format '${this.options.format}' is invalid`,
        field: 'format',
        type: 'error',
      });
    }

    if (misConfiguredRuleNames.length > 0) {
      issues.push({
        message: `The following rule(s) are invalid: ${misConfiguredRuleNames.join(
          ', '
        )}`,
        field: 'rules',
        type: 'warning',
      });
    }

    return issues;
  }
}

function loadOptionsFromConfig(configDirectory) {
  const searchPath = configDirectory || './';

  const cosmic = cosmiconfig('graphql-schema-linter', {
    cache: false,
    sync: true,
  }).load(searchPath);

  if (cosmic) {
    return {
      rules: cosmic.config.rules,
      customRulePaths: cosmic.config.customRulePaths || [],
    };
  } else {
    return {};
  }
}

function getSchemaFromFileDescriptor(fd) {
  let b = new Buffer(1024);
  let data = '';

  while (true) {
    let n = readSync(fd, b, 0, b.length);
    if (!n) {
      break;
    }
    data += b.toString('utf8', 0, n);
  }

  return data;
}

function getSchemaFromFile(path) {
  try {
    return readFileSync(path).toString('utf8');
  } catch (e) {
    console.error(e.message);
  }
  return null;
}

function getSchemaSegmentsFromFiles(paths) {
  return paths.reduce((segments, path) => {
    let schema = getSchemaFromFile(path);
    if (schema) {
      segments[path] = schema;
    }
    return segments;
  }, {});
}

function expandPaths(pathOrPattern) {
  return (
    pathOrPattern
      .map(path => {
        if (globHasMagic(path)) {
          return globSync(path);
        } else {
          return path;
        }
      })
      .reduce((a, b) => {
        return a.concat(b);
      }, [])
      // Resolve paths to absolute paths so that including the same file
      // multiple times is not treated as different files
      .map(p => path.resolve(p))
  );
}

function toUpperCamelCase(string) {
  return string
    .split('-')
    .map(part => part[0].toUpperCase() + part.slice(1))
    .join('');
}
<commit_msg>Return useful error when --stdin is specified but no schema is provided Closes #38<commit_after>const cosmiconfig = require('cosmiconfig');
import { readSync, readFileSync } from 'fs';
import path from 'path';
import { sync as globSync, hasMagic as globHasMagic } from 'glob';

import { SourceMap } from './source_map.js';
import JSONFormatter from './formatters/json_formatter.js';
import TextFormatter from './formatters/text_formatter.js';

export class Configuration {
  /*
    options:
      - configDirectory: path to begin searching for config files
      - format: (required) `text` | `json`
      - rules: [string array] whitelist rules
      - schemaPaths: [string array] file(s) to read schema from
      - customRulePaths: [string array] path to additional custom rules to be loaded
      - stdin: [boolean] pass schema via stdin?
  */
  constructor(options = {}, stdinFd = null) {
    const defaultOptions = { format: 'text', customRulePaths: [] };
    const configOptions = loadOptionsFromConfig(options.configDirectory);

    // TODO Get configs from .graphqlconfig file

    this.options = Object.assign({}, defaultOptions, configOptions, options);
    this.stdinFd = stdinFd;
    this.schema = null;
    this.sourceMap = null;
    this.rules = null;
    this.rulePaths = this.options.customRulePaths.concat(
      path.join(__dirname, 'rules/*.js')
    );
  }

  getSchema() {
    if (this.schema) {
      return this.schema;
    }

    if (this.options.stdin) {
      this.schema = getSchemaFromFileDescriptor(this.stdinFd);
      if (this.schema == null) {
        return null;
      }

      this.sourceMap = new SourceMap({ stdin: this.schema });
    } else if (this.options.schemaPaths) {
      const expandedPaths = expandPaths(this.options.schemaPaths);
      const segments = getSchemaSegmentsFromFiles(expandedPaths);
      if (Object.keys(segments).length === 0) {
        return null;
      }
      this.sourceMap = new SourceMap(segments);
      this.schema = this.sourceMap.getCombinedSource();
    }

    return this.schema;
  }

  getSchemaSourceMap() {
    if (!this.sourceMap) {
      this.getSchema();
    }

    return this.sourceMap;
  }

  getFormatter() {
    switch (this.options.format) {
      case 'json':
        return JSONFormatter;
      case 'text':
        return TextFormatter;
    }
  }

  getRules() {
    let rules = this.getAllRules();
    let specifiedRules;
    if (this.options.rules && this.options.rules.length > 0) {
      specifiedRules = this.options.rules.map(toUpperCamelCase);
      rules = this.getAllRules().filter(rule => {
        return specifiedRules.indexOf(rule.name) >= 0;
      });
    }

    // DEPRECATED - This code should be removed in v1.0.0.
    if (this.options.only && this.options.only.length > 0) {
      specifiedRules = this.options.only.map(toUpperCamelCase);
      rules = this.getAllRules().filter(rule => {
        return specifiedRules.indexOf(rule.name) >= 0;
      });
    }

    // DEPRECATED - This code should be removed in v1.0.0.
    if (this.options.except && this.options.except.length > 0) {
      specifiedRules = this.options.except.map(toUpperCamelCase);
      rules = this.getAllRules().filter(rule => {
        return specifiedRules.indexOf(rule.name) == -1;
      });
    }

    return rules;
  }

  getAllRules() {
    if (this.rules !== null) {
      return this.rules;
    }

    let expandedPaths = expandPaths(this.rulePaths);
    this.rules = [];
    expandedPaths.map(rulePath => {
      let ruleMap = require(rulePath);
      let rule = Object.keys(ruleMap).map(k => ruleMap[k]);

      if (rule) {
        this.rules = this.rules.concat(rule);
      }
    });

    return this.rules;
  }

  validate() {
    const issues = [];

    const ruleNames = this.getAllRules().map(rule => rule.name);
    let misConfiguredRuleNames = []
      .concat(
        this.options.only || [],
        this.options.except || [],
        this.options.rules || []
      )
      .map(toUpperCamelCase)
      .filter(name => ruleNames.indexOf(name) == -1);

    if (this.getFormatter() == null) {
      issues.push({
        message: `The output format '${this.options.format}' is invalid`,
        field: 'format',
        type: 'error',
      });
    }

    if (misConfiguredRuleNames.length > 0) {
      issues.push({
        message: `The following rule(s) are invalid: ${misConfiguredRuleNames.join(
          ', '
        )}`,
        field: 'rules',
        type: 'warning',
      });
    }

    return issues;
  }
}

function loadOptionsFromConfig(configDirectory) {
  const searchPath = configDirectory || './';

  const cosmic = cosmiconfig('graphql-schema-linter', {
    cache: false,
    sync: true,
  }).load(searchPath);

  if (cosmic) {
    return {
      rules: cosmic.config.rules,
      customRulePaths: cosmic.config.customRulePaths || [],
    };
  } else {
    return {};
  }
}

function getSchemaFromFileDescriptor(fd) {
  let b = new Buffer(1024);
  let data = '';

  while (true) {
    let n;
    try {
      n = readSync(fd, b, 0, b.length);
    } catch (e) {
      if (e.code == 'EAGAIN') {
        console.error(
          'The --stdin option was specified, but not schema was provided via stdin.'
        );
      } else {
        console.error(e.message);
      }
      return null;
    }

    if (!n) {
      break;
    }
    data += b.toString('utf8', 0, n);
  }

  return data;
}

function getSchemaFromFile(path) {
  try {
    return readFileSync(path).toString('utf8');
  } catch (e) {
    console.error(e.message);
  }
  return null;
}

function getSchemaSegmentsFromFiles(paths) {
  return paths.reduce((segments, path) => {
    let schema = getSchemaFromFile(path);
    if (schema) {
      segments[path] = schema;
    }
    return segments;
  }, {});
}

function expandPaths(pathOrPattern) {
  return (
    pathOrPattern
      .map(path => {
        if (globHasMagic(path)) {
          return globSync(path);
        } else {
          return path;
        }
      })
      .reduce((a, b) => {
        return a.concat(b);
      }, [])
      // Resolve paths to absolute paths so that including the same file
      // multiple times is not treated as different files
      .map(p => path.resolve(p))
  );
}

function toUpperCamelCase(string) {
  return string
    .split('-')
    .map(part => part[0].toUpperCase() + part.slice(1))
    .join('');
}
<|endoftext|>


<commit_before>//TODO: Make this a vows test

var Client = new require('../../../lib/pkgcloud/core/base/client').Client;
var helpers = require('../../helpers');

var client = helpers.createClient('azure', 'database');

client.list(function(err, res) {
  if(err) {
    console.dir(err);
  } else {
    console.dir(res);
  }
});

<commit_msg>updated code<commit_after>//TODO: Make this a vows test

var Client = new require('../../../lib/pkgcloud/core/base/client').Client;
var helpers = require('../../helpers');

var client = helpers.createClient('azure', 'database');

client.list(function(err, res) {
  if(err) {
    console.dir(err);
  } else {
    console.dir(res);
  }
});
<|endoftext|>