<commit_before>window.m = ( function( mithril ){
  // Registry of controllers and corresponding root nodes
  var roots     = new Map()
  // A record of recent view outputs for every root-level component
  var history   = new WeakMap()
  // Whether the current draw is being used to revert to its previous state
  var reverting = false

  // Register views to bind their roots to the above
  // so we can provide exit animations with the right DOM reference
  function register( view ){
    return function registeredView( ctrl ){
      var output = view.apply( this, arguments )

      // In case of a registered exit animation...
      if( ctrl.exit ){
        var node = output

        // If the view output is an array, deal with the first element
        while( node.length )
          node = node[ 0 ]

        var config = node.attrs.config

        // Map the root / first child element to the component instance
        node.attrs.config = function superConfig( el ){
          roots.set( ctrl, el )

          if( config )
            return config.apply( this, arguments )
        }
      }

      return output
    }
  }

  // Root components (those mounted or routed) are the source of redraws.
  // Before they draw, there is no stateful virtual DOM.
  // Therefore their view execution is the source of all truth in what is currently rendered.
  function root( component ){
    var view = component.view

    component.view = rootView

    return component

    function rootView( ctrl ){
      // If we are in the middle of a reversion, we just want to patch
      // Mithril's internal virtual DOM HEAD to what it was before the
      // last output
      if( reverting )
        return history.get( ctrl )

      // All previously registered exitable components are saved here
      var previous = array( roots )

      // Then we reset
      roots.clear()

      // Execute the view, registering all exitables
      var output   = register( view ).apply( this, arguments )

        // Record the output, we will need to return to this state if the next draw has exits
      history.set( ctrl, output )

      // Now, set up a list of confirmed exits
      var exits    = []

      // For every previous exitable instance...
      for( var i = 0; i < previous.length; i++ )
        // ...if it hasn't re-registered...
        if( !roots.has( previous[ i ][ 0 ] ) )
          // It's gone! Call the exit method and keep its output.
          exits.push( previous[ i ][ 0 ].exit( previous[ i ][ 1 ] ) )

      // If we have exits...
      if( exits.length ){
        // Noop this draw
        output = { subtree : 'retain' }

        // ...and all subsequent ones...
        mithril.startComputation()

        // ...until all exits have resolved
        mithril.sync( exits ).then( function(){
          // We now need to revert Mithril's internal virtual DOM head so that
          // it will correctly patch the live DOM to match the state in which
          // components are removed: it currently believes that already happend
          // Because it ran the diff before we told it to retain the subtree at
          // the last minute
          reverting = true

          // Next draw should not patch, only diff
          m.redraw.strategy( 'none' )

          // Force a synchronous draw despite being frozen
          m.redraw( true )

          // Now it's as if we were never here to begin with
          reverting = false

          // Resume business as usual
          m.endComputation()
        } )
      }

      return output
    }
  }

  // Helper: transform each value in an object. Even in ES7, this is painfully contrived.
  function reduce( object, transformer ){
    var output = {}

    for( var key in object )
      if( Object.prototype.hasOwnProperty.call( object, key ) )
        output[ key ] = transformer( object[ key ] )

    return output
  }

  // Helper: array from map
  function array( map ){
    var array   = []
    var entries = map.entries()

    while( true ){
      var entry = entries.next()

      if( entry.done )
        break

      array.push( entry.value )
    }

    return array
  }

  // Core m function needs to sniff out components...
  function m(){
    var output = mithril.apply( this, arguments )

    for( var i = 0; i < output.children.length; i++ )
      if( output.children[ i ].view )
        // ...and get their views to register controllers and root nodes
        output.children[ i ].view = register( output.children[ i ].view )

    return output
  }

  // Then we have all the m methods
  for( var key in mithril )
    if( Object.prototype.hasOwnProperty.call( mithril, key ) )
      m[ key ] = mithril[ key ]

  // m.component invocations produce virtual DOM.
  // We need to intercede to get at the view.
  m.component = function( component ){
    component.view = register( component.view )

    // I don't know how I coped without ES6 spread operator....
    return mithril.component.apply( mithril, [ component ].concat( [].slice.call( arguments, 1 ) ) )
  }

  // Mount and Route need to register root components for snapshot logic
  m.mount = function( el, component ){
    return mithril.mount( el, root( component ) )
  }

  m.route = function( el, path, map ){
    if( map ){
      return mithril.route( el, path, reduce( map, root ) )
    }
    else {
      return mithril.route.apply( this, arguments )
    }
  }

  // Export a patched Mithril API
  return m
}( m ) );
<commit_msg>Mithril 0.2.3 m() API compat fix<commit_after>window.m = ( function( mithril ){
  // Registry of controllers and corresponding root nodes
  var roots     = new Map()
  // A record of recent view outputs for every root-level component
  var history   = new WeakMap()
  // Whether the current draw is being used to revert to its previous state
  var reverting = false

  // Register views to bind their roots to the above
  // so we can provide exit animations with the right DOM reference
  function register( view ){
    return function registeredView( ctrl ){
      var output = view.apply( this, arguments )

      // In case of a registered exit animation...
      if( ctrl.exit ){
        var node = output

        // If the view output is an array, deal with the first element
        while( node.length )
          node = node[ 0 ]

        var config = node.attrs.config

        // Map the root / first child element to the component instance
        node.attrs.config = function superConfig( el ){
          roots.set( ctrl, el )

          if( config )
            return config.apply( this, arguments )
        }
      }

      return output
    }
  }

  // Root components (those mounted or routed) are the source of redraws.
  // Before they draw, there is no stateful virtual DOM.
  // Therefore their view execution is the source of all truth in what is currently rendered.
  function root( component ){
    var view = component.view

    component.view = rootView

    return component

    function rootView( ctrl ){
      // If we are in the middle of a reversion, we just want to patch
      // Mithril's internal virtual DOM HEAD to what it was before the
      // last output
      if( reverting )
        return history.get( ctrl )

      // All previously registered exitable components are saved here
      var previous = array( roots )

      // Then we reset
      roots.clear()

      // Execute the view, registering all exitables
      var output   = register( view ).apply( this, arguments )

        // Record the output, we will need to return to this state if the next draw has exits
      history.set( ctrl, output )

      // Now, set up a list of confirmed exits
      var exits    = []

      // For every previous exitable instance...
      for( var i = 0; i < previous.length; i++ )
        // ...if it hasn't re-registered...
        if( !roots.has( previous[ i ][ 0 ] ) )
          // It's gone! Call the exit method and keep its output.
          exits.push( previous[ i ][ 0 ].exit( previous[ i ][ 1 ] ) )

      // If we have exits...
      if( exits.length ){
        // Noop this draw
        output = { subtree : 'retain' }

        // ...and all subsequent ones...
        mithril.startComputation()

        // ...until all exits have resolved
        mithril.sync( exits ).then( function(){
          // We now need to revert Mithril's internal virtual DOM head so that
          // it will correctly patch the live DOM to match the state in which
          // components are removed: it currently believes that already happend
          // Because it ran the diff before we told it to retain the subtree at
          // the last minute
          reverting = true

          // Next draw should not patch, only diff
          m.redraw.strategy( 'none' )

          // Force a synchronous draw despite being frozen
          m.redraw( true )

          // Now it's as if we were never here to begin with
          reverting = false

          // Resume business as usual
          m.endComputation()
        } )
      }

      return output
    }
  }

  // Helper: transform each value in an object. Even in ES7, this is painfully contrived.
  function reduce( object, transformer ){
    var output = {}

    for( var key in object )
      if( Object.prototype.hasOwnProperty.call( object, key ) )
        output[ key ] = transformer( object[ key ] )

    return output
  }

  // Helper: array from map
  function array( map ){
    var array   = []
    var entries = map.entries()

    while( true ){
      var entry = entries.next()

      if( entry.done )
        break

      array.push( entry.value )
    }

    return array
  }

  // Core m function needs to sniff out components...
  function m( first ){
    if( 'view' in first )
      return m.component.apply( this, arguments )

    var output = mithril.apply( this, arguments )

    for( var i = 0; i < output.children.length; i++ )
      if( output.children[ i ].view )
        // ...and get their views to register controllers and root nodes
        output.children[ i ].view = register( output.children[ i ].view )

    return output
  }

  // Then we have all the m methods
  for( var key in mithril )
    if( Object.prototype.hasOwnProperty.call( mithril, key ) )
      m[ key ] = mithril[ key ]

  // m.component invocations produce virtual DOM.
  // We need to intercede to get at the view.
  m.component = function( component ){
    component.view = register( component.view )

    // I don't know how I coped without ES6 spread operator....
    return mithril.component.apply( mithril, [ component ].concat( [].slice.call( arguments, 1 ) ) )
  }

  // Mount and Route need to register root components for snapshot logic
  m.mount = function( el, component ){
    return mithril.mount( el, root( component ) )
  }

  m.route = function( el, path, map ){
    if( map ){
      return mithril.route( el, path, reduce( map, root ) )
    }
    else {
      return mithril.route.apply( this, arguments )
    }
  }

  // Export a patched Mithril API
  return m
}( m ) );
<|endoftext|>


<commit_before>//
// The MIT License (MIT)
//
// Copyright (c) 2013 Tristan Cavelier <t.cavelier@free.fr>
//
// 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.
//

/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global */

// keywords: js, javascript, promise, commonjs

function Promise() {
  this._onReject = [];
  this._onResolve = [];
  this._onProgress = [];
  this._state = "";
  this._answer = undefined;
}

Promise.createSolver = function (promise) {
  return {
    "resolve": function (answer) {
      if (promise._state !== "resolved" && promise._state !== "rejected") {
        promise._state = "resolved";
        promise._answer = answer;
        promise._onResolve.forEach(function (callback) {
          setTimeout(function () {
            callback(answer);
          });
        });
        promise._onResolve = [];
        promise._onReject = [];
        promise._onProgress = [];
      }
    },
    "reject": function (answer) {
      if (promise._state !== "resolved" && promise._state !== "rejected") {
        promise._state = "rejected";
        promise._answer = answer;
        promise._onReject.forEach(function (callback) {
          setTimeout(function () {
            callback(answer);
          });
        });
        promise._onResolve = [];
        promise._onReject = [];
        promise._onProgress = [];
      }
    },
    "notify": function (answer) {
      promise._onProgress.forEach(function (callback) {
        callback(answer);
      });
    }
  };
};

Promise.prototype.solver = function () {
  var that = this;
  switch (this._state) {
  case "running":
    throw new Error("Promise().execute(): Already running");
  case "resolved":
    throw new Error("Promise().execute(): Resolved");
  case "rejected":
    throw new Error("Promise().execute(): Rejected");
  default:
    break;
  }
  this._state = "running";
  return Promise.createSolver(this);
};

Promise.prototype.execute = function (callback) {
  var that = this;
  switch (this._state) {
  case "running":
    throw new Error("Promise().execute(): Already running");
  case "resolved":
    throw new Error("Promise().execute(): Resolved");
  case "rejected":
    throw new Error("Promise().execute(): Rejected");
  default:
    this._state = "running";
    setTimeout(function () {
      callback(Promise.createSolver(this));
    });
    break;
  }
  return this;
};

Promise.prototype.then = function (onSuccess, onError, onProgress) {
  var next = new Promise(), that = this;
  switch (this._state) {
  case "resolved":
    if (typeof onSuccess === 'function') {
      next.execute(function (resolver) {
        try {
          resolver.resolve(onSuccess(that._answer));
        } catch (e) {
          resolver.reject(e);
        }
      });
    }
    break;
  case "rejected":
    if (typeof onError === 'function') {
      next.execute(function (resolver) {
        try {
          resolver.resolve(onError(that._answer));
        } catch (e) {
          resolver.reject(e);
        }
      });
    }
    break;
  default:
    if (typeof onSuccess === 'function') {
      this._onResolve.push(function (answer) {
        next.execute(function (resolver) {
          try {
            resolver.resolve(onSuccess(answer));
          } catch (e) {
            resolver.reject(e);
          }
        });
      });
    }
    if (typeof onError === 'function') {
      this._onReject.push(function (answer) {
        next.execute(function (resolver) {
          try {
            resolver.resolve(onError(answer));
          } catch (e) {
            resolver.reject(e);
          }
        });
      });
    }
    if (typeof onProgress === 'function') {
      this._onProgress.push(onProgress);
    }
    break;
  }
  return next;
};

Promise.prototype.done = function (callback) {
  var that = this;
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "resolved":
    setTimeout(function () {
      callback(that._answer);
    });
    break;
  default:
    this._onResolve.push(callback);
    break;
  }
  return this;
};

Promise.prototype.fail = function (callback) {
  var that = this;
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "rejected":
    setTimeout(function () {
      callback(that._answer);
    });
    break;
  default:
    this._onReject.push(callback);
    break;
  }
  return this;
};

Promise.prototype.progress = function (callback) {
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "rejected":
  case "resolved":
    break;
  default:
    this._onProgress.push(callback);
    break;
  }
  return this;
};

Promise.prototype.always = function (callback) {
  var that = this;
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "resolved":
  case "rejected":
    setTimeout(function () {
      callback(that._answer);
    });
    break;
  default:
    ['_onReject', '_onResolve'].forEach(function (event) {
      that[event].push(callback);
    });
    break;
  }
  return this;
};

function Deferred() {
  this._promise = new Promise();
  this._solver = this._promise.solver();
}

Deferred.prototype.resolve = function () {
  this._solver.resolve.apply(this._solver, arguments);
};

Deferred.prototype.reject = function () {
  this._solver.reject.apply(this._solver, arguments);
};

Deferred.prototype.promise = function () {
  return this._promise;
};

// /////////////////////////////////////////////////////////////////////////////
// // Tests

// var one = new Promise().execute(function (r) {
//   r.notify(1);
//   r.notify(2);
//   r.resolve('a');
//   r.notify(3);
// }).progress(function (answer) {
//   console.log('progress', answer);
// });

// var two = one.then(function (answer) {
//   console.log(1, answer);
//   return answer + 'b';
// });

// two.then(function (answer) {
//   console.log(2, answer);
//   return answer + 'c';
// }).done(function (answer) {
//   console.log('done', answer);
// });

// setTimeout(function () {
//   one.then(function (answer) {
//     console.log(3, answer);
//   });
//   one.done(function (answer) {
//     console.log(4, answer);
//   });
// }, 100);

// /////////////////////////////////////////////////////////////////////////////
// // Tests Deferred

// var p = (function () {
//   var d = new Deferred();
//   d.resolve('a');
//   return d.promise();
// }());

// p.then(function (a) {
//   console.log(a);
// });
<commit_msg>Promise.js Deferred notify added<commit_after>//
// The MIT License (MIT)
//
// Copyright (c) 2013 Tristan Cavelier <t.cavelier@free.fr>
//
// 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.
//

/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global */

// keywords: js, javascript, promise, commonjs

function Promise() {
  this._onReject = [];
  this._onResolve = [];
  this._onProgress = [];
  this._state = "";
  this._answer = undefined;
}

Promise.createSolver = function (promise) {
  return {
    "resolve": function (answer) {
      if (promise._state !== "resolved" && promise._state !== "rejected") {
        promise._state = "resolved";
        promise._answer = answer;
        promise._onResolve.forEach(function (callback) {
          setTimeout(function () {
            callback(answer);
          });
        });
        promise._onResolve = [];
        promise._onReject = [];
        promise._onProgress = [];
      }
    },
    "reject": function (answer) {
      if (promise._state !== "resolved" && promise._state !== "rejected") {
        promise._state = "rejected";
        promise._answer = answer;
        promise._onReject.forEach(function (callback) {
          setTimeout(function () {
            callback(answer);
          });
        });
        promise._onResolve = [];
        promise._onReject = [];
        promise._onProgress = [];
      }
    },
    "notify": function (answer) {
      promise._onProgress.forEach(function (callback) {
        callback(answer);
      });
    }
  };
};

Promise.prototype.solver = function () {
  var that = this;
  switch (this._state) {
  case "running":
    throw new Error("Promise().execute(): Already running");
  case "resolved":
    throw new Error("Promise().execute(): Resolved");
  case "rejected":
    throw new Error("Promise().execute(): Rejected");
  default:
    break;
  }
  this._state = "running";
  return Promise.createSolver(this);
};

Promise.prototype.execute = function (callback) {
  var that = this;
  switch (this._state) {
  case "running":
    throw new Error("Promise().execute(): Already running");
  case "resolved":
    throw new Error("Promise().execute(): Resolved");
  case "rejected":
    throw new Error("Promise().execute(): Rejected");
  default:
    this._state = "running";
    setTimeout(function () {
      callback(Promise.createSolver(this));
    });
    break;
  }
  return this;
};

Promise.prototype.then = function (onSuccess, onError, onProgress) {
  var next = new Promise(), that = this;
  switch (this._state) {
  case "resolved":
    if (typeof onSuccess === 'function') {
      next.execute(function (resolver) {
        try {
          resolver.resolve(onSuccess(that._answer));
        } catch (e) {
          resolver.reject(e);
        }
      });
    }
    break;
  case "rejected":
    if (typeof onError === 'function') {
      next.execute(function (resolver) {
        try {
          resolver.resolve(onError(that._answer));
        } catch (e) {
          resolver.reject(e);
        }
      });
    }
    break;
  default:
    if (typeof onSuccess === 'function') {
      this._onResolve.push(function (answer) {
        next.execute(function (resolver) {
          try {
            resolver.resolve(onSuccess(answer));
          } catch (e) {
            resolver.reject(e);
          }
        });
      });
    }
    if (typeof onError === 'function') {
      this._onReject.push(function (answer) {
        next.execute(function (resolver) {
          try {
            resolver.resolve(onError(answer));
          } catch (e) {
            resolver.reject(e);
          }
        });
      });
    }
    if (typeof onProgress === 'function') {
      this._onProgress.push(onProgress);
    }
    break;
  }
  return next;
};

Promise.prototype.done = function (callback) {
  var that = this;
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "resolved":
    setTimeout(function () {
      callback(that._answer);
    });
    break;
  default:
    this._onResolve.push(callback);
    break;
  }
  return this;
};

Promise.prototype.fail = function (callback) {
  var that = this;
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "rejected":
    setTimeout(function () {
      callback(that._answer);
    });
    break;
  default:
    this._onReject.push(callback);
    break;
  }
  return this;
};

Promise.prototype.progress = function (callback) {
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "rejected":
  case "resolved":
    break;
  default:
    this._onProgress.push(callback);
    break;
  }
  return this;
};

Promise.prototype.always = function (callback) {
  var that = this;
  if (typeof callback !== 'function') {
    return this;
  }
  switch (this._state) {
  case "resolved":
  case "rejected":
    setTimeout(function () {
      callback(that._answer);
    });
    break;
  default:
    ['_onReject', '_onResolve'].forEach(function (event) {
      that[event].push(callback);
    });
    break;
  }
  return this;
};

function Deferred() {
  this._promise = new Promise();
  this._solver = this._promise.solver();
}

Deferred.prototype.resolve = function () {
  this._solver.resolve.apply(this._solver, arguments);
};

Deferred.prototype.reject = function () {
  this._solver.reject.apply(this._solver, arguments);
};

Deferred.prototype.notify = function () {
  this._solver.notify.apply(this._solver, arguments);
};

Deferred.prototype.promise = function () {
  return this._promise;
};

// /////////////////////////////////////////////////////////////////////////////
// // Tests

// var one = new Promise().execute(function (r) {
//   r.notify(1);
//   r.notify(2);
//   r.resolve('a');
//   r.notify(3);
// }).progress(function (answer) {
//   console.log('progress', answer);
// });

// var two = one.then(function (answer) {
//   console.log(1, answer);
//   return answer + 'b';
// });

// two.then(function (answer) {
//   console.log(2, answer);
//   return answer + 'c';
// }).done(function (answer) {
//   console.log('done', answer);
// });

// setTimeout(function () {
//   one.then(function (answer) {
//     console.log(3, answer);
//   });
//   one.done(function (answer) {
//     console.log(4, answer);
//   });
// }, 100);

// /////////////////////////////////////////////////////////////////////////////
// // Tests Deferred

// var p = (function () {
//   var d = new Deferred();
//   d.notify(1);
//   setTimeout(function () {
//     d.notify(2);
//     d.resolve('a');
//   });
//   return d.promise();
// }());

// p.progress(function () {
//   console.log('progress', arguments);
// });

// p.then(function () {
//   console.log('then', arguments);
// });
<|endoftext|>


<commit_before>/*!
 * moving.js
 *
 * Copyright © 2016 Jorge M. Peláez | MIT license
 * http://j-pel.github.io/adjustjs
 *
 */

(function(exports) {

  'use strict';

	/* properties */
	var storeChanges = function(changes){return(0)};
	var ongoingTouches = new Array();
	var moving = new Object();
	var touchMoving = false;

	/* client API */

	/*!
	 * init(store)
	 * Starts the handling of the proposed feature
	 * A default id is assigned to elements with no id given.
	 *
	 * @param {store} callback to receive the elements' changes.
	 * @api public
	 */
	var init = exports.init = function(store) {
		storeChanges = store;
		var elementList = document.getElementsByClassName('movable');
		for (var i = 0; i < elementList.length; i++) {
			var ele = elementList[i];
			ele.addEventListener('mousedown', handleMouseDown, false);
			ele.style.cursor = 'move';
			if (!ele.id) {
				ele.id = "nn_m_"+i;
			}
		}
		document.addEventListener('touchstart', handleTouchStart, false);
		document.addEventListener("touchmove", handleTouchMove, true);
		document.addEventListener("touchleave", handleTouchEnd, true);
		document.addEventListener("touchend", handleTouchEnd, true);
		return 0;
	}

	/*!
	 * stop()
	 * Stops the handling of the proposed feature.
	 *
	 * @api public
	 */
	var stop = exports.stop = function() {
		var elementList = document.getElementsByClassName('movable');
		for (var i = 0; i < elementList.length; i++) {
			var ele = elementList[i];
			ele.removeEventListener('mousedown', handleMouseDown, false);
			ele.style.cursor = 'auto';
		}
		document.removeEventListener('touchstart', handleTouchStart, false);
		document.removeEventListener("touchmove", handleTouchMove, true);
		document.removeEventListener("touchleave", handleTouchEnd, true);
		document.removeEventListener("touchend", handleTouchEnd, true);
		return 0;
	}

	/* private helpers */

	function log(msg) {
		var p = document.getElementById('status');
		p.innerHTML = msg + "\n" + p.innerHTML;
	}

	var handleMouseDown = function (event) {
		event = event || window.event;
		moving=this;
		moving.started = true;
		//log("Start moving " + this.innerHTML);
		document.addEventListener("mousemove", handleMouseMove, true);
		document.addEventListener("mouseup", handleMouseUp, true);
		event.preventDefault();
    if (!window.scrollX) {
			moving.mouseX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			moving.mouseY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    } else {
			moving.mouseX = event.clientX + window.scrollX;
			moving.mouseY = event.clientY + window.scrollY;
    }
		moving.startX = moving.offsetLeft;
		moving.startY = moving.offsetTop;
	}

	var handleMouseMove = function (event) {
		if (!moving.started) return;
		event = event || window.event;
		var x, y;
    if (!window.scrollX) {
			x = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			y = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    } else {
			x = event.clientX + window.scrollX;
			y = event.clientY + window.scrollY;
    }
		x = moving.startX + x - moving.mouseX;
		y = moving.startY + y - moving.mouseY;

		//log("Moving x = " + x + ", y = " + y);
		moving.style.left=(x < 0)? '0px' : x+'px';
		moving.style.top=(y < 0)? '0px' : y+'px';
    if (moving.firstChild.classList.contains("top-fixed")) {
      var evt = new CustomEvent("scroll",{detail: {},bubbles: true,cancelable: true});
      moving.dispatchEvent(evt);
    }
	}

	var handleMouseUp = function (event) {
		//log ("Stop moving " + moving.innerText);
		moving.started = false;
		var changes = [];
		if (parseInt(moving.startX) != parseInt(moving.style.left)) {
			changes.push(moving.id+".style.left="+moving.style.left);
		}
		if (parseInt(moving.startY) != parseInt(moving.style.top)) {
			changes.push(moving.id+".style.top="+moving.style.top);
		}
		storeChanges(changes);
		document.removeEventListener("mousemove", handleMouseMove, true);
		document.removeEventListener("mouseup", handleMouseUp, true);
	}

	var handleTouchStart = function (event) {
		var touches = event.changedTouches;
		for (var i=0; i < touches.length; i++) {
			if (touches[i].target.classList.contains('movable')) {
				touchMoving = true;
				ongoingTouches.push(copyTouch(touches[i]));
				//log("start touch "+i+ " on " +touches[i].target.innerHTML+" ("+touches[i].pageX+", "+touches[i].pageY+")");
			}
		}
	}

	var handleTouchMove = function (event) {
		if (!touchMoving) return;
		event.preventDefault();
		var touches = event.changedTouches;
		var x = 0;
		var y = 0;
		for (var i=0; i < touches.length; i++) {
			var idx = ongoingTouchIndexById(touches[i].identifier);
			if(idx >= 0) {
				x = touches[i].pageX - ongoingTouches[idx].pageX;
				y = touches[i].pageY - ongoingTouches[idx].pageY;
				//log("touch moving "+idx+" on "+ongoingTouches[idx].target.innerHTML+" ("+x+", "+y+")");
				ongoingTouches[idx].target.style.left = ongoingTouches[idx].target.offsetLeft + x + "px";
				ongoingTouches[idx].target.style.top = ongoingTouches[idx].target.offsetTop + y + "px";
				ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record
			} else {
				log("can't figure out which touch to continue");
			}
		}
	}

	var handleTouchEnd = function (event) {
		if (!touchMoving) return;
		touchMoving = false;
		event.preventDefault();
		var touches = event.changedTouches;
		for (var i=0; i < touches.length; i++) {
			var idx = ongoingTouchIndexById(touches[i].identifier);
			if(idx >= 0) {
				//log("touch finishing "+idx+" on "+ongoingTouches[idx].target.innerHTML);
				ongoingTouches.splice(idx, 1);  // remove it; we're done
			} else {
				log("can't figure out which touch to end");
			}
		}
	}

	function copyTouch(touch) {
		return {
			identifier: touch.identifier,
			target: touch.target,
			pageX: touch.pageX,
			pageY: touch.pageY
		};
	}

	function ongoingTouchIndexById(idToFind) {
		for (var i=0; i < ongoingTouches.length; i++) {
			var id = ongoingTouches[i].identifier;

			if (id == idToFind) {
				return i;
			}
		}
		return -1;    // not found
	}

})(typeof exports === 'undefined'? this['moving']={}: exports);
<commit_msg>Update moving.js<commit_after>/*!
 * moving.js
 *
 * Copyright © 2016 Jorge M. Peláez | MIT license
 * http://j-pel.github.io/dynamize
 *
 */

(function(exports) {

  'use strict';

	/* properties */
	var storeChanges = function(changes){return(0)};
	var ongoingTouches = new Array();
	var moving = new Object();
	var touchMoving = false;

	/* client API */

	/*!
	 * init(store)
	 * Starts the handling of the proposed feature
	 * A default id is assigned to elements with no id given.
	 *
	 * @param {store} callback to receive the elements' changes.
	 * @api public
	 */
	var init = exports.init = function(store) {
		storeChanges = store;
		var elementList = document.getElementsByClassName('movable');
		for (var i = 0; i < elementList.length; i++) {
			var ele = elementList[i];
			ele.addEventListener('mousedown', handleMouseDown, false);
			ele.style.cursor = 'move';
			if (!ele.id) {
				ele.id = "nn_m_"+i;
			}
		}
		document.addEventListener('touchstart', handleTouchStart, false);
		document.addEventListener("touchmove", handleTouchMove, true);
		document.addEventListener("touchleave", handleTouchEnd, true);
		document.addEventListener("touchend", handleTouchEnd, true);
		return 0;
	}

	/*!
	 * stop()
	 * Stops the handling of the proposed feature.
	 *
	 * @api public
	 */
	var stop = exports.stop = function() {
		var elementList = document.getElementsByClassName('movable');
		for (var i = 0; i < elementList.length; i++) {
			var ele = elementList[i];
			ele.removeEventListener('mousedown', handleMouseDown, false);
			ele.style.cursor = 'auto';
		}
		document.removeEventListener('touchstart', handleTouchStart, false);
		document.removeEventListener("touchmove", handleTouchMove, true);
		document.removeEventListener("touchleave", handleTouchEnd, true);
		document.removeEventListener("touchend", handleTouchEnd, true);
		return 0;
	}

	/* private helpers */

	function log(msg) {
		var p = document.getElementById('status');
		p.innerHTML = msg + "\n" + p.innerHTML;
	}

	var handleMouseDown = function (event) {
		event = event || window.event;
		moving=this;
		moving.started = true;
		//log("Start moving " + this.innerHTML);
		document.addEventListener("mousemove", handleMouseMove, true);
		document.addEventListener("mouseup", handleMouseUp, true);
		event.preventDefault();
    if (!window.scrollX) {
			moving.mouseX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			moving.mouseY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    } else {
			moving.mouseX = event.clientX + window.scrollX;
			moving.mouseY = event.clientY + window.scrollY;
    }
		moving.startX = moving.offsetLeft;
		moving.startY = moving.offsetTop;
	}

	var handleMouseMove = function (event) {
		if (!moving.started) return;
		event = event || window.event;
		var x, y;
    if (!window.scrollX) {
			x = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			y = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    } else {
			x = event.clientX + window.scrollX;
			y = event.clientY + window.scrollY;
    }
		x = moving.startX + x - moving.mouseX;
		y = moving.startY + y - moving.mouseY;

		//log("Moving x = " + x + ", y = " + y);
		moving.style.left=(x < 0)? '0px' : x+'px';
		moving.style.top=(y < 0)? '0px' : y+'px';
    if (moving.firstChild.classList.contains("top-fixed")) {
      var evt = new CustomEvent("scroll",{detail: {},bubbles: true,cancelable: true});
      moving.dispatchEvent(evt);
    }
	}

	var handleMouseUp = function (event) {
		//log ("Stop moving " + moving.innerText);
		moving.started = false;
		var changes = [];
		if (parseInt(moving.startX) != parseInt(moving.style.left)) {
			changes.push(moving.id+".style.left="+moving.style.left);
		}
		if (parseInt(moving.startY) != parseInt(moving.style.top)) {
			changes.push(moving.id+".style.top="+moving.style.top);
		}
		storeChanges(changes);
		document.removeEventListener("mousemove", handleMouseMove, true);
		document.removeEventListener("mouseup", handleMouseUp, true);
	}

	var handleTouchStart = function (event) {
		var touches = event.changedTouches;
		for (var i=0; i < touches.length; i++) {
			if (touches[i].target.classList.contains('movable')) {
				touchMoving = true;
				ongoingTouches.push(copyTouch(touches[i]));
				//log("start touch "+i+ " on " +touches[i].target.innerHTML+" ("+touches[i].pageX+", "+touches[i].pageY+")");
			}
		}
	}

	var handleTouchMove = function (event) {
		if (!touchMoving) return;
		event.preventDefault();
		var touches = event.changedTouches;
		var x = 0;
		var y = 0;
		for (var i=0; i < touches.length; i++) {
			var idx = ongoingTouchIndexById(touches[i].identifier);
			if(idx >= 0) {
				x = touches[i].pageX - ongoingTouches[idx].pageX;
				y = touches[i].pageY - ongoingTouches[idx].pageY;
				//log("touch moving "+idx+" on "+ongoingTouches[idx].target.innerHTML+" ("+x+", "+y+")");
				ongoingTouches[idx].target.style.left = ongoingTouches[idx].target.offsetLeft + x + "px";
				ongoingTouches[idx].target.style.top = ongoingTouches[idx].target.offsetTop + y + "px";
				ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record
			} else {
				log("can't figure out which touch to continue");
			}
		}
	}

	var handleTouchEnd = function (event) {
		if (!touchMoving) return;
		touchMoving = false;
		event.preventDefault();
		var touches = event.changedTouches;
		for (var i=0; i < touches.length; i++) {
			var idx = ongoingTouchIndexById(touches[i].identifier);
			if(idx >= 0) {
				//log("touch finishing "+idx+" on "+ongoingTouches[idx].target.innerHTML);
				ongoingTouches.splice(idx, 1);  // remove it; we're done
			} else {
				log("can't figure out which touch to end");
			}
		}
	}

	function copyTouch(touch) {
		return {
			identifier: touch.identifier,
			target: touch.target,
			pageX: touch.pageX,
			pageY: touch.pageY
		};
	}

	function ongoingTouchIndexById(idToFind) {
		for (var i=0; i < ongoingTouches.length; i++) {
			var id = ongoingTouches[i].identifier;

			if (id == idToFind) {
				return i;
			}
		}
		return -1;    // not found
	}

})(typeof exports === 'undefined'? this['moving']={}: exports);
<|endoftext|>


<commit_before>const _ = require('lodash');
const nconf = require('nconf');
const Promise = require('bluebird');
const JSDOM = require('jsdom').JSDOM;
const debug = require('debug')('datathon');
const moment = require('moment');

const utils = require('../lib/utils');
const mongo = require('../lib/mongo');
const l = require('../parsers/components/linkontime');

const cfgFile = "config/content.json";
nconf.argv().env().file({ file: cfgFile });

const cName = 'finalized';
const CHUNK = nconf.get('amount') ? _.parseInt(nconf.get('amount')) : 500;

let max = null;
const until = nconf.get('until');
if(!until) {
    max = new Date("2018-11-30");
    debug("`until` not set: using the default %s", max);
}
else {
    max = new Date(until);
    debug("`until` set, it will stop when reach %s", max);
}

const since = nconf.get('since');
let last = new Date(since);
let total = null;
let progressive = 0;
let initial = 0;
const executedAt = moment();

return mongo
    .readLimit(cName, {}, { savingTime: -1 }, 1, 0)
    .then(_.first)
    .then(function(lastSaved) {
        if(lastSaved) {
            if(since) {
                debug("Last reference found to %s but since %s request overrides",
                    lastSaved.savingTime, since);
                last = new Date(since);
            } else {
                debug("Last reference found to %s, and since not configured", lastSaved.savingTime);
                last = new Date(lastSaved.savingTime);
            }
        }
        else if(!since) {
            debug("When last reference don't exist, `since` is mandatory");
            process.exit(1);
        }
        else {
            last = new Date(since);
            debug("Starting `since` %s", last);
        }
        return last;
    })
    .tap(function(last) {
        return mongo.count(cName, {})
            .tap(function(before) {
                debug("previously found %d, chunk size configured (with `amount`) is %d", before, CHUNK);
                initial = before;
            });
    })
    .tap(function(last) {
        return mongo.count(nconf.get('schema').htmls, {
                savingTime: { $gt: last, $lte: max }
        })
        .tap(function(amount) {
            total = (amount - initial);
            debug("The # of htmls between %s and %s is: %d, still TBD %d",
                moment(last).format(), moment(max).format(), amount, total);
        });
    })
    .then(infiniteLoop);

function infiniteLoop(last) {
    let start = moment();
    return mongoPipeline(last)
        .map(enhanceRedact)
        .then(_.compact)
        .tap(massSave)
        .then(function(elements) {
            if(!_.size(elements)) {
                console.log("0 elements found");
                process.exit(1);
            }
            let end = moment();
            var secs = moment.duration(end - start).asSeconds();
            debug("exec %d secs 1st [%s] last [%s]",
                secs,
                _.first(elements) ? moment(_.first(elements).savingTime).format() : "NONE",
                _.last(elements) ? moment(_.last(elements).savingTime).format() : "NONE"
            );
            return new Date(_.last(elements).savingTime);
        })
        .then(infiniteLoop)
        .catch(function(error) {
            console.log("Fatal");
            console.error(error);
        });
};

function massSave(elements) {
    let copyable = new Object(elements);
    return Promise.map(elements, function(e) {
        return mongo
            .count(cName, { id: e.id })
            .tap(function(a) {
                if(a > 0)
                    copyable = _.reject(copyable, { id: e.id });
            });
    }, { concurrency: 5 })
    .then(function() {
        progressive += _.size(copyable);
        const runfor = moment.duration(moment() - executedAt).asSeconds();
        const pps = _.round(progressive / runfor, 0)
        const estim = (total - progressive) / pps;
        const stillwaitfor = moment.duration({ seconds: estim }).humanize();
        debug("Saving %d objects, total %d (still TBD %d) run since %s (%d secs) PPS %d ETA %s",
            _.size(copyable), progressive, total - progressive,
            moment.duration(executedAt - moment()).humanize(),
            runfor, pps, stillwaitfor
        );
        if(_.size(copyable))
            return mongo.writeMany(cName, copyable);
    });
};

function enhanceRedact(e) {
    try {
        _.unset(e, '_id');
        e.impressionOrder = _.first(e.impressionOrder);
        e.impressionTime = _.first(e.impressionTime);
        e.pseudo = utils.pseudonymizeUser(e.userId);
        const jsdom = new JSDOM(e.html).window.document;
        e.attributions = attributeOffsets(jsdom, e.html);
        e.details = l({jsdom}).linkedtime;
        _.unset(e, 'html');
        _.unset(e, 'userId');
    } catch(error) {
        console.error(error);
        return null;
    }
    return e;
};

function mongoPipeline(lastSaved) {

    if(moment(lastSaved).isAfter(max)) {
        debug("Execution completed, reach %s", max);
        process.exit(1);
    }

    return mongo.aggregate(nconf.get('schema').htmls, [{
        /* I use savingTime despite we use the impressionTime, because
         * savingTime is indexes, impressionTime ensure differencies */
            $match: {
                savingTime: { $gt: lastSaved }
            }},
            { $sort: {
                savingTime: 1
            }},
            { $limit: CHUNK },
            { $lookup: {
                from: "impressions2",
                localField: "id",
                foreignField: "htmlId",
                as: "impre"
            }},
            { $project: {
                html: true,
                utype: true,
                permaLink: true,
                id: true,
                timelineId: true,
                userId: true,
                savingTime: true,

                impressionOrder: '$impre.impressionOrder',
                impressionTime: '$impre.impressionTime',
            }}
        ]);
};

function attributeOffsets(jsdom, htmlstring) {

    let retval = []
    // { h: 'h5' || 'h6', offset: <Int>, name: <String>, display: <String> }
    const h5s = jsdom.querySelectorAll('h5');
    const h6s = jsdom.querySelectorAll('h6');

    function finder(initialO, h) {
        let linked = h.firstChild && h.firstChild.querySelector && h.firstChild.querySelector('a');
        if(linked) {
            let name = h.firstChild.querySelector('a').textContent;
            let display = h.textContent;
            let offset = htmlstring.indexOf(h.outerHTML);
            if(name) {
                retval.push(_.extend(initialO, {
                    offset,
                    name,
                    display
                }));
            }
        }
    };

    _.each(h5s, _.partial(finder, { h: 'h5' }));
    _.each(h6s, _.partial(finder, { h: 'h6' }));

    return retval;
};

<commit_msg>____ usual<commit_after>const _ = require('lodash');
const nconf = require('nconf');
const Promise = require('bluebird');
const JSDOM = require('jsdom').JSDOM;
const debug = require('debug')('datathon');
const moment = require('moment');

const utils = require('../lib/utils');
const mongo = require('../lib/mongo');
const l = require('../parsers/components/linkontime');

const cfgFile = "config/content.json";
nconf.argv().env().file({ file: cfgFile });

const cName = 'finalized';
const CHUNK = nconf.get('amount') ? _.parseInt(nconf.get('amount')) : 500;

let max = null;
const until = nconf.get('until');
if(!until) {
    max = new Date("2018-11-30");
    debug("`until` not set: using the default %s", max);
}
else {
    max = new Date(until);
    debug("`until` set, it will stop when reach %s", max);
}

const since = nconf.get('since');
let last = new Date(since);
let total = null;
let progressive = 0;
let initial = 0;
const executedAt = moment();

return mongo
    .readLimit(cName, {}, { savingTime: -1 }, 1, 0)
    .then(_.first)
    .then(function(lastSaved) {
        if(lastSaved) {
            if(since) {
                debug("Last reference found to %s but since %s request overrides",
                    lastSaved.savingTime, since);
                last = new Date(since);
            } else {
                debug("Last reference found to %s, and since not configured", lastSaved.savingTime);
                last = new Date(lastSaved.savingTime);
            }
        }
        else if(!since) {
            debug("When last reference don't exist, `since` is mandatory");
            process.exit(1);
        }
        else {
            last = new Date(since);
            debug("Starting `since` %s", last);
        }
        return last;
    })
    .tap(function(last) {
        return mongo.count(cName, {})
            .tap(function(before) {
                debug("previously found %d, chunk size configured (with `amount`) is %d", before, CHUNK);
                initial = before;
            });
    })
    .tap(function(last) {
        return mongo.count(nconf.get('schema').htmls, {
                savingTime: { $gt: last, $lte: max }
        })
        .tap(function(amount) {
            total = (amount - initial);
            debug("The # of htmls between %s and %s is: %d, still TBD %d",
                moment(last).format(), moment(max).format(), amount, total);
        });
    })
    .then(infiniteLoop);

function infiniteLoop(last) {
    let start = moment();
    return mongoPipeline(last)
        .map(enhanceRedact)
        .then(_.compact)
        .tap(massSave)
        .then(function(elements) {
            if(!_.size(elements)) {
                console.log("0 elements found");
                process.exit(1);
            }
            let end = moment();
            var secs = moment.duration(end - start).asSeconds();
            debug("exec %d secs 1st [%s] last [%s]",
                secs,
                _.first(elements) ? moment(_.first(elements).savingTime).format() : "NONE",
                _.last(elements) ? moment(_.last(elements).savingTime).format() : "NONE"
            );
            return new Date(_.last(elements).savingTime);
        })
        .then(infiniteLoop)
        .catch(function(error) {
            console.log("Fatal");
            console.error(error);
        });
};

function massSave(elements) {
    let copyable = new Object(elements);
    return Promise.map(elements, function(e) {
        return mongo
            .count(cName, { id: e.id })
            .tap(function(a) {
                if(a > 0)
                    copyable = _.reject(copyable, { id: e.id });
            });
    }, { concurrency: 5 })
    .then(function() {
        progressive += _.size(copyable);
        const runfor = moment.duration(moment() - executedAt).asSeconds();
        const pps = _.round(progressive / runfor, 0)
        const estim = (total - progressive) / pps;
        const stillwaitfor = moment.duration({ seconds: estim }).humanize();
        const successString = _.size(copyable) ? `+saving ${_.size(copyable)} objects` : "_____";
        debug("%s, total %d (still TBD %d) run since %s (%d secs) PPS %d ETA %s",
            successString, progressive, total - progressive,
            moment.duration(executedAt - moment()).humanize(),
            runfor, pps, stillwaitfor
        );
        if(_.size(copyable))
            return mongo.writeMany(cName, copyable);
    });
};

function enhanceRedact(e) {
    try {
        _.unset(e, '_id');
        e.impressionOrder = _.first(e.impressionOrder);
        e.impressionTime = _.first(e.impressionTime);
        e.pseudo = utils.pseudonymizeUser(e.userId);
        const jsdom = new JSDOM(e.html).window.document;
        e.attributions = attributeOffsets(jsdom, e.html);
        e.details = l({jsdom}).linkedtime;
        _.unset(e, 'html');
        _.unset(e, 'userId');
    } catch(error) {
        console.error(error);
        return null;
    }
    return e;
};

function mongoPipeline(lastSaved) {

    if(moment(lastSaved).isAfter(max)) {
        debug("Execution completed, reach %s", max);
        process.exit(1);
    }

    return mongo.aggregate(nconf.get('schema').htmls, [{
        /* I use savingTime despite we use the impressionTime, because
         * savingTime is indexes, impressionTime ensure differencies */
            $match: {
                savingTime: { $gt: lastSaved }
            }},
            { $sort: {
                savingTime: 1
            }},
            { $limit: CHUNK },
            { $lookup: {
                from: "impressions2",
                localField: "id",
                foreignField: "htmlId",
                as: "impre"
            }},
            { $project: {
                html: true,
                utype: true,
                permaLink: true,
                id: true,
                timelineId: true,
                userId: true,
                savingTime: true,

                impressionOrder: '$impre.impressionOrder',
                impressionTime: '$impre.impressionTime',
            }}
        ]);
};

function attributeOffsets(jsdom, htmlstring) {

    let retval = []
    // { h: 'h5' || 'h6', offset: <Int>, name: <String>, display: <String> }
    const h5s = jsdom.querySelectorAll('h5');
    const h6s = jsdom.querySelectorAll('h6');

    function finder(initialO, h) {
        let linked = h.firstChild && h.firstChild.querySelector && h.firstChild.querySelector('a');
        if(linked) {
            let name = h.firstChild.querySelector('a').textContent;
            let display = h.textContent;
            let offset = htmlstring.indexOf(h.outerHTML);
            if(name) {
                retval.push(_.extend(initialO, {
                    offset,
                    name,
                    display
                }));
            }
        }
    };

    _.each(h5s, _.partial(finder, { h: 'h5' }));
    _.each(h6s, _.partial(finder, { h: 'h6' }));

    return retval;
};

<|endoftext|>


<commit_before>/**
 * New node file
 */
pc_js2java.event = {};
pc_js2java.prototype.cb_createAnswer = function() {

}

pc_js2java.prototype.cb_createOffer = function() {

}

artc = window.androidRTCPeerConnection = function() {

};

artc.prototype.addIceCandidate = function() {
	pc_js2java.addIceCandidate();
};

artc.prototype.addStream = function() {
	pc_js2java.addStream();
};

artc.prototype.close = function() {
	pc_js2java.close();
};

artc.prototype.createAnswer = function() {
	pc_js2java.createAnswer();
};

artc.prototype.createDataChannel = function() {
	pc_js2java.createDataChannel();
};

artc.prototype.createOffer = function() {
	pc_js2java.createOffer();
};

artc.prototype.getLocalStreams = function() {
	pc_js2java.getLocalStreams();
};

artc.prototype.getRemoteStreams = function() {
	pc_js2java.getRemoteStreams();
};

artc.prototype.getStats = function() {
	pc_js2java.getStats();
};

artc.prototype.getStreamById = function() {
	pc_js2java.getStreamById();
};

artc.prototype.removeStream = function() {
	pc_js2java.removeStream();
};

artc.prototype.setLocalDescription = function() {
	pc_js2java.setLocalDescription();
};

artc.prototype.setRemoteDescription = function() {
	pc_js2java.setRemoteDescription();
};

artc.prototype.updateIce = function() {
	pc_js2java.updateIce();
};<commit_msg>peerconnection<commit_after>/**
 * New node file
 */

artc = window.androidRTCPeerConnection = function() {

};

artc.prototype.addIceCandidate = function() {
	pc_js2java.addIceCandidate();
};

artc.prototype.addStream = function() {
	pc_js2java.addStream();
};

artc.prototype.close = function() {
	pc_js2java.close();
};

artc.prototype.createAnswer = function(cb) {
	pc_js2java.createAnswer();
	artc.prototype.cb_createAnswer = cb;
};

artc.prototype.createDataChannel = function() {
	pc_js2java.createDataChannel();
};

artc.prototype.createOffer = function(cb) {
	pc_js2java.createOffer();
	artc.prototype.cb_createOffer = cb;
};

artc.prototype.getLocalStreams = function() {
	pc_js2java.getLocalStreams();
};

artc.prototype.getRemoteStreams = function() {
	pc_js2java.getRemoteStreams();
};

artc.prototype.getStats = function() {
	pc_js2java.getStats();
};

artc.prototype.getStreamById = function() {
	pc_js2java.getStreamById();
};

artc.prototype.removeStream = function() {
	pc_js2java.removeStream();
};

artc.prototype.setLocalDescription = function() {
	pc_js2java.setLocalDescription();
};

artc.prototype.setRemoteDescription = function() {
	pc_js2java.setRemoteDescription();
};

artc.prototype.updateIce = function() {
	pc_js2java.updateIce();
};
<|endoftext|>


<commit_before>function addWikiFormattingToolbar(textarea) {
  if ((typeof(document["selection"]) == "undefined")
   && (typeof(textarea["setSelectionRange"]) == "undefined")) {
    return;
  }

  var toolbar = document.createElement("div");
  toolbar.className = "wikitoolbar";

  function addButton(id, title, fn) {
    var a = document.createElement("a");
    a.href = "#";
    a.id = id;
    a.title = title;
    a.onclick = function() { try { fn() } catch (e) { } return false };
    a.tabIndex = 400;
    toolbar.appendChild(a);
  }

  function encloseSelection(prefix, suffix) {
    textarea.focus();
    var start, end, sel, scrollPos, subst;
    if (typeof(document["selection"]) != "undefined") {
      sel = document.selection.createRange().text;
    } else if (typeof(textarea["setSelectionRange"]) != "undefined") {
      start = textarea.selectionStart;
      end = textarea.selectionEnd;
      scrollPos = textarea.scrollTop;
      sel = textarea.value.substring(start, end);
    }
    if (sel.match(/ $/)) { // exclude ending space char, if any
      sel = sel.substring(0, sel.length - 1);
      suffix = suffix + " ";
    }
    subst = prefix + sel + suffix;
    if (typeof(document["selection"]) != "undefined") {
      var range = document.selection.createRange().text = subst;
      textarea.caretPos -= suffix.length;
    } else if (typeof(textarea["setSelectionRange"]) != "undefined") {
      textarea.value = textarea.value.substring(0, start) + subst +
                       textarea.value.substring(end);
      if (sel) {
        textarea.setSelectionRange(start + subst.length, start + subst.length);
      } else {
        textarea.setSelectionRange(start + prefix.length, start + prefix.length);
      }
      textarea.scrollTop = scrollPos;
    }
  }

  addButton("strong", "Bold text: '''Example'''", function() {
    encloseSelection("'''", "'''");
  });
  addButton("em", "Italic text: ''Example''", function() {
    encloseSelection("''", "''");
  });
  addButton("heading", "Heading: == Example ==", function() {
    encloseSelection("\n== ", " ==\n", "Heading");
  });
  addButton("link", "Link: [http://www.example.com/ Example]", function() {
    encloseSelection("[", "]");
  });
  addButton("code", "Code block: {{{ example }}}", function() {
    encloseSelection("\n{{{\n", "\n}}}\n");
  });
  addButton("hr", "Horizontal rule: ----", function() {
    encloseSelection("\n----\n", "");
  });

  textarea.parentNode.insertBefore(toolbar, textarea);
}

// Add the toolbar to all <textarea> elements on the page with the class
// 'wikitext'.
var re = /\bwikitext\b/;
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
  var textarea = textareas[i];
  if (textarea.className && re.test(textarea.className)) {
    addWikiFormattingToolbar(textarea);
  }
}
<commit_msg>Remove executable flag from JS file.<commit_after>function addWikiFormattingToolbar(textarea) {
  if ((typeof(document["selection"]) == "undefined")
   && (typeof(textarea["setSelectionRange"]) == "undefined")) {
    return;
  }

  var toolbar = document.createElement("div");
  toolbar.className = "wikitoolbar";

  function addButton(id, title, fn) {
    var a = document.createElement("a");
    a.href = "#";
    a.id = id;
    a.title = title;
    a.onclick = function() { try { fn() } catch (e) { } return false };
    a.tabIndex = 400;
    toolbar.appendChild(a);
  }

  function encloseSelection(prefix, suffix) {
    textarea.focus();
    var start, end, sel, scrollPos, subst;
    if (typeof(document["selection"]) != "undefined") {
      sel = document.selection.createRange().text;
    } else if (typeof(textarea["setSelectionRange"]) != "undefined") {
      start = textarea.selectionStart;
      end = textarea.selectionEnd;
      scrollPos = textarea.scrollTop;
      sel = textarea.value.substring(start, end);
    }
    if (sel.match(/ $/)) { // exclude ending space char, if any
      sel = sel.substring(0, sel.length - 1);
      suffix = suffix + " ";
    }
    subst = prefix + sel + suffix;
    if (typeof(document["selection"]) != "undefined") {
      var range = document.selection.createRange().text = subst;
      textarea.caretPos -= suffix.length;
    } else if (typeof(textarea["setSelectionRange"]) != "undefined") {
      textarea.value = textarea.value.substring(0, start) + subst +
                       textarea.value.substring(end);
      if (sel) {
        textarea.setSelectionRange(start + subst.length, start + subst.length);
      } else {
        textarea.setSelectionRange(start + prefix.length, start + prefix.length);
      }
      textarea.scrollTop = scrollPos;
    }
  }

  addButton("strong", "Bold text: '''Example'''", function() {
    encloseSelection("'''", "'''");
  });
  addButton("em", "Italic text: ''Example''", function() {
    encloseSelection("''", "''");
  });
  addButton("heading", "Heading: == Example ==", function() {
    encloseSelection("\n== ", " ==\n", "Heading");
  });
  addButton("link", "Link: [http://www.example.com/ Example]", function() {
    encloseSelection("[", "]");
  });
  addButton("code", "Code block: {{{ example }}}", function() {
    encloseSelection("\n{{{\n", "\n}}}\n");
  });
  addButton("hr", "Horizontal rule: ----", function() {
    encloseSelection("\n----\n", "");
  });

  textarea.parentNode.insertBefore(toolbar, textarea);
}

// Add the toolbar to all <textarea> elements on the page with the class
// 'wikitext'.
var re = /\bwikitext\b/;
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
  var textarea = textareas[i];
  if (textarea.className && re.test(textarea.className)) {
    addWikiFormattingToolbar(textarea);
  }
}
<|endoftext|>


<commit_before>define("dijit/_KeyNavContainer", ["dojo", "dijit", "dijit/_Container"], function(dojo, dijit) {

dojo.declare("dijit._KeyNavContainer",
	dijit._Container,
	{

		// summary:
		//		A _Container with keyboard navigation of its children.
		// description:
		//		To use this mixin, call connectKeyNavHandlers() in
		//		postCreate() and call startupKeyNavChildren() in startup().
		//		It provides normalized keyboard and focusing code for Container
		//		widgets.
/*=====
		// focusedChild: [protected] Widget
		//		The currently focused child widget, or null if there isn't one
		focusedChild: null,
=====*/

		// tabIndex: Integer
		//		Tab index of the container; same as HTML tabIndex attribute.
		//		Note then when user tabs into the container, focus is immediately
		//		moved to the first item in the container.
		tabIndex: "0",

		_keyNavCodes: {},

		connectKeyNavHandlers: function(/*dojo.keys[]*/ prevKeyCodes, /*dojo.keys[]*/ nextKeyCodes){
			// summary:
			//		Call in postCreate() to attach the keyboard handlers
			//		to the container.
			// preKeyCodes: dojo.keys[]
			//		Key codes for navigating to the previous child.
			// nextKeyCodes: dojo.keys[]
			//		Key codes for navigating to the next child.
			// tags:
			//		protected

			var keyCodes = (this._keyNavCodes = {});
			var prev = dojo.hitch(this, this.focusPrev);
			var next = dojo.hitch(this, this.focusNext);
			dojo.forEach(prevKeyCodes, function(code){ keyCodes[code] = prev; });
			dojo.forEach(nextKeyCodes, function(code){ keyCodes[code] = next; });
			keyCodes[dojo.keys.HOME] = dojo.hitch(this, "focusFirstChild");
			keyCodes[dojo.keys.END] = dojo.hitch(this, "focusLastChild");
			this.connect(this.domNode, "onkeypress", "_onContainerKeypress");
			this.connect(this.domNode, "onfocus", "_onContainerFocus");
		},

		startupKeyNavChildren: function(){
			// summary:
			//		Call in startup() to set child tabindexes to -1
			// tags:
			//		protected
			dojo.forEach(this.getChildren(), dojo.hitch(this, "_startupChild"));
		},

		addChild: function(/*dijit._Widget*/ widget, /*int?*/ insertIndex){
			// summary:
			//		Add a child to our _Container
			dijit._KeyNavContainer.superclass.addChild.apply(this, arguments);
			this._startupChild(widget);
		},

		focus: function(){
			// summary:
			//		Default focus() implementation: focus the first child.
			this.focusFirstChild();
		},

		focusFirstChild: function(){
			// summary:
			//		Focus the first focusable child in the container.
			// tags:
			//		protected
			var child = this._getFirstFocusableChild();
			if(child){ // edge case: Menu could be empty or hidden
				this.focusChild(child);
			}
		},

		focusLastChild: function(){
			// summary:
			//		Focus the last focusable child in the container.
			// tags:
			//		protected
			var child = this._getLastFocusableChild();
			if(child){ // edge case: Menu could be empty or hidden
				this.focusChild(child);
			}
		},

		focusNext: function(){
			// summary:
			//		Focus the next widget
			// tags:
			//		protected
			var child = this._getNextFocusableChild(this.focusedChild, 1);
			this.focusChild(child);
		},

		focusPrev: function(){
			// summary:
			//		Focus the last focusable node in the previous widget
			//		(ex: go to the ComboButton icon section rather than button section)
			// tags:
			//		protected
			var child = this._getNextFocusableChild(this.focusedChild, -1);
			this.focusChild(child, true);
		},

		focusChild: function(/*dijit._Widget*/ widget, /*Boolean*/ last){
			// summary:
			//		Focus widget.
			// widget:
			//		Reference to container's child widget
			// last:
			//		If true and if widget has multiple focusable nodes, focus the
			//		last one instead of the first one
			// tags:
			//		protected

			if(this.focusedChild && widget !== this.focusedChild){
				this._onChildBlur(this.focusedChild);
			}
			widget.focus(last ? "end" : "start");
			this._set("focusedChild", widget);
		},

		_startupChild: function(/*dijit._Widget*/ widget){
			// summary:
			//		Setup for each child widget
			// description:
			//		Sets tabIndex=-1 on each child, so that the tab key will
			//		leave the container rather than visiting each child.
			// tags:
			//		private

			widget.set("tabIndex", "-1");

			this.connect(widget, "_onFocus", function(){
				// Set valid tabIndex so tabbing away from widget goes to right place, see #10272
				widget.set("tabIndex", this.tabIndex);
			});
			this.connect(widget, "_onBlur", function(){
				widget.set("tabIndex", "-1");
			});
		},

		_onContainerFocus: function(evt){
			// summary:
			//		Handler for when the container gets focus
			// description:
			//		Initially the container itself has a tabIndex, but when it gets
			//		focus, switch focus to first child...
			// tags:
			//		private

			// Note that we can't use _onFocus() because switching focus from the
			// _onFocus() handler confuses the focus.js code
			// (because it causes _onFocusNode() to be called recursively)

			// focus bubbles on Firefox,
			// so just make sure that focus has really gone to the container
			if(evt.target !== this.domNode){ return; }

			this.focusFirstChild();

			// and then set the container's tabIndex to -1,
			// (don't remove as that breaks Safari 4)
			// so that tab or shift-tab will go to the fields after/before
			// the container, rather than the container itself
			dojo.attr(this.domNode, "tabIndex", "-1");
		},

		_onBlur: function(evt){
			// When focus is moved away the container, and its descendant (popup) widgets,
			// then restore the container's tabIndex so that user can tab to it again.
			// Note that using _onBlur() so that this doesn't happen when focus is shifted
			// to one of my child widgets (typically a popup)
			if(this.tabIndex){
				dojo.attr(this.domNode, "tabIndex", this.tabIndex);
			}
			this.inherited(arguments);
		},

		_onContainerKeypress: function(evt){
			// summary:
			//		When a key is pressed, if it's an arrow key etc. then
			//		it's handled here.
			// tags:
			//		private
			if(evt.ctrlKey || evt.altKey){ return; }
			var func = this._keyNavCodes[evt.charOrCode];
			if(func){
				func();
				dojo.stopEvent(evt);
			}
		},

		_onChildBlur: function(/*dijit._Widget*/ widget){
			// summary:
			//		Called when focus leaves a child widget to go
			//		to a sibling widget.
			// tags:
			//		protected
		},

		_getFirstFocusableChild: function(){
			// summary:
			//		Returns first child that can be focused
			return this._getNextFocusableChild(null, 1);	// dijit._Widget
		},

		_getLastFocusableChild: function(){
			// summary:
			//		Returns last child that can be focused
			return this._getNextFocusableChild(null, -1);	// dijit._Widget
		},

		_getNextFocusableChild: function(child, dir){
			// summary:
			//		Returns the next or previous focusable child, compared
			//		to "child"
			// child: Widget
			//		The current widget
			// dir: Integer
			//		* 1 = after
			//		* -1 = before
			if(child){
				child = this._getSiblingOfChild(child, dir);
			}
			var children = this.getChildren();
			for(var i=0; i < children.length; i++){
				if(!child){
					child = children[(dir>0) ? 0 : (children.length-1)];
				}
				if(child.isFocusable()){
					return child;	// dijit._Widget
				}
				child = this._getSiblingOfChild(child, dir);
			}
			// no focusable child found
			return null;	// dijit._Widget
		}
	}
);

return dijit._KeyNavContainer;
});
<commit_msg>Fix problem on Toolbar buttons where IE doesn't display focus border (after tabbing into the toolbar, or using the arrow keys to navigate).<commit_after>define("dijit/_KeyNavContainer", ["dojo", "dijit", "dijit/_Container"], function(dojo, dijit) {

dojo.declare("dijit._KeyNavContainer",
	dijit._Container,
	{

		// summary:
		//		A _Container with keyboard navigation of its children.
		// description:
		//		To use this mixin, call connectKeyNavHandlers() in
		//		postCreate() and call startupKeyNavChildren() in startup().
		//		It provides normalized keyboard and focusing code for Container
		//		widgets.
/*=====
		// focusedChild: [protected] Widget
		//		The currently focused child widget, or null if there isn't one
		focusedChild: null,
=====*/

		// tabIndex: Integer
		//		Tab index of the container; same as HTML tabIndex attribute.
		//		Note then when user tabs into the container, focus is immediately
		//		moved to the first item in the container.
		tabIndex: "0",

		_keyNavCodes: {},

		connectKeyNavHandlers: function(/*dojo.keys[]*/ prevKeyCodes, /*dojo.keys[]*/ nextKeyCodes){
			// summary:
			//		Call in postCreate() to attach the keyboard handlers
			//		to the container.
			// preKeyCodes: dojo.keys[]
			//		Key codes for navigating to the previous child.
			// nextKeyCodes: dojo.keys[]
			//		Key codes for navigating to the next child.
			// tags:
			//		protected

			var keyCodes = (this._keyNavCodes = {});
			var prev = dojo.hitch(this, this.focusPrev);
			var next = dojo.hitch(this, this.focusNext);
			dojo.forEach(prevKeyCodes, function(code){ keyCodes[code] = prev; });
			dojo.forEach(nextKeyCodes, function(code){ keyCodes[code] = next; });
			keyCodes[dojo.keys.HOME] = dojo.hitch(this, "focusFirstChild");
			keyCodes[dojo.keys.END] = dojo.hitch(this, "focusLastChild");
			this.connect(this.domNode, "onkeypress", "_onContainerKeypress");
			this.connect(this.domNode, "onfocus", "_onContainerFocus");
		},

		startupKeyNavChildren: function(){
			// summary:
			//		Call in startup() to set child tabindexes to -1
			// tags:
			//		protected
			dojo.forEach(this.getChildren(), dojo.hitch(this, "_startupChild"));
		},

		addChild: function(/*dijit._Widget*/ widget, /*int?*/ insertIndex){
			// summary:
			//		Add a child to our _Container
			dijit._KeyNavContainer.superclass.addChild.apply(this, arguments);
			this._startupChild(widget);
		},

		focus: function(){
			// summary:
			//		Default focus() implementation: focus the first child.
			this.focusFirstChild();
		},

		focusFirstChild: function(){
			// summary:
			//		Focus the first focusable child in the container.
			// tags:
			//		protected
			var child = this._getFirstFocusableChild();
			if(child){ // edge case: Menu could be empty or hidden
				this.focusChild(child);
			}
		},

		focusLastChild: function(){
			// summary:
			//		Focus the last focusable child in the container.
			// tags:
			//		protected
			var child = this._getLastFocusableChild();
			if(child){ // edge case: Menu could be empty or hidden
				this.focusChild(child);
			}
		},

		focusNext: function(){
			// summary:
			//		Focus the next widget
			// tags:
			//		protected
			var child = this._getNextFocusableChild(this.focusedChild, 1);
			this.focusChild(child);
		},

		focusPrev: function(){
			// summary:
			//		Focus the last focusable node in the previous widget
			//		(ex: go to the ComboButton icon section rather than button section)
			// tags:
			//		protected
			var child = this._getNextFocusableChild(this.focusedChild, -1);
			this.focusChild(child, true);
		},

		focusChild: function(/*dijit._Widget*/ widget, /*Boolean*/ last){
			// summary:
			//		Focus widget.
			// widget:
			//		Reference to container's child widget
			// last:
			//		If true and if widget has multiple focusable nodes, focus the
			//		last one instead of the first one
			// tags:
			//		protected

			if(this.focusedChild && widget !== this.focusedChild){
				this._onChildBlur(this.focusedChild);
			}
			widget.set("tabIndex", this.tabIndex);	// for IE focus outline to appear, must set tabIndex before focs
			widget.focus(last ? "end" : "start");
			this._set("focusedChild", widget);
		},

		_startupChild: function(/*dijit._Widget*/ widget){
			// summary:
			//		Setup for each child widget
			// description:
			//		Sets tabIndex=-1 on each child, so that the tab key will
			//		leave the container rather than visiting each child.
			// tags:
			//		private

			widget.set("tabIndex", "-1");

			this.connect(widget, "_onFocus", function(){
				// Set valid tabIndex so tabbing away from widget goes to right place, see #10272
				widget.set("tabIndex", this.tabIndex);
			});
			this.connect(widget, "_onBlur", function(){
				widget.set("tabIndex", "-1");
			});
		},

		_onContainerFocus: function(evt){
			// summary:
			//		Handler for when the container gets focus
			// description:
			//		Initially the container itself has a tabIndex, but when it gets
			//		focus, switch focus to first child...
			// tags:
			//		private

			// Note that we can't use _onFocus() because switching focus from the
			// _onFocus() handler confuses the focus.js code
			// (because it causes _onFocusNode() to be called recursively)

			// focus bubbles on Firefox,
			// so just make sure that focus has really gone to the container
			if(evt.target !== this.domNode){ return; }

			this.focusFirstChild();

			// and then set the container's tabIndex to -1,
			// (don't remove as that breaks Safari 4)
			// so that tab or shift-tab will go to the fields after/before
			// the container, rather than the container itself
			dojo.attr(this.domNode, "tabIndex", "-1");
		},

		_onBlur: function(evt){
			// When focus is moved away the container, and its descendant (popup) widgets,
			// then restore the container's tabIndex so that user can tab to it again.
			// Note that using _onBlur() so that this doesn't happen when focus is shifted
			// to one of my child widgets (typically a popup)
			if(this.tabIndex){
				dojo.attr(this.domNode, "tabIndex", this.tabIndex);
			}
			this.inherited(arguments);
		},

		_onContainerKeypress: function(evt){
			// summary:
			//		When a key is pressed, if it's an arrow key etc. then
			//		it's handled here.
			// tags:
			//		private
			if(evt.ctrlKey || evt.altKey){ return; }
			var func = this._keyNavCodes[evt.charOrCode];
			if(func){
				func();
				dojo.stopEvent(evt);
			}
		},

		_onChildBlur: function(/*dijit._Widget*/ widget){
			// summary:
			//		Called when focus leaves a child widget to go
			//		to a sibling widget.
			// tags:
			//		protected
		},

		_getFirstFocusableChild: function(){
			// summary:
			//		Returns first child that can be focused
			return this._getNextFocusableChild(null, 1);	// dijit._Widget
		},

		_getLastFocusableChild: function(){
			// summary:
			//		Returns last child that can be focused
			return this._getNextFocusableChild(null, -1);	// dijit._Widget
		},

		_getNextFocusableChild: function(child, dir){
			// summary:
			//		Returns the next or previous focusable child, compared
			//		to "child"
			// child: Widget
			//		The current widget
			// dir: Integer
			//		* 1 = after
			//		* -1 = before
			if(child){
				child = this._getSiblingOfChild(child, dir);
			}
			var children = this.getChildren();
			for(var i=0; i < children.length; i++){
				if(!child){
					child = children[(dir>0) ? 0 : (children.length-1)];
				}
				if(child.isFocusable()){
					return child;	// dijit._Widget
				}
				child = this._getSiblingOfChild(child, dir);
			}
			// no focusable child found
			return null;	// dijit._Widget
		}
	}
);

return dijit._KeyNavContainer;
});
<|endoftext|>


<commit_before>const DocumentDBClient = require('documentdb').DocumentClient;
const config = {
    DatabaseId: "mean-dev",
    CollectionId: "users",
    Host: process.env.DocDb_Host,
    AuthKey: process.env.DocDb_AuthKey,
};

config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.CollectionId

module.exports = function (context, message) {

    let err = null;

    const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey });
    const querySpec = {
        query: 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = \'@userid\' AND \'twitter\' = \'@platform\')',// OR (c.instagram[\'$id\'] = \'@userid\' AND \'instagram\' = \'@platform\') OR (c.facebook[\'$id\'] = \'@userid\' AND \'facebook\' = \'@platform\')',
        parameters: [{
            name: '@userid',
            value: message.userid
        },
        {
            name: '@platform',
            value: message.platform
        }]
    };

    const query = 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = \'' + message.userid + '\' AND \'twitter\' = \'' + message.platform + '\') OR (c.instagram[\'$id\'] = \'' + message.userid + '\' AND \'instagram\' = \'' + message.platform + '\') OR (c.facebook[\'$id\'] = \'' + message.userid + '\' AND \'facebook\' = \'' + message.platform + '\')';

    context.log(querySpec);
    docDbClient.queryDocuments(config.CollLink, query).toArray(function (err, results) {
        context.log(err);
        context.log(results);
        let userdata = results[0];

        if (!userdata || userdata == undefined) {
            context.log('Not tracking user');

            err = new Error('Not tracking user');
            return;
        }

        if ((!userdata.twitter || userdata.twitter == undefined)
            && (!userdata.facebook || userdata.facebook == undefined)
            || (!userdata.instagram || userdata.instagram == undefined)) {
            context.log('No social profiles');

            err = new Error('No social profiles');
            return;
        }

        if (!userdata.id) {
            context.log('No user id');

            err = new Error('No social profiles');
            return;
        }

        let data = new Object();

        if (!err) {
            data.userid = userdata.id;
            data.platform = message.platform;
            data.mediaid = message.mediaid;

            if (message.twitter) {
                context.log('adding twitter');

                data.twitter = {
                    id: message.twitter.$id,
                    token: message.twitter.token,
                    username: message.twitter.username,
                };
            }

            if (message.instagram) {
                context.log('adding instagram');

                data.instagram = {
                    id: message.instagram.$id,
                    token: message.instagram.token,
                    username: message.instagram.username,
                };
            }

            if (message.facebook) {
                context.log('adding facebook');

                data.facebook = {
                    id: message.facebook.$id,
                    token: message.facebook.token,
                    username: message.facebook.email,
                };
            }
        }

        context.done(err, data);
    });
};<commit_msg>remove crap<commit_after>const DocumentDBClient = require('documentdb').DocumentClient;
const config = {
    DatabaseId: "mean-dev",
    CollectionId: "users",
    Host: process.env.DocDb_Host,
    AuthKey: process.env.DocDb_AuthKey,
};

config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.CollectionId

module.exports = function (context, message) {

    let err = null;

    const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey });
    const query = 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = \'' + message.userid + '\' AND \'twitter\' = \'' + message.platform + '\') OR (c.instagram[\'$id\'] = \'' + message.userid + '\' AND \'instagram\' = \'' + message.platform + '\') OR (c.facebook[\'$id\'] = \'' + message.userid + '\' AND \'facebook\' = \'' + message.platform + '\')';

    docDbClient.queryDocuments(config.CollLink, query).toArray(function (err, results) {

        let userdata = results[0];

        if (!userdata || userdata == undefined) {
            context.log('Not tracking user');

            err = new Error('Not tracking user');
            return;
        }

        if ((!userdata.twitter || userdata.twitter == undefined)
            && (!userdata.facebook || userdata.facebook == undefined)
            || (!userdata.instagram || userdata.instagram == undefined)) {
            context.log('No social profiles');

            err = new Error('No social profiles');
            return;
        }

        if (!userdata.id) {
            context.log('No user id');

            err = new Error('No social profiles');
            return;
        }

        let data = new Object();

        if (!err) {
            data.userid = userdata.id;
            data.platform = message.platform;
            data.mediaid = message.mediaid;

            if (message.twitter) {
                context.log('adding twitter');

                data.twitter = {
                    id: message.twitter.$id,
                    token: message.twitter.token,
                    username: message.twitter.username,
                };
            }

            if (message.instagram) {
                context.log('adding instagram');

                data.instagram = {
                    id: message.instagram.$id,
                    token: message.instagram.token,
                    username: message.instagram.username,
                };
            }

            if (message.facebook) {
                context.log('adding facebook');

                data.facebook = {
                    id: message.facebook.$id,
                    token: message.facebook.token,
                    username: message.facebook.email,
                };
            }
        }

        context.done(err, data);
    });
};<|endoftext|>


<commit_before>/*
 *  Copyright 2015 Simon Shields
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var request = require('request');
var entities = require('entities');
(function(e) {
	const ABC_ELECTION_DATA = 'http://www.abc.net.au/dat/news/elections/federal/2016/results/OnlineLists.jsonp.js';
	const ABC_SEAT_STATUS = 'http://www.abc.net.au/dat/news/elections/federal/2016/results/OnlinePartyGroupTrends.jsonp.js';
	const ABC_SEAT_PRIMARIES = 'http://www.abc.net.au/dat/news/elections/federal/2016/results/OnlineElectorate{code}.jsonp.js';
	var CUR_SEAT_DATA = {};
	var electorates = {};
	var do_changes = true;
	var cached_msg;
	var msgQueue = [];
	var watched_seats = ['Banks'];
	function callback_OnlineLists(obj) {
		var old = JSON.parse(JSON.stringify(electorates));
		CUR_SEAT_DATA = obj.Erads.Elections.Election.Chambers.Chamber;
		var es = CUR_SEAT_DATA.Electorates.Electorate;
		for (var s = 0; s < es.length; s++) {
			var name = es[s].LongName.replace(' (*)', '');
			electorates[name] = es[s];
		}
		if (do_changes) showChanges(old, electorates);
	}

	function showChanges(old, nnew) {
		if (old == {}) return;
		for (var k in watched_seats) {
			k = watched_seats[k];
			console.log(k);
			if (genmsg(old[k], k) != genmsg(nnew[k], k)) {
				console.log('# CHANGED ###################################################3');
				var res = genmsg(nnew[k], k);
				msgQueue.push('Update: ' + res);
			}
		}
	}

	function sendMsgQ() {
		if (msgQueue.length != 0 && cached_msg != null)
			cached_msg.say(msgQueue.shift());
	}

	function poll() {
		request({
			'uri': ABC_ELECTION_DATA
		}, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				try {
					eval(body);
				} catch (e) {
					console.log(e, e.message);
				}
			} else {
				console.log(error);
				console.log(body);
			}
		});

	}

	e.cmd_ctxtEval = function(msg) {
		msg.reply(eval(msg.getArgs().join(' ')));
	}

	e.cmd_watch = function(msg) {
		watched_seats.push(msg.getArgs().join(' '));
		msg.reply('watched ' + msg.getArgs().join(' '));
	}

	e.cmd_unwatch = function(msg) {
		var arg = msg.getArgs().join(' ');
		var idx = watched_seats.indexOf(arg);
		if (idx != -1) {
			watched_seats.splice(idx, 1);
			msg.reply('unwatched ' + msg.getArgs().join(' '));
		} else {
			msg.reply('seat isn\'t watched!');
		}
	}

	e.cmd_watched = function(msg) {
		msg.reply('Watched seats: ' + watched_seats.join(', '));
	}

	poll();
	var id = setInterval(poll, 30000);
	var id2 = setInterval(sendMsgQ, 1000);

	e.unload = function() {
		clearInterval(id);
		clearInterval(id2);
	}

	function zfill(str) {
		if (str.length == 1) str = '0' + str;
		return str;
	}

	function genmsg(e, seat) {
		if (e == null) return "No results yet for " + seat + ".";
		var p = e.ElectoratePredictionSuppressed;
		if (e.Swingdial == null || e.LeadingCandidate == null) return "No results yet for " + seat + ".";
		var sd = e.Swingdial.Candidate;
		if (!p) {
			p = e.ElectoratePrediction;
		}
		if (p == null) return "No results yet for " + seat + ".";
		var cdt0 = sd[0].Party.PartyCode;
		var cdt1 = sd[1].Party.PartyCode;
		var date = new Date(e.LastUpdateTime);
		var message = "Results for " + seat + ": ";
		message += p.Result2CPPct + "% " + e.LeadingCandidate.Party.PartyCode
		if (cdt0 != e.LeadingCandidate.Party.PartyCode) {
			message += " (v " + cdt0 + "), ";
		} else {
			message += " (v " + cdt1 + "), ";
		}
		message += p.Result2CPSwingString + ". Prediction: " + p.PredictionString + ". ";
		message += "Currently held by " + e.HoldingParty.ShortName + " with a " + e.Margin + "% margin. ";
		message += + e.CountedPct + "% counted. Updated at " + date.getUTCHours() + ":" + zfill(date.getMinutes().toString()) + ".";
		return message;
	}

	function generate_seat(msg, e, seat) {
		if (msg == null) return;
		cached_msg = msg;
		msg.say(genmsg(e, seat));
	}

	e.cmd_seat = function(msg) {
		var seat = msg.getArgs().join(' ');
		if (seat in electorates) {
			var e = electorates[seat];
			generate_seat(msg, e, seat);
		} else {
			msg.reply("No such seat!");
		}
	}

	function callback_OnlineElectorate(obj) {
		var e = obj.Erads.Elections.Election.Chambers.Chamber.Electorates.Electorate;
		var msg = "Results for " + e.LongName + "(" + e.StateCategory.CategoryCode + "): ";
		var cand = e.Candidates.Candidate;
		for (var i = 0; i < cand.length; i++) {
			if (cand[i].BallotPosition.startsWith("9")) continue;
			msg += cand[i].Party.PartyCode + ": " + cand[i].PredictedPrimary.Percent + "% (" +
				cand[i].PredictedPrimary.Swing + "% swing)" + ", ";
		}
		msg += e.CountedPct + "% counted, " + e.NoOfPollingPlaces.Reporting2CP + "/" + e.NoOfPollingPlaces.Total + " booths counted.";
		if (e.IsKeySeat) {
			msg += " Key Seat!";
		}
		cached_msg.say(msg);

	}

	e.cmd_primary = function(msg) {
		cached_msg = msg;
		var seat = msg.getArgs().join(' ');
		if (seat in electorates) {
			var id = electorates[seat].ElectorateCode;
			var url = ABC_SEAT_PRIMARIES.replace('{code}', id);
			var name = 'callback_OnlineElectorate' + id;
			request({
				'uri': url
			}, function (error, response, body) {
				if (!error && response.statusCode == 200) {
					try {
						eval(body.replace(name, 'callback_OnlineElectorate'));
					} catch (e) {
						console.log(e, e.message);
					}
				} else {
					console.log(error);
					console.log(body);
				}
			});
		} else {
			msg.reply("No such seat!");
		}
	}

	function callback_OnlinePartyGroupTrends(obj) {
		var trend = obj.Erads.Elections.Election.Chambers.Chamber.Trends.Trend[0];
		console.log(trend);
		var parties = trend.PartyGroups.PartyGroup;
		var msg = "Current seat counts: ";
		for (var i = 0; i < parties.length; i++) {
			var p = parties[i];
			msg += p.PartyGroupCode.replace("L/NP", "LNP") + ": " + p.SeatsExcludingEarlyVotes.Won + " won, "
				if (p.SeatsExcludingEarlyVotes.Likely > 0)
					msg += p.SeatsExcludingEarlyVotes.Likely + " likely - ";
			msg += p.PredictedPrimary.Percent + "% primary, (" + p.PredictedPrimary.Swing + "% swing), ";
		}
		var pred = trend.PredictionStringSuppressed;
		if (pred) {
			msg += "AEC preliminary prediction: " + pred;
		} else {
			msg += "AEC prediction: " + trend.PredictionString;
		}
		msg += ". " + trend.CountedPct + "% counted.";
		cached_msg.say(msg);

	}

	e.cmd_seats = function(msg) {
		cached_msg = msg;
		request({
			'uri': ABC_SEAT_STATUS
		}, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				try {
					eval(body);
				} catch(e) {
					console.log(e, e.message);
				}
			} else {
				console.log(error);
				console.log(body);
			}
		});
	}

})(module.exports);
<commit_msg>report seat count updates regularly, show 2CP/Primary reporting count<commit_after>/*
 *  Copyright 2015 Simon Shields
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var request = require('request');
var entities = require('entities');
(function(e) {
	const ABC_ELECTION_DATA = 'http://www.abc.net.au/dat/news/elections/federal/2016/results/OnlineLists.jsonp.js';
	const ABC_SEAT_STATUS = 'http://www.abc.net.au/dat/news/elections/federal/2016/results/OnlinePartyGroupTrends.jsonp.js';
	const ABC_SEAT_PRIMARIES = 'http://www.abc.net.au/dat/news/elections/federal/2016/results/OnlineElectorate{code}.jsonp.js';
	var CUR_SEAT_DATA = {};
	var electorates = {};
	var do_changes = true;
	var cached_msg;
	var msgQueue = [];
	var watched_seats = ['Cowan', 'Capricornia', 'Hindmarsh', 'Forde'];
	var firstRun = true;
	var captureOPGT = false;
	var lastOPGT = "";
	var GROUP_TRENDS = {};
	function callback_OnlineLists(obj) {
		var old = JSON.parse(JSON.stringify(electorates));
		CUR_SEAT_DATA = obj.Erads.Elections.Election.Chambers.Chamber;
		var es = CUR_SEAT_DATA.Electorates.Electorate;
		for (var s = 0; s < es.length; s++) {
			var name = es[s].LongName.replace(' (*)', '');
			electorates[name] = es[s];
		}
		if (do_changes) showChanges(old, electorates);
	}

	function showChanges(old, nnew) {
		if (old == {}) return;
		for (var k in watched_seats) {
			k = watched_seats[k];
			console.log(k);
			if (genmsg(old[k], k) != genmsg(nnew[k], k)) {
				console.log('# CHANGED ###################################################3');
				var res = genmsg(nnew[k], k);
				msgQueue.push('Update: ' + res);
			}
		}
	}

	function sendMsgQ() {
		if (msgQueue.length != 0 && cached_msg != null)
			cached_msg.say(msgQueue.shift());
	}

	function poll() {
		request({
			'uri': ABC_ELECTION_DATA
		}, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				try {
					eval(body);
				} catch (e) {
					console.log(e, e.message);
				}
			} else {
				console.log(error);
				console.log(body);
			}
		});

	}

	e.cmd_ctxtEval = function(msg) {
		msg.reply(eval(msg.getArgs().join(' ')));
	}

	e.cmd_watch = function(msg) {
		watched_seats.push(msg.getArgs().join(' '));
		msg.reply('watched ' + msg.getArgs().join(' '));
	}

	e.cmd_unwatch = function(msg) {
		var arg = msg.getArgs().join(' ');
		var idx = watched_seats.indexOf(arg);
		if (idx != -1) {
			watched_seats.splice(idx, 1);
			msg.reply('unwatched ' + msg.getArgs().join(' '));
		} else {
			msg.reply('seat isn\'t watched!');
		}
	}

	e.cmd_watched = function(msg) {
		msg.reply('Watched seats: ' + watched_seats.join(', '));
	}

	poll();
	var id = setInterval(poll, 30000);
	var id2 = setInterval(sendMsgQ, 1000);

	e.unload = function() {
		clearInterval(id);
		clearInterval(id2);
		clearInterval(id3);
	}

	function zfill(str) {
		if (str.length == 1) str = '0' + str;
		return str;
	}

	function genmsg(e, seat) {
		if (e == null) return "No results yet for " + seat + ".";
		var p = e.ElectoratePredictionSuppressed;
		if (e.Swingdial == null || e.LeadingCandidate == null) return "No results yet for " + seat + ".";
		var sd = e.Swingdial.Candidate;
		if (!p) {
			p = e.ElectoratePrediction;
		}
		if (p == null) return "No results yet for " + seat + ".";
		var cdt0 = sd[0].Party.PartyCode;
		var cdt1 = sd[1].Party.PartyCode;
		var date = new Date(e.LastUpdateTime);
		var message = "Results for " + seat + ": ";
		message += p.Result2CPPct + "% " + e.LeadingCandidate.Party.PartyCode
		if (cdt0 != e.LeadingCandidate.Party.PartyCode) {
			message += " (v " + cdt0 + "), ";
		} else {
			message += " (v " + cdt1 + "), ";
		}
		message += p.Result2CPSwingString + ". Prediction: " + p.PredictionString + ". ";
		message += "Currently held by " + e.HoldingParty.ShortName + " with a " + e.Margin + "% margin. ";
		message += + e.CountedPct + "% counted. Updated at " + date.getUTCHours() + ":" + zfill(date.getMinutes().toString()) + ".";
		return message;
	}

	function generate_seat(msg, e, seat) {
		if (msg == null) return;
		cached_msg = msg;
		msg.say(genmsg(e, seat));
	}

	e.cmd_seat = function(msg) {
		var seat = msg.getArgs().join(' ');
		if (seat in electorates) {
			var e = electorates[seat];
			generate_seat(msg, e, seat);
		} else {
			msg.reply("No such seat!");
		}
	}

	function callback_OnlineElectorate(obj) {
		var e = obj.Erads.Elections.Election.Chambers.Chamber.Electorates.Electorate;
		var msg = "Results for " + e.LongName + "(" + e.StateCategory.CategoryCode + "): ";
		var cand = e.Candidates.Candidate;
		for (var i = 0; i < cand.length; i++) {
			if (cand[i].BallotPosition.startsWith("9")) continue;
			msg += cand[i].Party.PartyCode + ": " + cand[i].PredictedPrimary.Percent + "% (" +
				cand[i].PredictedPrimary.Swing + "% swing)" + ", ";
		}
		msg += e.CountedPct + "% counted, " + e.NoOfPollingPlaces.Reporting2CP + "(2CP)," + e.NoOfPollingPlaces.ReportingPrimary + "(Primary)/" + e.NoOfPollingPlaces.Total + " booths counted.";
		if (e.IsKeySeat) {
			msg += " Key Seat!";
		}
		cached_msg.say(msg);

	}

	e.cmd_primary = function(msg) {
		cached_msg = msg;
		var seat = msg.getArgs().join(' ');
		if (seat in electorates) {
			var id = electorates[seat].ElectorateCode;
			var url = ABC_SEAT_PRIMARIES.replace('{code}', id);
			var name = 'callback_OnlineElectorate' + id;
			request({
				'uri': url
			}, function (error, response, body) {
				if (!error && response.statusCode == 200) {
					try {
						eval(body.replace(name, 'callback_OnlineElectorate'));
					} catch (e) {
						console.log(e, e.message);
					}
				} else {
					console.log(error);
					console.log(body);
				}
			});
		} else {
			msg.reply("No such seat!");
		}
	}

	function callback_OnlinePartyGroupTrends(obj) {
		GROUP_TRENDS = obj.Erads.Elections.Election.Chambers.Chamber.Trends.Trend;
		var trend = GROUP_TRENDS[0];
		var parties = trend.PartyGroups.PartyGroup;
		var msg = "Current seat counts: ";
		for (var i = 0; i < parties.length; i++) {
			var p = parties[i];
			msg += p.PartyGroupCode.replace("L/NP", "LNP") + ": " + p.SeatsExcludingEarlyVotes.Won + " won, "
				if (p.SeatsExcludingEarlyVotes.Likely > 0)
					msg += p.SeatsExcludingEarlyVotes.Likely + " likely - ";
			msg += p.PredictedPrimary.Percent + "% primary, (" + p.PredictedPrimary.Swing + "% swing), ";
		}
		var pred = trend.PredictionStringSuppressed;
		if (pred) {
			msg += "AEC preliminary prediction: " + pred;
		} else {
			msg += "AEC prediction: " + trend.PredictionString;
		}
		msg += ". " + trend.CountedPct + "% counted.";
		if (captureOPGT) {
			captureOPGT = false;
			OPGT_poll_callback(msg);
		} else {
			lastOPGT = msg;
			cached_msg.say(msg);
		}
	}

	function OPGT_poll_callback(msg) {
		if (firstRun) {
			lastOPGT = msg;
			firstRun = false;
			return;
		}
		if (msg != lastOPGT) {
			cached_msg.say("Update: " + msg);
		}
	}

	e.cmd_seats = function(msg) {
		if (msg)
			cached_msg = msg;
		request({
			'uri': ABC_SEAT_STATUS
		}, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				try {
					eval(body);
				} catch(e) {
					console.log(e, e.message);
				}
			} else {
				console.log(error);
				console.log(body);
			}
		});
	}

	var id3 = setInterval(function() {
		captureOPGT = true;
		e.cmd_seats(false);
	}, 1000 * 60 * 5);

})(module.exports);
<|endoftext|>