<commit_before>var LEFT = 37;
var UP = 38;
var RIGHT = 39;
var DOWN = 40;

// Elements should be a jQuery set of input elements which should be turned
// into tree selectors. The data should be an array of object. Each object
// must have a 'name' property, which is displayed in the selector, and a
// 'children' property, which should either be an empty array, or an array
// containing more nested objects of the same format.
function TreeSelect(jqSelector, data, settings) {
	var tree = this;

	this.nodes = [];
	this.list = $("

");
	var container = $("

")
        .addClass("contents")
		.append(this.list);
	this.element = $("

")
		.addClass("tree-select")
        .append(container)
		.hide();
	this.settings = this.setDefaultSettings(settings);
	if (this.settings.showEmptyOption) {
	    tree.makeChild({
	        name: "",
	        value: "",
            label: "Nothing",
	        children: []
	    });
	}
	data.forEach(function(item) {
	    tree.makeChild(item);
	});
	$("body").append(this.element);

    jqSelector += " input.text";
    $(document).on("focus", jqSelector, function() {
        tree.clicked($(this).parent());
    });
    $(document).on("blur", jqSelector, function() {
        tree.blur();
    });
	this.element.find("*")
		.attr("tabindex", 1000)
		.blur(function() { tree.blur(); })
		.focus(function() { tree.focus(); });
}
TreeSelect.prototype.makeChild = function(data) {
    var node = new TreeSelect_Node(data, this.list, this, 0);
    this.nodes.push(node);
};
TreeSelect.prototype.clicked = function(section) {
	var tree = this;
    if (!this.field) {
    	this.field = section.find("input.text");
    	this.hidden = section.find("input.value");
    	this.previousTextField = section.find("input.previous-text");

    	this.field.keyup(function(event) {
    		tree.filter(tree.field.val());
            if (event.which == DOWN) {
                tree.nodes[0].info.focus();
            }
    	});
    }
	tree.filter(tree.field.val());
	this.element.find(".highlight").removeClass(".highlight");
	this.collapse();
	tree.focus();
	this.show();
	this.field.select();
}
TreeSelect.prototype.collapse = function() {
	this.nodes.forEach(function(node) {
		node.recursiveCollapse();
	});
}
TreeSelect.prototype.show = function() {
	var pos = this.field.offset();
	this.element
		.fadeIn()
		.css("left", pos.left)
		.css("top", pos.top + this.field.height());
}
TreeSelect.prototype.select = function (node) {
    this.hidden.val(node.value).trigger('change');
    this.field.val(node.name);
    this.previousTextField.val(node.name);
	this.element.fadeOut();
}
TreeSelect.prototype.filter = function (query) {
    if (query.length == 0 || query.length >= this.settings.minQueryLength) {
        query = query.toLowerCase();
        this.nodes.forEach(function (node) {
            node.filter(query);
        });
    }
}
TreeSelect.prototype.width = function() {
	return 250;
}
TreeSelect.prototype.blur = function() {
	if (this.timer == null) {
		var tree = this;
		this.timer = setTimeout(function() {
		    tree.element.fadeOut();
            if (tree.field.val() == "") {
                tree.hidden.val("");
                tree.previous.val("");
            } else {
		        tree.field.val(tree.previousTextField.val());
            }
		}, 50);
	}
}
TreeSelect.prototype.focus = function() {
	if (this.timer) {
		clearTimeout(this.timer);
		this.timer = null;
	}
}
TreeSelect.prototype.setDefaultSettings = function(input) {
    if (!input) {
        input = {};
    }
    if (!input.hasOwnProperty("minQueryLength")) {
        input.minQueryLength = 2;
    }
    if (!input.hasOwnProperty("showEmptyOption")) {
        input.showEmptyOption = true;
    }
    return input;
}
TreeSelect.prototype.changeContents = function(data) {
    var tree = this;
    data.forEach(function(item) {
        var node = tree.nodes.find(function (n) {
            return n.value == item.value
        });
        if (node) {
            node.updateContents(item);
        } else {
            tree.makeChild(item);
        }
    });
}

// data should be an object with 'name', 'value' and 'children' properties
// Optionally it can include a 'label' property, that is displayed instead
// of 'name' in the dropdown. In this case 'name' is still used in the textbox
// when this item is selected.
function TreeSelect_Node(data, container, tree, padding) {
		var node = this;
		this.name = data.name;
		this.value = data.value;
		this.padding = padding;
		this.label = data.label ? data.label : data.name;

		this.expanded = false;
		this.children = [];
		this.tree = tree;
		this.element = $("

");
		this.info = $("")
			.addClass("info")
			.css("padding-left", padding * 35 + 5)
			.css("width", tree.width() - padding * 35 + 5)
			.click(function() {
				tree.select(node);
			})
            .keydown(function(event) {
                if (event.which == RIGHT) {
                    node.expand();
                }
                if (event.which == LEFT) {
                    if (node.list && node.expanded) {
                        node.collapse();
                    } else {
                        node.element.closest("ol").closest("li").find(".info").first().focus();
                    }
                }
                if (event.which == DOWN) {
                    var next = node.element.find("ol:visible").first().find("li").first();
                    if (!next.length) {
                        next = node.element.next("li");
                    }
                    if (!next.length) {
                        next = node.element.closest("ol").closest("li").next("li");
                    }
                    next.find(".info").first().focus();
                    event.preventDefault();
                }
                if (event.which == UP) {
                    var previous = node.element.prev("li").first();
                    if (previous.length) {
                        var lastChild = previous.find("li:visible").last();
                        if (lastChild.length) {
                            previous = lastChild;
                        }
                    }
                    if (!previous.length) {
                        previous = node.element.closest("ol").closest("li");
                    }
                    if (previous.length) {
                        previous.find(".info").first().focus();
                    } else {
                        tree.field.focus();
                    }
                    event.preventDefault();
                }
            });
		this.element.append(this.info);
		this.info.append($(" 0) {
			this.list = $("

").hide();
			data.children.forEach(function (item) {
			    node.makeChild(item);
			});
			this.expander = this.makeExpander();
			this.info.prepend(this.expander);
			this.element.append(this.list);
		}
		container.append(this.element);
	}
TreeSelect_Node.prototype.filter = function(query) {
	if (query == "") {
		this.collapse();
		this.info.removeClass("highlight");
		this.element.slideDown();
		return;
	}

	var anyChildren = false;
	if (this.list) {
		this.children.forEach(function(child) {
			if (child.filter(query)) {
				anyChildren = true;
			}
		});
		if (anyChildren) {
			this.expand(false);
		} else {
			this.collapse();
		}
	}

	var myself = this.name.toLowerCase().indexOf(query) >= 0;
	if (myself) {
		this.info.addClass("highlight");
	} else {
		this.info.removeClass("highlight");
	}

	var visible = myself || anyChildren;
	if (visible) {
		this.element.slideDown();
	} else {
		this.element.slideUp();
	}
	return visible;
}
TreeSelect_Node.prototype.expand = function(expandChildren) {
	if (expandChildren) {
		this.children.forEach(function(child) {
			if (!child.expanded) {
				child.element.show();
			}
		});
	}
	this.list.slideDown();
	this.expanded = true;
	this.expander.attr("src", "/Content/minus.png");
}
TreeSelect_Node.prototype.collapse = function() {
	if (this.list) {
		this.list.slideUp();
	}
	this.expanded = false;
	if (this.expander) {
	    this.expander.attr("src", "/Content/plus.png");
	}
}
TreeSelect_Node.prototype.recursiveCollapse = function() {
	this.collapse(false);
	this.children.forEach(function(child) {
		child.recursiveCollapse();
	});
}
TreeSelect_Node.prototype.makeExpander = function() {
	var node = this;
	var e = $("")
		.addClass("expander")
		.attr("src", "/Content/minus.png")
		.click(function(e) {
			e.stopPropagation();
			if (node.expanded) {
				node.collapse();
			} else {
				node.expand(true);
			}
		});
	return e;
}
TreeSelect_Node.prototype.makeChild = function (data) {
    this.children.push(new TreeSelect_Node(data, this.list, this.tree, this.padding + 1));
}
TreeSelect_Node.prototype.updateContents = function (data) {
    var node = this;
    data.children.forEach(function (item) {
        var child = node.children.find(function (n) {
            return n.value == item.value;
        });
        if (child) {
            child.updateContents(item);
        } else {
            node.makeChild(item);
        }
    });
}<commit_msg>Can select with enter key. Fix bug around navigation post-filter<commit_after>var ENTER = 13;
var LEFT = 37;
var UP = 38;
var RIGHT = 39;
var DOWN = 40;

// Elements should be a jQuery set of input elements which should be turned
// into tree selectors. The data should be an array of object. Each object
// must have a 'name' property, which is displayed in the selector, and a
// 'children' property, which should either be an empty array, or an array
// containing more nested objects of the same format.
function TreeSelect(jqSelector, data, settings) {
	var tree = this;

	this.nodes = [];
	this.list = $("

");
	var container = $("

")
        .addClass("contents")
		.append(this.list);
	this.element = $("

")
		.addClass("tree-select")
        .append(container)
		.hide();
	this.settings = this.setDefaultSettings(settings);
	if (this.settings.showEmptyOption) {
	    tree.makeChild({
	        name: "",
	        value: "",
            label: "Nothing",
	        children: []
	    });
	}
	data.forEach(function(item) {
	    tree.makeChild(item);
	});
	$("body").append(this.element);

    jqSelector += " input.text";
    $(document).on("focus", jqSelector, function() {
        tree.clicked($(this).parent());
    });
    $(document).on("blur", jqSelector, function() {
        tree.blur();
    });
	this.element.find("*")
		.attr("tabindex", 1000)
		.blur(function() { tree.blur(); })
		.focus(function() { tree.focus(); });
}
TreeSelect.prototype.makeChild = function(data) {
    var node = new TreeSelect_Node(data, this.list, this, 0);
    this.nodes.push(node);
};
TreeSelect.prototype.clicked = function(section) {
	var tree = this;
    if (!this.field) {
    	this.field = section.find("input.text");
    	this.hidden = section.find("input.value");
    	this.previousTextField = section.find("input.previous-text");

    	this.field.keyup(function(event) {
    		tree.filter(tree.field.val());
            if (event.which == DOWN) {
                tree.element.find(".info:visible").first().focus();
                event.preventDefault();
            }
    	});
    }
	tree.filter(tree.field.val());
	this.element.find(".highlight").removeClass(".highlight");
	this.collapse();
	tree.focus();
	this.show();
	this.field.select();
}
TreeSelect.prototype.collapse = function() {
	this.nodes.forEach(function(node) {
		node.recursiveCollapse();
	});
}
TreeSelect.prototype.show = function() {
	var pos = this.field.offset();
	this.element
		.fadeIn()
		.css("left", pos.left)
		.css("top", pos.top + this.field.height());
}
TreeSelect.prototype.select = function (node) {
    this.hidden.val(node.value).trigger('change');
    this.field.val(node.name);
    this.previousTextField.val(node.name);
	this.element.fadeOut();
}
TreeSelect.prototype.filter = function (query) {
    if (query.length == 0 || query.length >= this.settings.minQueryLength) {
        query = query.toLowerCase();
        this.nodes.forEach(function (node) {
            node.filter(query);
        });
    }
}
TreeSelect.prototype.width = function() {
	return 250;
}
TreeSelect.prototype.blur = function() {
	if (this.timer == null) {
		var tree = this;
		this.timer = setTimeout(function() {
		    tree.element.fadeOut();
            if (tree.field.val() == "") {
                tree.hidden.val("");
                tree.previous.val("");
            } else {
		        tree.field.val(tree.previousTextField.val());
            }
		}, 50);
	}
}
TreeSelect.prototype.focus = function() {
	if (this.timer) {
		clearTimeout(this.timer);
		this.timer = null;
	}
}
TreeSelect.prototype.setDefaultSettings = function(input) {
    if (!input) {
        input = {};
    }
    if (!input.hasOwnProperty("minQueryLength")) {
        input.minQueryLength = 2;
    }
    if (!input.hasOwnProperty("showEmptyOption")) {
        input.showEmptyOption = true;
    }
    return input;
}
TreeSelect.prototype.changeContents = function(data) {
    var tree = this;
    data.forEach(function(item) {
        var node = tree.nodes.find(function (n) {
            return n.value == item.value
        });
        if (node) {
            node.updateContents(item);
        } else {
            tree.makeChild(item);
        }
    });
}

// data should be an object with 'name', 'value' and 'children' properties
// Optionally it can include a 'label' property, that is displayed instead
// of 'name' in the dropdown. In this case 'name' is still used in the textbox
// when this item is selected.
function TreeSelect_Node(data, container, tree, padding) {
		var node = this;
		this.name = data.name;
		this.value = data.value;
		this.padding = padding;
		this.label = data.label ? data.label : data.name;

		this.expanded = false;
		this.children = [];
		this.tree = tree;
		this.element = $("

");
		this.info = $("")
			.addClass("info")
			.css("padding-left", padding * 35 + 5)
			.css("width", tree.width() - padding * 35 + 5)
			.click(function() {
				tree.select(node);
			})
            .keyup(function(event) {
                if (event.which == ENTER) {
                    tree.select(node);
                }
            })
            .keydown(function(event) {
                if (event.which == RIGHT) {
                    node.expand(true);
                }
                if (event.which == LEFT) {
                    if (node.list && node.expanded) {
                        node.collapse();
                    } else {
                        node.element.closest("ol").closest("li").find(".info").first().focus();
                    }
                }
                if (event.which == DOWN) {
                    var next = node.element.find("ol:visible").first().find("li").first();
                    if (!next.length) {
                        next = node.element.next("li");
                    }
                    if (!next.length) {
                        next = node.element.closest("ol").closest("li").next("li");
                    }
                    next.find(".info").first().focus();
                    event.preventDefault();
                }
                if (event.which == UP) {
                    var previous = node.element.prev("li:visible").first();
                    if (previous.length) {
                        var lastChild = previous.find("li:visible").last();
                        if (lastChild.length) {
                            previous = lastChild;
                        }
                    }
                    if (!previous.length) {
                        previous = node.element.closest("ol").closest("li");
                    }
                    if (previous.length) {
                        previous.find(".info").first().focus();
                    } else {
                        tree.field.focus();
                    }
                    event.preventDefault();
                }
            });
		this.element.append(this.info);
		this.info.append($(" 0) {
			this.list = $("

").hide();
			data.children.forEach(function (item) {
			    node.makeChild(item);
			});
			this.expander = this.makeExpander();
			this.info.prepend(this.expander);
			this.element.append(this.list);
		}
		container.append(this.element);
	}
TreeSelect_Node.prototype.filter = function(query) {
	if (query == "") {
		this.collapse();
		this.info.removeClass("highlight");
		this.element.slideDown();
		return;
	}

	var anyChildren = false;
	if (this.list) {
		this.children.forEach(function(child) {
			if (child.filter(query)) {
				anyChildren = true;
			}
		});
		if (anyChildren) {
			this.expand(false);
		} else {
			this.collapse();
		}
	}

	var myself = this.name.toLowerCase().indexOf(query) >= 0;
	if (myself) {
		this.info.addClass("highlight");
	} else {
		this.info.removeClass("highlight");
	}

	var visible = myself || anyChildren;
	if (visible) {
		this.element.slideDown();
	} else {
		this.element.slideUp();
	}
	return visible;
}
TreeSelect_Node.prototype.expand = function(expandChildren) {
	if (expandChildren) {
		this.children.forEach(function(child) {
			if (!child.expanded) {
				child.element.show();
			}
		});
	}
	this.list.slideDown();
	this.expanded = true;
	this.expander.attr("src", "/Content/minus.png");
}
TreeSelect_Node.prototype.collapse = function() {
	if (this.list) {
		this.list.slideUp();
	}
	this.expanded = false;
	if (this.expander) {
	    this.expander.attr("src", "/Content/plus.png");
	}
}
TreeSelect_Node.prototype.recursiveCollapse = function() {
	this.collapse(false);
	this.children.forEach(function(child) {
		child.recursiveCollapse();
	});
}
TreeSelect_Node.prototype.makeExpander = function() {
	var node = this;
	var e = $("")
		.addClass("expander")
		.attr("src", "/Content/minus.png")
		.click(function(e) {
			e.stopPropagation();
			if (node.expanded) {
				node.collapse();
			} else {
				node.expand(true);
			}
		});
	return e;
}
TreeSelect_Node.prototype.makeChild = function (data) {
    this.children.push(new TreeSelect_Node(data, this.list, this.tree, this.padding + 1));
}
TreeSelect_Node.prototype.updateContents = function (data) {
    var node = this;
    data.children.forEach(function (item) {
        var child = node.children.find(function (n) {
            return n.value == item.value;
        });
        if (child) {
            child.updateContents(item);
        } else {
            node.makeChild(item);
        }
    });
}<|endoftext|>


<commit_before>import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import composeAsyncContainer from '../../../../../common/AsyncContainer';
import composeHelpfulContainer from '../../../../../common/HelpfulContainer';
import { fetchCreateFocusKeywordStoryCounts } from '../../../../../../actions/topicActions';
import DataCard from '../../../../../common/DataCard';
import BubbleChart, { TEXT_PLACEMENT_ABOVE } from '../../../../../vis/BubbleChart';
import { getBrandDarkColor } from '../../../../../../styles/colors';

const BUBBLE_CHART_DOM_ID = 'bubble-chart-keyword-preview-story-total';

const localMessages = {
  title: { id: 'topic.snapshot.keywords.storyCount.title', defaultMessage: 'Story Counts' },
  helpTitle: { id: 'topic.snapshot.keywords.storyCount.help.title', defaultMessage: 'About Story Counts' },
  helpText: { id: 'topic.snapshot.keywords.storyCount.help.text',
    defaultMessage: '
This is a visualization showing the how many of the stories from the total Topic would be included within this Focus.
',
  },
  filteredLabel: { id: 'topic.snapshot.keywords.storyCount.matching', defaultMessage: 'Matching Stories' },
  totalLabel: { id: 'topic.snapshot.keywords.storyCount.total', defaultMessage: 'All Stories' },
};

class KeywordStoryCountPreviewContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { keywords, fetchData } = this.props;
    if (nextProps.keywords !== keywords) {
      fetchData(nextProps.keywords);
    }
  }
  render() {
    const { counts, helpButton } = this.props;
    const { formatMessage } = this.props.intl;
    let content = null;
    if (counts !== null) {
      const data = [  // format the data for the bubble chart help
        { label: formatMessage(localMessages.filteredLabel),
          value: counts.filtered,
          color: getBrandDarkColor(),
          labelColor: 'rgb(255,255,255)' },
        { label: formatMessage(localMessages.totalLabel), value: counts.total },
      ];
      content = (<BubbleChart
        data={data}
        domId={BUBBLE_CHART_DOM_ID}
        textPlacement={TEXT_PLACEMENT_ABOVE}
        width={440}
      />);
    }
    return (
      <DataCard>

          <FormattedMessage {...localMessages.title} />
          {helpButton}

        {content}
      </DataCard>
    );
  }
}

KeywordStoryCountPreviewContainer.propTypes = {
  // from compositional chain
  intl: React.PropTypes.object.isRequired,
  helpButton: React.PropTypes.node.isRequired,
  // from parent
  topicId: React.PropTypes.number.isRequired,
  keywords: React.PropTypes.string.isRequired,
  // from dispatch
  asyncFetch: React.PropTypes.func.isRequired,
  fetchData: React.PropTypes.func.isRequired,
  // from state
  counts: React.PropTypes.object,
  fetchStatus: React.PropTypes.string.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.focalSets.create.matchingStoryCounts.fetchStatus,
  counts: state.topics.selected.focalSets.create.matchingStoryCounts.counts,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (keywords) => {
    dispatch(fetchCreateFocusKeywordStoryCounts(ownProps.topicId, { q: keywords }));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData(ownProps.keywords);
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      composeHelpfulContainer(localMessages.helpTitle, localMessages.helpText)(
        composeAsyncContainer(
          KeywordStoryCountPreviewContainer
        )
      )
    )
  );
<commit_msg>use correct var name in results for bubble chart (fix #180)<commit_after>import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import composeAsyncContainer from '../../../../../common/AsyncContainer';
import composeHelpfulContainer from '../../../../../common/HelpfulContainer';
import { fetchCreateFocusKeywordStoryCounts } from '../../../../../../actions/topicActions';
import DataCard from '../../../../../common/DataCard';
import BubbleChart, { TEXT_PLACEMENT_ABOVE } from '../../../../../vis/BubbleChart';
import { getBrandDarkColor } from '../../../../../../styles/colors';

const BUBBLE_CHART_DOM_ID = 'bubble-chart-keyword-preview-story-total';

const localMessages = {
  title: { id: 'topic.snapshot.keywords.storyCount.title', defaultMessage: 'Story Counts' },
  helpTitle: { id: 'topic.snapshot.keywords.storyCount.help.title', defaultMessage: 'About Story Counts' },
  helpText: { id: 'topic.snapshot.keywords.storyCount.help.text',
    defaultMessage: '
This is a visualization showing the how many of the stories from the total Topic would be included within this Focus.
',
  },
  filteredLabel: { id: 'topic.snapshot.keywords.storyCount.matching', defaultMessage: 'Matching Stories' },
  totalLabel: { id: 'topic.snapshot.keywords.storyCount.total', defaultMessage: 'All Stories' },
};

class KeywordStoryCountPreviewContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { keywords, fetchData } = this.props;
    if (nextProps.keywords !== keywords) {
      fetchData(nextProps.keywords);
    }
  }
  render() {
    const { counts, helpButton } = this.props;
    const { formatMessage } = this.props.intl;
    let content = null;
    if (counts !== null) {
      const data = [  // format the data for the bubble chart help
        { label: formatMessage(localMessages.filteredLabel),
          value: counts.count,
          color: getBrandDarkColor(),
          labelColor: 'rgb(255,255,255)' },
        { label: formatMessage(localMessages.totalLabel), value: counts.total },
      ];
      content = (<BubbleChart
        data={data}
        domId={BUBBLE_CHART_DOM_ID}
        textPlacement={TEXT_PLACEMENT_ABOVE}
        width={440}
      />);
    }
    return (
      <DataCard>

          <FormattedMessage {...localMessages.title} />
          {helpButton}

        {content}
      </DataCard>
    );
  }
}

KeywordStoryCountPreviewContainer.propTypes = {
  // from compositional chain
  intl: React.PropTypes.object.isRequired,
  helpButton: React.PropTypes.node.isRequired,
  // from parent
  topicId: React.PropTypes.number.isRequired,
  keywords: React.PropTypes.string.isRequired,
  // from dispatch
  asyncFetch: React.PropTypes.func.isRequired,
  fetchData: React.PropTypes.func.isRequired,
  // from state
  counts: React.PropTypes.object,
  fetchStatus: React.PropTypes.string.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.focalSets.create.matchingStoryCounts.fetchStatus,
  counts: state.topics.selected.focalSets.create.matchingStoryCounts.counts,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (keywords) => {
    dispatch(fetchCreateFocusKeywordStoryCounts(ownProps.topicId, { q: keywords }));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData(ownProps.keywords);
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      composeHelpfulContainer(localMessages.helpTitle, localMessages.helpText)(
        composeAsyncContainer(
          KeywordStoryCountPreviewContainer
        )
      )
    )
  );
<|endoftext|>


<commit_before>"use strict";

require("requirish")._(module);
var _ = require("underscore");
var should = require("should");
var assert = require("better-assert");
var path = require("path");
var opcua = require("index.js");
var async = require("async");
var StatusCodes = opcua.StatusCodes;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var DataValue = opcua.DataValue;

var UAProxyManager = require("lib/client/proxy").UAProxyManager;
require("lib/client/state_machine_proxy");

var makeRefId = require("lib/client/proxy").makeRefId;
function Namespace() {

}

function ns(namespaceIndex,browseName) {
    return namespaceIndex.toString() + ":" + browseName;
}

function create_analyser_device(addressSpace) {

    var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");
    var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");

    var deviceType = addressSpace.findObjectType("DeviceType",di_namespace);
    //xx console.log(deviceType.toString());

    var analyserDeviceType = addressSpace.findObjectType("AnalyserDeviceType",adi_namespace);
    //xx console.log(analyserDeviceType.toString());

    var myAnalyserDeviceType = addressSpace.addObjectType({
        browseName: "MyAnalyserDeviceType",
        subtypeOf: analyserDeviceType
    });

    var myAnalyser = myAnalyserDeviceType.instantiate({
       browseName: "MyAnalyser"
    });
    return myAnalyser;

}

var build_server_with_temperature_device = require("test/helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("test/helpers/perform_operation_on_client_session").perform_operation_on_client_session;

var standard_nodeset_file = opcua.standard_nodeset_file;

describe("ADI - Testing a server that exposes Analyser Devices",function(){

    var server, client, endpointUrl;

    this.timeout(Math.max(50000,this._timeout));

    var server_options = {
        port: 2000,
        nodeset_filename: [
            standard_nodeset_file,
            path.join(__dirname,"../../../../nodesets/Opc.Ua.Di.NodeSet2.xml"),
            path.join(__dirname,"../../../../nodesets/Opc.Ua.Adi.NodeSet2.xml")
        ]
    };

    var analyser_device;
    var port = 2000;

    var addressSpace;
    before(function (done) {
        port += 1;
        server = build_server_with_temperature_device(server_options, function (err) {
            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;

            addressSpace = server.engine.addressSpace;

            done(err);
        });
    });

    beforeEach(function (done) {
        client = new opcua.OPCUAClient();
        done();
    });

    afterEach(function (done) {
        client = null;
        done();
    });

    after(function (done) {
        server.shutdown(done);
    });

    it("should have a DeviceType in DI namespace",function() {

        var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");
        di_namespace.should.eql(2);

        var deviceType = addressSpace.findObjectType("DeviceType",di_namespace);
        (!!deviceType).should.eql(true,"DeviceType must exist in DI namespace");
    });

    it("should instantiate a DeviceType",function() {

        var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");
        var deviceType = addressSpace.findObjectType("DeviceType",di_namespace);

        //xx console.log(deviceType.toString());
        var myDevice = deviceType.instantiate({
            browseName:"MyDevice"
        });
    });

    it("should instantiate a AnalyserChannelType",function() {

        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");

        var analyserChannelType  = addressSpace.findObjectType("AnalyserChannelType",adi_namespace);
        analyserChannelType.browseName.toString().should.eql("3:AnalyserChannelType");

        var channel1 = analyserChannelType.instantiate({
            browseName: "__Channel1"
        });

        should(channel1.parameterSet).eql(undefined);
        should(channel1.getComponentByName("ParameterSet")).eql(null,"optional ParameterSet shall not be instantiate ");

        var channel2 = analyserChannelType.instantiate({
            browseName: "__Channel2",
            optionals: [ "ParameterSet" ]
        });

        channel2.parameterSet.browseName.toString().should.eql("2:ParameterSet");
        channel2._clear_caches();
        channel2.getComponentByName("2:ParameterSet").browseName.toString().should.eql("2:ParameterSet");

        // isEnable Property
        var isEnableParameter_variation1 = channel2.parameterSet.getComponentByName("3:IsEnabled");
        isEnableParameter_variation1.browseName.toString().should.eql("3:IsEnabled");

        var isEnableParameter_variation2 = channel2.parameterSet.isEnabled;
        isEnableParameter_variation2.browseName.toString().should.eql("3:IsEnabled");

        // verify that the isEnableParameter is also present in the "Configuration FunctionalGroup

        channel2.configuration.browseName.toString().should.eql("3:Configuration");

        channel2.configuration.findReferences("Organizes").length.should.be.aboveOrEqual(1);

        channel2.configuration.getFolderElementByName("3:IsEnabled").browseName.toString().should.eql("3:IsEnabled");
        channel2.configuration.isEnabled.browseName.toString().should.eql("3:IsEnabled");

    });

    it("should have a AnalyserDeviceType",function() {

        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");
        var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");

        //xxx console.log(addressSpace.getNamespaceArray());
        di_namespace.should.eql(2);
        adi_namespace.should.eql(3);

        var analyserDeviceType = addressSpace.findObjectType("AnalyserDeviceType",adi_namespace);

        should(analyserDeviceType).not.equal(undefined).and.not.eql(null);

        analyserDeviceType.browseName.toString().should.eql("3:AnalyserDeviceType");
    });

    it("should have a AnalyserDeviceType v2",function() {

        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");

        var analyserDeviceType = addressSpace.findObjectType(ns(adi_namespace,"AnalyserDeviceType"));

        analyserDeviceType.browseName.toString().should.eql("3:AnalyserDeviceType");

    });

    it("should create a analyser device",function() {
        analyser_device = create_analyser_device(server.engine.addressSpace);

    });

    function dumpStateMachine(stateMachineType) {

        var addressSpace = stateMachineType.__address_space;
        should(!!addressSpace).eql(true);
        // enumerate states from components

        // InitialStateType

        // StateType

        // TransitionType

        var initialStateType = addressSpace.findObjectType("InitialStateType");
        should(!!initialStateType).eql(true);

        var stateType = addressSpace.findObjectType("StateType");
        should(!!stateType).eql(true);

        var transitionType = addressSpace.findObjectType("TransitionType");
        should(!!transitionType).eql(true);

        var browse_service   = require("lib/services/browse_service");

        var resultMask = browse_service.makeResultMask("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition");

        var bd = new opcua.browse_service.BrowseDescription({
            nodeId: stateMachineType.nodeId,
            browseDirection: opcua.browse_service.BrowseDirection.Forward,
            referenceTypeId: makeRefId("HasComponent"),
            resultMask: resultMask

        });
        var results = stateMachineType.browseNode(bd);
        results.forEach(function(result){ console.log(result.toString());});
    }

    it("should have a AnalyserDeviceStateMachineType",function(done) {

        /**
         @startuml
         @startuml
         [*] --> 5022
         5022: Powerup
         5023: Operating
         5024: Local
         5025: Maintenance
         5026: Shutdown
         5022 --> 5023 : Powerup\nTo\nOperating\nTransition
         5023 --> 5024 : Operating\nTo\nLocal\nTransition
         5023 --> 5025 : Operating\nTo\nMaintenance\nTransition
         5024 --> 5023 : Local\nTo\nOperating\nTransition
         5024 --> 5025 : Local\nTo\nMaintenance\nTransition
         5025 --> 5023 : Maintenance\nTo\nOperating\nTransition
         5025 --> 5024 : Maintenance\nTo\nLocal\nTransition
         5023 --> 5026 : Operating\nTo\nShutdown\nTransition
         5024 --> 5026 : Local\nTo\nShutdown\nTransition
         5025 --> 5026 : Maintenance\nTo\nShutdown\nTransition
         5026 --> [*]
         @enduml
         */
        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");
        var analyserDeviceStateMachineType = addressSpace.findObjectType(ns(adi_namespace,"AnalyserDeviceStateMachineType"));

        analyserDeviceStateMachineType.browseName.toString().should.eql("3:AnalyserDeviceStateMachineType");

        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

            //xxdumpStateMachine(analyserDeviceStateMachineType);
            var proxyManager = new UAProxyManager(session);

            async.series([
                function (callback) {
                    proxyManager.start(callback);
                },
                function (callback) {
                    var stateMachineTypeId = analyserDeviceStateMachineType.nodeId;
                    //"3:AnalyserDeviceStateMachineType";

                    proxyManager.getStateMachineType(stateMachineTypeId, function (err, obj) {

                        callback(err);
                    });
                },
                function (callback) {
                    proxyManager.stop(callback);
                }
            ], inner_done);
        },done);
    });

});
<commit_msg>fix typo<commit_after>"use strict";

require("requirish")._(module);
var _ = require("underscore");
var should = require("should");
var assert = require("better-assert");
var path = require("path");
var opcua = require("index.js");
var async = require("async");
var StatusCodes = opcua.StatusCodes;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var DataValue = opcua.DataValue;

var UAProxyManager = require("lib/client/proxy").UAProxyManager;
require("lib/client/state_machine_proxy");

var makeRefId = require("lib/client/proxy").makeRefId;
function Namespace() {

}

function ns(namespaceIndex,browseName) {
    return namespaceIndex.toString() + ":" + browseName;
}

function create_analyser_device(addressSpace) {

    var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");
    var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");

    var deviceType = addressSpace.findObjectType("DeviceType",di_namespace);
    //xx console.log(deviceType.toString());

    var analyserDeviceType = addressSpace.findObjectType("AnalyserDeviceType",adi_namespace);
    //xx console.log(analyserDeviceType.toString());

    var myAnalyserDeviceType = addressSpace.addObjectType({
        browseName: "MyAnalyserDeviceType",
        subtypeOf: analyserDeviceType
    });

    var myAnalyser = myAnalyserDeviceType.instantiate({
       browseName: "MyAnalyser"
    });
    return myAnalyser;

}

var build_server_with_temperature_device = require("test/helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("test/helpers/perform_operation_on_client_session").perform_operation_on_client_session;

var standard_nodeset_file = opcua.standard_nodeset_file;

describe("ADI - Testing a server that exposes Analyser Devices",function(){

    var server, client, endpointUrl;

    this.timeout(Math.max(50000,this._timeout));

    var server_options = {
        port: 2000,
        nodeset_filename: [
            standard_nodeset_file,
            path.join(__dirname,"../../../../nodesets/Opc.Ua.Di.NodeSet2.xml"),
            path.join(__dirname,"../../../../nodesets/Opc.Ua.Adi.NodeSet2.xml")
        ]
    };

    var analyser_device;
    var port = 2000;

    var addressSpace;
    before(function (done) {
        port += 1;
        server = build_server_with_temperature_device(server_options, function (err) {
            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;

            addressSpace = server.engine.addressSpace;

            done(err);
        });
    });

    beforeEach(function (done) {
        client = new opcua.OPCUAClient();
        done();
    });

    afterEach(function (done) {
        client = null;
        done();
    });

    after(function (done) {
        server.shutdown(done);
    });

    it("should have a DeviceType in DI namespace",function() {

        var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");
        di_namespace.should.eql(2);

        var deviceType = addressSpace.findObjectType("DeviceType",di_namespace);
        (!!deviceType).should.eql(true,"DeviceType must exist in DI namespace");
    });

    it("should instantiate a DeviceType",function() {

        var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");
        var deviceType = addressSpace.findObjectType("DeviceType",di_namespace);

        //xx console.log(deviceType.toString());
        var myDevice = deviceType.instantiate({
            browseName:"MyDevice"
        });
    });

    it("should instantiate a AnalyserChannelType",function() {

        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");

        var analyserChannelType  = addressSpace.findObjectType("AnalyserChannelType",adi_namespace);
        analyserChannelType.browseName.toString().should.eql("3:AnalyserChannelType");

        var channel1 = analyserChannelType.instantiate({
            browseName: "__Channel1"
        });

        should(channel1.parameterSet).eql(undefined);
        should(channel1.getComponentByName("ParameterSet")).eql(null,"optional ParameterSet shall not be instantiate ");

        var channel2 = analyserChannelType.instantiate({
            browseName: "__Channel2",
            optionals: [ "ParameterSet" ]
        });

        channel2.parameterSet.browseName.toString().should.eql("2:ParameterSet");
        channel2._clear_caches();
        channel2.getComponentByName("2:ParameterSet").browseName.toString().should.eql("2:ParameterSet");

        // isEnable Property
        var isEnableParameter_variation1 = channel2.parameterSet.getComponentByName("3:IsEnabled");
        isEnableParameter_variation1.browseName.toString().should.eql("3:IsEnabled");

        var isEnableParameter_variation2 = channel2.parameterSet.isEnabled;
        isEnableParameter_variation2.browseName.toString().should.eql("3:IsEnabled");

        // verify that the isEnableParameter is also present in the "Configuration FunctionalGroup

        channel2.configuration.browseName.toString().should.eql("3:Configuration");

        channel2.configuration.findReferences("Organizes").length.should.be.aboveOrEqual(1);

        channel2.configuration.getFolderElementByName("3:IsEnabled").browseName.toString().should.eql("3:IsEnabled");
        channel2.configuration.isEnabled.browseName.toString().should.eql("3:IsEnabled");

    });

    it("should have a AnalyserDeviceType",function() {

        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");
        var di_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/DI/");

        //xxx console.log(addressSpace.getNamespaceArray());
        di_namespace.should.eql(2);
        adi_namespace.should.eql(3);

        var analyserDeviceType = addressSpace.findObjectType("AnalyserDeviceType",adi_namespace);

        should(analyserDeviceType).not.equal(undefined).and.not.eql(null);

        analyserDeviceType.browseName.toString().should.eql("3:AnalyserDeviceType");
    });

    it("should have a AnalyserDeviceType v2",function() {

        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");

        var analyserDeviceType = addressSpace.findObjectType(ns(adi_namespace,"AnalyserDeviceType"));

        analyserDeviceType.browseName.toString().should.eql("3:AnalyserDeviceType");

    });

    it("should create a analyser device",function() {
        analyser_device = create_analyser_device(server.engine.addressSpace);

    });

    function dumpStateMachine(stateMachineType) {

        var addressSpace = stateMachineType.__address_space;
        should(!!addressSpace).eql(true);
        // enumerate states from components

        // InitialStateType

        // StateType

        // TransitionType

        var initialStateType = addressSpace.findObjectType("InitialStateType");
        should(!!initialStateType).eql(true);

        var stateType = addressSpace.findObjectType("StateType");
        should(!!stateType).eql(true);

        var transitionType = addressSpace.findObjectType("TransitionType");
        should(!!transitionType).eql(true);

        var browse_service   = require("lib/services/browse_service");

        var resultMask = browse_service.makeResultMask("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition");

        var bd = new opcua.browse_service.BrowseDescription({
            nodeId: stateMachineType.nodeId,
            browseDirection: opcua.browse_service.BrowseDirection.Forward,
            referenceTypeId: makeRefId("HasComponent"),
            resultMask: resultMask

        });
        var results = stateMachineType.browseNode(bd);
        results.forEach(function(result){ console.log(result.toString());});
    }

    it("should have a AnalyserDeviceStateMachineType",function(done) {

        /**
         @startuml
         [*] --> 5022
         5022: Powerup
         5023: Operating
         5024: Local
         5025: Maintenance
         5026: Shutdown
         5022 --> 5023 : Powerup\nTo\nOperating\nTransition
         5023 --> 5024 : Operating\nTo\nLocal\nTransition
         5023 --> 5025 : Operating\nTo\nMaintenance\nTransition
         5024 --> 5023 : Local\nTo\nOperating\nTransition
         5024 --> 5025 : Local\nTo\nMaintenance\nTransition
         5025 --> 5023 : Maintenance\nTo\nOperating\nTransition
         5025 --> 5024 : Maintenance\nTo\nLocal\nTransition
         5023 --> 5026 : Operating\nTo\nShutdown\nTransition
         5024 --> 5026 : Local\nTo\nShutdown\nTransition
         5025 --> 5026 : Maintenance\nTo\nShutdown\nTransition
         5026 --> [*]
         @enduml
         */
        var adi_namespace = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/ADI/");
        var analyserDeviceStateMachineType = addressSpace.findObjectType(ns(adi_namespace,"AnalyserDeviceStateMachineType"));

        analyserDeviceStateMachineType.browseName.toString().should.eql("3:AnalyserDeviceStateMachineType");

        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

            //xxdumpStateMachine(analyserDeviceStateMachineType);
            var proxyManager = new UAProxyManager(session);

            async.series([
                function (callback) {
                    proxyManager.start(callback);
                },
                function (callback) {
                    var stateMachineTypeId = analyserDeviceStateMachineType.nodeId;
                    //"3:AnalyserDeviceStateMachineType";

                    proxyManager.getStateMachineType(stateMachineTypeId, function (err, obj) {

                        callback(err);
                    });
                },
                function (callback) {
                    proxyManager.stop(callback);
                }
            ], inner_done);
        },done);
    });

});
<|endoftext|>


<commit_before>module.exports =
{
  mutationFunction: function(phenotype)
  {
    // make a random change to phenotype
    return phenotype
  }
}
<commit_msg>Implement Mutation Function to Toggle Direction of Transistor<commit_after>module.exports =
{
  mutationFunction: function(phenotype)
  {
    // make a random change to phenotype
    var count = phenotype.nmos + phenotype.pmos
    var randNumb = Math.floor(Math.random() * (count + 1))

    if (randNumb < Math.floor(count/2))
      phenotype.nmosTransistors[randNumb].srcLeft = !phenotype.nmosTransistors[randNumb].srcLeft
    else
      phenotype.pmosTransistors[count-randNumb].srcLeft = !phenotype.pmosTransistors[count-randNumb].srcLeft

    return phenotype
  }
}
<|endoftext|>


<commit_before>'use strict'

const getFunctionOptions = require('../../src/getFunctionOptions.js')
const ServerlessOffline = require('../../src/ServerlessOffline.js')
const ServerlessBuilder = require('./ServerlessBuilder.js')

module.exports = class OfflineBuilder {
  constructor(serverlessBuilder, options) {
    this.handlers = {}
    this.options = options || {}
    this.serverlessBuilder = serverlessBuilder || new ServerlessBuilder()
  }

  addFunctionConfig(functionName, functionConfig, handler) {
    this.serverlessBuilder.addFunction(functionName, functionConfig)

    const funOptions = getFunctionOptions(functionName, functionConfig, '.')
    const [, handlerPath] = funOptions.handlerPath.split('/')

    this.handlers[handlerPath] = {
      [funOptions.handlerName]: handler,
    }

    return this
  }

  addCustom(prop, value) {
    this.serverlessBuilder.addCustom(prop, value)

    return this
  }

  addApiKeys(keys) {
    this.serverlessBuilder.addApiKeys(keys)

    return this
  }

  async toObject() {
    const serverlessOffline = new ServerlessOffline(
      this.serverlessBuilder.toObject(),
      this.options,
    )

    // offline.printBlankLine = jest.fn();

    serverlessOffline.mergeOptions()
    await serverlessOffline._createApiGateway()
    serverlessOffline.setupEvents()

    // offline.apiGateway.printBlankLine = jest.fn();

    return serverlessOffline.getApiGatewayServer()
  }
}
<commit_msg>Replace getFunctionOptions from OfflineBuilder<commit_after>'use strict'

const { join } = require('path')
const ServerlessOffline = require('../../src/ServerlessOffline.js')
const ServerlessBuilder = require('./ServerlessBuilder.js')
const { splitHandlerPathAndName } = require('../../src/utils/index.js')

module.exports = class OfflineBuilder {
  constructor(serverlessBuilder, options) {
    this.handlers = {}
    this.options = options || {}
    this.serverlessBuilder = serverlessBuilder || new ServerlessBuilder()
  }

  addFunctionConfig(functionName, functionConfig, handler) {
    this.serverlessBuilder.addFunction(functionName, functionConfig)

    const [handlerPath, handlerName] = splitHandlerPathAndName(
      functionConfig.handler,
    )

    const _handlerPath = join('.', handlerPath)

    this.handlers[_handlerPath] = {
      [handlerName]: handler,
    }

    return this
  }

  addCustom(prop, value) {
    this.serverlessBuilder.addCustom(prop, value)

    return this
  }

  addApiKeys(keys) {
    this.serverlessBuilder.addApiKeys(keys)

    return this
  }

  async toObject() {
    const serverlessOffline = new ServerlessOffline(
      this.serverlessBuilder.toObject(),
      this.options,
    )

    // offline.printBlankLine = jest.fn();

    serverlessOffline.mergeOptions()
    await serverlessOffline._createApiGateway()
    serverlessOffline.setupEvents()

    // offline.apiGateway.printBlankLine = jest.fn();

    return serverlessOffline.getApiGatewayServer()
  }
}
<|endoftext|>


<commit_before>const ignoreGenericWords = require('./ignoreGenericWords')();

describe('ignoreGenericWords', () => {
  it('should ignore generic words in all docs', () => {
    const docs = [{docType: 'package', name: 'create'}, {docType: 'class', name: 'Foo'}];
    const words = ['create', 'a', 'thing'];
    expect(ignoreGenericWords(docs, words, 0)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 1)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 2)).toEqual(docs);
  });

  it('should ignore generic words with mixed case in all docs', () => {
    const docs = [{docType: 'package', name: 'create'}, {docType: 'class', name: 'Foo'}];
    const words = ['Create', 'eRrOr', 'STUFF'];
    expect(ignoreGenericWords(docs, words, 0)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 1)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 2)).toEqual(docs);
  });

  it('should ignore `_` in all docs', () => {
    const docs = [{docType: 'package', name: 'create'}, {docType: 'class', name: 'Foo'}];
    const words = ['_'];
    expect(ignoreGenericWords(docs, words, 0)).toEqual([]);
  });
});

<commit_msg>fixup!: build(docs-infra): add _ to ignored ignoreGenericWords (#36316)<commit_after>const ignoreGenericWords = require('./ignoreGenericWords')();

describe('ignoreGenericWords', () => {
  it('should ignore generic words in all docs', () => {
    const docs = [{docType: 'package', name: 'create'}, {docType: 'class', name: 'Foo'}];
    const words = ['create', 'a', 'thing'];
    expect(ignoreGenericWords(docs, words, 0)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 1)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 2)).toEqual(docs);
  });

  it('should ignore generic words with mixed case in all docs', () => {
    const docs = [{docType: 'package', name: 'create'}, {docType: 'class', name: 'Foo'}];
    const words = ['Create', 'eRrOr', 'STUFF'];
    expect(ignoreGenericWords(docs, words, 0)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 1)).toEqual([]);
    expect(ignoreGenericWords(docs, words, 2)).toEqual(docs);
  });
});

<|endoftext|>


<commit_before>import OsfAdapter from './osf-adapter';

export default OsfAdapter.extend({
    buildURL(_, __, ___, requestType) {
        // TODO Not the best way to do this
        var base = this._super(...arguments);
        base = base.replace('preprint_providers', 'providers/preprints');
        return base;
    }
});
<commit_msg>Revert preprint-provider adapter change.<commit_after>import OsfAdapter from './osf-adapter';

export default OsfAdapter.extend({
});
<|endoftext|>


<commit_before>import { notEmpty } from '@ember/object/computed';
import { defineProperty, computed } from '@ember/object';
import { A } from '@ember/array';
import BsFormElement from 'ember-bootstrap/components/bs-form/element';

export default BsFormElement.extend({
  hasValidator: notEmpty('model.validate'),

  setupValidations() {
    let key = `model.error.${this.get('property')}.validation`;
    defineProperty(this, 'errors', computed(`model._errors`, function() {
      return A(this.get(key));
    }));
  }
});
<commit_msg>add description in source code<commit_after>import { notEmpty } from '@ember/object/computed';
import { defineProperty, computed } from '@ember/object';
import { A } from '@ember/array';
import BsFormElement from 'ember-bootstrap/components/bs-form/element';

export default BsFormElement.extend({
  hasValidator: notEmpty('model.validate'),

  setupValidations() {
    // `Changeset.error` is a getter based on a tracked property. Since it's a
    // derived state it's not working together with computed properties smoothly.
    // As a work-a-round we observe the `Changeset._errors` computed property
    // directly, which holds the state. This is not optimal cause it's private.
    // Should refactor to native getter as soon as `<FormElement>` component
    // of Ember Bootstrap supports native getters for `FormElement.errors`
    // property.
    let key = `model.error.${this.get('property')}.validation`;
    defineProperty(this, 'errors', computed(`model._errors`, function() {
      return A(this.get(key));
    }));
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/update-password';
import PasswordValidations from '../validations/password';
import Changeset from 'ember-changeset';
import lookupValidator from 'ember-changeset-validations';

export default Ember.Component.extend({
  layout,
  classNames: ['update-password-component'],
  firebaseApp: Ember.inject.service(),
  session: Ember.inject.service(),
  actions: {
    updatePassword(form) {
      const scope = this;
      if (this.get('session.isAuthenticated') && this.get('password').get('isValid')) {
        this.get('firebaseApp').auth().currentUser.updatePassword(form.get('password')).then(() => {
          Ember.Logger.log('successful update');
          scope.get('router').transitionTo('index');
        });
      }
    }
  },
  PasswordValidations,
  init() {
    this._super(...arguments);
    this.password = new Changeset({password: '', passwordConfirmation: ''}, lookupValidator(PasswordValidations), PasswordValidations);
  }
});
<commit_msg>JS: add reauthenticate to update password component<commit_after>import Ember from 'ember';
import layout from '../templates/components/update-password';
import PasswordValidations from '../validations/password';
import Changeset from 'ember-changeset';
import lookupValidator from 'ember-changeset-validations';

export default Ember.Component.extend({
  layout,
  classNames: ['update-password-component'],
  firebaseApp: Ember.inject.service(),
  session: Ember.inject.service(),
  actions: {
    updatePassword(form) {
      const scope = this;
      if (this.get('session.isAuthenticated') && this.get('password').get('isValid')) {
        this.get('firebaseApp').auth().currentUser.updatePassword(form.get('password')).then(() => {
          Ember.Logger.log('successful update');
          scope.get('router').transitionTo('index');
        }, (error) => {
          if(error.toString().contains('reauthenticate'))
            this.sendAction('reauthenticateUser');
        });
      }
    }
  },
  PasswordValidations,
  init() {
    this._super(...arguments);
    this.password = new Changeset({password: '', passwordConfirmation: ''}, lookupValidator(PasswordValidations), PasswordValidations);
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';

var RSVP = Ember.RSVP;

/*
 * This method does not change store, only change localforage
 *
 * @method reloadLocalRecords
 * @param {String|DS.Model} type
 */
export function reloadLocalRecords(type, reload, projectionName) {
  var store = Ember.getOwner(this).lookup('service:store');
  var modelType = store.modelFor(type);

  var localStore = Ember.getOwner(this).lookup('store:local');
  var localAdapter = localStore.get('adapter');

  var reloadedRecords = localAdapter.findAll(localStore, modelType)
    .then(deleteAll)
    .then(createAll);

  return reloadedRecords;

  function deleteAll(localRecords) {
    var deletedRecords = localRecords.map(function(record) {
      return localAdapter.deleteRecord(localStore, modelType, {id: record.id});
    });

    return RSVP.all(deletedRecords);
  }

  function createAll() {
    var projection = modelType.projections[projectionName];
    if (reload) {
      let options = { reload: true };
      options = Ember.isNone(projectionName) ? options : Ember.$.extend(true, options, { projection: projectionName });
      return store.findAll(type, options).then(function(records) {
        return createLocalRecords(store, localAdapter, localStore, modelType, records, projection);
      });
    }
    else {
      var records = store.peekAll(type);
	  return createLocalRecords(store, localAdapter, localStore, modelType, records, projection);
    }
  }
}

function createLocalRecord(store, localAdapter, localStore, modelType, record, projection) {
  if(record.get('id')) {
    var snapshot = record._createSnapshot();
    return localAdapter.createRecord(localStore, modelType, snapshot).then(function() {
      return syncDownRelatedRecords(store, record, localAdapter, localStore, projection);
    });
  }
  else {
    var recordName = record.constructor && record.constructor.modelName;
    var warnMessage = 'Record ' + recordName + ' does not have an id, therefor we can not create it locally: ';

    var recordData = record.toJSON && record.toJSON();

    Ember.Logger.warn(warnMessage, recordData);

    return RSVP.resolve();
  }
}

function createLocalRecords(store, localAdapter, localStore, modelType, records, projection) {
  var createdRecords = records.map(function(record) {
    return createLocalRecord(store, localAdapter, localStore, modelType, record, projection);
  });
  return RSVP.all(createdRecords);
}

export function syncDownRelatedRecords(store, mainRecord, localAdapter, localStore, projection) {
  function isEmbedded(store, modelType, relationshipName) {
    var serializerAttrs = store.serializerFor(modelType.modelName).get('attrs');
    return serializerAttrs[relationshipName] &&
    ((serializerAttrs[relationshipName].deserialize && serializerAttrs[relationshipName].deserialize === 'records') ||
    (serializerAttrs[relationshipName].embedded && serializerAttrs[relationshipName].embedded === 'always'));
  }

  function isAsync(modelType, relationshipName) {
    return Ember.get(modelType, 'relationshipsByName').get(relationshipName).options.async;
  }

  function createRelatedBelongsToRecord(store, modelType, relatedRecord, localAdapter, localStore, projection) {
    return createLocalRecord(store, localAdapter, localStore, modelType, relatedRecord, projection);
  }

  function createRelatedHasManyRecords(store, modelType, relatedRecords, localAdapter, localStore, projection) {
    let promises = Ember.A();
    for (let i = 0; i < relatedRecords.get('length'); i++) {
      let relatedRecord = relatedRecords.objectAt(i);
      promises.pushObject(createLocalRecord(store, localAdapter, localStore, modelType, relatedRecord, projection));
    }
    return promises;
  }

  function createRelatedRecords(store, mainRecord, localAdapter, localStore, projection) {
    var promises = Ember.A();
    var modelType = store.modelFor(mainRecord.constructor.modelName);
    var attrs = projection.attributes;
    var relationshipNames = Ember.get(modelType, 'relationshipNames');

    for (let i = 0; i < relationshipNames.belongsTo.length; i++) {
      var belongToName = relationshipNames.belongsTo[i];

      // Save related record into local store only if relationship included into projection.
      if (attrs.hasOwnProperty(belongToName)) {
        var async = isAsync(modelType, belongToName);
        if (async) {
          mainRecord.get(belongToName).then(function(relatedRecord) {
            if (!Ember.isNone(relatedRecord)) {
              promises.pushObject(createRelatedBelongsToRecord(store, modelType, relatedRecord, localAdapter, localStore, attrs[belongToName]));
            }
          });
        }
        else {
          if (isEmbedded(store, modelType, belongToName)) {
            var relatedRecord = mainRecord.get(belongToName);
            if (!Ember.isNone(relatedRecord)) {
              promises.pushObject(createRelatedBelongsToRecord(store, modelType, relatedRecord, localAdapter, localStore, attrs[belongToName]));
            }
          }
        }
      }
    }

    for (let i = 0; i < relationshipNames.hasMany.length; i++) {
      var hasManyName = relationshipNames.hasMany[i];

      // Save related records into local store only if relationship included into projection.
      if (attrs.hasOwnProperty(hasManyName)) {
        var async = isAsync(modelType, belongToName);
        if (async) {
          mainRecord.get(hasManyName).then(function(relatedRecords) {
            return promises.pushObjects(createRelatedHasManyRecords(store, modelType, relatedRecords, localAdapter, localStore, attrs[hasManyName]));
          });
        }
        else {
          if (isEmbedded(store, modelType, hasManyName)) {
            var relatedRecords = mainRecord.get(hasManyName);
            promises.pushObjects(createRelatedHasManyRecords(store, modelType, relatedRecords, localAdapter, localStore, attrs[hasManyName]));
          }
        }
      }
    }

    return RSVP.all(promises);
  }

  return createRelatedRecords(store, mainRecord, localAdapter, localStore, projection);
}<commit_msg>Fix use of incorrect model type<commit_after>import Ember from 'ember';

var RSVP = Ember.RSVP;

/*
 * This method does not change store, only change localforage
 *
 * @method reloadLocalRecords
 * @param {String|DS.Model} type
 */
export function reloadLocalRecords(type, reload, projectionName) {
  var store = Ember.getOwner(this).lookup('service:store');
  var modelType = store.modelFor(type);

  var localStore = Ember.getOwner(this).lookup('store:local');
  var localAdapter = localStore.get('adapter');

  var reloadedRecords = localAdapter.findAll(localStore, modelType)
    .then(deleteAll)
    .then(createAll);

  return reloadedRecords;

  function deleteAll(localRecords) {
    var deletedRecords = localRecords.map(function(record) {
      return localAdapter.deleteRecord(localStore, modelType, {id: record.id});
    });

    return RSVP.all(deletedRecords);
  }

  function createAll() {
    var projection = modelType.projections[projectionName];
    if (reload) {
      let options = { reload: true };
      options = Ember.isNone(projectionName) ? options : Ember.$.extend(true, options, { projection: projectionName });
      return store.findAll(type, options).then(function(records) {
        return createLocalRecords(store, localAdapter, localStore, modelType, records, projection);
      });
    }
    else {
      var records = store.peekAll(type);
	  return createLocalRecords(store, localAdapter, localStore, modelType, records, projection);
    }
  }
}

function createLocalRecord(store, localAdapter, localStore, modelType, record, projection) {
  if(record.get('id')) {
    var snapshot = record._createSnapshot();
    return localAdapter.createRecord(localStore, modelType, snapshot).then(function() {
      return syncDownRelatedRecords(store, record, localAdapter, localStore, projection);
    });
  }
  else {
    var recordName = record.constructor && record.constructor.modelName;
    var warnMessage = 'Record ' + recordName + ' does not have an id, therefor we can not create it locally: ';

    var recordData = record.toJSON && record.toJSON();

    Ember.Logger.warn(warnMessage, recordData);

    return RSVP.resolve();
  }
}

function createLocalRecords(store, localAdapter, localStore, modelType, records, projection) {
  var createdRecords = records.map(function(record) {
    return createLocalRecord(store, localAdapter, localStore, modelType, record, projection);
  });
  return RSVP.all(createdRecords);
}

export function syncDownRelatedRecords(store, mainRecord, localAdapter, localStore, projection) {
  function isEmbedded(store, modelType, relationshipName) {
    var serializerAttrs = store.serializerFor(modelType.modelName).get('attrs');
    return serializerAttrs[relationshipName] &&
    ((serializerAttrs[relationshipName].deserialize && serializerAttrs[relationshipName].deserialize === 'records') ||
    (serializerAttrs[relationshipName].embedded && serializerAttrs[relationshipName].embedded === 'always'));
  }

  function isAsync(modelType, relationshipName) {
    return Ember.get(modelType, 'relationshipsByName').get(relationshipName).options.async;
  }

  function createRelatedBelongsToRecord(store, relatedRecord, localAdapter, localStore, projection) {
    let modelType = store.modelFor(relatedRecord.constructor.modelName);
    return createLocalRecord(store, localAdapter, localStore, modelType, relatedRecord, projection);
  }

  function createRelatedHasManyRecords(store, relatedRecords, localAdapter, localStore, projection) {
    let promises = Ember.A();
    for (let i = 0; i < relatedRecords.get('length'); i++) {
      let relatedRecord = relatedRecords.objectAt(i);
      let modelType = store.modelFor(relatedRecord.constructor.modelName);
      promises.pushObject(createLocalRecord(store, localAdapter, localStore, modelType, relatedRecord, projection));
    }
    return promises;
  }

  function createRelatedRecords(store, mainRecord, localAdapter, localStore, projection) {
    var promises = Ember.A();
    var modelType = store.modelFor(mainRecord.constructor.modelName);
    var attrs = projection.attributes;
    var relationshipNames = Ember.get(modelType, 'relationshipNames');

    for (let i = 0; i < relationshipNames.belongsTo.length; i++) {
      var belongToName = relationshipNames.belongsTo[i];

      // Save related record into local store only if relationship included into projection.
      if (attrs.hasOwnProperty(belongToName)) {
        var async = isAsync(modelType, belongToName);
        if (async) {
          mainRecord.get(belongToName).then(function(relatedRecord) {
            if (!Ember.isNone(relatedRecord)) {
              promises.pushObject(createRelatedBelongsToRecord(store, relatedRecord, localAdapter, localStore, attrs[belongToName]));
            }
          });
        }
        else {
          if (isEmbedded(store, modelType, belongToName)) {
            var relatedRecord = mainRecord.get(belongToName);
            if (!Ember.isNone(relatedRecord)) {
              promises.pushObject(createRelatedBelongsToRecord(store, relatedRecord, localAdapter, localStore, attrs[belongToName]));
            }
          }
        }
      }
    }

    for (let i = 0; i < relationshipNames.hasMany.length; i++) {
      var hasManyName = relationshipNames.hasMany[i];

      // Save related records into local store only if relationship included into projection.
      if (attrs.hasOwnProperty(hasManyName)) {
        var async = isAsync(modelType, belongToName);
        if (async) {
          mainRecord.get(hasManyName).then(function(relatedRecords) {
            return promises.pushObjects(createRelatedHasManyRecords(store, relatedRecords, localAdapter, localStore, attrs[hasManyName]));
          });
        }
        else {
          if (isEmbedded(store, modelType, hasManyName)) {
            var relatedRecords = mainRecord.get(hasManyName);
            promises.pushObjects(createRelatedHasManyRecords(store, relatedRecords, localAdapter, localStore, attrs[hasManyName]));
          }
        }
      }
    }

    return RSVP.all(promises);
  }

  return createRelatedRecords(store, mainRecord, localAdapter, localStore, projection);
}<|endoftext|>


<commit_before>({
    baseUrl: './',
    paths: {
        snap: 'vendor/snap.svg/dist/snap.svg'
    },
    findNestedDependencies: true,
    optimize: 'uglify2',
    include: ['main'],
    name: "vendor/almond/almond",
    out: "main.min.js"
})
<commit_msg>add comments to build file<commit_after>/**
 * Build File for minification
 * r.js -o build.js
 */

 ({
    baseUrl: './',
    paths: {
        snap: 'vendor/snap.svg/dist/snap.svg'
    },
    findNestedDependencies: true,
    optimize: 'uglify2',
    include: ['main'],
    name: "vendor/almond/almond",
    out: "main.min.js"
})
<|endoftext|>