<commit_before>var formioUtils = require('formio-utils');

module.exports = function() {
  return {
    checkVisible: function(component, row, data) {
      var visible = formioUtils.checkCondition(component, row, data);
      if (!visible) {
        if (component.hasOwnProperty('clearOnHide') && component.clearOnHide === true) {
          if (row && row.hasOwnProperty(component.key)) {
            delete row[component.key];
          }
          if (data && data.hasOwnProperty(component.key)) {
            delete data[component.key];
          }
        }
        return false;
      }
      return true;
    },
    isVisible: function(component, row, data, hide) {
      // If the component is in the hideComponents array, then hide it by default.
      if (hide && Array.isArray(hide) && (hide.indexOf(component.key) !== -1)) {
        return false;
      }

      return this.checkVisible(component, row, data);
    },
    flattenComponents: formioUtils.flattenComponents,
    eachComponent: formioUtils.eachComponent,
    getComponent: formioUtils.getComponent,
    getValue: formioUtils.getValue,
    hideFields: function(form, components) {
      this.eachComponent(form.components, function(component) {
        for (var i in components) {
          if (component.key === components[i]) {
            component.type = 'hidden';
          }
        }
      });
    },
    uniqueName: function(name) {
      var parts = name.toLowerCase().replace(/[^0-9a-z\.]/g, '').split('.');
      var fileName = parts[0];
      var ext = '';
      if (parts.length > 1) {
        ext = '.' + parts[(parts.length - 1)];
      }
      return fileName.substr(0, 10) + '-' + this.guid() + ext;
    },
    guid: function() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      });
    },
    fieldWrap: function(input) {
      var multiInput = input.replace('data[component.key]', 'data[component.key][$index]');
      var inputLabel = '{{ component.label | formioTranslate:null:builder }}';
      var requiredInline = '';
      var template =
        '
' +
          inputLabel +
          '
' +
            '
{{ component.prefix }}
' +
            input +
            requiredInline +
            '
{{ component.suffix }}
' +
          '
' +
          '
' +
            '<formio-errors ng-if="::!builder"></formio-errors>' +
          '
' +
        '
' +
        '
' +
          '{{ component.description }}' +
        '
' +
        '

' +
          inputLabel +
          '
' +
            '' +
              '
' +
                '
{{ component.prefix }}
' +
                  multiInput +
                  requiredInline +
                '
{{ component.suffix }}
' +
              '
' +
              '
' +
                '<formio-errors ng-if="::!builder"></formio-errors>' +
              '
' +
            '	' +
            '	' +
          '
' +
          '
' +
            ' {{ component.addAnother || "Add Another" | formioTranslate:null:builder }}	' +
          '
' +
        '

';
      return template;
    }
  };
};
<commit_msg>Fixing logic for existing forms.<commit_after>var formioUtils = require('formio-utils');

module.exports = function() {
  return {
    checkVisible: function(component, row, data) {
      var visible = formioUtils.checkCondition(component, row, data);
      if (!visible) {
        if (!component.hasOwnProperty('clearOnHide') || (component.hasOwnProperty('clearOnHide') && ['true', true].indexOf(component.clearOnHide) !== -1)) {
          if (row && row.hasOwnProperty(component.key)) {
            delete row[component.key];
          }
          if (data && data.hasOwnProperty(component.key)) {
            delete data[component.key];
          }
        }
        return false;
      }
      return true;
    },
    isVisible: function(component, row, data, hide) {
      // If the component is in the hideComponents array, then hide it by default.
      if (hide && Array.isArray(hide) && (hide.indexOf(component.key) !== -1)) {
        return false;
      }

      return this.checkVisible(component, row, data);
    },
    flattenComponents: formioUtils.flattenComponents,
    eachComponent: formioUtils.eachComponent,
    getComponent: formioUtils.getComponent,
    getValue: formioUtils.getValue,
    hideFields: function(form, components) {
      this.eachComponent(form.components, function(component) {
        for (var i in components) {
          if (component.key === components[i]) {
            component.type = 'hidden';
          }
        }
      });
    },
    uniqueName: function(name) {
      var parts = name.toLowerCase().replace(/[^0-9a-z\.]/g, '').split('.');
      var fileName = parts[0];
      var ext = '';
      if (parts.length > 1) {
        ext = '.' + parts[(parts.length - 1)];
      }
      return fileName.substr(0, 10) + '-' + this.guid() + ext;
    },
    guid: function() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      });
    },
    fieldWrap: function(input) {
      var multiInput = input.replace('data[component.key]', 'data[component.key][$index]');
      var inputLabel = '{{ component.label | formioTranslate:null:builder }}';
      var requiredInline = '';
      var template =
        '
' +
          inputLabel +
          '
' +
            '
{{ component.prefix }}
' +
            input +
            requiredInline +
            '
{{ component.suffix }}
' +
          '
' +
          '
' +
            '<formio-errors ng-if="::!builder"></formio-errors>' +
          '
' +
        '
' +
        '
' +
          '{{ component.description }}' +
        '
' +
        '

' +
          inputLabel +
          '
' +
            '' +
              '
' +
                '
{{ component.prefix }}
' +
                  multiInput +
                  requiredInline +
                '
{{ component.suffix }}
' +
              '
' +
              '
' +
                '<formio-errors ng-if="::!builder"></formio-errors>' +
              '
' +
            '	' +
            '	' +
          '
' +
          '
' +
            ' {{ component.addAnother || "Add Another" | formioTranslate:null:builder }}	' +
          '
' +
        '

';
      return template;
    }
  };
};
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'ember-lts-2.4',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-4'
        },
        resolutions: {
          'ember': 'lts-2-4'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-lts-2.8',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-8'
        },
        resolutions: {
          'ember': 'lts-2-8'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-release',
      bower: {
        dependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-beta',
      bower: {
        dependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-canary',
      bower: {
        dependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-default',
      npm: {
        devDependencies: {}
      }
    }
  ]
};
<commit_msg>Removed scenario ember-lts-2.4<commit_after>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'ember-lts-2.8',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-8'
        },
        resolutions: {
          'ember': 'lts-2-8'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-release',
      bower: {
        dependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-beta',
      bower: {
        dependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-canary',
      bower: {
        dependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      },
      npm: {
        devDependencies: {
          'ember-source': null
        }
      }
    },
    {
      name: 'ember-default',
      npm: {
        devDependencies: {}
      }
    }
  ]
};
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'ember-lts-2.4',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-4'
        },
        resolutions: {
          'ember': 'lts-2-4'
        }
      }
    },
    {
      name: 'ember-lts-2.8',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-8'
        },
        resolutions: {
          'ember': 'lts-2-8'
        }
      }
    },
    {
      name: 'ember-release',
      bower: {
        dependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      }
    },
    {
      name: 'ember-beta',
      bower: {
        dependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      }
    },
    {
      name: 'ember-canary',
      bower: {
        dependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      }
    }
  ]
};
<commit_msg>Add 1.13<commit_after>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'ember-1.13.13',
      bower: {
        dependencies: {
          'ember': '~1.13.13',
          'ember-cli-shims': '0.1.1'
        },
        resolutions: {
          'ember': '~1.13.13'
        }
      }
    },
    {
      name: 'ember-lts-2.4',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-4'
        },
        resolutions: {
          'ember': 'lts-2-4'
        }
      }
    },
    {
      name: 'ember-lts-2.8',
      bower: {
        dependencies: {
          'ember': 'components/ember#lts-2-8'
        },
        resolutions: {
          'ember': 'lts-2-8'
        }
      }
    },
    {
      name: 'ember-release',
      bower: {
        dependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      }
    },
    {
      name: 'ember-beta',
      bower: {
        dependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      }
    },
    {
      name: 'ember-canary',
      bower: {
        dependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      }
    }
  ]
};
<|endoftext|>


<commit_before>module.exports = {
  scenarios: [
    {
      name: 'default',
      dependencies: { }
    },
    {
      name: 'ember-release',
      dependencies: {
        'ember': 'components/ember#release',
        'ember-data': 'components/ember-data#release'
      },
      resolutions: {
        'ember': 'release',
        'ember-data': 'release'
      }
    },
    {
      name: 'ember-beta',
      dependencies: {
        'ember': 'components/ember#beta',
        'ember-data': 'components/ember-data#beta'
      },
      resolutions: {
        'ember': 'beta',
        'ember-data': 'beta'
      }
    },
    {
      name: 'ember-canary',
      dependencies: {
        'ember': 'components/ember#canary',
        'ember-data': 'components/ember#canary'
      },
      resolutions: {
        'ember': 'canary',
        'ember-data': 'canary'
      }
    }
  ]
};
<commit_msg>Fix canary ember-try<commit_after>module.exports = {
  scenarios: [
    {
      name: 'default',
      dependencies: { }
    },
    {
      name: 'ember-release',
      dependencies: {
        'ember': 'components/ember#release',
        'ember-data': 'components/ember-data#release'
      },
      resolutions: {
        'ember': 'release',
        'ember-data': 'release'
      }
    },
    {
      name: 'ember-beta',
      dependencies: {
        'ember': 'components/ember#beta',
        'ember-data': 'components/ember-data#beta'
      },
      resolutions: {
        'ember': 'beta',
        'ember-data': 'beta'
      }
    },
    {
      name: 'ember-canary',
      dependencies: {
        'ember': 'components/ember#canary',
        'ember-data': 'components/ember-data#canary'
      },
      resolutions: {
        'ember': 'canary',
        'ember-data': 'canary'
      }
    }
  ]
};
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import Dygraph from 'shared/components/Dygraph'
import classnames from 'classnames'
import shallowCompare from 'react-addons-shallow-compare'

import timeSeriesToDygraph from 'utils/timeSeriesToDygraph'
import lastValues from 'shared/parsing/lastValues'

const {array, arrayOf, bool, func, number, shape, string} = PropTypes

const SMALL_CELL_HEIGHT = 1

export default React.createClass({
  displayName: 'LineGraph',
  propTypes: {
    data: arrayOf(shape({}).isRequired).isRequired,
    axes: shape({
      y: shape({
        bounds: array,
        label: string,
      }),
      y2: shape({
        bounds: array,
        label: string,
      }),
    }),
    title: string,
    isFetchingInitially: bool,
    isRefreshing: bool,
    underlayCallback: func,
    isGraphFilled: bool,
    isBarGraph: bool,
    overrideLineColors: array,
    queries: arrayOf(shape({}).isRequired).isRequired,
    showSingleStat: bool,
    displayOptions: shape({
      stepPlot: bool,
      stackedGraph: bool,
    }),
    activeQueryIndex: number,
    ruleValues: shape({}),
    timeRange: shape({
      lower: string.isRequired,
    }),
    isInDataExplorer: bool,
    synchronizer: func,
    setResolution: func,
    cellHeight: number,
    cell: shape({}),
    onZoom: func,
    resizeCoords: shape(),
  },

  getDefaultProps() {
    return {
      underlayCallback: () => {},
      isGraphFilled: true,
      overrideLineColors: null,
    }
  },

  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  },

  componentWillMount() {
    const {data, activeQueryIndex, isInDataExplorer} = this.props
    this._timeSeries = timeSeriesToDygraph(
      data,
      activeQueryIndex,
      isInDataExplorer
    )
  },

  componentWillUpdate(nextProps) {
    const {data, activeQueryIndex} = this.props
    if (
      data !== nextProps.data ||
      activeQueryIndex !== nextProps.activeQueryIndex
    ) {
      this._timeSeries = timeSeriesToDygraph(
        nextProps.data,
        nextProps.activeQueryIndex,
        nextProps.isInDataExplorer
      )
    }
  },

  render() {
    const {
      data,
      axes,
      cell,
      isFetchingInitially,
      isRefreshing,
      isGraphFilled,
      isBarGraph,
      overrideLineColors,
      title,
      queries,
      underlayCallback,
      showSingleStat,
      displayOptions,
      ruleValues,
      synchronizer,
      timeRange,
      cellHeight,
      onZoom,
      resizeCoords,
    } = this.props
    const {labels, timeSeries, dygraphSeries} = this._timeSeries

    // If data for this graph is being fetched for the first time, show a graph-wide spinner.
    if (isFetchingInitially) {
      return (

      )
    }

    const options = {
      labels,
      connectSeparatedPoints: true,
      labelsKMB: true,
      axisLineColor: '#383846',
      gridLineColor: '#383846',
      title,
      rightGap: 0,
      yRangePad: 10,
      axisLabelWidth: 60,
      drawAxesAtZero: true,
      underlayCallback,
      ...displayOptions,
    }

    const singleStatOptions = {
      ...options,
      highlightSeriesOpts: {
        strokeWidth: 1.5,
      },
    }
    const singleStatLineColors = [
      '#7A65F2',
      '#FFD255',
      '#7CE490',
      '#F95F53',
      '#4591ED',
      '#B1B6FF',
      '#FFF6B8',
      '#C6FFD0',
      '#6BDFFF',
    ]

    let roundedValue
    if (showSingleStat) {
      const lastValue = lastValues(data)[1]

      const precision = 100.0
      roundedValue = Math.round(+lastValue * precision) / precision
    }

    const lineColors = showSingleStat
      ? singleStatLineColors
      : overrideLineColors

    return (

        {isRefreshing ? this.renderSpinner() : null}
        <Dygraph
          cell={cell}
          resizeCoords={resizeCoords}
          axes={axes}
          queries={queries}
          containerStyle={{width: '100%', height: '100%'}}
          overrideLineColors={lineColors}
          isGraphFilled={showSingleStat ? false : isGraphFilled}
          isBarGraph={isBarGraph}
          timeSeries={timeSeries}
          labels={labels}
          options={showSingleStat ? singleStatOptions : options}
          dygraphSeries={dygraphSeries}
          ruleValues={ruleValues}
          synchronizer={synchronizer}
          timeRange={timeRange}
          setResolution={this.props.setResolution}
          onZoom={onZoom}
        />
        {showSingleStat
          ?

                  {roundedValue}

          : null}

    )
  },

  renderSpinner() {
    return (

    )
  },
})
<commit_msg>Convert LineGraph to class component<commit_after>import React, {PropTypes, Component} from 'react'
import Dygraph from 'shared/components/Dygraph'
import classnames from 'classnames'
import shallowCompare from 'react-addons-shallow-compare'

import timeSeriesToDygraph from 'utils/timeSeriesToDygraph'
import lastValues from 'shared/parsing/lastValues'

const {array, arrayOf, bool, func, number, shape, string} = PropTypes

const SMALL_CELL_HEIGHT = 1

class LineGraph extends Component {
  constructor(props) {
    super(props)
  }

  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }

  componentWillMount() {
    const {data, activeQueryIndex, isInDataExplorer} = this.props
    this._timeSeries = timeSeriesToDygraph(
      data,
      activeQueryIndex,
      isInDataExplorer
    )
  }

  componentWillUpdate(nextProps) {
    const {data, activeQueryIndex} = this.props
    if (
      data !== nextProps.data ||
      activeQueryIndex !== nextProps.activeQueryIndex
    ) {
      this._timeSeries = timeSeriesToDygraph(
        nextProps.data,
        nextProps.activeQueryIndex,
        nextProps.isInDataExplorer
      )
    }
  }

  render() {
    const {
      data,
      axes,
      cell,
      isFetchingInitially,
      isRefreshing,
      isGraphFilled,
      isBarGraph,
      overrideLineColors,
      title,
      queries,
      underlayCallback,
      showSingleStat,
      displayOptions,
      ruleValues,
      synchronizer,
      timeRange,
      cellHeight,
      onZoom,
      resizeCoords,
    } = this.props
    const {labels, timeSeries, dygraphSeries} = this._timeSeries

    // If data for this graph is being fetched for the first time, show a graph-wide spinner.
    if (isFetchingInitially) {
      return (

      )
    }

    const options = {
      labels,
      connectSeparatedPoints: true,
      labelsKMB: true,
      axisLineColor: '#383846',
      gridLineColor: '#383846',
      title,
      rightGap: 0,
      yRangePad: 10,
      axisLabelWidth: 60,
      drawAxesAtZero: true,
      underlayCallback,
      ...displayOptions,
    }

    const singleStatOptions = {
      ...options,
      highlightSeriesOpts: {
        strokeWidth: 1.5,
      },
    }
    const singleStatLineColors = [
      '#7A65F2',
      '#FFD255',
      '#7CE490',
      '#F95F53',
      '#4591ED',
      '#B1B6FF',
      '#FFF6B8',
      '#C6FFD0',
      '#6BDFFF',
    ]

    let roundedValue
    if (showSingleStat) {
      const lastValue = lastValues(data)[1]

      const precision = 100.0
      roundedValue = Math.round(+lastValue * precision) / precision
    }

    const lineColors = showSingleStat
      ? singleStatLineColors
      : overrideLineColors

    return (

        {isRefreshing ? <GraphLoadingDots /> : null}
        <Dygraph
          cell={cell}
          resizeCoords={resizeCoords}
          axes={axes}
          queries={queries}
          containerStyle={{width: '100%', height: '100%'}}
          overrideLineColors={lineColors}
          isGraphFilled={showSingleStat ? false : isGraphFilled}
          isBarGraph={isBarGraph}
          timeSeries={timeSeries}
          labels={labels}
          options={showSingleStat ? singleStatOptions : options}
          dygraphSeries={dygraphSeries}
          ruleValues={ruleValues}
          synchronizer={synchronizer}
          timeRange={timeRange}
          setResolution={this.props.setResolution}
          onZoom={onZoom}
        />
        {showSingleStat
          ?

                  {roundedValue}

          : null}

    )
  }
}

const GraphLoadingDots = () =>

LineGraph.defaultProps = {
  underlayCallback: () => {},
  isGraphFilled: true,
  overrideLineColors: null,
}

LineGraph.propTypes = {
  axes: shape({
    y: shape({
      bounds: array,
      label: string,
    }),
    y2: shape({
      bounds: array,
      label: string,
    }),
  }),
  title: string,
  isFetchingInitially: bool,
  isRefreshing: bool,
  underlayCallback: func,
  isGraphFilled: bool,
  isBarGraph: bool,
  overrideLineColors: array,
  showSingleStat: bool,
  displayOptions: shape({
    stepPlot: bool,
    stackedGraph: bool,
  }),
  activeQueryIndex: number,
  ruleValues: shape({}),
  timeRange: shape({
    lower: string.isRequired,
  }),
  isInDataExplorer: bool,
  synchronizer: func,
  setResolution: func,
  cellHeight: number,
  cell: shape(),
  onZoom: func,
  resizeCoords: shape(),
  queries: arrayOf(shape({}).isRequired).isRequired,
  data: arrayOf(shape({}).isRequired).isRequired,
}

export default LineGraph
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'default',
      bower: {
        devDependencies: {}
      }
    },
    {
      name: 'ember-ember-data-2.6',
      npm: {
        devDependencies: {
          'ember-data': '2.6.2',
          'ember-data-model-fragments': '2.3.3'
        }
      }
    },
    {
      name: 'ember-ember-data-release',
      bower: {
        devDependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'release'
        }
      }
    },
    {
      name: 'ember-ember-data-beta',
      bower: {
        devDependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'beta'
        }
      }
    },
    {
      name: 'ember-ember-data-canary',
      bower: {
        devDependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'canary'
        }
      }
    }
  ]
};
<commit_msg>ember try 2.6<commit_after>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'default',
      bower: {
        devDependencies: {}
      }
    },
    {
      name: 'ember-ember-data-2.6',
      bower: {
        devDependencies: {
          'ember': 'components/ember#2.6'
        },
        resolutions: {
          'ember': '2.6'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': '2.6.2',
          'ember-data-model-fragments': '2.3.3'
        }
      }
    },
    {
      name: 'ember-ember-data-release',
      bower: {
        devDependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'release'
        }
      }
    },
    {
      name: 'ember-ember-data-beta',
      bower: {
        devDependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'beta'
        }
      }
    },
    {
      name: 'ember-ember-data-canary',
      bower: {
        devDependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'canary'
        }
      }
    }
  ]
};
<|endoftext|>


<commit_before>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = function() {
  return Promise.all([
    getChannelURL('release'),
    getChannelURL('beta'),
    getChannelURL('canary')
  ]).then((urls) => {
    return {
      useYarn: true,
      scenarios: [
        {
          name: 'ember-lts-2.18',
          env: {
            EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true })
          },
          npm: {
            devDependencies: {
              '@ember/jquery': '^0.5.1',
              'ember-source': '~2.18.0'
            }
          }
        },
        {
          name: 'ember-lts-3.8',
          npm: {
            devDependencies: {
              'ember-source': '~3.8.0'
            }
          }
        },
        {
          name: 'ember-lts-3.4',
          npm: {
            devDependencies: {
              'ember-source': '~3.4.0'
            }
          }
        },
        {
          name: 'ember-release',
          npm: {
            devDependencies: {
              'ember-source': urls[0]
            }
          }
        },
        {
          name: 'ember-beta',
          npm: {
            devDependencies: {
              'ember-source': urls[1]
            }
          }
        },
        {
          name: 'ember-canary',
          npm: {
            devDependencies: {
              'ember-source': urls[2]
            }
          }
        },
        // The default `.travis.yml` runs this scenario via `npm test`,
        // not via `ember try`. It's still included here so that running
        // `ember try:each` manually or from a customized CI config will run it
        // along with all the other scenarios.
        {
          name: 'ember-default',
          npm: {
            devDependencies: {}
          }
        },
        {
          name: 'ember-default-with-jquery',
          env: {
            EMBER_OPTIONAL_FEATURES: JSON.stringify({
              'jquery-integration': true
            })
          },
          npm: {
            devDependencies: {
              '@ember/jquery': '^0.5.1'
            }
          }
        }
      ]
    };
  });
};
<commit_msg>setup 3.12<commit_after>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = function() {
  return Promise.all([
    getChannelURL('release'),
    getChannelURL('beta'),
    getChannelURL('canary')
  ]).then((urls) => {
    return {
      useYarn: true,
      scenarios: [
        {
          name: 'ember-lts-2.18',
          env: {
            EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true })
          },
          npm: {
            devDependencies: {
              '@ember/jquery': '^0.5.1',
              'ember-source': '~2.18.0'
            }
          }
        },
        {
          name: 'ember-lts-3.8',
          npm: {
            devDependencies: {
              'ember-source': '~3.8.0'
            }
          }
        },
        {
          name: 'ember-lts-3.4',
          npm: {
            devDependencies: {
              'ember-source': '~3.4.0'
            }
          }
        },
        {
          name: 'ember-lts-3.12',
          npm: {
            devDependencies: {
              'ember-source': '~3.12.0'
            }
          }
        },
        {
          name: 'ember-release',
          npm: {
            devDependencies: {
              'ember-source': urls[0]
            }
          }
        },
        {
          name: 'ember-beta',
          npm: {
            devDependencies: {
              'ember-source': urls[1]
            }
          }
        },
        {
          name: 'ember-canary',
          npm: {
            devDependencies: {
              'ember-source': urls[2]
            }
          }
        },
        // The default `.travis.yml` runs this scenario via `npm test`,
        // not via `ember try`. It's still included here so that running
        // `ember try:each` manually or from a customized CI config will run it
        // along with all the other scenarios.
        {
          name: 'ember-default',
          npm: {
            devDependencies: {}
          }
        },
        {
          name: 'ember-default-with-jquery',
          env: {
            EMBER_OPTIONAL_FEATURES: JSON.stringify({
              'jquery-integration': true
            })
          },
          npm: {
            devDependencies: {
              '@ember/jquery': '^0.5.1'
            }
          }
        }
      ]
    };
  });
};
<|endoftext|>


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

foam.CLASS({
  package: 'foam.dao',
  name: 'VersionNoDAO',
  extends: 'foam.dao.ProxyDAO',
  implements: [ 'foam.mlang.Expressions' ],

  classes: [
    {
      name: 'PutData',

      properties: [
        {
          class: 'FObjectProperty',
          of: 'FObject',
          name: 'data'
        },
        {
          class: 'Function',
          name: 'resolve'
        },
        {
          class: 'Function',
          name: 'reject'
        }
      ]
    }
  ],

  properties: [
    {
      class: 'FObjectProperty',
      of: 'Property',
      name: 'property',
      required: true,
      hidden: true,
      transient: true
    },
    {
      class: 'Int',
      name: 'version',
      value: 1
    },
    {
      class: 'FObjectArray',
      of: 'FObject',
      // of: 'PutData',
      name: 'putBacklog_'
    },
    {
      class: 'Function',
      name: 'putImpl_',
      factory: function() { return this.putToBacklog_; }
    }
  ],

  methods: [
    function init() {
      this.validate();
      this.SUPER();

      // Get largest version number in delegate's records.
      this.delegate
          // Like MAX(), but faster on DAOs that can optimize order+limit.
          .orderBy(this.DESC(this.property)).limit(1)
          .select().then(function(sink) {
            var propName = this.property.name;
            if ( sink.array[0] && sink.array[0][propName] )
              this.version = sink.array[0][propName] + 1;

            // Flush backlog, resolving put() promises.
            var delegate = this.delegate;
            var puts = this.putBacklog_;
            for ( var i = 0; i < puts.length; i++ ) {
              var obj = puts[i].data;
              obj[propName] = this.version;
              this.version++;
              delegate.put(obj).then(puts[i].resolve, puts[i].reject);
            }
            this.putImpl_ = this.putToDelegate_;
          }.bind(this));
    },
    function put_(x, obj) {
      // Either putToBacklog_() or putToDelegate_(), depending on whether
      // version number has been initialized.
      return this.putImpl_(x, obj);
    },
    function putToBacklog_(x, obj) {
      // Store put()s before version number is initialized.
      return new Promise(function(resolve, reject) {
        this.putBacklog_.push(this.PutData.create({
          data: obj,
          resolve: resolve,
          reject: reject
        }));
      }.bind(this));
    },
    function putToDelegate_(x, obj) {
      // Increment version number and put to delegate.
      obj[this.property.name] = this.version;
      this.version++;
      return this.delegate.put_(x, obj);
    }
  ]
});
<commit_msg>WIP: Implementing VersionNoDAO work<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'VersionNoDAO',
  extends: 'foam.dao.ProxyDAO',
  implements: [ 'foam.mlang.Expressions' ],

  documentation: `DAO decorator that applies an incrementing version number
      to all objects put() and remove()d. Instead of deleting objects that
      are remove()d, a placeholder with a deleted flag is put() in its place.
      This allows foam.dao.SyncDAO clients that are polling a VersionNoDAO to
      recieve deletes from other clients.

      This DAO throws an InternalException when writes are issued before it has
      synchronized its delegate. To get a DAO of this class that can accept
      writes immediately, decorate it with a StoreAndForwardDAO.`,

  requires: [ 'foam.dao.InternalException' ],

  properties: [
    {
      name: 'delegate',
      required: true,
      final: true
    },
    {
      class: 'FObjectProperty',
      of: 'Property',
      name: 'versionProperty',
      required: true,
      hidden: true,
      transient: true
    },
    {
      class: 'FObjectProperty',
      of: 'Property',
      name: 'deletedProperty',
      required: true,
      hidden: true,
      transient: true
    },
    {
      class: 'Int',
      name: 'version',
      value: 1
    },
    {
      class: 'Boolean',
      name: 'ready_',
    }
  ],

  methods: [
    function init() {
      this.validate();
      this.SUPER();

      // Get largest version number in delegate's records.
      this.delegate
          // Like MAX(), but faster on DAOs that can optimize order+limit.
          .orderBy(this.DESC(this.versionProperty)).limit(1)
          .select().then(function(sink) {
            var propName = this.versionProperty.name;
            if ( sink.array[0] && sink.array[0][propName] )
              this.version = sink.array[0][propName] + 1;

            // Flush backlog, resolving put() promises.
            var delegate = this.delegate;
            var puts = this.putBacklog_;
            for ( var i = 0; i < puts.length; i++ ) {
              var obj = puts[i].data;
              obj[propName] = this.version;
              this.version++;
              delegate.put(obj).then(puts[i].resolve, puts[i].reject);
            }
            this.ready_ = true;
          }.bind(this));
    },
    function put_(x, obj) {
      if ( ! this.ready_ ) return Promise.reject(this.InternalException.create());

      // Increment version number and put to delegate.
      obj[this.versionProperty.name] = this.version;
      this.version++;
      return this.delegate.put_(x, obj);
    },
    function remove_(x, obj) {
      if ( ! this.ready_ ) return Promise.reject(this.InternalException.create());

      // Increment version number and put empty object (except for "id"
      // and "deleted = true") to delegate.
      var deleted = this.of.create({ id: obj.id }, x);
      deleted[this.deletedProperty.name] = true;
      deleted[this.versionProperty.name] = this.version;
      this.version++;
      return this.delegate.put_(x, deleted);
    },
    function removeAll_(x, skip, limit, order, predicate) {
      // TODO(markdittmer): Implement this in terms of remove_() implementation.
    }
  ]
});
<|endoftext|>


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

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TreeViewRow',
  extends: 'foam.u2.Element',

  requires: [
    'foam.mlang.ExpressionsSingleton'
  ],

  exports: [
    'data'
  ],

  imports: [
    'onObjDrop',
    'selection',
    'startExpanded'
  ],

  css: `
    ^ {
      white-space: nowrap;
      margin: 6px 20px;
      inset: none;
      cursor: pointer;
    }

    ^label:hover {
      border-radius: 2px;
      background-color: rgba(0, 48, 249, 0.1);
      color: #0030f9;
    }

    ^label {
      min-width: 120px;
      padding: 4px;
      font-weight: 900;
      color: #2b2b2b;
    }

    ^selected > ^label {
      border-radius: 2px;
      background-color: rgba(0, 48, 249, 0.1);
      color: #0030f9;
    }

    ^expanded {
      transform: rotate(180deg);
    }
  `,

  properties: [
    {
      name: 'data'
    },
    {
      name: 'relationship'
    },
    {
      class: 'Boolean',
      name: 'expanded',
      value: false
    },
    {
      class: 'Function',
      name: 'formatter'
    },
    {
      class: 'Boolean',
      name: 'draggable',
      documentation: 'Enable to allow drag&drop editing.',
      value: true
    },
    {
      class: 'Boolean',
      name: 'hasChildren'
    }
  ],

  methods: [
    function initE() {
      var self = this;
      this.
        addClass(this.myClass()).
        addClass(this.slot(function(selected, id) {
          if ( selected && foam.util.equals(selected.id, id) ) {
            return this.myClass('selected');
          }
          return '';
        }, this.selection$, this.data$.dot('id'))).
        start('span').
          style({
            visibility: this.hasChildren$.map(function(c) { return c ? 'visible' : 'hidden'; }),
            'display': 'inline-block',
            'visibility': 'visible',
            'font-size': '16px',
            'transform': this.expanded$.map(function(c) { return c ? 'rotate(180deg)' : 'rotate(90deg)' })
          }).
          on('click', this.toggleExpanded).
          add('\u2303').
          entity('nbsp').
        end().
        on('click', this.selected).
        callIf(this.draggable, function() {
          this.
          attrs({ draggable: 'true' }).
          on('dragstart', this.onDragStart).
          on('dragenter', this.onDragOver).
          on('dragover',  this.onDragOver).
          on('drop',      this.onDrop);
        }).
        start('span').addClass(self.myClass('label')).call(this.formatter, [self.data]).end().
        add(this.slot(function(e) {
          var e2 = this.E('div');
          if ( ! e ) return e2;
          e2.select(this.data[self.relationship.forwardName]/*.dao*/, function(obj) {
            self.hasChildren = true;
            return self.cls_.create({
              data: obj,
              formatter: self.formatter,
              relationship: self.relationship,
              expanded: self.startExpanded
            }, this);
          });
          return e2;
        }, this.expanded$));
    }
  ],

  listeners: [
    function onDragStart(e) {
      e.dataTransfer.setData('application/x-foam-obj-id', this.data.id);
      e.stopPropagation();
    },

    function onDragOver(e) {
      if ( ! e.dataTransfer.types.some(function(m) { return m === 'application/x-foam-obj-id'; }) )
        return;

      var id = e.dataTransfer.getData('application/x-foam-obj-id');

      if ( foam.util.equals(id, this.data.id) )
        return;

      e.preventDefault();
      e.stopPropagation();
    },

    function onDrop(e) {
      if ( ! e.dataTransfer.types.some(function(m) { return m === 'application/x-foam-obj-id'; }) )
        return;

      var id = e.dataTransfer.getData('application/x-foam-obj-id');

      if ( foam.util.equals(id, this.data.id) ) return;

      e.preventDefault();
      e.stopPropagation();

      var self = this;
      var dao  = this.__context__[this.relationship.targetDAOKey];
      dao.find(id).then(function(obj) {
        if ( ! obj ) return null;

        // TODO: We shouldn't have to remove then put,
        // We currently have to because the FLOW editor is not updating properly
        // on a put event for an object that it already has.
        dao.remove(obj).then(function() {
          self.data[self.relationship.forwardName].dao.put(obj).then(function(obj) {
            self.onObjDrop(obj, id);
          });
        });
      });
    },

    function selected(e) {
      this.selection = this.data;
      e.preventDefault();
      e.stopPropagation();
    },

    function toggleExpanded(e) {
      this.expanded = ! this.expanded;
      this.selection = this.data;
      e.preventDefault();
      e.stopPropagation();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TreeView',
  extends: 'foam.u2.Element',

  requires: [
    'foam.mlang.ExpressionsSingleton',
    'foam.u2.view.TreeViewRow'
  ],

  exports: [
    'onObjDrop',
    'selection',
    'startExpanded'
  ],

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      name: 'relationship'
    },
    {
      name: 'selection'
    },
    {
      class: 'Function',
      name: 'formatter'
    },
    {
      class: 'Boolean',
      name: 'startExpanded',
      value: false
    }
  ],

  methods: [
    function initE() {
      var M   = this.ExpressionsSingleton.create();
      var of  = this.lookup(this.relationship.sourceModel);
      var dao = this.data$proxy.where(
        M.NOT(M.HAS(of.getAxiomByName(this.relationship.inverseName))));

      var self = this;
      this.addClass(this.myClass()).
        select(dao, function(obj) {
          return self.TreeViewRow.create({
            data: obj,
            relationship: self.relationship,
            expanded: self.startExpanded,
            formatter: self.formatter
          }, this);
        });
    },

    function onObjDrop(obj, target) {
      // Template Method
    }
  ]
});
<commit_msg>Styled treeview arrow<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TreeViewRow',
  extends: 'foam.u2.Element',

  requires: [
    'foam.mlang.ExpressionsSingleton'
  ],

  exports: [
    'data'
  ],

  imports: [
    'onObjDrop',
    'selection',
    'startExpanded'
  ],

  css: `
    ^ {
      white-space: nowrap;
      margin: 6px 20px;
      inset: none;
      cursor: pointer;
    }

    ^label:hover {
      border-radius: 2px;
      background-color: rgba(0, 48, 249, 0.1);
      color: #0030f9;
    }

    ^label {
      min-width: 120px;
      padding: 4px;
      font-weight: 900;
      color: #2b2b2b;
    }

    ^selected > ^label {
      border-radius: 2px;
      background-color: rgba(0, 48, 249, 0.1);
      color: #0030f9;
    }

    ^expanded {
      transform: rotate(180deg);
    }
  `,

  properties: [
    {
      name: 'data'
    },
    {
      name: 'relationship'
    },
    {
      class: 'Boolean',
      name: 'expanded',
      value: false
    },
    {
      class: 'Function',
      name: 'formatter'
    },
    {
      class: 'Boolean',
      name: 'draggable',
      documentation: 'Enable to allow drag&drop editing.',
      value: true
    },
    {
      class: 'Boolean',
      name: 'hasChildren'
    }
  ],

  methods: [
    function initE() {
      var self = this;
      this.
        addClass(this.myClass()).
        addClass(this.slot(function(selected, id) {
          if ( selected && foam.util.equals(selected.id, id) ) {
            return this.myClass('selected');
          }
          return '';
        }, this.selection$, this.data$.dot('id'))).
        start('span').
          style({
            visibility: this.hasChildren$.map(function(c) { return c ? 'visible' : 'hidden'; }),
            'vertical-align': 'middle',
            'font-weight': 'bold',
            'display': 'inline-block',
            'visibility': 'visible',
            'font-size': '16px',
            'transform': this.expanded$.map(function(c) { return c ? 'rotate(180deg)' : 'rotate(90deg)' })
          }).
          on('click', this.toggleExpanded).
          add('\u2303').
          entity('nbsp').
        end().
        on('click', this.selected).
        callIf(this.draggable, function() {
          this.
          attrs({ draggable: 'true' }).
          on('dragstart', this.onDragStart).
          on('dragenter', this.onDragOver).
          on('dragover',  this.onDragOver).
          on('drop',      this.onDrop);
        }).
        start('span').addClass(self.myClass('label')).call(this.formatter, [self.data]).end().
        add(this.slot(function(e) {
          var e2 = this.E('div');
          if ( ! e ) return e2;
          e2.select(this.data[self.relationship.forwardName]/*.dao*/, function(obj) {
            self.hasChildren = true;
            return self.cls_.create({
              data: obj,
              formatter: self.formatter,
              relationship: self.relationship,
              expanded: self.startExpanded
            }, this);
          });
          return e2;
        }, this.expanded$));
    }
  ],

  listeners: [
    function onDragStart(e) {
      e.dataTransfer.setData('application/x-foam-obj-id', this.data.id);
      e.stopPropagation();
    },

    function onDragOver(e) {
      if ( ! e.dataTransfer.types.some(function(m) { return m === 'application/x-foam-obj-id'; }) )
        return;

      var id = e.dataTransfer.getData('application/x-foam-obj-id');

      if ( foam.util.equals(id, this.data.id) )
        return;

      e.preventDefault();
      e.stopPropagation();
    },

    function onDrop(e) {
      if ( ! e.dataTransfer.types.some(function(m) { return m === 'application/x-foam-obj-id'; }) )
        return;

      var id = e.dataTransfer.getData('application/x-foam-obj-id');

      if ( foam.util.equals(id, this.data.id) ) return;

      e.preventDefault();
      e.stopPropagation();

      var self = this;
      var dao  = this.__context__[this.relationship.targetDAOKey];
      dao.find(id).then(function(obj) {
        if ( ! obj ) return null;

        // TODO: We shouldn't have to remove then put,
        // We currently have to because the FLOW editor is not updating properly
        // on a put event for an object that it already has.
        dao.remove(obj).then(function() {
          self.data[self.relationship.forwardName].dao.put(obj).then(function(obj) {
            self.onObjDrop(obj, id);
          });
        });
      });
    },

    function selected(e) {
      this.selection = this.data;
      e.preventDefault();
      e.stopPropagation();
    },

    function toggleExpanded(e) {
      this.expanded = ! this.expanded;
      this.selection = this.data;
      e.preventDefault();
      e.stopPropagation();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TreeView',
  extends: 'foam.u2.Element',

  requires: [
    'foam.mlang.ExpressionsSingleton',
    'foam.u2.view.TreeViewRow'
  ],

  exports: [
    'onObjDrop',
    'selection',
    'startExpanded'
  ],

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      name: 'relationship'
    },
    {
      name: 'selection'
    },
    {
      class: 'Function',
      name: 'formatter'
    },
    {
      class: 'Boolean',
      name: 'startExpanded',
      value: false
    }
  ],

  methods: [
    function initE() {
      var M   = this.ExpressionsSingleton.create();
      var of  = this.lookup(this.relationship.sourceModel);
      var dao = this.data$proxy.where(
        M.NOT(M.HAS(of.getAxiomByName(this.relationship.inverseName))));

      var self = this;
      this.addClass(this.myClass()).
        select(dao, function(obj) {
          return self.TreeViewRow.create({
            data: obj,
            relationship: self.relationship,
            expanded: self.startExpanded,
            formatter: self.formatter
          }, this);
        });
    },

    function onObjDrop(obj, target) {
      // Template Method
    }
  ]
});
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
  module: {},
  resolve: {
    alias: {
      vclub: path.resolve('./src'),
    },
  },
};
<commit_msg>add new config for webpack storybook<commit_after>const path = require('path');

module.exports = {
  module: {
    loaders: [
      {
        test: /.css$/,
        loaders: ['style', 'css?modules&importLoaders=1'],
      }
    ]
  },
  resolve: {
    alias: {
      vclub: path.resolve('./src'),
    },
  },
};
<|endoftext|>


<commit_before>// @flow
import template from './templates/field.hbs';
import dropdown from 'dropdown';
import ErrorButtonView from './views/ErrorButtonView';
import InfoButtonView from './views/InfoButtonView';
import TooltipPanelView from './views/TooltipPanelView';
import ErrosPanelView from './views/ErrosPanelView';
import formRepository from '../formRepository';

const classes = {
    REQUIRED: 'required',
    READONLY: 'readonly',
    DISABLED: 'disabled',
    ERROR: 'error'
};

export default Marionette.View.extend({
    initialize(options = {}) {
        this.schema = options.schema;

        this.fieldId = _.uniqueId('field-');

        this.__createEditor(options, this.fieldId,  _.isString(this.schema.type) ? formRepository.editors[this.schema.type] : this.schema.type);
        if (this.schema.getReadonly || this.schema.getHidden) {
            this.listenTo(this.model, 'change', this.__updateExternalChange);
        }
    },

    templateContext() {
        return {
            title: this.schema.title,
            fieldId: this.fieldId
        };
    },

    template: Handlebars.compile(template),

    regions: {
        editorRegion: {
            el: '.js-editor-region',
            replaceElement: true
        },
        errorTextRegion: '.js-error-text-region',
        helpTextRegion: '.js-help-text-region'
    },

    onRender() {
        this.showChildView('editorRegion', this.editor);
        if (this.schema.helpText) {
            this.__viewModel = new Backbone.Model({
                helpText: this.schema.helpText,
                errorText: null
            });

            const infoPopout = dropdown.factory.createPopout({
                buttonView: InfoButtonView,
                panelView: TooltipPanelView,
                panelViewOptions: {
                    model: this.__viewModel,
                    textAttribute: 'helpText'
                },
                popoutFlow: 'right',
                customAnchor: true
            });
            this.showChildView('helpTextRegion', infoPopout);
        }
        this.__rendered = true;
        this.setRequired(this.schema.required);
        this.__updateEditorState(this.schema.readonly, this.schema.enabled);
    },

    /**
     * Check the validity of the field
     *
     * @return {String}
     */
    validate() {
        const error = this.editor.validate();
        if (error) {
            this.setError([error]);
        } else {
            this.clearError();
        }
        return error;
    },

    setError(errors: Array<any>): void {
        if (!this.__checkUiReady()) {
            return;
        }

        this.$el.addClass(classes.ERROR);
        this.errorCollection ? this.errorCollection.reset(errors) : (this.errorCollection = new Backbone.Collection(errors));
        if (!this.isErrorShown) {
            const errorPopout = dropdown.factory.createPopout({
                buttonView: ErrorButtonView,
                panelView: ErrosPanelView,
                panelViewOptions: {
                    collection: this.errorCollection
                },
                popoutFlow: 'right',
                customAnchor: true
            });
            this.showChildView('errorTextRegion', errorPopout);
            this.isErrorShown = true;
        }
    },

    clearError(): void {
        if (!this.__checkUiReady()) {
            return;
        }
        this.$el.removeClass(classes.ERROR);
        this.errorCollection && this.errorCollection.reset();
    },

    /**
     * Update the model with the new value from the editor
     *
     * @return {Mixed}
     */
    commit() {
        return this.editor.commit();
    },

    /**
     * Get the value from the editor
     *
     * @return {Mixed}
     */
    getValue() {
        return this.editor.getValue();
    },

    /**
     * Set/change the value of the editor
     *
     * @param {Mixed} value
     */
    setValue(value) {
        this.editor.setValue(value);
    },

    /**
     * Give the editor focus
     */
    focus() {
        this.editor.focus();
    },

    /**
     * Remove focus from the editor
     */
    blur() {
        this.editor.blur();
    },

    setRequired(required) {
        if (!this.__checkUiReady()) {
            return;
        }
        this.$el.toggleClass(classes.REQUIRED, Boolean(required));
    },

    __updateEditorState(readonly, enabled) {
        if (!this.__checkUiReady()) {
            return;
        }
        this.$el.toggleClass(classes.READONLY, Boolean(readonly));
        this.$el.toggleClass(classes.DISABLED, Boolean(readonly || !enabled));
    },

    __updateExternalChange() {
        if (_.isFunction(this.schema.getReadonly)) {
            this.editor.setReadonly(this.schema.getReadonly(this.model));
        }
        if (_.isFunction(this.schema.getHidden)) {
            this.editor.setHidden(Boolean(this.schema.getHidden(this.model)));
        }
    },

    __createEditor(options, fieldId, ConstructorFn) {
        this.editor = new ConstructorFn({
            schema: this.schema,
            key: options.key,
            model: this.model,
            id: this.__createEditorId(options.key),
            value: this.options.value,
            fieldId
        });
        this.key = options.key;
        this.editor.on('readonly', readonly => {
            this.__updateEditorState(readonly, this.editor.getEnabled());
        });
        this.editor.on('enabled', enabled => {
            this.__updateEditorState(this.editor.getReadonly(), enabled);
        });
    },

    __createEditorId(key) {
        if (this.model) {
            return `${this.model.cid}_${key}`;
        }
        return key;
    },

    __checkUiReady() {
        return this.__rendered && !this.isDestroyed();
    }
});
<commit_msg>Returning editor missing options<commit_after>// @flow
import template from './templates/field.hbs';
import dropdown from 'dropdown';
import ErrorButtonView from './views/ErrorButtonView';
import InfoButtonView from './views/InfoButtonView';
import TooltipPanelView from './views/TooltipPanelView';
import ErrosPanelView from './views/ErrosPanelView';
import formRepository from '../formRepository';

const classes = {
    REQUIRED: 'required',
    READONLY: 'readonly',
    DISABLED: 'disabled',
    ERROR: 'error'
};

export default Marionette.View.extend({
    initialize(options = {}) {
        this.schema = options.schema;

        this.fieldId = _.uniqueId('field-');

        this.__createEditor(options, this.fieldId,  _.isString(this.schema.type) ? formRepository.editors[this.schema.type] : this.schema.type);
        if (this.schema.getReadonly || this.schema.getHidden) {
            this.listenTo(this.model, 'change', this.__updateExternalChange);
        }
    },

    templateContext() {
        return {
            title: this.schema.title,
            fieldId: this.fieldId
        };
    },

    template: Handlebars.compile(template),

    regions: {
        editorRegion: {
            el: '.js-editor-region',
            replaceElement: true
        },
        errorTextRegion: '.js-error-text-region',
        helpTextRegion: '.js-help-text-region'
    },

    onRender() {
        this.showChildView('editorRegion', this.editor);
        if (this.schema.helpText) {
            this.__viewModel = new Backbone.Model({
                helpText: this.schema.helpText,
                errorText: null
            });

            const infoPopout = dropdown.factory.createPopout({
                buttonView: InfoButtonView,
                panelView: TooltipPanelView,
                panelViewOptions: {
                    model: this.__viewModel,
                    textAttribute: 'helpText'
                },
                popoutFlow: 'right',
                customAnchor: true
            });
            this.showChildView('helpTextRegion', infoPopout);
        }
        this.__rendered = true;
        this.setRequired(this.schema.required);
        this.__updateEditorState(this.schema.readonly, this.schema.enabled);
    },

    /**
     * Check the validity of the field
     *
     * @return {String}
     */
    validate() {
        const error = this.editor.validate();
        if (error) {
            this.setError([error]);
        } else {
            this.clearError();
        }
        return error;
    },

    setError(errors: Array<any>): void {
        if (!this.__checkUiReady()) {
            return;
        }

        this.$el.addClass(classes.ERROR);
        this.errorCollection ? this.errorCollection.reset(errors) : (this.errorCollection = new Backbone.Collection(errors));
        if (!this.isErrorShown) {
            const errorPopout = dropdown.factory.createPopout({
                buttonView: ErrorButtonView,
                panelView: ErrosPanelView,
                panelViewOptions: {
                    collection: this.errorCollection
                },
                popoutFlow: 'right',
                customAnchor: true
            });
            this.showChildView('errorTextRegion', errorPopout);
            this.isErrorShown = true;
        }
    },

    clearError(): void {
        if (!this.__checkUiReady()) {
            return;
        }
        this.$el.removeClass(classes.ERROR);
        this.errorCollection && this.errorCollection.reset();
    },

    /**
     * Update the model with the new value from the editor
     *
     * @return {Mixed}
     */
    commit() {
        return this.editor.commit();
    },

    /**
     * Get the value from the editor
     *
     * @return {Mixed}
     */
    getValue() {
        return this.editor.getValue();
    },

    /**
     * Set/change the value of the editor
     *
     * @param {Mixed} value
     */
    setValue(value) {
        this.editor.setValue(value);
    },

    /**
     * Give the editor focus
     */
    focus() {
        this.editor.focus();
    },

    /**
     * Remove focus from the editor
     */
    blur() {
        this.editor.blur();
    },

    setRequired(required) {
        if (!this.__checkUiReady()) {
            return;
        }
        this.$el.toggleClass(classes.REQUIRED, Boolean(required));
    },

    __updateEditorState(readonly, enabled) {
        if (!this.__checkUiReady()) {
            return;
        }
        this.$el.toggleClass(classes.READONLY, Boolean(readonly));
        this.$el.toggleClass(classes.DISABLED, Boolean(readonly || !enabled));
    },

    __updateExternalChange() {
        if (_.isFunction(this.schema.getReadonly)) {
            this.editor.setReadonly(this.schema.getReadonly(this.model));
        }
        if (_.isFunction(this.schema.getHidden)) {
            this.editor.setHidden(Boolean(this.schema.getHidden(this.model)));
        }
    },

    __createEditor(options, fieldId, ConstructorFn) {
        this.editor = new ConstructorFn({
            schema: this.schema,
            form: options.form,
            field: this,
            key: options.key,
            model: this.model,
            id: this.__createEditorId(options.key),
            value: this.options.value,
            fieldId
        });
        this.key = options.key;
        this.editor.on('readonly', readonly => {
            this.__updateEditorState(readonly, this.editor.getEnabled());
        });
        this.editor.on('enabled', enabled => {
            this.__updateEditorState(this.editor.getReadonly(), enabled);
        });
    },

    __createEditorId(key) {
        if (this.model) {
            return `${this.model.cid}_${key}`;
        }
        return key;
    },

    __checkUiReady() {
        return this.__rendered && !this.isDestroyed();
    }
});
<|endoftext|>


<commit_before>const yt = require('ytdl-core');
const fs = require('fs');
const msg = require('./../msg/');

var playlist = [];
var stream = [];
var current = [];

exports.sound = sound;
exports.play = play;
exports.add = add;
exports.skip = skip;
exports.stop = stop;

//A function to keep playing that stream
function sound(message) {
	var voiceChannel = message.member.voiceChannel;

	voiceChannel.join()
	.then(connnection => {
		//Declare a function that will be called by itself so the play(message) command will be called when required, instead of all at once.
		var looper = function() {
			play(message);
			const dispatcher = connnection.playStream(stream[message.guild.id]);
			dispatcher.on('end', () => {
				looper();
			});
		}
		looper();
	});
}

//A function to generate the streams from the playlist
function play(message) {
	var voiceChannel = message.member.voiceChannel;

	if(!voiceChannel) {
		//Not in voice
		return MSS.msg.react(message, false, "call");
	}

	if (playlist[message.guild.id].length > 0) {
		current[message.guild.id] = JSON.parse(playlist[message.guild.id].shift());
		message.channel.sendMessage('**Music Control Panel**')
			.then(function(message) {
				message.react(String.fromCodePoint(10145));
				message.react(String.fromCodePoint(8505));
				message.react(String.fromCodePoint(128240));
			});
		switch (current[message.guild.id]["type"]) {
			case "youtube":
				stream[message.guild.id] = yt(current[message.guild.id]["url"], {audioonly: true});
				break;
			case "local":
				stream[message.guild.id] = fs.createReadStream(current[message.guild.id]["url"]);
				break;
		}
	} else {
		if (voiceChannel && voiceChannel.connection) voiceChannel.leave();
		playlist[message.guild.id] = [];
		if (stream[message.guild.id]) stream[message.guild.id].destroy();
		message.reply("The playlist has ended.");
		return;
	}
}

//A function to push a new video onto the playlist stack
function add(message, type, url, title, thumb_url) {
	playlist[message.guild.id] = playlist[message.guild.id] || [];
	playlist[message.guild.id].push(JSON.stringify({type: type, url: url, title: title, thumb_url: thumb_url}));
	if (!message.member.voiceChannel.connection) {
		sound(message);
	}
}

function skip(message) {
	let voiceChannel = message.member.voiceChannel;

	if (!voiceChannel || !voiceChannel.connection) {
		//No bot in channel
		return msg.react(false, "robot");
	}

	message.channel.send("Destroying stream...");
	stream[message.guild.id].destroy();
}

function stop(message) {
	let voiceChannel = message.member.voiceChannel;

	if (!voiceChannel || !voiceChannel.connection) {
		//No bot in channel
		return msg.react(false, "robot");
	}

	playlist[message.guild.id] = [];
	skip(message);
}
<commit_msg>Forgot to put message into  msg.react<commit_after>const yt = require('ytdl-core');
const fs = require('fs');
const msg = require('./../msg/');

var playlist = [];
var stream = [];
var current = [];

exports.sound = sound;
exports.play = play;
exports.add = add;
exports.skip = skip;
exports.stop = stop;

//A function to keep playing that stream
function sound(message) {
	var voiceChannel = message.member.voiceChannel;

	voiceChannel.join()
	.then(connnection => {
		//Declare a function that will be called by itself so the play(message) command will be called when required, instead of all at once.
		var looper = function() {
			play(message);
			const dispatcher = connnection.playStream(stream[message.guild.id]);
			dispatcher.on('end', () => {
				looper();
			});
		}
		looper();
	});
}

//A function to generate the streams from the playlist
function play(message) {
	var voiceChannel = message.member.voiceChannel;

	if(!voiceChannel) {
		//Not in voice
		return MSS.msg.react(message, false, "call");
	}

	if (playlist[message.guild.id].length > 0) {
		current[message.guild.id] = JSON.parse(playlist[message.guild.id].shift());
		message.channel.sendMessage('**Music Control Panel**')
			.then(function(message) {
				message.react(String.fromCodePoint(10145));
				message.react(String.fromCodePoint(8505));
				message.react(String.fromCodePoint(128240));
			});
		switch (current[message.guild.id]["type"]) {
			case "youtube":
				stream[message.guild.id] = yt(current[message.guild.id]["url"], {audioonly: true});
				break;
			case "local":
				stream[message.guild.id] = fs.createReadStream(current[message.guild.id]["url"]);
				break;
		}
	} else {
		if (voiceChannel && voiceChannel.connection) voiceChannel.leave();
		playlist[message.guild.id] = [];
		if (stream[message.guild.id]) stream[message.guild.id].destroy();
		message.reply("The playlist has ended.");
		return;
	}
}

//A function to push a new video onto the playlist stack
function add(message, type, url, title, thumb_url) {
	playlist[message.guild.id] = playlist[message.guild.id] || [];
	playlist[message.guild.id].push(JSON.stringify({type: type, url: url, title: title, thumb_url: thumb_url}));
	if (!message.member.voiceChannel.connection) {
		sound(message);
	}
}

function skip(message) {
	let voiceChannel = message.member.voiceChannel;

	if (!voiceChannel || !voiceChannel.connection) {
		//No bot in channel
		return msg.react(message, false, "robot");
	}

	message.channel.send("Destroying stream...");
	stream[message.guild.id].destroy();
}

function stop(message) {
	let voiceChannel = message.member.voiceChannel;

	if (!voiceChannel || !voiceChannel.connection) {
		//No bot in channel
		return msg.react(message, false, "robot");
	}

	playlist[message.guild.id] = [];
	skip(message);
}

<|endoftext|>


<commit_before><commit_msg>add GridGallery class constructor to the window global object<commit_after><|endoftext|>


<commit_before>/**
 * Contains functions for actually commiting changes to the backend, mutating the interior composition tree
 * and causing the changes to be reflected in the visualization.
 */

import R from 'ramda';

import { getNodeData } from 'src/data/compositionTree/nodeTypes';
import { addNode, deleteNode, replaceNode } from 'src/interop';
import { denormalizeNode } from 'src/helpers/compositionTree/normalization';
import { getLeafAttr, getNodeParent } from 'src/selectors/compositionTree';
import { NULL_UUID } from 'src/data/misc';
import { mapIdsToEntites } from 'src/helpers/compositionTree/util';

/**
 * Finds the path to a node in the composition tree and returns it as an array of integers.
 */
const getNodeCoords = (entities, nodeId) => {
  let coordBuf = [];
  let curId = nodeId;

  while(true) {
    if(curId === NULL_UUID) {
      break;
    }

    const { id, type, settings, children } = getNodeParent(entities.nodes, curId);

    const indexOffset = getLeafAttr('indexOffset', getNodeData(type), mapIdsToEntites(entities.settings, settings));
    coordBuf = [children.indexOf(curId) - indexOffset, ...coordBuf];

    curId = id;
  }

  return coordBuf;
};

export const commitChanges = (entities, { new: newNodes, updated: updatedNodes, deleted: deletedNodes }) => {
  // console.log('COMMITING CHANGES: ', newNodes, updatedNodes, deletedNodes);

  // first handle all deleted nodes
  deletedNodes.forEach( ({ id, parentId, index }) => {
    const coords = getNodeCoords(entities, parentId);
    const { type: parentType, settings: parentSettingIds } = entities.nodes[parentId];
    const parentSettings = mapIdsToEntites(entities.settings, parentSettingIds);
    const indexOffset = getLeafAttr('indexOffset', getNodeData(parentType), parentSettings);

    deleteNode(coords, index - indexOffset);
  });

  // then, replace all modified nodes with newly-built versions.
  updatedNodes.forEach(nodeId => {
    const def = JSON.stringify(denormalizeNode(entities, nodeId));
    const coords = getNodeCoords(entities, nodeId);

    // console.log("Replacing node: ", def);
    replaceNode(R.init(coords), R.last(coords), def);
  });

  // finally, handle all new nodes, parsing them into their denormalized form and creating them on the backend
  newNodes.forEach(nodeId => {
    // only add it if it's of type `'noiseModule'`
    if(entities.nodes[nodeId].type === 'noiseModule') {
      const def = JSON.stringify(denormalizeNode(entities, nodeId));
      const coords = getNodeCoords(entities, nodeId);

      // Allocate memory in the Emscripten heap and call the backend function
      // console.log("Adding node: ", def);
      addNode(R.init(coords), R.last(coords), def);
    }
  });
};
<commit_msg>Handle issue when changing from composed node to leaf node<commit_after>/**
 * Contains functions for actually commiting changes to the backend, mutating the interior composition tree
 * and causing the changes to be reflected in the visualization.
 */

import R from 'ramda';

import { getNodeData } from 'src/data/compositionTree/nodeTypes';
import { addNode, deleteNode, replaceNode } from 'src/interop';
import { denormalizeNode } from 'src/helpers/compositionTree/normalization';
import { getLeafAttr, getNodeParent, getSettingByName } from 'src/selectors/compositionTree';
import { NULL_UUID } from 'src/data/misc';
import { mapIdsToEntites } from 'src/helpers/compositionTree/util';

/**
 * Finds the path to a node in the composition tree and returns it as an array of integers.
 */
const getNodeCoords = (entities, nodeId) => {
  let coordBuf = [];
  let curId = nodeId;

  while(true) {
    if(curId === NULL_UUID) {
      break;
    }

    const parentNode = getNodeParent(entities.nodes, curId);
    if(!parentNode) {
      return false;
    }
    const { id, type, settings, children } = parentNode;

    const indexOffset = getLeafAttr('indexOffset', getNodeData(type), mapIdsToEntites(entities.settings, settings));
    coordBuf = [children.indexOf(curId) - indexOffset, ...coordBuf];

    curId = id;
  }

  return coordBuf;
};

export const commitChanges = (entities, { new: newNodes, updated: updatedNodes, deleted: deletedNodes }) => {
  // console.log('COMMITING CHANGES: ', newNodes, updatedNodes, deletedNodes);

  // first handle all deleted nodes
  deletedNodes.forEach( ({ id, parentId, index }) => {
    const coords = getNodeCoords(entities, parentId);
    if(coords === false) {
      // node's parent has been deleted already so we don't have to do anything
      return;
    }

    const { type: parentType, settings: parentSettingIds } = entities.nodes[parentId];
    const mappedParentSettings = mapIdsToEntites(entities.settings, parentSettingIds);

    // don't try to delete this if the parent node isn't composed (switching from composed node to leaf node)
    const parentModuleType = getSettingByName(mappedParentSettings, 'moduleType');
    if(parentModuleType !== 'Composed' && parentType !== 'root') {
      return;
    }

    const parentSettings = mapIdsToEntites(entities.settings, parentSettingIds);
    const indexOffset = getLeafAttr('indexOffset', getNodeData(parentType), parentSettings);

    deleteNode(coords, index - indexOffset);
  });

  // then, replace all modified nodes with newly-built versions.
  updatedNodes.forEach(nodeId => {
    const def = JSON.stringify(denormalizeNode(entities, nodeId));
    const coords = getNodeCoords(entities, nodeId);

    // console.log("Replacing node: ", def);
    replaceNode(R.init(coords), R.last(coords), def);
  });

  // finally, handle all new nodes, parsing them into their denormalized form and creating them on the backend
  newNodes.forEach(nodeId => {
    // only add it if it's of type `'noiseModule'`
    if(entities.nodes[nodeId].type === 'noiseModule') {
      const def = JSON.stringify(denormalizeNode(entities, nodeId));
      const coords = getNodeCoords(entities, nodeId);

      // Allocate memory in the Emscripten heap and call the backend function
      // console.log("Adding node: ", def);
      addNode(R.init(coords), R.last(coords), def);
    }
  });
};
<|endoftext|>


<commit_before><commit_msg>fixed loading progress calculation<commit_after><|endoftext|>


<commit_before><commit_msg>Removed id column from Admin table<commit_after><|endoftext|>


<commit_before>/**
 * @fileoverview
 * HTTP logger service
 */

var cls = window.cls || ( window.cls = {} );

/**
  * HTTP logger class
  * @constructor
  * @extends ServiceBase
  */
cls.HTTPLoggerService = function(name)
{
    var self = this;
    var view = "http_logger";

    this.onreceive = function(xml) // only called if there is a xml
    {
        //opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + xml.documentElement.nodeName);
        if( ini.debug )
        {
            debug.logEvents(xml);
        }

        if( self[xml.documentElement.nodeName] )
        {
            self[xml.documentElement.nodeName](xml)
        }
        else
        {
            opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
              "http-logger not handled: " + new XMLSerializer().serializeToString(xml))
        }
    }

  // events supported: request, response

    this['request'] = function(msg)
    {
        var data = this.parseRequest(msg);
        //opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + "just parsed a request:\n" + JSON.stringify(data));
        HTTPLoggerData.addRequest(data);
    }

    this['response'] = function(msg)
    {
        var data = this.parseResponse(msg);
        //opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + "just parsed a response:\n" + JSON.stringify(data))
        HTTPLoggerData.addResponse(data);
    }

    this.onconnect = function(xml)
    {
    }

    var onAplicationsetup = function()
    {
    }

    /**
     * Parse a request. Returns an object with the shape:
     * request = {
     *  request-id: 123,
     *  window-id: 234,
     *  time: 345,
     *  method: "GET/POST/..",
     *  path: "/foo/bar/baz",
     *  query: "?asdf=morradi",
     *  queryDict: {asdf: "morradi"}
     *  headers: {
     *            headername1, value: headerval1,
     *            headername2, value: [headerval2_a, headerval2_b]
     *           }
     * }
     *
     */
    this.parseRequest = function(request)
    {
        var retval = {};
        var children = request.documentElement.childNodes;
        for (var n=0, ele; ele=children[n]; n++)
        {
            if (ele.nodeName == "header")
            {
                retval.raw = ele.textContent;
                var hd = this.parseRequestHeader(ele);
                retval.headers = hd.headers;
                retval.method = hd.method;
                retval.path = hd.path;
                retval.query = hd.query;
                retval.queryDict = hd.queryDict;
                retval.protocol = hd.protocol;
            }
            else
            {
                retval[ele.nodeName] = ele.textContent;
            }
        }

        retval.url = retval.headers.Host + retval.path
        return retval;
    }

    /**
     * Parse a response. Returns an object with the shape:
     * response = {
     *  request-id: 123,
     *  window-id: 234,
     *  time: 345,
     *  protocol: "HTTP 1/1",
     *  status: 200,
     *  reason: OK
     *  headers: {
     *            headername1, value: headerval1,
     *            headername2, value: [headerval2_a, headerval2_b]
     *           }
     * }
     *
     */
    this.parseResponse = function(response)
    {
        var retval = {};
        var children = response.documentElement.childNodes;
        for (var n=0, ele; ele=children[n]; n++)
        {
            if (ele.nodeName == "header")
            {
                retval.raw = ele.textContent;
                var hd = this.parseResponseHeader(ele);
                if (!hd) {
                    opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
                      "could not parse response header")
                    continue;
                }
                retval.protocol= hd.protocol;
                retval.status = hd.status;
                retval.reason = hd.reason;
                retval.headers = hd.headers;
            }
            else
            {
                retval[ele.nodeName] = ele.textContent;
            }
        }
        return retval;
    }

    /**
     * Parse a request header, returns an object with the shape:
     *
     * requst was GET http://example.com/foo?bar=baz&meh=flabaten
     *
     * header = {
     *            method: "GET",
     *            path: "/foo",
     *            protocol: "http",
     *            query: {
     *                  bar: "baz",
     *                  meh: "flabaten"
     *            }
     *            headers: {
     *                  name1: "value1",
     *                  name2: "value2
     *            }
     *  }
     *
     *
     */
    this.parseRequestHeader = function(ele)
    {
        var retval = {};
        var txt = ele.textContent;
        var lines = txt.split("\n");

        var requestline = lines.shift();
        reqparts = requestline.match(/(\w*?) (.*) (.*)/);

        if (!reqparts || reqparts.length != 4) {
            opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
              "Could not parse request:\n" + txt);
            return null;
        }

        retval.method = reqparts[1];
        retval.query = "";
        retval.path = reqparts[2];

        var i;
        if ((i = retval.path.indexOf("?")) > 0)
        {
            retval.query = retval.path.slice(i);
            retval.queryDict = {};
            retval.query.substr(1).split("&").forEach(function(e)
            {
                var offset = e.indexOf("=");
                if (offset<1) { return }
                var key = e.substr(0, offset);
                var val = e.substr(offset+1);
                retval.queryDict[key] = val;
            })

            retval.path = retval.path.slice(0, i);
        }

        retval.protocol = reqparts[3];
        retval.headers = this.parseHeaders(lines);

        return retval;
    }

    /**
     * Parse a response header into a dictionary of the shape
     * header = {
     *     protocol: "http",
     *     status: "200",
     *     reason: "OK",
     *     headers: <dictionary of http headers parsed by parseHeaders()>
     * }
     *
     */
    this.parseResponseHeader = function(ele)
    {
        var retval = {};
        var txt = ele.textContent;
        var lines = txt.split("\n");
        var respline = lines.shift();

        respparts = respline.match(/(\w*?) (\w*?) (.*)/);

        if (!respparts || respparts.length != 4) {
            opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
              "Could not parse response:\n" + respline);
            return null;
        }

        retval.protocol = respparts[1];
        retval.status = respparts[2];
        retval.reason = respparts[3];
        retval.headers = this.parseHeaders(lines);

        return retval;
    }

    /**
     * Parse the raw request block, including method, path and headers
     * @argument {Element}
     */
    this.parseHeaders = function(lines)
    {
        var headers = {};
        for (var n=0, line; line=lines[n]; n++)
        {
            var parts = line.match(/([\w-]*?): (.*)/);
            var name = parts[1];
            var value = parts[2];

            if (name in headers) {
                if (typeof headers[name] == "string")
                {
                    headers[name] = [headers[name], parts[1]];
                }
                else
                {
                    headers[name].push(value);
                }
            }
            else
            {
                headers[name] = value;
            }
        }
        return headers;
    }

  // constructor calls

    this.initBase(name);

    if( ! client)
    {
        opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + 'client does not exist');
        return;
    }
    client.addService(this);

  // messages.addListener('application-setup', onAplicationsetup);
}

cls.HTTPLoggerService.prototype = ServiceBase;
new cls.HTTPLoggerService('http-logger');
<commit_msg>Added a sanity check to header parsing so we don't get an exception with malformed headers. ( To test malformed headers: http://twop.com  )<commit_after>/**
 * @fileoverview
 * HTTP logger service
 */

var cls = window.cls || ( window.cls = {} );

/**
  * HTTP logger class
  * @constructor
  * @extends ServiceBase
  */
cls.HTTPLoggerService = function(name)
{
    var self = this;
    var view = "http_logger";

    this.onreceive = function(xml) // only called if there is a xml
    {
        //opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + xml.documentElement.nodeName);
        if( ini.debug )
        {
            debug.logEvents(xml);
        }

        if( self[xml.documentElement.nodeName] )
        {
            self[xml.documentElement.nodeName](xml)
        }
        else
        {
            opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
              "http-logger not handled: " + new XMLSerializer().serializeToString(xml))
        }
    }

  // events supported: request, response

    this['request'] = function(msg)
    {
        var data = this.parseRequest(msg);
        //opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + "just parsed a request:\n" + JSON.stringify(data));
        HTTPLoggerData.addRequest(data);
    }

    this['response'] = function(msg)
    {
        var data = this.parseResponse(msg);
        //opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + "just parsed a response:\n" + JSON.stringify(data))
        HTTPLoggerData.addResponse(data);
    }

    this.onconnect = function(xml)
    {
    }

    var onAplicationsetup = function()
    {
    }

    /**
     * Parse a request. Returns an object with the shape:
     * request = {
     *  request-id: 123,
     *  window-id: 234,
     *  time: 345,
     *  method: "GET/POST/..",
     *  path: "/foo/bar/baz",
     *  query: "?asdf=morradi",
     *  queryDict: {asdf: "morradi"}
     *  headers: {
     *            headername1, value: headerval1,
     *            headername2, value: [headerval2_a, headerval2_b]
     *           }
     * }
     *
     */
    this.parseRequest = function(request)
    {
        var retval = {};
        var children = request.documentElement.childNodes;
        for (var n=0, ele; ele=children[n]; n++)
        {
            if (ele.nodeName == "header")
            {
                retval.raw = ele.textContent;
                var hd = this.parseRequestHeader(ele);
                retval.headers = hd.headers;
                retval.method = hd.method;
                retval.path = hd.path;
                retval.query = hd.query;
                retval.queryDict = hd.queryDict;
                retval.protocol = hd.protocol;
            }
            else
            {
                retval[ele.nodeName] = ele.textContent;
            }
        }

        retval.url = retval.headers.Host + retval.path
        return retval;
    }

    /**
     * Parse a response. Returns an object with the shape:
     * response = {
     *  request-id: 123,
     *  window-id: 234,
     *  time: 345,
     *  protocol: "HTTP 1/1",
     *  status: 200,
     *  reason: OK
     *  headers: {
     *            headername1, value: headerval1,
     *            headername2, value: [headerval2_a, headerval2_b]
     *           }
     * }
     *
     */
    this.parseResponse = function(response)
    {
        var retval = {};
        var children = response.documentElement.childNodes;
        for (var n=0, ele; ele=children[n]; n++)
        {
            if (ele.nodeName == "header")
            {
                retval.raw = ele.textContent;
                var hd = this.parseResponseHeader(ele);
                if (!hd) {
                    opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
                      "could not parse response header")
                    continue;
                }
                retval.protocol= hd.protocol;
                retval.status = hd.status;
                retval.reason = hd.reason;
                retval.headers = hd.headers;
            }
            else
            {
                retval[ele.nodeName] = ele.textContent;
            }
        }
        return retval;
    }

    /**
     * Parse a request header, returns an object with the shape:
     *
     * requst was GET http://example.com/foo?bar=baz&meh=flabaten
     *
     * header = {
     *            method: "GET",
     *            path: "/foo",
     *            protocol: "http",
     *            query: {
     *                  bar: "baz",
     *                  meh: "flabaten"
     *            }
     *            headers: {
     *                  name1: "value1",
     *                  name2: "value2
     *            }
     *  }
     *
     *
     */
    this.parseRequestHeader = function(ele)
    {
        var retval = {};
        var txt = ele.textContent;
        var lines = txt.split("\n");

        var requestline = lines.shift();
        reqparts = requestline.match(/(\w*?) (.*) (.*)/);

        if (!reqparts || reqparts.length != 4) {
            opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
              "Could not parse request:\n" + txt);
            return null;
        }

        retval.method = reqparts[1];
        retval.query = "";
        retval.path = reqparts[2];

        var i;
        if ((i = retval.path.indexOf("?")) > 0)
        {
            retval.query = retval.path.slice(i);
            retval.queryDict = {};
            retval.query.substr(1).split("&").forEach(function(e)
            {
                var offset = e.indexOf("=");
                if (offset<1) { return }
                var key = e.substr(0, offset);
                var val = e.substr(offset+1);
                retval.queryDict[key] = val;
            })

            retval.path = retval.path.slice(0, i);
        }

        retval.protocol = reqparts[3];
        retval.headers = this.parseHeaders(lines);

        return retval;
    }

    /**
     * Parse a response header into a dictionary of the shape
     * header = {
     *     protocol: "http",
     *     status: "200",
     *     reason: "OK",
     *     headers: <dictionary of http headers parsed by parseHeaders()>
     * }
     *
     */
    this.parseResponseHeader = function(ele)
    {
        var retval = {};
        var txt = ele.textContent;
        var lines = txt.split("\n");
        var respline = lines.shift();

        respparts = respline.match(/(\w*?) (\w*?) (.*)/);

        if (!respparts || respparts.length != 4) {
            opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
              "Could not parse response:\n" + respline);
            return null;
        }

        retval.protocol = respparts[1];
        retval.status = respparts[2];
        retval.reason = respparts[3];
        retval.headers = this.parseHeaders(lines);

        return retval;
    }

    /**
     * Parse the raw request block, including method, path and headers
     * @argument {Element}
     */
    this.parseHeaders = function(lines)
    {
        var headers = {};
        for (var n=0, line; line=lines[n]; n++)
        {
            var parts = line.match(/([\w-]*?): (.*)/);
            if (!parts || parts.length!=3) {
                opera.postError("Could not parse header!:\n" + line)
                continue;
            }
            var name = parts[1];
            var value = parts[2];

            if (name in headers) {
                if (typeof headers[name] == "string")
                {
                    headers[name] = [headers[name], parts[1]];
                }
                else
                {
                    headers[name].push(value);
                }
            }
            else
            {
                headers[name] = value;
            }
        }
        return headers;
    }

  // constructor calls

    this.initBase(name);

    if( ! client)
    {
        opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + 'client does not exist');
        return;
    }
    client.addService(this);

  // messages.addListener('application-setup', onAplicationsetup);
}

cls.HTTPLoggerService.prototype = ServiceBase;
new cls.HTTPLoggerService('http-logger');
<|endoftext|>


<commit_before><commit_msg>Clean code<commit_after><|endoftext|>


<commit_before><commit_msg>add icon class name<commit_after><|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Jun 17 2017 00:55:49 GMT+0800 (CST)

module.exports = function(config) {
  const customLanchers = {
    'SL_Chrome': {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '45'
    },
    'SL_Firefox': {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '45'
    },
    'SL_Safari_8': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10',
      version: '8'
    },
    'SL_Safari_9': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11',
      version: '9'
    },
    'SL_Safari_10': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.12',
      version: '10'
    },
    'SL_IE_8': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows XP',
      version: '8'
    },
    'SL_IE_9': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    'SL_IE_10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    },
    'SL_IE_11': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '11'
    },
    'SL_EDGE': {
      base: 'SauceLabs',
      browserName: 'microsoftedge',
      platform: 'Windows 10',
      version: '14'
    },
    'SL_iOS_8_1': {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'iPhone 6',
      version: '8.1'
    },
    'SL_iOS_9_0': {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'iPhone 6',
      version: '9.0'
    },
    'SL_iOS_10_2': {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'iPhone 7',
      version: '10.2'
    },
    'SL_Android_4_4': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '4.4'
    },
    'SL_Android_5': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5'
    },
    'SL_Android_6': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '6'
    },
    'SL_Android_7': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '7'
    },
  };

  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      'node_modules/chai/chai.js',
      'dist/tiny-cookie.js',
      'test/setup.js',
      'test/index.spec.js'
    ],
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: false,
    browsers: Object.keys(customLaunchers),
    sauceLabs: {
      testName: 'tiny-cookie'
    },
    customLanchers: customLaunchers,
    singleRun: true,
    concurrency: Infinity
  })
}
<commit_msg>Fix typo<commit_after>// Karma configuration
// Generated on Sat Jun 17 2017 00:55:49 GMT+0800 (CST)

module.exports = function(config) {
  const customLaunchers = {
    'SL_Chrome': {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '45'
    },
    'SL_Firefox': {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '45'
    },
    'SL_Safari_8': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10',
      version: '8'
    },
    'SL_Safari_9': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11',
      version: '9'
    },
    'SL_Safari_10': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.12',
      version: '10'
    },
    'SL_IE_8': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows XP',
      version: '8'
    },
    'SL_IE_9': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    'SL_IE_10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    },
    'SL_IE_11': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '11'
    },
    'SL_EDGE': {
      base: 'SauceLabs',
      browserName: 'microsoftedge',
      platform: 'Windows 10',
      version: '14'
    },
    'SL_iOS_8_1': {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'iPhone 6',
      version: '8.1'
    },
    'SL_iOS_9_0': {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'iPhone 6',
      version: '9.0'
    },
    'SL_iOS_10_2': {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'iPhone 7',
      version: '10.2'
    },
    'SL_Android_4_4': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '4.4'
    },
    'SL_Android_5': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5'
    },
    'SL_Android_6': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '6'
    },
    'SL_Android_7': {
      base: 'SauceLabs',
      browserName: 'android',
      version: '7'
    },
  };

  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      'node_modules/chai/chai.js',
      'dist/tiny-cookie.js',
      'test/setup.js',
      'test/index.spec.js'
    ],
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: false,
    browsers: Object.keys(customLaunchers),
    sauceLabs: {
      testName: 'tiny-cookie'
    },
    customLaunchers: customLaunchers,
    singleRun: true,
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before><commit_msg>Need to provide instance name (#304)<commit_after><|endoftext|>