<commit_before>/**
 * CUSTOMIZED STANDBY WIDGET FOR JQUERY
 *
 * Created by
 * ----------
 * Name 	- SANDEEP KANANGATT
 * Email 	- sandeepsuvit@gmail.com
 * Website 	- www.dotedlabs.com
 *
 * This widget is a customized Standby widget with a loader image. This also
 * helps the user to display text content dynamically when they want to show the
 * loader for any particular event.
 *
 * This standby loader can be invoked in the following ways.
 *
 * Note: The loader has been default set to work on the "body" on the html
 * pages.
 *
 * ----------------------------------------------------------------------------
 * How to use this widget:
 * ----------------------------------------------------------------------------
 * 1. standbyLoader.show(); -> Displays the loader with the default text "Please
 * wait...".
 *
 * 2. standbyLoader.show({text: "my message"}); -> Displays the loader with the
 * parameterized string.
 *
 * 3. standbyLoader.hide(); -> Hides the loader and defaults the loader text to
 * "Please wait...".
 *
 */

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

// Path for the image to show on the loader
var standbyLoader_image_path = "ajaxLoader.gif";

// Default text to show on the loader
var standbyLoader_default_text = "Please wait...";

// Globally set variables
var standbyLoader = new Object();

// Utility functions for string operations
var StringUtilsFunctions = {
	// Check if the string is empty
	isEmpty : function(param) {
		if (param === undefined) {
			return true;
		} else {
			if (param == null)
				return true;
			if (param.length < 0)
				return true;
			if (param.length == 0)
				return true;
			return false;
		}
	},

	// Capitalizes the first letter of a string
	capitaliseFirstLetter : function(param) {
		return param.charAt(0).toUpperCase() + param.slice(1);
	}
};

$(document).ready(
		function() {

			// Appending the loader widget
			standbyLoader = {

				// Loader text reference
				loaderText : standbyLoader_default_text,

				// Loader image reference
				loaderImage : standbyLoader_image_path,

				// Show the overlay
				show : function(param) {
					// If the overlay is already present, remove it before
					// showing the overlay again.
					if ($("#standbyLoader-overlay").size() > 0) {
						// Remove the overlay
						this.hide();
					}

					// Check if the text parameter is passed
					if (param === undefined) {
						// Set all to its default values
						this.revertToDefaultText();

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					} else {
						// Check for loader text
						if (!StringUtilsFunctions.isEmpty(param.text)) {
							this.loaderText = param.text;
							this.changeText(this.loaderText);
						} else {
							this.revertToDefaultText();
						}

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					}

				},

				// Remove the overlay
				hide : function() {
					this.revertToDefaultText();

					// Hide the image
					$("#standbyLoader-loading").fadeOut();

					// Hide the text
					$("#standbyLoader-loading-text").fadeOut();

					// Check If the overlay is already presents
					if ($("#standbyLoader-overlay").size() != 0) {
						$("#standbyLoader-overlay").slideUp(function() {
							$("#standbyLoader-overlay").remove();
						});
					}
				},

				// Change the default message to custom message
				changeText : function(param) {
					if (!StringUtilsFunctions.isEmpty(param)) {
						this.loaderText = StringUtilsFunctions
								.capitaliseFirstLetter(param);
					} else {
						this.revertToDefaultText();
					}
				},

				// Revert back the custom message to the default message
				revertToDefaultText : function() {
					this.loaderText = standbyLoader_default_text;
				},

				// Content to display on the loader
				getContentToDisplay : function() {
					// Show the image
					$("#standbyLoader-loading").fadeIn();

					// Show the text
					$("#standbyLoader-loading-text").fadeIn();

					return '
'
							+ ""
							+ "
"
							+ this.loaderText + "
" + '
';
				}
			};

		});
<commit_msg>Update standbyLoader.js<commit_after>/**
 * CUSTOMIZED STANDBY WIDGET FOR JQUERY
 *
 * Created by
 * ----------
 * Name 	- SANDEEP KANANGATT
 * Email 	- sandeepsuvit@gmail.com
 * Website 	- www.dotedlabs.com
 *
 * This widget is a customized Standby widget with a loader image. This also
 * helps the user to display text content dynamically when the user wants to
 * show the loader for any particular event.
 *
 * This standby loader can be invoked in the following ways.
 *
 * Note: The loader has been default set to work on the "body" of the html
 * pages.
 *
 * ----------------------------------------------------------------------------
 * How to use this widget:
 * ----------------------------------------------------------------------------
 * 1. standbyLoader.show(); -> Displays the loader with the default text "Please
 * wait...".
 *
 * 2. standbyLoader.show({text: "my message"}); -> Displays the loader with the
 * parameterized string.
 *
 * 3. standbyLoader.hide(); -> Hides the loader and defaults the loader text to
 * "Please wait...".
 *
 */

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

// Path for the image to show on the loader
var standbyLoader_image_path = "ajaxLoader.gif";

// Default text to show on the loader
var standbyLoader_default_text = "Please wait...";

// Globally set variables
var standbyLoader = new Object();

// Utility functions for string operations
var StringUtilsFunctions = {
	// Check if the string is empty
	isEmpty : function(param) {
		if (param === undefined) {
			return true;
		} else {
			if (param == null)
				return true;
			if (param.length < 0)
				return true;
			if (param.length == 0)
				return true;
			return false;
		}
	},

	// Capitalizes the first letter of a string
	capitaliseFirstLetter : function(param) {
		return param.charAt(0).toUpperCase() + param.slice(1);
	}
};

$(document).ready(
		function() {

			// Appending the loader widget
			standbyLoader = {

				// Loader text reference
				loaderText : standbyLoader_default_text,

				// Loader image reference
				loaderImage : standbyLoader_image_path,

				// Show the overlay
				show : function(param) {
					// If the overlay is already present, remove it before
					// showing the overlay again.
					if ($("#standbyLoader-overlay").size() > 0) {
						// Remove the overlay
						this.hide();
					}

					// Check if the text parameter is passed
					if (param === undefined) {
						// Set all to its default values
						this.revertToDefaultText();

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					} else {
						// Check for loader text
						if (!StringUtilsFunctions.isEmpty(param.text)) {
							this.loaderText = param.text;
							this.changeText(this.loaderText);
						} else {
							this.revertToDefaultText();
						}

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					}

				},

				// Remove the overlay
				hide : function() {
					this.revertToDefaultText();

					// Hide the image
					$("#standbyLoader-loading").fadeOut();

					// Hide the text
					$("#standbyLoader-loading-text").fadeOut();

					// Check If the overlay is already presents
					if ($("#standbyLoader-overlay").size() != 0) {
						$("#standbyLoader-overlay").slideUp(function() {
							$("#standbyLoader-overlay").remove();
						});
					}
				},

				// Change the default message to custom message
				changeText : function(param) {
					if (!StringUtilsFunctions.isEmpty(param)) {
						this.loaderText = StringUtilsFunctions
								.capitaliseFirstLetter(param);
					} else {
						this.revertToDefaultText();
					}
				},

				// Revert back the custom message to the default message
				revertToDefaultText : function() {
					this.loaderText = standbyLoader_default_text;
				},

				// Content to display on the loader
				getContentToDisplay : function() {
					// Show the image
					$("#standbyLoader-loading").fadeIn();

					// Show the text
					$("#standbyLoader-loading-text").fadeIn();

					return '
'
							+ ""
							+ "
"
							+ this.loaderText + "
" + '
';
				}
			};

		});
<|endoftext|>


<commit_before>/**
* @author mrdoob / http://mrdoob.com/
*/

THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {

	var mode;

	function setMode( value ) {

		mode = value;

	}

	function render( start, count ) {

		_gl.drawArrays( mode, start, count );

		_infoRender.calls ++;
		_infoRender.vertices += count;
		if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;

	}

	function renderInstances( geometry ) {

		var extension = extensions.get( 'ANGLE_instanced_arrays' );

		if ( extension === null ) {

			console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
			return;

		}

		var position = geometry.attributes.position;

		if ( position instanceof THREE.InterleavedBufferAttribute ) {

			var count = position.data.count;

			extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );

			_infoRender.calls ++;
			_infoRender.vertices += count * geometry.maxInstancedCount;
			if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;

		} else {

			var count = position.count;

			extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );

			_infoRender.calls ++;
			_infoRender.vertices += count * geometry.maxInstancedCount;
			if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;

		}

	}

	this.setMode = setMode;
	this.render = render;
	this.renderInstances = renderInstances;

};
<commit_msg>put statistics calculation out of the conditional<commit_after>/**
* @author mrdoob / http://mrdoob.com/
*/

THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {

	var mode;

	function setMode( value ) {

		mode = value;

	}

	function render( start, count ) {

		_gl.drawArrays( mode, start, count );

		_infoRender.calls ++;
		_infoRender.vertices += count;
		if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;

	}

	function renderInstances( geometry ) {

		var extension = extensions.get( 'ANGLE_instanced_arrays' );

		if ( extension === null ) {

			console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
			return;

		}

		var position = geometry.attributes.position;

		var count = 0;

		if ( position instanceof THREE.InterleavedBufferAttribute ) {

			count = position.data.count;

			extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );

		} else {

			count = position.count;

			extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );

		}

		_infoRender.calls ++;
		_infoRender.vertices += count * geometry.maxInstancedCount;
		if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;

	}

	this.setMode = setMode;
	this.render = render;
	this.renderInstances = renderInstances;

};
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import * as actionTypes from '../actionTypes';

const isOpen = (state = false, action) => {
  switch (action.type) {
    case actionTypes.STICKY_HAS_SHOWN:
      return true;
    case actionTypes.STICKY_HAS_HIDDEN:
      return false;
    default:
      return state;
  }
};

const timeout = (state = null, action) => {
  switch (action.type) {
    case actionTypes.STICKY_HAS_SHOWN:
      return action.timeout;
    case actionTypes.STICKY_UPDATE_TIMEOUT:
      return action.timeout;
    case actionTypes.STICKY_HAS_HIDDEN:
      return null;
    default:
      return state;
  }
};

const closedByUser = (state = false, action) => {
  switch (action.type) {
    case actionTypes.STICKY_HAS_HIDDEN:
      return action.closedByUser;
    default:
      return state;
  }
};

export default combineReducers({
  isOpen,
  timeout,
  closedByUser,
});
<commit_msg>Fixes reducer export<commit_after>import { combineReducers } from 'redux';
import * as actionTypes from '../actionTypes';

const isOpen = (state = false, action) => {
  switch (action.type) {
    case actionTypes.STICKY_HAS_SHOWN:
      return true;
    case actionTypes.STICKY_HAS_HIDDEN:
      return false;
    default:
      return state;
  }
};

const timeout = (state = null, action) => {
  switch (action.type) {
    case actionTypes.STICKY_HAS_SHOWN:
      return action.timeout;
    case actionTypes.STICKY_UPDATE_TIMEOUT:
      return action.timeout;
    case actionTypes.STICKY_HAS_HIDDEN:
      return null;
    default:
      return state;
  }
};

const closedByUser = (state = false, action) => {
  switch (action.type) {
    case actionTypes.STICKY_HAS_HIDDEN:
      return action.closedByUser;
    default:
      return state;
  }
};

export default () =>
  combineReducers({
    isOpen,
    timeout,
    closedByUser,
  });
<|endoftext|>


<commit_before>var requirejs = require('requirejs');

requirejs.config({
    nodeRequire: require
});

requirejs(['src/batteryListener', 'src/workshopLoader'],function (batteryListener, workshop) {

        var autonomy = require('../ardrone-autonomy'),
            mission = autonomy.createMission(),
            arDroneConstants = require('ar-drone/lib/constants');

        batteryListener.listen(mission._client);

        // Connect and configure the drone
        mission.client().config('control:outdoor', 0);
        mission.client().config('control:altitude_max', 3000);
        mission.client().config('control:altitude_min', 0);
        mission.client().config('detect:detect_type', 12);
        mission.client().config('general:navdata_demo', true);

        workshop.runWith(mission);

        mission.run(function (err, result) {
            if (err) {

                console.log("Oops, something bad happened: %s", err.message);
                console.log('SecurityBox ', err.securityBox);
                console.log('Goal ', err.goal);

                mission.client().stop();
                mission.client().land();

                setTimeout(function () {
                    process.exit(0);
                }, 1000);
            } else {
                console.log("We are done!");
                process.exit(0);
            }
        });
    }
);<commit_msg>add try catch on workshoploader<commit_after>var requirejs = require('requirejs');

requirejs.config({
    nodeRequire: require
});

requirejs(['src/batteryListener', 'src/workshopLoader'], function (batteryListener, workshop) {

        var autonomy = require('../ardrone-autonomy'),
            mission = autonomy.createMission(),
            arDroneConstants = require('ar-drone/lib/constants');

        batteryListener.listen(mission._client);

        mission.client().config('general:navdata_demo', 'TRUE');

        // Connect and configure the drone
        mission.client().config('control:outdoor', 0);
        mission.client().config('control:altitude_max', 3000);
        mission.client().config('control:altitude_min', 0);
        mission.client().config('detect:detect_type', 12);

        try {
            workshop.runWith(mission);
        }
        catch (e) {
            console.log(e.message);
        }

        mission.run(function (err, result) {
            if (err) {

                console.log("Oops, something bad happened: %s", err.message);
                console.log('SecurityBox ', err.securityBox);
                console.log('Goal ', err.goal);

                mission.client().stop();
                mission.client().land();

                setTimeout(function () {
                    process.exit(0);
                }, 1000);
            } else {
                console.log("We are done!");
                process.exit(0);
            }
        });
    }
);<|endoftext|>


<commit_before>/* global $, cy, notify, window, document */

(function(){

  var assign = function( tgt ){
    let args = arguments;

    for( let i = 1; i < args.length; i++ ){
      let obj = args[ i ];

      if( obj == null ){ continue; }

      let keys = Object.keys( obj );

      for( let j = 0; j < keys.length; j++ ){
        let k = keys[j];

        tgt[ k ] = obj[ k ];
      }
    }

    return tgt;
  };

  var tests = {}; // name => setup
  function test(options){
    var option = document.createElement('option');

    option.value = options.name;
    option.innerHTML = options.displayName;

    $("#test-type-select").appendChild( option );

    tests[options.name] = assign({}, {
      setup: function(){},
      teardown: function(){},
      description: ""
    }, options);
  }
  test({
    name: "none",
    displayName: "None",
    description: "Not currently running any test"
  });

  var currentTest;
  for(var i in tests){
    currentTest = tests[i];
    break;
  }

  $('#note').addEventListener('click', function(){
    $('#note').style.display = 'none';
  });

  $("#test-type-select").addEventListener('change', function(){
    currentTest.teardown();

    var name = $("#test-type-select").value;
    currentTest = tests[name];

    notify( currentTest.displayName, currentTest.description );

    currentTest.setup();
  });

  function randomColor(){
    function randCh(){
      return Math.round( Math.random() * 255 );
    }

    return 'rgb(' + randCh() + ', ' + randCh() + ', ' + randCh() + ')';
  }

  test({
    name: "randomEdgeColors",
    displayName: "Random edge colours",
    description: "Set each edge to a random colour",
    setup: function(){
      cy.edges().each(function( ele ){
        ele.css( 'line-color', randomColor() );
      });
    },
    teardown: function(){
      cy.edges().removeCss();
    }
  });

  test({
    name: "bypassOnClick",
    displayName: "Bypass on click",
    description: "Set nodes to red and edges to orange on click",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css("background-color", "red");

        this.css({
          lineColor: "orange",
          targetArrowColor: "orange",
          sourceArrowColor: "orange"
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "shapeOnClick",
    displayName: "Squares on click",
    description: "Set nodes to squares and edge arrows to squares on click",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css({
          shape: "rectangle",
          targetArrowShape: "square",
          sourceArrowShape: "square"
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "positionOnClick",
    displayName: "Random position on click",
    description: "Put node to random position on click",
    setup: function(){

      var $cy = $("#cytoscape");

      var w = $cy.width();
      var h = $cy.height();

      cy.nodes().bind("click", function(){
        var node = this;
        var padding = 50;

        var p2 = {
          x: Math.random() * (w - padding) + padding,
          y: Math.random() * (h - padding) + padding
        };

        node.animate({
          position: p2
        },
        {
          duration: 1000
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click");
    }
  });

  test({
    name: "labelOnClick",
    displayName: "Label on click",
    description: "Change label on click",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css({
          content: "clicked"
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "labelWithWeight",
    displayName: "Labels with weight",
    description: "Show weight in element labels",
    setup: function(){
      cy.style()
        .selector('*')
          .css({
            'content': 'data(weight)'
          })

        .update()
      ;
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "hideOnClick",
    displayName: "visibility:hidden on click",
    description: "visibility:hidden on nodes and edges when clicked",
    setup: function(){
      cy.elements().bind("click", function(){
        this.style('visibility', 'hidden');
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "hideOnClick2",
    displayName: "display:none on click",
    description: "display:none on nodes and edges when clicked",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css("display", "none");
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "hideOnClick3",
    displayName: "opacity:0 on click",
    description: "opacity:0 on nodes and edges when clicked",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css("opacity", 0);
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "growOnClick",
    displayName: "Coloured and sized",
    description: "Make nodes grow/shrink and change colour on click",
    setup: function(){
      cy.nodes().bind("click", function(){
        function rch(){
          return Math.round( Math.random() * 255 );
        }

        function rcolor(){
          return "rgb(" + rch() + "," + rch() + "," + rch() + ")";
        }

        function rsize(){
          return 5 + Math.round( Math.random() * 50 );
        }

        var size = rsize();

        this.stop().animate({
          css: {
            backgroundColor: rcolor(),
            height: size,
            width: size
          }
        }, {
          duration: 1000
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").removeCss();
    }
  });

  test({
    name: "colourThenGrow",
    displayName: "Orange, delay, grow, reset",
    description: "Click nodes to trigger",
    setup: function(){
      cy.nodes().bind("click", function(){
        var self = this;
        self
          .stop(true)
          .animate({
            css: {
              backgroundColor: "orange"
            }
          },
          {
            duration: 1000
          })
          .delay(1000)
          .animate({
            css: {
              height: 50,
              width: 50
            }
          },
          {
            duration: 1000
          }).delay(1000, function(){
            self.removeCss();
          });
      });

      cy.edges().bind("click", function(){
        this
          .stop(true)
          .animate({
            bypass: {
              lineColor: "orange",
              targetArrowColor: "orange",
              sourceArrowColor: "orange"
            }
          },
          {
            duration: 1000
          })
          .delay(1000)
          .animate({
            css: {
              width: 7
            }
          },
          {
            duration: 1000
          });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").removeCss();
    }
  });

  test({
    name: "redAndGrow",
    displayName: "Blue and grow in parallel",
    description: "Click nodes to trigger",
    setup: function(){
      cy.nodes().bind("click", function(){
        this
          .stop(true)
          .animate({
            css: {
              backgroundColor: "blue"
            }
          },
          {
            duration: 1000
          })
          .animate({
            css: {
              height: 50,
              width: 50
            }
          },
          {
            duration: 1000,
            queue: false
          });
      });
    },
    teardown: function(){
      cy.nodes().unbind("click").removeCss();
    }
  });

  test({
    name: "bigRedOnClick",
    displayName: "Big & red",
    description: "Click background to toggle",
    setup: function(){
      var on = false;

      cy.bind("click", function(){

        if( !on ){
          cy.nodes().stop().animate({
            css: {
              backgroundColor: "red",
              height: 50,
              width: 50
            }
          },
          {
            duration: 2000
          });

          on = true;
        } else {
          cy.nodes().stop().removeCss();
          on = false;
        }

      });
    },
    teardown: function(){
      cy.unbind("click");
      cy.nodes().removeCss();
    }
  });

  test({
    name: "bigRedOnClickE",
    displayName: "Big & red edges",
    description: "Click background to toggle",
    setup: function(){
      var on = false;

      cy.bind("click", function(){

        if( !on ){
          cy.edges().stop().animate({
            css: {
              lineColor: "red",
              targetArrowColor: "red",
              sourceArrowColor: "red",
              width: 10
            }
          },
          {
            duration: 2000
          });

          on = true;
        } else {
          cy.edges().stop().removeCss();
          on = false;
        }

      });
    },
    teardown: function(){
      cy.unbind("click");
      cy.edges().removeCss();
    }
  });

  test({
    name: "fancyStyle",
    displayName: "Set a fancy visual style",
    description: "Change the visual style and make sure it takes effect",
    setup: function(){

      cy.style()
        .resetToDefault()
        .selector("node")
          .css({
            shape: "rectangle",
            backgroundColor: "lightblue",
            borderColor: "black",
            borderWidth: 1,
            width: "mapData(weight, 20, 100, 20, 100)",
            height: 20,
            labelFontWeight: "normal",
            labelFontSize: "0.75em",
            content: "data(weight)",
            textValign: "center",
            textHalign: "center"
          })
        .selector("edge")
          .css({
            lineColor: "mapData(weight, 0, 100, blue, red)",
            targetArrowShape: "triangle"
          })
        .selector("edge:selected")
          .css({
            width: 3
          })
        .selector("node:selected")
          .css({
            borderWidth: 3
          })
        .update()
      ;
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "strStyle",
    displayName: "Set a string stylesheet",
    description: "Change the visual style and make sure it takes effect",
    setup: function(){
      cy.style('node { background-color: blue; }');
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "addStyle",
    displayName: "Add to current stylesheet",
    description: "Add to the visual style and make sure it takes effect",
    setup: function(){
      cy.style()
        .selector('node')
          .css({
            'background-color': 'blue'
          })

        .update()
      ;
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "redTap",
    displayName: "Mouseover nodes to toggle red bypass",
    description: "..",
    setup: function(){
      var on = {}; // id => true | false

      cy.on('mouseover', 'node', function(){
        if( on[ this.id() ] ){
          this.removeCss();
          on[ this.id() ] = false;
        } else {
          this.css('background-color', 'red');
          on[ this.id() ] = true;
        }
      });
    },

    teardown: function(){
      cy.off('mouseover', 'node');
    }
  });

  test({
    name: "multAni",
    displayName: "Multiple simultaneous animations",
    description: "Tap node to start",
    setup: function(){
      cy.on('tap', 'node', function(e){
        var n = e.target;
        var p = n.position();

        var a1 = n.animation({
          style: {
            'background-color': 'cyan'
          },
          position: {
            x: p.x + 100,
            y: p.y + 100
          },
          duration: 1000
        });

        a1.play();

        var a2 = n.animation({
          style: {
            'width': 60,
            'height': 60
          },
          duration: 1000
        });

        a2.play().promise('complete').then(function(){
          return a2.rewind().reverse().play().promise('complete');
        }).then(function(){
          n.removeStyle();
        });
      });
    },

    teardown: function(){
      cy.off('tap', 'node');
    }
  });

  var faded = false;

  test({
    name: "fadeAni",
    displayName: "Animate element opacity",
    description: "Tap background to toggle",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        faded = !faded;

        cy.elements().animate({
          style: {
            'opacity': faded ? 0.5 : 1
          },
          duration: 1000
        });
      });
    },

    teardown: function(){
      cy.off('tap');
      cy.elements().removeStyle();
    }
  });

  test({
    name: "pngblob",
    displayName: "Export big PNG image via promise",
    description: "Tap background to save the file",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        console.time('pngblob');

        var save = function(blob){
          console.timeEnd('pngblob');

          saveAs(blob, 'blob-promise.png');
        };

        var N = 10000;

        cy.png({ output: 'blob-promise', maxWidth: N, maxHeight: N }).then(save);
      });
    },

    teardown: function(){
      cy.off('tap');
    }
  });

  test({
    name: "png64",
    displayName: "Export big PNG image via base64 blob",
    description: "Tap background to save the file",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        console.time('png64');

        var save = function(blob){
          saveAs(blob, 'base64-blob.png');
        };

        var N = 10000;

        var blob = cy.png({ output: 'blob', maxWidth: N, maxHeight: N });

        console.timeEnd('png64');

        save( blob );
      });
    },

    teardown: function(){
      cy.off('tap');
    }
  });

  test({
    name: "randomLayoutAni",
    displayName: "Animate random layout",
    description: "Tap background to run layout",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        cy.layout({
          name: 'random',
          animate: true,
          animationDuration: 1000
        }).run();
      });
    },

    teardown: function(){
      cy.off('tap');
    }
  });
})();
<commit_msg>Fix random position test on debug page<commit_after>/* global $, cy, notify, window, document */

(function(){

  var assign = function( tgt ){
    let args = arguments;

    for( let i = 1; i < args.length; i++ ){
      let obj = args[ i ];

      if( obj == null ){ continue; }

      let keys = Object.keys( obj );

      for( let j = 0; j < keys.length; j++ ){
        let k = keys[j];

        tgt[ k ] = obj[ k ];
      }
    }

    return tgt;
  };

  var tests = {}; // name => setup
  function test(options){
    var option = document.createElement('option');

    option.value = options.name;
    option.innerHTML = options.displayName;

    $("#test-type-select").appendChild( option );

    tests[options.name] = assign({}, {
      setup: function(){},
      teardown: function(){},
      description: ""
    }, options);
  }
  test({
    name: "none",
    displayName: "None",
    description: "Not currently running any test"
  });

  var currentTest;
  for(var i in tests){
    currentTest = tests[i];
    break;
  }

  $('#note').addEventListener('click', function(){
    $('#note').style.display = 'none';
  });

  $("#test-type-select").addEventListener('change', function(){
    currentTest.teardown();

    var name = $("#test-type-select").value;
    currentTest = tests[name];

    notify( currentTest.displayName, currentTest.description );

    currentTest.setup();
  });

  function randomColor(){
    function randCh(){
      return Math.round( Math.random() * 255 );
    }

    return 'rgb(' + randCh() + ', ' + randCh() + ', ' + randCh() + ')';
  }

  test({
    name: "randomEdgeColors",
    displayName: "Random edge colours",
    description: "Set each edge to a random colour",
    setup: function(){
      cy.edges().each(function( ele ){
        ele.css( 'line-color', randomColor() );
      });
    },
    teardown: function(){
      cy.edges().removeCss();
    }
  });

  test({
    name: "bypassOnClick",
    displayName: "Bypass on click",
    description: "Set nodes to red and edges to orange on click",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css("background-color", "red");

        this.css({
          lineColor: "orange",
          targetArrowColor: "orange",
          sourceArrowColor: "orange"
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "shapeOnClick",
    displayName: "Squares on click",
    description: "Set nodes to squares and edge arrows to squares on click",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css({
          shape: "rectangle",
          targetArrowShape: "square",
          sourceArrowShape: "square"
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "positionOnClick",
    displayName: "Random position on click",
    description: "Put node to random position on click",
    setup: function(){
      var w = cy.width();
      var h = cy.height();

      cy.nodes().bind("click", function(){
        var node = this;
        var padding = 50;

        var p2 = {
          x: Math.random() * (w - padding) + padding,
          y: Math.random() * (h - padding) + padding
        };

        node.animate({
          position: p2
        },
        {
          duration: 1000
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click");
    }
  });

  test({
    name: "labelOnClick",
    displayName: "Label on click",
    description: "Change label on click",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css({
          content: "clicked"
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "labelWithWeight",
    displayName: "Labels with weight",
    description: "Show weight in element labels",
    setup: function(){
      cy.style()
        .selector('*')
          .css({
            'content': 'data(weight)'
          })

        .update()
      ;
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "hideOnClick",
    displayName: "visibility:hidden on click",
    description: "visibility:hidden on nodes and edges when clicked",
    setup: function(){
      cy.elements().bind("click", function(){
        this.style('visibility', 'hidden');
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "hideOnClick2",
    displayName: "display:none on click",
    description: "display:none on nodes and edges when clicked",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css("display", "none");
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "hideOnClick3",
    displayName: "opacity:0 on click",
    description: "opacity:0 on nodes and edges when clicked",
    setup: function(){
      cy.elements().bind("click", function(){
        this.css("opacity", 0);
      });
    },
    teardown: function(){
      cy.elements().unbind("click").css("*", "");
    }
  });

  test({
    name: "growOnClick",
    displayName: "Coloured and sized",
    description: "Make nodes grow/shrink and change colour on click",
    setup: function(){
      cy.nodes().bind("click", function(){
        function rch(){
          return Math.round( Math.random() * 255 );
        }

        function rcolor(){
          return "rgb(" + rch() + "," + rch() + "," + rch() + ")";
        }

        function rsize(){
          return 5 + Math.round( Math.random() * 50 );
        }

        var size = rsize();

        this.stop().animate({
          css: {
            backgroundColor: rcolor(),
            height: size,
            width: size
          }
        }, {
          duration: 1000
        });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").removeCss();
    }
  });

  test({
    name: "colourThenGrow",
    displayName: "Orange, delay, grow, reset",
    description: "Click nodes to trigger",
    setup: function(){
      cy.nodes().bind("click", function(){
        var self = this;
        self
          .stop(true)
          .animate({
            css: {
              backgroundColor: "orange"
            }
          },
          {
            duration: 1000
          })
          .delay(1000)
          .animate({
            css: {
              height: 50,
              width: 50
            }
          },
          {
            duration: 1000
          }).delay(1000, function(){
            self.removeCss();
          });
      });

      cy.edges().bind("click", function(){
        this
          .stop(true)
          .animate({
            bypass: {
              lineColor: "orange",
              targetArrowColor: "orange",
              sourceArrowColor: "orange"
            }
          },
          {
            duration: 1000
          })
          .delay(1000)
          .animate({
            css: {
              width: 7
            }
          },
          {
            duration: 1000
          });
      });
    },
    teardown: function(){
      cy.elements().unbind("click").removeCss();
    }
  });

  test({
    name: "redAndGrow",
    displayName: "Blue and grow in parallel",
    description: "Click nodes to trigger",
    setup: function(){
      cy.nodes().bind("click", function(){
        this
          .stop(true)
          .animate({
            css: {
              backgroundColor: "blue"
            }
          },
          {
            duration: 1000
          })
          .animate({
            css: {
              height: 50,
              width: 50
            }
          },
          {
            duration: 1000,
            queue: false
          });
      });
    },
    teardown: function(){
      cy.nodes().unbind("click").removeCss();
    }
  });

  test({
    name: "bigRedOnClick",
    displayName: "Big & red",
    description: "Click background to toggle",
    setup: function(){
      var on = false;

      cy.bind("click", function(){

        if( !on ){
          cy.nodes().stop().animate({
            css: {
              backgroundColor: "red",
              height: 50,
              width: 50
            }
          },
          {
            duration: 2000
          });

          on = true;
        } else {
          cy.nodes().stop().removeCss();
          on = false;
        }

      });
    },
    teardown: function(){
      cy.unbind("click");
      cy.nodes().removeCss();
    }
  });

  test({
    name: "bigRedOnClickE",
    displayName: "Big & red edges",
    description: "Click background to toggle",
    setup: function(){
      var on = false;

      cy.bind("click", function(){

        if( !on ){
          cy.edges().stop().animate({
            css: {
              lineColor: "red",
              targetArrowColor: "red",
              sourceArrowColor: "red",
              width: 10
            }
          },
          {
            duration: 2000
          });

          on = true;
        } else {
          cy.edges().stop().removeCss();
          on = false;
        }

      });
    },
    teardown: function(){
      cy.unbind("click");
      cy.edges().removeCss();
    }
  });

  test({
    name: "fancyStyle",
    displayName: "Set a fancy visual style",
    description: "Change the visual style and make sure it takes effect",
    setup: function(){

      cy.style()
        .resetToDefault()
        .selector("node")
          .css({
            shape: "rectangle",
            backgroundColor: "lightblue",
            borderColor: "black",
            borderWidth: 1,
            width: "mapData(weight, 20, 100, 20, 100)",
            height: 20,
            labelFontWeight: "normal",
            labelFontSize: "0.75em",
            content: "data(weight)",
            textValign: "center",
            textHalign: "center"
          })
        .selector("edge")
          .css({
            lineColor: "mapData(weight, 0, 100, blue, red)",
            targetArrowShape: "triangle"
          })
        .selector("edge:selected")
          .css({
            width: 3
          })
        .selector("node:selected")
          .css({
            borderWidth: 3
          })
        .update()
      ;
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "strStyle",
    displayName: "Set a string stylesheet",
    description: "Change the visual style and make sure it takes effect",
    setup: function(){
      cy.style('node { background-color: blue; }');
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "addStyle",
    displayName: "Add to current stylesheet",
    description: "Add to the visual style and make sure it takes effect",
    setup: function(){
      cy.style()
        .selector('node')
          .css({
            'background-color': 'blue'
          })

        .update()
      ;
    },

    teardown: function(){
      var stylesheet = window.defaultSty;

      cy.style( stylesheet );
    }
  });

  test({
    name: "redTap",
    displayName: "Mouseover nodes to toggle red bypass",
    description: "..",
    setup: function(){
      var on = {}; // id => true | false

      cy.on('mouseover', 'node', function(){
        if( on[ this.id() ] ){
          this.removeCss();
          on[ this.id() ] = false;
        } else {
          this.css('background-color', 'red');
          on[ this.id() ] = true;
        }
      });
    },

    teardown: function(){
      cy.off('mouseover', 'node');
    }
  });

  test({
    name: "multAni",
    displayName: "Multiple simultaneous animations",
    description: "Tap node to start",
    setup: function(){
      cy.on('tap', 'node', function(e){
        var n = e.target;
        var p = n.position();

        var a1 = n.animation({
          style: {
            'background-color': 'cyan'
          },
          position: {
            x: p.x + 100,
            y: p.y + 100
          },
          duration: 1000
        });

        a1.play();

        var a2 = n.animation({
          style: {
            'width': 60,
            'height': 60
          },
          duration: 1000
        });

        a2.play().promise('complete').then(function(){
          return a2.rewind().reverse().play().promise('complete');
        }).then(function(){
          n.removeStyle();
        });
      });
    },

    teardown: function(){
      cy.off('tap', 'node');
    }
  });

  var faded = false;

  test({
    name: "fadeAni",
    displayName: "Animate element opacity",
    description: "Tap background to toggle",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        faded = !faded;

        cy.elements().animate({
          style: {
            'opacity': faded ? 0.5 : 1
          },
          duration: 1000
        });
      });
    },

    teardown: function(){
      cy.off('tap');
      cy.elements().removeStyle();
    }
  });

  test({
    name: "pngblob",
    displayName: "Export big PNG image via promise",
    description: "Tap background to save the file",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        console.time('pngblob');

        var save = function(blob){
          console.timeEnd('pngblob');

          saveAs(blob, 'blob-promise.png');
        };

        var N = 10000;

        cy.png({ output: 'blob-promise', maxWidth: N, maxHeight: N }).then(save);
      });
    },

    teardown: function(){
      cy.off('tap');
    }
  });

  test({
    name: "png64",
    displayName: "Export big PNG image via base64 blob",
    description: "Tap background to save the file",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        console.time('png64');

        var save = function(blob){
          saveAs(blob, 'base64-blob.png');
        };

        var N = 10000;

        var blob = cy.png({ output: 'blob', maxWidth: N, maxHeight: N });

        console.timeEnd('png64');

        save( blob );
      });
    },

    teardown: function(){
      cy.off('tap');
    }
  });

  test({
    name: "randomLayoutAni",
    displayName: "Animate random layout",
    description: "Tap background to run layout",
    setup: function(){
      cy.on('tap', function(e){
        if( e.target !== cy ){ return; }

        cy.layout({
          name: 'random',
          animate: true,
          animationDuration: 1000
        }).run();
      });
    },

    teardown: function(){
      cy.off('tap');
    }
  });
})();
<|endoftext|>


<commit_before>;(function ($, _, window, document, undefined) {
    "use strict";

    var StateProvider = function( options ) {
        options = _({}).extend(options);
        this.state = _({}).extend(options.initial_state);
    };

    _.extend(StateProvider.prototype, {
        get: function( key, default_value ) {
            return _(this.state[key]).isUndefined() ? default_value : this.state[key];
        },

        set: function( key, value ) {
            var new_value = JSON.stringify(value);
            var old_value = JSON.stringify(this.get(key));

            if( old_value != new_value ) {
                this.state[key] = value;
                console.log("state:update",key,value);
                $(this).trigger('state:update', [key, value]);
            }
        },

        remove: function( key ) {
            delete this.state[ key ];
            console.log("state:remove",key);
            $(this).trigger('state:remove', [key] );
        },

        clear: function() {
        }
    });

    window.StateProvider = StateProvider;

    var AjaxStateProvider = function( options ) {
        options = _({delay: 500}).extend(options);
        this.parent.constructor.call(this,options);
        this.ajax = options.ajax;

        this.queue = { update: {}, remove: {} };

        $(this).on('state:update', this.queue_update);
        $(this).on('state:remove', this.queue_remove);

        this.submit_state = _.debounce(function(){
            if( ! this.ajax.url )
                return;

            var queue = $.extend(true,{},this.queue);
            this.queue = { update: {}, clear: {} };

            $.ajax(
                _.extend(this.ajax, {
                    data: JSON.stringify(queue),
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    type: 'POST'
                })
            );
        },options.delay);
    };

    AjaxStateProvider.prototype = new StateProvider;

    _.extend(AjaxStateProvider.prototype, {
        constructor: AjaxStateProvider,
        parent: StateProvider.prototype,

        queue_update: function( event, key, value ) {
            this.queue.update[key] = value;
            this.submit_state();
        },

        queue_remove: function( event, key ) {
            delete this.queue.update[key];
            this.queue.remove[key] = true;
            this.submit_state();
        }
    });

    window.AjaxStateProvider = AjaxStateProvider;

    window.store = function() {
        var provider = new StateProvider();

        return {
            set_provider: function( new_provider ) {
                provider = new_provider;
            },

            get_provider: function( ) {
                return provider;
            },

            get : function( key, default_value ) {
                return provider.get(key,default_value);
            },

            set : function( key, value ) {
                if( (_(value).isObject() || _(value).isString()) && _(value).isEmpty() ) {
                    provider.remove(key);
                } else {
                    provider.set(key,value);
                }
                return this;
            },

            remove : function( key ) {
                provider.remove( key );
            },

            clear : function() {
                provider.clear();
            }

            //,getAll : function() {
            //
            //}
            //
            //,forEach: function( callback ) {
            //
            //}
        }
    }();

}(jQuery, _, window, document));
<commit_msg>if initial hash is passed it is used by reference + if initial data is passed then use it in all subsequent requests<commit_after>;(function ($, _, window, document, undefined) {
    "use strict";

    var StateProvider = function( options ) {
        options = _({}).extend(options);
        this.state = options.initial_state || {};
    };

    _.extend(StateProvider.prototype, {
        get: function( key, default_value ) {
            return _(this.state[key]).isUndefined() ? default_value : this.state[key];
        },

        set: function( key, value ) {
            var new_value = JSON.stringify(value);
            var old_value = JSON.stringify(this.get(key));

            if( old_value != new_value ) {
                this.state[key] = value;
                console.log("state:update",key,value);
                $(this).trigger('state:update', [key, value]);
            }
        },

        remove: function( key ) {
            delete this.state[ key ];
            console.log("state:remove",key);
            $(this).trigger('state:remove', [key] );
        },

        clear: function() {
        }
    });

    window.StateProvider = StateProvider;

    var AjaxStateProvider = function( options ) {
        options = _({delay: 500}).extend(options);
        this.parent.constructor.call(this,options);
        this.ajax = options.ajax;

        this.queue = { update: {}, remove: {} };

        $(this).on('state:update', this.queue_update);
        $(this).on('state:remove', this.queue_remove);

        this.submit_state = _.debounce(function(){
            if( ! this.ajax.url )
                return;

            var queue = $.extend(true,{},this.ajax.data,this.queue);
            this.queue = { update: {}, remove: {} };

            $.ajax(
                _.extend({}, this.ajax, {
                    data: JSON.stringify(queue),
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    type: 'POST'
                })
            );
        },options.delay);
    };

    AjaxStateProvider.prototype = new StateProvider;

    _.extend(AjaxStateProvider.prototype, {
        constructor: AjaxStateProvider,
        parent: StateProvider.prototype,

        queue_update: function( event, key, value ) {
            this.queue.update[key] = value;
            this.submit_state();
        },

        queue_remove: function( event, key ) {
            delete this.queue.update[key];
            this.queue.remove[key] = true;
            this.submit_state();
        }
    });

    window.AjaxStateProvider = AjaxStateProvider;

    window.store = function() {
        var provider = new StateProvider();

        return {
            set_provider: function( new_provider ) {
                provider = new_provider;
            },

            get_provider: function( ) {
                return provider;
            },

            get : function( key, default_value ) {
                return provider.get(key,default_value);
            },

            set : function( key, value ) {
                if( (_(value).isObject() || _(value).isString()) && _(value).isEmpty() ) {
                    provider.remove(key);
                } else {
                    provider.set(key,value);
                }
                return this;
            },

            remove : function( key ) {
                provider.remove( key );
            },

            clear : function() {
                provider.clear();
            }

            //,getAll : function() {
            //
            //}
            //
            //,forEach: function( callback ) {
            //
            //}
        }
    }();

}(jQuery, _, window, document));
<|endoftext|>


<commit_before>"use strict";

module.exports = function(destination) {
	var i = 0;
	var key = 0;
	var source = null;
	for (i = 0; i < arguments.length; i++) {
		if (i !== 0) {
			source = arguments[i];
			for (key in source) {
				if (source.hasOwnProperty(key)) {
					if ((destination[key]) && (source[key].constructor === Object) && (destination[key].constructor === Object)) {
						destination[key] = this(destination[key], source[key]);
					} else {
						destination[key] = source[key];
					}
				}
			}
		}
	}
	return destination;
};
<commit_msg>Fixed syntax error<commit_after>"use strict";

module.exports = function(destination) {
	var i = 0;
	var key = 0;
	var source = null;
	for (i = 0; i < arguments.length; i++) {
		if (i !== 0) {
			source = arguments[i];
			for (key in source) {
				if (source.hasOwnProperty(key)) {
					if ((destination[key]) && (source[key].constructor === Object) && (destination[key].constructor === Object)) {
						destination[key] = module.exports(destination[key], source[key]);
					} else {
						destination[key] = source[key];
					}
				}
			}
		}
	}
	return destination;
};
<|endoftext|>


<commit_before>import Mixin from '@ember/object/mixin';
import { isNone } from '@ember/utils';
import decorator from '@onehilltech/decorator';

const USER_SCOPE = 'user';

function ajax (url, type, options) {
  // We are going to intercept the original request before it goes out and
  // replace the error handler with our error handler.

  const ajax = this._super.bind (this);

  return ajax (...arguments).catch (err => {
    if (isNone (err.errors)) {
      throw err;
    }

    const { errors: [{ code }] } = err;

    if (code === 'invalid_token' || code === 'unknown_token' || code === 'token_expired' ) {
      // Refresh the access token, and try the request again. If the request fails
      // a second time, then return the original error.

      // Should we try to authenticate the client with the same options
      // contained in the token?!

      const refreshPromise = this.session.isSignedIn ?
        this.session.refresh () :
        this.session.gatekeeper.authenticate ({}, true);

      return refreshPromise.then (() => ajax (url, type, options));
    }
    else {
      throw err;
    }
  });
}

/**
 * The ajax function used in the mixin and the override approach.
 *
 * @param url
 * @param type
 * @param options
 * @returns {*}
 */
// eslint-disable-next-line ember/no-new-mixins
const BearerMixin = Mixin.create ({
  ajax
});

/**
 * Implementation of the bearer decorator.
 *
 * @param target
 * @param name
 * @param descriptor
 * @param options
 */
function bearer (target, name, descriptor, options = {}) {
  const {
    scope = USER_SCOPE
  } = options;

  Object.defineProperty (target.prototype, 'accessToken', {
    get () {
      return scope === USER_SCOPE ? this.session.accessToken : this.session.gatekeeper.accessToken;
    }
  });

  Object.defineProperty (target.prototype, 'headers', {
    get () {
      console.log ('getting the headers');

      const  headers = { 'Cache-Control': 'private, max-age=0, no-cache, no-store' };

      const accessToken = scope === USER_SCOPE && this.session.isSignedIn ?
        this.session.accessToken.toString () :
        this.session.gatekeeper.accessToken.toString ();

      headers.Authorization = `Bearer ${accessToken}`;

      return headers;
    }
  });

  // Extend the current REST adapter with the bearer mixin.
  return target.extend (BearerMixin);
}

export default decorator (bearer);
<commit_msg>chore: removed console message<commit_after>import Mixin from '@ember/object/mixin';
import { isNone } from '@ember/utils';
import decorator from '@onehilltech/decorator';

const USER_SCOPE = 'user';

function ajax (url, type, options) {
  // We are going to intercept the original request before it goes out and
  // replace the error handler with our error handler.

  const ajax = this._super.bind (this);

  return ajax (...arguments).catch (err => {
    if (isNone (err.errors)) {
      throw err;
    }

    const { errors: [{ code }] } = err;

    if (code === 'invalid_token' || code === 'unknown_token' || code === 'token_expired' ) {
      // Refresh the access token, and try the request again. If the request fails
      // a second time, then return the original error.

      // Should we try to authenticate the client with the same options
      // contained in the token?!

      const refreshPromise = this.session.isSignedIn ?
        this.session.refresh () :
        this.session.gatekeeper.authenticate ({}, true);

      return refreshPromise.then (() => ajax (url, type, options));
    }
    else {
      throw err;
    }
  });
}

/**
 * The ajax function used in the mixin and the override approach.
 *
 * @param url
 * @param type
 * @param options
 * @returns {*}
 */
// eslint-disable-next-line ember/no-new-mixins
const BearerMixin = Mixin.create ({
  ajax
});

/**
 * Implementation of the bearer decorator.
 *
 * @param target
 * @param name
 * @param descriptor
 * @param options
 */
function bearer (target, name, descriptor, options = {}) {
  const {
    scope = USER_SCOPE
  } = options;

  Object.defineProperty (target.prototype, 'accessToken', {
    get () {
      return scope === USER_SCOPE ? this.session.accessToken : this.session.gatekeeper.accessToken;
    }
  });

  Object.defineProperty (target.prototype, 'headers', {
    get () {
      const  headers = { 'Cache-Control': 'private, max-age=0, no-cache, no-store' };

      const accessToken = scope === USER_SCOPE && this.session.isSignedIn ?
        this.session.accessToken.toString () :
        this.session.gatekeeper.accessToken.toString ();

      headers.Authorization = `Bearer ${accessToken}`;

      return headers;
    }
  });

  // Extend the current REST adapter with the bearer mixin.
  return target.extend (BearerMixin);
}

export default decorator (bearer);
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
/* globals console */
'use strict';
// Load required libraries
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const dynamodb = new AWS.DynamoDB.DocumentClient();
const moment = require('moment-timezone');

exports.handler = (event, context, callback) => {

  console.log(event.startTime);

  // If there is a lastupdated parameter, scan from that time
  if (Number(event.lastupdated) > 1) {
    console.log('Detecting lastupdated variable, ' + event.lastupdated);
    startTime = Number(event.lastupdated);
  }

  // Set scan limit to 20 if not present or greater than 20
  let limit = 20;
  if (Number(event.limit) < 20) {
    limit = event.limit;
  }

  console.log('Scanning from greater than ' + startTime);
  // Set scanning parameters
  let params = {
    TableName: 'impact-map',
    // Only get Coordinates and Action data from the table
    ProjectionExpression: 'Coordinates, #b',
    // Only return items that have an Added time that is greater than startTime
    FilterExpression: 'Added > :start',
    ExpressionAttributeNames: {
      // Set an 'alias' for the word, 'Action', because 'Action' is a reserved word in DynamoDB
      '#b': 'Action'
    },
    ExpressionAttributeValues: {
      // Set an 'alias' for startTime, called ':start'
      ':start': startTime
    },
    Limit: limit
  };

  if (typeof event.LastEvaluatedKey != 'undefined') {
    params.LastEvaluatedKey = event.LastEvaluatedKey;
  }

  console.log('Scanning table.');
  dynamodb.scan(params, onScan);

  function onScan(err, data) {
    // Log error if scanning returns err
    if (err) {
      console.error('Unable to scan the table. Error JSON:', JSON.stringify(err, null, 2));
    } else {
      console.log('Scan succeeded.');
      // Continue scanning if we have more items, because scan can retrieve a maximum of 1MB of data
      if (typeof data.LastEvaluatedKey != 'undefined') {
        console.log('LastEvaluatedKey detected');
      }
      // Returns the item data back to the client
      console.log('Returning ' + data.length + ' items to the client');
      callback(null, data);
    }
  }
};
<commit_msg>Add JS hint variable declarations<commit_after>/*jshint esversion: 6 */
/* globals console, require*/
'use strict';
// Load required libraries
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const dynamodb = new AWS.DynamoDB.DocumentClient();
const moment = require('moment-timezone');

exports.handler = (event, context, callback) => {

  console.log(event.startTime);

  // If there is a lastupdated parameter, scan from that time
  if (Number(event.lastupdated) > 1) {
    console.log('Detecting lastupdated variable, ' + event.lastupdated);
    startTime = Number(event.lastupdated);
  }

  // Set scan limit to 20 if not present or greater than 20
  let limit = 20;
  if (Number(event.limit) < 20) {
    limit = event.limit;
  }

  console.log('Scanning from greater than ' + startTime);
  // Set scanning parameters
  let params = {
    TableName: 'impact-map',
    // Only get Coordinates and Action data from the table
    ProjectionExpression: 'Coordinates, #b',
    // Only return items that have an Added time that is greater than startTime
    FilterExpression: 'Added > :start',
    ExpressionAttributeNames: {
      // Set an 'alias' for the word, 'Action', because 'Action' is a reserved word in DynamoDB
      '#b': 'Action'
    },
    ExpressionAttributeValues: {
      // Set an 'alias' for startTime, called ':start'
      ':start': startTime
    },
    Limit: limit
  };

  if (typeof event.LastEvaluatedKey != 'undefined') {
    params.LastEvaluatedKey = event.LastEvaluatedKey;
  }

  console.log('Scanning table.');
  dynamodb.scan(params, onScan);

  function onScan(err, data) {
    // Log error if scanning returns err
    if (err) {
      console.error('Unable to scan the table. Error JSON:', JSON.stringify(err, null, 2));
    } else {
      console.log('Scan succeeded.');
      // Continue scanning if we have more items, because scan can retrieve a maximum of 1MB of data
      if (typeof data.LastEvaluatedKey != 'undefined') {
        console.log('LastEvaluatedKey detected');
      }
      // Returns the item data back to the client
      console.log('Returning ' + data.length + ' items to the client');
      callback(null, data);
    }
  }
};
<|endoftext|>


<commit_before>/**
 * @file Defines the hydrater settings.
 */

// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
var default_port = 8000;

var default_tika_version = "1.4";
var default_tika_path = "/etc/tika-" + default_tika_version + "/tika-app-" + default_tika_version + ".jar";

// Number of tika instance to run simultaneously
var default_concurrency = 2;

if(node_env === "production") {
  default_port = 80;
}

// Exports configuration
module.exports = {
  env: node_env,
  port: process.env.PORT || default_port,
  workers: process.env.WORKERS || 2;

  tika_version: process.env.TIKA_VERSION || default_tika_version,
  tika_path: process.env.TIKA_PATH || default_tika_path,
  concurrency: process.env.TIKA_CONCURRENCY || default_concurrency
};
<commit_msg>Oops. Typo.<commit_after>/**
 * @file Defines the hydrater settings.
 */

// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
var default_port = 8000;

var default_tika_version = "1.4";
var default_tika_path = "/etc/tika-" + default_tika_version + "/tika-app-" + default_tika_version + ".jar";

// Number of tika instance to run simultaneously
var default_concurrency = 2;

if(node_env === "production") {
  default_port = 80;
}

// Exports configuration
module.exports = {
  env: node_env,
  port: process.env.PORT || default_port,
  workers: process.env.WORKERS || 2,

  tika_version: process.env.TIKA_VERSION || default_tika_version,
  tika_path: process.env.TIKA_PATH || default_tika_path,
  concurrency: process.env.TIKA_CONCURRENCY || default_concurrency
};
<|endoftext|>


<commit_before>exports.definition = {
	config : {
		columns : {
			id : "TEXT NOT NULL PRIMARY KEY",
			name : "TEXT NOT NULL",
			currencyId : "TEXT NOT NULL",
			currentBalance : "REAL NOT NULL",
			remark : "TEXT",
			sharingType : "TEXT　NOT NULL",
			accountType : "TEXT NOT NULL",
			accountNumber : "TEXT",
			bankAddress : "TEXT",
			ownerUserId : "TEXT NOT NULL",
			lastSyncTime : "TEXT",
			lastModifyTime : "TEXT"
		},
		defaults : {
			currentBalance : 0
		},
		hasMany : {
			moneyExpenses : {
				type : "MoneyExpense",
				attribute : "moneyAccount"
			},
			moneyIncomes : {
				type : "MoneyIncome",
				attribute : "moneyAccount"
			},
			moneyBorrows : {
				type : "MoneyBorrow",
				attribute : "moneyAccount"
			},
			moneyLends : {
				type : "MoneyLend",
				attribute : "moneyAccount"
			},
			moneyPayback : {
				type : "MoneyPayback",
				attribute : "moneyAccount"
			},
			moneyReturns : {
				type : "MoneyReturn",
				attribute : "moneyAccount"
			}
		},
		belongsTo : {
			currency : {
				type : "Currency",
				attribute : "moneyAccounts"
			},
			ownerUser : {
				type : "User",
				attribute : "moneyAccounts"
			}
		},
		rowView : "money/moneyAccount/moneyAccountRow",
		adapter : {
			type : "hyjSql"
		}
	},
	extendModel : function(Model) {
		_.extend(Model.prototype, Alloy.Globals.XModel, {
			// extended functions and properties go here
			validators : {
				currency : function(xValidateComplete) {
					var error;
					if (!this.isNew()) {
						if (this.xGet("currency") !== this.previous("currency")) {
							error = {
								msg : "账户币种不可以修改"
							};
						}
					}
				}
			},
			xDelete : function(xFinishCallback) {
				var error;
				if (Alloy.Models.User.xGet("activeMoneyAccount") === this) {
					error = {
						msg : "默认账户不能删除"
					};
				} else if (this.xGet("moneyExpenses") && this.xGet("moneyExpenses").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关支出，不能删除"
					});
				} else if (this.xGet("moneyIncomes") && this.xGet("moneyIncomes").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关收入，不能删除"
					});
				} else if (this.xGet("moneyBorrows") && this.xGet("moneyBorrows").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关借入，不能删除"
					});
				} else if (this.xGet("moneyLends") && this.xGet("moneyLends").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关借出，不能删除"
					});
				} else if (this.xGet("moneyPaybacks") && this.xGet("moneyPaybacks").length > 0 || this.xGet("moneyReturns").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关收款，不能删除"
					});
				} else if (this.xGet("moneyReturns") && this.xGet("moneyReturns").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关还款，不能删除"
					});
				} else {
					this._xDelete(xFinishCallback);
					return;
				}
				xFinishCallback(error);
			},
			getAccountNameCurrency : function() {
				if (this.xGet("ownerUser") === Alloy.Models.User) {
					return this.xGet("name") + " (" + this.xGet("currency").xGet("symbol") + this.xGet("currentBalance").toUserCurrency() + ")";
				} else {
					return this.xGet("name") + " (" + this.xGet("currency").xGet("symbol") + ")";
				}
			},
			getCurrentBalance : function() {
				if (this.xGet("ownerUser") === Alloy.Models.User) {
					return this.xGet("currentBalance").toUserCurrency();
				}
			}
		});

		return Model;
	},
	extendCollection : function(Collection) {
		_.extend(Collection.prototype, Alloy.Globals.XCollection, {
			// extended functions and properties go here
		});

		return Collection;
	}
}

<commit_msg>fix #232<commit_after>exports.definition = {
	config : {
		columns : {
			id : "TEXT NOT NULL PRIMARY KEY",
			name : "TEXT NOT NULL",
			currencyId : "TEXT NOT NULL",
			currentBalance : "REAL NOT NULL",
			remark : "TEXT",
			sharingType : "TEXT　NOT NULL",
			accountType : "TEXT NOT NULL",
			accountNumber : "TEXT",
			bankAddress : "TEXT",
			ownerUserId : "TEXT NOT NULL",
			lastSyncTime : "TEXT",
			lastModifyTime : "TEXT"
		},
		defaults : {
			currentBalance : 0
		},
		hasMany : {
			moneyExpenses : {
				type : "MoneyExpense",
				attribute : "moneyAccount"
			},
			moneyIncomes : {
				type : "MoneyIncome",
				attribute : "moneyAccount"
			},
			moneyBorrows : {
				type : "MoneyBorrow",
				attribute : "moneyAccount"
			},
			moneyLends : {
				type : "MoneyLend",
				attribute : "moneyAccount"
			},
			moneyPayback : {
				type : "MoneyPayback",
				attribute : "moneyAccount"
			},
			moneyReturns : {
				type : "MoneyReturn",
				attribute : "moneyAccount"
			}
		},
		belongsTo : {
			currency : {
				type : "Currency",
				attribute : "moneyAccounts"
			},
			ownerUser : {
				type : "User",
				attribute : "moneyAccounts"
			}
		},
		rowView : "money/moneyAccount/moneyAccountRow",
		adapter : {
			type : "hyjSql"
		}
	},
	extendModel : function(Model) {
		_.extend(Model.prototype, Alloy.Globals.XModel, {
			// extended functions and properties go here
			validators : {
				currency : function(xValidateComplete) {
					var error;
					if (!this.isNew()) {
						if (this.xGet("currency") !== this.previous("currency")) {
							error = {
								msg : "账户币种不可以修改"
							};
						}
					}
					xFinishCallback(error);
				}
			},
			xDelete : function(xFinishCallback) {
				var error;
				if (Alloy.Models.User.xGet("activeMoneyAccount") === this) {
					error = {
						msg : "默认账户不能删除"
					};
				} else if (this.xGet("moneyExpenses") && this.xGet("moneyExpenses").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关支出，不能删除"
					});
				} else if (this.xGet("moneyIncomes") && this.xGet("moneyIncomes").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关收入，不能删除"
					});
				} else if (this.xGet("moneyBorrows") && this.xGet("moneyBorrows").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关借入，不能删除"
					});
				} else if (this.xGet("moneyLends") && this.xGet("moneyLends").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关借出，不能删除"
					});
				} else if (this.xGet("moneyPaybacks") && this.xGet("moneyPaybacks").length > 0 || this.xGet("moneyReturns").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关收款，不能删除"
					});
				} else if (this.xGet("moneyReturns") && this.xGet("moneyReturns").length > 0) {
					xFinishCallback({
						msg : "当前账户有相关还款，不能删除"
					});
				} else {
					this._xDelete(xFinishCallback);
					return;
				}
				xFinishCallback(error);
			},
			getAccountNameCurrency : function() {
				if (this.xGet("ownerUser") === Alloy.Models.User) {
					return this.xGet("name") + " (" + this.xGet("currency").xGet("symbol") + this.xGet("currentBalance").toUserCurrency() + ")";
				} else {
					return this.xGet("name") + " (" + this.xGet("currency").xGet("symbol") + ")";
				}
			},
			getCurrentBalance : function() {
				if (this.xGet("ownerUser") === Alloy.Models.User) {
					return this.xGet("currentBalance").toUserCurrency();
				}
			}
		});

		return Model;
	},
	extendCollection : function(Collection) {
		_.extend(Collection.prototype, Alloy.Globals.XCollection, {
			// extended functions and properties go here
		});

		return Collection;
	}
}

<|endoftext|>


<commit_before>function setSessions(val) {
    if (navigator.id) {
	navigator.id.sessions = val ? val : [ ];
    }
}

function loggedIn(email) {
    setSessions([ { email: email } ]);
    $('#logout').bind('click', logout);
    $('#new-server').submit(addServer);
    $('#new-server').modal({
	keyboard: true,
	backdrop: true
    });
    listServers();
    $('#usermenu').dropdown();
    $('#usermenu .dropdown-toggle').html(email);
    $('.logged-out').hide();
    $('.logged-in').show();
}

function loggedOut() {
    setSessions();
    $('#browserid').css('opacity', '1.0');
    $('.logged-in').hide();
    $('.logged-out').show();
}

function logout(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/logout',
	success: function() {
	    // and then redraw the UI.
	    loggedOut();
	}
    });
}

function hostnameId(hostname) {
    return hostname.replace(/\./g,'-');
}

function serverControls(hostname_id) {
    return '

Server

<input class="xlarge" name="'+hostname_id+'" size="30" type="text"/>

';
}

function listChannels(hostname) {
    var url = '/api/networks/'+hostname;
    var hostname_id = '#' + hostnameId(hostname);
    $(hostname_id).append(serverControls(hostname_id));
    $.getJSON(url, function (channel_list) {
	$.each(channel_list, function(index, val) {
	    // Fixme: Will break with multiple servers
	    $('.channels-nav').append('
'+val+'
');
	});
    });
    $('.tabs').tabs();
}

function switchServerTab() {
    var hostname_id = '#'+this.href.split('#')[1];
    $('#servers-nav .active').removeClass('active');
    $(this).parent().addClass('active');
    $('#servers .active').removeClass('active');
    $('#servers').find(hostname_id).addClass('active');
}

function addServerTab(hostname) {
    var hostname_id = hostnameId(hostname);
    $('#servers-nav').append('
'+hostname+'
');
    $('#servers-nav a').click(switchServerTab);
    $('#servers').append('

');
    listChannels(hostname);
}

function listServers() {
    $("#server-list tbody tr").remove();
    $.getJSON('/api/networks', function (server_list) {
	$.each(server_list, function(index, val) {
	    var cols = new Array();
	    // Enabled server
	    if (val[0]) {
		cols[0] = '<input type="checkbox" class="server-disable" checked />	';
	    }
	    else {
		cols[0] = '<input type="checkbox" class="server-enable" />	';
	    }
	    cols[1] = ''+val[1]+'	';
	    cols[2] = ''+val[2]+'	';
	    // SSL heart or skull
	    if (val[3]) {
		// Remove disabled when this is implemented
		cols[3] = '\u2665	';
	    }
	    else {
		cols[3] = '\u2620	';
	    }
	    // Nick configured yet?
	    if (val[4]) {
		cols[4] = '<input type="text" class="disabled" value="'+val[4]+'" />	';
	    }
	    else {
		cols[4] = '<input type="text" class="disabled" />	';
	    }
	    // Server configuration line
	    $('#server-list > tbody:last').append('
<form>'+cols.join()+'</form>
');
	    addServerTab(val[1]);
	});
    });
}

function addServerClear() {
    $('#hostname').parent().parent().removeClass("error");
    $('#hostname').next('.help-inline').empty();
}

function addServer() {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/networks',
	data: $(this).serialize(),
	dataType: 'json',
	success: function() {
	    $('#new-server').modal('hide');
	    // Connect to a new server by default
	    serverSettings($('#hostname').val(), true, $('#nick').val());
	},
	error: function(xhr, status, error) {
	    if (xhr.status == 409) {
		$('#hostname').keypress(addServerClear);
	    }
	    $('#hostname').parent().parent().addClass("error");
	    var error = $.parseJSON(xhr.responseText);
	    $('#hostname').next('.help-inline').text(error);
	}
    });
}

function serverSettings(server, enabled, nick) {
    $.ajax({
	type: 'POST',
	url: '/api/networks/' + server,
	data: {'enabled':enabled, 'nick':nick},
	dataType: 'json',
	success: function() {
	    // Refresh the list on success
	    listServers();
	},
	error: function(res, status, xhr) {
	    alert("toggleServer failed: "+res);
	}
    });
}

function gotVerifiedEmail(assertion) {
    if (assertion !== null) {
	$.ajax({
	    type: 'POST',
	    url: '/api/login',
	    dataType: 'json',
	    data: { assertion: assertion },
	    success: function(res, status, xhr) {
		if (res === null) loggedOut();
		else loggedIn(res);
	    },
	    error: function(res, status, xhr) {
		loggedOut();
		alert("login failure" + res);
	    }
	});
    }
    else {
	loggedOut();
    }
}

$(document).ready(function() {
    if (!navigator.id) {
        $('#browserid').hide();
        return;
    }

    $.get('/api/whoami', function (res) {
	if (res === null) loggedOut();
	else loggedIn(res);
    }, 'json');

    $('#browserid').click(function() {
	$('#browserid').css('opacity', '0.4');
        navigator.id.get(gotVerifiedEmail);
    });
});
<commit_msg>Web client: Load the channel scrollback in a tab, start actually displaying IRC content.<commit_after>function setSessions(val) {
    if (navigator.id) {
	navigator.id.sessions = val ? val : [ ];
    }
}

function loggedIn(email) {
    setSessions([ { email: email } ]);
    $('#logout').bind('click', logout);
    $('#new-server').submit(addServer);
    $('#new-server').modal({
	keyboard: true,
	backdrop: true
    });
    listServers();
    $('#usermenu').dropdown();
    $('#usermenu .dropdown-toggle').html(email);
    $('.logged-out').hide();
    $('.logged-in').show();
}

function loggedOut() {
    setSessions();
    $('#browserid').css('opacity', '1.0');
    $('.logged-in').hide();
    $('.logged-out').show();
}

function logout(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/logout',
	success: function() {
	    // and then redraw the UI.
	    loggedOut();
	}
    });
}

function hostnameId(hostname) {
    return hostname.replace(/\./g,'-');
}

function serverControls(hostname_id) {
    return '

Server

<input class="xlarge" name="'+hostname_id+'" size="30" type="text"/>

';
}

function refreshChannel(hostname, channel, position) {
    var channel_url = '/api/networks/'+hostname+'/'+channel+'/messages';
    $.getJSON(channel_url, function (channel_messages) {
	var hostname_id = hostnameId(hostname);
	var channel_id = hostname_id + '-' + position;
	$('#'+hostname_id).children('.pill-content')
	    .append('

');
	channel_messages.reverse();
	$.each(channel_messages, function(index, val) {
	    $('#'+channel_id+' ul')
		.append('
'+val[0]+''+val[1]+'
');
	});
    });
}

function listChannels(hostname) {
    var url = '/api/networks/'+hostname;
    var hostname_id = hostnameId(hostname);
    $('#'+hostname_id).append(serverControls(hostname_id));
    $.getJSON(url, function (channel_list) {
	$.each(channel_list, function(index, val) {
	    // Fixme: Will break with multiple servers
	    var chan = encodeURIComponent(val);
	    $('.channels-nav')
		.append('
'+val+'
');
	    refreshChannel(hostname, chan, index);
	});
	$('.tabs').tabs();
    });
}

function switchServerTab() {
    var hostname_id = '#'+this.href.split('#')[1];
    $('#servers-nav .active').removeClass('active');
    $(this).parent().addClass('active');
    $('#servers .active').removeClass('active');
    $('#servers').find(hostname_id).addClass('active');
}

function addServerTab(hostname) {
    var hostname_id = hostnameId(hostname);
    $('#servers-nav').append('
'+hostname+'
');
    $('#servers-nav a').click(switchServerTab);
    $('#servers').append('

');
    listChannels(hostname);
}

function listServers() {
    $("#server-list tbody tr").remove();
    $.getJSON('/api/networks', function (server_list) {
	$.each(server_list, function(index, val) {
	    var cols = new Array();
	    // Enabled server
	    if (val[0]) {
		cols[0] = '<input type="checkbox" class="server-disable" checked />	';
	    }
	    else {
		cols[0] = '<input type="checkbox" class="server-enable" />	';
	    }
	    cols[1] = ''+val[1]+'	';
	    cols[2] = ''+val[2]+'	';
	    // SSL heart or skull
	    if (val[3]) {
		// Remove disabled when this is implemented
		cols[3] = '\u2665	';
	    }
	    else {
		cols[3] = '\u2620	';
	    }
	    // Nick configured yet?
	    if (val[4]) {
		cols[4] = '<input type="text" class="disabled" value="'+val[4]+'" />	';
	    }
	    else {
		cols[4] = '<input type="text" class="disabled" />	';
	    }
	    // Server configuration line
	    $('#server-list > tbody:last').append('
<form>'+cols.join()+'</form>
');
	    addServerTab(val[1]);
	});
    });
}

function addServerClear() {
    $('#hostname').parent().parent().removeClass("error");
    $('#hostname').next('.help-inline').empty();
}

function addServer() {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/networks',
	data: $(this).serialize(),
	dataType: 'json',
	success: function() {
	    $('#new-server').modal('hide');
	    // Connect to a new server by default
	    serverSettings($('#hostname').val(), true, $('#nick').val());
	},
	error: function(xhr, status, error) {
	    if (xhr.status == 409) {
		$('#hostname').keypress(addServerClear);
	    }
	    $('#hostname').parent().parent().addClass("error");
	    var error = $.parseJSON(xhr.responseText);
	    $('#hostname').next('.help-inline').text(error);
	}
    });
}

function serverSettings(server, enabled, nick) {
    $.ajax({
	type: 'POST',
	url: '/api/networks/' + server,
	data: {'enabled':enabled, 'nick':nick},
	dataType: 'json',
	success: function() {
	    // Refresh the list on success
	    listServers();
	},
	error: function(res, status, xhr) {
	    alert("toggleServer failed: "+res);
	}
    });
}

function gotVerifiedEmail(assertion) {
    if (assertion !== null) {
	$.ajax({
	    type: 'POST',
	    url: '/api/login',
	    dataType: 'json',
	    data: { assertion: assertion },
	    success: function(res, status, xhr) {
		if (res === null) loggedOut();
		else loggedIn(res);
	    },
	    error: function(res, status, xhr) {
		loggedOut();
		alert("login failure" + res);
	    }
	});
    }
    else {
	loggedOut();
    }
}

$(document).ready(function() {
    if (!navigator.id) {
        $('#browserid').hide();
        return;
    }

    $.get('/api/whoami', function (res) {
	if (res === null) loggedOut();
	else loggedIn(res);
    }, 'json');

    $('#browserid').click(function() {
	$('#browserid').css('opacity', '0.4');
        navigator.id.get(gotVerifiedEmail);
    });
});
<|endoftext|>


<commit_before>import Em from 'ember';
import ArraySlice from 'array-slice';

var computed = Em.computed;
var lte = computed.lte;
var get = Em.get;
var set = Em.set;
var max = Math.max;
var ceil = Math.ceil;

var ArrayPager = ArraySlice.extend({
	// 1-based
	page: computed('offset', 'limit', {
		get: function () {
			var limit = get(this, 'limit');
			var offset = get(this, 'offset') || 0;
			return ceil(offset / limit) || 1;
		},
		set: function (key, page) {
			var limit = get(this, 'limit');
			var offset = get(this, 'offset');
			// no negative pages
			page = max(page - 1, 0);
			offset = (limit * page) || 0;
			set(this, 'offset', offset);
			return page + 1;
		}
	}),

	// 1-based
	pages: computed('content.length', 'limit', {
		get: function () {
			var limit = get(this, 'limit');
			var length = get(this, 'content.length');
			var pages = ceil(length / limit) || 1;
			if (pages === Infinity) {
				pages = 0;
			}
			return pages;
		},
		set: function () {
			throw new Error('Cannot set `pages` property of array pager');
		}
	}),

	isFirstPage: lte('page', 1),

	isLastPage: computed('page', 'pages', {
		get: function () {
			var page = this.get('page');
			var pages = this.get('pages');
			var isLast = page >= pages;
			return isLast;
		}
	}),

	goToFirstPage: function () {
		this.set('page', 0);
	},

	goToLastPage: function () {
		var max = this.get('pages');
		this.set('page', max);
	}
});

ArrayPager.computed = {
	page: function (prop, limit, page) {
		return computed({
			get: function () {
				return ArrayPager.create({
					content: get(this, prop),
					page: (page || 0),
					limit: limit
				});
			}
		});
	}
};

export default ArrayPager;
<commit_msg>Removed unnecessary get/set function calls<commit_after>import Em from 'ember';
import ArraySlice from 'array-slice';

var computed = Em.computed;
var lte = computed.lte;
var max = Math.max;
var ceil = Math.ceil;

var ArrayPager = ArraySlice.extend({
	// 1-based
	page: computed('offset', 'limit', {
		get: function () {
			var limit = this.get('limit');
			var offset = this.get('offset') || 0;
			return ceil(offset / limit) || 1;
		},
		set: function (key, page) {
			var limit = this.get('limit');
			var offset = this.get('offset');
			// no negative pages
			page = max(page - 1, 0);
			offset = (limit * page) || 0;
			this.set('offset', offset);
			return page + 1;
		}
	}),

	// 1-based
	pages: computed('content.length', 'limit', {
		get: function () {
			var limit = this.get('limit');
			var length = this.get('content.length');
			var pages = ceil(length / limit) || 1;
			if (pages === Infinity) {
				pages = 0;
			}
			return pages;
		},
		set: function () {
			throw new Error('Cannot set `pages` property of array pager');
		}
	}),

	isFirstPage: lte('page', 1),

	isLastPage: computed('page', 'pages', {
		get: function () {
			var page = this.get('page');
			var pages = this.get('pages');
			var isLast = page >= pages;
			return isLast;
		}
	}),

	goToFirstPage: function () {
		this.set('page', 0);
	},

	goToLastPage: function () {
		var max = this.get('pages');
		this.set('page', max);
	}
});

ArrayPager.computed = {
	page: function (prop, limit, page) {
		return computed({
			get: function () {
				return ArrayPager.create({
					content: this.get(prop),
					page: (page || 0),
					limit: limit
				});
			}
		});
	}
};

export default ArrayPager;
<|endoftext|>


<commit_before>(function () {

	var TEMPLATE_BUTTON = (
		'<button id="focus-reading-button" title="Focus Reading">FR</button>'
	)
	var TEMPLATE_PAD = (
		'
' +
			'×' +
			'

' +
		'
'
	)
	var CLASS_READING_PAD_SHOWING = 'focus-reading'

	var ContentGenerator = {
		generators: []
	}
	var $readingPad

	// init as soon as possible
	// even before document ready
	function tryInit() {
		if (document.body) {
			init()
		} else {
			setTimeout(tryInit, 100)
		}
	}

	function init() {
		var $button = $(TEMPLATE_BUTTON).appendTo('body')
		$button.on('click', focusRead)

		$readingPad = $(TEMPLATE_PAD).hide().appendTo('body')
		$readingPad.on('click', '#focus-reading-pad-close-button', hidePad)
	}

	function showPad(title, content) {
		$readingPad.find('#focus-reading-pad-content').html(
			'
' + title + '
' +
			content
		)
		$readingPad.show()
		$('html,body').addClass(CLASS_READING_PAD_SHOWING)
		$(document).on('keydown', hidePadOnEscKeydown)

		// everytime show pad, focus at the start
		$readingPad.animate({'scrollTop': 0}, 500)
	}

	function hidePad() {
		$readingPad.hide()
		$('html,body').removeClass(CLASS_READING_PAD_SHOWING)
		$(document).off('keydown', hidePadOnEscKeydown)
	}

	function focusRead() {
		var article = ContentGenerator.generatArticle()
		if (article) {
			showPad(article.title, article.content)
		} else {
			alert('Focus Reading: Can not find anything to read.')
		}
	}

	function hidePadOnEscKeydown(e) {
		if (e.keyCode === 27) {
			hidePad()
		}
	}

	/**
	 * 1. generator object
	 * @param {Object} siteGenerator
	 *   - name {sring}
	 *   - title {string|function}
	 *   - content {string|function}
	 *
	 * 2. generator params
	 * @param {string} - name
	 * @param {string|function} - title selector | generator
	 * @param {string|function} - content selector | generator
	 */
	ContentGenerator.add = function (generator) {
		if (typeof siteGenerator === 'object') {
			this.generators.push(generator)
		} else if (arguments.length === 3) {
			this.generators.push({
				name: arguments[0],
				title: arguments[1],
				content: arguments[2]
			})
		}
		return this
	}

	ContentGenerator.generatArticle = function () {
		var generator
		var hostname = location.hostname
		var i = 0
		while ((generator = this.generators[i++])) {
			if (hostname.indexOf(generator.name) > -1) {
				var title = getText(generator.title)
				var content = getHtml(generator.content)
				if (title && content) {
					return {
						title: title,
						content: content
					}
				}
			}
		}
		return null
	}

	ContentGenerator
	.add('gamersky.com', 'h1', '.Mid2L_con')
	.add('movie.douban', 'h1', '#link-report')
	.add('baike.baidu', 'h1', '.main-content')
	.add('jianshu.com', 'h1.title', '.show-content')
	.add('tieba.baidu', 'h1', function () {
		return [].map.call(
		$('.d_post_content'), function (content) {
			return (
				'
' +  content.innerHTML + '
'
			)
		}).join('')
	})
	.add('guancha.cn', '.content-title1', '.all-txt')
	.add('tuicool.com', 'h1', '.article_body')
	.add('chinanews.com', 'h1', '.left_zw')
	.add('xinhuanet.com', '#title', '.article')
	.add('21ccom.net', 'h4', '#contents')
	.add('chinavalue.net', '.ArticleTitle', '.ArticleContent')
	.add('dajia.qq.com', 'h1', '#content')
	.add('news.163.com', '#h1title', '#endText')
	.add('zhihu.com', getZhihuTitle, getZhihuContent)
	.add('tech.163.com', 'h1', '#endText')

	function getText(s) {
		if (typeof s === 'string') {
			return $(s).text()
		} else if (typeof s === 'function') {
			return s()
		} else {
			return null
		}
	}

	function getHtml(s) {
		if (typeof s === 'string') {
			return tryRemoveStyleInfo($(s).clone())
		} else if (typeof s === 'function') {
			return s()
		} else {
			return null
		}
	}

	function tryRemoveStyleInfo(el, deep) {
		var $el = $(el).attr('style', '')

		$el.children().each(function (i, el) {
			tryRemoveStyleInfo(el, true)
		})

		if (!deep) {
			return $el.html()
		}
	}

	function getZhihuTitle() {
		if (location.pathname.startsWith('/question')) {
			return $('.zm-item-title').text()
		} else {
			var $item = getZhihuReadingItemOnIndexPage()
			if ($item) {
				return $item.find('h2').text()
			} else {
				return null
			}
		}
	}

	function getZhihuContent() {
		if (location.pathname.startsWith('/question')) {
			var $answer = getZhihuReadingItemOnQuestionPage()
			if ($answer) {
				return (
					'
' +
						(
							$answer.find('.zm-item-answer-author-info').html()
						) +
					'
' +
					processZhihuContentHtml(
						$answer.find('.zm-editable-content').html()
					)
				)
			} else {
				return null
			}
		} else {
			var $item = getZhihuReadingItemOnIndexPage()
			if ($item) {
				return (
					'
' +
						(
							$item.find('.zm-item-answer-author-info').html() ||
							$item.find('.author-info').html()
						) +
					'
' +
					processZhihuContentHtml(
						$item.find('textarea.content').val()
					)
				)
			} else {
				return null
			}
		}
	}

	function processZhihuContentHtml(html) {
		var regNoscript = /\[^<]*\<\/noscript\>/g
		var regImg = /\]*data-original=(\S+) [^>]*\>/g
		return html
		.replace(regNoscript, '')
		.replace(regImg, function (m, src) {
			return ''
		})
	}

	function getZhihuReadingItemOnIndexPage() {
		return findReadingElement('.zm-item-expanded')
	}

	function getZhihuReadingItemOnQuestionPage() {
		return findReadingElement('.zm-item-answer')
	}

	function findReadingElement(selector) {
		var $items =  $(selector)
		var item
		var i = 0
		while ((item = $items[i++])) {
			if (isElementInReading(item)) {
				return $(item)
			}
		}
		return null
	}

	function isElementInReading(el) {
		var scrollTop = document.body.scrollTop
		var screenHeight = $(window).height()

		var $item = $(el)
		var itemTop = $item.offset().top
		var itemHeight = $item.height()

		if (itemTop > scrollTop) {
			if (itemTop < scrollTop + screenHeight) {
				return true
			} else {
				return false
			}
		} else if (itemTop + itemHeight > scrollTop + 100) {
			return true
		} else {
			return false
		}
	}

	tryInit()
})()<commit_msg>lazyload image support get src from data-actualsrc if no data-original<commit_after>(function () {

	var TEMPLATE_BUTTON = (
		'<button id="focus-reading-button" title="Focus Reading">FR</button>'
	)
	var TEMPLATE_PAD = (
		'
' +
			'×' +
			'

' +
		'
'
	)
	var CLASS_READING_PAD_SHOWING = 'focus-reading'

	var ContentGenerator = {
		generators: []
	}
	var $readingPad

	// init as soon as possible
	// even before document ready
	function tryInit() {
		if (document.body) {
			init()
		} else {
			setTimeout(tryInit, 100)
		}
	}

	function init() {
		var $button = $(TEMPLATE_BUTTON).appendTo('body')
		$button.on('click', focusRead)

		$readingPad = $(TEMPLATE_PAD).hide().appendTo('body')
		$readingPad.on('click', '#focus-reading-pad-close-button', hidePad)
	}

	function showPad(title, content) {
		$readingPad.find('#focus-reading-pad-content').html(
			'
' + title + '
' +
			content
		)
		$readingPad.show()
		$('html,body').addClass(CLASS_READING_PAD_SHOWING)
		$(document).on('keydown', hidePadOnEscKeydown)

		// everytime show pad, focus at the start
		$readingPad.animate({'scrollTop': 0}, 500)
	}

	function hidePad() {
		$readingPad.hide()
		$('html,body').removeClass(CLASS_READING_PAD_SHOWING)
		$(document).off('keydown', hidePadOnEscKeydown)
	}

	function focusRead() {
		var article = ContentGenerator.generatArticle()
		if (article) {
			showPad(article.title, article.content)
		} else {
			alert('Focus Reading: Can not find anything to read.')
		}
	}

	function hidePadOnEscKeydown(e) {
		if (e.keyCode === 27) {
			hidePad()
		}
	}

	/**
	 * 1. generator object
	 * @param {Object} siteGenerator
	 *   - name {sring}
	 *   - title {string|function}
	 *   - content {string|function}
	 *
	 * 2. generator params
	 * @param {string} - name
	 * @param {string|function} - title selector | generator
	 * @param {string|function} - content selector | generator
	 */
	ContentGenerator.add = function (generator) {
		if (typeof siteGenerator === 'object') {
			this.generators.push(generator)
		} else if (arguments.length === 3) {
			this.generators.push({
				name: arguments[0],
				title: arguments[1],
				content: arguments[2]
			})
		}
		return this
	}

	ContentGenerator.generatArticle = function () {
		var generator
		var hostname = location.hostname
		var i = 0
		while ((generator = this.generators[i++])) {
			if (hostname.indexOf(generator.name) > -1) {
				var title = getText(generator.title)
				var content = getHtml(generator.content)
				if (title && content) {
					return {
						title: title,
						content: content
					}
				}
			}
		}
		return null
	}

	ContentGenerator
	.add('gamersky.com', 'h1', '.Mid2L_con')
	.add('movie.douban', 'h1', '#link-report')
	.add('baike.baidu', 'h1', '.main-content')
	.add('jianshu.com', 'h1.title', '.show-content')
	.add('tieba.baidu', 'h1', function () {
		return [].map.call(
		$('.d_post_content'), function (content) {
			return (
				'
' +  content.innerHTML + '
'
			)
		}).join('')
	})
	.add('guancha.cn', '.content-title1', '.all-txt')
	.add('tuicool.com', 'h1', '.article_body')
	.add('chinanews.com', 'h1', '.left_zw')
	.add('xinhuanet.com', '#title', '.article')
	.add('21ccom.net', 'h4', '#contents')
	.add('chinavalue.net', '.ArticleTitle', '.ArticleContent')
	.add('dajia.qq.com', 'h1', '#content')
	.add('news.163.com', '#h1title', '#endText')
	.add('zhihu.com', getZhihuTitle, getZhihuContent)
	.add('tech.163.com', 'h1', '#endText')

	function getText(s) {
		if (typeof s === 'string') {
			return $(s).text()
		} else if (typeof s === 'function') {
			return s()
		} else {
			return null
		}
	}

	function getHtml(s) {
		if (typeof s === 'string') {
			return tryRemoveStyleInfo($(s).clone())
		} else if (typeof s === 'function') {
			return s()
		} else {
			return null
		}
	}

	function tryRemoveStyleInfo(el, deep) {
		var $el = $(el).attr('style', '')

		$el.children().each(function (i, el) {
			tryRemoveStyleInfo(el, true)
		})

		if (!deep) {
			return $el.html()
		}
	}

	function getZhihuTitle() {
		if (location.pathname.startsWith('/question')) {
			return $('.zm-item-title').text()
		} else {
			var $item = getZhihuReadingItemOnIndexPage()
			if ($item) {
				return $item.find('h2').text()
			} else {
				return null
			}
		}
	}

	function getZhihuContent() {
		if (location.pathname.startsWith('/question')) {
			var $answer = getZhihuReadingItemOnQuestionPage()
			if ($answer) {
				return (
					'
' +
						(
							$answer.find('.zm-item-answer-author-info').html()
						) +
					'
' +
					processZhihuContentHtml(
						$answer.find('.zm-editable-content').html()
					)
				)
			} else {
				return null
			}
		} else {
			var $item = getZhihuReadingItemOnIndexPage()
			if ($item) {
				return (
					'
' +
						(
							$item.find('.zm-item-answer-author-info').html() ||
							$item.find('.author-info').html()
						) +
					'
' +
					processZhihuContentHtml(
						$item.find('textarea.content').val()
					)
				)
			} else {
				return null
			}
		}
	}

	function processZhihuContentHtml(html) {
		var regNoscript = /\[^<]*\<\/noscript\>/g
		var regImg = /\]*(data-original|data-actualsrc)=(\S+) [^>]*\>/g
		return html
		.replace(regNoscript, '')
		.replace(regImg, function (m, attr, src) {
			return ''
		})
	}

	function getZhihuReadingItemOnIndexPage() {
		return findReadingElement('.zm-item-expanded')
	}

	function getZhihuReadingItemOnQuestionPage() {
		return findReadingElement('.zm-item-answer')
	}

	function findReadingElement(selector) {
		var $items =  $(selector)
		var item
		var i = 0
		while ((item = $items[i++])) {
			if (isElementInReading(item)) {
				return $(item)
			}
		}
		return null
	}

	function isElementInReading(el) {
		var scrollTop = document.body.scrollTop
		var screenHeight = $(window).height()

		var $item = $(el)
		var itemTop = $item.offset().top
		var itemHeight = $item.height()

		if (itemTop > scrollTop) {
			if (itemTop < scrollTop + screenHeight) {
				return true
			} else {
				return false
			}
		} else if (itemTop + itemHeight > scrollTop + 100) {
			return true
		} else {
			return false
		}
	}

	tryInit()
})()<|endoftext|>