<commit_before>/*
Copyright (c) 2009-2015, Dan "Ducky" Little & GeoMOOSE.org

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

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

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

/** HashTrack
 *
 *  Continuously update the hash tag in the URL to match the location of
 *  the map.  On startup, change the default extents to the stored location.
 *
 */

HashTrack = new OpenLayers.Class(GeoMOOSE.UX.Extension, {
	center: null,
	zoomLevel: null,

	parseHashTag: function() {
		var args = dojo.queryToObject(''+window.location.hash.substring(1));

		this.center = null;
		if(args.l) {
			var split = args.l.split(',');

			this.center = new OpenLayers.LonLat();
			this.center.lat = parseFloat(split[0]);
			this.center.lon = parseFloat(split[1]);
			this.zoomLevel = parseFloat(split[2]);
		}

	},

	init: function(map) {
		this.parseHashTag();
		if(this.center != null) {
			GeoMOOSE.register('onMapbookLoaded', this, function() {
				map.setCenter(this.center, this.zoomLevel);
			});
		}
		map.events.register('moveend', this, this.mapMoved);
	},

	mapMoved: function() {
		var center = Map.getCenter();
		var zoom = Map.getZoom();
		var position = center.lat + ',' + center.lon + ',' + zoom;
		window.location.hash = '#l='+position
	},

	load: function() {
		GeoMOOSE.register('onMapCreated', this, this.init);

		dojo.connect(window, 'hashchange', dojo.hitch(this, function() {
			this.parseHashTag();
			if(this.center != null) {
				Map.setCenter(this.center, this.zoomLevel);
			}
		}));
	},

	CLASS_NAME: "HashTrack"
});

GeoMOOSE.UX.register('HashTrack');
<commit_msg>Changed "l=" to "xy=" for clarity<commit_after>/*
Copyright (c) 2009-2015, Dan "Ducky" Little & GeoMOOSE.org

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

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

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

/** HashTrack
 *
 *  Continuously update the hash tag in the URL to match the location of
 *  the map.  On startup, change the default extents to the stored location.
 *
 */

HashTrack = new OpenLayers.Class(GeoMOOSE.UX.Extension, {
	center: null,
	zoomLevel: null,

	parseHashTag: function() {
		var args = dojo.queryToObject(''+window.location.hash.substring(1));

		this.center = null;
		if(args.xy) {
			var split = args.xy.split(',');

			this.center = new OpenLayers.LonLat();
			this.center.lat = parseFloat(split[0]);
			this.center.lon = parseFloat(split[1]);
			this.zoomLevel = parseFloat(split[2]);
		}

	},

	init: function(map) {
		this.parseHashTag();
		if(this.center != null) {
			GeoMOOSE.register('onMapbookLoaded', this, function() {
				map.setCenter(this.center, this.zoomLevel);
			});
		}
		map.events.register('moveend', this, this.mapMoved);
	},

	mapMoved: function() {
		var center = Map.getCenter();
		var zoom = Map.getZoom();
		var position = center.lat + ',' + center.lon + ',' + zoom;
		window.location.hash = '#xy='+position
	},

	load: function() {
		GeoMOOSE.register('onMapCreated', this, this.init);

		dojo.connect(window, 'hashchange', dojo.hitch(this, function() {
			this.parseHashTag();
			if(this.center != null) {
				Map.setCenter(this.center, this.zoomLevel);
			}
		}));
	},

	CLASS_NAME: "HashTrack"
});

GeoMOOSE.UX.register('HashTrack');
<|endoftext|>


<commit_before>const tbHeaderbar = require('./shared/TB-Headerbar/tb-headerbar'),
	  tbLoading   = require('./shared/TB-Loading/tb-loading'),
	  tbRoundBtn  = require('./shared/TB-RoundBtn/tb-round-btn'),
	  tbSearch    = require('./shared/TB-Search/tb-search'),
	  tbSidebar   = require('./shared/TB-Sidebar/tb-sidebar'),
	  tbTable     = require('./shared/TB-Table/tb-table');

const moduleName  = 'vinculacion.shared',
     dependencies = [ tbHeaderbar, tbLoading, tbRoundBtn,
	                  tbSearch, tbSidebar, tbTable ];

angular.module(moduleName, dependencies);

module.exports = moduleName;<commit_msg>Add missing shared modules<commit_after>const tbButton    = require('./shared/TB-Button/tb-button.module'),
      tbHeaderbar = require('./shared/TB-Headerbar/tb-headerbar.module'),
	  tbLoading   = require('./shared/TB-Loading/tb-loading.module'),
	  tbPaginator = require('./shared/TB-Paginator/tb-paginator.module'),
	  tbRoundBtn  = require('./shared/TB-RoundBtn/tb-round-btn.module'),
	  tbSearch    = require('./shared/TB-Search/tb-search.module'),
	  tbSidebar   = require('./shared/TB-Sidebar/tb-sidebar.module'),
	  tbTable     = require('./shared/TB-Table/tb-table.module');

const moduleName  = 'vinculacion.shared',
     dependencies = [ tbButton, tbHeaderbar, tbLoading, tbPaginator,
                      tbRoundBtn, tbSearch, tbSidebar, tbTable ];

angular.module(moduleName, dependencies);

module.exports = moduleName;<|endoftext|>


<commit_before>// NodeMCU Handler
const SerialPort = require("serialport");

/**
 * Class to handle the interactions with the NodeMCU device
 *
 * @param baud_rate Baud rate to establish connection with.
 * @param output_console to write output to
 * @param port A serial port to make this with.
 *
 * @constructor
 */
bounce.Nodemcu = function(port_info, baud_rate, output_console) {
    this.port_info = port_info;
    this._port = null;// If connected - the port connection object
    var _received_str = '';
    var _node_instance = this;
    this._output_console = output_console;
    this._multiline_listener = false; // Chains multiline data sends

    /**
     * Register a an event for a line of text received.
     * Note - stuff like prompts, do not come as a line!
     *
     * @param listener
     */
    this.addLineEventListener = function(listener) {
        document.addEventListener('line_received', listener, false);
    };

    this._fire_line_received_event = function(line) {
        var event = new CustomEvent('line_received', {'detail': {node: _node_instance, line: line}});
        document.dispatchEvent(event);
    };

    /**
     * Listener for data - assembling into lines.
     * @param info
     * @private
     */
    function _data_received(data) {
        if(data) {
            output_console.write(data);
            // Append str to received str
            _received_str += data;
            if(_received_str.indexOf('\n') > 0) {
                var parts = _received_str.split("\n");
                for(var n=0; n<parts.length-1; n++) {
                    _node_instance._fire_line_received_event(parts[n]);
                }
                _received_str = parts[n];
            }
        }
    }

    function _setup_data_listener() {
        _node_instance._port.on('data', (data)=>{
            console.log(data);
            if (_node_instance._multiline_listener) {
                _node_instance._multiline_listener();
            }
            _data_received(data)
        });
    }

    this.connect = function (connected_callback) {
        output_console.writeLine("Connecting to device on " + this.port_info.comName);
        this._port = new SerialPort(this.port_info.comName, {baudRate: baud_rate}, (err)=>{
            if (err) {
                console.log(err.message);
                throw err;
            }
            this._port.on('error', function(err) {
                output_console.writeLine('Error: ', err.message);
                throw err;
            });
            this._port.setEncoding('utf-8');
            _setup_data_listener();
            connected_callback(_node_instance);
        });
    };

    this.disconnect = function(disconnected_callback) {
        output_console.writeLine("Disconnecting");
        this._port.close(()=>{if (disconnected_callback) disconnected_callback()});
    };

    /**
     * Send data as a single chunk to the micro
     *
     * @param data Data to send to the device. Always flushed for now.
     * @param sent_callback Called when data was sent and flushed.
     */
    this.send_data = function(data, sent_callback) {
        // Send, flush when done, then perform the callback after this.
        this._port.write(data);
        this._port.drain(()=>{if (sent_callback) sent_callback();});
    };

    /**
     * Send data a line at a time to the micro
     *
     * @param data                  Multiline chunk of text to send
     * @param completed_callback    Call this when done
     */
    this.send_multiline_data = function(data, completed_callback) {
        var lines;
        if(data instanceof Array) {
            lines = data;
        } else {
            lines = data.split("\n");
        }
        var current_line = 0;
        var send_next;
        var last_data = '';

        this._multiline_listener = function(data) {
            console.log("Received call. Data is ", JSON.stringify(data));
            if(goog.string.endsWith(last_data + data, "> ")) {
                send_next();
            } else {
                last_data = data;
            }
        };

        // Send each one, with the sent callback priming the next.
        send_next = function() {
            if (current_line < lines.length) {
                _node_instance.send_data(lines[current_line++] + "\n", function() {});
            } else {
                console.log("Last line sent. Removing listener....");
                this._multiline_listener = null;
                completed_callback();
            }
        };

        send_next();
    };
};

/**
 * Exception to raise when the connection failed
 * @param mcu - the chip we failed to connect to.
 * @param original - the original exception
 * @constructor
 */
bounce.Nodemcu.ConnectionFailed = function(mcu, original) {
    this.mcu = mcu;
    this.original = original;
};

/**
 * USed by scan to validate this is a node.
 *
 * @param found_callback - Function to call when found
 * @param timeout_millis - Time to wait before giving up/disconnecting.
 */
bounce.Nodemcu.prototype.validate = function(found_callback, timeout_millis) {
    var _node_instance = this;

    function _timed_out() {
        _node_instance._output_console.writeLine("Timed out - not running NodeMCU");
        _node_instance.disconnect();
    }

    // Validate by attempting a connection
    this._output_console.writeLine("Attempting connection");
    this.connect(function() {
        _node_instance._output_console.writeLine("Connected");
        // We need two events here:
        // - A timeout - it didn't respond confirming - disconnect the port.
        var timeout = new goog.async.Delay(_timed_out, timeout_millis);
        timeout.start();
        // - A receive - the node response confirms it - cancel the timeout.
        _node_instance.addLineEventListener(function(e) {
            if(goog.string.contains(e.detail.line, 'node mcu confirmed')||
                goog.string.contains(e.detail.line, 'powered by Lua')) {
                _node_instance._output_console.writeLine("Confirmed - NodeMCU found");
                _node_instance.disconnect(()=>found_callback(_node_instance));
                timeout.stop();
            }
        });
        _node_instance._output_console.writeLine("Sending confirmation test");
        _node_instance.send_data("print('node mcu confirmed')\n");
    });
};

/**
 * Send a block of code - save it under the given filename on the device.
 *
 * @param  data     - Data to send
 * @param filename  - Filename to store on the device as
 * @param completed_callback    - Function call when all sent.
 */
bounce.Nodemcu.prototype.send_as_file= function(data, filename, completed_callback) {
        var input_lines = data.split("\n");
        var output_lines = [];
        output_lines.push('file.open("' + filename + '", "w")');
        goog.array.every(input_lines, function(line) {
            output_lines.push('file.write("' + line + '\\n")');
            return true;
        });
        output_lines.push('file.close()');
        this.send_multiline_data(output_lines, completed_callback);
    };

/**
 * Stop all timers.
 */
bounce.Nodemcu.prototype.stop = function() {
    this.send_multiline_data(["for i=0, 6 do", "tmr.stop(i)", "end"], function() {});
};

/**
 * Scan for NodeMCU boards connected
 *
 * @param console - output goes here.
 * @param baud_rate number - the baud rate to scan with.
 * @param timeout - how long to wait in seconds for a serial response to the sent text.
 * @param found_callback Called when it's found with the Serial path.
 */
bounce.Nodemcu.scan = function(console, baud_rate, timeout, found_callback) {
    console.writeLine("Starting scan at " + baud_rate + "...");
    var onGetDevices = function(err, ports) {
        ports.forEach((port)=> {
            console.writeLine('Found serial port ' + port.comName + ', ' + port.manufacturer + '. Testing...');
            var mcu = new bounce.Nodemcu(port, baud_rate, console);
            mcu.validate(found_callback, timeout * 1000);
        });
    };

    SerialPort.list(onGetDevices);
};
<commit_msg>Add easy way to get name (decoupling from underlying thing)<commit_after>// NodeMCU Handler
const SerialPort = require("serialport");

/**
 * Class to handle the interactions with the NodeMCU device
 *
 * @param baud_rate Baud rate to establish connection with.
 * @param output_console to write output to
 * @param port A serial port to make this with.
 *
 * @constructor
 */
bounce.Nodemcu = function(port_info, baud_rate, output_console) {
    this.port_info = port_info;
    this._port = null;// If connected - the port connection object
    var _received_str = '';
    var _node_instance = this;
    this._output_console = output_console;
    this._multiline_listener = false; // Chains multiline data sends

    /**
     * Register a an event for a line of text received.
     * Note - stuff like prompts, do not come as a line!
     *
     * @param listener
     */
    this.addLineEventListener = function(listener) {
        document.addEventListener('line_received', listener, false);
    };

    this._fire_line_received_event = function(line) {
        var event = new CustomEvent('line_received', {'detail': {node: _node_instance, line: line}});
        document.dispatchEvent(event);
    };

    /**
     * Listener for data - assembling into lines.
     * @param info
     * @private
     */
    function _data_received(data) {
        if(data) {
            output_console.write(data);
            // Append str to received str
            _received_str += data;
            if(_received_str.indexOf('\n') > 0) {
                var parts = _received_str.split("\n");
                for(var n=0; n<parts.length-1; n++) {
                    _node_instance._fire_line_received_event(parts[n]);
                }
                _received_str = parts[n];
            }
        }
    }

    function _setup_data_listener() {
        _node_instance._port.on('data', (data)=>{
            console.log(data);
            if (_node_instance._multiline_listener) {
                _node_instance._multiline_listener();
            }
            _data_received(data)
        });
    }

    this.connect = function (connected_callback) {
        output_console.writeLine("Connecting to device on " + this.port_info.comName);
        this._port = new SerialPort(this.port_info.comName, {baudRate: baud_rate}, (err)=>{
            if (err) {
                console.log(err.message);
                throw err;
            }
            this._port.on('error', function(err) {
                output_console.writeLine('Error: ', err.message);
                throw err;
            });
            this._port.setEncoding('utf-8');
            _setup_data_listener();
            connected_callback(_node_instance);
        });
    };

    this.disconnect = function(disconnected_callback) {
        output_console.writeLine("Disconnecting");
        this._port.close(()=>{if (disconnected_callback) disconnected_callback()});
    };

    /**
     * Send data as a single chunk to the micro
     *
     * @param data Data to send to the device. Always flushed for now.
     * @param sent_callback Called when data was sent and flushed.
     */
    this.send_data = function(data, sent_callback) {
        // Send, flush when done, then perform the callback after this.
        this._port.write(data);
        this._port.drain(()=>{if (sent_callback) sent_callback();});
    };

    /**
     * Send data a line at a time to the micro
     *
     * @param data                  Multiline chunk of text to send
     * @param completed_callback    Call this when done
     */
    this.send_multiline_data = function(data, completed_callback) {
        var lines;
        if(data instanceof Array) {
            lines = data;
        } else {
            lines = data.split("\n");
        }
        var current_line = 0;
        var send_next;
        var last_data = '';

        this._multiline_listener = function(data) {
            console.log("Received call. Data is ", JSON.stringify(data));
            if(goog.string.endsWith(last_data + data, "> ")) {
                send_next();
            } else {
                last_data = data;
            }
        };

        // Send each one, with the sent callback priming the next.
        send_next = function() {
            if (current_line < lines.length) {
                _node_instance.send_data(lines[current_line++] + "\n", function() {});
            } else {
                console.log("Last line sent. Removing listener....");
                this._multiline_listener = null;
                completed_callback();
            }
        };

        send_next();
    };
};

/**
 * Exception to raise when the connection failed
 * @param mcu - the chip we failed to connect to.
 * @param original - the original exception
 * @constructor
 */
bounce.Nodemcu.ConnectionFailed = function(mcu, original) {
    this.mcu = mcu;
    this.original = original;
};

bounce.Nodemcu.prototype.get_name = function() {
    return this.port_info.comName;
}

/**
 * USed by scan to validate this is a node.
 *
 * @param found_callback - Function to call when found
 * @param timeout_millis - Time to wait before giving up/disconnecting.
 */
bounce.Nodemcu.prototype.validate = function(found_callback, timeout_millis) {
    var _node_instance = this;

    function _timed_out() {
        _node_instance._output_console.writeLine("Timed out - not running NodeMCU");
        _node_instance.disconnect();
    }

    // Validate by attempting a connection
    this._output_console.writeLine("Attempting connection");
    this.connect(function() {
        _node_instance._output_console.writeLine("Connected");
        // We need two events here:
        // - A timeout - it didn't respond confirming - disconnect the port.
        var timeout = new goog.async.Delay(_timed_out, timeout_millis);
        timeout.start();
        // - A receive - the node response confirms it - cancel the timeout.
        _node_instance.addLineEventListener(function(e) {
            if(goog.string.contains(e.detail.line, 'node mcu confirmed')||
                goog.string.contains(e.detail.line, 'powered by Lua')) {
                _node_instance._output_console.writeLine("Confirmed - NodeMCU found");
                _node_instance.disconnect(()=>found_callback(_node_instance));
                timeout.stop();
            }
        });
        _node_instance._output_console.writeLine("Sending confirmation test");
        _node_instance.send_data("print('node mcu confirmed')\n");
    });
};

/**
 * Send a block of code - save it under the given filename on the device.
 *
 * @param  data     - Data to send
 * @param filename  - Filename to store on the device as
 * @param completed_callback    - Function call when all sent.
 */
bounce.Nodemcu.prototype.send_as_file= function(data, filename, completed_callback) {
        var input_lines = data.split("\n");
        var output_lines = [];
        output_lines.push('file.open("' + filename + '", "w")');
        goog.array.every(input_lines, function(line) {
            output_lines.push('file.write("' + line + '\\n")');
            return true;
        });
        output_lines.push('file.close()');
        this.send_multiline_data(output_lines, completed_callback);
    };

/**
 * Stop all timers.
 */
bounce.Nodemcu.prototype.stop = function() {
    this.send_multiline_data(["for i=0, 6 do", "tmr.stop(i)", "end"], function() {});
};

/**
 * Scan for NodeMCU boards connected
 *
 * @param console - output goes here.
 * @param baud_rate number - the baud rate to scan with.
 * @param timeout - how long to wait in seconds for a serial response to the sent text.
 * @param found_callback Called when it's found with the Serial path.
 */
bounce.Nodemcu.scan = function(console, baud_rate, timeout, found_callback) {
    console.writeLine("Starting scan at " + baud_rate + "...");
    var onGetDevices = function(err, ports) {
        ports.forEach((port)=> {
            console.writeLine('Found serial port ' + port.comName + ', ' + port.manufacturer + '. Testing...');
            var mcu = new bounce.Nodemcu(port, baud_rate, console);
            mcu.validate(found_callback, timeout * 1000);
        });
    };

    SerialPort.list(onGetDevices);
};
<|endoftext|>


<commit_before>"use strict"
class WebSocketP extends EventEmitter{
  constructor(Options){
    super()
    let Me = this
    this.Connection = new WebSocket(Options)
    this.Connection.addEventListener('message', function(Data){
      try {
        Data = JSON.parse(Data.data)
        if(!Data.EXCHANGE) throw null
      } catch(err){
        return Me.emit('ParseError', Data)
      }
      if(Data.Type === 'Request'){
        Data.Result = null
        Me.emit(Data.SubType, Data.Message, Data)
        Me.emit('All', Data.Message, Data)
      } else if(Data.Type === 'Broadcast'){
        Me.emit(Data.SubType, Data.Message, Data)
        Me.emit('All', Data.Message, Data)
      } else if (Data.Type === 'Reply'){
        Me.emit(`JOB:${Data.ID}`, Data.Message)
      }
    })
  }
  Send(Type, Message){
    Message = Message || ''
    this.Connection.send(JSON.stringify({Type: 'Broadcast', SubType: Type, Message: Message, Exchange: true}))
    return this
  }
  Request(Type, Message){
    Message = Message || ''
    let Me = this
    return new Promise(function(Resolve){
      let JobID = (Math.random().toString(36)+'00000000000000000').slice(2, 7+2)
      Me.once(`JOB:${JobID}`, Resolve)
      Me.Connection.send(JSON.stringify({Type: 'Request', SubType: Type, Message: Message, ID: JobID, EXCHANGE: true}))
    })
  }
  Finished(Job){
    this.Connection.send(JSON.stringify({Type: 'Reply', ID: Job.ID, Message: Job.Result, EXCHANGE: true}))
  }
  Terminate(){
    this.Connection.close()
  }
}<commit_msg>:art: Add UC Tags<commit_after>"use strict"
// @Compiler-Compress "true"
// @Compiler-Transpile "true"
// @Compiler-Output "WebSocketP.min.js"
class WebSocketP extends EventEmitter{
  constructor(Options){
    super()
    let Me = this
    this.Connection = new WebSocket(Options)
    this.Connection.addEventListener('message', function(Data){
      try {
        Data = JSON.parse(Data.data)
        if(!Data.EXCHANGE) throw null
      } catch(err){
        return Me.emit('ParseError', Data)
      }
      if(Data.Type === 'Request'){
        Data.Result = null
        Me.emit(Data.SubType, Data.Message, Data)
        Me.emit('All', Data.Message, Data)
      } else if(Data.Type === 'Broadcast'){
        Me.emit(Data.SubType, Data.Message, Data)
        Me.emit('All', Data.Message, Data)
      } else if (Data.Type === 'Reply'){
        Me.emit(`JOB:${Data.ID}`, Data.Message)
      }
    })
  }
  Send(Type, Message){
    Message = Message || ''
    this.Connection.send(JSON.stringify({Type: 'Broadcast', SubType: Type, Message: Message, Exchange: true}))
    return this
  }
  Request(Type, Message){
    Message = Message || ''
    let Me = this
    return new Promise(function(Resolve){
      let JobID = (Math.random().toString(36)+'00000000000000000').slice(2, 7+2)
      Me.once(`JOB:${JobID}`, Resolve)
      Me.Connection.send(JSON.stringify({Type: 'Request', SubType: Type, Message: Message, ID: JobID, EXCHANGE: true}))
    })
  }
  Finished(Job){
    this.Connection.send(JSON.stringify({Type: 'Reply', ID: Job.ID, Message: Job.Result, EXCHANGE: true}))
  }
  Terminate(){
    this.Connection.close()
  }
}
window.WebSocketP = WebSocketP<|endoftext|>


<commit_before>var OAuth2Strategy = require('passport-oauth2')
	, request = require('request')
	, querystring = require('querystring')
	, util = require('util')
	, AuthorizationError = require('passport-oauth2').AuthorizationError
	, InternalOAuthError = require('passport-oauth2').InternalOAuthError
	;

function OAuth2(clientID, clientSecret, authorizationURL, tokenURL, customHeaders) {
	this.clientID = clientID;
	this.clientSecret = clientSecret;
	this.authorizationURL = authorizationURL || "https://api.nylas.com/oauth/authorize";
	this.tokenURL = tokenURL || "https://api.nylas.com/oauth/token";
	this._accessTokenName = "access_token";
	this.customHeaders = customHeaders || {};

	return this;
}

// -- https://api.nylas.com/oauth/authorize
OAuth2.prototype.getAuthorizeUrl = function(params) {
	var params = params || {};
	if (!(this.clientID && this.clientSecret)) {
		throw new Error("getAuthorizeUrl() cannot be called until you provide a client_id and client_secret");
	}
	if (params.redirect_uri == null) {
		throw new Error("getAuthorizeUrl() requires a redirect_uri");
	}
	if (params.loginHint == null) {
		params.loginHint = '';
	}
	if (params.trial == null) {
		params.trial = false;
	}
	params.client_id = this.clientID;
	return this.authorizationURL + "?" + querystring.stringify(params);
}

OAuth2.prototype.setAccessTokenName = function(name) {
	this._accessTokenName = name;
}

OAuth2.prototype.getOAuthAccessToken = function(code, params, callback) {
	var params = params || {};
	params.client_id = this.clientID;
	params.client_secret = this.clientSecret;
	params.code = code;

	//var post_data = querystring.stringify(params);

	var _oauth = this;

	request({
		method	: 'POST',
		json: true,
		url		: _oauth.tokenURL,
		qs		: params
	}, function(error, response, body) {
		if (error) { return callback(error, null) }
		if (response.statusCode === 403) {return callback(403, null) }

		else {
			var results;
			try {
				//response body should be in JSON
				// http://tools.ietf.org/html/draft-ietf-oauth-v2-07
				results = JSON.parse(body);
			}
			catch(e) {
				//Content-Type thrown correctly?
				results =  querystring.parse(body);
			}
			var email_address = results["email_address"];
			var access_token = results["access_token"];
			//var provider = results["provider"];
			//var account_id = results["account_id"]; -- both should be available in the results object
			callback(null, email_address, access_token, results);
		}
	});
}

/**
* Strategy constructor.
*
* The Nylas authentication strategy authenticates requests by delegating to
* Nylas using the OAuth 2.0 protocol.

* Applications must provide a `verify` callback which accepts an `email`,
* `accessToken`, and `nylas` object, containing addiditional info.
* callback will then call the `done` callback supplying a `user`, which is
* set to `false` if the credentials are invalid. `err` would be set if an exception occured.
*
*
* Options:
*	- `clientID`		your Nylas application's clientID
*	- `clientSecret`	your Nylas application's clientSecret
*	- `callbackURL`		your Nylas application's callbackURL -- URL to redirect to after successful authorization

* @param {Object} options
* @param {Function} verify
* @api public
*/
function Strategy(options, verify) {
	options = options || {};
	options.sessionKey = options.sessionKey || 'oauth2:nylas';
	/*options.authorizationURL = options.authorizationURL || 'https://api.nylas.com/oauth/authorize';
	options.tokenURL = options.tokenURL || 'https://api.nylas.com/oauth/token';
	options.clientID = options.clientID;
	options.clientSecret = options.clientSecret;
	options.scope = options.scope;
	*/

	if (!verify) {throw new TypeError('OAuth2Strategy requires a verify callback'); }
	//if (!options.authorizationURL) {throw new TypeError('OAuth2Strategy requires an authorizationURL option'); }
	//if (!options.tokenURL) {throw new TypeError('OAuth2Strategy requires a tokenURL option'); }
	//if (!options.clientID) {throw new TypeError('OAuth2Strategy requires a clientID option'); }

	//this._options = options
	this._verify = verify;
	this._oauth2 = new OAuth2(options.clientID, options.clientSecret, options.authorizationURL, options.tokenURL, options.customHeaders);
	this._scope = options.scope;
	this._callbackURL = options.callbackURL;

	this.name = 'nylas';
}

util.inherits(Strategy, OAuth2Strategy);

/**
* Authenticating request using the OAuth 2.0 protocol
* @param {Object} req
* @api protected
*/

Strategy.prototype.authenticate = function(req, options) {
	options = options || {};

	if (req.query && req.query.error) {
		if (req.query.error == 'access_denied') {
			return this.fail({ message: req.query.error_description});
		} else {
			return this.error(new AuthorizationError(req.query.error_description, req.query.error, req.query.error_uri));
		}
	}

	if (!req.session) { return this.error(new Error('OAuth authentication requires session support '))}

	var self = this;

	req.session.nylasCode = req.query.code;
	if (req.session && req.session.nylasCode) {

		function verified(err, user, info) {
			if (err) {return self.error(err); }
			if (!user) {return self.fail(info); }

			info = info || {};
			req.session.nylasData.info = info;
			self.success(user, info);
		}

		var params = this.tokenParams(options);
		params.grant_type = 'authorization_code';
		//params.redirect_uri = this._callbackURL;
		if (req.session.nylasData) {
			self.pass(req.session.nylasData.email, req.session.nylasData.info );
		} else {
			this._oauth2.getOAuthAccessToken(req.session.nylasCode, params,
				function(err, email, accessToken, params) {
					if (err) {return self.error(new InternalOAuthError('failed to obtain access token', err)); }

					//Additional nylas boject returned
					var nylas = {};
					nylas.provider = params.provider || null;
					nylas.account_id = params.account_id || null;
					nylas.token_type = params.token_type || null;
					nylas.scope = params.scope || null;
					req.session.nylasData = {
						email: email,
						accessToken: accessToken
					}

					self._verify(email, accessToken, nylas, verified);
				}
			);
		}
	} else {
		var params = this.authorizationParams(options);
			params.response_type = 'code';
			params.redirect_uri = this._callbackURL;
			params.scope = 'email' || this._scope;
			var state = options.state || req.query.state;
			if (state) {params.state = state; }
		var location = this._oauth2.getAuthorizeUrl(params);
		this.redirect(location);
	}
};

/* Authorize URL = "/oauth/authorize?client_id=" +
	this.appId +
	"&trial=" + options.trial +
	"&response_type=code&scope=email&login_hint=" +
	options.loginHint +
	"&redirect_uri=" + options.redirectURI;
*/

/*
* Override OAuth authorizeParams method to allow passing additional parms
* per "pre-fill" Nylas feature
* Return extra parameters to be included in the authorization request.
*/
Strategy.prototype.authorizationParams = function(options) {
	return options;
};

/*
* Override OAuth authorizeParams method to allow passing additional parms
* per "pre-fill" Nylas feature
* Return extra parameters to be included in the token request.
*/
Strategy.prototype.tokenParams = function(options) {
	return options;
};

//example
Strategy.prototype.getThread = function(accessToken, params, offset, limit, callback) {
	return request({
		method: 'GET',
		path: "https://api.nylas.com/threads",
		auth: {
			'user': accessToken,
			'pass': '',
			'sendImmediately': true
		},
		json: true,
		qs: {
			offset: offset,
			limit: limit
		}
	}, function(error, response, body) {
		if (body) {
			return callback(null, body);
		}
	})
}

Strategy.prototype.getFirstThread = function(accessToken, params, callback) {

	if (params == null) {
		params = {};
	}
	return this.getThread(params, 0, 1, function(err, data) {
		if (err) return callback(err, null);
		if (data) {
			callback(null, data[0]);
		}
	});
};

Strategy.prototype.findThread = function(id, callback) {
	request({
		method: 'GET',
		path: 'https://api.nylas.com/threads' + id,
		json: true,
	}, function(err, response, body) {
		if (body) {
			callback(err, body);
		}
	});
};

module.exports = Strategy;<commit_msg>getOAuthAccessToken edit<commit_after>var OAuth2Strategy = require('passport-oauth2')
	, request = require('request')
	, querystring = require('querystring')
	, util = require('util')
	, AuthorizationError = require('passport-oauth2').AuthorizationError
	, InternalOAuthError = require('passport-oauth2').InternalOAuthError
	;

function OAuth2(clientID, clientSecret, authorizationURL, tokenURL, customHeaders) {
	this.clientID = clientID;
	this.clientSecret = clientSecret;
	this.authorizationURL = authorizationURL || "https://api.nylas.com/oauth/authorize";
	this.tokenURL = tokenURL || "https://api.nylas.com/oauth/token";
	this._accessTokenName = "access_token";
	this.customHeaders = customHeaders || {};

	return this;
}

// -- https://api.nylas.com/oauth/authorize
OAuth2.prototype.getAuthorizeUrl = function(params) {
	var params = params || {};
	if (!(this.clientID && this.clientSecret)) {
		throw new Error("getAuthorizeUrl() cannot be called until you provide a client_id and client_secret");
	}
	if (params.redirect_uri == null) {
		throw new Error("getAuthorizeUrl() requires a redirect_uri");
	}
	if (params.loginHint == null) {
		params.loginHint = '';
	}
	if (params.trial == null) {
		params.trial = false;
	}
	params.client_id = this.clientID;
	return this.authorizationURL + "?" + querystring.stringify(params);
}

OAuth2.prototype.setAccessTokenName = function(name) {
	this._accessTokenName = name;
}

OAuth2.prototype.getOAuthAccessToken = function(code, params, callback) {
	var params = params || {};
	params.client_id = this.clientID;
	params.client_secret = this.clientSecret;
	params.code = code;

	//var post_data = querystring.stringify(params);

	var _oauth = this;

	request({
		method	: 'POST',
		json: true,
		url		: _oauth.tokenURL,
		qs		: params
	}, function(error, response, body) {
		if (error) { return callback(error, null) }
		if (response.statusCode === 403) {return callback(403, null) }

		var email_address = body["email_address"];
		var access_token = body["access_token"];
		//var provider = results["provider"];
		//var account_id = results["account_id"]; -- both should be available in the results object
		return callback(null, email_address, access_token, body);
	});
}

/**
* Strategy constructor.
*
* The Nylas authentication strategy authenticates requests by delegating to
* Nylas using the OAuth 2.0 protocol.

* Applications must provide a `verify` callback which accepts an `email`,
* `accessToken`, and `nylas` object, containing addiditional info.
* callback will then call the `done` callback supplying a `user`, which is
* set to `false` if the credentials are invalid. `err` would be set if an exception occured.
*
*
* Options:
*	- `clientID`		your Nylas application's clientID
*	- `clientSecret`	your Nylas application's clientSecret
*	- `callbackURL`		your Nylas application's callbackURL -- URL to redirect to after successful authorization

* @param {Object} options
* @param {Function} verify
* @api public
*/
function Strategy(options, verify) {
	options = options || {};
	options.sessionKey = options.sessionKey || 'oauth2:nylas';
	/*options.authorizationURL = options.authorizationURL || 'https://api.nylas.com/oauth/authorize';
	options.tokenURL = options.tokenURL || 'https://api.nylas.com/oauth/token';
	options.clientID = options.clientID;
	options.clientSecret = options.clientSecret;
	options.scope = options.scope;
	*/

	if (!verify) {throw new TypeError('OAuth2Strategy requires a verify callback'); }
	//if (!options.authorizationURL) {throw new TypeError('OAuth2Strategy requires an authorizationURL option'); }
	//if (!options.tokenURL) {throw new TypeError('OAuth2Strategy requires a tokenURL option'); }
	//if (!options.clientID) {throw new TypeError('OAuth2Strategy requires a clientID option'); }

	//this._options = options
	this._verify = verify;
	this._oauth2 = new OAuth2(options.clientID, options.clientSecret, options.authorizationURL, options.tokenURL, options.customHeaders);
	this._scope = options.scope;
	this._callbackURL = options.callbackURL;

	this.name = 'nylas';
}

util.inherits(Strategy, OAuth2Strategy);

/**
* Authenticating request using the OAuth 2.0 protocol
* @param {Object} req
* @api protected
*/

Strategy.prototype.authenticate = function(req, options) {
	options = options || {};

	if (req.query && req.query.error) {
		if (req.query.error == 'access_denied') {
			return this.fail({ message: req.query.error_description});
		} else {
			return this.error(new AuthorizationError(req.query.error_description, req.query.error, req.query.error_uri));
		}
	}

	if (!req.session) { return this.error(new Error('OAuth authentication requires session support '))}

	var self = this;

	req.session.nylasCode = req.query.code;
	if (req.session && req.session.nylasCode) {

		function verified(err, user, info) {
			if (err) {return self.error(err); }
			if (!user) {return self.fail(info); }

			info = info || {};
			req.session.nylasData.info = info;
			self.success(user, info);
		}

		var params = this.tokenParams(options);
		params.grant_type = 'authorization_code';
		//params.redirect_uri = this._callbackURL;
		if (req.session.nylasData) {
			self.pass(req.session.nylasData.email, req.session.nylasData.info );
		} else {
			this._oauth2.getOAuthAccessToken(req.session.nylasCode, params,
				function(err, email, accessToken, params) {
					console.log(email);
					console.log(accessToken);
					if (err) {return self.error(new InternalOAuthError('failed to obtain access token', err)); }

					//Additional nylas boject returned
					var nylas = {};
					nylas.provider = params.provider || null;
					nylas.account_id = params.account_id || null;
					nylas.token_type = params.token_type || null;
					nylas.scope = params.scope || null;
					req.session.nylasData = {
						email: email,
						accessToken: accessToken
					}

					self._verify(email, accessToken, nylas, verified);
				}
			);
		}
	} else {
		var params = this.authorizationParams(options);
			params.response_type = 'code';
			params.redirect_uri = this._callbackURL;
			params.scope = 'email' || this._scope;
			var state = options.state || req.query.state;
			if (state) {params.state = state; }
		var location = this._oauth2.getAuthorizeUrl(params);
		this.redirect(location);
	}
};

/* Authorize URL = "/oauth/authorize?client_id=" +
	this.appId +
	"&trial=" + options.trial +
	"&response_type=code&scope=email&login_hint=" +
	options.loginHint +
	"&redirect_uri=" + options.redirectURI;
*/

/*
* Override OAuth authorizeParams method to allow passing additional parms
* per "pre-fill" Nylas feature
* Return extra parameters to be included in the authorization request.
*/
Strategy.prototype.authorizationParams = function(options) {
	return options;
};

/*
* Override OAuth authorizeParams method to allow passing additional parms
* per "pre-fill" Nylas feature
* Return extra parameters to be included in the token request.
*/
Strategy.prototype.tokenParams = function(options) {
	return options;
};

//example
Strategy.prototype.getThread = function(accessToken, params, offset, limit, callback) {
	return request({
		method: 'GET',
		path: "https://api.nylas.com/threads",
		auth: {
			'user': accessToken,
			'pass': '',
			'sendImmediately': true
		},
		json: true,
		qs: {
			offset: offset,
			limit: limit
		}
	}, function(error, response, body) {
		if (body) {
			return callback(null, body);
		}
	})
}

Strategy.prototype.getFirstThread = function(accessToken, params, callback) {

	if (params == null) {
		params = {};
	}
	return this.getThread(accessToken, params, 0, 1, function(err, data) {
		if (err) return callback(err, null);
		if (data) {
			callback(null, data[0]);
		}
	});
};

Strategy.prototype.findThread = function(id, callback) {
	request({
		method: 'GET',
		path: 'https://api.nylas.com/threads' + id,
		json: true,
	}, function(err, response, body) {
		if (body) {
			callback(err, body);
		}
	});
};

module.exports = Strategy;<|endoftext|>


<commit_before>var apps = [
    { "folder": "o2_lib", "tasks": ["move"] },
    { "folder": "o2_core", "tasks": ["move", "min"] },
    { "folder": "x_component_ANN", "tasks": ["move", "min"] },
    { "folder": "x_component_AppCenter", "tasks": ["move", "min"] },
    { "folder": "x_component_AppMarketV2", "tasks": ["move", "min"] },
    { "folder": "x_component_AppMarketV2_Application", "tasks": ["move", "min"] },
    { "folder": "x_component_Attendance", "tasks": ["move", "min"] },
    { "folder": "x_component_BAM", "tasks": ["move", "min"] },
    { "folder": "x_component_Calendar", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Column", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_ColumnManager", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_DictionaryDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Document", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_FormDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Index", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Module", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_QueryViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_ScriptDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_ViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Xform", "tasks": ["move", "min"] },
    { "folder": "x_component_Collect", "tasks": ["move", "min"] },
    { "folder": "x_component_Common", "tasks": ["move", "min"] },
    { "folder": "x_component_Console", "tasks": ["move", "min"] },
    { "folder": "x_component_ControlPanel", "tasks": ["move", "min"] },
    { "folder": "x_component_CRM", "tasks": ["move", "min"] },
    { "folder": "x_component_Deployment", "tasks": ["move", "min"] },
    { "folder": "x_component_DesignCenter", "tasks": ["move", "min"] },
    { "folder": "x_component_Empty", "tasks": ["move", "min"] },
    { "folder": "x_component_Execution", "tasks": ["move", "min"] },
    { "folder": "x_component_ExeManager", "tasks": ["move", "min"] },
    { "folder": "x_component_FaceSet", "tasks": ["move", "min"] },
    { "folder": "x_component_File", "tasks": ["move", "min"] },
    { "folder": "x_component_Forum", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumCategory", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumDocument", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumPerson", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumSearch", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumSection", "tasks": ["move", "min"] },
    { "folder": "x_component_Homepage", "tasks": ["move", "min"] },
    { "folder": "x_component_HotArticle", "tasks": ["move", "min"] },
    { "folder": "x_component_LogViewer", "tasks": ["move", "min"] },
    { "folder": "x_component_Meeting", "tasks": ["move", "min"] },
    { "folder": "x_component_Minder", "tasks": ["move", "min"] },
    { "folder": "x_component_MinderEditor", "tasks": ["move", "min"] },
    { "folder": "x_component_Note", "tasks": ["move", "min"] },
    { "folder": "x_component_OKR", "tasks": ["move", "min"] },
    { "folder": "x_component_Org", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_PageDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_Portal", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_PortalExplorer", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_PortalManager", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_ScriptDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_WidgetDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_Application", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ApplicationExplorer", "tasks": ["move", "min"] },
    { "folder": "x_component_process_DictionaryDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_FormDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ProcessDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ProcessManager", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ScriptDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_StatDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_TaskCenter", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_WidgetDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_Work", "tasks": ["move", "min"] },
    { "folder": "x_component_process_Xform", "tasks": ["move", "min"] },
    { "folder": "x_component_Profile", "tasks": ["move", "min"] },
    { "folder": "x_component_query_Query", "tasks": ["move", "min"] },
    { "folder": "x_component_query_QueryExplorer", "tasks": ["move", "min"] },
    { "folder": "x_component_query_QueryManager", "tasks": ["move", "min"] },
    { "folder": "x_component_query_StatDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_query_ViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_query_TableDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_query_StatementDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_Report", "tasks": ["move", "min"] },
    { "folder": "x_component_ReportDocument", "tasks": ["move", "min"] },
    { "folder": "x_component_ReportMinder", "tasks": ["move", "min"] },
    { "folder": "x_component_Search", "tasks": ["move", "min"] },
    { "folder": "x_component_Selector", "tasks": ["move", "min"] },
    { "folder": "x_component_service_AgentDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_service_InvokeDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_service_ServiceManager", "tasks": ["move", "min"] },
    { "folder": "x_component_Setting", "tasks": ["move", "min"] },
    { "folder": "x_component_Strategy", "tasks": ["move", "min"] },
    { "folder": "x_component_Template", "tasks": ["move", "min"] },
    { "folder": "x_component_TeamWork", "tasks": ["move", "min"] },
    { "folder": "x_desktop", "tasks": ["move", "min"] },
    { "folder": "x_component_IMV2", "tasks": ["move", "min"] },

];

module.exports = apps;
<commit_msg>[系统设置]bug修复<commit_after>var apps = [
    { "folder": "o2_lib", "tasks": ["move"] },
    { "folder": "o2_core", "tasks": ["move", "min"] },
    { "folder": "x_component_ANN", "tasks": ["move", "min"] },
    { "folder": "x_component_AppCenter", "tasks": ["move", "min"] },
    { "folder": "x_component_AppMarketV2", "tasks": ["move", "min"] },
    { "folder": "x_component_AppMarketV2_Application", "tasks": ["move", "min"] },
    { "folder": "x_component_Attendance", "tasks": ["move", "min"] },
    { "folder": "x_component_BAM", "tasks": ["move", "min"] },
    { "folder": "x_component_Calendar", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Column", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_ColumnManager", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_DictionaryDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Document", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_FormDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Index", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Module", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_QueryViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_ScriptDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_ViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_cms_Xform", "tasks": ["move", "min"] },
    { "folder": "x_component_Collect", "tasks": ["move", "min"] },
    { "folder": "x_component_Common", "tasks": ["move", "min"] },
    { "folder": "x_component_Console", "tasks": ["move", "min"] },
    { "folder": "x_component_ControlPanel", "tasks": ["move", "min"] },
    { "folder": "x_component_CRM", "tasks": ["move", "min"] },
    { "folder": "x_component_Deployment", "tasks": ["move", "min"] },
    { "folder": "x_component_DesignCenter", "tasks": ["move", "min"] },
    { "folder": "x_component_Empty", "tasks": ["move", "min"] },
    { "folder": "x_component_Execution", "tasks": ["move", "min"] },
    { "folder": "x_component_ExeManager", "tasks": ["move", "min"] },
    { "folder": "x_component_FaceSet", "tasks": ["move", "min"] },
    { "folder": "x_component_File", "tasks": ["move", "min"] },
    { "folder": "x_component_Forum", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumCategory", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumDocument", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumPerson", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumSearch", "tasks": ["move", "min"] },
    { "folder": "x_component_ForumSection", "tasks": ["move", "min"] },
    { "folder": "x_component_Homepage", "tasks": ["move", "min"] },
    { "folder": "x_component_HotArticle", "tasks": ["move", "min"] },
    { "folder": "x_component_LogViewer", "tasks": ["move", "min"] },
    { "folder": "x_component_Meeting", "tasks": ["move", "min"] },
    { "folder": "x_component_Minder", "tasks": ["move", "min"] },
    { "folder": "x_component_MinderEditor", "tasks": ["move", "min"] },
    { "folder": "x_component_Note", "tasks": ["move", "min"] },
    { "folder": "x_component_OKR", "tasks": ["move", "min"] },
    { "folder": "x_component_Org", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_PageDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_Portal", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_PortalExplorer", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_PortalManager", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_ScriptDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_portal_WidgetDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_Application", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ApplicationExplorer", "tasks": ["move", "min"] },
    { "folder": "x_component_process_DictionaryDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_FormDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ProcessDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ProcessManager", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ScriptDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_StatDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_TaskCenter", "tasks": ["move", "min"] },
    { "folder": "x_component_process_ViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_WidgetDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_process_Work", "tasks": ["move", "min"] },
    { "folder": "x_component_process_Xform", "tasks": ["move", "min"] },
    { "folder": "x_component_Profile", "tasks": ["move", "min"] },
    { "folder": "x_component_query_Query", "tasks": ["move", "min"] },
    { "folder": "x_component_query_QueryExplorer", "tasks": ["move", "min"] },
    { "folder": "x_component_query_QueryManager", "tasks": ["move", "min"] },
    { "folder": "x_component_query_StatDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_query_ViewDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_query_TableDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_query_StatementDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_Report", "tasks": ["move", "min"] },
    { "folder": "x_component_ReportDocument", "tasks": ["move", "min"] },
    { "folder": "x_component_ReportMinder", "tasks": ["move", "min"] },
    { "folder": "x_component_Search", "tasks": ["move", "min"] },
    { "folder": "x_component_Selector", "tasks": ["move", "min"] },
    { "folder": "x_component_service_AgentDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_service_InvokeDesigner", "tasks": ["move", "min"] },
    { "folder": "x_component_service_ServiceManager", "tasks": ["move", "min"] },
    { "folder": "x_component_Setting", "tasks": ["move", "min"] },
    { "folder": "x_component_Strategy", "tasks": ["move", "min"] },
    { "folder": "x_component_Template", "tasks": ["move", "min"] },
    { "folder": "x_component_TeamWork", "tasks": ["move", "min"] },
    { "folder": "x_desktop", "tasks": ["move", "min"] },
    { "folder": "x_component_IMV2", "tasks": ["move", "min"] },
    { "folder": "x_component_ConfigDesigner", "tasks": ["move", "min"] },

];

module.exports = apps;
<|endoftext|>


<commit_before>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
/*global exports:true*/

/**
 * Implements ES6 call spread.
 *
 * instance.method(a, b, c, ...d)
 *
 * instance.method.apply(instance, [a, b, c].concat(d))
 *
 */

var Syntax = require('esprima-fb').Syntax;
var utils = require('../src/utils');

function process(traverse, node, path, state) {
  utils.move(node.range[0], state);
  traverse(node, path, state);
  utils.catchup(node.range[1], state);
}

function visitCallSpread(traverse, node, path, state) {
  utils.catchup(node.range[0], state);

  if (node.type === Syntax.NewExpression) {
    // Input  = new Set(1, 2, ...list)
    // Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
    utils.append('new (Function.prototype.bind.apply(', state);
    process(traverse, node.callee, path, state);
  } else if (node.callee.type === Syntax.MemberExpression) {
    // Input  = get().fn(1, 2, ...more)
    // Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
    var tempVar = utils.injectTempVar(state);
    utils.append('(' + tempVar + ' = ', state);
    process(traverse, node.callee.object, path, state);
    utils.append(')', state);
    if (node.callee.property.type === Syntax.Identifier) {
      utils.append('.', state);
      process(traverse, node.callee.property, path, state);
    } else {
      utils.append('[', state);
      process(traverse, node.callee.property, path, state);
      utils.append(']', state);
    }
    utils.append('.apply(' + tempVar, state);
  } else {
    // Input  = max(1, 2, ...list)
    // Output = max.apply(undefined, [1, 2].concat(list))
    var needsToBeWrappedInParenthesis =
      node.callee.type === Syntax.FunctionDeclaration ||
      node.callee.type === Syntax.FunctionExpression;
    if (needsToBeWrappedInParenthesis) {
      utils.append('(', state);
    }
    process(traverse, node.callee, path, state);
    if (needsToBeWrappedInParenthesis) {
      utils.append(')', state);
    }
    utils.append('.apply(undefined', state);
  }
  utils.append(', ', state);

  var args = node.arguments.slice();
  var spread = args.pop();
  if (args.length || node.type === Syntax.NewExpression) {
    utils.append('[', state);
    if (node.type === Syntax.NewExpression) {
      utils.append('null' + (args.length ? ', ' : ''), state);
    }
    while (args.length) {
      var arg = args.shift();
      utils.move(arg.range[0], state);
      traverse(arg, path, state);
      if (args.length) {
        utils.catchup(args[0].range[0], state);
      } else {
        utils.catchup(arg.range[1], state);
      }
    }
    utils.append('].concat(', state);
    process(traverse, spread.argument, path, state);
    utils.append(')', state);
  } else {
    process(traverse, spread.argument, path, state);
  }
  utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);

  utils.move(node.range[1], state);
  return false;
}

visitCallSpread.test = function(node, path, state) {
  return (
    (
      node.type === Syntax.CallExpression ||
      node.type === Syntax.NewExpression
    ) &&
    node.arguments.length > 0 &&
    node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
  );
};

exports.visitorList = [
  visitCallSpread,
];
<commit_msg>Remove trailing array comma in es6-call-spread-visitors.js<commit_after>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
/*global exports:true*/

/**
 * Implements ES6 call spread.
 *
 * instance.method(a, b, c, ...d)
 *
 * instance.method.apply(instance, [a, b, c].concat(d))
 *
 */

var Syntax = require('esprima-fb').Syntax;
var utils = require('../src/utils');

function process(traverse, node, path, state) {
  utils.move(node.range[0], state);
  traverse(node, path, state);
  utils.catchup(node.range[1], state);
}

function visitCallSpread(traverse, node, path, state) {
  utils.catchup(node.range[0], state);

  if (node.type === Syntax.NewExpression) {
    // Input  = new Set(1, 2, ...list)
    // Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
    utils.append('new (Function.prototype.bind.apply(', state);
    process(traverse, node.callee, path, state);
  } else if (node.callee.type === Syntax.MemberExpression) {
    // Input  = get().fn(1, 2, ...more)
    // Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
    var tempVar = utils.injectTempVar(state);
    utils.append('(' + tempVar + ' = ', state);
    process(traverse, node.callee.object, path, state);
    utils.append(')', state);
    if (node.callee.property.type === Syntax.Identifier) {
      utils.append('.', state);
      process(traverse, node.callee.property, path, state);
    } else {
      utils.append('[', state);
      process(traverse, node.callee.property, path, state);
      utils.append(']', state);
    }
    utils.append('.apply(' + tempVar, state);
  } else {
    // Input  = max(1, 2, ...list)
    // Output = max.apply(undefined, [1, 2].concat(list))
    var needsToBeWrappedInParenthesis =
      node.callee.type === Syntax.FunctionDeclaration ||
      node.callee.type === Syntax.FunctionExpression;
    if (needsToBeWrappedInParenthesis) {
      utils.append('(', state);
    }
    process(traverse, node.callee, path, state);
    if (needsToBeWrappedInParenthesis) {
      utils.append(')', state);
    }
    utils.append('.apply(undefined', state);
  }
  utils.append(', ', state);

  var args = node.arguments.slice();
  var spread = args.pop();
  if (args.length || node.type === Syntax.NewExpression) {
    utils.append('[', state);
    if (node.type === Syntax.NewExpression) {
      utils.append('null' + (args.length ? ', ' : ''), state);
    }
    while (args.length) {
      var arg = args.shift();
      utils.move(arg.range[0], state);
      traverse(arg, path, state);
      if (args.length) {
        utils.catchup(args[0].range[0], state);
      } else {
        utils.catchup(arg.range[1], state);
      }
    }
    utils.append('].concat(', state);
    process(traverse, spread.argument, path, state);
    utils.append(')', state);
  } else {
    process(traverse, spread.argument, path, state);
  }
  utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);

  utils.move(node.range[1], state);
  return false;
}

visitCallSpread.test = function(node, path, state) {
  return (
    (
      node.type === Syntax.CallExpression ||
      node.type === Syntax.NewExpression
    ) &&
    node.arguments.length > 0 &&
    node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
  );
};

exports.visitorList = [
  visitCallSpread
];
<|endoftext|>


<commit_before>/*global describe, expect, it, testPromise*/

'use strict';

var Promise = testPromise;
var Knex   = require('../../../knex');
var _ = require('lodash');

module.exports = function(knex) {

  describe('Transactions', function() {

    it('can run with asCallback', function(ok) {
      knex.transaction(function(t) {
        t.commit();
      })
      .asCallback(ok)
    });

    it('should be able to commit transactions', function() {

      var id = null;
      return knex.transaction(function(t) {
        knex('accounts')
          .transacting(t)
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User',
            email:'transaction-test1@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          }).then(function(resp) {
            return knex('test_table_two').transacting(t).insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            });
          }).then(function() {
            t.commit('Hello world');
          });

      }).then(function(commitMessage) {
        expect(commitMessage).to.equal('Hello world');
        return knex('accounts').where('id', id).select('first_name');
      }).then(function(resp) {
        expect(resp).to.have.length(1);
      });
    });

    it('should be able to rollback transactions', function() {
      var id = null;
      var err = new Error('error message');
      return knex.transaction(function(t) {
        knex('accounts')
          .transacting(t)
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User2',
            email:'transaction-test2@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          }).then(function(resp) {
            return knex('test_table_two').transacting(t).insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            });
          }).then(function() {
            t.rollback(err);
          });
      }).catch(function(msg) {
        expect(msg).to.equal(err);
        return knex('accounts').where('id', id).select('first_name');
      }).then(function(resp) {
        expect(resp.length).to.equal(0);
      });
    });

    it('should be able to commit transactions with a resolved trx query', function() {

      var id = null;
      return knex.transaction(function(trx) {
        return trx('accounts')
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User',
            email:'transaction-test3@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          }).then(function(resp) {
            return trx('test_table_two').insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            });
          }).then(function() {
            return 'Hello World';
          });
      }).then(function(commitMessage) {
        expect(commitMessage).to.equal('Hello World');
        return knex('accounts').where('id', id).select('first_name');
      }).then(function(resp) {
        expect(resp).to.have.length(1);
      });
    });

    it('should be able to rollback transactions with rejected trx query', function() {
      var id = null;
      var err = new Error('error message');
      var __knexUid, count = 0;
      return knex.transaction(function(trx) {
        return trx('accounts')
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User2',
            email:'transaction-test4@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          })
          .then(function(resp) {
            return trx.insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            }).into('test_table_two');
          })
          .then(function() {
            throw err;
          });
      })
      .on('query', function(obj) {
        count++;
        if (!__knexUid) __knexUid = obj.__knexUid;
        expect(__knexUid).to.equal(obj.__knexUid);
      })
      .catch(function(msg) {
        if (knex.client.dialect === 'oracle' || knex.client.dialect === 'mssql') {
          // oracle start transaction /rollback are no queries
          expect(count).to.equal(2);
        } else {
          expect(count).to.equal(4);
        }
        expect(msg).to.equal(err);
        return knex('accounts').where('id', id).select('first_name');
      })
      .then(function(resp) {
        expect(resp).to.eql([]);
      });
    });

    it('should be able to run schema methods', function() {
      var __knexUid, count = 0;
      var err = new Error('error message');
      if (knex.client.dialect === 'postgresql') {
        return knex.transaction(function(trx) {
          return trx.schema.createTable('test_schema_transactions', function(table) {
              table.increments();
              table.string('name');
              table.timestamps();
            }).then(function() {
              return trx('test_schema_transactions').insert({name: 'bob'});
            }).then(function() {
              return trx('test_schema_transactions').count('*');
            }).then(function(resp) {
              var _count = parseInt(resp[0].count, 10);
              expect(_count).to.equal(1);
              throw err;
            });
        })
        .on('query', function(obj) {
          count++;
          if (!__knexUid) __knexUid = obj.__knexUid;
          expect(__knexUid).to.equal(obj.__knexUid);
        })
        .catch(function(msg) {
          expect(msg).to.equal(err);
          expect(count).to.equal(5);
          return knex('test_schema_migrations').count('*');
        })
        .catch(function(e) {
          expect(e.message).to.equal('select count(*) from \"test_schema_migrations\" - relation "test_schema_migrations" does not exist');
        });
      } else {
        var id = null;
        return knex.transaction(function(trx) {
          return trx('accounts')
            .returning('id')
            .insert({
              first_name: 'Transacting',
              last_name: 'User3',
              email:'transaction-test5@example.com',
              logins: 1,
              about: 'Lorem ipsum Dolore labore incididunt enim.',
              created_at: new Date(),
              updated_at: new Date()
            }).then(function(resp) {
              return trx('test_table_two').insert({
                account_id: (id = resp[0]),
                details: '',
                status: 1
              });
            }).then(function() {
              return trx.schema.createTable('test_schema_transactions', function(table) {
                table.increments();
                table.string('name');
                table.timestamps();
              });
            });
        })
        .on('query', function(obj) {
          count++;
          if (!__knexUid) __knexUid = obj.__knexUid;
          expect(__knexUid).to.equal(obj.__knexUid);
        }).then(function() {
          if (knex.client.dialect === 'mssql') {
            expect(count).to.equal(3);
          } else {
            expect(count).to.equal(5);
          }
          return knex('accounts').where('id', id).select('first_name');
        }).then(function(resp) {
          expect(resp).to.have.length(1);
        }).finally(function() {
          return knex.schema.dropTableIfExists('test_schema_transactions');
        });
      }
    });

    it('should resolve with the correct value, #298', function() {
      return knex.transaction(function(trx) {
        trx.debugging = true;
        return Promise.resolve(null)
      }).then(function(result) {
        expect(result).to.equal(null)
      });
    });

    it('should allow for nested transactions', function() {

      return knex.transaction(function(trx) {
        return trx.select('*').from('accounts').then(function() {
          return trx.transaction(function() {
            return trx.select('*').from('accounts')
          })
        })
      })
    })

    it('#855 - Query Event should trigger on Transaction Client AND main Client', function(done) {
      var queryEventTriggered = false;

      knex.once('query', function(queryData) {
        queryEventTriggered = true;
        return queryData;
      });

      function expectQueryEventToHaveBeenTriggered() {
        expect(queryEventTriggered).to.equal(true);
        done();
      }

      knex.transaction(function(trx) {
        trx.select('*').from('accounts').then(trx.commit).catch(trx.rollback);
      })
          .then(expectQueryEventToHaveBeenTriggered)
          .catch(expectQueryEventToHaveBeenTriggered);

    });

    it('#1040, #1171 - When pool is filled with transaction connections, Non-transaction queries should not hang the application, but instead throw a timeout error', function(done) {
      this.timeout(15000);
      //To make this test easier, I'm changing the pool settings to max 1.
      var knexConfig = _.clone(knex.client.config);
      knexConfig.pool.min = 0;
      knexConfig.pool.max = 1;
      knexConfig.acquireConnectionTimeout = 10000;

      var knexDb = new Knex(knexConfig);

      //Create a transaction that will occupy the only available connection, and avoid trx.commit.
     knexDb.transaction(function(trx) {
        trx.raw('SELECT version()').then(function() {

          //No connection is available, so try issuing a query without transaction.
          //Since there is no available connection, it should throw a timeout error based on knex pool config.
          knexDb.raw('select * FROM accounts WHERE username = ?', ['Test'])
              .then(function(res) {
                expect(res).to.not.exist();
              })
              .catch(function(error) {
                expect(error.bindings).to.be.an('array');
                expect(error.bindings[0]).to.equal('Test');
                expect(error.sql).to.equal('select * FROM accounts WHERE username = ?');
                expect(error.message).to.equal('Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?');
                trx.commit();
              });
        }).catch(trx.rollback);
      })
      .then(function() {
           done();
      })
      .catch(done);
    });

  });

};
<commit_msg>select version() => select 1 = 1 for test<commit_after>/*global describe, expect, it, testPromise*/

'use strict';

var Promise = testPromise;
var Knex   = require('../../../knex');
var _ = require('lodash');

module.exports = function(knex) {

  describe('Transactions', function() {

    it('can run with asCallback', function(ok) {
      knex.transaction(function(t) {
        t.commit();
      })
      .asCallback(ok)
    });

    it('should be able to commit transactions', function() {

      var id = null;
      return knex.transaction(function(t) {
        knex('accounts')
          .transacting(t)
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User',
            email:'transaction-test1@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          }).then(function(resp) {
            return knex('test_table_two').transacting(t).insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            });
          }).then(function() {
            t.commit('Hello world');
          });

      }).then(function(commitMessage) {
        expect(commitMessage).to.equal('Hello world');
        return knex('accounts').where('id', id).select('first_name');
      }).then(function(resp) {
        expect(resp).to.have.length(1);
      });
    });

    it('should be able to rollback transactions', function() {
      var id = null;
      var err = new Error('error message');
      return knex.transaction(function(t) {
        knex('accounts')
          .transacting(t)
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User2',
            email:'transaction-test2@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          }).then(function(resp) {
            return knex('test_table_two').transacting(t).insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            });
          }).then(function() {
            t.rollback(err);
          });
      }).catch(function(msg) {
        expect(msg).to.equal(err);
        return knex('accounts').where('id', id).select('first_name');
      }).then(function(resp) {
        expect(resp.length).to.equal(0);
      });
    });

    it('should be able to commit transactions with a resolved trx query', function() {

      var id = null;
      return knex.transaction(function(trx) {
        return trx('accounts')
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User',
            email:'transaction-test3@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          }).then(function(resp) {
            return trx('test_table_two').insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            });
          }).then(function() {
            return 'Hello World';
          });
      }).then(function(commitMessage) {
        expect(commitMessage).to.equal('Hello World');
        return knex('accounts').where('id', id).select('first_name');
      }).then(function(resp) {
        expect(resp).to.have.length(1);
      });
    });

    it('should be able to rollback transactions with rejected trx query', function() {
      var id = null;
      var err = new Error('error message');
      var __knexUid, count = 0;
      return knex.transaction(function(trx) {
        return trx('accounts')
          .returning('id')
          .insert({
            first_name: 'Transacting',
            last_name: 'User2',
            email:'transaction-test4@example.com',
            logins: 1,
            about: 'Lorem ipsum Dolore labore incididunt enim.',
            created_at: new Date(),
            updated_at: new Date()
          })
          .then(function(resp) {
            return trx.insert({
              account_id: (id = resp[0]),
              details: '',
              status: 1
            }).into('test_table_two');
          })
          .then(function() {
            throw err;
          });
      })
      .on('query', function(obj) {
        count++;
        if (!__knexUid) __knexUid = obj.__knexUid;
        expect(__knexUid).to.equal(obj.__knexUid);
      })
      .catch(function(msg) {
        if (knex.client.dialect === 'oracle' || knex.client.dialect === 'mssql') {
          // oracle start transaction /rollback are no queries
          expect(count).to.equal(2);
        } else {
          expect(count).to.equal(4);
        }
        expect(msg).to.equal(err);
        return knex('accounts').where('id', id).select('first_name');
      })
      .then(function(resp) {
        expect(resp).to.eql([]);
      });
    });

    it('should be able to run schema methods', function() {
      var __knexUid, count = 0;
      var err = new Error('error message');
      if (knex.client.dialect === 'postgresql') {
        return knex.transaction(function(trx) {
          return trx.schema.createTable('test_schema_transactions', function(table) {
              table.increments();
              table.string('name');
              table.timestamps();
            }).then(function() {
              return trx('test_schema_transactions').insert({name: 'bob'});
            }).then(function() {
              return trx('test_schema_transactions').count('*');
            }).then(function(resp) {
              var _count = parseInt(resp[0].count, 10);
              expect(_count).to.equal(1);
              throw err;
            });
        })
        .on('query', function(obj) {
          count++;
          if (!__knexUid) __knexUid = obj.__knexUid;
          expect(__knexUid).to.equal(obj.__knexUid);
        })
        .catch(function(msg) {
          expect(msg).to.equal(err);
          expect(count).to.equal(5);
          return knex('test_schema_migrations').count('*');
        })
        .catch(function(e) {
          expect(e.message).to.equal('select count(*) from \"test_schema_migrations\" - relation "test_schema_migrations" does not exist');
        });
      } else {
        var id = null;
        return knex.transaction(function(trx) {
          return trx('accounts')
            .returning('id')
            .insert({
              first_name: 'Transacting',
              last_name: 'User3',
              email:'transaction-test5@example.com',
              logins: 1,
              about: 'Lorem ipsum Dolore labore incididunt enim.',
              created_at: new Date(),
              updated_at: new Date()
            }).then(function(resp) {
              return trx('test_table_two').insert({
                account_id: (id = resp[0]),
                details: '',
                status: 1
              });
            }).then(function() {
              return trx.schema.createTable('test_schema_transactions', function(table) {
                table.increments();
                table.string('name');
                table.timestamps();
              });
            });
        })
        .on('query', function(obj) {
          count++;
          if (!__knexUid) __knexUid = obj.__knexUid;
          expect(__knexUid).to.equal(obj.__knexUid);
        }).then(function() {
          if (knex.client.dialect === 'mssql') {
            expect(count).to.equal(3);
          } else {
            expect(count).to.equal(5);
          }
          return knex('accounts').where('id', id).select('first_name');
        }).then(function(resp) {
          expect(resp).to.have.length(1);
        }).finally(function() {
          return knex.schema.dropTableIfExists('test_schema_transactions');
        });
      }
    });

    it('should resolve with the correct value, #298', function() {
      return knex.transaction(function(trx) {
        trx.debugging = true;
        return Promise.resolve(null)
      }).then(function(result) {
        expect(result).to.equal(null)
      });
    });

    it('should allow for nested transactions', function() {

      return knex.transaction(function(trx) {
        return trx.select('*').from('accounts').then(function() {
          return trx.transaction(function() {
            return trx.select('*').from('accounts')
          })
        })
      })
    })

    it('#855 - Query Event should trigger on Transaction Client AND main Client', function(done) {
      var queryEventTriggered = false;

      knex.once('query', function(queryData) {
        queryEventTriggered = true;
        return queryData;
      });

      function expectQueryEventToHaveBeenTriggered() {
        expect(queryEventTriggered).to.equal(true);
        done();
      }

      knex.transaction(function(trx) {
        trx.select('*').from('accounts').then(trx.commit).catch(trx.rollback);
      })
          .then(expectQueryEventToHaveBeenTriggered)
          .catch(expectQueryEventToHaveBeenTriggered);

    });

    it('#1040, #1171 - When pool is filled with transaction connections, Non-transaction queries should not hang the application, but instead throw a timeout error', function(done) {
      this.timeout(15000);
      //To make this test easier, I'm changing the pool settings to max 1.
      var knexConfig = _.clone(knex.client.config);
      knexConfig.pool.min = 0;
      knexConfig.pool.max = 1;
      knexConfig.acquireConnectionTimeout = 10000;

      var knexDb = new Knex(knexConfig);

      //Create a transaction that will occupy the only available connection, and avoid trx.commit.
     knexDb.transaction(function(trx) {
        trx.raw('SELECT 1 = 1').then(function() {

          //No connection is available, so try issuing a query without transaction.
          //Since there is no available connection, it should throw a timeout error based on knex pool config.
          knexDb.raw('select * FROM accounts WHERE username = ?', ['Test'])
              .then(function(res) {
                expect(res).to.not.exist();
              })
              .catch(function(error) {
                expect(error.bindings).to.be.an('array');
                expect(error.bindings[0]).to.equal('Test');
                expect(error.sql).to.equal('select * FROM accounts WHERE username = ?');
                expect(error.message).to.equal('Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?');
                trx.commit();
              });
        }).catch(trx.rollback);
      })
      .then(function() {
           done();
      })
      .catch(done);
    });

  });

};
<|endoftext|>


<commit_before>angular.module('npact')
  .service('GraphingCalculator', function GraphingCalculator(Utils, npactConstants) {
    'use strict';
    var self = this;

    this.partition = function(opts) {
      var offset = Math.round(opts.offset || 0),
          startBase = opts.startBase + offset,
          endBase = opts.endBase,
          basesPerGraph = opts.basesPerGraph;
      if(basesPerGraph)
        return _.range(startBase, endBase, basesPerGraph);
      else
        return [];
    };

    self.stops = function(a, b, length){
      length = length || b - a;
      var
          // get even stops; look for one lower order of magnitude
          // than our length
          interval = Utils.orderOfMagnitude(length, -1),
          // want to get ticks aligned on `interval`. a and b might
          // have weird offsets
          start = Math.floor(a/interval)*interval,
          end = Math.floor(b/interval)*interval;

      return {
        interval: interval,
        stops: _.range(
          Math.max(0, start),
          // want to be start/end INCLUSIVE so pad the end
          end + interval,
          interval)
      };
    };

    /**
     * determine new offset and basesPerGraph for a zoom, retaining
     * relative position
     *
     * so if you zoom in on gene 2000, after the zoom the mouse cursor
     * is still on 2000, but the rest of the graph has shifted. Treats
     * the genes as a number line.
     *
     * @param {Number} startBase - low end of the graph that we're zooming on
     * (gene space)
     * @param {Number} zoomOnPct - where we're zooming to, as a percent of
     * the graph
     * @param {Number} basesPerGraph - how many bases per graph,
     * indicates current zoom level
     * @param {Number} offset - the current offset for the graphs
     * (gene space)
     * @param {Boolean} zoomingOut - true for zooming out, false for
     * zooming in
     * @returns {Object} new offset and basesPerGraph such that we remain focused on the selected gene
     */
    self.zoom = function(opts){
      //
      // O = offset from L such that Z is positionally at the same
      // point on the screen
      // LH = distance between L and H, a measure of how zoomed in we are
      //
      // all units are in gene space

      var zoomToBase = opts.startBase + Math.floor(opts.zoomOnPct*opts.basesPerGraph),
          row = Math.floor((opts.startBase - opts.offset)/opts.basesPerGraph),
          zoomFactor = opts.zoomingOut ? 2 : 0.5,
          newbasesPerGraph = opts.basesPerGraph * zoomFactor,
          newstartBase = zoomToBase - Math.floor(newbasesPerGraph * opts.zoomOnPct),
          newoffset = newstartBase - (row*newbasesPerGraph);

      return {offset: newoffset, basesPerGraph: newbasesPerGraph};
    };

    self.trackSizeCalc = function(activeTracks, trackPadding) {
      trackPadding = trackPadding || 0;
      var offset = 0;
      _.forEach(activeTracks, function(track) {
        track.y = offset;
        offset += track.style.height + trackPadding;
      });
      return offset;
    };

    /**
     * calculate measurements about the chart
     */
    self.chart = function(opts) {
      var style = npactConstants.graphStyle;
      var pstyle = style.profile;
      var totalTrackHeight = self.trackSizeCalc(opts.tracks, style.paddingUnit);
      var graphTop = totalTrackHeight || style.paddingUnit,
          xAxisTop = graphTop + pstyle.height,
          xAxisHeight = pstyle.axis.text.fontSize + pstyle.tickLength,
          totalHeight = xAxisTop + xAxisHeight;

      //Stop a point left of our full width so no cutoff on the right side
      var graphWidth = opts.width - style.leftPadding - 3;
      return {
        height: totalHeight,
        graph: {
          x: style.leftPadding,
          y: graphTop,
          h: style.profile.height,
          w: graphWidth
        },
        xaxis: {
          height: xAxisHeight,
          y: xAxisTop,
          length: opts.basesPerGraph,
          scaleX: graphWidth / opts.basesPerGraph

        },
        yaxis: {
          height: style.profile.height,
          y: graphTop,
          x: style.leftPadding
        }
      };
    };

    /**
     * find a position that will align the two rectangles on their center
     *
     * @param {Object} rect - the rectangle to align to {width,height}
     * @param {Object} toAlign - the rectangle you want to move {width,height}
     * @returns {Object} x,y coordinates to shift `toAlign` by, from the top/left
     */
    self.alignRectangles = function(rect, toAlign){
      // get the top left coordinate of the `toAlign` rect
      return {x: rect.x + (rect.width/2) - (toAlign.width/2),
              y: rect.y + (rect.height/2) - (toAlign.height/2)};
    };
  })
;
<commit_msg>Ensure basesPerGraph is an int when rezooming<commit_after>angular.module('npact')
  .service('GraphingCalculator', function GraphingCalculator(Utils, npactConstants) {
    'use strict';
    var self = this;

    this.partition = function(opts) {
      var offset = Math.round(opts.offset || 0),
          startBase = opts.startBase + offset,
          endBase = opts.endBase,
          basesPerGraph = opts.basesPerGraph;
      if(basesPerGraph)
        return _.range(startBase, endBase, basesPerGraph);
      else
        return [];
    };

    self.stops = function(a, b, length){
      length = length || b - a;
      var
          // get even stops; look for one lower order of magnitude
          // than our length
          interval = Utils.orderOfMagnitude(length, -1),
          // want to get ticks aligned on `interval`. a and b might
          // have weird offsets
          start = Math.floor(a/interval)*interval,
          end = Math.floor(b/interval)*interval;

      return {
        interval: interval,
        stops: _.range(
          Math.max(0, start),
          // want to be start/end INCLUSIVE so pad the end
          end + interval,
          interval)
      };
    };

    /**
     * determine new offset and basesPerGraph for a zoom, retaining
     * relative position
     *
     * so if you zoom in on gene 2000, after the zoom the mouse cursor
     * is still on 2000, but the rest of the graph has shifted. Treats
     * the genes as a number line.
     *
     * @param {Number} startBase - low end of the graph that we're zooming on
     * (gene space)
     * @param {Number} zoomOnPct - where we're zooming to, as a percent of
     * the graph
     * @param {Number} basesPerGraph - how many bases per graph,
     * indicates current zoom level
     * @param {Number} offset - the current offset for the graphs
     * (gene space)
     * @param {Boolean} zoomingOut - true for zooming out, false for
     * zooming in
     * @returns {Object} new offset and basesPerGraph such that we remain focused on the selected gene
     */
    self.zoom = function(opts){
      //
      // O = offset from L such that Z is positionally at the same
      // point on the screen
      // LH = distance between L and H, a measure of how zoomed in we are
      //
      // all units are in gene space

      var zoomToBase = opts.startBase + Math.floor(opts.zoomOnPct*opts.basesPerGraph),
          row = Math.floor((opts.startBase - opts.offset)/opts.basesPerGraph),
          zoomFactor = opts.zoomingOut ? 2 : 0.5,
          newbasesPerGraph = Math.floor(opts.basesPerGraph * zoomFactor),
          newstartBase = zoomToBase - Math.floor(newbasesPerGraph * opts.zoomOnPct),
          newoffset = newstartBase - (row * newbasesPerGraph);

      return {offset: newoffset, basesPerGraph: newbasesPerGraph};
    };

    self.trackSizeCalc = function(activeTracks, trackPadding) {
      trackPadding = trackPadding || 0;
      var offset = 0;
      _.forEach(activeTracks, function(track) {
        track.y = offset;
        offset += track.style.height + trackPadding;
      });
      return offset;
    };

    /**
     * calculate measurements about the chart
     */
    self.chart = function(opts) {
      var style = npactConstants.graphStyle;
      var pstyle = style.profile;
      var totalTrackHeight = self.trackSizeCalc(opts.tracks, style.paddingUnit);
      var graphTop = totalTrackHeight || style.paddingUnit,
          xAxisTop = graphTop + pstyle.height,
          xAxisHeight = pstyle.axis.text.fontSize + pstyle.tickLength,
          totalHeight = xAxisTop + xAxisHeight;

      //Stop a point left of our full width so no cutoff on the right side
      var graphWidth = opts.width - style.leftPadding - 3;
      return {
        height: totalHeight,
        graph: {
          x: style.leftPadding,
          y: graphTop,
          h: style.profile.height,
          w: graphWidth
        },
        xaxis: {
          height: xAxisHeight,
          y: xAxisTop,
          length: opts.basesPerGraph,
          scaleX: graphWidth / opts.basesPerGraph

        },
        yaxis: {
          height: style.profile.height,
          y: graphTop,
          x: style.leftPadding
        }
      };
    };

    /**
     * find a position that will align the two rectangles on their center
     *
     * @param {Object} rect - the rectangle to align to {width,height}
     * @param {Object} toAlign - the rectangle you want to move {width,height}
     * @returns {Object} x,y coordinates to shift `toAlign` by, from the top/left
     */
    self.alignRectangles = function(rect, toAlign){
      // get the top left coordinate of the `toAlign` rect
      return {x: rect.x + (rect.width/2) - (toAlign.width/2),
              y: rect.y + (rect.height/2) - (toAlign.height/2)};
    };
  })
;
<|endoftext|>