<commit_before>/*
 * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
 */

/**
 * @class Mobile.SalesLogix.Views.Charts.GenericPie
 *
 * @extends Sage.Platform.Mobile.View
 * @mixins Mobile.SalesLogix.Views.Charts._ChartMixin
 *
 * @requires Sage.Platform.Mobile.View
 *
 */
define('Mobile/SalesLogix/Views/Charts/GenericPie', [
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/dom-geometry',
    'dojox/charting/Chart',
    'dojox/charting/plot2d/Pie',
    'dojox/charting/axis2d/Default',
    'dojox/charting/widget/Legend',
    'Sage/Platform/Mobile/View',
    './_ChartMixin'
], function(
    declare,
    lang,
    array,
    domGeo,
    Chart,
    PlotType,
    Default,
    Legend,
    View,
    _ChartMixin
) {
    return declare('Mobile.SalesLogix.Views.Charts.GenericPie', [View, _ChartMixin], {
        id: 'chart_generic_pie',
        titleText: '',
        otherText: 'Other',
        expose: false,
        chart: null,
        MAX_ITEMS: 5,
        pieColor: '#0896e9',
        stroke: '#ffffff',
        seriesColors: [
            '#4fb521',
            '#0896e9',
            '#1c9a18',
            '#0c7ad8',
            '#157a13'
        ],
        otherColor: '#005bb8',

        formatter: function(val) {
            return val;
        },

        attributeMap: {
            chartContent: {node: 'contentNode', type: 'innerHTML'}
        },

        widgetTemplate: new Simplate([
            '
',
                '

',
                '

',
            '
'
        ]),
        createChart: function (feedData) {
            this.inherited(arguments);

            var labels, box, searchExpressionHeight;

            if (this.chart) {
                this.chart.destroy(true);
            }

            this.showSearchExpression();
            searchExpressionHeight = this.getSearchExpressionHeight();

            labels = this._labels(feedData);
            box = domGeo.getMarginBox(this.domNode);
            box.h = box.h - searchExpressionHeight;

            this.chart = new Chart(this.contentNode);
            this.chart.addPlot('default', {
                type: PlotType,
                font: this.font,
                fontColor: this.fontColor,
                fontColor: 'black',
                labelOffset: 50,
                radius: box.w >= box.h /* check lanscape or portrait mode */ ?
                    Math.floor(box.h / 2) - 10 :
                    Math.floor(box.w / 2) - 10
            });

            this.chart.addSeries('default', labels, {
                stroke: {
                    color: this.stroke
                },
                fill: this.pieColor,
                font: this.font,
                fontColor: this.fontColor
            });
            this.chart.render();
            this.chart.resize(box.w, box.h);
        },
        _labels: function(feedData) {
            var data = [], otherY = 0, otherText;
            array.forEach(feedData, function(item, index) {
                if (index < this.MAX_ITEMS) {
                    data.push({
                        y: item.value,
                        text: item.$descriptor + ' (' + this.formatter(item.value) + ')',
                        value: index,
                        color: this.seriesColors[index] || this.pieColor
                    });
                } else {
                    otherY = otherY + item.value;
                    otherText = this.otherText + ' (' + this.formatter(otherY) + ')';
                    data[this.MAX_ITEMS] = {
                        y: otherY,
                        text: otherText,
                        color: this.otherColor
                    };
                }
            }, this);

            return data;
        }
    });
});
<commit_msg>JShint fix.<commit_after>/*
 * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
 */

/**
 * @class Mobile.SalesLogix.Views.Charts.GenericPie
 *
 * @extends Sage.Platform.Mobile.View
 * @mixins Mobile.SalesLogix.Views.Charts._ChartMixin
 *
 * @requires Sage.Platform.Mobile.View
 *
 */
define('Mobile/SalesLogix/Views/Charts/GenericPie', [
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/dom-geometry',
    'dojox/charting/Chart',
    'dojox/charting/plot2d/Pie',
    'dojox/charting/axis2d/Default',
    'dojox/charting/widget/Legend',
    'Sage/Platform/Mobile/View',
    './_ChartMixin'
], function(
    declare,
    lang,
    array,
    domGeo,
    Chart,
    PlotType,
    Default,
    Legend,
    View,
    _ChartMixin
) {
    return declare('Mobile.SalesLogix.Views.Charts.GenericPie', [View, _ChartMixin], {
        id: 'chart_generic_pie',
        titleText: '',
        otherText: 'Other',
        expose: false,
        chart: null,
        MAX_ITEMS: 5,
        pieColor: '#0896e9',
        stroke: '#ffffff',
        seriesColors: [
            '#4fb521',
            '#0896e9',
            '#1c9a18',
            '#0c7ad8',
            '#157a13'
        ],
        otherColor: '#005bb8',

        formatter: function(val) {
            return val;
        },

        attributeMap: {
            chartContent: {node: 'contentNode', type: 'innerHTML'}
        },

        widgetTemplate: new Simplate([
            '
',
                '

',
                '

',
            '
'
        ]),
        createChart: function (feedData) {
            this.inherited(arguments);

            var labels, box, searchExpressionHeight;

            if (this.chart) {
                this.chart.destroy(true);
            }

            this.showSearchExpression();
            searchExpressionHeight = this.getSearchExpressionHeight();

            labels = this._labels(feedData);
            box = domGeo.getMarginBox(this.domNode);
            box.h = box.h - searchExpressionHeight;

            this.chart = new Chart(this.contentNode);
            this.chart.addPlot('default', {
                type: PlotType,
                font: this.font,
                fontColor: this.fontColor,
                labelOffset: 50,
                radius: box.w >= box.h /* check lanscape or portrait mode */ ?
                    Math.floor(box.h / 2) - 10 :
                    Math.floor(box.w / 2) - 10
            });

            this.chart.addSeries('default', labels, {
                stroke: {
                    color: this.stroke
                },
                fill: this.pieColor,
                font: this.font,
                fontColor: this.fontColor
            });
            this.chart.render();
            this.chart.resize(box.w, box.h);
        },
        _labels: function(feedData) {
            var data = [], otherY = 0, otherText;
            array.forEach(feedData, function(item, index) {
                if (index < this.MAX_ITEMS) {
                    data.push({
                        y: item.value,
                        text: item.$descriptor + ' (' + this.formatter(item.value) + ')',
                        value: index,
                        color: this.seriesColors[index] || this.pieColor
                    });
                } else {
                    otherY = otherY + item.value;
                    otherText = this.otherText + ' (' + this.formatter(otherY) + ')';
                    data[this.MAX_ITEMS] = {
                        y: otherY,
                        text: otherText,
                        color: this.otherColor
                    };
                }
            }, this);

            return data;
        }
    });
});
<|endoftext|>


<commit_before>import { scaleLinear, scaleBand } from 'd3';
import keyBy from 'lodash/keyBy';
import isUndefined from 'lodash/isUndefined';
import values from 'lodash/values';

import { computeDataMax } from './data';
import { propResolver } from './objects';

/**
 * Determines the orientation of the bars relative to the default orientation
 * of vertical bars.
 * @param orientation : A string that represents the orientation of the chart
 * @returns {boolean} : Returns whether the given argument is vertical
 */
export function isVertical(orientation) {
  return (orientation.toLowerCase() === 'vertical');
}

export function computeStackMax(data, stackAccessor, valueAccessor) {
  // Iterate through the data, creating an object mapping stack name to the max value for the stack.
  const maxPerStack = data.reduce((acc, datum) => {
    const stack = propResolver(datum, stackAccessor);
    const value = propResolver(datum, valueAccessor);
    // If the key exists on the accumulator, add the current value to its value.
    // Otherwise add the key, initializing its value with the current value.
    /* eslint-disable no-param-reassign */
    if (stack in acc) {
      acc[stack] += value;
    } else {
      acc[stack] = value;
    }
    /* eslint-enable no-param-reassign */
    return acc;
  }, {});

  // Return the max of the biggest stack.
  return values(maxPerStack).reduce((prevMax, currMax) => Math.max(prevMax, currMax), 0);
}

export function computeStackDatumKey(stack, layer) {
  return `${stack}:${layer}`;
}

/**
 * Computes the spatial offsets (start, end) for each bar in a stacked bar chart
 *
 * @param {datum[]} data - Array of datum objects, each of which must contain fields denoting the
 *   stack, layer, and value.
 * @param {string[]|number[]} stackDomain - names of the categories represented by each stack
 * @param {string[]|number[]} layerDomain - names of the categories represented by each layer
 * @param {string|number} stackField - property name of each datum object denoting the stack
 * @param {string|number} layerField - property name on each datum object denoting the layer
 * @param {number} valueField - property name on each datum object denoting the value
 *
 * @returns {object} - a mapping of keys in the form `${stack}:${layer}` to each bar's spatial offset
 */
export function computeStackOffsets(
  data,
  stackDomain,
  layerDomain,
  stackField,
  layerField,
  valueField,
) {
  // We create an object mapping keys `${stack}:${layer}` to each datum object.
  // That allows us quick lookups to retrieve the value of each bar.
  const dataByStackAndLayer = keyBy(
    data,
    datum => computeStackDatumKey(datum[stackField], datum[layerField]),
  );

  // Now we create an object mapping keys `${stack}:${layer}`, the same as in `dataByStackAndLayer`,
  // to the spatial offsets [start, end] for each bar. It's important that we traverse each stack in
  // the same order, so that the ordering of layers is consistent.
  const offsetsByStackAndLayer = Object.create(null);

  // traverse the stacks
  for (const stack of stackDomain) {
    // In each stack, we keep track of where the previous layer ended.
    // This will be the start of the next layer.
    let prevEnd = 0;

    // traverse the layers in a stack
    for (const layer of layerDomain) {
      const key = computeStackDatumKey(stack, layer);
      const datum = dataByStackAndLayer[key];
      const value = datum[valueField];
      const start = prevEnd;

      // store the starting offset for the current bar
      offsetsByStackAndLayer[key] = start;

      // store the ending offset for use in the next iteration
      prevEnd = start + value;
    }
  }

  return offsetsByStackAndLayer;
}

export function computeDomainScale(categories, orientation, spaceAvailable) {
  return scaleBand()
    .domain(categories)
    .range(isVertical(orientation) ? [0, spaceAvailable] : [spaceAvailable, 0]);
}

/**
 * Adjusts the domain scaling function with alignment and band padding
 *
 * @param scale : a function that computes the bar's position on the domain axis
 * @param align : Represents the alignment properties for the ordinal scale bandwidth
 * @param innerPadding : Represents the inner band padding property for the ordinal scale bandwidth
 * @param outerPadding : Represents the outter band padding property for the ordinal scale bandwidth
 * @returns {function} : Returns a function that represents the ordinal scale for chart
 */
export function adjustDomainScale(scale, align, innerPadding, outerPadding) {
  scale.paddingInner(innerPadding);
  scale.paddingOuter(outerPadding);
  scale.align(align);
  return scale;
}

export function getDomainScale({
  align,
  bandPadding,
  innerPadding,
  outerPadding,
  categories,
  orientation,
  scales,
  height,
  width,
}) {
  const vertical = isVertical(orientation);

  const scale = (vertical ? scales.x : scales.y);
  const domainScale = scale
    // If a scaling function was passed via the `scales` prop, we make a copy of it (to avoid mutating the original).
    ? scale.copy()
    // Otherwise we compute the scaling function.
    : computeDomainScale(categories, orientation, vertical ? width : height);

  // Adjust the domain scale based on alignment and padding.
  return adjustDomainScale(
    domainScale,
    align,
    !isUndefined(innerPadding) ? innerPadding : bandPadding,
    !isUndefined(outerPadding) ? outerPadding : bandPadding,
  );
}

export function computeRangeScale(max, orientation, spaceAvailable) {
  return scaleLinear()
    .domain([0, max])
    .range(isVertical(orientation) ? [spaceAvailable, 0] : [0, spaceAvailable]);
}

export function getRangeScale({
  data,
  dataAccessors,
  orientation,
  rangeMax,
  scales: { x: scaleX, y: scaleY },
  height,
  width,
  stacked = false,
}) {
  const vertical = isVertical(orientation);

  const scale = vertical ? scaleY : scaleX;
  if (scale) {
    return scale.copy();
  }

  /* eslint-disable no-nested-ternary */
  const max = !isUndefined(rangeMax)
    ? rangeMax
    : (
      stacked
      ? computeStackMax(data, dataAccessors.category, dataAccessors.value)
      : computeDataMax(data, dataAccessors.value)
    );
  /* eslint-enable no-nested-ternary */

  return computeRangeScale(max, orientation, vertical ? height : width);
}
<commit_msg>When getting domain and range scales, remember to check for undefined<commit_after>import { scaleLinear, scaleBand } from 'd3';
import keyBy from 'lodash/keyBy';
import isUndefined from 'lodash/isUndefined';
import values from 'lodash/values';

import { computeDataMax } from './data';
import { propResolver } from './objects';

/**
 * Determines the orientation of the bars relative to the default orientation
 * of vertical bars.
 * @param orientation : A string that represents the orientation of the chart
 * @returns {boolean} : Returns whether the given argument is vertical
 */
export function isVertical(orientation) {
  return (orientation.toLowerCase() === 'vertical');
}

export function computeStackMax(data, stackAccessor, valueAccessor) {
  // Iterate through the data, creating an object mapping stack name to the max value for the stack.
  const maxPerStack = data.reduce((acc, datum) => {
    const stack = propResolver(datum, stackAccessor);
    const value = propResolver(datum, valueAccessor);
    // If the key exists on the accumulator, add the current value to its value.
    // Otherwise add the key, initializing its value with the current value.
    /* eslint-disable no-param-reassign */
    if (stack in acc) {
      acc[stack] += value;
    } else {
      acc[stack] = value;
    }
    /* eslint-enable no-param-reassign */
    return acc;
  }, {});

  // Return the max of the biggest stack.
  return values(maxPerStack).reduce((prevMax, currMax) => Math.max(prevMax, currMax), 0);
}

export function computeStackDatumKey(stack, layer) {
  return `${stack}:${layer}`;
}

/**
 * Computes the spatial offsets (start, end) for each bar in a stacked bar chart
 *
 * @param {datum[]} data - Array of datum objects, each of which must contain fields denoting the
 *   stack, layer, and value.
 * @param {string[]|number[]} stackDomain - names of the categories represented by each stack
 * @param {string[]|number[]} layerDomain - names of the categories represented by each layer
 * @param {string|number} stackField - property name of each datum object denoting the stack
 * @param {string|number} layerField - property name on each datum object denoting the layer
 * @param {number} valueField - property name on each datum object denoting the value
 *
 * @returns {object} - a mapping of keys in the form `${stack}:${layer}` to each bar's spatial offset
 */
export function computeStackOffsets(
  data,
  stackDomain,
  layerDomain,
  stackField,
  layerField,
  valueField,
) {
  // We create an object mapping keys `${stack}:${layer}` to each datum object.
  // That allows us quick lookups to retrieve the value of each bar.
  const dataByStackAndLayer = keyBy(
    data,
    datum => computeStackDatumKey(datum[stackField], datum[layerField]),
  );

  // Now we create an object mapping keys `${stack}:${layer}`, the same as in `dataByStackAndLayer`,
  // to the spatial offsets [start, end] for each bar. It's important that we traverse each stack in
  // the same order, so that the ordering of layers is consistent.
  const offsetsByStackAndLayer = Object.create(null);

  // traverse the stacks
  for (const stack of stackDomain) {
    // In each stack, we keep track of where the previous layer ended.
    // This will be the start of the next layer.
    let prevEnd = 0;

    // traverse the layers in a stack
    for (const layer of layerDomain) {
      const key = computeStackDatumKey(stack, layer);
      const datum = dataByStackAndLayer[key];
      const value = datum[valueField];
      const start = prevEnd;

      // store the starting offset for the current bar
      offsetsByStackAndLayer[key] = start;

      // store the ending offset for use in the next iteration
      prevEnd = start + value;
    }
  }

  return offsetsByStackAndLayer;
}

export function computeDomainScale(categories, orientation, spaceAvailable) {
  return scaleBand()
    .domain(categories)
    .range(isVertical(orientation) ? [0, spaceAvailable] : [spaceAvailable, 0]);
}

/**
 * Adjusts the domain scaling function with alignment and band padding
 *
 * @param scale : a function that computes the bar's position on the domain axis
 * @param align : Represents the alignment properties for the ordinal scale bandwidth
 * @param innerPadding : Represents the inner band padding property for the ordinal scale bandwidth
 * @param outerPadding : Represents the outter band padding property for the ordinal scale bandwidth
 * @returns {function} : Returns a function that represents the ordinal scale for chart
 */
export function adjustDomainScale(scale, align, innerPadding, outerPadding) {
  scale.paddingInner(innerPadding);
  scale.paddingOuter(outerPadding);
  scale.align(align);
  return scale;
}

export function getDomainScale({
  align,
  bandPadding,
  innerPadding,
  outerPadding,
  categories,
  orientation,
  scales,
  height,
  width,
}) {
  const vertical = isVertical(orientation);

  const scale = scales && (vertical ? scales.x : scales.y);
  const domainScale = scale
    // If a scaling function was passed via the `scales` prop, we make a copy of it (to avoid mutating the original).
    ? scale.copy()
    // Otherwise we compute the scaling function.
    : computeDomainScale(categories, orientation, vertical ? width : height);

  // Adjust the domain scale based on alignment and padding.
  return adjustDomainScale(
    domainScale,
    align,
    !isUndefined(innerPadding) ? innerPadding : bandPadding,
    !isUndefined(outerPadding) ? outerPadding : bandPadding,
  );
}

export function computeRangeScale(max, orientation, spaceAvailable) {
  return scaleLinear()
    .domain([0, max])
    .range(isVertical(orientation) ? [spaceAvailable, 0] : [0, spaceAvailable]);
}

export function getRangeScale({
  data,
  dataAccessors,
  orientation,
  rangeMax,
  scales,
  height,
  width,
  stacked = false,
}) {
  const vertical = isVertical(orientation);

  const scale = scales && (vertical ? scales.y : scales.x);
  if (scale) {
    return scale.copy();
  }

  /* eslint-disable no-nested-ternary */
  const max = !isUndefined(rangeMax)
    ? rangeMax
    : (
      stacked
      ? computeStackMax(data, dataAccessors.category, dataAccessors.value)
      : computeDataMax(data, dataAccessors.value)
    );
  /* eslint-enable no-nested-ternary */

  return computeRangeScale(max, orientation, vertical ? height : width);
}
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dijit/layout/BorderContainer", "dojo/on",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"../formatter", "../../WorkspaceManager", "dojo/_base/Deferred", "dojo/dom-attr", "dojo/_base/array"
], function(declare, BorderContainer, on,
			domClass, ContentPane, domConstruct,
			formatter, WS, Deferred, domAttr, array){
	return declare([BorderContainer], {
		baseClass: "FileViewer",
		disabled: false,
		containerType: "file",
		filepath: null,
		file: null,

		_setFileAttr: function(val){
			//console.log('[File] _setFileAttr:', val);
			if(!val){
				this.file = {}, this.filepath = "", this.url = "";
				return;
			}
			if(typeof val == "string"){
				this.set("filepath", val);
			}else{
				this.filepath =
					'path' in val.metadata ?
						val.metadata.path +
						((val.metadata.path.charAt(val.metadata.path.length - 1) == "/") ? "" : "/")
					 	+ val.metadata.name : '/'

				this.file = val;
				this.refresh();
			}
		},
		_setFilepathAttr: function(val){
			//console.log('[File] _setFilepathAttr:', val);
			this.filepath = val;
			var _self = this;
			return Deferred.when(WS.getObject(val, true), function(meta){
				_self.file = {metadata: meta}
				_self.refresh();
			});

		},
		startup: function(){
			if(this._started){
				return;
			}
			this.inherited(arguments);
			this.viewHeader = new ContentPane({content: "", region: "top"});
			this.viewer = new ContentPane({region: "center"});
			this.addChild(this.viewHeader);
			this.addChild(this.viewer);
			this.refresh();

			this.on("i:click", function(evt){
				var rel = domAttr.get(evt.target, 'rel');
				if(rel){
					WS.downloadFile(rel);
				}else{
					console.warn("link not found: ", rel);
				}
			});
		},

		formatFileMetaData: function(){
			var output = [];
			var fileMeta = this.file.metadata;
			if(this.file && fileMeta){
				var content = '

' + fileMeta.type + " file: " + fileMeta.name + '
';

				if(WS.downloadTypes.indexOf(fileMeta.type) >= 0){
					content += ' ';
				}

				var formatLabels = formatter.autoLabel("fileView", fileMeta);
				content += formatter.keyValueTable(formatLabels);
				content += "

";
			}

			return content;
		},

		refresh: function(){
			var _self = this;
			if(!this._started){
				return;
			}
			if(!this.file || !this.file.metadata){
				this.viewer.set("content", "
Unable to load file
");
				return;
			}

			//console.log('[File] file:', this.file);
			var viewable = false;
			if(WS.viewableTypes.indexOf(this.file.metadata.type) >= 0){
				viewable = true;
			}
			//console.log('[File] viewable?:', viewable);

			if(!this.file.data && viewable && this.file.metadata.size <= 10000000) {
				// get the object to display
				Deferred.when(WS.getObject(this.filepath, false), function(obj){
					//console.log('[File] obj:', obj);
					_self.set("file", obj);
				});
			}

			if(!this.url && viewable){
				// get the download url
				Deferred.when(WS.getDownloadUrls(this.filepath), function(url){
					//console.log('[File] url:', url);
					_self.set("url", url);
				});
			}

			if(this.file && this.file.metadata){
				if (viewable) {
					//this.viewer.set('content', this.formatFileMetaData() + "
" + this.file.data + "
");
					this.viewer.set('content', this.formatFileMetaData());

					if (this.file.data) {
						var childContent = '
';
						switch(this.file.metadata.type){
							case "html":
								//console.log('[File] type: html');
								childContent = this.file.data;
								break;
							case "json":
							case "diffexp_experiment":
							case "diffexp_expression":
							case "diffexp_mapping":
							case "diffexp_sample":
								//console.log('[File] type: json');
								childContent = '
' + JSON.stringify(JSON.parse(this.file.data || null),null,2)  + "
";
								break;
							case "svg":
							case "gif":
							case "png":
							case "jpg":
							case "txt":
							default:
								//console.log('[File] type: txt/img');
								childContent = '
' + this.file.data + '
';
								break;
						}
						this.viewer.addChild(new ContentPane({content: childContent, region: "center"}));
					}
				} else {
					this.viewer.set('content', this.formatFileMetaData());
				}
			}
		}
	});
});
<commit_msg>added loading message (issue 1618) and cleaned up WS calls<commit_after>define([
	"dojo/_base/declare", "dijit/layout/BorderContainer", "dojo/on",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"../formatter", "../../WorkspaceManager", "dojo/_base/Deferred", "dojo/dom-attr", "dojo/_base/array"
], function(declare, BorderContainer, on,
			domClass, ContentPane, domConstruct,
			formatter, WS, Deferred, domAttr, array){
	return declare([BorderContainer], {
		baseClass: "FileViewer",
		disabled: false,
		containerType: "file",
		file: null,
		viewable: false,
		url: null,

		_setFileAttr: function(val){
			//console.log('[File] _setFileAttr:', val);
			if(!val){
				this.file = {}, this.filepath = "", this.url = "";
				return;
			}
			if(typeof val == "string"){
				this.set("filepath", val);
			}else{
				this.filepath =
					'path' in val.metadata ?
						val.metadata.path +
						((val.metadata.path.charAt(val.metadata.path.length - 1) == "/") ? "" : "/")
					 	+ val.metadata.name : '/'

				this.file = val;
				this.refresh();
			}
		},
		_setFilepathAttr: function(val){
			//console.log('[File] _setFilepathAttr:', val);
			this.filepath = val;
			var _self = this;
			return Deferred.when(WS.getObject(val, true), function(meta){
				_self.file = {metadata: meta}
				_self.refresh();
			});
		},
		startup: function(){
			if(this._started){
				return;
			}
			this.inherited(arguments);
			this.viewHeader = new ContentPane({content: "", region: "top"});
			this.viewer = new ContentPane({region: "center"});
			this.addChild(this.viewHeader);
			this.addChild(this.viewer);

			var _self = this;
			Deferred.when(WS.getDownloadUrls(_self.filepath), function(url){
					_self.url = url;
			});

			if(WS.viewableTypes.indexOf(this.file.metadata.type) >= 0 && this.file.metadata.size <= 10000000){
				this.viewable = true;
			}
			// console.log('[File] viewable?:', this.viewable);

			if(!this.file.data && this.viewable) {
				// get the object to display
				var _self = this;
				Deferred.when(WS.getObject(this.filepath, false), function(obj){
					// console.log('[File] obj:', obj);
					_self.set("file", obj);
				}).then(function(){
					_self.refresh();
				});
			}

			this.refresh();
		},

		formatFileMetaData: function(){
			var output = [];
			var fileMeta = this.file.metadata;
			if(this.file && fileMeta){
				var content = '

' + fileMeta.type + " file: " + fileMeta.name + '
';

				if(WS.downloadTypes.indexOf(fileMeta.type) >= 0){
					content += '';
				}

				var formatLabels = formatter.autoLabel("fileView", fileMeta);
				content += formatter.keyValueTable(formatLabels);
				content += "

";
			}

			return content;
		},

		refresh: function(){
			var _self = this;
			if(!this._started){
				return;
			}
			if(!this.file || !this.file.metadata){
				this.viewer.set("content", "
Unable to load file
");
				return;
			}

			if(this.file && this.file.metadata){
				if (this.viewable) {
					this.viewer.set('content', this.formatFileMetaData());

					if (this.file.data) {
						var childContent = '
';
						switch(this.file.metadata.type){
							case "html":
								// console.log('[File] type: html');
								childContent = this.file.data;
								break;
							case "json":
							case "diffexp_experiment":
							case "diffexp_expression":
							case "diffexp_mapping":
							case "diffexp_sample":
								// console.log('[File] type: json');
								childContent = '
' + JSON.stringify(JSON.parse(this.file.data || null),null,2)  + "
";
								break;
							case "svg":
							case "gif":
							case "png":
							case "jpg":
							case "txt":
							default:
								// console.log('[File] type: txt/img');
								childContent = '
' + this.file.data + '
';
								break;
						}
						this.viewer.addChild(new ContentPane({content: childContent, region: "center"}));
					} else {
						this.viewer.addChild(new ContentPane({content: '
Loading file preview.  Content will appear here when available.  Wait time is usually less than 10 seconds.
', region: "center"}));
					}
				} else {
					this.viewer.set('content', this.formatFileMetaData());
				}
			}
		}
	});
});
<|endoftext|>


<commit_before>/**
* CLASS CONSTRUCTOR
* @PARAM settings
  var settings = {
    minX: -10,
    minY: -10,
    maxX: 10,
    maxY: 10,
    pixelWidth: 500,
    pixelHeight: 500
  }
* USAGE: var inputCanvas = Canvas(inputCanvasSettings);
*/
// import vector.js
// var vector = require('../actors/vector.js');
function Canvas(settings) {
  //input error handling
  this.minX = settings.minX || -10,
  this.minY = settings.minY || -10,
  this.maxX = settings.maxX || 10,
  this.maxY = settings.maxY || 10,
  this.pixelWidth = settings.pixelWidth || 500,
  this.pixelHeight = settings.pixelHeight || 500,
  this.originX = ( this.pixelWidth * (-this.minX)/(this.maxX - this.minX)) || 250,
  this.originY = ( this.pixelHeight * (-this.minY)/(this.maxY - this.minY)) || 250,
  this.origin = {
    x: this.originX,
    y: this.originY
  };
  this.type = settings.type || "not a valid type";
}

Canvas.prototype.drawCanvas = function() {

  var drag = d3.behavior.drag()
              .on("dragstart", function (){
                var d = {
              // id: this.type+"-vector"
                  x: d3.event.sourceEvent.x,
                  y: d3.event.sourceEvent.y
                };
                // in theory this would be Vector.updateInputVector(d);
                updateInputVector(d);
                updateOutputVector(d);
              })
              .on("drag", function(d) {
              var d = {
              // id: this.type+"-vector"
                  x: d3.event.x,
                  y: d3.event.y
                };
                // in theory this would be Vector.updateInputVector(d);
                updateInputVector(d);
                updateOutputVector(d);
              })

  if(this.type) {
    d3.select('#'+this.type+'-canvas').append('svg')
    .attr({
      id: this.type+"-svg",
      width: this.pixelWidth,
      height: this.pixelHeight
    })
    .call(drag)
    // remove this and notify eye of sauron instead
    // updateLog(d) as example
  }
  else {
    console.log("Invalid canvas type: ",this.type)
  }
};

function updateInputVector(d){
// redraw input vector
  d3.select('#input-vector').remove();
  d3.select('#input-svg').append('path')
    .attr({
      "stroke": "red",
      "stroke-width":"4",
      "d": "M 250 250 L"+d.x+" "+d.y+"z",
      "id": 'input-vector'
  });
};

function updateOutputVector(d) {
  var i = applyMatrix(d.x,d.y);
  d3.select('#output-vector').remove();
  d3.select('#output-svg').append('path')
    .attr({
      "stroke": "red",
      "stroke-width":"4",
      //"fill": "/path/to/here",
      "d": "M 250 250 L"+i[0]+" "+i[1]+"z",
      "id": 'output-vector'
  });
};

/**
*
*
*/
Canvas.prototype.checkCollisions = function(oldVector,newVector,targets) {
  var start_x = oldVector.x,
      start_y = oldVector.y,
      end_x = newVector.x,
      end_y = newVector.y,
      results = [];
  for (i = 0; i < targets.length; i++) {
    var tar_x = targets[i].x,
        tar_y = targets[i].y;
    //10 pixels is from Joseph's old settings
    if (isClose(end_x,end_y,tar_x,tar_y,10)) {
      results[i] = true;
    }
    else {
      var param =(tar_x - start_x) * (end_x - start_x) + (tar_y - start_y) * (end_y - start_y);
      var temp = Math.pow((end_x - start_x),2) + Math.pow((end_y - start_y),2);
      param /= temp;
      var dis_x = start_x + param * (end_x - start_x);
      var dis_y = start_y + param * (end_y - start_y);
      //10 pixels is from Joseph's old settings
      if (isClose(dis_x,dis_y,tar_x,tar_y,10)) {
        results[i] = true;
      }
      else {
        results[i] = false;
      }
    }
  }
  return results;
}

Canvas.prototype.isClose = function(oX, oY, tX, tY, radius) {
  var dist = Math.sqrt(Math.pow((tX - oX),2) + Math.pow((tY - oY),2));
  if (dist <= radius) {
    return true;
  }
  return false;
}

Canvas.prototype.proximity = function(outputVector, target) {
    if (isClose(targetX, targetY, 500)) {
      target.updateColor('#e5e5ff', target.id);
    }
    else if (isClose(targetX, targetY, 450)) {
      target.updateColor('#ccccff', target.id);
    }
    else if (isClose(targetX, targetY, 400)) {
      target.updateColor('#b2b2ff', target.id);
    }
    else if (isClose(targetX, targetY, 350)) {
      target.updateColor('#9999ff', target.id);
    }
    else if (isClose(targetX, targetY, 300)) {
      target.updateColor('#7f7fff', target.id);
    }
    else if (isClose(targetX, targetY, 250)) {
      target.updateColor('#6666ff', target.id);
    }
    else if (isClose(targetX, targetY, 200)) {
      target.updateColor('#4c4cff', target.id);
    }
    else if (isClose(targetX, targetY, 150)) {
      target.updateColor('#3232ff', target.id);
    }
    else if (isClose(targetX, targetY, 100)) {
      target.updateColor('#1919ff', target.id);
    }
    else if (isClose(targetX, targetY, 50)) {
      target.updateColor('#0000ff', target.id);
    }
  }

/**
* @PARAM target object as described in target.js
* @RETURNS nothing
*/
Canvas.prototype.drawTarget = function(target) {
  // grab svg container
  d3.select('#'+this.type+'-canvas').append("circle")
    .attr({
      cx: target.x,
      cy: target.y,
      r: target.r,
      color: target.color
    });
};

Canvas.prototype.drawTargets = function(targets) {
  // just a for loop with drawTarget
  for( var i = 0; i < targets.length; i++ ) {
    drawTarget(targets[i]);
  }
};

Canvas.prototype.checkProximity = function(vector, target) {
  return this.isClose(vector.head.x, vector.head.y, target.x, target.y, target.r);
}

function screenToMath(x,y) {
  return [(x - 250) * 10 / 250, - (y - 250) * 10 / 250];
}

function mathToScreen(x,y) {
  return [x * 250 / 10 + 250, - y * 250 / 10 + 250];
}

function applyMatrix(sX,sY,matrix) {
  var matrix = matrix || [[1,3],[2,0]];
  var math_coord = screenToMath(sX,sY),
      applied_coord = [matrix[0][0] * math_coord[0] + matrix[0][1] * math_coord[1], matrix[1][0] * math_coord[0] + matrix[1][1] * math_coord[1]];
  return mathToScreen(applied_coord[0],applied_coord[1]);
}

Canvas.prototype.getRandom = function(min,max) {
  return Math.random() * (max - min) + min;
}

Canvas.prototype.generateTarget = function(matrix) {
  var legal = false,
      par = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
  var newX, newY;

  while (!legal) {
    newX = this.getRandom(0,500);
    newY = this.getRandom(0,500);
    var pre = screenToMath(newX,newY);
    var prex = (matrix[1][1] * pre[0] - matrix[0][1] * pre[1]) / par,
        prey = (- matrix[1][0] * pre[0] + matrix[0][0] * pre[1]) / par;
    pre = mathToScreen(prex,prey);

    if (pre[0] >= 0 && pre[0] <= this.pixelWidth && pre[1] >= 0 && pre[1] <= this.pixelHeight) {
      legal = true;
      var targetSettings = {
      	x: newX,
      	y: newY,
      	r: 20,
      	color: "black",
      	isScore: false
      };
      var newTarget = new Target(targetSettings);
      newTarget.drawTarget();
    }
  }

}
<commit_msg>cleaned vector drag code<commit_after>/**
* CLASS CONSTRUCTOR
* @PARAM settings
  var settings = {
    minX: -10,
    minY: -10,
    maxX: 10,
    maxY: 10,
    pixelWidth: 500,
    pixelHeight: 500
  }
* USAGE: var inputCanvas = Canvas(inputCanvasSettings);
*/
// import vector.js
// var vector = require('../actors/vector.js');
function Canvas(settings) {
  //input error handling
  this.minX = settings.minX || -10,
  this.minY = settings.minY || -10,
  this.maxX = settings.maxX || 10,
  this.maxY = settings.maxY || 10,
  this.pixelWidth = settings.pixelWidth || 500,
  this.pixelHeight = settings.pixelHeight || 500,
  this.originX = ( this.pixelWidth * (-this.minX)/(this.maxX - this.minX)) || 250,
  this.originY = ( this.pixelHeight * (-this.minY)/(this.maxY - this.minY)) || 250,
  this.origin = {
    x: this.originX,
    y: this.originY
  };
  this.type = settings.type || "not a valid type";
}

Canvas.prototype.vectorDrag = function() {
  var drag = d3.behavior.drag()
              .on("dragstart", function (){
                var d = {
              // id: this.type+"-vector"
                  x: d3.event.sourceEvent.x,
                  y: d3.event.sourceEvent.y
                };
                // in theory this would be Vector.updateInputVector(d);
                updateInputVector(d);
                updateOutputVector(d);
              })
              .on("drag", function(d) {
              var d = {
              // id: this.type+"-vector"
                  x: d3.event.x,
                  y: d3.event.y
                };
                // in theory this would be Vector.updateInputVector(d);
                updateInputVector(d);
                updateOutputVector(d);
              });
    return drag;

}

Canvas.prototype.drawCanvas = function() {

  if(this.type) {
    d3.select('#'+this.type+'-canvas').append('svg')
    .attr({
      id: this.type+"-svg",
      width: this.pixelWidth,
      height: this.pixelHeight
    })
    .call(this.vectorDrag())
    // remove this and notify eye of sauron instead
    // updateLog(d) as example
  }
  else {
    console.log("Invalid canvas type: ",this.type)
  }
};

function updateInputVector(d){
// redraw input vector
  d3.select('#input-vector').remove();
  d3.select('#input-svg').append('path')
    .attr({
      "stroke": "red",
      "stroke-width":"4",
      "d": "M 250 250 L"+d.x+" "+d.y+"z",
      "id": 'input-vector'
  });
};

function updateOutputVector(d) {
  var i = applyMatrix(d.x,d.y);
  d3.select('#output-vector').remove();
  d3.select('#output-svg').append('path')
    .attr({
      "stroke": "red",
      "stroke-width":"4",
      //"fill": "/path/to/here",
      "d": "M 250 250 L"+i[0]+" "+i[1]+"z",
      "id": 'output-vector'
  });
};

/**
*
*
*/
Canvas.prototype.checkCollisions = function(oldVector,newVector,targets) {
  var start_x = oldVector.x,
      start_y = oldVector.y,
      end_x = newVector.x,
      end_y = newVector.y,
      results = [];
  for (i = 0; i < targets.length; i++) {
    var tar_x = targets[i].x,
        tar_y = targets[i].y;
    //10 pixels is from Joseph's old settings
    if (isClose(end_x,end_y,tar_x,tar_y,10)) {
      results[i] = true;
    }
    else {
      var param =(tar_x - start_x) * (end_x - start_x) + (tar_y - start_y) * (end_y - start_y);
      var temp = Math.pow((end_x - start_x),2) + Math.pow((end_y - start_y),2);
      param /= temp;
      var dis_x = start_x + param * (end_x - start_x);
      var dis_y = start_y + param * (end_y - start_y);
      //10 pixels is from Joseph's old settings
      if (isClose(dis_x,dis_y,tar_x,tar_y,10)) {
        results[i] = true;
      }
      else {
        results[i] = false;
      }
    }
  }
  return results;
}

Canvas.prototype.isClose = function(oX, oY, tX, tY, radius) {
  var dist = Math.sqrt(Math.pow((tX - oX),2) + Math.pow((tY - oY),2));
  if (dist <= radius) {
    return true;
  }
  return false;
}

Canvas.prototype.proximity = function(outputVector, target) {
    if (isClose(targetX, targetY, 500)) {
      target.updateColor('#e5e5ff', target.id);
    }
    else if (isClose(targetX, targetY, 450)) {
      target.updateColor('#ccccff', target.id);
    }
    else if (isClose(targetX, targetY, 400)) {
      target.updateColor('#b2b2ff', target.id);
    }
    else if (isClose(targetX, targetY, 350)) {
      target.updateColor('#9999ff', target.id);
    }
    else if (isClose(targetX, targetY, 300)) {
      target.updateColor('#7f7fff', target.id);
    }
    else if (isClose(targetX, targetY, 250)) {
      target.updateColor('#6666ff', target.id);
    }
    else if (isClose(targetX, targetY, 200)) {
      target.updateColor('#4c4cff', target.id);
    }
    else if (isClose(targetX, targetY, 150)) {
      target.updateColor('#3232ff', target.id);
    }
    else if (isClose(targetX, targetY, 100)) {
      target.updateColor('#1919ff', target.id);
    }
    else if (isClose(targetX, targetY, 50)) {
      target.updateColor('#0000ff', target.id);
    }
  }

/**
* @PARAM target object as described in target.js
* @RETURNS nothing
*/
Canvas.prototype.drawTarget = function(target) {
  // grab svg container
  d3.select('#'+this.type+'-canvas').append("circle")
    .attr({
      cx: target.x,
      cy: target.y,
      r: target.r,
      color: target.color
    });
};

Canvas.prototype.drawTargets = function(targets) {
  // just a for loop with drawTarget
  for( var i = 0; i < targets.length; i++ ) {
    drawTarget(targets[i]);
  }
};

Canvas.prototype.checkProximity = function(vector, target) {
  return this.isClose(vector.head.x, vector.head.y, target.x, target.y, target.r);
}

function screenToMath(x,y) {
  return [(x - 250) * 10 / 250, - (y - 250) * 10 / 250];
}

function mathToScreen(x,y) {
  return [x * 250 / 10 + 250, - y * 250 / 10 + 250];
}

function applyMatrix(sX,sY,matrix) {
  var matrix = matrix || [[1,3],[2,0]];
  var math_coord = screenToMath(sX,sY),
      applied_coord = [matrix[0][0] * math_coord[0] + matrix[0][1] * math_coord[1], matrix[1][0] * math_coord[0] + matrix[1][1] * math_coord[1]];
  return mathToScreen(applied_coord[0],applied_coord[1]);
}

Canvas.prototype.getRandom = function(min,max) {
  return Math.random() * (max - min) + min;
}

Canvas.prototype.generateTarget = function(matrix) {
  var legal = false,
      par = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
  var newX, newY;

  while (!legal) {
    newX = this.getRandom(0,500);
    newY = this.getRandom(0,500);
    var pre = screenToMath(newX,newY);
    var prex = (matrix[1][1] * pre[0] - matrix[0][1] * pre[1]) / par,
        prey = (- matrix[1][0] * pre[0] + matrix[0][0] * pre[1]) / par;
    pre = mathToScreen(prex,prey);

    if (pre[0] >= 0 && pre[0] <= this.pixelWidth && pre[1] >= 0 && pre[1] <= this.pixelHeight) {
      legal = true;
      var targetSettings = {
      	x: newX,
      	y: newY,
      	r: 20,
      	color: "black",
      	isScore: false
      };
      var newTarget = new Target(targetSettings);
      newTarget.drawTarget();
    }
  }

}
<|endoftext|>


<commit_before>
//  Return the last element of an array
//  >
//  > end([1,2,3,4,5])
//  5
//
function end(x){
  return x[x.length-1] ;
}

function start(x){
  return x[0] ;
}

function logger1(message){
 console.log(message)

}

function logger2(object){
 console.dir(object)
}

function map(fun, x){

  results = []

  for (i = 0; i < x.length; i++) {

    results.push(fun(x[i]));
   }

return results

}// End of MAP

function length(List){
   return List.length
}

function take(n, List){
    return List.slice(0, n)
}

function take_(n){
    function f(List){
        return List.slice(0, n)
    }
    return f
}

function reverse(List){
  return List.reverse()
}

function compose(functions){

   var function2 = functions.reverse() ;
   var N = functions.length ;

   function composed(){

       for (i = 0; i < N; i++) {

        result = result(functions2[i])  ;
       }

      return result ;
    };

    return composed ;
}

//  Equivalent to python dict(zip(['AB', 'CD', 'EF', 'GH'],[1, 2, 3, 4])) in javascript
//  https://gist.github.com/ThomasG77/2186830
//
//  var first = ['AB', 'CD', 'EF', 'GH'];
//  var second = [1, 2, 3, 4];
//  var test = dict_zip(first, second)
//  console.dir(test);
//
// Equivalent to python dict(zip(['AB', 'CD', 'EF', 'GH'],[1, 2, 3, 4])) in javascript
var dict_zip = function (key_array, val_array) {
    if (key_array.length === val_array.length) {
        var obj = {};
        var len = first.length;

        for (var i = 0;i<len;i++) {
            obj[first[i]] = second[i];
        }
    return obj;
    }
}

function range(start, stop, step){
    if (typeof stop=='undefined'){
        // one param defined
        stop = start;
        start = 0;
    };
    if (typeof step=='undefined'){
        step = 1;
    };
    if ((step>0 && start>=stop) || (step<0 && start<=stop)){
        return [];
    };
    var result = [];
    for (var i=start; step>0 ? i<stop : i>stop; i+=step){
        result.push(i);
    };
    return result;
};

//linspace.js Generate linearly spaced vectors
//Helena F. Deus (helenadeus@gmail.com)
//200809
//
//  > linspace(0, 8, 4)
//  [0, 2.6667, 5.3334, 8]
//
function linspace(d1,d2,n) {

        j=0;
        var L = new Array();

        while (j<=(n-1)) {

                var tmp1 = j*(d2-d1)/(Math.floor(n)-1);
                var tmp2 = Math.ceil((d1+tmp1)*10000)/10000;
                L.push(tmp2);
                j=j+1;
        }

        return L;
 }

//  Get the maximum number in a array
//
function max(x) {
    var i;
    var mmax = x[0];

    for (i = 0; i < x.length; i++) {
        if (x[i] > mmax) {
            mmax =x[i];
        }
    }
    return mmax;
}

//  Get the maximum number in a array
//
function min(x) {
    var i;
    var mmin = x[0];

    for (i = 0; i < x.length; i++) {
        if (x[i] < mmin) {
            mmin =x[i];
        }
    }
    return mmin;
}

//
// Javascript Clousure ( Functional Programming)
//
function makepower(power){
  function powerfn(base){
     return Math.pow(base, power) ;
  }
  return powerfn
}

function  get(property){
    function get_property(object){
        return object[property]
    }

    return get_property
}

function pluck(property){

    function get_property(List_of_objects){
        return map(get(property), List_of_objects)
    }

    return get_property
}

function sum(List){

    var S = 0
    for (i = 0; i < List.length; i++) {
       S = S + List[i]
    }
    return S
}

function product(List){

    var S = 1
    for (i = 0; i < List.length; i++) {
       S = S*List[i]
    }
    return S
}

function fibonacci(n) {
   if (n < 2){
     return 1;
   }else{
     return fibonacci(n-2) + fibonacci(n-1);
   }
}

function redirect_url(url){
    window.location.replace(url);
}

function reload_page(){
    window.location.reload()
}

function open_window(url){
    window.open(url , '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes')
}

//   Create Version of a function
//   ( a function that accepts an array instead
//     of a single argument)
//
//   Example:
//   > sqrt = vectorize(Math.sqrt)
//   > sqrt([1, 2, 3])
//     [1, 1.4142135623730951, 1.7320508075688772]
//
function vectorize(fun){
  function fun_vectorized(x){
    return map(fun, x)
  }

  return fun_vectorized
}

// PAR
function even(n){
   return n % 2 == 0
}

// IMPAR
function odd(n){
   return n % 2 == 1
}

//
//
//  zip([1,2, 3], [33, 55, 44], range(10))
//  [[1, 33, 0], [2, 55, 1], [3, 44, 2]]
//
function zip(){

  N = min(map(length, arguments))

  //logger1(N)
   //takeN = take_(N)

  var List2 = []

  for (var i = 0; i < N; i++) {

      var Listrow = []

      for (var j = 0; j < length(arguments); j++) {

       Listrow.push(arguments[j][i])

  //# alert(arguments[i]);
       }

      //logger1(Listrow)
      List2.push(Listrow)
  //# alert(arguments[i]);
  }

  return List2
}

// Create dynamic popup window
//
function popup_window(content){
  var w = window.open('', '', 'width=400,height=400,resizeable,scrollbars');
  w.document.write(content);
  w.document.close(); // needed for chrome and safari
  return w
}

function str(object){
    return object.toString()
}

// var str = "My Name is %NAME% and my age is %AGE%.";
// var replaceData = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
// var output = substitute(str, replaceData);
// console.log(output)
function format(str, data) {
    var output = str.replace(/%[^%]+%/g, function(match) {
        if (match in data) {
            return(data[match]);
        } else {
            return("");
        }
    });
    return(output);
}

function image_template(image_src, alt="", height=500, width=500){

      //var template = ''
      //return format(template)

      var template = ''
      return format(template, {"%SRC%" : image_src, "%ALT%" : alt, "%W%" : width, "%H%" : height});
}

// Open a new Window in the Slideshare website with
// all slides images.
//////////////////////////////
function scrape_slideshare(){

    elements = document.getElementsByClassName("slide_image")
    urls = pluck("full")(pluck("dataset")(elements))
    codelst = map(image_template, urls)
    code = codelst.join("\n
")
    return popup_window(code)

}

//
//
function find_class(classname){

    return document.getElementsByClassName(classname)
}

function scrape_slideshare2(){

    elements = document.getElementsByClassName("slide_image")
    urls = pluck("full")(pluck("dataset")(elements))
    codelst = map(image_template, urls)
    code = codelst.join("\n
")
    document.write(code)

}

//-----------------------------------//
//  Eval an base64 encoded string    //
//
// Example: evalb64("YWxlcnQoJ2xvcmVtIGlwc3VtJyk=")
// will run alert  alert('lorem ipsum')!
//
function evalb64(b64string){
    eval(atob(b64string))
}

function injectscript(script_url){
    document.body.appendChild(document.createElement('script')).src= script_url
}

function inject_jquery(){
    injectscript("http://code.jquery.com/jquery-1.7.2.min.js")
}
inject_jquery()

sin = vectorize(Math.sin)
cos = vectorize(Math.cos)
exp = vectorize(Math.exp)

people = [{ 'name': 'moe', 'age': 40}, {'name': 'larry', 'age': 50}, {'name': 'curly', 'age': 60}]

//  // Encode the String
// var encodedString = Base64.encode(string);
// console.log(encodedString); // Outputs: "YWxlcnQoJ2hlbGxvIHdvcmxkJykgOyA="
//
// Decode the String
//
// var decodedString = Base64.decode(encodedString);
// console.log(decodedString); // Outputs: "Hello World!"
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Dynamically removing an external JavaScript or CSS file
// removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page
// removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page
//
// http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
//
//
function removejs(filename, filetype="js"){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
   allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
 }
}

function user_guide(){
    console.log("Functional.js - A functional programming Library for Javascript ")

    console.log("Higher Order functions ")
    console.log("map(func, list), filter(func, list), zip(*list), compose(func1, func2) ")
    console.log("")
    console.log("List Manipulation Utilities")
    console.log("")
    console.log("reverse(list), sort(list), max(list), sum(list), product(list),")
}
<commit_msg>upload updated added remove_alljs<commit_after>
//  Return the last element of an array
//  >
//  > end([1,2,3,4,5])
//  5
//
function end(x){
  return x[x.length-1] ;
}

function start(x){
  return x[0] ;
}

function logger1(message){
 console.log(message)

}

function logger2(object){
 console.dir(object)
}

function map(fun, x){

  results = []

  for (i = 0; i < x.length; i++) {

    results.push(fun(x[i]));
   }

return results

}// End of MAP

function length(List){
   return List.length
}

function take(n, List){
    return List.slice(0, n)
}

function take_(n){
    function f(List){
        return List.slice(0, n)
    }
    return f
}

function reverse(List){
  return List.reverse()
}

function compose(functions){

   var function2 = functions.reverse() ;
   var N = functions.length ;

   function composed(){

       for (i = 0; i < N; i++) {

        result = result(functions2[i])  ;
       }

      return result ;
    };

    return composed ;
}

//  Equivalent to python dict(zip(['AB', 'CD', 'EF', 'GH'],[1, 2, 3, 4])) in javascript
//  https://gist.github.com/ThomasG77/2186830
//
//  var first = ['AB', 'CD', 'EF', 'GH'];
//  var second = [1, 2, 3, 4];
//  var test = dict_zip(first, second)
//  console.dir(test);
//
// Equivalent to python dict(zip(['AB', 'CD', 'EF', 'GH'],[1, 2, 3, 4])) in javascript
var dict_zip = function (key_array, val_array) {
    if (key_array.length === val_array.length) {
        var obj = {};
        var len = first.length;

        for (var i = 0;i<len;i++) {
            obj[first[i]] = second[i];
        }
    return obj;
    }
}

function range(start, stop, step){
    if (typeof stop=='undefined'){
        // one param defined
        stop = start;
        start = 0;
    };
    if (typeof step=='undefined'){
        step = 1;
    };
    if ((step>0 && start>=stop) || (step<0 && start<=stop)){
        return [];
    };
    var result = [];
    for (var i=start; step>0 ? i<stop : i>stop; i+=step){
        result.push(i);
    };
    return result;
};

//linspace.js Generate linearly spaced vectors
//Helena F. Deus (helenadeus@gmail.com)
//200809
//
//  > linspace(0, 8, 4)
//  [0, 2.6667, 5.3334, 8]
//
function linspace(d1,d2,n) {

        j=0;
        var L = new Array();

        while (j<=(n-1)) {

                var tmp1 = j*(d2-d1)/(Math.floor(n)-1);
                var tmp2 = Math.ceil((d1+tmp1)*10000)/10000;
                L.push(tmp2);
                j=j+1;
        }

        return L;
 }

//  Get the maximum number in a array
//
function max(x) {
    var i;
    var mmax = x[0];

    for (i = 0; i < x.length; i++) {
        if (x[i] > mmax) {
            mmax =x[i];
        }
    }
    return mmax;
}

//  Get the maximum number in a array
//
function min(x) {
    var i;
    var mmin = x[0];

    for (i = 0; i < x.length; i++) {
        if (x[i] < mmin) {
            mmin =x[i];
        }
    }
    return mmin;
}

//
// Javascript Clousure ( Functional Programming)
//
function makepower(power){
  function powerfn(base){
     return Math.pow(base, power) ;
  }
  return powerfn
}

function  get(property){
    function get_property(object){
        return object[property]
    }

    return get_property
}

function pluck(property){

    function get_property(List_of_objects){
        return map(get(property), List_of_objects)
    }

    return get_property
}

function sum(List){

    var S = 0
    for (i = 0; i < List.length; i++) {
       S = S + List[i]
    }
    return S
}

function product(List){

    var S = 1
    for (i = 0; i < List.length; i++) {
       S = S*List[i]
    }
    return S
}

function fibonacci(n) {
   if (n < 2){
     return 1;
   }else{
     return fibonacci(n-2) + fibonacci(n-1);
   }
}

function redirect_url(url){
    window.location.replace(url);
}

function reload_page(){
    window.location.reload()
}

function open_window(url){
    window.open(url , '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes')
}

//   Create Version of a function
//   ( a function that accepts an array instead
//     of a single argument)
//
//   Example:
//   > sqrt = vectorize(Math.sqrt)
//   > sqrt([1, 2, 3])
//     [1, 1.4142135623730951, 1.7320508075688772]
//
function vectorize(fun){
  function fun_vectorized(x){
    return map(fun, x)
  }

  return fun_vectorized
}

// PAR
function even(n){
   return n % 2 == 0
}

// IMPAR
function odd(n){
   return n % 2 == 1
}

//
//
//  zip([1,2, 3], [33, 55, 44], range(10))
//  [[1, 33, 0], [2, 55, 1], [3, 44, 2]]
//
function zip(){

  N = min(map(length, arguments))

  //logger1(N)
   //takeN = take_(N)

  var List2 = []

  for (var i = 0; i < N; i++) {

      var Listrow = []

      for (var j = 0; j < length(arguments); j++) {

       Listrow.push(arguments[j][i])

  //# alert(arguments[i]);
       }

      //logger1(Listrow)
      List2.push(Listrow)
  //# alert(arguments[i]);
  }

  return List2
}

// Create dynamic popup window
//
function popup_window(content){
  var w = window.open('', '', 'width=400,height=400,resizeable,scrollbars');
  w.document.write(content);
  w.document.close(); // needed for chrome and safari
  return w
}

function str(object){
    return object.toString()
}

// var str = "My Name is %NAME% and my age is %AGE%.";
// var replaceData = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
// var output = substitute(str, replaceData);
// console.log(output)
function format(str, data) {
    var output = str.replace(/%[^%]+%/g, function(match) {
        if (match in data) {
            return(data[match]);
        } else {
            return("");
        }
    });
    return(output);
}

function image_template(image_src, alt="", height=500, width=500){

      //var template = ''
      //return format(template)

      var template = ''
      return format(template, {"%SRC%" : image_src, "%ALT%" : alt, "%W%" : width, "%H%" : height});
}

// Open a new Window in the Slideshare website with
// all slides images.
//////////////////////////////
function scrape_slideshare(){

    elements = document.getElementsByClassName("slide_image")
    urls = pluck("full")(pluck("dataset")(elements))
    codelst = map(image_template, urls)
    code = codelst.join("\n
")
    return popup_window(code)

}

//
//
function find_class(classname){

    return document.getElementsByClassName(classname)
}

function scrape_slideshare2(){

    elements = document.getElementsByClassName("slide_image")
    urls = pluck("full")(pluck("dataset")(elements))
    codelst = map(image_template, urls)
    code = codelst.join("\n
")
    document.write(code)

}

//-----------------------------------//
//  Eval an base64 encoded string    //
//
// Example: evalb64("YWxlcnQoJ2xvcmVtIGlwc3VtJyk=")
// will run alert  alert('lorem ipsum')!
//
function evalb64(b64string){
    eval(atob(b64string))
}

function injectscript(script_url){
    document.body.appendChild(document.createElement('script')).src= script_url
}

function inject_jquery(){
    injectscript("http://code.jquery.com/jquery-1.7.2.min.js")
}
inject_jquery()

sin = vectorize(Math.sin)
cos = vectorize(Math.cos)
exp = vectorize(Math.exp)

people = [{ 'name': 'moe', 'age': 40}, {'name': 'larry', 'age': 50}, {'name': 'curly', 'age': 60}]

//  // Encode the String
// var encodedString = Base64.encode(string);
// console.log(encodedString); // Outputs: "YWxlcnQoJ2hlbGxvIHdvcmxkJykgOyA="
//
// Decode the String
//
// var decodedString = Base64.decode(encodedString);
// console.log(decodedString); // Outputs: "Hello World!"
// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Dynamically removing an external JavaScript or CSS file
// removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page
// removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page
//
// http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
//
//
function removejs(filename, filetype="js"){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
   allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
 }
}https://raw.githubusercontent.com/wolfprogrammer/javascript/master/functional.js

function remove_alljs(){
        var url = ""
        map(removejs ,pluck("src")(document.scripts))
        document.body.appendChild(document.createElement('script')).src = "https://raw.githubusercontent.com/wolfprogrammer/javascript/master/functional.js"

}

function user_guide(){
    console.log("Functional.js - A functional programming Library for Javascript ")

    console.log("Higher Order functions ")
    console.log("map(func, list), filter(func, list), zip(*list), compose(func1, func2) ")
    console.log("")
    console.log("List Manipulation Utilities")
    console.log("")
    console.log("reverse(list), sort(list), max(list), sum(list), product(list),")
}
<|endoftext|>


<commit_before>/**
 * Kebab Application FeedbackForm
 *
 * @category    Kebab (kebab-reloaded)
 * @package     Applications
 * @namespace   KebabOS.applications.feedback.application.views
 * @author      Yunus ÖZCAN <yunus.ozcan@lab2023.com>
 * @copyright   Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. (http://www.lab2023.com)
 * @license     http://www.kebab-project.com/licensing
 */
KebabOS.applications.feedback.application.views.FeedbackForm = Ext.extend(Ext.form.FormPanel, {

    // Application bootstrap
    bootstrap: null,
    //POST url
    url : BASE_URL + '/feedback/feedback',

    bodyStyle: 'padding:5px 10px;',

    initComponent: function() {

        var userId = this.bootstrap.app.getUser().id;

        var applications = this.bootstrap.app.getApplications();

        var applicationsCombobox = new Ext.form.ComboBox({
            fieldLabel: 'Application name',
            typeAhead: true,
            triggerAction: 'all',
            forceSelection: true,
            lazyRender:false,
            mode: 'local',
            store: new Ext.data.JsonStore({
                fields: ['name', 'id',{name:'title', type: 'object', mapping: 'launcher.text'}],
                data: applications
            }),
            valueField: 'id',
            displayField: 'title',
            hiddenName: 'applicationIdentity',
            scope:this
        });

        // form config
        var config = {

            items: [
                {
                    xtype:'panel',
                    layout: 'form',
                    border:false,
                    labelAlign: 'top',
                    defaults: {
                        anchor: '100%'
                    },
                    items: [
                        {
                            name:'userId',
                            xtype:'hidden',
                            value: userId
                        },
                        applicationsCombobox ,
                        {
                            fieldLabel: 'Description',
                            name: 'description',
                            xtype: 'textarea',
                            height:235
                        }
                    ]
                }
            ],
            buttons: [
                {
                    text: 'Send',
                    iconCls: 'icon-email',
                    scope: this,
                    handler : this.onSave
                }
            ]

        }

        Ext.apply(this, Ext.apply(this.initialConfig, config));

        this.addEvents('loadGrid');

        KebabOS.applications.feedback.application.views.FeedbackForm.superclass.initComponent.apply(this, arguments);
    },

    onSave: function() {

        if (this.getForm().isValid()) {

            var notification = new Kebab.OS.Notification();

            this.getForm().submit({

                url: this.url,

                method: 'POST',

                //waitMsg: 'Updating...',

                success : function() {
                    notification.message(this.bootstrap.launcher.text, 'Success');
                },

                failure : function() {
                    notification.message(this.bootstrap.launcher.text, 'Failure');
                },

                scope:this
            });
        }
    }

});
<commit_msg>Fixed Feedback<commit_after>/**
 * Kebab Application FeedbackForm
 *
 * @category    Kebab (kebab-reloaded)
 * @package     Applications
 * @namespace   KebabOS.applications.feedback.application.views
 * @author      Yunus ÖZCAN <yunus.ozcan@lab2023.com>
 * @copyright   Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. (http://www.lab2023.com)
 * @license     http://www.kebab-project.com/licensing
 */
KebabOS.applications.feedback.application.views.FeedbackForm = Ext.extend(Ext.form.FormPanel, {

    // Application bootstrap
    bootstrap: null,
    //POST url
    url : BASE_URL + '/feedback/feedback',

    bodyStyle: 'padding:5px 10px;',

    initComponent: function() {

        var userId = this.bootstrap.app.getUser().id;

        var applications = this.bootstrap.app.getApplications();

        var applicationsCombobox = new Ext.form.ComboBox({
            fieldLabel: 'Application name',
            typeAhead: true,
            triggerAction: 'all',
            forceSelection: true,
            lazyRender:false,
            mode: 'local',
            store: new Ext.data.JsonStore({
                fields: ['name', 'id',{name:'title', type: 'object', mapping: 'launcher.text'}],
                data: applications
            }),
            valueField: 'id',
            displayField: 'title',
            hiddenName: 'applicationIdentity',
            scope:this
        });

        // form config
        var config = {

            items: [
                {
                    xtype:'panel',
                    layout: 'form',
                    border:false,
                    labelAlign: 'top',
                    defaults: {
                        anchor: '100%'
                    },
                    items: [
                        {
                            name:'userId',
                            xtype:'hidden',
                            value: userId
                        },
                        applicationsCombobox ,
                        {
                            fieldLabel: 'Description',
                            name: 'description',
                            xtype: 'textarea',
                            height:235
                        }
                    ]
                }
            ],
            buttons: [
                {
                    text: 'Send',
                    iconCls: 'icon-email',
                    scope: this,
                    handler : this.onSave
                }
            ]

        }

        Ext.apply(this, Ext.apply(this.initialConfig, config));

        KebabOS.applications.feedback.application.views.FeedbackForm.superclass.initComponent.apply(this, arguments);
    },

    onSave: function() {

        if (this.getForm().isValid()) {

            var notification = new Kebab.OS.Notification();

            this.getForm().submit({

                url: this.url,

                method: 'POST',

                //waitMsg: 'Updating...',

                success : function() {
                    notification.message(this.bootstrap.launcher.text, 'Success');
                    this.fireEvent('loadGrid');
                    this.getForm().reset();
                },

                failure : function() {
                    notification.message(this.bootstrap.launcher.text, 'Failure');
                },

                scope:this
            });
        }
    }

});
<|endoftext|>


<commit_before>/**
 * Created by quasarchimaere on 25.03.2019.
 */

import angular from "angular";
import inviewModule from "angular-inview";
import labelledHrModule from "./labelled-hr.js";
import postHeaderModule from "./post-header.js";
import suggestPostPickerModule from "./details/picker/suggestpost-picker.js";
import { attach, getIn, get } from "../utils.js";
import won from "../won-es6.js";
import { connect2Redux } from "../won-utils.js";
import * as needUtils from "../need-utils.js";
import * as connectionSelectors from "../selectors/connection-selectors.js";
import { actionCreators } from "../actions/actions.js";
import ngAnimate from "angular-animate";

import "style/_post-content-participants.scss";

const CONNECTION_READ_TIMEOUT = 1500;

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

          <won-post-header
            class="clickable"
            ng-click="self.router__stateGoCurrent({viewNeedUri: memberUri, viewConnUri: undefined})"
            need-uri="::memberUri">
          </won-post-header>

          <won-post-header
            class="clickable"
            ng-click="self.router__stateGoCurrent({viewNeedUri: conn.get('remoteNeedUri'), viewConnUri: undefined})"
            need-uri="::conn.get('remoteNeedUri')">
          </won-post-header>

                  Accept

                  Reject

                  Request

                  Waiting for Accept...

                  Remove

          No Groupmembers present.

      <won-labelled-hr label="::'Invite'" class="pc-participants__labelledhr" ng-if="self.isOwned"></won-labelled-hr>
      <won-suggestpost-picker
          ng-if="self.isOwned"
          initial-value="undefined"
          on-update="self.inviteParticipant(value)"
          detail="::{placeholder: 'Insert NeedUri to invite'}"
          excluded-uris="self.excludedFromInviteUris"
          allowed-facets="::[self.won.WON.ChatFacetCompacted, self.won.WON.GroupFacetCompacted]"
          excluded-text="::'Invitation does not work for needs that are already part of the Group, or the group itself'"
          not-allowed-facet-text="::'Invitation does not work on needs without Group or Chat Facet'"
          no-suggestions-text="::'No Participants available to invite'"
      ></won-suggestpost-picker>
    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      this.won = won;
      window.postcontentparticipants4dbg = this;

      const selectFromState = state => {
        const post = getIn(state, ["needs", this.postUri]);
        const isOwned = needUtils.isOwned(post);

        const hasGroupFacet = needUtils.hasGroupFacet(post);

        const groupMembers = hasGroupFacet && get(post, "groupMembers");
        const groupChatConnections =
          isOwned &&
          hasGroupFacet &&
          connectionSelectors.getGroupChatConnectionsByNeedUri(
            state,
            this.postUri
          );

        let excludedFromInviteUris = [this.postUri];

        if (groupChatConnections) {
          groupChatConnections.map(conn =>
            excludedFromInviteUris.push(get(conn, "remoteNeedUri"))
          );
        }

        return {
          post,
          isOwned,
          hasGroupFacet,
          hasGroupMembers: groupMembers && groupMembers.size > 0,
          hasGroupChatConnections:
            groupChatConnections && groupChatConnections.size > 0,
          groupChatConnectionsArray:
            groupChatConnections && groupChatConnections.toArray(),
          excludedFromInviteUris: [this.postUri],
          groupMembersArray: groupMembers && groupMembers.toArray(),
        };
      };
      connect2Redux(selectFromState, actionCreators, ["self.postUri"], this);
    }

    closeConnection(conn, rateBad = false) {
      if (!conn) {
        return;
      }

      const connUri = conn.get("uri");

      if (rateBad) {
        this.connections__rate(connUri, won.WON.binaryRatingBad);
      }

      if (conn.get("unread")) {
        this.connections__markAsRead({
          connectionUri: connUri,
          needUri: this.postUri,
        });
      }

      this.connections__close(connUri);
    }

    openRequest(conn, message = "") {
      if (!conn) {
        return;
      }

      const connUri = get(conn, "uri");

      if (conn.get("unread")) {
        this.connections__markAsRead({
          connectionUri: connUri,
          needUri: this.postUri,
        });
      }

      this.connections__open(connUri, message);
    }

    sendRequest(conn, message = "") {
      if (!conn) {
        return;
      }

      const connUri = get(conn, "uri");
      const remoteNeedUri = get(conn, "remoteNeedUri");

      if (conn.get("unread")) {
        this.connections__markAsRead({
          connectionUri: connUri,
          needUri: this.postUri,
        });
      }

      this.connections__rate(connUri, won.WON.binaryRatingGood);
      this.needs__connect(this.postUri, connUri, remoteNeedUri, message);
    }

    inviteParticipant(needUri, message = "") {
      if (!this.isOwned || !this.hasGroupFacet) {
        console.warn("Trying to invite to a non-owned or non groupFacet need");
        return;
      }
      this.needs__connect(this.postUri, undefined, needUri, message);
    }

    markAsRead(conn) {
      if (conn && conn.get("unread")) {
        const payload = {
          connectionUri: conn.get("uri"),
          needUri: this.postUri,
        };

        const tmp_connections__markAsRead = this.connections__markAsRead;

        setTimeout(function() {
          tmp_connections__markAsRead(payload);
        }, CONNECTION_READ_TIMEOUT);
      }
    }
  }

  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    template: template,
    scope: {
      postUri: "=",
    },
  };
}

export default angular
  .module("won.owner.components.postContentParticipants", [
    ngAnimate,
    labelledHrModule,
    postHeaderModule,
    suggestPostPickerModule,
    inviewModule.name,
  ])
  .directive("wonPostContentParticipants", genComponentConf).name;
<commit_msg>Updates exclude list accordingly<commit_after>/**
 * Created by quasarchimaere on 25.03.2019.
 */

import angular from "angular";
import inviewModule from "angular-inview";
import labelledHrModule from "./labelled-hr.js";
import postHeaderModule from "./post-header.js";
import suggestPostPickerModule from "./details/picker/suggestpost-picker.js";
import { attach, getIn, get } from "../utils.js";
import won from "../won-es6.js";
import { connect2Redux } from "../won-utils.js";
import * as needUtils from "../need-utils.js";
import * as connectionSelectors from "../selectors/connection-selectors.js";
import { actionCreators } from "../actions/actions.js";
import ngAnimate from "angular-animate";

import "style/_post-content-participants.scss";

const CONNECTION_READ_TIMEOUT = 1500;

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

          <won-post-header
            class="clickable"
            ng-click="self.router__stateGoCurrent({viewNeedUri: memberUri, viewConnUri: undefined})"
            need-uri="::memberUri">
          </won-post-header>

          <won-post-header
            class="clickable"
            ng-click="self.router__stateGoCurrent({viewNeedUri: conn.get('remoteNeedUri'), viewConnUri: undefined})"
            need-uri="::conn.get('remoteNeedUri')">
          </won-post-header>

                  Accept

                  Reject

                  Request

                  Waiting for Accept...

                  Remove

          No Groupmembers present.

      <won-labelled-hr label="::'Invite'" class="pc-participants__labelledhr" ng-if="self.isOwned"></won-labelled-hr>
      <won-suggestpost-picker
          ng-if="self.isOwned"
          initial-value="undefined"
          on-update="self.inviteParticipant(value)"
          detail="::{placeholder: 'Insert NeedUri to invite'}"
          excluded-uris="self.excludedFromInviteUris"
          allowed-facets="::[self.won.WON.ChatFacetCompacted, self.won.WON.GroupFacetCompacted]"
          excluded-text="::'Invitation does not work for needs that are already part of the Group, or the group itself'"
          not-allowed-facet-text="::'Invitation does not work on needs without Group or Chat Facet'"
          no-suggestions-text="::'No Participants available to invite'"
      ></won-suggestpost-picker>
    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      this.won = won;
      window.postcontentparticipants4dbg = this;

      const selectFromState = state => {
        const post = getIn(state, ["needs", this.postUri]);
        const isOwned = needUtils.isOwned(post);

        const hasGroupFacet = needUtils.hasGroupFacet(post);

        const groupMembers = hasGroupFacet && get(post, "groupMembers");
        const groupChatConnections =
          isOwned &&
          hasGroupFacet &&
          connectionSelectors.getGroupChatConnectionsByNeedUri(
            state,
            this.postUri
          );

        let excludedFromInviteUris = [this.postUri];

        if (groupChatConnections) {
          groupChatConnections.map(conn =>
            excludedFromInviteUris.push(get(conn, "remoteNeedUri"))
          );
        }

        return {
          post,
          isOwned,
          hasGroupFacet,
          hasGroupMembers: groupMembers && groupMembers.size > 0,
          hasGroupChatConnections:
            groupChatConnections && groupChatConnections.size > 0,
          groupChatConnectionsArray:
            groupChatConnections && groupChatConnections.toArray(),
          excludedFromInviteUris,
          groupMembersArray: groupMembers && groupMembers.toArray(),
        };
      };
      connect2Redux(selectFromState, actionCreators, ["self.postUri"], this);
    }

    closeConnection(conn, rateBad = false) {
      if (!conn) {
        return;
      }

      const connUri = conn.get("uri");

      if (rateBad) {
        this.connections__rate(connUri, won.WON.binaryRatingBad);
      }

      if (conn.get("unread")) {
        this.connections__markAsRead({
          connectionUri: connUri,
          needUri: this.postUri,
        });
      }

      this.connections__close(connUri);
    }

    openRequest(conn, message = "") {
      if (!conn) {
        return;
      }

      const connUri = get(conn, "uri");

      if (conn.get("unread")) {
        this.connections__markAsRead({
          connectionUri: connUri,
          needUri: this.postUri,
        });
      }

      this.connections__open(connUri, message);
    }

    sendRequest(conn, message = "") {
      if (!conn) {
        return;
      }

      const connUri = get(conn, "uri");
      const remoteNeedUri = get(conn, "remoteNeedUri");

      if (conn.get("unread")) {
        this.connections__markAsRead({
          connectionUri: connUri,
          needUri: this.postUri,
        });
      }

      this.connections__rate(connUri, won.WON.binaryRatingGood);
      this.needs__connect(this.postUri, connUri, remoteNeedUri, message);
    }

    inviteParticipant(needUri, message = "") {
      if (!this.isOwned || !this.hasGroupFacet) {
        console.warn("Trying to invite to a non-owned or non groupFacet need");
        return;
      }
      this.needs__connect(this.postUri, undefined, needUri, message);
    }

    markAsRead(conn) {
      if (conn && conn.get("unread")) {
        const payload = {
          connectionUri: conn.get("uri"),
          needUri: this.postUri,
        };

        const tmp_connections__markAsRead = this.connections__markAsRead;

        setTimeout(function() {
          tmp_connections__markAsRead(payload);
        }, CONNECTION_READ_TIMEOUT);
      }
    }
  }

  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    template: template,
    scope: {
      postUri: "=",
    },
  };
}

export default angular
  .module("won.owner.components.postContentParticipants", [
    ngAnimate,
    labelledHrModule,
    postHeaderModule,
    suggestPostPickerModule,
    inviewModule.name,
  ])
  .directive("wonPostContentParticipants", genComponentConf).name;
<|endoftext|>


<commit_before>/**
 * Created by Jackey Li on 15/9/22.
 */
(function (angular) {
    'use strict';

    var moduleName = 'piggyBank.account';

    /**
     *
     */
    angular.module(moduleName, [])
        .config(function ($stateProvider) {
            $stateProvider
                .state('desktop.account', {
                    url: '/account',
                    views: {
                        'desktop-account': {
                            templateUrl: 'chats/templates/account.html',
                            controller: 'ChatsCtrl'
                        }
                    }
                })
                .state('desktop.account-detail', {
                    url: '/account/:chatId',
                    views: {
                        'desktop-account': {
                            templateUrl: function(){
                                return  'chats/templates/account-detail.html'
                            },

                            controller: 'ChatDetailCtrl'
                        }
                    }
                });
        });
})(angular);<commit_msg>use templateUrl<commit_after>/**
 * Created by Jackey Li on 15/9/22.
 */
(function (angular) {
    'use strict';

    var moduleName = 'piggyBank.account';

    /**
     *
     */
    angular.module(moduleName, [])
        .config(function ($stateProvider) {
            $stateProvider
                .state('desktop.account', {
                    url: '/account',
                    views: {
                        'desktop-account': {
                            templateUrl: function () {
                                return 'chats/templates/account.html'
                            },
                            controller: 'ChatsCtrl'
                        }
                    }
                })
                .state('desktop.account-detail', {
                    url: '/account/:chatId',
                    views: {
                        'desktop-account': {
                            templateUrl: function () {
                                return 'chats/templates/account-detail.html'
                            },
                            controller: 'ChatDetailCtrl'
                        }
                    }
                });
        });
})(angular);<|endoftext|>


<commit_before>import useScales from '../useScales';
import ChartData from '../chartdata/ChartData';
const columns = [
    {key: 'foo'},
    {key: 'bar'},
    {key: 'baz'},
    {key: 'qux'}
];

const rows = [
    {foo: 1, bar: 4, baz: 'a', qux: new Date('1970-01-01')},
    {foo: 2, bar: 5, baz: 'b', qux: new Date('1970-01-02')},
    {foo: 3, bar: 6, baz: 'c', qux: new Date('1970-01-03')},
    {foo: 4, bar: 7, baz: 'c', qux: new Date('1970-01-03')}
];

const data = new ChartData(rows, columns);

test('useScales will scale data', () => {
    const [x, y] = useScales([
        {columns: ['foo'], upperBound: 100},
        {columns: ['bar'], upperBound: 100}
    ])(data);

    expect(x.scaledData).toEqual([[25], [50], [75], [100]]);
    expect(y.scaledData).toBe(0);
});
<commit_msg>test: useScales<commit_after>import useScales from '../useScales';
import ChartData from '../chartdata/ChartData';
const columns = [
    {key: 'foo'},
    {key: 'bar'},
    {key: 'baz'},
    {key: 'qux'}
];

const rows = [
    {foo: 1, bar: 4, baz: 'a', qux: new Date('1970-01-01')},
    {foo: 2, bar: 5, baz: 'b', qux: new Date('1970-01-02')},
    {foo: 3, bar: 6, baz: 'c', qux: new Date('1970-01-03')},
    {foo: 4, bar: 7, baz: 'c', qux: new Date('1970-01-03')}
];

const data = new ChartData(rows, columns);

describe('useScales', () => {
    it('can create many dimensions', () => {
        const dimensions = useScales([
            {columns: ['foo'], range: [0, 100]},
            {columns: ['bar'], range: [0, 100]},
        ])(data);

        expect(dimensions.length).toBe(2);
    });

    it('can scale one column', () => {
        const [foo] = useScales([
            {columns: ['foo'], range: [0, 100]},
        ])(data);

        expect(foo.scaledData).toEqual([[[25], [50], [75], [100]]]);
    });

    it('can scale multiple columns', () => {
        const [foo] = useScales([
            {columns: ['foo', 'bar'], range: [0, 14]},
        ])(data);

        expect(foo.scaledData).toEqual([
            [[2],[4],[6],[8]],
            [[8],[10],[12],[14]]
        ]);
    });

    it('will ignore nulls', () => {
            const rows = [
                {foo: 1, bar: 1},
                {foo: null, bar: null},
                {foo: 3, bar: 3}
            ];

            const data = new ChartData(rows, columns);
            const [foo] = useScales([
                {columns: ['foo', 'bar'], range: [0, 6]},
            ])(data);

            expect(foo.scaledData).toEqual([
                [[2], [null], [6]],
                [[2], [null], [6]]
            ]);
    });

    it('should throw if you try and stack non-numerical data', () => {
        const badRequest = () => useScales([
            {columns: ['qux', 'qux'], range: [0, 1], stack: true}
        ])(data);

        expect(badRequest).toThrow();
    });
});

describe('stacking', () => {
    it('can stack multiple columns', () => {
            const rows = [
                {foo: 1, bar: 1},
                {foo: 2, bar: 2},
                {foo: 3, bar: 3}
            ];

            const data = new ChartData(rows, columns);
            const [foo] = useScales([
                {columns: ['foo', 'bar'], range: [0, 6], stack: true},
            ])(data);

            expect(foo.scaledData).toEqual([
                [[0, 1], [0, 2], [0, 3]],
                [[1, 2], [2, 4], [3, 6]]
            ]);
    });

    it('will ignore nulls', () => {
            const rows = [
                {foo: 1, bar: 1},
                {foo: null, bar: null},
                {foo: 3, bar: 3}
            ];

            const data = new ChartData(rows, columns);
            const [foo] = useScales([
                {columns: ['foo', 'bar'], range: [0, 6], stack: true},
            ])(data);

            expect(foo.scaledData).toEqual([
                [[0, 1], [null, null], [0, 3]],
                [[1, 2], [null, null], [3, 6]]
            ]);
    });
});
<|endoftext|>