<commit_before>var PODLOVE = PODLOVE || {};

(function($){
	PODLOVE.Auphonic = function (container) {

		var o = {};
		var data_cache;
		var field_cache;

		var typewatch = (function() {
			var timer = 0;
			return function(callback, ms) {
				clearTimeout (timer);
				timer = setTimeout(callback, ms);
			}
		})();

		var maybe_update_auphonic_metadata = function () {

			var episode_slug = $("#_podlove_meta_slug").val(),
			    data = {
					action: 'get_auphonic_data',
					post_id: $("#post_ID").val(),
					slug: episode_slug
			};

			if (!episode_slug.length) return;

			$.ajax({
		    	type: "GET",
				dataType: "json",
				data: data,
				url: ajaxurl,
				success: function (result) {
					if (result && result.metadata) {
						data_cache = result;
						override_fields();
					} else if (result && result.message) {
						if ( ! $("#debug_info").length ) {
							$("table.media_file_table").after("

");
						}
						CodeMirror(
							document.getElementById("debug_info"),
							{ value: result.message, mode: "yaml" }
						);
					}
				}
			});
		};

		var override_fields = function () {
			if (!data_cache) return;

			var fields = {
				'title': data_cache.metadata.title,
				'_podlove_meta_subtitle': data_cache.metadata.subtitle,
				'_podlove_meta_summary': data_cache.metadata.summary,
				'_podlove_meta_duration': data_cache.length_timestring,
			};

			field_cache = fields;

			$.each(fields, function(field_id, remote_value) {
				var input = $("#" + field_id)
				    current_value = input.val();

				if (current_value.length == 0) {
					input.val(remote_value);
				} else if (current_value.split(/\r\n|\r|\n/g).join() != remote_value.split(/\r\n|\r|\n/g).join()) {
					var label = $('label[for="' + field_id + '"]');
					if (!label.find(".auphonic_update").length) {
						label.append(" Import update from Auphonic");
					}
				}
			});
		};

		$(container).on('click', '.auphonic_update', function(e) {
			if (!field_cache) return;

			var field = $(this).data('field'),
			    remote_value = field_cache[field];

			$("#" + field).val(remote_value);
			$(this).remove();
		});

		$("#_podlove_meta_slug").on('mediaFileHasUpdated', function(event, url) {
			if (url.match("json$")) maybe_update_auphonic_metadata();
		});
		maybe_update_auphonic_metadata();

		return o;

	}
}(jQuery));

jQuery(function($) {
	PODLOVE.Auphonic($("#podlove_podcast"));
});
<commit_msg>fix js glitch in auphonic module<commit_after>var PODLOVE = PODLOVE || {};

(function($){
	PODLOVE.Auphonic = function (container) {

		var o = {};
		var data_cache;
		var field_cache;

		var typewatch = (function() {
			var timer = 0;
			return function(callback, ms) {
				clearTimeout (timer);
				timer = setTimeout(callback, ms);
			}
		})();

		var maybe_update_auphonic_metadata = function () {

			var episode_slug = $("#_podlove_meta_slug").val(),
			    data = {
					action: 'get_auphonic_data',
					post_id: $("#post_ID").val(),
					slug: episode_slug
			};

			if (!episode_slug || !episode_slug.length) return;

			$.ajax({
		    	type: "GET",
				dataType: "json",
				data: data,
				url: ajaxurl,
				success: function (result) {
					if (result && result.metadata) {
						data_cache = result;
						override_fields();
					} else if (result && result.message) {
						if ( ! $("#debug_info").length ) {
							$("table.media_file_table").after("

");
						}
						CodeMirror(
							document.getElementById("debug_info"),
							{ value: result.message, mode: "yaml" }
						);
					}
				}
			});
		};

		var override_fields = function () {
			if (!data_cache) return;

			var fields = {
				'title': data_cache.metadata.title,
				'_podlove_meta_subtitle': data_cache.metadata.subtitle,
				'_podlove_meta_summary': data_cache.metadata.summary,
				'_podlove_meta_duration': data_cache.length_timestring,
			};

			field_cache = fields;

			$.each(fields, function(field_id, remote_value) {
				var input = $("#" + field_id)
				    current_value = input.val();

				if (current_value.length == 0) {
					input.val(remote_value);
				} else if (current_value.split(/\r\n|\r|\n/g).join() != remote_value.split(/\r\n|\r|\n/g).join()) {
					var label = $('label[for="' + field_id + '"]');
					if (!label.find(".auphonic_update").length) {
						label.append(" Import update from Auphonic");
					}
				}
			});
		};

		$(container).on('click', '.auphonic_update', function(e) {
			if (!field_cache) return;

			var field = $(this).data('field'),
			    remote_value = field_cache[field];

			$("#" + field).val(remote_value);
			$(this).remove();
		});

		$("#_podlove_meta_slug").on('mediaFileHasUpdated', function(event, url) {
			if (url.match("json$")) maybe_update_auphonic_metadata();
		});
		maybe_update_auphonic_metadata();

		return o;

	}
}(jQuery));

jQuery(function($) {
	PODLOVE.Auphonic($("#podlove_podcast"));
});
<|endoftext|>


<commit_before>sparks.jsonActivity = {
  "title": "Measuring a Series Circuit",
  "show_multimeter": "true",
  "disable_multimeter_position": "r",//r,dcv,acv,dca,diode,hfe,c_10a,p_9v",
  "circuit": [
      {
        "type": "resistor",
        "UID": "r1",
        "connections": "b23,b17",
        "label": "R1",
        "resistance": "100"
      },
      {
        "type": "resistor",
        "UID": "r2",
        "connections": "c17,c11",
        "label": "R2",
        "resistance": "100"
      },
      {
        "type": "resistor",
        "UID": "r3",
        "connections": "d11,d5",
        "label": "R3",
        "resistance": "100"
      },
      {
        "type": "wire",
        "connections": "left_positive20,a23"
      },
      {
        "type": "wire",
        "connections": "left_negative3,a5"
      }
   ],

  "questions": [
    {
      "prompt": "What are the measured values of",
      "subquestions": [
        {
          "prompt": "Vtot:",
          "shortPrompt": "Total voltage across R1, R2, and R3",
          "correct_answer": "9",
          "correct_units": "V"
        },
        {
          "prompt": "Itot:",
          "shortPrompt": "Current through R1, R2, and R3",
          "correct_answer": "[9 / (${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance})]",
          "correct_units": "A"
        },
        {
          "prompt": "Rtot:",
          "shortPrompt": "Total resistance of R1, R2, and R3",
          "correct_answer": "[${r1.nominalResistance}+ ${r2.nominalResistance}+ ${r3.nominalResistance}] ohm",
          "correct_units": "ohm",
          "multichoice": [
          	"value...",
          	"[${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance}]",//correct answer w/o units
          	//"[${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance}] ohm",//correct answser!
          	"[9 * 9 / (${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance})]",
          	//"[9 * 9 / (${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance})] incorrectUnit",
          	"[1 / (${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance})]",
          	//"[1 / (${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance})] incorrectUnit",
          ]
        }
      ]
    }
  ]
};<commit_msg>new setup<commit_after>sparks.jsonActivity = {
  "title": "Measuring a Series Circuit",
  "show_multimeter": "true",
  "disable_multimeter_position": "r",//r,dcv,acv,dca,diode,hfe,c_10a,p_9v",
  "circuit": [
      {
        "type": "resistor",
        "UID": "r1",
        "connections": "b23,b17",
        "label": "R1",
        //"resistance": "100"
      },
      {
        "type": "resistor",
        "UID": "r2",
        "connections": "c17,c11",
        "label": "R2",
        //"resistance": "100"
      },
      {
        "type": "resistor",
        "UID": "r3",
        "connections": "d11,d5",
        "label": "R3",
        //"resistance": "100"
      },
      {
        "type": "wire",
        "connections": "left_positive20,a23"
      },
      {
        "type": "wire",
        "connections": "left_negative3,a5"
      }
   ],

  "questions": [
    {
      "prompt": "What are the measured values of",
      "subquestions": [
        {
          "prompt": "Vtot:",
          "shortPrompt": "Total voltage across R1, R2, and R3",
          "correct_answer": "9",
          "correct_units": "V"
        },
        {
          "prompt": "Itot:",
          "shortPrompt": "Current through R1, R2, and R3",
          "correct_answer": "[9 / (${r1.nominalResistance} + ${r2.nominalResistance} + ${r3.nominalResistance})]",
          "correct_units": "A"
        },
        {
          "prompt": "Rtot:",
          "shortPrompt": "Total resistance of R1, R2, and R3",
          "correct_answer": "[${r1.nominalResistance}+ ${r2.nominalResistance}+ ${r3.nominalResistance}]",
          "correct_units": "ohms"
        }
      ]
    }
  ]
};<|endoftext|>


<commit_before>'use strict'

const iif = require('gulp-if')
const filter = require('gulp-filter')
const ts = require('gulp-typescript')
const sourcemaps = require('gulp-sourcemaps')
const util = require('gulp-util')

exports.dep = ['clean:js']
exports.fn = function (gulp, paths, mode, done) {
  var tsProject = ts.createProject('tsconfig.json')
  var tsResult = tsProject.src()
    .pipe(iif(mode.production, filter(['**/*', '!test/**'])))
    .pipe(iif(!mode.production, sourcemaps.init()))
    .pipe(ts(tsProject))

  return tsResult.js
    .pipe(iif(!mode.production, sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var truncatedSourcePath = sourcePath.substr(sourcePath.lastIndexOf('/') + 1)
        util.log('SourcePath within source map truncated to:', util.colors.cyan(truncatedSourcePath))
        return truncatedSourcePath
      }
    })))
    .pipe(gulp.dest('.'))
}
<commit_msg>Adjust method call to gulp-typescript 3 api.<commit_after>'use strict'

const iif = require('gulp-if')
const filter = require('gulp-filter')
const ts = require('gulp-typescript')
const sourcemaps = require('gulp-sourcemaps')
const util = require('gulp-util')

exports.dep = ['clean:js']
exports.fn = function (gulp, paths, mode, done) {
  var tsProject = ts.createProject('tsconfig.json')
  var tsResult = tsProject.src()
    .pipe(iif(mode.production, filter(['**/*', '!test/**'])))
    .pipe(iif(!mode.production, sourcemaps.init()))
    .pipe(tsProject())

  return tsResult.js
    .pipe(iif(!mode.production, sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var truncatedSourcePath = sourcePath.substr(sourcePath.lastIndexOf('/') + 1)
        util.log('SourcePath within source map truncated to:', util.colors.cyan(truncatedSourcePath))
        return truncatedSourcePath
      }
    })))
    .pipe(gulp.dest('.'))
}
<|endoftext|>


<commit_before>Package.describe({
  name: 'ecmascript',
  version: '0.11.0',
  summary: 'Compiler plugin that supports ES2015+ in all .js files',
  documentation: 'README.md'
});

Package.registerBuildPlugin({
  name: 'compile-ecmascript',
  use: ['babel-compiler'],
  sources: ['plugin.js']
});

Package.onUse(function (api) {
  api.use('isobuild:compiler-plugin@1.0.0');
  api.use('babel-compiler');

  // The following api.imply calls should match those in
  // ../coffeescript/package.js.
  api.imply('modules');
  api.imply('ecmascript-runtime');
  api.imply('babel-runtime');
  api.imply('promise');

  // Runtime support for Meteor 1.5 dynamic import(...) syntax.
  api.imply('dynamic-import');

  api.addFiles("ecmascript.js", "server");
  api.export("ECMAScript", "server");
});

Package.onTest(function (api) {
  api.use(["tinytest", "underscore"]);
  api.use(["es5-shim", "ecmascript", "babel-compiler"]);
  api.addFiles("runtime-tests.js");
  api.addFiles("transpilation-tests.js", "server");

  api.addFiles("bare-test.js");
  api.addFiles("bare-test-file.js", ["client", "server"], {
    bare: true
  });
});
<commit_msg>Bump ecmascript patch version to 0.11.1.<commit_after>Package.describe({
  name: 'ecmascript',
  version: '0.11.1',
  summary: 'Compiler plugin that supports ES2015+ in all .js files',
  documentation: 'README.md'
});

Package.registerBuildPlugin({
  name: 'compile-ecmascript',
  use: ['babel-compiler'],
  sources: ['plugin.js']
});

Package.onUse(function (api) {
  api.use('isobuild:compiler-plugin@1.0.0');
  api.use('babel-compiler');

  // The following api.imply calls should match those in
  // ../coffeescript/package.js.
  api.imply('modules');
  api.imply('ecmascript-runtime');
  api.imply('babel-runtime');
  api.imply('promise');

  // Runtime support for Meteor 1.5 dynamic import(...) syntax.
  api.imply('dynamic-import');

  api.addFiles("ecmascript.js", "server");
  api.export("ECMAScript", "server");
});

Package.onTest(function (api) {
  api.use(["tinytest", "underscore"]);
  api.use(["es5-shim", "ecmascript", "babel-compiler"]);
  api.addFiles("runtime-tests.js");
  api.addFiles("transpilation-tests.js", "server");

  api.addFiles("bare-test.js");
  api.addFiles("bare-test-file.js", ["client", "server"], {
    bare: true
  });
});
<|endoftext|>


<commit_before>/*
* Inline script loader
* https://github.com/ytiurin/inlinescriptloader.js
*
* The MIT License (MIT)
* https://github.com/ytiurin/inlinescriptloader.js/blob/master/LICENSE
*
* September 14, 2015
*/

'use strict';

!function(){

var

//state variables
pathStack=[],scriptQueue=[],pathMap={},

//service variables
rq=new XMLHttpRequest,importPtrn='"import ',

//internal objects aliases
args=arguments,storage,cl=console,

//properties names
nmError='error',nmLength='length',nmPush='push',nmSplice='splice',
nmIndexOf='indexOf',nmSubstring='substring',nmGetItem='getItem',
nmSetItem='setItem',nmResponceURL='responseURL',
nmResponceText='responseText',nmGetResponceHeader='getResponseHeader',
nmLastModif="last-modified";

function isFailStatus(status)
{
  return -1<[4,5][nmIndexOf](parseInt(status/100));
}

function performRequest(type,path,handler)
{
  rq.onload=handler;
  // anticache parameter affects on already loaded scripts usage effeciency
  // '?'+(new Date().getTime())
  rq.open(type,path,true);
  rq.send();
}

function queueScriptAndContinue(scriptData)
{
  var dependencies=[];

  //remove repeating dependency
  for(var i=scriptQueue[nmLength];i--;)
    if(scriptQueue[i].url===scriptData.url)
      scriptQueue[nmSplice](i,1);

  //retrieve dependencies
  var t=scriptData.text.replace(/'|"/g,'"');
  var p1,p2,dp,words;

  for(;-1<(p1=t[nmIndexOf](importPtrn,p1));p1=p2+1){
    dp={};
    p2=t[nmIndexOf]('"',p1+1);
    words=t[nmSubstring](p1,p2).split(' ');
    if(words[1]){
      dp.path=words[1];
      if(words[2]==='from'&&words[3]){
        dp.name=words[1];
        dp.path=words[3];
      }
      pathStack[nmSplice](0,0,dp.path);
    }
  }

  scriptData.dependencies=dependencies;
  scriptQueue[nmSplice](0,0,scriptData);
  iterateScriptLoad();
}

function loadScriptBody(path)
{
  performRequest("get",path,
    function(){
      if(!isFailStatus(this.status)){
        //store script
        if(userConf.cache&&storage){
          try{
            storage[nmSetItem](path+'[url]',this[nmResponceURL]);
            storage[nmSetItem](path+'[text]',this[nmResponceText]);
            storage[nmSetItem](path+'[time]',this[nmGetResponceHeader](
              nmLastModif));
          }
          catch(e){
            cl.warn('Caching script failed because: '+e.message);
          }
        }

        queueScriptAndContinue({url:this[nmResponceURL],
          text:this[nmResponceText],source:'remote'});
      }
      else
        cl[nmError]('Failed loding '+path+': '+this.statusText);
    });
}

function iterateScriptLoad()
{
  if(pathStack[nmLength]){
    //fill script stack
    var path=pathStack[nmSplice](0,1);

    var lurl,ltext,ltime;
    if(userConf.cache&&storage&&
      //get script from storage
      (lurl=storage[nmGetItem](path+'[url]'))!==null&&
      (ltext=storage[nmGetItem](path+'[text]'))!==null&&
      (ltime=storage[nmGetItem](path+'[time]'))!==null){

      //compare local and remote script time
      performRequest("head",path,
        function(){
          var cacheExpired=this[nmGetResponceHeader](nmLastModif)!==ltime;

          if(!isFailStatus(this.status)&&cacheExpired)
            loadScriptBody(path);
          else
            queueScriptAndContinue({url:lurl,text:ltext,source:'local'});
        });
    }
    else
      //get remote script if not cached
      loadScriptBody(path);
  }
  else{
    //execute script stack
    var r,p,dps;
    for(var i=0;i


<commit_before>/*
 * Copyright 2013 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var UglifyJS = require("uglify-js");
var grunt = require('./grunt').grunt();

var acceptedAriaMethods = {
    'classDefinition' : 1,
    'interfaceDefinition' : 1,
    'beanDefinitions' : 1,
    'tplScriptDefinition' : 1
};

var getBaseLogicalPath = function (classpath) {
    return classpath.replace(/\./g, '/');
};

var createGetLogicalPathFn = function (extension) {
    return function (classpath) {
        return getBaseLogicalPath(classpath) + extension;
    };
};

var getLogicalPath = {
    JS : createGetLogicalPathFn('.js'),
    TPL : createGetLogicalPathFn('.tpl'),
    RES : createGetLogicalPathFn('.js'),
    CSS : createGetLogicalPathFn('.tpl.css'),
    TML : createGetLogicalPathFn('.tml'),
    CML : createGetLogicalPathFn('.cml'),
    TXT : createGetLogicalPathFn('.tpl.txt')
};

var appendString = function (stringLitteral, mapFunction, array) {
    if (stringLitteral instanceof UglifyJS.AST_String) {
        var value = mapFunction(stringLitteral.value);
        array.push(value);
    } else {
        reportError('Expected a string litteral.', stringLitteral);
    }
};

var appendMappedStringLitterals = function (stringLitterals, mapFunction, array) {
    for (var i = 0, l = stringLitterals.length; i < l; i++) {
        appendString(stringLitterals[i], mapFunction, array);
    }
};

var appendMappedMapValueStringLitterals = function (object, mapFunction, array) {
    var properties = object.properties;
    for (var i = 0, l = properties.length; i < l; i++) {
        appendString(properties[i].value, mapFunction, array);
    }
};

var findMapValue = function (astObject, key) {
    var properties = astObject.properties;
    for (var i = 0, l = properties.length; i < l; i++) {
        var curProperty = properties[i];
        if (curProperty.key === key) {
            return curProperty.value;
        }
    }
};

var reportError = function (errorMsg, item) {
    var msg = ["ATDependencies warning: ", errorMsg.yellow];
    var file = item.start.file;
    if (file) {
        msg.push(" in ", file.cyan, ' (line ', item.start.line, ')');
    }
    msg.push('\n ', item.print_to_string().yellow);
    grunt.log.writeln(msg.join(''));
};

var checkAriaDefinition = function (walker) {
    // check that the walker is positioned in the argument of
    // an Aria.classDefinition, Aria.interfaceDefinition, Aria.tplScriptDefinition or Aria.beanDefinitions
    var parent = walker.parent(1);
    if (parent instanceof UglifyJS.AST_Call) {
        var expr = parent.expression;
        if (expr instanceof UglifyJS.AST_Dot) {
            var aria = expr.expression;
            if (aria instanceof UglifyJS.AST_SymbolRef && aria.name === "Aria" &&
                    acceptedAriaMethods.hasOwnProperty(expr.property)) {
                return true;
            }
        }
    }
    // To check what is happening:
    // reportError('Not taking the property into account.', walker.self())
    return false;
};

var handleArray = function (mapFunction) {
    return function (value, res, walker) {
        if (value instanceof UglifyJS.AST_Array) {
            appendMappedStringLitterals(value.elements, mapFunction, res);
        } else {
            reportError('Expected an array litteral', walker.self());
        }
    };
};

var handleMap = function (mapFunction) {
    return function (value, res, walker) {
        if (value instanceof UglifyJS.AST_Object) {
            appendMappedMapValueStringLitterals(value, mapFunction, res);
        } else {
            reportError('Expected an object litteral', walker.self());
        }
    };
};

var processNames = {
    '$dependencies' : handleArray(getLogicalPath.JS),
    '$extends' : function (value, res, walker) {
        var extendsType;
        var extendsTypeValue = findMapValue(walker.parent(0), '$extendsType');
        if (extendsTypeValue && extendsTypeValue instanceof UglifyJS.AST_String) {
            extendsType = extendsTypeValue.value;
        }
        if (!getLogicalPath.hasOwnProperty(extendsType)) {
            extendsType = "JS";
        }
        appendString(value, getLogicalPath[extendsType], res);
    },
    '$implements' : handleArray(getLogicalPath.JS),
    '$namespaces' : handleMap(getLogicalPath.JS),
    '$css' : handleArray(getLogicalPath.CSS),
    '$templates' : handleArray(getLogicalPath.TPL),
    '$texts' : handleMap(getLogicalPath.TXT)
};

/**
 * Analyses the AST of an Aria Templates file and returns its dependencies as an array of logical paths.
 * @param {Object} ast uglify-js abstract syntax tree
 * @return {Array} array of dependencies
 */
var getATDependencies = function (ast) {
    var res = [];
    var walker = new UglifyJS.TreeWalker(function (node) {
        if (node instanceof UglifyJS.AST_ObjectProperty && processNames.hasOwnProperty(node.key)) {
            if (checkAriaDefinition(walker)) {
                processNames[node.key](node.value, res, walker);
            }
        }
    });
    ast.walk(walker);
    return res;
};

module.exports = getATDependencies;<commit_msg>In ATDependencies, added support for $macrolibs and $csslibs dependencies.<commit_after>/*
 * Copyright 2013 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var UglifyJS = require("uglify-js");
var grunt = require('./grunt').grunt();

var acceptedAriaMethods = {
    'classDefinition' : 1,
    'interfaceDefinition' : 1,
    'beanDefinitions' : 1,
    'tplScriptDefinition' : 1
};

var getBaseLogicalPath = function (classpath) {
    return classpath.replace(/\./g, '/');
};

var createGetLogicalPathFn = function (extension) {
    return function (classpath) {
        return getBaseLogicalPath(classpath) + extension;
    };
};

var getLogicalPath = {
    JS : createGetLogicalPathFn('.js'),
    TPL : createGetLogicalPathFn('.tpl'),
    RES : createGetLogicalPathFn('.js'),
    CSS : createGetLogicalPathFn('.tpl.css'),
    TML : createGetLogicalPathFn('.tml'),
    CML : createGetLogicalPathFn('.cml'),
    TXT : createGetLogicalPathFn('.tpl.txt')
};

var appendString = function (stringLitteral, mapFunction, array) {
    if (stringLitteral instanceof UglifyJS.AST_String) {
        var value = mapFunction(stringLitteral.value);
        array.push(value);
    } else {
        reportError('Expected a string litteral.', stringLitteral);
    }
};

var appendMappedStringLitterals = function (stringLitterals, mapFunction, array) {
    for (var i = 0, l = stringLitterals.length; i < l; i++) {
        appendString(stringLitterals[i], mapFunction, array);
    }
};

var appendMappedMapValueStringLitterals = function (object, mapFunction, array) {
    var properties = object.properties;
    for (var i = 0, l = properties.length; i < l; i++) {
        appendString(properties[i].value, mapFunction, array);
    }
};

var findMapValue = function (astObject, key) {
    var properties = astObject.properties;
    for (var i = 0, l = properties.length; i < l; i++) {
        var curProperty = properties[i];
        if (curProperty.key === key) {
            return curProperty.value;
        }
    }
};

var reportError = function (errorMsg, item) {
    var msg = ["ATDependencies warning: ", errorMsg.yellow];
    var file = item.start.file;
    if (file) {
        msg.push(" in ", file.cyan, ' (line ', item.start.line, ')');
    }
    msg.push('\n ', item.print_to_string().yellow);
    grunt.log.writeln(msg.join(''));
};

var checkAriaDefinition = function (walker) {
    // check that the walker is positioned in the argument of
    // an Aria.classDefinition, Aria.interfaceDefinition, Aria.tplScriptDefinition or Aria.beanDefinitions
    var parent = walker.parent(1);
    if (parent instanceof UglifyJS.AST_Call) {
        var expr = parent.expression;
        if (expr instanceof UglifyJS.AST_Dot) {
            var aria = expr.expression;
            if (aria instanceof UglifyJS.AST_SymbolRef && aria.name === "Aria" &&
                    acceptedAriaMethods.hasOwnProperty(expr.property)) {
                return true;
            }
        }
    }
    // To check what is happening:
    // reportError('Not taking the property into account.', walker.self())
    return false;
};

var handleArray = function (mapFunction) {
    return function (value, res, walker) {
        if (value instanceof UglifyJS.AST_Array) {
            appendMappedStringLitterals(value.elements, mapFunction, res);
        } else {
            reportError('Expected an array litteral', walker.self());
        }
    };
};

var handleMap = function (mapFunction) {
    return function (value, res, walker) {
        if (value instanceof UglifyJS.AST_Object) {
            appendMappedMapValueStringLitterals(value, mapFunction, res);
        } else {
            reportError('Expected an object litteral', walker.self());
        }
    };
};

var processNames = {
    '$dependencies' : handleArray(getLogicalPath.JS),
    '$extends' : function (value, res, walker) {
        var extendsType;
        var extendsTypeValue = findMapValue(walker.parent(0), '$extendsType');
        if (extendsTypeValue && extendsTypeValue instanceof UglifyJS.AST_String) {
            extendsType = extendsTypeValue.value;
        }
        if (!getLogicalPath.hasOwnProperty(extendsType)) {
            extendsType = "JS";
        }
        appendString(value, getLogicalPath[extendsType], res);
    },
    '$implements' : handleArray(getLogicalPath.JS),
    '$namespaces' : handleMap(getLogicalPath.JS),
    '$css' : handleArray(getLogicalPath.CSS),
    '$templates' : handleArray(getLogicalPath.TPL),
    '$texts' : handleMap(getLogicalPath.TXT),
    '$macrolibs' : handleArray(getLogicalPath.TML),
    '$csslibs' : handleArray(getLogicalPath.CML)
};

/**
 * Analyses the AST of an Aria Templates file and returns its dependencies as an array of logical paths.
 * @param {Object} ast uglify-js abstract syntax tree
 * @return {Array} array of dependencies
 */
var getATDependencies = function (ast) {
    var res = [];
    var walker = new UglifyJS.TreeWalker(function (node) {
        if (node instanceof UglifyJS.AST_ObjectProperty && processNames.hasOwnProperty(node.key)) {
            if (checkAriaDefinition(walker)) {
                processNames[node.key](node.value, res, walker);
            }
        }
    });
    ast.walk(walker);
    return res;
};

module.exports = getATDependencies;<|endoftext|>


<commit_before>;(function(mag) {

"use strict";

  var mod = {
    modules: [],
    controllers: [],
    elements: []
  }

  mod.submodule = function(module, args) {

    var controller = function(args) {
      return (module.controller || function() {}).apply(this, args)
    }.bind({}, args)

    var view = function(ctrl) {
      if (arguments.length > 1) args = args.concat([].slice.call(arguments, 1))
      var template = module.view.apply(module, args ? [ctrl].concat(args) : [ctrl])
      if (args[0] && args[0].key != null) template.attrs.key = args[0].key
      // There's no template return ??
      return template
    }

    controller.$original = module.controller

    var output = {
      controller: controller,
      view: view
    }
    if (args[0] && args[0].key != null) output.attrs = {
      key: args[0].key
    }
    return output
  }

  mod.getArgs = function(i) {
    var args = mod.modules[i].controller && mod.modules[i].controller.$$args ? [mod.controllers[i]].concat(mod.modules[i].controller.$$args) : [mod.controllers[i]]
  // console.log(i,args[0])
    return args
  }
  mag.mod = mod

})(window.mag || {})
<commit_msg>getController function added<commit_after>;
(function(mag) {

  "use strict";

  var mod = {
    modules: [],
    controllers: [],
    elements: []
  }

  mod.getController = function(mod, element, fill) {
    var controller

    // FireFox support only
    if (typeof Proxy !== 'undefined') {
      controller = new Proxy(new mod.controller, {
        get: function(target, prop) {
          if (target[prop] === undefined && ['watchers', 'toJSON', 'called', 'onload', 'onunload'].indexOf(prop) === -1) {
            var a = fill.find(element, prop),
              v
            if (a[0]) {
              if (a[0].value && a[0].value.length > 0) {
                v = a[0].value
                if (a[0].type && a[0].type == 'checkbox') {
                  v = {
                    _text: v,
                    _checked: a[0].checked
                  }
                }
              }
              if (a[0].innerText && a[0].innerText.length > 0)
                v = a[0].innerText
              if (a[0].innerHTML && a[0].innerHTML.length > 0)
                v = a[0].innerHTML
            }
            return v
          }
          return target[prop]
        }
      })
    } else {
      controller = new mod.controller
    }
    return controller
  }

  mod.submodule = function(module, args) {
    var controller = function(args) {
      return (module.controller || function() {}).apply(this, args)
    }.bind({}, args)

    var view = function(ctrl) {
      if (arguments.length > 1) args = args.concat([].slice.call(arguments, 1))
      var template = module.view.apply(module, args ? [ctrl].concat(args) : [ctrl])
      if (args[0] && args[0].key != null) template.attrs.key = args[0].key
      // There's no template return ??
      return template
    }

    controller.$original = module.controller

    var output = {
      controller: controller,
      view: view
    }
    if (args[0] && args[0].key != null) output.attrs = {
      key: args[0].key
    }
    return output
  }

  mod.getArgs = function(i) {
    var args = mod.modules[i].controller && mod.modules[i].controller.$$args ? [mod.controllers[i]].concat(mod.modules[i].controller.$$args) : [mod.controllers[i]]
    return args
  }
  mag.mod = mod

})(window.mag || {})
<|endoftext|>


<commit_before>/**
 * @file TableContent component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import BaseTable from '../_BaseTable';

import Theme from '../Theme';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortType from '../_statics/SortType';

import Util from '../_vendors/Util';

class TableContent extends Component {

    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortType = SortType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    /**
     * slice data by pagination
     * @param data
     * @returns {*[]}
     */
    paginateData = (data = this.props.data) => {

        const {pagination} = this.props,
            {pageSize, page} = pagination,
            len = data.length;

        let start = page * pageSize,
            stop = start + pageSize;

        start = start < 0 ? 0 : start;
        stop = stop > len ? len : stop;

        return data.slice(start, stop);

    };

    render() {

        const {
            className, style, data, isPaginated,
            ...restProps
        } = this.props;

        return (

                <BaseTable {...restProps}
                           data={isPaginated ? this.paginateData() : data}
                           isPaginated={isPaginated}/>

        );

    }
}

TableContent.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    /**
     * Default sort type of table.
     */
    defaultSortType: PropTypes.oneOf(Util.enumerateValue(SortType)),

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * The class name of header.
         */
        headerClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headerStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headerRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of td.
         */
        cellClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        cellStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        cellRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footerClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footerStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footerRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sort field.
         */
        sortProp: PropTypes.string,

        defaultSortType: PropTypes.oneOf(Util.enumerateValue(SortType)),

        span: PropTypes.func

    })).isRequired,

    data: PropTypes.array,

    sort: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortType))
    }),

    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,

    onSort: PropTypes.func

};

TableContent.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    defaultSortType: SortType.ASC,

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20]

};

export default TableContent;
<commit_msg>update TableContent<commit_after>/**
 * @file TableContent component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import BaseTable from '../_BaseTable';

import Theme from '../Theme';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';

class TableContent extends Component {

    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    /**
     * sort data by sorting
     * @param data
     * @returns {*[]}
     */
    sortData = (data = this.props.data) => {
        const {sorting, sortingFunc} = this.props;
        return sorting ? TableCalculation.sortTableData(data, sorting, sortingFunc) : data;
    };

    /**
     * slice data by pagination
     * @param data
     * @returns {*[]}
     */
    paginateData = (data = this.props.data) => {

        const {pagination} = this.props;

        if (!pagination) {
            return data;
        }

        const {pageSize, page} = pagination,
            len = data.length;

        let start = page * pageSize,
            stop = start + pageSize;

        start = start < 0 ? 0 : start;
        stop = stop > len ? len : stop;

        return data.slice(start, stop);

    };

    render() {

        const {
            className, style, data, isPaginated,
            ...restProps
        } = this.props;

        return (

                <BaseTable {...restProps}
                           data={this.paginateData(this.sortData(data))}
                           isPaginated={isPaginated}/>

        );

    }
}

TableContent.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * The class name of header.
         */
        headerClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headerStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headerRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of td.
         */
        cellClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        cellStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        cellRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footerClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footerStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footerRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        span: PropTypes.func

    })).isRequired,

    data: PropTypes.array,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,

    /**
     * callback
     */
    onSortChange: PropTypes.func

};

TableContent.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20]

};

export default TableContent;
<|endoftext|>


<commit_before>const mkdirp = require('mkdirp');
const sassGlob = require('node-sass-glob');
const sass = require('node-sass');
const fs = require('fs');
const chokidar = require('chokidar');

compile();

chokidar
  .watch('src/stylesheets/**/*.scss', { ignoreInitial: true })
  .on('all', compile);

function compile(event, path) {
  sass.render({
    file: 'src/stylesheets/main.scss',
    includePaths: ['src/stylesheets/'],
    importer: sassGlob
  }, (err, result) => {
    if (err) { throw err; }
    if (path) {
      process.stdout.write(`=> ${event.toUpperCase()} ${path}\n`);
    }

    const css = { dir: 'build/assets/css', name: 'main.css' };

    mkdirp(css.dir, (err) => {
      if (err) { throw err; }

      fs.writeFile(`${css.dir}/${css.name}`, result.css, (err) => {
        if (err) { throw err; }
        process.stdout.write(`=> Wrote CSS to ${css.dir}/${css.name}\n`);
      });
    });
  });
}
<commit_msg>fix(task): sass shutdowned when it got an error<commit_after>const mkdirp = require('mkdirp');
const sassGlob = require('node-sass-glob');
const sass = require('node-sass');
const fs = require('fs');
const chokidar = require('chokidar');

compile();

chokidar
  .watch('src/stylesheets/**/*.scss', { ignoreInitial: true })
  .on('all', compile);

function compile(event, path) {
  sass.render({
    file: 'src/stylesheets/main.scss',
    includePaths: ['src/stylesheets/'],
    importer: sassGlob
  }, (err, result) => {
    if (err) { return console.error(err); }
    if (path) {
      process.stdout.write(`=> ${event.toUpperCase()} ${path}\n`);
    }

    const css = { dir: 'build/assets/css', name: 'main.css' };

    mkdirp(css.dir, (err) => {
      if (err) { throw err; }

      fs.writeFile(`${css.dir}/${css.name}`, result.css, (err) => {
        if (err) { throw err; }
        process.stdout.write(`=> Wrote CSS to ${css.dir}/${css.name}\n`);
      });
    });
  });
}
<|endoftext|>


<commit_before>var KEY_ENTER = 13,
	KEY_LEFT = 37,
	KEY_UP = 38,
	KEY_RIGHT = 39,
	KEY_DOWN = 40,

	canvas = null,
	ctx = null,
	lastPress = null,
	pause = true,
	x = 50,
	y = 50,
	player = null,
	puerta = null,
	diana = null,
	puntos = 0,
	numPuertas = 0,
	dir = 1,
	gameover = false,
	init = true;

function Rectangle(x, y, width, height) {
	this.x = (x == null) ? 0 : x;
	this.y = (y == null) ? 0 : y;
	this.width = (width == null) ? 0 : width;
	this.height = (height == null) ? this.width : height;
	this.intersects = function (rect) {
					if (rect == null) {
						window.console.warn('Missing parameters on function intersects');
					} else {
						return (this.x < rect.x + rect.width && this.x + this.width > rect.x && this.y < rect.y + rect.height && this.y + this.height > rect.y);
					}
				};
	this.fill = function (ctx) {
					if (ctx == null) {
						window.console.warn('Missing parameters on function fill');
					} else {
						ctx.fillRect(this.x, this.y, this.width, this.height);
					}
				};
}

function random(max) {
		return Math.floor(Math.random() * max);
}

window.requestAnimationFrame = (function () {
					return window.requestAnimationFrame ||
						window.mozRequestAnimationFrame ||
						window.webkitRequestAnimationFrame ||
						function (callback) {
							window.setTimeout(callback, 10);
						};
				}());

document.addEventListener('keydown', function (evt) {
					lastPress = evt.which;
				}, false);

function paint(ctx) {
	// Clean canvas
	ctx.fillStyle = '#000';
	ctx.fillRect(0, 0, canvas.width, canvas.height);

	//Player
	ctx.fillStyle = '#0f0';
	player.fill(ctx);

	//Puerta y diana
	ctx.fillStyle = '#898989';
	puerta.fill(ctx);
	ctx.fillStyle = '#000';
	diana. fill(ctx);

	// Debug last key pressed
	ctx.fillStyle = '#fff';
	//ctx.fillText('Last Press: ' + lastPress, 0, 20);

	//Puntos
	ctx.fillText('Puntos: ' + puntos, 0, 10);

	// Draw pause
	if (pause) {
		ctx.textAlign = 'center';
		ctx.font="80px Arial";
		ctx.shadowColor = '#f00'
		if(!init)
			if(gameover){
				ctx.fillText('GAMEOVER', 300, 150);
			}else{
				ctx.fillText('PAUSE', 300, 150);
			}
		}else{
			ctx.fillText('PLAY', 300, 150);
		}
		init=false;
		ctx.font="14px Arial";
		ctx.textAlign = 'left';
	}
}

function reset() {
	puntos = 0;
	numPuertas = 0;
	dir = 1;
	player.x = 40;
	player.y = 40;
	puerta.width = 30;
	puerta.height = 10;
	puerta.x = (random(canvas.width / 10 - 2) * 10)+10;
	puerta.y = (random(canvas.height / 10 - 2) * 10)+10;
	diana.x = puerta.x + 10;
	diana.y = puerta.y;
	gameover = false;
}

function act() {
	if (!pause) {
		if(gameover) reset();

		// Change Direction
		if (lastPress == KEY_UP) { dir = 0; }
		if (lastPress == KEY_RIGHT) { dir = 1; }
		if (lastPress == KEY_DOWN) { dir = 2; }
		if (lastPress == KEY_LEFT) { dir = 3; }

		// Move Rect
		if (dir == 0) { player.y -= 10; }
		if (dir == 1) { player.x += 10; }
		if (dir == 2) { player.y += 10; }
		if (dir == 3) { player.x -= 10; }

		// Out Screen
		if (player.x >= canvas.width) { player.x -= 10; pause = true; gameover = true; }
		if (player.y >= canvas.height) { player.y -= 10; pause = true; gameover = true; }
		if (player.x < 0) { player.x = 0; pause = true; gameover = true; }
		if (player.y < 0) { player.y = 0; pause = true; gameover = true; }

		if(player.intersects(puerta) || player.intersects(diana)){
			if(player.intersects(puerta)){
				puntos += 5;
				numPuertas++;
			}
			if(player.intersects(diana)){
				puntos += 5;
				numPuertas++;
			}

			var orientacion = random(2);
			if(orientacion == 1){
				puerta.width = 30;
				puerta.height = 10;
				puerta.x = (random(canvas.width / 10 - 3) * 10) + 10; //-2 y -3 para evitar que la diana no esté en pegada a la pared
				puerta.y = (random(canvas.height / 10 - 2) * 10) + 10;
				diana.x = puerta.x + 10;
				diana.y = puerta.y;
			}
			else if(orientacion == 0){
				puerta.width = 10;
				puerta.height = 30;
				puerta.x = (random(canvas.width / 10 - 2) * 10) + 10;
				puerta.y = (random(canvas.height / 10 - 3) * 10) + 10;
				diana.x = puerta.x;
				diana.y = puerta.y + 10;
			}
		}
	}
		// Pause/Unpause
	if (lastPress == KEY_ENTER) {
		pause = !pause;
		lastPress = null;
	}
}

function repaint() {
	window.requestAnimationFrame(repaint);
	paint(ctx);
}

function run() {
	setTimeout(run, 75/(1+(numPuertas/10)));
	act();
}

function init() {
	// Get canvas and context
	canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d');

	player = new Rectangle(40, 40, 10, 10);
	diana = new Rectangle(80, 90, 10, 10);
	puerta = new Rectangle(80, 80, 10, 30);

	// Start game
	run();
	repaint();
}

window.addEventListener('load', init, false);<commit_msg>init4<commit_after>var KEY_ENTER = 13,
	KEY_LEFT = 37,
	KEY_UP = 38,
	KEY_RIGHT = 39,
	KEY_DOWN = 40,

	canvas = null,
	ctx = null,
	lastPress = null,
	pause = true,
	x = 50,
	y = 50,
	player = null,
	puerta = null,
	diana = null,
	puntos = 0,
	numPuertas = 0,
	dir = 1,
	gameover = false,
	init = true;

function Rectangle(x, y, width, height) {
	this.x = (x == null) ? 0 : x;
	this.y = (y == null) ? 0 : y;
	this.width = (width == null) ? 0 : width;
	this.height = (height == null) ? this.width : height;
	this.intersects = function (rect) {
					if (rect == null) {
						window.console.warn('Missing parameters on function intersects');
					} else {
						return (this.x < rect.x + rect.width && this.x + this.width > rect.x && this.y < rect.y + rect.height && this.y + this.height > rect.y);
					}
				};
	this.fill = function (ctx) {
					if (ctx == null) {
						window.console.warn('Missing parameters on function fill');
					} else {
						ctx.fillRect(this.x, this.y, this.width, this.height);
					}
				};
}

function random(max) {
		return Math.floor(Math.random() * max);
}

window.requestAnimationFrame = (function () {
					return window.requestAnimationFrame ||
						window.mozRequestAnimationFrame ||
						window.webkitRequestAnimationFrame ||
						function (callback) {
							window.setTimeout(callback, 10);
						};
				}());

document.addEventListener('keydown', function (evt) {
					lastPress = evt.which;
				}, false);

function paint(ctx) {
	// Clean canvas
	ctx.fillStyle = '#000';
	ctx.fillRect(0, 0, canvas.width, canvas.height);

	//Player
	ctx.fillStyle = '#0f0';
	player.fill(ctx);

	//Puerta y diana
	ctx.fillStyle = '#898989';
	puerta.fill(ctx);
	ctx.fillStyle = '#000';
	diana. fill(ctx);

	// Debug last key pressed
	ctx.fillStyle = '#fff';
	//ctx.fillText('Last Press: ' + lastPress, 0, 20);

	//Puntos
	ctx.fillText('Puntos: ' + puntos, 0, 10);

	// Draw pause
	if (pause) {
		ctx.textAlign = 'center';
		ctx.font="80px Arial";
		ctx.shadowColor = '#f00';
		if(!init){
			if(gameover){
				ctx.fillText('GAMEOVER', 300, 150);
			}else{
				ctx.fillText('PAUSE', 300, 150);
			}
		}else{
			ctx.fillText('PLAY', 300, 150);
		}
		init = false;
		ctx.font = "14px Arial";
		ctx.textAlign = 'left';
	}
}

function reset() {
	puntos = 0;
	numPuertas = 0;
	dir = 1;
	player.x = 40;
	player.y = 40;
	puerta.width = 30;
	puerta.height = 10;
	puerta.x = (random(canvas.width / 10 - 2) * 10)+10;
	puerta.y = (random(canvas.height / 10 - 2) * 10)+10;
	diana.x = puerta.x + 10;
	diana.y = puerta.y;
	gameover = false;
}

function act() {
	if (!pause) {
		if(gameover) reset();

		// Change Direction
		if (lastPress == KEY_UP) { dir = 0; }
		if (lastPress == KEY_RIGHT) { dir = 1; }
		if (lastPress == KEY_DOWN) { dir = 2; }
		if (lastPress == KEY_LEFT) { dir = 3; }

		// Move Rect
		if (dir == 0) { player.y -= 10; }
		if (dir == 1) { player.x += 10; }
		if (dir == 2) { player.y += 10; }
		if (dir == 3) { player.x -= 10; }

		// Out Screen
		if (player.x >= canvas.width) { player.x -= 10; pause = true; gameover = true; }
		if (player.y >= canvas.height) { player.y -= 10; pause = true; gameover = true; }
		if (player.x < 0) { player.x = 0; pause = true; gameover = true; }
		if (player.y < 0) { player.y = 0; pause = true; gameover = true; }

		if(player.intersects(puerta) || player.intersects(diana)){
			if(player.intersects(puerta)){
				puntos += 5;
				numPuertas++;
			}
			if(player.intersects(diana)){
				puntos += 5;
				numPuertas++;
			}

			var orientacion = random(2);
			if(orientacion == 1){
				puerta.width = 30;
				puerta.height = 10;
				puerta.x = (random(canvas.width / 10 - 3) * 10) + 10; //-2 y -3 para evitar que la diana no esté en pegada a la pared
				puerta.y = (random(canvas.height / 10 - 2) * 10) + 10;
				diana.x = puerta.x + 10;
				diana.y = puerta.y;
			}
			else if(orientacion == 0){
				puerta.width = 10;
				puerta.height = 30;
				puerta.x = (random(canvas.width / 10 - 2) * 10) + 10;
				puerta.y = (random(canvas.height / 10 - 3) * 10) + 10;
				diana.x = puerta.x;
				diana.y = puerta.y + 10;
			}
		}
	}
		// Pause/Unpause
	if (lastPress == KEY_ENTER) {
		pause = !pause;
		lastPress = null;
	}
}

function repaint() {
	window.requestAnimationFrame(repaint);
	paint(ctx);
}

function run() {
	setTimeout(run, 75/(1+(numPuertas/10)));
	act();
}

function init() {
	// Get canvas and context
	canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d');

	player = new Rectangle(40, 40, 10, 10);
	diana = new Rectangle(80, 90, 10, 10);
	puerta = new Rectangle(80, 80, 10, 30);

	// Start game
	run();
	repaint();
}

window.addEventListener('load', init, false);<|endoftext|>


<commit_before>// ==UserScript==
// @name        GitHub Indent Comments
// @version     1.0.16
// @description A userscript that allows you to indent & outdent blocks in the comment editor
// @license     MIT
// @author      Rob Garrison
// @namespace   https://github.com/Mottie
// @include     https://github.com/*
// @include     https://gist.github.com/*
// @run-at      document-idle
// @grant       GM_addStyle
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_registerMenuCommand
// @connect     github.com
// @require     https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=952601
// @require     https://greasyfork.org/scripts/28239-rangy-inputs-mod-js/code/rangy-inputs-modjs.js?version=181769
// @icon        https://github.githubassets.com/pinned-octocat.svg
// @updateURL   https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-indent-comments.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-indent-comments.user.js
// @supportURL  https://github.com/Mottie/GitHub-userscripts/issues
// ==/UserScript==
(() => {
	"use strict";

	let spaceSize = GM_getValue("space-size", 2);

	const icons = {
		indent: `
			<svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16">
				<path d="M12 13c0 .6 0 1-.9 1H.9c-.9 0-.9-.4-.9-1s0-1 .9-1h10.2c.88 0 .88.4.88 1zM.92 4h10.2C12 4 12 3.6 12 3s0-1-.9-1H.92c-.9 0-.9.4-.9 1s0 1 .9 1zM11.5 7h-5C6 7 6 7.4 6 8s0 1 .5 1h5c.5 0 .5-.4.5-1s0-1-.5-1zm-7 1L0 5v6z"/>
			</svg>`,
		outdent: `
			<svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16">
				<path d="M12 13c0 .6 0 1-.9 1H.9c-.9 0-.9-.4-.9-1s0-1 .9-1h10.2c.88 0 .88.4.88 1zM.92 4h10.2C12 4 12 3.6 12 3s0-1-.9-1H.92c-.9 0-.9.4-.9 1s0 1 .9 1zm10.7 3H6.4c-.46 0-.4.4-.4 1s-.06 1 .4 1h5.2c.47 0 .4-.4.4-1s.07-1-.4-1zM0 8l4.5-3v6z"/>
			</svg>`
	};

	GM_addStyle(".ghio-in-outdent * { pointer-events:none; }");

	// Add indent & outdent buttons
	function addButtons() {
		createButton("Outdent");
		createButton("Indent");
	}

	function createButton(name) {
		const toolbars = $$(".toolbar-commenting"),
			nam = name.toLowerCase(),
			button = document.createElement("button");
		let el,
			indx = toolbars.length;
		if (indx) {
			button.type = "button";
			button.className = `ghio-${nam.toLowerCase()} ghio-in-outdent toolbar-item tooltipped tooltipped-n`;
			button.setAttribute("aria-label", `${name} Selected Text`);
			button.setAttribute("tabindex", "-1");
			button.innerHTML = icons[nam.toLowerCase()];
			while (indx--) {
				el = toolbars[indx];
				if (!$(`.ghio-${nam.toLowerCase()}`, el)) {
					el.insertBefore(button.cloneNode(true), el.childNodes[0]);
				}
			}
		}
	}

	function indent(text) {
		let result = [],
			block = new Array(parseInt(spaceSize, 10) + 1).join(" ");
		(text || "").split(/\r*\n/).forEach(line => {
			result.push(block + line);
		});
		return result.join("\n");
	}

	function outdent(text) {
		let regex = new RegExp(`^(\x20{1,${spaceSize}}|\xA0{1,${spaceSize}}|\x09)`),
			result = [];
		(text || "").split(/\r*\n/).forEach(line => {
			result.push(line.replace(regex, ""));
		});
		return result.join("\n");
	}

	function addBindings() {
		window.rangyInput.init();
		saveTabSize();
		$("body").addEventListener("click", event => {
			let textarea,
				target = event.target;
			if (target && target.classList.contains("ghio-in-outdent")) {
				textarea = closest(".previewable-comment-form", target);
				textarea = $(".comment-form-textarea", textarea);
				textarea.focus();
				setTimeout(() => {
					window.rangyInput.indentSelectedText(
						textarea,
						target.classList.contains("ghio-indent") ? indent : outdent
					);
				}, 100);
				return false;
			}
		});
		// Add Tab & Shift + Tab
		$("body").addEventListener("keydown", event => {
			if (event.key === "Tab") {
				let target = event.target;
				if (target && target.classList.contains("comment-form-textarea")) {
					event.preventDefault();
					target.focus();
					setTimeout(() => {
						window.rangyInput.indentSelectedText(
							target,
							// shift + tab = outdent
							event.getModifierState("Shift") ? outdent : indent
						);
					}, 100);
				}
			}
		});
	}

	function saveTabSize() {
		let $el = $(".gh-indent-size");
		if (!$el) {
			$el = document.createElement("style");
			$el.setAttribute("rel", "stylesheet");
			$el.className = "gh-indent-size";
			document.querySelector("head").appendChild($el);
		}
		$el.innerHTML = `.comment-form-textarea { tab-size:${spaceSize}; }`;
	}

	function $(selector, el) {
		return (el || document).querySelector(selector);
	}

	function $$(selector, el) {
		return Array.from((el || document).querySelectorAll(selector));
	}

	function closest(selector, el) {
		while (el && el.nodeType === 1) {
			if (el.matches(selector)) {
				return el;
			}
			el = el.parentNode;
		}
		return null;
	}

	// Add GM options
	GM_registerMenuCommand(
		"Indent or outdent size",
		() => {
			const spaces = GM_getValue("indentOutdentSize", spaceSize);
			let val = prompt("Enter number of spaces to indent or outdent:", spaces);
			if (val !== null && typeof val === "string") {
				spaceSize = val;
				GM_setValue("space-size", val);
				saveTabSize();
			}
		}
	);

	document.addEventListener("ghmo:container", addButtons);
	addBindings();
	addButtons();
})();
<commit_msg>Indent-comments: Update styling & code<commit_after>// ==UserScript==
// @name        GitHub Indent Comments
// @version     1.0.17
// @description A userscript that allows you to indent & outdent blocks in the comment editor
// @license     MIT
// @author      Rob Garrison
// @namespace   https://github.com/Mottie
// @include     https://github.com/*
// @include     https://gist.github.com/*
// @run-at      document-idle
// @grant       GM_addStyle
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_registerMenuCommand
// @connect     github.com
// @require     https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=952601
// @require     https://greasyfork.org/scripts/398877-utils-js/code/utilsjs.js?version=952600
// @require     https://greasyfork.org/scripts/28239-rangy-inputs-mod-js/code/rangy-inputs-modjs.js?version=181769
// @icon        https://github.githubassets.com/pinned-octocat.svg
// @updateURL   https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-indent-comments.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-indent-comments.user.js
// @supportURL  https://github.com/Mottie/GitHub-userscripts/issues
// ==/UserScript==
/* global $ $$ on make */
(() => {
	"use strict";

	let spaceSize = GM_getValue("space-size", 2);

	const icons = {
		indent: `
			<svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16">
				<path d="M12 13c0 .6 0 1-.9 1H.9c-.9 0-.9-.4-.9-1s0-1 .9-1h10.2c.88 0 .88.4.88 1zM.92 4h10.2C12 4 12 3.6 12 3s0-1-.9-1H.92c-.9 0-.9.4-.9 1s0 1 .9 1zM11.5 7h-5C6 7 6 7.4 6 8s0 1 .5 1h5c.5 0 .5-.4.5-1s0-1-.5-1zm-7 1L0 5v6z"/>
			</svg>`,
		outdent: `
			<svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16">
				<path d="M12 13c0 .6 0 1-.9 1H.9c-.9 0-.9-.4-.9-1s0-1 .9-1h10.2c.88 0 .88.4.88 1zM.92 4h10.2C12 4 12 3.6 12 3s0-1-.9-1H.92c-.9 0-.9.4-.9 1s0 1 .9 1zm10.7 3H6.4c-.46 0-.4.4-.4 1s-.06 1 .4 1h5.2c.47 0 .4-.4.4-1s.07-1-.4-1zM0 8l4.5-3v6z"/>
			</svg>`
	};

	GM_addStyle(".ghio-in-outdent * { pointer-events:none; }");

	// Add indent & outdent buttons
	function addButtons() {
		createButton("Outdent");
		createButton("Indent");
	}

	function createButton(name) {
		const nam = name.toLowerCase();
		const button = make({
			className: `ghio-${nam.toLowerCase()} ghio-in-outdent btn-link toolbar-item btn-octicon no-underline tooltipped tooltipped-n`,
			attrs: {
				"aria-label": `${name} Selected Text`,
				tabindex: "-1",
				type: "button"
			},
			html: icons[nam.toLowerCase()]
		});
		$$(".toolbar-commenting").forEach(el => {
			if (el && !$(`.ghio-${nam.toLowerCase()}`, el)) {
				el.insertBefore(button.cloneNode(true), el.childNodes[0]);
			}
		});
	}

	function indent(text) {
		let result = [];
		let block = new Array(parseInt(spaceSize, 10) + 1).join(" ");
		(text || "").split(/\r*\n/).forEach(line => {
			result.push(block + line);
		});
		return result.join("\n");
	}

	function outdent(text) {
		let regex = new RegExp(`^(\x20{1,${spaceSize}}|\xA0{1,${spaceSize}}|\x09)`);
		let result = [];
		(text || "").split(/\r*\n/).forEach(line => {
			result.push(line.replace(regex, ""));
		});
		return result.join("\n");
	}

	function addBindings() {
		window.rangyInput.init();
		saveTabSize();
		on($("body"), "click", ({ target }) => {
			if (target?.classList.contains("ghio-in-outdent")) {
				const form = target.closest(".previewable-comment-form");
				const textarea = $(".comment-form-textarea", form);
				textarea.focus();
				setTimeout(() => {
					window.rangyInput.indentSelectedText(
						textarea,
						target.classList.contains("ghio-indent") ? indent : outdent
					);
				}, 100);
				return false;
			}
		});
		// Add Tab & Shift + Tab
		on($("body"), "keydown", event => {
			const { target, key } = event;
			if (key === "Tab") {
				if (target?.classList.contains("comment-form-textarea")) {
					event.preventDefault();
					target.focus();
					setTimeout(() => {
						window.rangyInput.indentSelectedText(
							target,
							// shift + tab = outdent
							event.getModifierState("Shift") ? outdent : indent
						);
					}, 100);
				}
			}
		});
	}

	function saveTabSize() {
		let $el = $(".gh-indent-size");
		if (!$el) {
			$el = document.createElement("style");
			$el.setAttribute("rel", "stylesheet");
			$el.className = "gh-indent-size";
			document.querySelector("head").appendChild($el);
		}
		$el.innerHTML = `.comment-form-textarea { tab-size:${spaceSize}; }`;
	}

	// Add GM options
	GM_registerMenuCommand(
		"Indent or outdent size",
		() => {
			const spaces = GM_getValue("indentOutdentSize", spaceSize);
			let val = prompt("Enter number of spaces to indent or outdent:", spaces);
			if (val !== null && typeof val === "string") {
				spaceSize = val;
				GM_setValue("space-size", val);
				saveTabSize();
			}
		}
	);

	on(document, "ghmo:container", addButtons);
	addBindings();
	addButtons();
})();
<|endoftext|>


<commit_before>$jit.ST.Plot.NodeTypes.implement({
  'areachart-default' : {
    'render' : function(node, canvas) {
      var pos = node.pos.getc(true),
          width = node.getData('width'),
          height = node.getData('height'),
          algnPos = this.getAlignedPos(pos, width, height),
          x = algnPos.x, y = algnPos.y,
          dimArray = node.getData('dimArray'),
          colorArray = node.getData('colorArray'),
          stringArray = node.getData('stringArray');

      var ctx = canvas.getCtx(), border = node.getData('border');
      if (colorArray && dimArray && stringArray) {
        for (var i=0, l=dimArray.length, acumLeft=0, acumRight=0; i<l; i++) {
          ctx.fillStyle = ctx.strokeStyle = colorArray[i];
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(x, y - acumLeft);
          ctx.lineTo(x + width, y - acumRight);
          ctx.lineTo(x + width, y - acumRight - dimArray[i][1]);
          ctx.lineTo(x, y - acumLeft - dimArray[i][0]);
          ctx.lineTo(x, y - acumLeft);
          ctx.fill();
          ctx.restore();
          if(border) {
            var strong = border.name == stringArray[i];
            var color = $.rgbToHex($.map($.hexToRgb(colorArray[i].slice(1)),
                function(v) { return v * (strong? 0.7 : 0.8) >> 0; }));
            ctx.strokeStyle = color;
            ctx.lineWidth = strong? 4 : 1;
            ctx.save();
            ctx.beginPath();
            if(border.index === 0) {
              ctx.moveTo(x, y - acumLeft);
              ctx.lineTo(x, y - acumLeft - dimArray[i][0]);
            } else {
              ctx.moveTo(x + width, y - acumRight);
              ctx.lineTo(x + width, y - acumRight - dimArray[i][1]);
            }
            ctx.stroke();
            ctx.restore();
          }
          acumLeft += (dimArray[i][0] || 0);
          acumRight += (dimArray[i][1] || 0);
        }
      }
    },
    'contains': function(node, mpos) {
      var pos = node.pos.getc(true),
          width = node.getData('width'),
          height = node.getData('height'),
          algnPos = this.getAlignedPos(pos, width, height),
          x = algnPos.x, y = algnPos.y,
          dimArray = node.getData('dimArray'),
          rx = mpos.x - x;
      //bounding box check
      if(mpos.x < x || mpos.x > x + width
        || mpos.y > y || mpos.y < y - height) {
        return false;
      }
      //deep check
      for(var i=0, l=dimArray.length, lAcum=y, rAcum=y; i<l; i++) {
        var dimi = dimArray[i];
        lAcum -= dimi[0];
        rAcum -= dimi[1];
        var intersec = lAcum + (rAcum - lAcum) * rx / width;
        if(mpos.y >= intersec) {
          var index = +(rx > width/2);
          return {
            'name': node.getData('stringArray')[i],
            'color': node.getData('colorArray')[i],
            'value': node.getData('valueArray')[i][index],
            'index': index
          };
        }
      }
      return false;
    }
  }
});

$jit.AreaChart = new Class({
  st: null,
  colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"],
  selected: {},

  initialize: function(opt) {
    this.controller = this.config =
      $.merge(Options("Canvas", "AreaChart"), opt);
    this.initializeViz();
  },

  initializeViz: function() {
    var config = this.config, that = this;
    var st = new $jit.ST({
      injectInto: config.injectInto,
      orientation: "bottom",
      levelDistance: 0,
      siblingOffset: 0,
      subtreeOffset: 0,
      Node: {
        overridable: true,
        type: 'areachart-' + config.type,
        align: 'left'
      },
      Edge: {
        type: 'none'
      },
      Tips: {
        allow: config.Tips.enable,
        attachToDOM: false,
        attachToCanvas: true,
        force: true,
        onShow: function(tip, node, opt) {
          var elem = opt.contains;
          config.Tips.onShow(tip, elem, node);
          that.select(node.id, elem.name, elem.index);
        },
        onHide: function() {
          that.select(false, false, false);
        }
      },
      NodeStyles: {
        attachToDOM: false,
        attachToCanvas: true,
        onClick: function(node, opt, set) {
          if(!config.filterOnClick) return;
          var elem = opt.contains;
          that.filter(elem.name);
        },
        onRightClick: function(node, opt, set) {
          if(!config.restoreOnRightClick) return;
          that.restore();
        }
      }
    });

    var size = st.canvas.getSize();
    st.config.offsetY = -size.height/2 + config.offset;
    this.st = st;
  },

  loadJSON: function(json) {
    var prefix = $.time(),
        ch = [],
        st = this.st,
        name = $.splat(json.label),
        color = $.splat(json.color || this.colors),
        animate = this.config.animate;

    for(var i=0, values=json.values, l=values.length; i<l-1; i++) {
      var val = values[i], prev = values[i-1], next = values[i+1];
      var valLeft = values[i].values, valRight = values[i+1].values;
      var valArray = $.zip(valLeft, valRight);
      var acumLeft = 0, acumRight = 0;
      ch.push({
        'id': prefix + val.label,
        'name': val.label,
        'data': {
          'value': valArray,
          '$valueArray': valArray,
          '$colorArray': color,
          '$stringArray': name,
          '$next': next.label,
          '$prev': prev? prev.label:null
        },
        'children': []
      });
    }
    var root = {
      'id': prefix + '$root',
      'name': '',
      'data': {
        '$type': 'none',
        '$width': 1,
        '$height': 1
      },
      'children': ch
    };
    st.loadJSON(root);

    this.normalizeDims();
    st.compute();
    st.select(st.root);
    if(animate) {
      st.fx.animate({
        modes: ['node-property:height:dimArray'],
        duration:1500
      });
    }
  },

  updateJSON: function(json) {
    var st = this.st;
    var graph = st.graph;
    var values = json.values;
    var animate = this.config.animate;
    $.each(values, function(v) {
      var n = graph.getByName(v.label);
      if(n) {
        var valArray = n.getData('valueArray');
        $.each(valArray, function(a, i) {
          a[0] = v.values[i];
        });
        n.setData('valueArray', valArray);
        var prev = n.getData('prev');
        if(prev) {
          var p = graph.getByName(prev);
          var valArray = p.getData('valueArray');
          $.each(valArray, function(a, i) {
            a[1] = v.values[i];
          });
          p.setData('valueArray', valArray);
        }
      }
    });
    this.normalizeDims();
    st.compute();
    st.select(st.root);
    if(animate) {
      st.fx.animate({
        modes: ['node-property:height:dimArray'],
        duration:1500
      });
    }
  },

  filter: function() {
    var args = Array.prototype.slice.call(arguments);
    var rt = this.st.graph.getNode(this.st.root);
    $jit.Graph.Util.eachAdjacency(rt, function(adj) {
      var n = adj.nodeTo,
          dimArray = n.getData('dimArray'),
          stringArray = n.getData('stringArray');
      n.setData('dimArray', $.map(dimArray, function(d, i) {
        return (args.indexOf(stringArray[i]) > -1)? d:[0, 0];
      }), 'end');
    });
    this.st.fx.animate({
      modes: ['node-property:dimArray'],
      duration:1500
    });
  },

  restore: function() {
    this.normalizeDims();
    this.st.fx.animate({
      modes: ['node-property:height:dimArray'],
      duration:1500
    });
  },
  //adds the little brown bar when hovering the node
  select: function(id, name, index) {
    var s = this.selected;
    if(s.id != id || s.name != name
        || s.index != index) {
      s.id = id;
      s.name = name;
      s.index = index;
      $jit.Graph.Util.eachNode(this.st.graph, function(n) {
        n.setData('border', false);
      });
      if(id) {
        var n = this.st.graph.getNode(id);
        n.setData('border', s);
        var link = index === 0? 'prev':'next';
        link = n.getData(link);
        if(link) {
          n = this.st.graph.getByName(link);
          if(n) {
            n.setData('border', {
              name: name,
              index: 1-index
            });
          }
        }
      }
      this.st.plot();
    }
  },

  getMaxValue: function() {
    var maxValue = 0;
    $jit.Graph.Util.eachNode(this.st.graph, function(n) {
      var valArray = n.getData('valueArray'),
          acumLeft = 0, acumRight = 0;
      $.each(valArray, function(v) {
        acumLeft += +v[0];
        acumRight += +v[1];
      });
      var acum = acumRight>acumLeft? acumRight:acumLeft;
      maxValue = maxValue>acum? maxValue:acum;
    });
    return maxValue;
  },

  normalizeDims: function() {
    //number of elements
    var root = this.st.graph.getNode(this.st.root), l=0;
    $jit.Graph.Util.eachAdjacency(root, function() {
      l++;
    });
    var maxValue = this.getMaxValue(),
        size = this.st.canvas.getSize(),
        config = this.config,
        offset = config.offset,
        fixedDim = (size.width - 2 * offset) / l,
        animate = config.animate,
        height = size.height - 2 * offset;
    $jit.Graph.Util.eachNode(this.st.graph, function(n) {
      var acumLeft = 0, acumRight = 0, animateValue = [];
      $.each(n.getData('valueArray'), function(v) {
        acumLeft += +v[0];
        acumRight += +v[1];
        animateValue.push([0, 0]);
      });
      var acum = acumRight>acumLeft? acumRight:acumLeft;
      n.setData('width', fixedDim);
      if(animate) {
        n.setData('height', 0);
        n.setData('height', acum * height / maxValue, 'end');
        n.setData('dimArray', $.map(n.getData('valueArray'), function(n) {
          return [n[0] * height / maxValue, n[1] * height / maxValue];
        }), 'end');
        var dimArray = n.getData('dimArray');
        if(!dimArray) {
          n.setData('dimArray', animateValue);
        }
      } else {
        n.setData('height', acum * height / maxValue);
        n.setData('dimArray', $.map(n.getData('valueArray'), function(n) {
          return [n[0] * height / maxValue, n[1] * height / maxValue];
        }));
      }
    });
  }
});<commit_msg>AreaChart: getLegend()<commit_after>$jit.ST.Plot.NodeTypes.implement({
  'areachart-default' : {
    'render' : function(node, canvas) {
      var pos = node.pos.getc(true),
          width = node.getData('width'),
          height = node.getData('height'),
          algnPos = this.getAlignedPos(pos, width, height),
          x = algnPos.x, y = algnPos.y,
          dimArray = node.getData('dimArray'),
          colorArray = node.getData('colorArray'),
          stringArray = node.getData('stringArray');

      var ctx = canvas.getCtx(), border = node.getData('border');
      if (colorArray && dimArray && stringArray) {
        for (var i=0, l=dimArray.length, acumLeft=0, acumRight=0; i<l; i++) {
          ctx.fillStyle = ctx.strokeStyle = colorArray[i];
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(x, y - acumLeft);
          ctx.lineTo(x + width, y - acumRight);
          ctx.lineTo(x + width, y - acumRight - dimArray[i][1]);
          ctx.lineTo(x, y - acumLeft - dimArray[i][0]);
          ctx.lineTo(x, y - acumLeft);
          ctx.fill();
          ctx.restore();
          if(border) {
            var strong = border.name == stringArray[i];
            var color = $.rgbToHex($.map($.hexToRgb(colorArray[i].slice(1)),
                function(v) { return v * (strong? 0.7 : 0.8) >> 0; }));
            ctx.strokeStyle = color;
            ctx.lineWidth = strong? 4 : 1;
            ctx.save();
            ctx.beginPath();
            if(border.index === 0) {
              ctx.moveTo(x, y - acumLeft);
              ctx.lineTo(x, y - acumLeft - dimArray[i][0]);
            } else {
              ctx.moveTo(x + width, y - acumRight);
              ctx.lineTo(x + width, y - acumRight - dimArray[i][1]);
            }
            ctx.stroke();
            ctx.restore();
          }
          acumLeft += (dimArray[i][0] || 0);
          acumRight += (dimArray[i][1] || 0);
        }
      }
    },
    'contains': function(node, mpos) {
      var pos = node.pos.getc(true),
          width = node.getData('width'),
          height = node.getData('height'),
          algnPos = this.getAlignedPos(pos, width, height),
          x = algnPos.x, y = algnPos.y,
          dimArray = node.getData('dimArray'),
          rx = mpos.x - x;
      //bounding box check
      if(mpos.x < x || mpos.x > x + width
        || mpos.y > y || mpos.y < y - height) {
        return false;
      }
      //deep check
      for(var i=0, l=dimArray.length, lAcum=y, rAcum=y; i<l; i++) {
        var dimi = dimArray[i];
        lAcum -= dimi[0];
        rAcum -= dimi[1];
        var intersec = lAcum + (rAcum - lAcum) * rx / width;
        if(mpos.y >= intersec) {
          var index = +(rx > width/2);
          return {
            'name': node.getData('stringArray')[i],
            'color': node.getData('colorArray')[i],
            'value': node.getData('valueArray')[i][index],
            'index': index
          };
        }
      }
      return false;
    }
  }
});

$jit.AreaChart = new Class({
  st: null,
  colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"],
  selected: {},

  initialize: function(opt) {
    this.controller = this.config =
      $.merge(Options("Canvas", "AreaChart"), opt);
    this.initializeViz();
  },

  initializeViz: function() {
    var config = this.config, that = this;
    var st = new $jit.ST({
      injectInto: config.injectInto,
      orientation: "bottom",
      levelDistance: 0,
      siblingOffset: 0,
      subtreeOffset: 0,
      Node: {
        overridable: true,
        type: 'areachart-' + config.type,
        align: 'left'
      },
      Edge: {
        type: 'none'
      },
      Tips: {
        allow: config.Tips.enable,
        attachToDOM: false,
        attachToCanvas: true,
        force: true,
        onShow: function(tip, node, opt) {
          var elem = opt.contains;
          config.Tips.onShow(tip, elem, node);
          that.select(node.id, elem.name, elem.index);
        },
        onHide: function() {
          that.select(false, false, false);
        }
      },
      NodeStyles: {
        attachToDOM: false,
        attachToCanvas: true,
        onClick: function(node, opt, set) {
          if(!config.filterOnClick) return;
          var elem = opt.contains;
          that.filter(elem.name);
        },
        onRightClick: function(node, opt, set) {
          if(!config.restoreOnRightClick) return;
          that.restore();
        }
      }
    });

    var size = st.canvas.getSize();
    st.config.offsetY = -size.height/2 + config.offset;
    this.st = st;
  },

  loadJSON: function(json) {
    var prefix = $.time(),
        ch = [],
        st = this.st,
        name = $.splat(json.label),
        color = $.splat(json.color || this.colors),
        animate = this.config.animate;

    for(var i=0, values=json.values, l=values.length; i<l-1; i++) {
      var val = values[i], prev = values[i-1], next = values[i+1];
      var valLeft = values[i].values, valRight = values[i+1].values;
      var valArray = $.zip(valLeft, valRight);
      var acumLeft = 0, acumRight = 0;
      ch.push({
        'id': prefix + val.label,
        'name': val.label,
        'data': {
          'value': valArray,
          '$valueArray': valArray,
          '$colorArray': color,
          '$stringArray': name,
          '$next': next.label,
          '$prev': prev? prev.label:null
        },
        'children': []
      });
    }
    var root = {
      'id': prefix + '$root',
      'name': '',
      'data': {
        '$type': 'none',
        '$width': 1,
        '$height': 1
      },
      'children': ch
    };
    st.loadJSON(root);

    this.normalizeDims();
    st.compute();
    st.select(st.root);
    if(animate) {
      st.fx.animate({
        modes: ['node-property:height:dimArray'],
        duration:1500
      });
    }
  },

  updateJSON: function(json) {
    var st = this.st;
    var graph = st.graph;
    var values = json.values;
    var animate = this.config.animate;
    $.each(values, function(v) {
      var n = graph.getByName(v.label);
      if(n) {
        var valArray = n.getData('valueArray');
        $.each(valArray, function(a, i) {
          a[0] = v.values[i];
        });
        n.setData('valueArray', valArray);
        var prev = n.getData('prev');
        if(prev) {
          var p = graph.getByName(prev);
          var valArray = p.getData('valueArray');
          $.each(valArray, function(a, i) {
            a[1] = v.values[i];
          });
          p.setData('valueArray', valArray);
        }
      }
    });
    this.normalizeDims();
    st.compute();
    st.select(st.root);
    if(animate) {
      st.fx.animate({
        modes: ['node-property:height:dimArray'],
        duration:1500
      });
    }
  },

  filter: function() {
    var args = Array.prototype.slice.call(arguments);
    var rt = this.st.graph.getNode(this.st.root);
    $jit.Graph.Util.eachAdjacency(rt, function(adj) {
      var n = adj.nodeTo,
          dimArray = n.getData('dimArray'),
          stringArray = n.getData('stringArray');
      n.setData('dimArray', $.map(dimArray, function(d, i) {
        return (args.indexOf(stringArray[i]) > -1)? d:[0, 0];
      }), 'end');
    });
    this.st.fx.animate({
      modes: ['node-property:dimArray'],
      duration:1500
    });
  },

  restore: function() {
    this.normalizeDims();
    this.st.fx.animate({
      modes: ['node-property:height:dimArray'],
      duration:1500
    });
  },
  //adds the little brown bar when hovering the node
  select: function(id, name, index) {
    var s = this.selected;
    if(s.id != id || s.name != name
        || s.index != index) {
      s.id = id;
      s.name = name;
      s.index = index;
      $jit.Graph.Util.eachNode(this.st.graph, function(n) {
        n.setData('border', false);
      });
      if(id) {
        var n = this.st.graph.getNode(id);
        n.setData('border', s);
        var link = index === 0? 'prev':'next';
        link = n.getData(link);
        if(link) {
          n = this.st.graph.getByName(link);
          if(n) {
            n.setData('border', {
              name: name,
              index: 1-index
            });
          }
        }
      }
      this.st.plot();
    }
  },

  getLegend: function() {
    var legend = {};
    var n;
    $jit.Graph.Util.eachAdjacency(this.st.graph.getNode(this.st.root), function(adj) {
      n = adj.nodeTo;
    });
    $.each(n.getData('stringArray'), function(s, i) {
      legend[s] = n.getData('colorArray')[i];
    });
    return legend;
  },

  getMaxValue: function() {
    var maxValue = 0;
    $jit.Graph.Util.eachNode(this.st.graph, function(n) {
      var valArray = n.getData('valueArray'),
          acumLeft = 0, acumRight = 0;
      $.each(valArray, function(v) {
        acumLeft += +v[0];
        acumRight += +v[1];
      });
      var acum = acumRight>acumLeft? acumRight:acumLeft;
      maxValue = maxValue>acum? maxValue:acum;
    });
    return maxValue;
  },

  normalizeDims: function() {
    //number of elements
    var root = this.st.graph.getNode(this.st.root), l=0;
    $jit.Graph.Util.eachAdjacency(root, function() {
      l++;
    });
    var maxValue = this.getMaxValue(),
        size = this.st.canvas.getSize(),
        config = this.config,
        offset = config.offset,
        fixedDim = (size.width - 2 * offset) / l,
        animate = config.animate,
        height = size.height - 2 * offset;
    $jit.Graph.Util.eachNode(this.st.graph, function(n) {
      var acumLeft = 0, acumRight = 0, animateValue = [];
      $.each(n.getData('valueArray'), function(v) {
        acumLeft += +v[0];
        acumRight += +v[1];
        animateValue.push([0, 0]);
      });
      var acum = acumRight>acumLeft? acumRight:acumLeft;
      n.setData('width', fixedDim);
      if(animate) {
        n.setData('height', 0);
        n.setData('height', acum * height / maxValue, 'end');
        n.setData('dimArray', $.map(n.getData('valueArray'), function(n) {
          return [n[0] * height / maxValue, n[1] * height / maxValue];
        }), 'end');
        var dimArray = n.getData('dimArray');
        if(!dimArray) {
          n.setData('dimArray', animateValue);
        }
      } else {
        n.setData('height', acum * height / maxValue);
        n.setData('dimArray', $.map(n.getData('valueArray'), function(n) {
          return [n[0] * height / maxValue, n[1] * height / maxValue];
        }));
      }
    });
  }
});<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var _ = require('underscore');
var async = require('async');
var logging = require('./lib/logging');
var loggingMiddleware = require('./middleware/logging');
var cluster = require('cluster');
var os = require('os');
var config = require('./lib/config');
var rateLimiter = require('./lib/rate-limiter');
var metrics_middleware = require('./middleware/metrics');
var redis = require('./lib/redis-client');
var client = redis.client;

var app = express();
// Middleware to run before processing requests
if (config.log_requests.toLowerCase() === 'true') {
  app.use(loggingMiddleware.handle);
}
app.use(metrics_middleware.handle);
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

var logger = logging.logger;

app.get('/health', function(req, res) {
  return res.sendStatus(200);
});

/**
 * POST /rate-limit
 * This will check the application's key to make sure a request is allowed
 * limit: number of requests allowed per minute
 * remaining: number of requests remaining
 * is_rate_limited: will return boolean based off of if the request should be rate limited
 * reset: time your rate limit will be reset, in epoch_ms
 * @param {string} app_name the name of the app trying to use the rate limiter
 * @param {string} key the key the app is attempting to rate limit on
 * @param {integer} cost how many tokens the requests take
 * @param {integer} rate_limit max number of requests per minute for this key
 */
app.post('/rate-limit', function(req, res) {
  appName = req.body.app_name;
  key = req.body.key;
  cost = req.body.cost;
  rateLimit = req.body.rate_limit;

  responseBody = {};

  client.keys('*', function(err, values){});

  if ([appName, key, cost, rateLimit].some(_.isUndefined)) {
    return res.sendStatus(400);
  }
  rateLimiter.rateLimitAppKey(appName, key, cost, rateLimit, function(err, returnVals){
        if(err){res.status(500);}

        if (returnVals[0] < 0) {
          responseBody.is_rate_limited = true;
        } else {
          responseBody.is_rate_limited = false;
        }

        responseBody.remaining = returnVals[1];
        responseBody.reset = returnVals[2];
        responseBody.limit = returnVals[3];
        res.json(responseBody);
        return;
  });
});

if (cluster.isMaster) {
  var numCPUs = os.cpus().length;
  logger.info('Starting ' + numCPUs + ' penalty box processes');
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    logger.error('Worker process ' + worker.process.pid + ' died. Restarting...');
    cluster.fork();
  });
} else {
  app.listen(config.port, function() {
    logger.info('penalty-box server listening on port ' + config.port);
  });
}

module.exports = app;
<commit_msg>do not call keys every time (#19)<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var _ = require('underscore');
var async = require('async');
var logging = require('./lib/logging');
var loggingMiddleware = require('./middleware/logging');
var cluster = require('cluster');
var os = require('os');
var config = require('./lib/config');
var rateLimiter = require('./lib/rate-limiter');
var metrics_middleware = require('./middleware/metrics');
var redis = require('./lib/redis-client');
var client = redis.client;

var app = express();
// Middleware to run before processing requests
if (config.log_requests.toLowerCase() === 'true') {
  app.use(loggingMiddleware.handle);
}
app.use(metrics_middleware.handle);
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

var logger = logging.logger;

app.get('/health', function(req, res) {
  return res.sendStatus(200);
});

/**
 * POST /rate-limit
 * This will check the application's key to make sure a request is allowed
 * limit: number of requests allowed per minute
 * remaining: number of requests remaining
 * is_rate_limited: will return boolean based off of if the request should be rate limited
 * reset: time your rate limit will be reset, in epoch_ms
 * @param {string} app_name the name of the app trying to use the rate limiter
 * @param {string} key the key the app is attempting to rate limit on
 * @param {integer} cost how many tokens the requests take
 * @param {integer} rate_limit max number of requests per minute for this key
 */
app.post('/rate-limit', function(req, res) {
  appName = req.body.app_name;
  key = req.body.key;
  cost = req.body.cost;
  rateLimit = req.body.rate_limit;

  responseBody = {};

  if ([appName, key, cost, rateLimit].some(_.isUndefined)) {
    return res.sendStatus(400);
  }
  rateLimiter.rateLimitAppKey(appName, key, cost, rateLimit, function(err, returnVals){
        if(err){res.status(500);}

        if (returnVals[0] < 0) {
          responseBody.is_rate_limited = true;
        } else {
          responseBody.is_rate_limited = false;
        }

        responseBody.remaining = returnVals[1];
        responseBody.reset = returnVals[2];
        responseBody.limit = returnVals[3];
        res.json(responseBody);
        return;
  });
});

if (cluster.isMaster) {
  var numCPUs = os.cpus().length;
  logger.info('Starting ' + numCPUs + ' penalty box processes');
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    logger.error('Worker process ' + worker.process.pid + ' died. Restarting...');
    cluster.fork();
  });
} else {
  app.listen(config.port, function() {
    logger.info('penalty-box server listening on port ' + config.port);
  });
}

module.exports = app;
<|endoftext|>