<commit_before>/* global $ */
$(function() {
	// Prepend translation icons to translatable fields.
	$($('#translatable-fields').val()).closest('fieldset').each(function(i, el){
		$(el).find('label').first().prepend(' ');
	})

	// Move locale switcher to tab navigation
	$("#locale-select").detach().appendTo('#filtertabs');

	var currentLocale;

	$(Bolt).on('done.bolt.content.save', function(){
		$('#locale-select [data-locale="'+currentLocale+'"]').trigger('click', true);
	});

	$('#locale-select a').click(function(e, force) {
		e.preventDefault();
		var el = $(this),
			locale = el.data('locale');

		currentLocale = locale;

		if(el.parent().hasClass('disabled') && !force) {
			return false;
		}

		lockInputFields(true);

		$('#locale-select button .selected').html(el.text());

		el.parent()
			.addClass('disabled')
			.siblings()
			.removeClass('disabled');

		var boltField = $('[data-bolt-field="slug"]');
		var fconf = boltField.data('bolt-fconf');
		$.each(fconf.uses, function (i, name) {
			$('#' + name).off('propertychange.bolt input.bolt change.bolt');
		});

		$.get(el.attr('href'), {
			locale: locale,
			content_type: $('#contenttype').val(),
			content_type_id: $('#id').val()
		}, function(data) {
			console.log(data)
			$.each(data, function() {
				if(this.field == "templatefields"){
					try{
						var val = JSON.parse(this.value);
						for (var field in val) {
							setValue('templatefields-' + field, val[field]);
						}
						console.log(val)
					} catch (e) {
						console.log(e)
					}
				}else{
					setValue(this.field, this.value);
				}
			})
			$('#locale').val(locale);
			lockInputFields(false);
			//Bolt.app.run()
		})
		.fail(function() {
			// show warning
			lockInputFields(false);
		});
	});
});

function lockInputFields(status) {
	$('#editcontent').find('input, select, textarea').prop('disabled', status);
	$.each(CKEDITOR.instances, function() {
		this.setReadOnly(status);
	});
}

function setValue(field, value) {
	var el = $('#' + field + ', #field-' + field + ', [data-bolt-field="' + field + '"], #' + field + '-video, #gridfield-' + field);
	var parent = el.closest('.form-group[data-fieldtype]');
	if(parent.length == 0 && field == 'seo'){
		parent = $('#seo').closest('.tab-pane').find('[data-fieldtype="seo"]')
	}
	var type = parent.attr('data-fieldtype');
	var boltField = $('[data-bolt-field="slug"]');
	var fconf = boltField.data('bolt-fconf');
	switch (type) {
		case 'integer':
		case 'float':
		case 'textarea':
		case 'text':
			el.val(value);
			break;
		case 'html':
			CKEDITOR.instances[el.attr('name')].setData(value);
			break;
		case 'markdown':
			parent.find('.CodeMirror').get(0).CodeMirror.setValue(value);
			break;
		case 'checkbox':
			if(value == 1){
				el.prop('checked', true);
			}else{
				el.prop('checked', false);
			}
			break;
		case 'slug':
			if (value.trim() == ''){
				fconf.isEmpty = true;
			} else {
				fconf.isEmpty = false;
				parent.find('.input-group').removeClass('unlocked').addClass('locked');
				$.each(fconf.uses, function (i, name) {
					$('#' + name).off('propertychange.bolt input.bolt change.bolt');
				});
			}
			boltField.get(0).dataset.boltFconf = JSON.stringify(fconf);
			parent.find('input').val(value);
			parent.find('em').html(value);
			Bolt.fields.slug.init(boltField, fconf);
			break;
		case 'datetime':
		case 'date':
			el.val(value);
			Bolt.datetime.update();
			break;
		case 'select':
			if(fconf.uses.indexOf(field)){
				el.off('propertychange.bolt input.bolt change.bolt');
			}
			if(el.attr('multiple')){
				try {
					el.val(JSON.parse(value))
				} catch (e) {
					console.log('not valid json for field ' + field)
				}
			}else{
				el.val(value);
			}
			break;
		case 'geolocation':
			parent.find('input').val('');
			try {
				value = JSON.parse(value);
				for (var key in value) {
					$('[name="'+field+'['+key+']"]').val(value[key]).trigger('input')
				}
			} catch (e) {
				console.log('not valid json for field ' + field)
			}
			break;
		case 'image':
			parent.find('input').val('');
			try {
				value = JSON.parse(value);
				for (var key in value) {
					$('[name="'+field+'['+key+']"]').val(value[key])
				}
				$('#thumbnail-' + field).html('');
			} catch (e) {
				parent.find('.content-preview img').attr('src','/app/view/img/default_empty_4x3.png')
				console.log('not valid json for field ' + field)
			}
			break;
		case 'video':
			try {
				value = JSON.parse(value);
				$('[name="'+field+'[url]"]').val(value.url).trigger('input');
			} catch (e) {
				$('[name="'+field+'[url]"]').val('').trigger('input');
				console.log('not valid json for field ' + field)
			}
			break;
		case 'filelist':
		case 'imagelist':
			Bolt[type][field].list.reset();
			Bolt[type][field].render();
			try {
				value = JSON.parse(value);
				for (var key in value) {
					Bolt[type][field].add(value[key].filename, value[key].title)
				}
			} catch (e) {
				console.log('not valid json for field ' + field)
			}

			break;
		case 'seo':
			try {
				value = JSON.parse(value);
				$.each(value, function (subindex, subitem) {
					$('#seofields-' + subindex).val(subitem).trigger('input').trigger('blur');
				});
				el.val(value).trigger('input').trigger('blur');
			} catch (e) {
				console.log('Error on SEO field: ', field, value);
				el.val(value);
			}
			break;
		case 'grid':
			if(value == "" || value == "[]"){
				value = "[[],[]]"
			}
			el.val(value);
			document.getElementById('hot-'+field).hot.loadData(JSON.parse(value));
			break;
		case 'faiconpicker':
			el.val(value);
			parent.find('[title=".'+value+'"]').trigger('click');
			break;
		case 'bootstrapcolorpicker':
			el.val(value);
			el.colorpicker('setValue', value);
			break;
		default:
			try {
				value = JSON.parse(value);
				if ($.type(value) === 'object') {
					$.each(value, function (subindex, subitem) {
						$(':input[name="' + field + '[' + subindex + ']"]').val(subitem).trigger('input').trigger('blur');
					});
				}else{
					console.log('Unkown field with non-objects, trying to set with val: ', field, value);
					el.val(value).trigger('input').trigger('blur');
				}
			} catch (e) {
				el.val(value).trigger('input').trigger('blur');
			}
			break;
	}
}

// See http://stackoverflow.com/a/9116746/709769
$.fn.getType = function() {
	return this[0].tagName == 'INPUT' ? this[0].type.toLowerCase() : this[0].tagName.toLowerCase();
}
<commit_msg>JS cleanup<commit_after>/* global $ */
$(function() {
	// Prepend translation icons to translatable fields.
	$($('#translatable-fields').val()).closest('fieldset').each(function(i, el){
		$(el).find('label').first().prepend(' ');
	})

	// Move locale switcher to tab navigation
	$("#locale-select").detach().appendTo('#filtertabs');

	var locale;

	$(Bolt).on('start.bolt.content.save', function(){
		$('[data-fieldtype="slug"] .unlocked .btn-default.lock').trigger('click');
	});

	$(Bolt).on('done.bolt.content.save', function(){
		$('#locale-select [data-locale="'+locale+'"]').trigger('click', true);
	});

	$('#locale-select a').click(function(e, force) {
		e.preventDefault();
		var el = $(this);
		locale = el.data('locale');

		if(el.parent().hasClass('disabled') && !force) {
			return false;
		}

		lockInputFields(true);

		$('#locale-select button .selected').html(el.text());

		el.parent()
			.addClass('disabled')
			.siblings()
			.removeClass('disabled');

		$.get(el.attr('href'), {
			locale: locale,
			content_type: $('#contenttype').val(),
			content_type_id: $('#id').val()
		}, function(data) {
			console.log(data)
			$.each(data, function() {
				if(this.field == "templatefields"){
					try{
						var val = JSON.parse(this.value);
						for (var field in val) {
							setValue('templatefields-' + field, val[field]);
						}
						console.log(val)
					} catch (e) {
						console.log(e)
					}
				}else{
					setValue(this.field, this.value);
				}
			})
			$('#locale').val(locale);
			lockInputFields(false);
		})
		.fail(function() {
			// show warning
			lockInputFields(false);
		});
	});
});

function lockInputFields(status) {
	$('#editcontent').find('input, select, textarea').prop('disabled', status);
	$.each(CKEDITOR.instances, function() {
		this.setReadOnly(status);
	});
}

function logerror(field, type) {
	console.log('not valid json for ' + type + ' field ' + field)
}

function setValue(field, value) {
	var el = $('#' + field + ', #field-' + field + ', [data-bolt-field="' + field + '"], #' + field + '-video, #gridfield-' + field);
	var parent = el.closest('.form-group[data-fieldtype]');
	if(parent.length == 0 && field == 'seo'){
		parent = $('#seo').closest('.tab-pane').find('[data-fieldtype="seo"]')
	}
	var type = parent.attr('data-fieldtype');
	switch (type) {
		case 'integer':
		case 'float':
		case 'textarea':
		case 'text':
			el.val(value);
			break;
		case 'html':
			CKEDITOR.instances[el.attr('name')].setData(value);
			break;
		case 'markdown':
			parent.find('.CodeMirror').get(0).CodeMirror.setValue(value);
			break;
		case 'checkbox':
			if(value == 1){
				el.prop('checked', true);
			}else{
				el.prop('checked', false);
			}
			break;
		case 'slug':
			parent.find('input').val(value);
			parent.find('em').html(value);
			break;
		case 'datetime':
		case 'date':
			el.val(value);
			Bolt.datetime.update();
			break;
		case 'select':
			if(el.attr('multiple')){
				try {
					el.val(JSON.parse(value))
				} catch (e) {
					logerror(field, type)
				}
			}else{
				el.val(value);
			}
			break;
		case 'geolocation':
			parent.find('input').val('');
			try {
				value = JSON.parse(value);
				for (var key in value) {
					$('[name="'+field+'['+key+']"]').val(value[key]).trigger('input')
				}
			} catch (e) {
				logerror(field, type)
			}
			break;
		case 'image':
			parent.find('input').val('');
			try {
				value = JSON.parse(value);
				for (var key in value) {
					$('[name="'+field+'['+key+']"]').val(value[key])
				}
				$('#thumbnail-' + field).html('');
			} catch (e) {
				parent.find('.content-preview img').attr('src','/app/view/img/default_empty_4x3.png')
				logerror(field, type)
			}
			break;
		case 'video':
			try {
				value = JSON.parse(value);
				$('[name="'+field+'[url]"]').val(value.url).trigger('input');
			} catch (e) {
				$('[name="'+field+'[url]"]').val('').trigger('input');
				logerror(field, type)
			}
			break;
		case 'filelist':
		case 'imagelist':
			Bolt[type][field].list.reset();
			Bolt[type][field].render();
			try {
				value = JSON.parse(value);
				for (var key in value) {
					Bolt[type][field].add(value[key].filename, value[key].title)
				}
			} catch (e) {
				logerror(field, type)
			}
			break;
		case 'seo':
			try {
				value = JSON.parse(value);
				$.each(value, function (subindex, subitem) {
					$('#seofields-' + subindex).val(subitem).trigger('input').trigger('blur');
				});
				el.val(value).trigger('input').trigger('blur');
			} catch (e) {
				el.val(value);
				logerror(field, type)
			}
			break;
		case 'grid':
			if(value == "" || value == "[]"){
				value = "[[],[]]"
			}
			el.val(value);
			document.getElementById('hot-'+field).hot.loadData(JSON.parse(value));
			break;
		case 'faiconpicker':
			el.val(value);
			parent.find('[title=".'+value+'"]').trigger('click');
			break;
		case 'bootstrapcolorpicker':
			el.val(value);
			el.colorpicker('setValue', value);
			break;
		default:
			try {
				value = JSON.parse(value);
				if ($.type(value) === 'object') {
					$.each(value, function (subindex, subitem) {
						$(':input[name="' + field + '[' + subindex + ']"]').val(subitem).trigger('input').trigger('blur');
					});
				}else{
					console.log('Unkown field with non-objects, trying to set with val: ', field, value);
					el.val(value).trigger('input').trigger('blur');
				}
			} catch (e) {
				el.val(value).trigger('input').trigger('blur');
			}
			break;
	}
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Nominet UK (http://www.nominet.org.uk).
 *
 * 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
 *
 * This software is provided 'as-is', without any express or implied warranty.
 * No representation is provided that this software is suitable or fit for
 * any purpose. In no event will Nominet be held liable for any damages
 * arising from the use of this software, unless such liability may not be
 * excluded or limited as a matter of law.
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, save that altered source versions must be plainly marked as
 * such, and must not be misrepresented as being the original software.
 * Your use of the software and our relationship is subject to English law
 * and the exclusive jurisdiction of the English courts.
 **/

var dns = require('native-dns');

module.exports = function (RED) {
    "use strict";

    function DnsQueryNode(config) {
        var newmsg = {};

        RED.nodes.createNode(this, config);
        var node = this;
        this.on('input', function (msg) {
            var question = dns.Question({
                name: msg.payload.name,
                type: msg.payload.type
            });

            var req = dns.Request({
                question: question,
                server: {address: '8.8.8.8', port: 53, type: 'udp'},
                timeout: 1000
            });

            req.on('timeout', function () {
                console.log('Timeout in making request');
            });

            req.on('message', function (err, answer) {
                answer.answer.forEach(function (a) {
                    if (a.type == 1) {	// A
                        newmsg.topic = "A";
                        newmsg.payload = a.address;
                    }
                    else if (a.type == 16) {	// TXT
                        for (var i = 0; i < a.data.length; i++) {
                            newmsg.topic = "TXT";
                            newmsg.payload = a.data[i];
                        }
                    }
                    else if (a.type == 33) {	// SRV
                        newmsg.topic = "SRV";
                        newmsg.payload = a.target;
                    }
                    else if (a.type == 256) {	// URI
                        newmsg.topic = "URI";
                        newmsg.payload = a.target;
                    }
                });
                node.send(newmsg);
            });
            req.send();
        });
    }

    RED.nodes.registerType("dns-query", DnsQueryNode);
}
<commit_msg>Added dnsQuery and dnsResponse in message<commit_after>/**
 * Copyright 2015 Nominet UK (http://www.nominet.org.uk).
 *
 * 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
 *
 * This software is provided 'as-is', without any express or implied warranty.
 * No representation is provided that this software is suitable or fit for
 * any purpose. In no event will Nominet be held liable for any damages
 * arising from the use of this software, unless such liability may not be
 * excluded or limited as a matter of law.
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, save that altered source versions must be plainly marked as
 * such, and must not be misrepresented as being the original software.
 * Your use of the software and our relationship is subject to English law
 * and the exclusive jurisdiction of the English courts.
 **/

var dns = require('native-dns');

module.exports = function (RED) {
    "use strict";

    function DnsQueryNode(config) {

        RED.nodes.createNode(this, config);
        var node = this;
        this.on('input', function (msg) {
            var question = dns.Question({
                name: msg.payload.dnsQuery.name,
                type: msg.payload.dnsQuery.type
            });

            var req = dns.Request({
                question: question,
                server: {address: '8.8.8.8', port: 53, type: 'udp'},
                timeout: 1000
            });

            req.on('timeout', function () {
                console.log('Timeout in making request');
            });

            req.on('message', function (err, answer) {
                msg.payload.dnsResponse = {};

                answer.answer.forEach(function (a) {
                    if (a.type == 1) {	// A
                        msg.payload.dnsResponse.type = "A";
                        msg.payload.dnsResponse.value = a.address;
                    }
                    else if (a.type == 16) {	// TXT
                        for (var i = 0; i < a.data.length; i++) {
                            msg.payload.dnsResponse.type = "TXT";
                            msg.payload.dnsResponse.value = a.data[i];
                        }
                    }
                    else if (a.type == 33) {	// SRV
                        msg.payload.dnsResponse.type = "SRV";
                        msg.payload.dnsResponse.value = a.target;
                    }
                    else if (a.type == 256) {	// URI
                        msg.payload.dnsResponse.type = "URI";
                        msg.payload.dnsResponse.value = a.target;
                    }
                });
                node.send(msg);
            });
            req.send();
        });
    }

    RED.nodes.registerType("dns-query", DnsQueryNode);
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');

var template = fs.readFileSync(__dirname + '/processDiagram.html', 'utf8');

var angular = require('camunda-commons-ui/vendor/angular');

var DirectiveController = ['$scope', '$compile', 'Views', function( $scope,   $compile,   Views) {

  $scope.vars = { read: [ 'processData', 'bpmnElement', 'pageData', 'viewer' ] };

  $scope.overlayProviders = Views.getProviders({ component:  $scope.overlayProviderComponent });

  var overlay = '

';
  var actions = '

';

  var bpmnElements,
      selection;

  $scope.$on('$destroy', function() {
    $scope.processDiagram = null;
    $scope.overlayProviders = null;
  });

  $scope.control = {};

  $scope.$on('collapse-change', function() {
    console.log('bpmn collapse change!');
    $scope.control.resetZoom();
  });

  /**
  * If the process diagram changes, then the diagram will be rendered.
  */
  $scope.$watch('processDiagram', function(newValue) {
    if (newValue && newValue.$loaded !== false) {
      bpmnElements = newValue.bpmnElements;
      $scope.diagramData = newValue.bpmnDefinition;
    }
  });

  $scope.onLoad = function() {
    $scope.viewer = $scope.control.getViewer();
    decorateDiagram($scope.processDiagram.bpmnElements);

    if ($scope.actionProviderComponent) {
      addActions();
    }

// update selection in case it has been provided earlier
    updateSelection(selection);
  };

  var isElementSelectable = function(element) {
    return element.isSelectable || (
      $scope.selectAll &&
      element.$instanceOf('bpmn:FlowNode')
    );
  };

  $scope.onClick = function(element, $event) {
    safeApply(function() {
      if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id])) {
        $scope.onElementClick({id: element.businessObject.id, $event: $event});
      } else {
        $scope.onElementClick({id: null, $event: $event});
      }
    });
  };

  function safeApply(fn) {
    if (!$scope.$$phase) {
      $scope.$apply(fn);
    } else {
      fn();
    }
  }

  $scope.onMouseEnter = function(element) {
    if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id])) {
      $scope.control.getViewer().get('canvas').addMarker(element.businessObject.id, 'selectable');
      $scope.control.highlight(element.businessObject.id);
    }
  };

  $scope.onMouseLeave = function(element) {
    if(bpmnElements[element.businessObject.id] &&
    isElementSelectable(bpmnElements[element.businessObject.id]) &&
    (!selection || selection.indexOf(element.businessObject.id) === -1) &&
    (!selection || selection.indexOf(element.businessObject.id + '#multiInstanceBody') === -1)) {
      $scope.control.clearHighlight(element.businessObject.id);
    }
  };

/*------------------- Decorate diagram ---------------------*/

  function decorateDiagram(bpmnElements) {
    angular.forEach(bpmnElements, decorateBpmnElement);
  }

  function decorateBpmnElement(bpmnElement) {

    var elem = $scope.control.getElement(bpmnElement.id);

    if(elem) {
      var childScope = $scope.$new();

      childScope.bpmnElement = bpmnElement;

      var newOverlay = angular.element(overlay);

      newOverlay.css({
        width: elem.width,
        height: elem.height
      });

      $compile(newOverlay)(childScope);

      try {
        $scope.control.createBadge(bpmnElement.id, {
          html: newOverlay,
          position: {
            top: 0,
            left: 0
          }
        });
      } catch (exception) {
        // do nothing
      }
    }
  }

/*------------------- Add actions ------------------------------------*/

  function addActions() {
    $scope.actionProviders = Views.getProviders({ component:  $scope.actionProviderComponent });
    var actionElement = angular.element(actions);
    var childScope = $scope.$new();
    $compile(actionElement)(childScope);
    $scope.control.addAction( {
      html : actionElement
    });
  }

/*------------------- Handle selected activity id---------------------*/

  $scope.$watch('selection.activityIds', function(newValue) {
    updateSelection(newValue);
  });

  function updateSelection(newSelection) {
    if ($scope.control.isLoaded()) {
      if (selection) {
        angular.forEach(selection, function(elementId) {
          if(elementId.indexOf('#multiInstanceBody') !== -1 &&
elementId.indexOf('#multiInstanceBody') === elementId.length - 18) {
            elementId = elementId.substr(0, elementId.length - 18);
          }
          if(bpmnElements[elementId]) {
            $scope.control.clearHighlight(elementId);
          }
        });
      }

      if (newSelection) {
        angular.forEach(newSelection, function(elementId) {
          if(elementId.indexOf('#multiInstanceBody') !== -1 &&
elementId.indexOf('#multiInstanceBody') === elementId.length - 18) {
            elementId = elementId.substr(0, elementId.length - 18);
          }
          if(bpmnElements[elementId]) {
            $scope.control.highlight(elementId);
          }
        });
      }
    }

    $scope.$root.$emit('instance-diagram-selection-change', newSelection);

    selection = newSelection;
  }

/*------------------- Handle scroll to bpmn element ---------------------*/

  $scope.$watch('selection.scrollToBpmnElement', function(newValue) {
    if (newValue) {
      scrollToBpmnElement(newValue);
    }
  });

  function scrollToBpmnElement(bpmnElementId) {
    if ($scope.control.isLoaded() && bpmnElementId) {
      scrollTo(bpmnElementId);
    }
  }

  function scrollTo(elementId) {
    if(bpmnElements[elementId]) {
      $scope.control.scrollToElement(elementId);
    }
  }

}];

var Directive = function() {
  return {
    restrict: 'EAC',
    scope: {
      processDiagram: '=',
      processDiagramOverlay: '=',
      onElementClick: '&',
      selection: '=',
      processData: '=',
      pageData: '=',
      overlayProviderComponent: '@',
      actionProviderComponent: '@',
      selectAll: '&'
    },
    controller: DirectiveController,
    template: template,

    link: function($scope) {
      $scope.selectAll = $scope.$eval($scope.selectAll);
    }
  };
};

module.exports = Directive;
<commit_msg>chore: remove console.log<commit_after>'use strict';

var fs = require('fs');

var template = fs.readFileSync(__dirname + '/processDiagram.html', 'utf8');

var angular = require('camunda-commons-ui/vendor/angular');

var DirectiveController = ['$scope', '$compile', 'Views', function( $scope,   $compile,   Views) {

  $scope.vars = { read: [ 'processData', 'bpmnElement', 'pageData', 'viewer' ] };

  $scope.overlayProviders = Views.getProviders({ component:  $scope.overlayProviderComponent });

  var overlay = '

';
  var actions = '

';

  var bpmnElements,
      selection;

  $scope.$on('$destroy', function() {
    $scope.processDiagram = null;
    $scope.overlayProviders = null;
  });

  $scope.control = {};

  $scope.$on('collapse-change', function() {
    $scope.control.resetZoom();
  });

  /**
  * If the process diagram changes, then the diagram will be rendered.
  */
  $scope.$watch('processDiagram', function(newValue) {
    if (newValue && newValue.$loaded !== false) {
      bpmnElements = newValue.bpmnElements;
      $scope.diagramData = newValue.bpmnDefinition;
    }
  });

  $scope.onLoad = function() {
    $scope.viewer = $scope.control.getViewer();
    decorateDiagram($scope.processDiagram.bpmnElements);

    if ($scope.actionProviderComponent) {
      addActions();
    }

// update selection in case it has been provided earlier
    updateSelection(selection);
  };

  var isElementSelectable = function(element) {
    return element.isSelectable || (
      $scope.selectAll &&
      element.$instanceOf('bpmn:FlowNode')
    );
  };

  $scope.onClick = function(element, $event) {
    safeApply(function() {
      if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id])) {
        $scope.onElementClick({id: element.businessObject.id, $event: $event});
      } else {
        $scope.onElementClick({id: null, $event: $event});
      }
    });
  };

  function safeApply(fn) {
    if (!$scope.$$phase) {
      $scope.$apply(fn);
    } else {
      fn();
    }
  }

  $scope.onMouseEnter = function(element) {
    if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id])) {
      $scope.control.getViewer().get('canvas').addMarker(element.businessObject.id, 'selectable');
      $scope.control.highlight(element.businessObject.id);
    }
  };

  $scope.onMouseLeave = function(element) {
    if(bpmnElements[element.businessObject.id] &&
    isElementSelectable(bpmnElements[element.businessObject.id]) &&
    (!selection || selection.indexOf(element.businessObject.id) === -1) &&
    (!selection || selection.indexOf(element.businessObject.id + '#multiInstanceBody') === -1)) {
      $scope.control.clearHighlight(element.businessObject.id);
    }
  };

/*------------------- Decorate diagram ---------------------*/

  function decorateDiagram(bpmnElements) {
    angular.forEach(bpmnElements, decorateBpmnElement);
  }

  function decorateBpmnElement(bpmnElement) {

    var elem = $scope.control.getElement(bpmnElement.id);

    if(elem) {
      var childScope = $scope.$new();

      childScope.bpmnElement = bpmnElement;

      var newOverlay = angular.element(overlay);

      newOverlay.css({
        width: elem.width,
        height: elem.height
      });

      $compile(newOverlay)(childScope);

      try {
        $scope.control.createBadge(bpmnElement.id, {
          html: newOverlay,
          position: {
            top: 0,
            left: 0
          }
        });
      } catch (exception) {
        // do nothing
      }
    }
  }

/*------------------- Add actions ------------------------------------*/

  function addActions() {
    $scope.actionProviders = Views.getProviders({ component:  $scope.actionProviderComponent });
    var actionElement = angular.element(actions);
    var childScope = $scope.$new();
    $compile(actionElement)(childScope);
    $scope.control.addAction( {
      html : actionElement
    });
  }

/*------------------- Handle selected activity id---------------------*/

  $scope.$watch('selection.activityIds', function(newValue) {
    updateSelection(newValue);
  });

  function updateSelection(newSelection) {
    if ($scope.control.isLoaded()) {
      if (selection) {
        angular.forEach(selection, function(elementId) {
          if(elementId.indexOf('#multiInstanceBody') !== -1 &&
elementId.indexOf('#multiInstanceBody') === elementId.length - 18) {
            elementId = elementId.substr(0, elementId.length - 18);
          }
          if(bpmnElements[elementId]) {
            $scope.control.clearHighlight(elementId);
          }
        });
      }

      if (newSelection) {
        angular.forEach(newSelection, function(elementId) {
          if(elementId.indexOf('#multiInstanceBody') !== -1 &&
elementId.indexOf('#multiInstanceBody') === elementId.length - 18) {
            elementId = elementId.substr(0, elementId.length - 18);
          }
          if(bpmnElements[elementId]) {
            $scope.control.highlight(elementId);
          }
        });
      }
    }

    $scope.$root.$emit('instance-diagram-selection-change', newSelection);

    selection = newSelection;
  }

/*------------------- Handle scroll to bpmn element ---------------------*/

  $scope.$watch('selection.scrollToBpmnElement', function(newValue) {
    if (newValue) {
      scrollToBpmnElement(newValue);
    }
  });

  function scrollToBpmnElement(bpmnElementId) {
    if ($scope.control.isLoaded() && bpmnElementId) {
      scrollTo(bpmnElementId);
    }
  }

  function scrollTo(elementId) {
    if(bpmnElements[elementId]) {
      $scope.control.scrollToElement(elementId);
    }
  }

}];

var Directive = function() {
  return {
    restrict: 'EAC',
    scope: {
      processDiagram: '=',
      processDiagramOverlay: '=',
      onElementClick: '&',
      selection: '=',
      processData: '=',
      pageData: '=',
      overlayProviderComponent: '@',
      actionProviderComponent: '@',
      selectAll: '&'
    },
    controller: DirectiveController,
    template: template,

    link: function($scope) {
      $scope.selectAll = $scope.$eval($scope.selectAll);
    }
  };
};

module.exports = Directive;
<|endoftext|>


<commit_before>var BattleshipSingle = {};
BattleshipSingle.Game = function(game) {};
var line;
BattleshipSingle.Game.prototype = {
    preload: function(game) {
        game.load.image('ship', 'assets/battleship.gif');
        game.load.image('cloud', 'assets/cloud_1.png');
        game.load.image("background", "assets/wallpaper.png");
    },
    create: function(game){

        game.add.tileSprite(0, 0, 1000, 1000, 'background');
        game.stage.backgroundColor = "#0B65F8";

        this.player = game.add.sprite(game.world.centerX, game.world.centerY, 'ship');
        this.player.enableBody = true;
        game.physics.arcade.enable(this.player);

        this.player.body.collideWorldBounds = true;
        this.player.body.bounce.setTo(0.8,0.8);
        this.player.scale.setTo(0.3, 0.3);
        this.player.anchor.setTo(0.5,0.5);
        // this.point = new Phaser.Point(this.player.x, this.player.y);

        // enable player physics

        game.input.addMoveCallback(function(pointer, x, y) {
            line = new Phaser.Line(this.x, this.y, x, y);
            var rotation = new Phaser.Physics.Arcade(game);
            rotation = rotation.angleToXY(this, x, y);
            console.log(rotation);
            this.rotation = rotation;
        }, this.player);

        this.cursor = game.input.keyboard.addKeys({
            'space': Phaser.Keyboard.SPACEBAR
        });

        // this.gamePointer = new Phaser.Pointer(game, 1,  Phaser.PointerMode.CURSOR);
    },
    update: function(game) {

        if(this.cursor.space.isDown) {
            this.player.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(this.player.angle , 100))
        }
        else if(this.cursor.space.isUp) {
            game.physics.arcade.computeVelocity(1, this.player.body, this.player.body.velocity, 0, 20, 200)
            // game.physics.arcade.computeVelocity(0, this.player.body, this.player.body.velocity, 0, 20, 200)
        // //     console.log(this.input.mousePointer.position);
        // //     this.player.body.velocity = this.input.mousePointer.position;
        }

    },
    render: function(game) {
        // game.debug.body(this.player);
        game.debug.bodyInfo(this.player, 32, 32);
        // game.debug.body(this.player);
        // game.debug.spriteBounds(this.player, 'black', false);
        // game.debug.geom(this.point, 'rgb(0,255,0)');
        // game.debug.pointer(this.input.mousePointer);

    }
};
<commit_msg>I got what I wanted for the acceleration and drag<commit_after>var BattleshipSingle = {};
BattleshipSingle.Game = function(game) {};
var line, x = 0, y = 0;
BattleshipSingle.Game.prototype = {
    preload: function(game) {
        game.load.image('ship', 'assets/battleship.gif');
        game.load.image('cloud', 'assets/cloud_1.png');
        game.load.image("background", "assets/wallpaper.png");
    },
    create: function(game){

        game.add.tileSprite(0, 0, 1000, 1000, 'background');
        game.stage.backgroundColor = "#0B65F8";

        this.player = game.add.sprite(game.world.centerX, game.world.centerY, 'ship');
        this.player.enableBody = true;
        game.physics.arcade.enable(this.player);

        this.player.body.collideWorldBounds = true;
        this.player.body.bounce.setTo(0.8,0.8);
        this.player.scale.setTo(0.3, 0.3);
        this.player.anchor.setTo(0.5,0.5);
        // this.point = new Phaser.Point(this.player.x, this.player.y);

        // enable player physics

        game.input.addMoveCallback(function(pointer, x, y) {
            line = new Phaser.Line(this.x, this.y, x, y);
            var rotation = new Phaser.Physics.Arcade(game);
            rotation = rotation.angleToXY(this, x, y);
            // console.log(rotation);
            this.rotation = rotation;
        }, this.player);

        this.cursor = game.input.keyboard.addKeys({
            'space': Phaser.Keyboard.SPACEBAR
        });

        // this.gamePointer = new Phaser.Pointer(game, 1,  Phaser.PointerMode.CURSOR);
    },
    update: function(game) {

        if(this.cursor.space.isDown) {
            this.player.rotation = game.physics.arcade.accelerateToPointer(this.player , game.input.cursor, 20, 200, 200);
        }

    },
    render: function(game) {
        // game.debug.body(this.player);
        game.debug.bodyInfo(this.player, 32, 32);
        // game.debug.body(this.player);
        // game.debug.spriteBounds(this.player, 'black', false);
        // game.debug.geom(this.point, 'rgb(0,255,0)');
        // game.debug.pointer(this.input.mousePointer);

    }
};
<|endoftext|>


<commit_before>/* global React */
// sc_require('react/dg-react');

DG.React.ready(function () {
  var
      span = React.DOM.span;

  DG.React.Components.AttributeSummary = DG.React.createComponent(
      (function () {

        /**
         * Props are
         *    cases: {[DG.Case]}  The cases for which we'll provide a summary
         *    attrID: {Number}    This is the attribute whose values we'll summarize
         *    unit: {String}
         */

        return {

          render: function () {
            var tAttrID = this.props.attrID,
                tAllNumeric = true,
                tMin = Number.MAX_VALUE,
                tMax = Number.MIN_VALUE,
                tUniqueValues = {},
                tNumUniqueValues,
                tSummary;
            this.props.cases.forEach(function (iCase) {
              var tValue = iCase.getValue(tAttrID);
              if (!tUniqueValues[tValue])
                tUniqueValues[tValue] = 0;
              tUniqueValues[tValue]++;
              if (tValue !== '' && isFinite(tValue)) {
                tMin = Math.min(tMin, tValue);
                tMax = Math.max(tMax, tValue);
              } else if( tValue !== '') {
                tAllNumeric = false;
              }
            });
            if( tAllNumeric) {
              tMin = DG.MathUtilities.formatNumber(tMin, 2);
              tMax = DG.MathUtilities.formatNumber(tMax, 2);
            }
            tNumUniqueValues = Object.keys(tUniqueValues).length;
            if( tNumUniqueValues > 2 || tAllNumeric) {
              tSummary = tAllNumeric ?
                  (tMin === tMax ? (tMin + this.props.unit) :
                      'DG.CaseCard.summaryRange'.loc(tMin, tMax, this.props.unit)) :
                  'DG.CaseCard.summaryValues'.loc(tNumUniqueValues);
              return span({className: 'react-data-card-attribute-summary'}, tSummary);
            }
            else {
              var tUniqueValue = Object.keys( tUniqueValues).join(', ');
              if(tUniqueValue==='undefined')
                tUniqueValue = '';
              return span({
                className: 'react-data-card-attribute-summary'
              }, tUniqueValue);
            }
          }
        };
      }()), []);

});
<commit_msg>[#158017440] Bug fix: Empty case cells come up as Infinity-0 in case card<commit_after>/* global React */
// sc_require('react/dg-react');

DG.React.ready(function () {
  var
      span = React.DOM.span;

  DG.React.Components.AttributeSummary = DG.React.createComponent(
      (function () {

        /**
         * Props are
         *    cases: {[DG.Case]}  The cases for which we'll provide a summary
         *    attrID: {Number}    This is the attribute whose values we'll summarize
         *    unit: {String}
         */

        return {

          render: function () {
            var tAttrID = this.props.attrID,
                tAllNumeric = true,
                tMin = Number.MAX_VALUE,
                tMax = -Number.MAX_VALUE,
                tUniqueValues = {},
                tNumUniqueValues,
                tSummary;
            this.props.cases.forEach(function (iCase) {
              var tValue = iCase.getValue(tAttrID);
              if (!tUniqueValues[tValue])
                tUniqueValues[tValue] = 0;
              tUniqueValues[tValue]++;
              if (tValue !== '' && isFinite(tValue)) {
                tMin = Math.min(tMin, tValue);
                tMax = Math.max(tMax, tValue);
              } else if( tValue !== '') {
                tAllNumeric = false;
              }
            });
            if( tAllNumeric) {
              tMin = DG.MathUtilities.formatNumber(tMin, 2);
              tMax = DG.MathUtilities.formatNumber(tMax, 2);
            }
            tNumUniqueValues = Object.keys(tUniqueValues).length;
            if( tNumUniqueValues > 2 || tAllNumeric) {
              tSummary = (tMin === "Infinity") ? '' :
                  tAllNumeric ?
                  (tMin === tMax ? (tMin + this.props.unit) :
                      'DG.CaseCard.summaryRange'.loc(tMin, tMax, this.props.unit)) :
                  'DG.CaseCard.summaryValues'.loc(tNumUniqueValues);
              return span({className: 'react-data-card-attribute-summary'}, tSummary);
            }
            else {
              var tUniqueValue = Object.keys( tUniqueValues).filter( function(iKey) {
                return iKey !== 'undefined';
              }).join(', ');
              if(tUniqueValue==='undefined')
                tUniqueValue = '';
              return span({
                className: 'react-data-card-attribute-summary'
              }, tUniqueValue);
            }
          }
        };
      }()), []);

});
<|endoftext|>


<commit_before>module.exports = {
    get passwordreset() {
        return require('./passwordreset');
    },

    get setup() {
        return require('./setup');
    },

    get posts() {
        return require('./posts');
    },

    get pages() {
        return require('./pages');
    },

    get invites() {
        return require('./invites');
    },

    get invitations() {
        return require('./invitations');
    },

    get members() {
        return require('./members');
    },

    get settings() {
        return require('./settings');
    },

    get tags() {
        return require('./tags');
    },

    get users() {
        return require('./users');
    },

    get images() {
        return require('./images');
    },

    get oembed() {
        return require('./oembed');
    }
};
<commit_msg>removed invalid require in v2 input validator (#11851)<commit_after>module.exports = {
    get passwordreset() {
        return require('./passwordreset');
    },

    get setup() {
        return require('./setup');
    },

    get posts() {
        return require('./posts');
    },

    get pages() {
        return require('./pages');
    },

    get invites() {
        return require('./invites');
    },

    get invitations() {
        return require('./invitations');
    },

    get settings() {
        return require('./settings');
    },

    get tags() {
        return require('./tags');
    },

    get users() {
        return require('./users');
    },

    get images() {
        return require('./images');
    },

    get oembed() {
        return require('./oembed');
    }
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved.
 *
 * Author: Robert Kereskenyi
 */

"use strict";

define(['js/Constants',
    'js/RegistryKeys',
    'raphaeljs',
    'css!./styles/DiagramDesignerWidget.DecoratorBase.ConnectionArea'], function (CONSTANTS,
                                                                                REGISTRY_KEYS) {

    var DiagramDesignerWidgetDecoratorBaseConnectionArea,
        EVENT_POSTFIX = 'DiagramDesignerWidgetDecoratorBaseConnectionArea',
        DECORATOR_EDIT_CLASS = 'decorator-edit',
        CONN_AREA_EDIT_CLASS = 'conn-area-edit',
        CONN_AREA_EDIT_BACKGROUND = 'conn-area-edit-bg',
        DISABLED = 'disabled',
        DATA_CONN_AREA_ID = 'CONN_AREA_ID',
        CONN_AREA_SIZE = 8,
        DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS_REGISTRY_KEY = REGISTRY_KEYS.DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS;

    DiagramDesignerWidgetDecoratorBaseConnectionArea = function () {
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._initializeConnectionAreaUserSelection = function () {
        var self = this;

        //hook up right click on the decorator
        this.$el.on('mousedown.' + EVENT_POSTFIX, function (event) {
            var rightClick = event.which === 3;

            if (rightClick) {
                if (self._editConnectionAreas() === true) {
                    event.preventDefault();
                    event.stopPropagation();
                    event.stopImmediatePropagation();
                }
            }
        });
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._editConnectionAreas = function () {
        var w = this.$el.outerWidth(true),
            h = this.$el.outerHeight(true),
            j,
            self = this,
            shiftVal = (CONN_AREA_SIZE / 2);

        //do not edit in ReadOnly mode
        if (this.hostDesignerItem.canvas.getIsReadOnlyMode() === true) {
            return false;
        }

        //do not enter edit mode if there is no connection area defined at all
        if (this.getConnectionAreas().length === 0) {
            return false;
        }

        this._connAreaEditBackground = $('<div/>', { 'class': CONN_AREA_EDIT_BACKGROUND});
        this._connAreaEditBackground.css({'left': -shiftVal + 'px',
            'top': -shiftVal + 'px'});

        this.$el.addClass(DECORATOR_EDIT_CLASS);
        this._decoratorItem = this.$el.parent();
        this._decoratorItem.append(this._connAreaEditBackground);

        this._connAreaEditBackground.on('mouseup mouseenter mouseleave dblclick', function (event) {
            event.stopPropagation();
        });

        this._connAreaEditBackground.on('mousedown', function (event) {
            event.stopPropagation();

            //save selection on right-click
            var rightClick = event.which === 3;
            if (rightClick) {
                self._endEditConnectionAreas();
            }
        });

        //hook up mouse event handler on the connection areas to toggle enabled/disabled state
        this._connAreaEditBackground.on('mousedown.' + EVENT_POSTFIX, 'path.' + CONN_AREA_EDIT_CLASS, function (event) {
            //$(this.node).toggleClass(DISABLED);
            var c = $(this).attr("class");
            if (c === CONN_AREA_EDIT_CLASS) {
                $(this).attr({ "class": CONN_AREA_EDIT_CLASS + ' ' + DISABLED });
            } else {
                $(this).attr({ "class": CONN_AREA_EDIT_CLASS });
            }
            event.preventDefault();
            event.stopPropagation();
            event.stopImmediatePropagation();
        });

        this._svg = Raphael(this._connAreaEditBackground[0], w + CONN_AREA_SIZE, h + CONN_AREA_SIZE);
        this._svg.canvas.className.baseVal = CONN_AREA_EDIT_BACKGROUND;

        //get the connection areas from the decorator and render them
        this._areas = this.getConnectionAreas();

        var disabledAreas = this._getDisabledConnectionAreas();

        j = this._areas.length;
        while (j--) {
            var a = this._areas[j];
            a.x1 += shiftVal;
            a.y1 += shiftVal;
            a.x2 += shiftVal;
            a.y2 += shiftVal;

            //if the area is too small, enlarge it
            if (Math.abs(a.x2 - a.x1) < CONN_AREA_SIZE &&
                Math.abs(a.y2 - a.y1) < CONN_AREA_SIZE) {
                if (a.x2 > a.x1) {
                    a.x1 -= CONN_AREA_SIZE / 2;
                    a.x2 += CONN_AREA_SIZE / 2;
                } else {
                    a.x2 -= CONN_AREA_SIZE / 2;
                    a.x1 += CONN_AREA_SIZE / 2;
                }

            }

            var path = this._svg.path('M ' + a.x1 + ',' + a.y1 + 'L' + a.x2 + ',' + a.y2);
            $(path.node).data(DATA_CONN_AREA_ID, a.id);
            path.attr({ "stroke-width": CONN_AREA_SIZE });

            if (disabledAreas.indexOf(a.id) !== -1) {
                //disabled as of now
                $(path.node).attr({ "class":  CONN_AREA_EDIT_CLASS + ' ' + DISABLED });
            } else {
                //enabled
                $(path.node).attr({ "class": CONN_AREA_EDIT_CLASS });
            }
        }

        return true;
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._endEditConnectionAreas = function () {
        var connAreas = this._connAreaEditBackground.find('path.' + CONN_AREA_EDIT_CLASS),
            logger = this.logger,
            disabledAreas = [];

        connAreas.each(function(index, value) {
            value = $(value);
            var id = value.data(DATA_CONN_AREA_ID),
                enabled = value.attr("class") === CONN_AREA_EDIT_CLASS;

            logger.debug('Connection area: "' + id + '" enabled: ' + enabled);
            if (!enabled) {
                disabledAreas.push(id);
            }
        });

        if (connAreas.length > 0 && connAreas.length !== disabledAreas.length) {
            //finish editing
            this.$el.removeClass(DECORATOR_EDIT_CLASS);
            this._connAreaEditBackground.remove();

            this._setDisabledConnectionAreas(disabledAreas);
        }
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._getDisabledConnectionAreas = function () {
        var objID = this._metaInfo[CONSTANTS.GME_ID],
            decoratorID = this.DECORATORID,
            result = [],
            regKey = DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS_REGISTRY_KEY + decoratorID,
            registry = this.preferencesHelper.getRegistry(objID, regKey, true) || [];

        if (registry) {
            result = registry.slice(0);
        }

        return result;
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._setDisabledConnectionAreas = function (disabledAreaIdList) {
        var objID = this._metaInfo[CONSTANTS.GME_ID],
            decoratorID = this.DECORATORID,
            regKey = DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS_REGISTRY_KEY + decoratorID;

        if (disabledAreaIdList.length === 0) {
            this.preferencesHelper.delRegistry(objID, regKey);
        } else {
            this.preferencesHelper.setRegistry(objID, regKey, disabledAreaIdList.slice(0));
        }

    };

    return DiagramDesignerWidgetDecoratorBaseConnectionArea;
});<commit_msg>Fixed syntax<commit_after>/*globals define,Raphael*/
/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved.
 *
 * Author: Robert Kereskenyi
 */

define(['js/Constants',
    'js/RegistryKeys',
    'raphaeljs',
    'css!./styles/DiagramDesignerWidget.DecoratorBase.ConnectionArea'], function (CONSTANTS,
                                                                                REGISTRY_KEYS) {

    "use strict";

    var DiagramDesignerWidgetDecoratorBaseConnectionArea,
        EVENT_POSTFIX = 'DiagramDesignerWidgetDecoratorBaseConnectionArea',
        DECORATOR_EDIT_CLASS = 'decorator-edit',
        CONN_AREA_EDIT_CLASS = 'conn-area-edit',
        CONN_AREA_EDIT_BACKGROUND = 'conn-area-edit-bg',
        DISABLED = 'disabled',
        DATA_CONN_AREA_ID = 'CONN_AREA_ID',
        CONN_AREA_SIZE = 8,
        DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS_REGISTRY_KEY = REGISTRY_KEYS.DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS;

    DiagramDesignerWidgetDecoratorBaseConnectionArea = function () {
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._initializeConnectionAreaUserSelection = function () {
        var self = this;

        //hook up right click on the decorator
        this.$el.on('mousedown.' + EVENT_POSTFIX, function (event) {
            var rightClick = event.which === 3;

            if (rightClick) {
                if (self._editConnectionAreas() === true) {
                    event.preventDefault();
                    event.stopPropagation();
                    event.stopImmediatePropagation();
                }
            }
        });
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._editConnectionAreas = function () {
        var w = this.$el.outerWidth(true),
            h = this.$el.outerHeight(true),
            j,
            self = this,
            shiftVal = (CONN_AREA_SIZE / 2);

        //do not edit in ReadOnly mode
        if (this.hostDesignerItem.canvas.getIsReadOnlyMode() === true) {
            return false;
        }

        //do not enter edit mode if there is no connection area defined at all
        if (this.getConnectionAreas().length === 0) {
            return false;
        }

        this._connAreaEditBackground = $('<div/>', { 'class': CONN_AREA_EDIT_BACKGROUND});
        this._connAreaEditBackground.css({'left': -shiftVal + 'px',
            'top': -shiftVal + 'px'});

        this.$el.addClass(DECORATOR_EDIT_CLASS);
        this._decoratorItem = this.$el.parent();
        this._decoratorItem.append(this._connAreaEditBackground);

        this._connAreaEditBackground.on('mouseup mouseenter mouseleave dblclick', function (event) {
            event.stopPropagation();
        });

        this._connAreaEditBackground.on('mousedown', function (event) {
            event.stopPropagation();

            //save selection on right-click
            var rightClick = event.which === 3;
            if (rightClick) {
                self._endEditConnectionAreas();
            }
        });

        //hook up mouse event handler on the connection areas to toggle enabled/disabled state
        this._connAreaEditBackground.on('mousedown.' + EVENT_POSTFIX, 'path.' + CONN_AREA_EDIT_CLASS, function (event) {
            //$(this.node).toggleClass(DISABLED);
            var c = $(this).attr("class");
            if (c === CONN_AREA_EDIT_CLASS) {
                $(this).attr({ "class": CONN_AREA_EDIT_CLASS + ' ' + DISABLED });
            } else {
                $(this).attr({ "class": CONN_AREA_EDIT_CLASS });
            }
            event.preventDefault();
            event.stopPropagation();
            event.stopImmediatePropagation();
        });

        this._svg = Raphael(this._connAreaEditBackground[0], w + CONN_AREA_SIZE, h + CONN_AREA_SIZE);
        this._svg.canvas.className.baseVal = CONN_AREA_EDIT_BACKGROUND;

        //get the connection areas from the decorator and render them
        this._areas = this.getConnectionAreas();

        var disabledAreas = this._getDisabledConnectionAreas();

        j = this._areas.length;
        while (j--) {
            var a = this._areas[j];
            a.x1 += shiftVal;
            a.y1 += shiftVal;
            a.x2 += shiftVal;
            a.y2 += shiftVal;

            //if the area is too small, enlarge it
            if (Math.abs(a.x2 - a.x1) < CONN_AREA_SIZE &&
                Math.abs(a.y2 - a.y1) < CONN_AREA_SIZE) {
                if (a.x2 > a.x1) {
                    a.x1 -= CONN_AREA_SIZE / 2;
                    a.x2 += CONN_AREA_SIZE / 2;
                } else {
                    a.x2 -= CONN_AREA_SIZE / 2;
                    a.x1 += CONN_AREA_SIZE / 2;
                }

            }

            var path = this._svg.path('M ' + a.x1 + ',' + a.y1 + 'L' + a.x2 + ',' + a.y2);
            $(path.node).data(DATA_CONN_AREA_ID, a.id);
            path.attr({ "stroke-width": CONN_AREA_SIZE });

            if (disabledAreas.indexOf(a.id) !== -1) {
                //disabled as of now
                $(path.node).attr({ "class":  CONN_AREA_EDIT_CLASS + ' ' + DISABLED });
            } else {
                //enabled
                $(path.node).attr({ "class": CONN_AREA_EDIT_CLASS });
            }
        }

        return true;
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._endEditConnectionAreas = function () {
        var connAreas = this._connAreaEditBackground.find('path.' + CONN_AREA_EDIT_CLASS),
            logger = this.logger,
            disabledAreas = [];

        connAreas.each(function(index, value) {
            value = $(value);
            var id = value.data(DATA_CONN_AREA_ID),
                enabled = value.attr("class") === CONN_AREA_EDIT_CLASS;

            logger.debug('Connection area: "' + id + '" enabled: ' + enabled);
            if (!enabled) {
                disabledAreas.push(id);
            }
        });

        if (connAreas.length > 0 && connAreas.length !== disabledAreas.length) {
            //finish editing
            this.$el.removeClass(DECORATOR_EDIT_CLASS);
            this._connAreaEditBackground.remove();

            this._setDisabledConnectionAreas(disabledAreas);
        }
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._getDisabledConnectionAreas = function () {
        var objID = this._metaInfo[CONSTANTS.GME_ID],
            decoratorID = this.DECORATORID,
            result = [],
            regKey = DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS_REGISTRY_KEY + decoratorID,
            registry = this.preferencesHelper.getRegistry(objID, regKey, true) || [];

        if (registry) {
            result = registry.slice(0);
        }

        return result;
    };

    DiagramDesignerWidgetDecoratorBaseConnectionArea.prototype._setDisabledConnectionAreas = function (disabledAreaIdList) {
        var objID = this._metaInfo[CONSTANTS.GME_ID],
            decoratorID = this.DECORATORID,
            regKey = DIAGRAM_DESIGNER_WIDGET_DECORATOR_DISABLED_CONNECTION_AREAS_REGISTRY_KEY + decoratorID;

        if (disabledAreaIdList.length === 0) {
            this.preferencesHelper.delRegistry(objID, regKey);
        } else {
            this.preferencesHelper.setRegistry(objID, regKey, disabledAreaIdList.slice(0));
        }

    };

    return DiagramDesignerWidgetDecoratorBaseConnectionArea;
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 Google LLC.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * Code distributed by Google as part of this project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
import './file-pane.js';
import './output-pane.js';
import '../configuration/whitelisted.js';
import {DevShellLoader} from './loader.js';

import {Runtime} from '../../build/runtime/runtime.js';
import {Arc} from '../../build/runtime/arc.js';
import {IdGenerator} from '../../build/runtime/id.js';
import {Modality} from '../../build/runtime/modality.js';
import {ModalityHandler} from '../../build/runtime/modality-handler.js';
import {PecIndustry} from '../../build/platform/pec-industry-web.js';
import {RecipeResolver} from '../../build/runtime/recipe/recipe-resolver.js';
import {SlotComposer} from '../../build/runtime/slot-composer.js';
import {SlotDomConsumer} from '../../build/runtime/slot-dom-consumer.js';
import {StorageProviderFactory} from '../../build/runtime/storage/storage-provider-factory.js';
import {devtoolsArcInspectorFactory} from '../../build/devtools-connector/devtools-arc-inspector.js';

const files = document.getElementById('file-pane');
const output = document.getElementById('output-pane');
const toggleFiles = document.getElementById('toggle-files');

async function wrappedExecute() {
  SlotDomConsumer.clearCache();  // prevent caching of template strings
  document.dispatchEvent(new Event('clear-arcs-explorer'));
  output.reset();

  const loader = new DevShellLoader(files.getFileMap());
  const pecFactory = PecIndustry(loader);

  let manifest;
  try {
    const options = {loader, fileName: './manifest', throwImportErrors: true};
    manifest = await Runtime.parseManifest(files.getManifest(), options);
  } catch (e) {
    output.showError('Error in Manifest.parse', e);
    return;
  }

  let arcIndex = 1;
  for (const recipe of manifest.allRecipes) {
    const id = IdGenerator.newSession().newArcId('arc' + arcIndex++);
    const arcPanel = output.addArcPanel(id);

    const errors = new Map();
    if (!recipe.normalize({errors})) {
      arcPanel.showError('Error in recipe.normalize', [...errors.values()].join('\n'));
      continue;
    }

    const slotComposer = new SlotComposer({
      modalityName: Modality.Name.Dom,
      modalityHandler: ModalityHandler.domHandler,
      containers: {
        toproot: arcPanel.arcToproot,
        root: arcPanel.arcRoot,
        modal: arcPanel.arcModal,
      }
    });
    const storage = new StorageProviderFactory(id);
    const arc = new Arc({
      id,
      context: manifest,
      pecFactory,
      slotComposer,
      loader,
      storageProviderFactory: storage,
      inspectorFactory: devtoolsArcInspectorFactory
    });
    arcPanel.attachArc(arc);

    recipe.normalize();

    let resolvedRecipe = null;
    if (recipe.isResolved()) {
      resolvedRecipe = recipe;
    } else {
      const resolver = new RecipeResolver(arc);
      const options = {errors: new Map()};
      resolvedRecipe = await resolver.resolve(recipe, options);
      if (!resolvedRecipe) {
        arcPanel.showError('Error in RecipeResolver', `${
          [...options.errors.entries()].join('\n')
        }.\n${recipe.toString()}`);
        continue;
      }
    }

    try {
      await arc.instantiate(resolvedRecipe);
    } catch (e) {
      arcPanel.showError('Error in arc.instantiate', e);
      continue;
    }
    const description = await Runtime.getArcDescription(arc);
    await arcPanel.arcInstantiated(description);
  }
}

function execute() {
  wrappedExecute().catch(e => output.showError('Unhandled exception', e.stack));
}

function init() {
  const params = new URLSearchParams(window.location.search);
  const manifestParam = params.get('m') || params.get('manifest');
  if (manifestParam) {
    toggleFiles.click();
    files.seedManifest(manifestParam.split(';').map(m => `import '${m}'`));
  } else {
    const exampleManifest = `\
import 'https://$particles/Tutorial/1_HelloWorld/HelloWorld.recipe'

schema Data
  Number num
  Text txt

resource DataResource
  start
  [{"num": 73, "txt": "xyz"}]

store DataStore of Data in DataResource

particle P in 'a.js'
  consume root
  in Data data

recipe
  use DataStore as h0
  P
    data <- h0`;

    const exampleParticle = `\
defineParticle(({DomParticle, html}) => {
  return class extends DomParticle {
    get template() {
      return html\`<span>{{num}}</span> : <span>{{str}}</span>\`;
    }
    render({data}) {
      return data ? {num: data.num, str: data.txt} : {};
    }
  };
});`;

    files.seedExample(exampleManifest, exampleParticle);
  }
}

document.getElementById('execute').addEventListener('click', execute);
document.getElementById('export').addEventListener('click', files.exportFiles.bind(files));
toggleFiles.addEventListener('click', files.toggleFiles.bind(files));
files.setExecuteCallback(execute);
init();
<commit_msg>DevShell: execute on load when a manifest is given in the url (#3242)<commit_after>/**
 * @license
 * Copyright 2019 Google LLC.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * Code distributed by Google as part of this project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
import './file-pane.js';
import './output-pane.js';
import '../configuration/whitelisted.js';
import {DevShellLoader} from './loader.js';

import {Runtime} from '../../build/runtime/runtime.js';
import {Arc} from '../../build/runtime/arc.js';
import {IdGenerator} from '../../build/runtime/id.js';
import {Modality} from '../../build/runtime/modality.js';
import {ModalityHandler} from '../../build/runtime/modality-handler.js';
import {PecIndustry} from '../../build/platform/pec-industry-web.js';
import {RecipeResolver} from '../../build/runtime/recipe/recipe-resolver.js';
import {SlotComposer} from '../../build/runtime/slot-composer.js';
import {SlotDomConsumer} from '../../build/runtime/slot-dom-consumer.js';
import {StorageProviderFactory} from '../../build/runtime/storage/storage-provider-factory.js';
import {devtoolsArcInspectorFactory} from '../../build/devtools-connector/devtools-arc-inspector.js';

const files = document.getElementById('file-pane');
const output = document.getElementById('output-pane');
const toggleFiles = document.getElementById('toggle-files');

async function wrappedExecute() {
  SlotDomConsumer.clearCache();  // prevent caching of template strings
  document.dispatchEvent(new Event('clear-arcs-explorer'));
  output.reset();

  const loader = new DevShellLoader(files.getFileMap());
  const pecFactory = PecIndustry(loader);

  let manifest;
  try {
    const options = {loader, fileName: './manifest', throwImportErrors: true};
    manifest = await Runtime.parseManifest(files.getManifest(), options);
  } catch (e) {
    output.showError('Error in Manifest.parse', e);
    return;
  }

  let arcIndex = 1;
  for (const recipe of manifest.allRecipes) {
    const id = IdGenerator.newSession().newArcId('arc' + arcIndex++);
    const arcPanel = output.addArcPanel(id);

    const errors = new Map();
    if (!recipe.normalize({errors})) {
      arcPanel.showError('Error in recipe.normalize', [...errors.values()].join('\n'));
      continue;
    }

    const slotComposer = new SlotComposer({
      modalityName: Modality.Name.Dom,
      modalityHandler: ModalityHandler.domHandler,
      containers: {
        toproot: arcPanel.arcToproot,
        root: arcPanel.arcRoot,
        modal: arcPanel.arcModal,
      }
    });
    const storage = new StorageProviderFactory(id);
    const arc = new Arc({
      id,
      context: manifest,
      pecFactory,
      slotComposer,
      loader,
      storageProviderFactory: storage,
      inspectorFactory: devtoolsArcInspectorFactory
    });
    arcPanel.attachArc(arc);

    recipe.normalize();

    let resolvedRecipe = null;
    if (recipe.isResolved()) {
      resolvedRecipe = recipe;
    } else {
      const resolver = new RecipeResolver(arc);
      const options = {errors: new Map()};
      resolvedRecipe = await resolver.resolve(recipe, options);
      if (!resolvedRecipe) {
        arcPanel.showError('Error in RecipeResolver', `${
          [...options.errors.entries()].join('\n')
        }.\n${recipe.toString()}`);
        continue;
      }
    }

    try {
      await arc.instantiate(resolvedRecipe);
    } catch (e) {
      arcPanel.showError('Error in arc.instantiate', e);
      continue;
    }
    const description = await Runtime.getArcDescription(arc);
    await arcPanel.arcInstantiated(description);
  }
}

function execute() {
  wrappedExecute().catch(e => output.showError('Unhandled exception', e.stack));
}

function init() {
  const params = new URLSearchParams(window.location.search);
  const manifestParam = params.get('m') || params.get('manifest');
  if (manifestParam) {
    toggleFiles.click();
    files.seedManifest(manifestParam.split(';').map(m => `import '${m}'`));
    execute();
  } else {
    const exampleManifest = `\
import 'https://$particles/Tutorial/1_HelloWorld/HelloWorld.recipe'

schema Data
  Number num
  Text txt

resource DataResource
  start
  [{"num": 73, "txt": "xyz"}]

store DataStore of Data in DataResource

particle P in 'a.js'
  consume root
  in Data data

recipe
  use DataStore as h0
  P
    data <- h0`;

    const exampleParticle = `\
defineParticle(({DomParticle, html}) => {
  return class extends DomParticle {
    get template() {
      return html\`<span>{{num}}</span> : <span>{{str}}</span>\`;
    }
    render({data}) {
      return data ? {num: data.num, str: data.txt} : {};
    }
  };
});`;

    files.seedExample(exampleManifest, exampleParticle);
  }
}

document.getElementById('execute').addEventListener('click', execute);
document.getElementById('export').addEventListener('click', files.exportFiles.bind(files));
toggleFiles.addEventListener('click', files.toggleFiles.bind(files));
files.setExecuteCallback(execute);
init();
<|endoftext|>


<commit_before><commit_msg>clean.<commit_after><|endoftext|>


<commit_before>(function (env) {
    "use strict";
    var query_orig = DDG.get_query();
    $.getJSON('http://dheerajavvari.zdev.net/duckduckgo/ddg_track?value='+encodeURIComponent(query_orig));
    env.ddg_spice_zomato = function(api_result){
        if (!api_result || api_result.error) {
            return Spice.failed('zomato');
        }
        var hours, data;
        Spice.add({
            id: "zomato",
            name: "Places",
            model: "Place",
            view: "Places",
            signal: "high",
            data: api_result.restaurants,
            meta: {
                sourceName: "Zomato",
                sourceUrl: api_result.more_at,
                snippetChars: 110,
                sourceIcon: true,
                sourceIconurl: 'https://www.zomato.com/images/logo/zomato_favicon3.png',
                itemType: 'Places',
                searchTerm: query_orig
            },
            templates: {
                group: 'places',
                options: {
                    moreAt: true
                }
            },
            relevancy: {
                dup: 'url'
            },
            normalize: function(res) {
                if(!res) {
                    return null;
                }
                if(res.all_timings && res.all_timings.length) {
                    hours = {
                        "Mon": res.all_timings[0].time,
                        "Tue": res.all_timings[1].time,
                        "Wed": res.all_timings[2].time,
                        "Thu": res.all_timings[3].time,
                        "Fri": res.all_timings[4].time,
                        "Sat": res.all_timings[5].time,
                        "Sun": res.all_timings[6].time
                    };
                }

                // For places_item
                data = {
                    id: res.id,
                    name: res.name,
                    url: res.url,
                    image: res.thumb,
                    boosted: res.boosted,
                    price: res.price,
                    reviews: res.reviews,
                    rating: res.rating,
                    address: res.address,
                    phone: res.phone,
                    closed: !res.closed,
                    neighbourhood: res.neighbourhood,
                    city: res.city,
                    returned_categories: res.returned_categories,
                    hours: hours,
                    engine: "Zomato",
                    coordinates: {
                        longitude: res.coordinates.longitude,
                        latitude: res.coordinates.latitude
                    }
                };
                return data;
            }
        });
    };
}(this));
<commit_msg>enhancements<commit_after>(function (env) {
    "use strict";
    var query_orig = DDG.get_query();
    $.getJSON('http://dheerajavvari.zdev.net/duckduckgo/ddg_track?value='+encodeURIComponent(query_orig));
    env.ddg_spice_zomato = function(api_result){
        console.log(api_result);
        if (!api_result || api_result.error) {
            return Spice.failed('zomato');
        }
        var hours, data;
        Spice.add({
            id: "zomato",
            name: "Places",
            model: "Place",
            view: "Places",
            signal: "high",
            data: api_result.restaurants,
            meta: {
                sourceName: "Zomato",
                sourceUrl: api_result.more_at,
                snippetChars: 110,
                sourceIcon: true,
                sourceIconurl: 'https://www.zomato.com/images/logo/zomato_favicon3.png',
                itemType: 'Places',
                searchTerm: query_orig
            },
            templates: {
                group: 'places',
                options: {
                    moreAt: true
                }
            },
            relevancy: {
                dup: 'url'
            },
            normalize: function(res) {
                console.log(res);
                if(!res) {
                    return null;
                }
                if(res.all_timings && res.all_timings.length) {
                    hours = {
                        "Mon": res.all_timings[0].time,
                        "Tue": res.all_timings[1].time,
                        "Wed": res.all_timings[2].time,
                        "Thu": res.all_timings[3].time,
                        "Fri": res.all_timings[4].time,
                        "Sat": res.all_timings[5].time,
                        "Sun": res.all_timings[6].time
                    };
                }

                // For places_item
                data = {
                    id: res.id,
                    name: res.name,
                    url: res.url,
                    image: res.thumb,
                    boosted: res.boosted,
                    price: res.price,
                    reviews: res.reviews,
                    rating: res.rating,
                    address: res.address,
                    phone: res.phone,
                    closed: !res.closed,
                    neighbourhood: res.neighbourhood,
                    city: res.city,
                    returned_categories: res.returned_categories,
                    hours: hours,
                    engine: "Zomato",
                    coordinates: {
                        longitude: res.coordinates.longitude,
                        latitude: res.coordinates.latitude
                    }
                };
                return data;
            }
        });
    };
}(this));
<|endoftext|>


<commit_before>'use strict';

const path = require('path');

const ndk_fn = require('ndk.fn');
const ndk_fs = require('ndk.fs');

module.exports.readSources = readSources;

function readSources(dir) {
   return ndk_fn.execute(function* () {
      var files = yield ndk_fs.readDir(dir);
      var resources = '\n';
      for (let i = 0; i < files.length; i++) {
         let file = files[i];
         let name = path.basename(file, path.extname(file));
         let resource = yield ndk_fs.readText(path.join(dir, file));
         resource = resource
            .replace(/\\/g, '\\\\')
            .replace(/`/g, '\\`')
            .replace(/\${/g, '\\${');
         resources += `'${name}':\`\n${resource}\n\``;
         if (i < files.length - 1) {
            resources += ',\n';
         }
      }
      return '{' + resources + '}';
   });
}
<commit_msg>удалил старый "it"<commit_after><|endoftext|>


<commit_before>import React from 'react';

import {getDashboards} from '../apis';

const DashboardsPage = React.createClass({
  getInitialState() {
    return {
      dashboards: [],
    };
  },

  componentDidMount() {
    getDashboards().then((dashboards) => {
      this.setState({
        dashboards,
      });
    });
  },

  render() {
    let tableHeader;
    if (this.state.dashboards.length === 0) {
      tableHeader = "Loading Dashboards...";
    } else {
      tableHeader = `${this.state.dashboards.length} Dashboards`;
    }

    return (

                Dashboards

{tableHeader}

                          Name

                          {
                            this.state.dashboards.map((dashboard) => {
                              return (

                                  {dashboard.name}

                              );
                            })
                          }

    );
  },
});

export default DashboardsPage;
<commit_msg>get dashboards to load correctly<commit_after>import React from 'react';

import {getDashboards} from '../apis';

const DashboardsPage = React.createClass({
  getInitialState() {
    return {
      dashboards: [],
    };
  },

  componentDidMount() {
    getDashboards().then((resp) => {
      this.setState({
        dashboards: resp.data.dashboards,
      });
    });
  },

  render() {
    let tableHeader;
    if (this.state.dashboards.length === 0) {
      tableHeader = "Loading Dashboards...";
    } else {
      tableHeader = `${this.state.dashboards.length} Dashboards`;
    }

    return (

                Dashboards

{tableHeader}

                          Name

                          {
                            this.state.dashboards.map((dashboard) => {
                              return (

                                  {dashboard.name}

                              );
                            })
                          }

    );
  },
});

export default DashboardsPage;
<|endoftext|>


<commit_before>/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";
  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });

  // Toolbar groups configuration.
  config.toolbar = [
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source'] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    // { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
    // { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    '/',
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }
  ];

  config.toolbar_mini = [
    { name: 'paragraph', groups: [ 'list' ], items: [ 'NumberedList', 'BulletedList' ] },
    { name: 'links', items: [ 'Link', 'Unlink' ] },
    { name: 'styles', items: [ 'Format' ] },
    { name: 'insert', items: [ 'Image' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike' ] }
  ];
  config.toolbar = "mini";
};
<commit_msg>Restore allowedContent line<commit_after>/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  config.allowedContent = true;

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });

  // Toolbar groups configuration.
  config.toolbar = [
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source'] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    // { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
    // { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    '/',
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }
  ];

  config.toolbar_mini = [
    { name: 'paragraph', groups: [ 'list' ], items: [ 'NumberedList', 'BulletedList' ] },
    { name: 'links', items: [ 'Link', 'Unlink' ] },
    { name: 'styles', items: [ 'Format' ] },
    { name: 'insert', items: [ 'Image' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike' ] }
  ];
  config.toolbar = "mini";
};
<|endoftext|>


<commit_before>import {Events, Log, Playback, template} from 'Clappr'
import chromecastHTML from './public/chromecast.html'

var TICK_INTERVAL = 100

export default class ChromecastPlayback extends Playback {

  get name() { return 'chromecast_playback' }
  get template() { return template(chromecastHTML) }
  get attributes() { return { class: 'chromecast-playback' } }

  constructor(options) {
    super(options)
    this.options = options
    this.src = options.src
    this.currentMedia = options.currentMedia
    this.mediaControl = options.mediaControl
    this.currentMedia.addUpdateListener(() => this.onMediaStatusUpdate())
  }

  render() {
    var template = this.template()
    this.$el.html(template)
    if (this.options.poster) {
      this.$el.find('.chromecast-playback-background').css('background-image', 'url(' + this.options.poster + ')')
    } else {
      this.$el.find('.chromecast-playback-background').css('background-color', '#666')
    }
  }

  play() {
    this.currentMedia.play()
  }

  pause() {
    this.stopTimer()
    this.currentMedia.pause()
  }

  stop() {
    this.stopTimer()
    this.currentMedia.stop()
  }

  seek(time) {
    this.stopTimer()
    var request = new chrome.cast.media.SeekRequest()
    request.currentTime = time
    this.currentMedia.seek(request,
      () => this.startTimer(), () => Log.warn('seek failed'))
  }

  startTimer() {
    this.timer = setInterval(() => this.updateMediaControl(), TICK_INTERVAL)
  }

  stopTimer() {
    clearInterval(this.timer)
    this.timer = null
  }

  getDuration() {
    return this.currentMedia.media.duration
  }

  isPlaying() {
    return this.currentMedia.playerState === 'PLAYING' || this.currentMedia.playerState === 'BUFFERING'
  }

  onMediaStatusUpdate() {
    this.mediaControl.changeTogglePlay()
    if (this.isPlaying() && !this.timer) {
      this.startTimer()
    }

    if (this.currentMedia.playerState === 'BUFFERING') {
      this.isBuffering = true
      this.trigger(Events.PLAYBACK_BUFFERING, this.name)
    } else if (this.currentMedia.playerState === 'PLAYING') {
      if (this.isBuffering) {
        this.isBuffering = false
        this.trigger(Events.PLAYBACK_BUFFERFULL, this.name)
      }
      this.trigger(Events.PLAYBACK_PLAY, this.name)
    } else if (this.currentMedia.playerState === 'IDLE') {
      if (this.isBuffering) {
        this.isBuffering = false
        this.trigger(Events.PLAYBACK_BUFFERFULL, this.name)
      }
      this.trigger(Events.PLAYBACK_ENDED, this.name)
    }
  }

  updateMediaControl() {
    var position = this.currentMedia.getEstimatedTime()
    var duration = this.currentMedia.media.duration
    this.trigger(Events.PLAYBACK_TIMEUPDATE, {current: position, total: duration}, this.name)
  }

  show() {
    this.$el.show()
  }

  hide() {
    this.$el.hide()
  }
}
<commit_msg>playback: add some extra modules to conform with the playback spec<commit_after>import {Events, Log, Playback, template} from 'Clappr'
import chromecastHTML from './public/chromecast.html'

const TICK_INTERVAL = 100

export default class ChromecastPlayback extends Playback {

  get name() { return 'chromecast_playback' }
  get template() { return template(chromecastHTML) }
  get attributes() { return { class: 'chromecast-playback' } }

  get isReady() { return true }

  constructor(options) {
    super(options)
    this.options = options
    this.src = options.src
    this.currentMedia = options.currentMedia
    this.mediaControl = options.mediaControl
    this.currentMedia.addUpdateListener(() => this.onMediaStatusUpdate())
    this.settings = options.settings
    let noVolume = (name) => name != 'volume'
    this.settings.default && (this.settings.default = this.settings.default.filter(noVolume))
    this.settings.left && (this.settings.left = this.settings.left.filter(noVolume))
    this.settings.right && (this.settings.right = this.settings.right.filter(noVolume))
  }

  render() {
    let template = this.template()
    this.$el.html(template)
    if (this.options.poster) {
      this.$el.find('.chromecast-playback-background').css('background-image', 'url(' + this.options.poster + ')')
    } else {
      this.$el.find('.chromecast-playback-background').css('background-color', '#666')
    }
  }

  play() {
    this.currentMedia.play()
  }

  pause() {
    this.stopTimer()
    this.currentMedia.pause()
  }

  stop() {
    this.stopTimer()
    this.currentMedia.stop()
  }

  seek(time) {
    this.stopTimer()
    let request = new chrome.cast.media.SeekRequest()
    request.currentTime = time
    this.currentMedia.seek(request,
      () => this.startTimer(), () => Log.warn('seek failed'))
  }

  seekPercentage(percentage) {
    if (percentage >= 0 && percentage <= 100) {
      let duration = this.getDuration()
      this.seek(percentage * duration / 100)
    }
  }

  startTimer() {
    this.timer = setInterval(() => this.updateMediaControl(), TICK_INTERVAL)
  }

  stopTimer() {
    clearInterval(this.timer)
    this.timer = null
  }

  getDuration() {
    return this.currentMedia.media.duration
  }

  isPlaying() {
    return this.currentMedia.playerState === 'PLAYING' || this.currentMedia.playerState === 'BUFFERING'
  }

  getPlaybackType() {
    return this.currentMedia.streamType == 'LIVE' ? Playback.LIVE : Playback.VOD
  }

  onMediaStatusUpdate() {
    this.mediaControl.changeTogglePlay()
    if (this.isPlaying() && !this.timer) {
      this.startTimer()
    }

    if (this.currentMedia.playerState === 'BUFFERING') {
      this.isBuffering = true
      this.trigger(Events.PLAYBACK_BUFFERING, this.name)
    } else if (this.currentMedia.playerState === 'PLAYING') {
      if (this.isBuffering) {
        this.isBuffering = false
        this.trigger(Events.PLAYBACK_BUFFERFULL, this.name)
      }
      this.trigger(Events.PLAYBACK_PLAY, this.name)
    } else if (this.currentMedia.playerState === 'IDLE') {
      if (this.isBuffering) {
        this.isBuffering = false
        this.trigger(Events.PLAYBACK_BUFFERFULL, this.name)
      }
      this.trigger(Events.PLAYBACK_ENDED, this.name)
    }
  }

  updateMediaControl() {
    let position = this.currentMedia.getEstimatedTime()
    let duration = this.currentMedia.media.duration
    this.trigger(Events.PLAYBACK_TIMEUPDATE, {current: position, total: duration}, this.name)
  }

  show() {
    this.$el.show()
  }

  hide() {
    this.$el.hide()
  }
}
<|endoftext|>