<commit_before>import { assign, defaults, flatten, isFunction, keys, uniq, some, orderBy } from "lodash";
import React from "react";
import Axis from "./axis";
import { Style, Transitions, Collection, Data, Domain, Events } from "victory-core";

export default {
  getData(props, childComponents) {
    if (props.data) {
      return Data.getData(props);
    }
    childComponents = childComponents || React.Children.toArray(props.children);
    return this.getDataFromChildren(childComponents);
  },

  getDefaultDomainPadding(props, axis, childComponents) {
    const horizontalChildren = childComponents.some((component) => {
      return component.props && component.props.horizontal;
    });
    const horizontal = props && props.horizontal || horizontalChildren;
    const groupComponent = childComponents.filter((child) => {
      return child.type && child.type.role && child.type.role === "group";
    });

    if (groupComponent.length < 1) {
      return undefined;
    }
    const { offset, children } = groupComponent[0].props;
    const defaultDomainPadding = horizontal ?
      { y: (offset * children.length) / 2 } :
      { x: (offset * children.length) / 2 };
    return defaultDomainPadding[axis];
  },

  getDomain(props, axis, childComponents) {
    childComponents = childComponents || React.Children.toArray(props.children);
    const propsDomain = Domain.getDomainFromProps(props, axis);
    const domainPadding = props.polar ?
      0 : this.getDefaultDomainPadding(props, axis, childComponents);
    let domain;
    if (propsDomain) {
      domain = propsDomain;
    } else {
      const dataset = (props.data || props.y) && Data.getData(props);
      const dataDomain = dataset ? Domain.getDomainFromData(props, axis, dataset) : [];
      const childDomain = this.getDomainFromChildren(props, axis, childComponents);
      const min = Collection.getMinValue([...dataDomain, ...childDomain]);
      const max = Collection.getMaxValue([...dataDomain, ...childDomain]);
      domain = [min, max];
    }
    const paddedDomain = Domain.padDomain(domain, assign({ domainPadding }, props), axis);
    return Domain.cleanDomain(paddedDomain, props, axis);
  },

  setAnimationState(props, nextProps) {
    if (!props.animate) {
      return;
    }
    if (props.animate.parentState) {
      const nodesWillExit = props.animate.parentState.nodesWillExit;
      const oldProps = nodesWillExit ? props : null;
      this.setState(defaults({ oldProps, nextProps }, props.animate.parentState));
    } else {
      const oldChildren = React.Children.toArray(props.children);
      const nextChildren = React.Children.toArray(nextProps.children);
      const isContinuous = (child) => {
        const check = (c) => c.type && c.type.continuous;
        return Array.isArray(child) ? some(child, check) : check(child);
      };

      const continuous = !props.polar && some(oldChildren, (child) => {
        return isContinuous(child) || child.props.children && isContinuous(child.props.children);
      });
      const {
        nodesWillExit,
        nodesWillEnter,
        childrenTransitions,
        nodesShouldEnter
      } = Transitions.getInitialTransitionState(oldChildren, nextChildren);

      this.setState({
        nodesWillExit,
        nodesWillEnter,
        nodesShouldEnter,
        childrenTransitions: Collection.isArrayOfArrays(childrenTransitions) ?
          childrenTransitions[0] : childrenTransitions,
        oldProps: nodesWillExit ? props : null,
        nextProps,
        continuous
      });
    }
  },

  getAllEvents(props) {
    const components = ["groupComponent", "containerComponent", "labelComponent"];
    this.componentEvents = Events.getComponentEvents(props, components);
    if (Array.isArray(this.componentEvents)) {
      return Array.isArray(props.events) ?
        this.componentEvents.concat(...props.events) : this.componentEvents;
    }
    return props.events;
  },

  getAnimationProps(props, child, index) {
    if (!props.animate) {
      return child.props.animate;
    }
    const getFilteredState = () => {
      let childrenTransitions = this.state && this.state.childrenTransitions;
      childrenTransitions = Collection.isArrayOfArrays(childrenTransitions) ?
        childrenTransitions[index] : childrenTransitions;
      return defaults({ childrenTransitions }, this.state);
    };

    let getTransitions = props.animate && props.animate.getTransitions;
    const state = getFilteredState();
    const parentState = props.animate && props.animate.parentState || state;
    if (!getTransitions) {
      const getTransitionProps = Transitions.getTransitionPropsFactory(
        props,
        state,
        (newState) => this.setState(newState)
      );
      getTransitions = (childComponent) => getTransitionProps(childComponent, index);
    }
    return defaults({ getTransitions, parentState }, props.animate, child.props.animate);
  },

  getDomainFromChildren(props, axis, childComponents) { // eslint-disable-line max-statements, complexity, max-len
    const childDomains = [];
    let childDomainsLength = 0;

    const children = childComponents
      ? childComponents.slice(0)
      : React.Children.toArray(props.children);
    let childrenLength = children.length;

    const horizontalChildren = childComponents.some((component) => {
      return component.props && component.props.horizontal;
    });
    const horizontal = props && props.horizontal || horizontalChildren.length > 0;
    const currentAxis = Axis.getCurrentAxis(axis, horizontal);
    const parentData = props.data ? Data.getData(props, axis) : undefined;
    const { polar, startAngle, endAngle, categories } = props;
    const parentProps = parentData ?
      { data: parentData, polar, startAngle, endAngle, categories } :
      { polar, startAngle, endAngle, categories };

    while (childrenLength > 0) {
      const child = children[--childrenLength];

      if (child.type && isFunction(child.type.getDomain)) {
        const sharedProps = assign({}, child.props, parentProps);
        const childDomain = child.props && child.type.getDomain(sharedProps, currentAxis);
        if (childDomain) {
          const childDomainLength = childDomain.length;
          for (let index = 0; index < childDomainLength; index++) {
            childDomains[childDomainsLength++] = childDomain[index];
          }
        }
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      }
    }
    const min = Collection.getMinValue(childDomains);
    const max = Collection.getMaxValue(childDomains);
    return childDomains.length === 0 ?
      [0, 1] : [min, max];
  },

  getDataFromChildren(props, childComponents) { // eslint-disable-line max-statements
    const getData = (childProps) => {
      const data = Data.getData(childProps);
      return Array.isArray(data) && data.length > 0 ? data : undefined;
    };

    // Reverse the child array to maintain correct order when looping over
    // children starting from the end of the array.
    const children = childComponents
      ? childComponents.slice(0).reverse()
      : React.Children.toArray(props.children).reverse();

    let childrenLength = children.length;

    const dataArr = [];
    let dataArrLength = 0;
    while (childrenLength > 0) {
      const child = children[--childrenLength];
      if (child.type && child.type.role === "axis") {
        dataArrLength = dataArrLength;
      } else if (child.type && child.type.role !== "axis" && isFunction(child.type.getData)) {
        dataArr[dataArrLength++] = child.type.getData(child.props);
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      } else {
        dataArr[dataArrLength++] = getData(child.props);
      }
    }

    return dataArr;
  },

  // Assumes data in `datasets` is sorted by `Data.getData`.
  fillInMissingData(props, datasets) {
    const { fillInMissingData } = props;
    const xMap = datasets.reduce((prev, dataset) => {
      dataset.forEach((datum) => {
        prev[datum._x instanceof Date ? datum._x.getTime() : datum._x] = true;
      });
      return prev;
    }, {});
    const xKeys = keys(xMap).map((k) => +k);
    const xArr = orderBy(xKeys);

    return datasets.map((dataset) => {
      let indexOffset = 0;
      const isDate = dataset[0] && dataset[0]._x instanceof Date;
      const filledInData = xArr.map((x, index) => {
        x = +x;
        const datum = dataset[index - indexOffset];

        if (datum) {
          const x1 = isDate ? datum._x.getTime() : datum._x;
          if (x1 === x) {
            return datum;
          } else {
            indexOffset++;
            const y = fillInMissingData ? 0 : null;
            x = isDate ? new Date(x) : x;
            return { x, y, _x: x, _y: y };
          }
        } else {
          const y = fillInMissingData ? 0 : null;
          x = isDate ? new Date(x) : x;
          return { x, y, _x: x, _y: y };
        }
      });

      return filledInData;
    });
  },

  getStackedDomain(props, axis) {
    const propsDomain = Domain.getDomainFromProps(props, axis);
    if (propsDomain) {
      return propsDomain;
    }
    const { horizontal } = props;
    const ensureZero = (domain) => {
      const isDependent = (axis === "y" && !horizontal) || (axis === "x" && horizontal);
      return isDependent ?
        [Collection.getMinValue(domain, 0), Collection.getMaxValue(domain, 0)] : domain;
    };
    const datasets = this.getDataFromChildren(props);
    return ensureZero(Domain.getDomainFromGroupedData(props, axis, datasets));
  },

  getColor(calculatedProps, child, index) {
    // check for styles first
    const { style } = calculatedProps;
    let { colorScale, color } = calculatedProps;
    if (style && style.data && style.data.fill) {
      return style.data.fill;
    }
    colorScale = child.props && child.props.colorScale ? child.props.colorScale : colorScale;
    color = child.props && child.props.color ? child.props.color : color;
    if (!colorScale && !color) {
      return undefined;
    }
    const colors = Array.isArray(colorScale) ?
      colorScale : Style.getColorScale(colorScale);
    return color || colors[index % colors.length];
  },

  getWidth(props) {
    const { datasets, scale, horizontal } = props;
    const range = horizontal ? scale.y.range() : scale.x.range();
    const extent = Math.abs(range[1] - range[0]);
    const bars = datasets.length * (datasets[0].length || 1) + 2;
    const barRatio = 0.5;
    return { width: Math.round(barRatio * extent / bars) };
  },

  getChildStyle(child, index, calculatedProps) {
    const { style, role } = calculatedProps;
    const childStyle = child.props.style || {};
    if (Array.isArray(childStyle)) {
      return childStyle;
    }
    const childRole = child.type && child.type.role;
    const defaultFill = childRole === "stack" ?
      undefined : this.getColor(calculatedProps, child, index);
    const defaultColor = childRole === "line" ?
      { fill: "none", stroke: defaultFill } : { fill: defaultFill };
    const dataWidth = role === "stack" ? {} : this.getWidth(calculatedProps);
    const dataStyle = defaults(
      {}, childStyle.data, assign({}, dataWidth, style.data, defaultColor)
    );
    const labelsStyle = defaults({}, childStyle.labels, style.labels);
    return {
      parent: style.parent,
      data: dataStyle,
      labels: labelsStyle
    };
  },

  getStringsFromCategories(childComponents, axis) { // eslint-disable-line max-statements
    const strings = [];
    let stringsLength = 0;

    const children = childComponents.slice(0).reverse();
    let childrenLength = children.length;

    while (childrenLength > 0) {
      const child = children[--childrenLength];

      if (child.props && child.props.categories) {
        const newStrings = Data.getStringsFromCategories(child.props, axis);
        const newStringsLength = newStrings.length;
        for (let index = 0; index < newStringsLength; index++) {
          strings[stringsLength++] = newStrings[index];
        }
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      }
    }

    return strings;
  },

  getStringsFromData(childComponents, axis) { // eslint-disable-line max-statements
    const strings = [];
    let stringsLength = 0;

    const children = childComponents.slice(0).reverse();
    let childrenLength = children.length;

    while (childrenLength > 0) {
      const child = children[--childrenLength];

      if (child.props && child.props.data) {
        const newStrings = Data.getStringsFromData(child.props, axis);
        const newStringsLength = newStrings.length;
        for (let index = 0; index < newStringsLength; index++) {
          strings[stringsLength++] = newStrings[index];
        }
      } else if (child.type && isFunction(child.type.getData)) {
        const data = flatten(child.type.getData(child.props));
        const attr = axis === "x" ? "xName" : "yName";
        for (let index = 0; index < data.length; index++) {
          const datum = data[index];
          if (datum[attr]) {
            strings[stringsLength++] = datum[attr];
          }
        }
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      }
    }

    return strings;
  },

  getStringsFromChildren(props, axis, childComponents) {
    childComponents = childComponents || React.Children.toArray(props.children);
    const axisComponent = Axis.getAxisComponent(childComponents, axis);
    const axisStrings = axisComponent ? Data.getStringsFromAxes(axisComponent.props, axis) : [];
    const categoryStrings = this.getStringsFromCategories(childComponents, axis);
    const dataStrings = this.getStringsFromData(childComponents, axis);
    return uniq(flatten([...categoryStrings, ...dataStrings, ...axisStrings]));
  },

  getCategories(props, axis) {
    const categories = Data.getCategories(props, axis) ||
      this.getStringsFromChildren(props, axis);
    return categories.length > 0 ? categories : undefined;
  },

  getY0(datum, index, calculatedProps) {
    if (datum.y0) {
      return datum.y0;
    }
    const { datasets } = calculatedProps;
    const y = datum._y;
    const previousDatasets = datasets.slice(0, index);
    const previousPoints = previousDatasets.reduce((prev, dataset) => {
      return prev.concat(dataset
        .filter((previousDatum) => datum._x instanceof Date
          ? previousDatum._x.getTime() === datum._x.getTime()
          : previousDatum._x === datum._x)
        .map((previousDatum) => previousDatum._y || 0)
      );
    }, []);
    const y0 = previousPoints.length && previousPoints.reduce((memo, value) => {
      const sameSign = (y < 0 && value < 0) || (y >= 0 && value >= 0);
      return sameSign ? +value + memo : memo;
    }, 0);
    return previousPoints.some((point) => point instanceof Date) ? new Date(y0) : y0;
  }
};
<commit_msg>support minDomain maxDomain on wrapper components<commit_after>import { assign, defaults, flatten, isFunction, keys, uniq, some, orderBy } from "lodash";
import React from "react";
import Axis from "./axis";
import { Style, Transitions, Collection, Data, Domain, Events } from "victory-core";

export default {
  getData(props, childComponents) {
    if (props.data) {
      return Data.getData(props);
    }
    childComponents = childComponents || React.Children.toArray(props.children);
    return this.getDataFromChildren(childComponents);
  },

  getDefaultDomainPadding(props, axis, childComponents) {
    const horizontalChildren = childComponents.some((component) => {
      return component.props && component.props.horizontal;
    });
    const horizontal = props && props.horizontal || horizontalChildren;
    const groupComponent = childComponents.filter((child) => {
      return child.type && child.type.role && child.type.role === "group";
    });

    if (groupComponent.length < 1) {
      return undefined;
    }
    const { offset, children } = groupComponent[0].props;
    const defaultDomainPadding = horizontal ?
      { y: (offset * children.length) / 2 } :
      { x: (offset * children.length) / 2 };
    return defaultDomainPadding[axis];
  },

  // eslint-disable-next-line max-statements
  getDomain(props, axis, childComponents) {
    childComponents = childComponents || React.Children.toArray(props.children);
    const propsDomain = Domain.getDomainFromProps(props, axis);
    const minDomain = Domain.getMinFromProps(props, axis);
    const maxDomain = Domain.getMaxFromProps(props, axis);
    const domainPadding = props.polar ?
      0 : this.getDefaultDomainPadding(props, axis, childComponents);
    let domain;
    if (propsDomain || minDomain !== undefined && maxDomain !== undefined) {
      domain = propsDomain || Domain.getDomainFromMinMax(minDomain, maxDomain);
    } else {
      const dataset = (props.data || props.y) && Data.getData(props);
      const dataDomain = dataset ? Domain.getDomainFromData(props, axis, dataset) : [];
      const childDomain = this.getDomainFromChildren(props, axis, childComponents);
      const min = minDomain || Collection.getMinValue([...dataDomain, ...childDomain]);
      const max = maxDomain || Collection.getMaxValue([...dataDomain, ...childDomain]);
      domain = Domain.getDomainFromMinMax(min, max);
    }
    const paddedDomain = Domain.padDomain(domain, assign({ domainPadding }, props), axis);
    return Domain.cleanDomain(paddedDomain, props, axis);
  },

  setAnimationState(props, nextProps) {
    if (!props.animate) {
      return;
    }
    if (props.animate.parentState) {
      const nodesWillExit = props.animate.parentState.nodesWillExit;
      const oldProps = nodesWillExit ? props : null;
      this.setState(defaults({ oldProps, nextProps }, props.animate.parentState));
    } else {
      const oldChildren = React.Children.toArray(props.children);
      const nextChildren = React.Children.toArray(nextProps.children);
      const isContinuous = (child) => {
        const check = (c) => c.type && c.type.continuous;
        return Array.isArray(child) ? some(child, check) : check(child);
      };

      const continuous = !props.polar && some(oldChildren, (child) => {
        return isContinuous(child) || child.props.children && isContinuous(child.props.children);
      });
      const {
        nodesWillExit,
        nodesWillEnter,
        childrenTransitions,
        nodesShouldEnter
      } = Transitions.getInitialTransitionState(oldChildren, nextChildren);

      this.setState({
        nodesWillExit,
        nodesWillEnter,
        nodesShouldEnter,
        childrenTransitions: Collection.isArrayOfArrays(childrenTransitions) ?
          childrenTransitions[0] : childrenTransitions,
        oldProps: nodesWillExit ? props : null,
        nextProps,
        continuous
      });
    }
  },

  getAllEvents(props) {
    const components = ["groupComponent", "containerComponent", "labelComponent"];
    this.componentEvents = Events.getComponentEvents(props, components);
    if (Array.isArray(this.componentEvents)) {
      return Array.isArray(props.events) ?
        this.componentEvents.concat(...props.events) : this.componentEvents;
    }
    return props.events;
  },

  getAnimationProps(props, child, index) {
    if (!props.animate) {
      return child.props.animate;
    }
    const getFilteredState = () => {
      let childrenTransitions = this.state && this.state.childrenTransitions;
      childrenTransitions = Collection.isArrayOfArrays(childrenTransitions) ?
        childrenTransitions[index] : childrenTransitions;
      return defaults({ childrenTransitions }, this.state);
    };

    let getTransitions = props.animate && props.animate.getTransitions;
    const state = getFilteredState();
    const parentState = props.animate && props.animate.parentState || state;
    if (!getTransitions) {
      const getTransitionProps = Transitions.getTransitionPropsFactory(
        props,
        state,
        (newState) => this.setState(newState)
      );
      getTransitions = (childComponent) => getTransitionProps(childComponent, index);
    }
    return defaults({ getTransitions, parentState }, props.animate, child.props.animate);
  },

  getDomainFromChildren(props, axis, childComponents) { // eslint-disable-line max-statements, complexity, max-len
    const childDomains = [];
    let childDomainsLength = 0;

    const children = childComponents
      ? childComponents.slice(0)
      : React.Children.toArray(props.children);
    let childrenLength = children.length;

    const horizontalChildren = childComponents.some((component) => {
      return component.props && component.props.horizontal;
    });
    const horizontal = props && props.horizontal || horizontalChildren.length > 0;
    const currentAxis = Axis.getCurrentAxis(axis, horizontal);
    const parentData = props.data ? Data.getData(props, axis) : undefined;
    const { polar, startAngle, endAngle, categories, minDomain, maxDomain } = props;
    const baseParentProps = { polar, startAngle, endAngle, categories, minDomain, maxDomain };
    const parentProps = parentData ?
      assign(baseParentProps, { data: parentData }) : baseParentProps;

    while (childrenLength > 0) {
      const child = children[--childrenLength];

      if (child.type && isFunction(child.type.getDomain)) {
        const sharedProps = assign({}, child.props, parentProps);
        const childDomain = child.props && child.type.getDomain(sharedProps, currentAxis);
        if (childDomain) {
          const childDomainLength = childDomain.length;
          for (let index = 0; index < childDomainLength; index++) {
            childDomains[childDomainsLength++] = childDomain[index];
          }
        }
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      }
    }
    const min = Collection.getMinValue(childDomains);
    const max = Collection.getMaxValue(childDomains);
    return childDomains.length === 0 ?
      [0, 1] : [min, max];
  },

  getDataFromChildren(props, childComponents) { // eslint-disable-line max-statements
    const getData = (childProps) => {
      const data = Data.getData(childProps);
      return Array.isArray(data) && data.length > 0 ? data : undefined;
    };

    // Reverse the child array to maintain correct order when looping over
    // children starting from the end of the array.
    const children = childComponents
      ? childComponents.slice(0).reverse()
      : React.Children.toArray(props.children).reverse();

    let childrenLength = children.length;

    const dataArr = [];
    let dataArrLength = 0;
    while (childrenLength > 0) {
      const child = children[--childrenLength];
      if (child.type && child.type.role === "axis") {
        dataArrLength = dataArrLength;
      } else if (child.type && child.type.role !== "axis" && isFunction(child.type.getData)) {
        dataArr[dataArrLength++] = child.type.getData(child.props);
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      } else {
        dataArr[dataArrLength++] = getData(child.props);
      }
    }

    return dataArr;
  },

  // Assumes data in `datasets` is sorted by `Data.getData`.
  fillInMissingData(props, datasets) {
    const { fillInMissingData } = props;
    const xMap = datasets.reduce((prev, dataset) => {
      dataset.forEach((datum) => {
        prev[datum._x instanceof Date ? datum._x.getTime() : datum._x] = true;
      });
      return prev;
    }, {});
    const xKeys = keys(xMap).map((k) => +k);
    const xArr = orderBy(xKeys);

    return datasets.map((dataset) => {
      let indexOffset = 0;
      const isDate = dataset[0] && dataset[0]._x instanceof Date;
      const filledInData = xArr.map((x, index) => {
        x = +x;
        const datum = dataset[index - indexOffset];

        if (datum) {
          const x1 = isDate ? datum._x.getTime() : datum._x;
          if (x1 === x) {
            return datum;
          } else {
            indexOffset++;
            const y = fillInMissingData ? 0 : null;
            x = isDate ? new Date(x) : x;
            return { x, y, _x: x, _y: y };
          }
        } else {
          const y = fillInMissingData ? 0 : null;
          x = isDate ? new Date(x) : x;
          return { x, y, _x: x, _y: y };
        }
      });

      return filledInData;
    });
  },

  getStackedDomain(props, axis) {
    const propsDomain = Domain.getDomainFromProps(props, axis);
    if (propsDomain) {
      return propsDomain;
    }
    const { horizontal } = props;
    const ensureZero = (domain) => {
      const isDependent = (axis === "y" && !horizontal) || (axis === "x" && horizontal);
      return isDependent ?
        [Collection.getMinValue(domain, 0), Collection.getMaxValue(domain, 0)] : domain;
    };
    const datasets = this.getDataFromChildren(props);
    return ensureZero(Domain.getDomainFromGroupedData(props, axis, datasets));
  },

  getColor(calculatedProps, child, index) {
    // check for styles first
    const { style } = calculatedProps;
    let { colorScale, color } = calculatedProps;
    if (style && style.data && style.data.fill) {
      return style.data.fill;
    }
    colorScale = child.props && child.props.colorScale ? child.props.colorScale : colorScale;
    color = child.props && child.props.color ? child.props.color : color;
    if (!colorScale && !color) {
      return undefined;
    }
    const colors = Array.isArray(colorScale) ?
      colorScale : Style.getColorScale(colorScale);
    return color || colors[index % colors.length];
  },

  getWidth(props) {
    const { datasets, scale, horizontal } = props;
    const range = horizontal ? scale.y.range() : scale.x.range();
    const extent = Math.abs(range[1] - range[0]);
    const bars = datasets.length * (datasets[0].length || 1) + 2;
    const barRatio = 0.5;
    return { width: Math.round(barRatio * extent / bars) };
  },

  getChildStyle(child, index, calculatedProps) {
    const { style, role } = calculatedProps;
    const childStyle = child.props.style || {};
    if (Array.isArray(childStyle)) {
      return childStyle;
    }
    const childRole = child.type && child.type.role;
    const defaultFill = childRole === "stack" ?
      undefined : this.getColor(calculatedProps, child, index);
    const defaultColor = childRole === "line" ?
      { fill: "none", stroke: defaultFill } : { fill: defaultFill };
    const dataWidth = role === "stack" ? {} : this.getWidth(calculatedProps);
    const dataStyle = defaults(
      {}, childStyle.data, assign({}, dataWidth, style.data, defaultColor)
    );
    const labelsStyle = defaults({}, childStyle.labels, style.labels);
    return {
      parent: style.parent,
      data: dataStyle,
      labels: labelsStyle
    };
  },

  getStringsFromCategories(childComponents, axis) { // eslint-disable-line max-statements
    const strings = [];
    let stringsLength = 0;

    const children = childComponents.slice(0).reverse();
    let childrenLength = children.length;

    while (childrenLength > 0) {
      const child = children[--childrenLength];

      if (child.props && child.props.categories) {
        const newStrings = Data.getStringsFromCategories(child.props, axis);
        const newStringsLength = newStrings.length;
        for (let index = 0; index < newStringsLength; index++) {
          strings[stringsLength++] = newStrings[index];
        }
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      }
    }

    return strings;
  },

  getStringsFromData(childComponents, axis) { // eslint-disable-line max-statements
    const strings = [];
    let stringsLength = 0;

    const children = childComponents.slice(0).reverse();
    let childrenLength = children.length;

    while (childrenLength > 0) {
      const child = children[--childrenLength];

      if (child.props && child.props.data) {
        const newStrings = Data.getStringsFromData(child.props, axis);
        const newStringsLength = newStrings.length;
        for (let index = 0; index < newStringsLength; index++) {
          strings[stringsLength++] = newStrings[index];
        }
      } else if (child.type && isFunction(child.type.getData)) {
        const data = flatten(child.type.getData(child.props));
        const attr = axis === "x" ? "xName" : "yName";
        for (let index = 0; index < data.length; index++) {
          const datum = data[index];
          if (datum[attr]) {
            strings[stringsLength++] = datum[attr];
          }
        }
      } else if (child.props && child.props.children) {
        const newChildren = React.Children.toArray(child.props.children);
        const newChildrenLength = newChildren.length;
        for (let index = 0; index < newChildrenLength; index++) {
          children[childrenLength++] = newChildren[index];
        }
      }
    }

    return strings;
  },

  getStringsFromChildren(props, axis, childComponents) {
    childComponents = childComponents || React.Children.toArray(props.children);
    const axisComponent = Axis.getAxisComponent(childComponents, axis);
    const axisStrings = axisComponent ? Data.getStringsFromAxes(axisComponent.props, axis) : [];
    const categoryStrings = this.getStringsFromCategories(childComponents, axis);
    const dataStrings = this.getStringsFromData(childComponents, axis);
    return uniq(flatten([...categoryStrings, ...dataStrings, ...axisStrings]));
  },

  getCategories(props, axis) {
    const categories = Data.getCategories(props, axis) ||
      this.getStringsFromChildren(props, axis);
    return categories.length > 0 ? categories : undefined;
  },

  getY0(datum, index, calculatedProps) {
    if (datum.y0) {
      return datum.y0;
    }
    const { datasets } = calculatedProps;
    const y = datum._y;
    const previousDatasets = datasets.slice(0, index);
    const previousPoints = previousDatasets.reduce((prev, dataset) => {
      return prev.concat(dataset
        .filter((previousDatum) => datum._x instanceof Date
          ? previousDatum._x.getTime() === datum._x.getTime()
          : previousDatum._x === datum._x)
        .map((previousDatum) => previousDatum._y || 0)
      );
    }, []);
    const y0 = previousPoints.length && previousPoints.reduce((memo, value) => {
      const sameSign = (y < 0 && value < 0) || (y >= 0 && value >= 0);
      return sameSign ? +value + memo : memo;
    }, 0);
    return previousPoints.some((point) => point instanceof Date) ? new Date(y0) : y0;
  }
};
<|endoftext|>


<commit_before>// Export the i18next object for **CommonJS**.
// If we're not in CommonJS, add `i18n` to the
// global object or to jquery.
if (typeof module !== 'undefined' && module.exports) {
    module.exports = i18n;
} else {
    if ($) {
        $.i18n = $.i18n || i18n;
    }

    root.i18n = root.i18n || i18n;
}<commit_msg>append to jquery if available in browserify<commit_after>// Export the i18next object for **CommonJS**.
// If we're not in CommonJS, add `i18n` to the
// global object or to jquery.
if (typeof module !== 'undefined' && module.exports) {
    if (!$) {
      try {
        $ = require('jquery');
      } catch(e) {
        // just ignore
      }
    }
    if ($) {
        $.i18n = $.i18n || i18n;
    }
    module.exports = i18n;
} else {
    if ($) {
        $.i18n = $.i18n || i18n;
    }

    root.i18n = root.i18n || i18n;
}<|endoftext|>


<commit_before>/* eslint no-underscore-dangle: 0 */
import { AppState, NetInfo } from 'react-native'; // eslint-disable-line
import LegacyDetectNetwork from './detectNetwork.native.legacy';

class DetectNetwork {
  constructor(callback) {
    this._reach = null;
    this._isConnected = null;
    this._isConnectionExpensive = null;
    this._callback = callback;

    this._init();
    this._addListeners();
  }

  /**
   * Check props for changes
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {boolean} - Whether the connection reachability or the connection props have changed
   * @private
   */
  _hasChanged = reach => {
    if (this._reach !== reach) {
      return true;
    }
    if (this._isConnected !== this._getConnection(reach)) {
      return true;
    }
    return false;
  };
  /**
   * Sets the connection reachability prop
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {void}
   * @private
   */
  _setReach = reach => {
    this._reach = reach;
    this._isConnected = this._getConnection(reach);
  };
  /**
   * Gets the isConnected prop depending on the connection reachability's value
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {void}
   * @private
   */
  _getConnection = reach => reach !== 'none' && reach !== 'unknown';
  /**
   * Sets the isConnectionExpensive prop
   * @returns {Promise.<void>} Resolves to true if connection is expensive,
   * false if not, and null if not supported.
   * @private
   */
  _setIsConnectionExpensive = async () => {
    try {
      this._isConnectionExpensive = await NetInfo.isConnectionExpensive();
    } catch (err) {
      // err means that isConnectionExpensive is not supported in iOS
      this._isConnectionExpensive = null;
    }
  };
  /**
   * Fetches and sets the connection reachability and the isConnected props
   * @returns {Promise.<void>} Resolves when the props have been
   * initialized and update.
   * @private
   */
  _init = async () => {
    const connectionInfo = await NetInfo.getConnectionInfo();
    this._update(connectionInfo.type);
  };
  /**
   * Check changes on props and store and dispatch if neccesary
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {void}
   * @private
   */
  _update = reach => {
    if (this._hasChanged(reach)) {
      this._setReach(reach);
      this._dispatch();
    }
  };

  /**
   * Adds listeners for when connection reachability and app state changes to update props
   * @returns {void}
   * @private
   */
  _addListeners() {
    NetInfo.addEventListener('connectionChange', connectionInfo => {
      this._update(connectionInfo.type);
    });
    AppState.addEventListener('change', this._init);
  }

  /**
   * Executes the given callback to update redux's store with the new internal props
   * @returns {Promise.<void>} Resolves after fetching the isConnectionExpensive
   * and dispatches actions
   * @private
   */
  _dispatch = async () => {
    await this._setIsConnectionExpensive();
    this._callback({
      online: this._isConnected,
      netInfo: {
        isConnectionExpensive: this._isConnectionExpensive,
        reach: this._reach
      }
    });
  };
}

const isLegacy = typeof NetInfo.getConnectionInfo === 'undefined';
export default callback => (isLegacy ? LegacyDetectNetwork(callback) : DetectNetwork(callback))
<commit_msg>Fixed linting error<commit_after>/* eslint no-underscore-dangle: 0 */
import { AppState, NetInfo } from 'react-native'; // eslint-disable-line
import LegacyDetectNetwork from './detectNetwork.native.legacy';

class DetectNetwork {
  constructor(callback) {
    this._reach = null;
    this._isConnected = null;
    this._isConnectionExpensive = null;
    this._callback = callback;

    this._init();
    this._addListeners();
  }

  /**
   * Check props for changes
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {boolean} - Whether the connection reachability or the connection props have changed
   * @private
   */
  _hasChanged = reach => {
    if (this._reach !== reach) {
      return true;
    }
    if (this._isConnected !== this._getConnection(reach)) {
      return true;
    }
    return false;
  };
  /**
   * Sets the connection reachability prop
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {void}
   * @private
   */
  _setReach = reach => {
    this._reach = reach;
    this._isConnected = this._getConnection(reach);
  };
  /**
   * Gets the isConnected prop depending on the connection reachability's value
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {void}
   * @private
   */
  _getConnection = reach => reach !== 'none' && reach !== 'unknown';
  /**
   * Sets the isConnectionExpensive prop
   * @returns {Promise.<void>} Resolves to true if connection is expensive,
   * false if not, and null if not supported.
   * @private
   */
  _setIsConnectionExpensive = async () => {
    try {
      this._isConnectionExpensive = await NetInfo.isConnectionExpensive();
    } catch (err) {
      // err means that isConnectionExpensive is not supported in iOS
      this._isConnectionExpensive = null;
    }
  };
  /**
   * Fetches and sets the connection reachability and the isConnected props
   * @returns {Promise.<void>} Resolves when the props have been
   * initialized and update.
   * @private
   */
  _init = async () => {
    const connectionInfo = await NetInfo.getConnectionInfo();
    this._update(connectionInfo.type);
  };
  /**
   * Check changes on props and store and dispatch if neccesary
   * @param {string} reach - connection reachability.
   *     - Cross-platform: [none, wifi, cellular, unknown]
   *     - Android: [bluetooth, ethernet, wimax]
   * @returns {void}
   * @private
   */
  _update = reach => {
    if (this._hasChanged(reach)) {
      this._setReach(reach);
      this._dispatch();
    }
  };

  /**
   * Adds listeners for when connection reachability and app state changes to update props
   * @returns {void}
   * @private
   */
  _addListeners() {
    NetInfo.addEventListener('connectionChange', connectionInfo => {
      this._update(connectionInfo.type);
    });
    AppState.addEventListener('change', this._init);
  }

  /**
   * Executes the given callback to update redux's store with the new internal props
   * @returns {Promise.<void>} Resolves after fetching the isConnectionExpensive
   * and dispatches actions
   * @private
   */
  _dispatch = async () => {
    await this._setIsConnectionExpensive();
    this._callback({
      online: this._isConnected,
      netInfo: {
        isConnectionExpensive: this._isConnectionExpensive,
        reach: this._reach
      }
    });
  };
}

const isLegacy = typeof NetInfo.getConnectionInfo === 'undefined';
export default callback =>
  isLegacy ? LegacyDetectNetwork(callback) : DetectNetwork(callback);
<|endoftext|>


<commit_before> rec.name = "UserUser"
 rec.module = org.grouplens.lenskit.knn.user.UserRecommenderModule
 rec.module.knn.similarityDamping = 50
 rec.module.core.baseline = org.grouplens.lenskit.baseline.ItemUserMeanPredictor
<commit_msg>Update user-user script to provide an implementation<commit_after> rec.name = "UserUser"
 rec.module = org.grouplens.lenskit.knn.user.UserRecommenderModule
 rec.module.variant = org.grouplens.lenskit.knn.user.SimpleUserUserRatingRecommender
 rec.module.knn.similarityDamping = 50
 rec.module.core.baseline = org.grouplens.lenskit.baseline.ItemUserMeanPredictor
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _collectionNames = require('./collectionNames');

var _collectionNames2 = _interopRequireDefault(_collectionNames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// getByID, deleteByID and update uses model.deviceID as ID for querying
var DeviceAttributeDatabaseRepository = function DeviceAttributeDatabaseRepository(database, permissionManager) {
  var _this = this;

  (0, _classCallCheck3.default)(this, DeviceAttributeDatabaseRepository);
  this._collectionName = _collectionNames2.default.DEVICE_ATTRIBUTES;
  this.create = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
    return _regenerator2.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            throw new Error('The method is not implemented');

          case 1:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, _this);
  }));

  this.deleteByID = function () {
    var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(deviceID) {
      return _regenerator2.default.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return _this._database.remove(_this._collectionName, { deviceID: deviceID });

            case 2:
              return _context2.abrupt('return', _context2.sent);

            case 3:
            case 'end':
              return _context2.stop();
          }
        }
      }, _callee2, _this);
    }));

    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  this.getAll = function () {
    var _ref3 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
      var userID = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var query;
      return _regenerator2.default.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              query = userID ? { ownerID: userID } : {};
              _context3.next = 3;
              return _this._database.find(_this._collectionName, query);

            case 3:
              _context3.t0 = _this._parseVariables;
              return _context3.abrupt('return', _context3.sent.map(_context3.t0));

            case 5:
            case 'end':
              return _context3.stop();
          }
        }
      }, _callee3, _this);
    }));

    return function () {
      return _ref3.apply(this, arguments);
    };
  }();

  this.getByID = function () {
    var _ref4 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4(deviceID) {
      return _regenerator2.default.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.t0 = _this;
              _context4.next = 3;
              return _this._database.findOne(_this._collectionName, { deviceID: deviceID });

            case 3:
              _context4.t1 = _context4.sent;
              return _context4.abrupt('return', _context4.t0._parseVariables.call(_context4.t0, _context4.t1));

            case 5:
            case 'end':
              return _context4.stop();
          }
        }
      }, _callee4, _this);
    }));

    return function (_x3) {
      return _ref4.apply(this, arguments);
    };
  }();

  this.updateByID = function () {
    var _ref5 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee5(deviceID, _ref6) {
      var variables = _ref6.variables,
          props = (0, _objectWithoutProperties3.default)(_ref6, ['variables']);
      var attributesToSave;
      return _regenerator2.default.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              attributesToSave = (0, _extends3.default)({}, props, {
                variables: variables ? (0, _stringify2.default)(variables) : undefined
              });
              _context5.next = 3;
              return _this._database.findAndModify(_this._collectionName, { deviceID: deviceID }, { $set: (0, _extends3.default)({}, attributesToSave, { timeStamp: new Date() }) });

            case 3:
              return _context5.abrupt('return', _context5.sent);

            case 4:
            case 'end':
              return _context5.stop();
          }
        }
      }, _callee5, _this);
    }));

    return function (_x4, _x5) {
      return _ref5.apply(this, arguments);
    };
  }();

  this._parseVariables = function (attributesFromDB) {
    if (!attributesFromDB) {
      return null;
    }

    var variables = attributesFromDB.variables;

    return (0, _extends3.default)({}, attributesFromDB, {
      variables: variables ? JSON.parse(variables) : undefined
    });
  };

  this._database = database;
  this._permissionManager = permissionManager;
}

// mongo and neDB don't support dots in variables names
// but some of the server users want to have dots in their device var names
// so we have to stringify them and parse back.
;

exports.default = DeviceAttributeDatabaseRepository;<commit_msg>build deviceAttributesDatabaseRepository.js<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _collectionNames = require('./collectionNames');

var _collectionNames2 = _interopRequireDefault(_collectionNames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// getByID, deleteByID and update uses model.deviceID as ID for querying
var DeviceAttributeDatabaseRepository = function DeviceAttributeDatabaseRepository(database, permissionManager) {
  var _this = this;

  (0, _classCallCheck3.default)(this, DeviceAttributeDatabaseRepository);
  this._collectionName = _collectionNames2.default.DEVICE_ATTRIBUTES;
  this.create = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
    return _regenerator2.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            throw new Error('The method is not implemented');

          case 1:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, _this);
  }));

  this.deleteByID = function () {
    var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(deviceID) {
      return _regenerator2.default.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return _this._database.remove(_this._collectionName, { deviceID: deviceID });

            case 2:
              return _context2.abrupt('return', _context2.sent);

            case 3:
            case 'end':
              return _context2.stop();
          }
        }
      }, _callee2, _this);
    }));

    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  this.getAll = function () {
    var _ref3 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
      var userID = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var query;
      return _regenerator2.default.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              query = userID ? { ownerID: userID } : {};
              _context3.next = 3;
              return _this._database.find(_this._collectionName, query);

            case 3:
              _context3.t0 = _this._parseVariables;
              return _context3.abrupt('return', _context3.sent.map(_context3.t0));

            case 5:
            case 'end':
              return _context3.stop();
          }
        }
      }, _callee3, _this);
    }));

    return function () {
      return _ref3.apply(this, arguments);
    };
  }();

  this.getByID = function () {
    var _ref4 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4(deviceID) {
      return _regenerator2.default.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.t0 = _this;
              _context4.next = 3;
              return _this._database.findOne(_this._collectionName, { deviceID: deviceID });

            case 3:
              _context4.t1 = _context4.sent;
              return _context4.abrupt('return', _context4.t0._parseVariables.call(_context4.t0, _context4.t1));

            case 5:
            case 'end':
              return _context4.stop();
          }
        }
      }, _callee4, _this);
    }));

    return function (_x3) {
      return _ref4.apply(this, arguments);
    };
  }();

  this.updateByID = function () {
    var _ref5 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee5(deviceID, _ref6) {
      var variables = _ref6.variables,
          props = (0, _objectWithoutProperties3.default)(_ref6, ['variables']);
      var attributesToSave;
      return _regenerator2.default.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              attributesToSave = (0, _extends3.default)({}, props, {
                variables: variables ? (0, _stringify2.default)(variables) : undefined
              });
              _context5.next = 3;
              return _this._database.findAndModify(_this._collectionName, { deviceID: deviceID }, { $set: (0, _extends3.default)({}, attributesToSave, { timeStamp: new Date() }) });

            case 3:
              return _context5.abrupt('return', _context5.sent);

            case 4:
            case 'end':
              return _context5.stop();
          }
        }
      }, _callee5, _this);
    }));

    return function (_x4, _x5) {
      return _ref5.apply(this, arguments);
    };
  }();

  this._parseVariables = function (attributesFromDB) {
    if (!attributesFromDB) {
      return null;
    }

    var variables = attributesFromDB.variables;

    try {
      return (0, _extends3.default)({}, attributesFromDB, {
        variables: variables ? JSON.parse(variables) : undefined
      });
    } catch (ignore) {
      return attributesFromDB;
    }
  };

  this._database = database;
  this._permissionManager = permissionManager;
}

// mongo and neDB don't support dots in variables names
// but some of the server users want to have dots in their device var names
// so we have to stringify them and parse back.
;

exports.default = DeviceAttributeDatabaseRepository;<|endoftext|>


<commit_before>import express from 'express';
import favicon from 'serve-favicon';
import { applyMiddleware } from './applyMiddleware';

const mainApp = express();

applyMiddleware(mainApp);

mainApp.use(express.static('public'));
mainApp.use(favicon('public/favicon.ico'));

export default mainApp;
<commit_msg>minor<commit_after>import express from 'express';
import favicon from 'serve-favicon';
import { applyMiddleware } from './applyMiddleware';

const mainApp = express();

mainApp.use(express.static('public'));
mainApp.use(favicon('public/favicon.ico'));

applyMiddleware(mainApp);

export default mainApp;
<|endoftext|>


<commit_before>'use strict';

var React = require('react/addons');

var PlayerKeyStore = require('../stores/PlayerKeyStore.js');
var PlayerKeyActions = require('../actions/PlayerKeyActions.js');

function getPlayerKeySettingsState() {
  return {
    set: PlayerKeyStore.isKeySet(),
    key: PlayerKeyStore.getKey()
  };
}

var Settings = React.createClass({
  getInitialState: function() {
    return getPlayerKeySettingsState();
  },

  render: function() {
    return (

        <PlayerKeyForm />
        <PushToPlayerKeyForm />

    );
  }
});

function randomString(len)
{
  var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var res = "";
  for (var i = 0; i < len; i++) {
    res += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
  }
  return res;
}

function getPlayerKeyFormState() {
  return {
    set: PlayerKeyStore.isKeySet(),
    key: PlayerKeyStore.getKey(),
  };
}

var PlayerKeyForm = React.createClass({
  getInitialState: function() {
    return getPlayerKeyFormState();
  },

  componentDidMount: function() {
    PlayerKeyStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    PlayerKeyStore.removeChangeListener(this._onChange);
  },

  render: function() {
    var form = (
      <form onSubmit={this._onSetSubmit}>
        <input type="text" placeholder="Enter a player key" size="50" value={this.state.key} onChange={this._handleChange} />
        <button className={(!this.state.key) ? "" : "set"}>Set</button> or <button onClick={this._onGenerate}>Generate</button>
      </form>
    );

    if (this.state.set) {
      form = (
        <form onSubmit={this._onResetSubmit}>
          <input type="text" size="50" value={this.state.key} disabled />
          <button className="reset">Reset</button>
        </form>
      );
    }

    return (

Player Key

        A Player Key uniquely identifies each music player and can be used to control it.
        {form}

    );
  },

  _onGenerate: function(e) {
    e.preventDefault();
    PlayerKeyActions.setKey(randomString(30));
  },

  _onChange: function() {
    this.setState(getPlayerKeyFormState());
  },

  _handleChange: function(event) {
     this.setState({key: event.target.value});
  },

  _onResetSubmit: function(e) {
    e.preventDefault();
    PlayerKeyActions.setKey("");
  },

  _onSetSubmit: function(e) {
    e.preventDefault();
    PlayerKeyActions.setKey(this.state.key);
  }
});

function getPushKeyFormState() {
  return {
    key: PlayerKeyStore.getPushKey(),
    set: PlayerKeyStore.isPushKeySet(),
  };
}

var PushToPlayerKeyForm = React.createClass({
  getInitialState: function() {
    return getPushKeyFormState();
  },

  componentDidMount: function() {
    PlayerKeyStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    PlayerKeyStore.removeChangeListener(this._onChange);
  },

  render: function() {
    var form = (
      <form onSubmit={this._onSetSubmit}>
        <input type="text" placeholder="Enter a player key" size="50" value={this.state.key} onChange={this._handleChange} />
        <button className={(!this.state.key) ? "" : "set"}>Set</button>
      </form>
    );

    if (this.state.set) {
      form = (
        <form onSubmit={this._onResetSubmit}>
          <input type="text" size="50" value={this.state.key} disabled />
          <button className="reset">Reset</button>
        </form>
      );
    }

    return (

Push Commands to a Player Key

        Set a Player Key to push all UI commands to (instead of the UI player).
        {form}

    );
  },

  _onChange: function() {
    this.setState(getPushKeyFormState());
  },

  _handleChange: function(event) {
     this.setState({key: event.target.value});
  },

  _onResetSubmit: function(e) {
    e.preventDefault();
    PlayerKeyActions.setPushKey("");
  },

  _onSetSubmit: function(e) {
    e.preventDefault();
    PlayerKeyActions.setPushKey(this.state.key);
  }
});

module.exports = Settings;
<commit_msg>[es6] Rewritten Settings component<commit_after>'use strict';

import React from 'react/addons';

import PlayerKeyStore from '../stores/PlayerKeyStore.js';
import PlayerKeyActions from '../actions/PlayerKeyActions.js';

function getPlayerKeySettingsState() {
  return {
    set: PlayerKeyStore.isKeySet(),
    key: PlayerKeyStore.getKey()
  };
}

export default class Settings extends React.Component {
  constructor(props) {
    super(props);

    this.state = getPlayerKeySettingsState();
  }

  render() {
    return (

        <PlayerKeyForm />
        <PushToPlayerKeyForm />

    );
  }
}

function randomString(len)
{
  var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var res = "";
  for (var i = 0; i < len; i++) {
    res += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
  }
  return res;
}

function getPlayerKeyFormState() {
  return {
    set: PlayerKeyStore.isKeySet(),
    key: PlayerKeyStore.getKey(),
  };
}

class PlayerKeyForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = getPlayerKeyFormState();
    this._onChange = this._onChange.bind(this);
    this._handleChange = this._handleChange.bind(this);
    this._onSetSubmit = this._onSetSubmit.bind(this);
  }

  componentDidMount() {
    PlayerKeyStore.addChangeListener(this._onChange);
  }

  componentWillUnmount() {
    PlayerKeyStore.removeChangeListener(this._onChange);
  }

  render() {
    var form = (
      <form onSubmit={this._onSetSubmit}>
        <input type="text" placeholder="Enter a player key" size="50" value={this.state.key} onChange={this._handleChange} />
        <button className={(!this.state.key) ? "" : "set"}>Set</button> or <button onClick={this._onGenerate}>Generate</button>
      </form>
    );

    if (this.state.set) {
      form = (
        <form onSubmit={this._onResetSubmit}>
          <input type="text" size="50" value={this.state.key} disabled />
          <button className="reset">Reset</button>
        </form>
      );
    }

    return (

Player Key

        A Player Key uniquely identifies each music player and can be used to control it.
        {form}

    );
  }

  _onGenerate(e) {
    e.preventDefault();
    PlayerKeyActions.setKey(randomString(30));
  }

  _onChange() {
    this.setState(getPlayerKeyFormState());
  }

  _handleChange(event) {
     this.setState({key: event.target.value});
  }

  _onResetSubmit(e) {
    e.preventDefault();
    PlayerKeyActions.setKey("");
  }

  _onSetSubmit(e) {
    e.preventDefault();
    PlayerKeyActions.setKey(this.state.key);
  }
}

function getPushKeyFormState() {
  return {
    key: PlayerKeyStore.getPushKey(),
    set: PlayerKeyStore.isPushKeySet(),
  };
}

class PushToPlayerKeyForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = getPushKeyFormState();
    this._onChange = this._onChange.bind(this);
    this._handleChange = this._handleChange.bind(this);
    this._onSetSubmit = this._onSetSubmit.bind(this);
  }

  componentDidMount() {
    PlayerKeyStore.addChangeListener(this._onChange);
  }

  componentWillUnmount() {
    PlayerKeyStore.removeChangeListener(this._onChange);
  }

  render() {
    var form = (
      <form onSubmit={this._onSetSubmit}>
        <input type="text" placeholder="Enter a player key" size="50" value={this.state.key} onChange={this._handleChange} />
        <button className={(!this.state.key) ? "" : "set"}>Set</button>
      </form>
    );

    if (this.state.set) {
      form = (
        <form onSubmit={this._onResetSubmit}>
          <input type="text" size="50" value={this.state.key} disabled />
          <button className="reset">Reset</button>
        </form>
      );
    }

    return (

Push Commands to a Player Key

        Set a Player Key to push all UI commands to (instead of the UI player).
        {form}

    );
  }

  _onChange() {
    this.setState(getPushKeyFormState());
  }

  _handleChange(event) {
     this.setState({key: event.target.value});
  }

  _onResetSubmit(e) {
    e.preventDefault();
    PlayerKeyActions.setPushKey("");
  }

  _onSetSubmit(e) {
    e.preventDefault();
    PlayerKeyActions.setPushKey(this.state.key);
  }
}
<|endoftext|>


<commit_before>Layouts.application = function(delegate) {
	var win = Ti.UI.createWindow({
		backgroundImage:'images/main_bg.png',
		orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT]
	});

	var main_content = Ti.UI.createView({
		backgroundImage:'images/main_bg.png',
	});

	var nav = Ti.UI.createView({
		layout: "horizontal",
		right: 0,
		height:"100%",
		width:60
	});

	var makeTab = function(attrs) {
		var tab = Ti.UI.createButton({
			backgroundImage:attrs.background,
			backgroundSelectedImage:attrs.background,
			right:0,
			width:attrs.width,
			height:attrs.height,
			top:-40
		});

		tab.addEventListener('click', App.swapView(main_content, Controllers.content.index.p(Formatter.underscore(attrs.name))));
		nav.add(tab);
		return tab;
	}

	var tabs = [
		{name: "Technology", background: "images/tabs/tabs_technology.png", width:60, height:160}
		, {name: "Results", background: "images/tabs/tabs_results.png", width:60, height:150}
		, {name: "Case Studies", background: "images/tabs/tabs_case_studies.png", width:60, height:190}
		, {name: "Cost", background: "images/tabs/tabs_cost.png", width:60, height:150}
		, {name: "Reimbursment", background: "images/tabs/tabs_reimbursement.png", width:60, height:190}
		, {name: "Dfine", background: "images/tabs/tabs_dfine.png", width:60, height:150}
	]

	var tabButtons = map(makeTab, tabs);

	var button_group = UI.ButtonGroup.apply(this, tabButtons);

	win.add(main_content);
	win.add(nav);
	win.open({transition:Ti.UI.iPhone.AnimationStyle.CURL_DOWN});
	delegate.root(main_content);
}
<commit_msg>quick fix<commit_after>Layouts.application = function(delegate) {
	var win = Ti.UI.createWindow({
		backgroundImage:'images/main_bg.png',
		orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT]
	});

	var main_content = Ti.UI.createView({
		backgroundImage:'images/main_bg.png',
	});

	var nav = Ti.UI.createView({
		layout: "horizontal",
		right: 0,
		height:"100%",
		width:60
	});

	var makeTab = function(attrs) {
		var tab = Ti.UI.createButton({
			backgroundImage:attrs.background,
			backgroundSelectedImage:attrs.background,
			right:0,
			width:attrs.width,
			height:attrs.height,
			top:-40
		});

		tab.addEventListener('click', App.swapView(main_content, Controllers.content.index.p(Formatter.underscore(attrs.name))));
		nav.add(tab);
		return tab;
	}

	var tabs = [
		{name: "Technology", background: "images/tabs/tabs_technology.png", width:60, height:160}
		, {name: "Results", background: "images/tabs/tabs_results.png", width:60, height:150}
		, {name: "Case Studies", background: "images/tabs/tabs_case_studies.png", width:60, height:190}
		, {name: "Cost", background: "images/tabs/tabs_cost.png", width:60, height:150}
		, {name: "Reimbursment", background: "images/tabs/tabs_reimbursement.png", width:60, height:190}
		, {name: "Dfine", background: "images/tabs/tabs_dfine.png", width:60, height:150}
	]

	var tabButtons = map(makeTab, tabs);

	var button_group = UI.ButtonGroup.apply(this, tabButtons);

	win.add(main_content);
	win.add(nav);
	win.open({transition:Ti.UI.iPhone.AnimationStyle.CURL_DOWN});
	delegate.root(main_content);
}
<|endoftext|>


<commit_before>var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var logger = require('../utils/logger.js');

var Utils = require('../utils/util.js');
var async = require('async');

module.exports.collapseDb = (userref, serviceName) => {

	if(!userref) {
		console.err("impossibile to collapseDb becase user is null or undefined");
	}

	var extUser = Object.create(userref);

	console.log("--------------------------******----");
	console.log("--------------------------******----");
	console.log("--------------------------******----");
	console.log('called collapseDb');
	console.log("INPUT extUser");
	console.log(extUser);
	console.log("serviceName: " + serviceName);

	const inputEmail = extUser[serviceName] ? extUser[serviceName].email : null;

	console.log("1*****************************************");
	console.log(extUser);

	console.log("inputEmail " + inputEmail);

	console.log("--------------------------******----");
	console.log("--------------------------******----");
	console.log("--------------------------******----");

	const key =  serviceName + '.email';
	const query = {};

	query[key] = inputEmail;

	// query._id = {
	// 	'$ne' : extUser._id
	// };

	console.log("1bis*****************************************");
	console.log(extUser);

	console.log(query);

	if(inputEmail) {
		console.log("1tris*****************************************");
			console.log(extUser);

		const iduserOriginal = extUser._id + '';

		User.find(query, (err, users) => {

			if(err) {
				console.log("--------------------------******---- Error - user not found!!!");
			}

			console.log("--------------------------******---- search");

			console.log("--------------------------******---- users found");
			console.log(users);
			console.log("--------------------------******---- starting cycle");

			var user = users.find(function (el) {
				if(el && el._id) {
					console.log("---" + el);
    			return el._id + '' === iduserOriginal + '';
    		}
			});

			let duplicatedUser = {};

			console.log("2*****************************************");
			console.log(user);
			console.log("2*****************************************");

			for(let iUser of users) {
				console.log("--------------------------******---- iUser in for: ");
				console.log(iUser);
				console.log("--------------------------******---- if condition");
				console.log("--------------------------******----iUser[serviceName]: ");
				console.log((iUser ? iUser[serviceName] : 'not found'));

				const idiUser = iUser._id + '';
				const iduser = user._id + '';
				console.log("--------------------------******----iUser._id: " + iUser._id);
				console.log("--------------------------******----user._id: " + user._id);
				if (iUser && iUser[serviceName] && iUser[serviceName].email === inputEmail && idiUser !== iduser) {
					console.log('--------------------------******----found a duplicated ' + serviceName + ' iUser:');
					console.log(iUser[serviceName]);
					duplicatedUser = iUser;
					break;
					//here I found one account with the same service
					//I want to merge all infos in this account [not logged] with the new one [used to connect] (to prevent logout/login and session invalidation)
				}

				console.log("3*****************************************");
				console.log(user);
				console.log("3*****************************************");
				console.log('--------------------------******----cycle completed');
			}

			console.log("**--------------------------******----preparing to collapse duplicated db's users");
			console.log(user);
			console.log("**--------------------------******----");

			let updated = false;

			for(let s of ['google', 'github', 'facebook', 'local', 'linkedin', 'twitter']) {
				console.log('**--------------------------******----cycle s: ' + s + ', serviceName: ' + serviceName);
				if(s !== serviceName) {
					console.log('--------------------------******----user[s]: ' + user[s]);
					console.log('--------------------------******----duplicatedUser[s]: ' + duplicatedUser[s]);
					console.log('--------------------------******----!user[s]: ' + !user[s]);
					console.log('--------------------------******----(!user[s] || !user[s].email): ' + (!user[s] || !user[s].email));
					if((!user[s] || !user[s].email) && duplicatedUser[s]) {
						console.log("**--------------------------******---- merging service: " + s);
						console.log("**--------------------------******----  modified user in cycle (duplicatedUser): ");
						console.log(duplicatedUser[s]);
						console.log("**--------------------------******----");
						console.log("**--------------------------******----  user in cycle before changes: ");
						console.log(user[s]);
						console.log("**--------------------------******----");

						user[s] = duplicatedUser[s];
						updated=true;
						console.log("**--------------------------******----  modified user in cycle: ");
						console.log(user[s]);
						console.log("**--------------------------******----");
					}
				}
			}

			console.log("**--------------------------******---- modified user");
			console.log(user);
			console.log("**--------------------------******---- saving this modified user");

			if(duplicatedUser && updated) {
				user.save((err, savedUser) => {
		      if (err) {
		      	console.log("Error while saving collapsed users");
		        throw err;
		      }
		      console.log("Saved modified user: " + savedUser);
		  	});

		  	console.log("--------------------------******---- removing duplicated user");

		  	User.findByIdAndRemove(duplicatedUser._id, function(err) {
				  if (err) throw err;

				  // we have deleted the user
				  console.log('--------------------------******---- duplicated User deleted!');
				});
	  	}

			console.log("--------------------------******---- search finished");
		});
	}
};
<commit_msg>code refactoring collapse-db<commit_after>var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var logger = require('../utils/logger.js');

var Utils = require('../utils/util.js');
var async = require('async');

module.exports.collapseDb = (loggedUser, serviceName) => {

	if(!loggedUser || !serviceName) {
		console.err("impossibile to collapseDb becase either loggedUser or serviceName are null or undefined.");
	}

	console.log("--------------------------******----");
	console.log("INPUT loggedUser");
	console.log(loggedUser);
	console.log("serviceName: " + serviceName);

	const inputEmail = loggedUser[serviceName] ? loggedUser[serviceName].email : null;

	console.log("inputEmail " + inputEmail);

	if(!inputEmail) {
		console.err("inputEmail is not valid");
		return;
	}

	console.log("--------------------------******----");
	console.log("--------------------------******----");
	console.log("--------------------------******----");

	const key =  serviceName + '.email';
	const query = {};

	query[key] = inputEmail;

	// query._id = {
	// 	'$ne' : loggedUser._id
	// };

	console.log(query);

	const idLoggedUser = loggedUser._id + '';

	User.find(query, (err, users) => {

		if(err) {
			console.err("--------------------------******---- Error - users not found!!!");
			throw err;
		}

		console.log("--------------------------******---- users found");
		console.log(users);

		var user = users.find(function (el) {
			if(el && el._id) {
				return el._id + '' === idLoggedUser + '';
			}
		});

		if(!user) {
			console.err("--------------------------******---- Error - user not found!!!");
			return;
		}

		let duplicatedUser = {};

		console.log("2*****************************************");
		console.log(user);
		console.log("2*****************************************");
		const idUser = user._id + '';

		for(let dbUser of users) {
			console.log("--------------------------******---- dbUser in for: ");
			console.log(dbUser);
			console.log("--------------------------******---- if condition");
			console.log("--------------------------******----dbUser[serviceName]: ");
			console.log((dbUser ? dbUser[serviceName] : 'not found'));

			const iddbUser = dbUser._id + '';

			console.log("--------------------------******----dbUser._id: " + iddbUser);
			console.log("--------------------------******----user._id: " + idUser);
			if (dbUser && dbUser[serviceName] && dbUser[serviceName].email === inputEmail && iddbUser !== idUser) {
				console.log('--------------------------******----found a duplicated ' + serviceName + ' dbUser:');
				console.log(dbUser[serviceName]);
				duplicatedUser = dbUser;
				break;
					//here I found one account with the same service
					//I want to merge all infos in this account [not logged] with the new one [used to connect] (to prevent logout/login and session invalidation)
				}
				console.log('--------------------------******----cycle completed');
		}

		console.log("**--------------------------******----preparing to collapse duplicated db's users");
		console.log(user);
		console.log("**--------------------------******----");

		let updated = false;

		for(let s of ['google', 'github', 'facebook', 'local', 'linkedin', 'twitter']) {
			console.log('**--------------------------******----cycle s: ' + s + ', serviceName: ' + serviceName);
			if(s !== serviceName) {
				// console.log('--------------------------******----user[s]: ' + user[s]);
				// console.log('--------------------------******----duplicatedUser[s]: ' + duplicatedUser[s]);
				// console.log('--------------------------******----!user[s]: ' + !user[s]);
				// console.log('--------------------------******----(!user[s] || !user[s].email): ' + (!user[s] || !user[s].email));
				if((!user[s] || !user[s].email) && duplicatedUser[s]) {
					console.log("**--------------------------******---- merging service: " + s);
					// console.log("**--------------------------******----  modified user in cycle (duplicatedUser): ");
					// console.log(duplicatedUser[s]);
					// console.log("**--------------------------******----");
					// console.log("**--------------------------******----  user in cycle before changes: ");
					// console.log(user[s]);
					// console.log("**--------------------------******----");

					user[s] = duplicatedUser[s];
					updated=true;
				}
			}
		}

		console.log("**--------------------------******---- modified user");
		console.log(user);
		console.log("**--------------------------******---- saving this modified user");

		if(duplicatedUser && updated) {
			user.save((err, savedUser) => {
				if (err) {
					console.log("Error while saving collapsed users");
					throw err;
				}
				console.log("Saved modified user: " + savedUser);
			});

			console.log("--------------------------******---- removing duplicated user [OK]");

			User.findByIdAndRemove(duplicatedUser._id, err => {
				if (err) {
					throw err;
				}

			  // we have deleted the user
			  console.log('--------------------------******---- duplicated User deleted! [OK]');
			});
		} else {
			console.log("I can't do anything because there isn't a duplicated users! [OK]");
		}

		console.log("--------------------------******---- search finished");
	});
};
<|endoftext|>