<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import FlowGrid from 'gComponents/lib/FlowGrid/FlowGrid'
import Metric from 'gComponents/metrics/card/index'

import {denormalizedSpaceSelector} from '../denormalized-space-selector'

import {addMetric, changeMetric, removeMetrics} from 'gModules/metrics/actions'
import {changeSelect, deSelect} from 'gModules/selected_cell/actions'
import {selectRegion, deSelectRegion} from 'gModules/selected_region/actions'
import {runSimulations, deleteSimulations} from 'gModules/simulations/actions'
import * as canvasStateActions from 'gModules/canvas_state/actions'
import {undo, redo} from 'gModules/checkpoints/actions'
import {fillRegion} from 'gModules/auto_fill_region/actions'

import {hasMetricUpdated} from 'gComponents/metrics/card/updated'
import * as canvasStateProps from 'gModules/canvas_state/prop_type'

import * as segment from 'servers/segment'

import './style.css'

import {isLocation, isAtLocation, existsAtLoc, isWithinRegion} from 'lib/locationUtils.js'

function mapStateToProps(state) {
  return {
    copied: state.copied,
    selectedCell: state.selectedCell,
    selectedRegion: state.selectedRegion,
  }
}

const PT = PropTypes;
@connect(mapStateToProps)
export default class Canvas extends Component{
  static propTypes = {
    denormalizedSpace: PropTypes.object,
    dispatch: PropTypes.func,
    selectedCell: PropTypes.object,
    embed: PropTypes.bool,
  }

  static defaultProps = {
    screenshot: false
  }

  componentDidMount(){
    window.recorder.recordMountEvent(this)

    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    if (!_.isEmpty(metrics) && metrics.length > 19){
      this.props.dispatch(canvasStateActions.change({edgeView: 'hidden'}))
    } else {
      this.props.dispatch(canvasStateActions.change({edgeView: 'visible'}))
    }
    this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))

    if (this.props.screenshot) {
      this.props.dispatch(canvasStateActions.change({metricCardView: 'display'}))
    }
  }

  componentWillUpdate() { window.recorder.recordRenderStartEvent(this) }

  componentDidUpdate(prevProps) {
    window.recorder.recordRenderStopEvent(this)

    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    const oldMetrics = _.get(prevProps.denormalizedSpace, 'metrics')
    if ((oldMetrics.length === 0) && (metrics.length > 0)){
      this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))
    }
  }

  componentWillUnmount(){
    window.recorder.recordUnmountEvent(this)
    this.props.dispatch(deleteSimulations(this.props.denormalizedSpace.metrics.map(m => m.id)))
  }

  _handleUndo() {
    segment.trackUndo(true)
    this.props.dispatch(undo(this.props.denormalizedSpace.id))
  }

  _handleRedo() {
    segment.trackUndo(true)
    this.props.dispatch(redo(this.props.denormalizedSpace.id))
  }

  _handleSelect(location, selectedFrom = null) {
    this.props.dispatch(changeSelect(location, selectedFrom))
    this.props.dispatch(selectRegion(location, location))
  }

  _handleMultipleSelect(corner1, corner2) {
    if (!isAtLocation(corner1, corner2)) { segment.trackSelectedRegion() }
    this.props.dispatch(selectRegion(corner1, corner2))
  }

  _handleDeSelectAll() {
    this.props.dispatch(deSelect())
    this.props.dispatch(deSelectRegion())
  }

  _handleAddMetric(location) {
    this.props.dispatch(addMetric({space: this.props.denormalizedSpace.id, location: location}))
  }

  _handleMoveMetric({prev, next}) {
    if (_.some(this.props.denormalizedSpace.metrics, existsAtLoc(next))) { return }

    const metric = this.props.denormalizedSpace.metrics.find(existsAtLoc(prev))
    this.props.dispatch(changeMetric({id: metric.id, location: next}))
    this.props.dispatch(changeSelect(next))
  }

  _selectedMetric() {
   const {selectedCell} = this.props
   const metrics = _.get(this.props.denormalizedSpace, 'metrics')

   return metrics && isLocation(selectedCell) && metrics.find(existsAtLoc(selectedCell))
  }

  _isAnalysisView(props = this.props) {
    return (_.get(props, 'denormalizedSpace.canvasState.metricCardView') === 'analysis')
  }

  isMetricEmpty(id) {
    const metric = this.props.denormalizedSpace.metrics.find(m => m.id === id)
    const {input, data} = metric.guesstimate
    return _.isEmpty(metric.name) && _.isEmpty(input) && _.isEmpty(data)
  }

  renderMetric(metric, selected) {
    const {location} = metric
    const hasSelected = selected && metric
    const selectedSamples = _.get(selected, 'simulation.sample.values')
    const passSelected = hasSelected && selectedSamples && !_.isEmpty(selectedSamples)

    const is_private = _.get(this, 'props.denormalizedSpace.is_private')
    const organizationId = _.get(this, 'props.denormalizedSpace.organization_id')
    const canUseOrganizationFacts = !!is_private && !!this.props.organizationHasFacts && !!organizationId
    return (
      <Metric
        canvasState={this.props.denormalizedSpace.canvasState}
        key={metric.id}
        location={location}
        metric={metric}
        organizationId={organizationId}
        canUseOrganizationFacts={canUseOrganizationFacts}
        analyzedMetric={passSelected && selected}
      />
    )
  }

  showEdges() {
    return (this.props.denormalizedSpace.canvasState.edgeView === 'visible')
  }

  getSelectedLineage() {
    const {selectedRegion, denormalizedSpace: {metrics}} = this.props
    const selectedMetrics = metrics.filter(m => isWithinRegion(m.location, selectedRegion))

    let ancestors = [...selectedMetrics], descendants = [...selectedMetrics]
    const getAncestors = metrics => _.uniq(_.flatten(metrics.map(m => m.edges.inputs))).filter(id => !_.some(ancestors, a => a.id === id)).map(this.findMetric.bind(this))
    const getDescendants = metrics => _.uniq(_.flatten(metrics.map(m => m.edges.outputs))).filter(id => !_.some(descendants, d => d.id === id)).map(this.findMetric.bind(this))

    let nextAncestors = getAncestors(ancestors)
    let nextDescendants = getDescendants(descendants)

    while (nextAncestors.length > 0 || nextDescendants.length > 0) {
      ancestors = [...ancestors, ...nextAncestors]
      descendants = [...descendants, ...nextDescendants]

      nextAncestors = getAncestors(nextAncestors)
      nextDescendants = getDescendants(nextDescendants)
    }

    return {ancestors, descendants}
  }

  findMetric(metricId) {
    return this.props.denormalizedSpace.metrics.find(m => m.id === metricId)
  }

  edges() {
    if (!this.showEdges()) { return [] }

    const {selectedRegion, denormalizedSpace: {metrics, edges}} = this.props
    const selectedMetrics = metrics.filter(m => isWithinRegion(m.location, selectedRegion))

    const hasSelectedMetrics = _.some(metrics, m => isWithinRegion(m.location, selectedRegion))
    const unconnectedStatus = hasSelectedMetrics ? 'unconnected' : 'default'

    const {ancestors, descendants} = this.getSelectedLineage()

    return edges.map(e => {
      const [inputMetric, outputMetric] = [this.findMetric(e.input), this.findMetric(e.output)]
      let errors = _.get(inputMetric, 'simulation.sample.errors')
      const outputIsAncestor = _.some(ancestors, a => a.id === outputMetric.id)
      const inputIsDescendant = _.some(descendants, d => d.id === inputMetric.id)
      const withinSelectedRegion = _.some(selectedMetrics, m => m.id === outputMetric.id) && _.some(selectedMetrics, m => m.id === inputMetric.id)

      const hasErrors = !_.isEmpty(errors)
      let pathStatus
      if (withinSelectedRegion) {
        pathStatus = unconnectedStatus
      } else {
        pathStatus = outputIsAncestor ? 'ancestor' : inputIsDescendant ? 'descendant' : unconnectedStatus
      }

      return {input: inputMetric.location, output: outputMetric.location, hasErrors, pathStatus }
    })
  }

  onAutoFillRegion(region) {
    segment.trackAutoFill()
    this.props.dispatch(fillRegion(this.props.denormalizedSpace.id, region))
  }

  analyzedMetric() {
    const {metrics, canvasState} = this.props.denormalizedSpace
    const analysisMetricId = canvasState.analysisMetricId
    if (!_.isEmpty(analysisMetricId)){
      return metrics.find(e => e.id === analysisMetricId)
    }
    return false
  }

  render () {
    const {selectedCell, selectedRegion, copied} = this.props
    const {metrics, canvasState} = this.props.denormalizedSpace
    const {metricCardView} = canvasState
    const analyzedMetric = this.analyzedMetric()

    const edges = this.edges()
    let className = 'canvas-space'
    className += this.showEdges() ? ' showEdges' : ''
    className += this.props.screenshot ? ' overflow-hidden' : ''

    const showGridLines = (metricCardView !== 'display')

    const copiedRegion = (copied && (copied.pastedTimes < 1) && copied.region) || []
    const analyzedCellLocation = analyzedMetric.location
    return (

        <FlowGrid
          items={_.map(metrics, m => ({key: m.id, location: m.location, component: this.renderMetric(m, analyzedMetric)}))}
          onMultipleSelect={this._handleMultipleSelect.bind(this)}
          hasItemUpdated = {(oldItem, newItem) => hasMetricUpdated(oldItem.props, newItem.props)}
          isItemEmpty = {this.isMetricEmpty.bind(this)}
          edges={edges}
          selectedRegion={selectedRegion}
          copiedRegion={copiedRegion}
          selectedCell={selectedCell}
          analyzedRegion={analyzedCellLocation && [analyzedCellLocation, analyzedCellLocation] || []}
          onUndo={this._handleUndo.bind(this)}
          onRedo={this._handleRedo.bind(this)}
          onSelectItem={this._handleSelect.bind(this)}
          onDeSelectAll={this._handleDeSelectAll.bind(this)}
          onAutoFillRegion={this.onAutoFillRegion.bind(this)}
          onAddItem={this._handleAddMetric.bind(this)}
          onMoveItem={this._handleMoveMetric.bind(this)}
          onRemoveItems={(ids) => {this.props.dispatch(removeMetrics(ids))}}
          onCopy={this.props.onCopy}
          onPaste={this.props.onPaste}
          onCut={this.props.onCut}
          showGridLines={showGridLines}
          canvasState={canvasState}
        />

    );
  }
}
<commit_msg>Minor refactoring to make syntax more clear<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import FlowGrid from 'gComponents/lib/FlowGrid/FlowGrid'
import Metric from 'gComponents/metrics/card/index'

import {denormalizedSpaceSelector} from '../denormalized-space-selector'

import {addMetric, changeMetric, removeMetrics} from 'gModules/metrics/actions'
import {changeSelect, deSelect} from 'gModules/selected_cell/actions'
import {selectRegion, deSelectRegion} from 'gModules/selected_region/actions'
import {runSimulations, deleteSimulations} from 'gModules/simulations/actions'
import * as canvasStateActions from 'gModules/canvas_state/actions'
import {undo, redo} from 'gModules/checkpoints/actions'
import {fillRegion} from 'gModules/auto_fill_region/actions'

import {hasMetricUpdated} from 'gComponents/metrics/card/updated'
import * as canvasStateProps from 'gModules/canvas_state/prop_type'

import * as segment from 'servers/segment'

import './style.css'

import {isLocation, isAtLocation, existsAtLoc, isWithinRegion} from 'lib/locationUtils.js'

function mapStateToProps(state) {
  return {
    copied: state.copied,
    selectedCell: state.selectedCell,
    selectedRegion: state.selectedRegion,
  }
}

const PT = PropTypes;
@connect(mapStateToProps)
export default class Canvas extends Component{
  static propTypes = {
    denormalizedSpace: PropTypes.object,
    dispatch: PropTypes.func,
    selectedCell: PropTypes.object,
    embed: PropTypes.bool,
  }

  static defaultProps = {
    screenshot: false
  }

  componentDidMount(){
    window.recorder.recordMountEvent(this)

    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    if (!_.isEmpty(metrics) && metrics.length > 19){
      this.props.dispatch(canvasStateActions.change({edgeView: 'hidden'}))
    } else {
      this.props.dispatch(canvasStateActions.change({edgeView: 'visible'}))
    }
    this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))

    if (this.props.screenshot) {
      this.props.dispatch(canvasStateActions.change({metricCardView: 'display'}))
    }
  }

  componentWillUpdate() { window.recorder.recordRenderStartEvent(this) }

  componentDidUpdate(prevProps) {
    window.recorder.recordRenderStopEvent(this)

    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    const oldMetrics = _.get(prevProps.denormalizedSpace, 'metrics')
    if ((oldMetrics.length === 0) && (metrics.length > 0)){
      this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))
    }
  }

  componentWillUnmount(){
    window.recorder.recordUnmountEvent(this)
    this.props.dispatch(deleteSimulations(this.props.denormalizedSpace.metrics.map(m => m.id)))
    this.props.dispatch(canvasStateActions.endAnalysis())
  }

  _handleUndo() {
    segment.trackUndo(true)
    this.props.dispatch(undo(this.props.denormalizedSpace.id))
  }

  _handleRedo() {
    segment.trackUndo(true)
    this.props.dispatch(redo(this.props.denormalizedSpace.id))
  }

  _handleSelect(location, selectedFrom = null) {
    this.props.dispatch(changeSelect(location, selectedFrom))
    this.props.dispatch(selectRegion(location, location))
  }

  _handleMultipleSelect(corner1, corner2) {
    if (!isAtLocation(corner1, corner2)) { segment.trackSelectedRegion() }
    this.props.dispatch(selectRegion(corner1, corner2))
  }

  _handleDeSelectAll() {
    this.props.dispatch(deSelect())
    this.props.dispatch(deSelectRegion())
  }

  _handleAddMetric(location) {
    this.props.dispatch(addMetric({space: this.props.denormalizedSpace.id, location: location}))
  }

  _handleMoveMetric({prev, next}) {
    if (_.some(this.props.denormalizedSpace.metrics, existsAtLoc(next))) { return }

    const metric = this.props.denormalizedSpace.metrics.find(existsAtLoc(prev))
    this.props.dispatch(changeMetric({id: metric.id, location: next}))
    this.props.dispatch(changeSelect(next))
  }

  _selectedMetric() {
   const {selectedCell} = this.props
   const metrics = _.get(this.props.denormalizedSpace, 'metrics')

   return metrics && isLocation(selectedCell) && metrics.find(existsAtLoc(selectedCell))
  }

  _isAnalysisView(props = this.props) {
    return (_.get(props, 'denormalizedSpace.canvasState.metricCardView') === 'analysis')
  }

  isMetricEmpty(id) {
    const metric = this.props.denormalizedSpace.metrics.find(m => m.id === id)
    const {input, data} = metric.guesstimate
    return _.isEmpty(metric.name) && _.isEmpty(input) && _.isEmpty(data)
  }

  renderMetric(metric, analyzed) {
    const {location} = metric
    const hasAnalyzed = analyzed && metric
    const analyzedSamples = _.get(analyzed, 'simulation.sample.values')
    const passAnalyzed = hasAnalyzed && analyzedSamples && !_.isEmpty(analyzedSamples)

    const is_private = _.get(this, 'props.denormalizedSpace.is_private')
    const organizationId = _.get(this, 'props.denormalizedSpace.organization_id')
    const canUseOrganizationFacts = !!is_private && !!this.props.organizationHasFacts && !!organizationId
    return (
      <Metric
        canvasState={this.props.denormalizedSpace.canvasState}
        key={metric.id}
        location={location}
        metric={metric}
        organizationId={organizationId}
        canUseOrganizationFacts={canUseOrganizationFacts}
        analyzedMetric={passAnalyzed && analyzed}
      />
    )
  }

  showEdges() {
    return (this.props.denormalizedSpace.canvasState.edgeView === 'visible')
  }

  getSelectedLineage() {
    const {selectedRegion, denormalizedSpace: {metrics}} = this.props
    const selectedMetrics = metrics.filter(m => isWithinRegion(m.location, selectedRegion))

    let ancestors = [...selectedMetrics], descendants = [...selectedMetrics]
    const getAncestors = metrics => _.uniq(_.flatten(metrics.map(m => m.edges.inputs))).filter(id => !_.some(ancestors, a => a.id === id)).map(this.findMetric.bind(this))
    const getDescendants = metrics => _.uniq(_.flatten(metrics.map(m => m.edges.outputs))).filter(id => !_.some(descendants, d => d.id === id)).map(this.findMetric.bind(this))

    let nextAncestors = getAncestors(ancestors)
    let nextDescendants = getDescendants(descendants)

    while (nextAncestors.length > 0 || nextDescendants.length > 0) {
      ancestors = [...ancestors, ...nextAncestors]
      descendants = [...descendants, ...nextDescendants]

      nextAncestors = getAncestors(nextAncestors)
      nextDescendants = getDescendants(nextDescendants)
    }

    return {ancestors, descendants}
  }

  findMetric(metricId) {
    return this.props.denormalizedSpace.metrics.find(m => m.id === metricId)
  }

  edges() {
    if (!this.showEdges()) { return [] }

    const {selectedRegion, denormalizedSpace: {metrics, edges}} = this.props
    const selectedMetrics = metrics.filter(m => isWithinRegion(m.location, selectedRegion))

    const hasSelectedMetrics = _.some(metrics, m => isWithinRegion(m.location, selectedRegion))
    const unconnectedStatus = hasSelectedMetrics ? 'unconnected' : 'default'

    const {ancestors, descendants} = this.getSelectedLineage()

    return edges.map(e => {
      const [inputMetric, outputMetric] = [this.findMetric(e.input), this.findMetric(e.output)]
      let errors = _.get(inputMetric, 'simulation.sample.errors')
      const outputIsAncestor = _.some(ancestors, a => a.id === outputMetric.id)
      const inputIsDescendant = _.some(descendants, d => d.id === inputMetric.id)
      const withinSelectedRegion = _.some(selectedMetrics, m => m.id === outputMetric.id) && _.some(selectedMetrics, m => m.id === inputMetric.id)

      const hasErrors = !_.isEmpty(errors)
      let pathStatus
      if (withinSelectedRegion) {
        pathStatus = unconnectedStatus
      } else {
        pathStatus = outputIsAncestor ? 'ancestor' : inputIsDescendant ? 'descendant' : unconnectedStatus
      }

      return {input: inputMetric.location, output: outputMetric.location, hasErrors, pathStatus }
    })
  }

  onAutoFillRegion(region) {
    segment.trackAutoFill()
    this.props.dispatch(fillRegion(this.props.denormalizedSpace.id, region))
  }

  analyzedMetric() {
    const {metrics, canvasState} = this.props.denormalizedSpace
    const analysisMetricId = canvasState.analysisMetricId
    if (!_.isEmpty(analysisMetricId)){
      return metrics.find(e => e.id === analysisMetricId)
    }
    return false
  }

  render () {
    const {selectedCell, selectedRegion, copied} = this.props
    const {metrics, canvasState} = this.props.denormalizedSpace
    const {metricCardView} = canvasState
    const analyzedMetric = this.analyzedMetric()

    const edges = this.edges()
    let className = 'canvas-space'
    className += this.showEdges() ? ' showEdges' : ''
    className += this.props.screenshot ? ' overflow-hidden' : ''

    const showGridLines = (metricCardView !== 'display')

    const copiedRegion = (copied && (copied.pastedTimes < 1) && copied.region) || []
    const analyzedRegion = analyzedMetric ? [analyzedMetric.location, analyzedMetric.location] : []
    return (

        <FlowGrid
          items={_.map(metrics, m => ({key: m.id, location: m.location, component: this.renderMetric(m, analyzedMetric)}))}
          onMultipleSelect={this._handleMultipleSelect.bind(this)}
          hasItemUpdated = {(oldItem, newItem) => hasMetricUpdated(oldItem.props, newItem.props)}
          isItemEmpty = {this.isMetricEmpty.bind(this)}
          edges={edges}
          selectedRegion={selectedRegion}
          copiedRegion={copiedRegion}
          selectedCell={selectedCell}
          analyzedRegion={analyzedRegion}
          onUndo={this._handleUndo.bind(this)}
          onRedo={this._handleRedo.bind(this)}
          onSelectItem={this._handleSelect.bind(this)}
          onDeSelectAll={this._handleDeSelectAll.bind(this)}
          onAutoFillRegion={this.onAutoFillRegion.bind(this)}
          onAddItem={this._handleAddMetric.bind(this)}
          onMoveItem={this._handleMoveMetric.bind(this)}
          onRemoveItems={(ids) => {this.props.dispatch(removeMetrics(ids))}}
          onCopy={this.props.onCopy}
          onPaste={this.props.onPaste}
          onCut={this.props.onCut}
          showGridLines={showGridLines}
          canvasState={canvasState}
        />

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import FlowGrid from 'gComponents/lib/FlowGrid/FlowGrid'
import Metric from 'gComponents/metrics/card/index'

import {denormalizedSpaceSelector} from '../denormalized-space-selector'

import {addMetric, changeMetric, removeMetrics} from 'gModules/metrics/actions'
import * as copiedActions from 'gModules/copied/actions'
import {changeSelect, deSelect} from 'gModules/selected_cell/actions'
import {selectRegion, deSelectRegion} from 'gModules/selected_region/actions'
import {runSimulations, deleteSimulations} from 'gModules/simulations/actions'
import * as canvasStateActions from 'gModules/canvas_state/actions'
import {undo, redo} from 'gModules/checkpoints/actions'

import {hasMetricUpdated} from 'gComponents/metrics/card/updated'
import * as canvasStateProps from 'gModules/canvas_state/prop_type'

import './style.css'

import {isLocation, isAtLocation} from 'lib/locationUtils.js'

function mapStateToProps(state) {
  return {
    copied: state.copied,
    canvasState: state.canvasState,
    selectedCell: state.selectedCell,
    selectedRegion: state.selectedRegion,
  }
}

const PT = PropTypes;
@connect(mapStateToProps)
@connect(denormalizedSpaceSelector)
export default class Canvas extends Component{
  static propTypes = {
    canvasState: PT.shape({
      edgeView: canvasStateProps.edgeView,
      metricCardView: canvasStateProps.metricCardView,
      metricClickMode: canvasStateProps.metricClickMode
    }),
    denormalizedSpace: PropTypes.object,
    dispatch: PropTypes.func,
    selectedCell: PropTypes.object,
    embed: PropTypes.bool,
    spaceId: PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ])
  }

  static defaultProps = {
    screenshot: false
  }

  componentDidMount(){
    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    if (!_.isEmpty(metrics) && metrics.length > 19){
      this.props.dispatch(canvasStateActions.change({edgeView: 'hidden'}))
    } else {
      this.props.dispatch(canvasStateActions.change({edgeView: 'visible'}))
    }
    this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))

    if (this.props.screenshot) {
      this.props.dispatch(canvasStateActions.change({metricCardView: 'display'}))
    }
  }

  componentDidUpdate(prevProps) {
    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    const oldMetrics = _.get(prevProps.denormalizedSpace, 'metrics')
    if ((oldMetrics.length === 0) && (metrics.length > 0)){
      this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))
    }
  }

  componentWillUnmount(){
    this.props.dispatch(deleteSimulations(this.props.denormalizedSpace.metrics.map(m => m.id)))
  }

  _handleUndo() {
    this.props.dispatch(undo(this.props.denormalizedSpace.id))
  }

  _handleRedo() {
    this.props.dispatch(redo(this.props.denormalizedSpace.id))
  }

  _handleSelect(location) {
    this.props.dispatch(changeSelect(location))
    this.props.dispatch(selectRegion(location, location))
  }

  _handleMultipleSelect(corner1, corner2) {
    this.props.dispatch(selectRegion(corner1, corner2))
  }

  _handleDeSelectAll() {
    this.props.dispatch(deSelect())
    this.props.dispatch(deSelectRegion())
  }

  _handleAddMetric(location) {
    this.props.dispatch(addMetric({space: this.props.spaceId, location: location, isNew: true}))
  }

  _handleMoveMetric({prev, next}) {
    const destinationMetric = this.props.denormalizedSpace.metrics.find(f => f.location.row === next.row && f.location.column === next.column)
    if (!!destinationMetric) {
      return
    }
    const metric = this.props.denormalizedSpace.metrics.find(f => f.location.row === prev.row && f.location.column === prev.column)
    this.props.dispatch(changeMetric({id: metric.id, location: next}))
    this.props.dispatch(changeSelect(next))
  }

  _selectedMetric() {
   const {selectedCell} = this.props
   const metrics = _.get(this.props.denormalizedSpace, 'metrics')

   return metrics && isLocation(selectedCell) && metrics.find(m => isAtLocation(m.location, selectedCell));
  }

  _isAnalysisView(props = this.props) {
    return (_.get(props, 'canvasState.metricCardView') === 'analysis')
  }

  renderMetric(metric, selected) {
    const {location} = metric
    const hasSelected = selected && metric && (selected.id !== metric.id)
    const selectedSamples = _.get(selected, 'simulation.sample.values')
    const passSelected = hasSelected && selectedSamples && !_.isEmpty(selectedSamples)
    return (
      <Metric
          canvasState={this.props.canvasState}
          key={metric.id}
          location={location}
          metric={metric}
          selectedMetric={passSelected && selected}
      />
    )
  }

  showEdges() {
    return (this.props.canvasState.edgeView === 'visible')
  }

  edges() {
    let edges = []

    if (this.showEdges()){
      const space = this.props.denormalizedSpace
      const {metrics} = space
      const findMetric = (metricId) => metrics.find(m => m.id === metricId)
      const metricIdToLocation = (metricId) => findMetric(metricId).location

      edges = space.edges.map(e => {
        const [inputMetric, outputMetric] = [findMetric(e.input), findMetric(e.output)]
        let errors = _.get(inputMetric, 'simulation.sample.errors')
        const color = (errors && !!errors.length) ? 'RED' : 'BLUE'
        return {input: inputMetric.location, output: outputMetric.location, color}
      })
    }
    return edges
  }

  render () {
    const {selectedCell, selectedRegion, copied} = this.props
    const {metrics} = this.props.denormalizedSpace
    const {metricCardView} = this.props.canvasState

    const edges = this.edges()
    let className = 'canvas-space'
    const showGridLines = (metricCardView !== 'display')
    this.showEdges() ? className += ' showEdges' : ''
    const selectedMetric = this._isAnalysisView() && this._selectedMetric()
    const overflow = this.props.screenshot ? 'hidden' : 'default'

    const copiedRegion = (copied && (copied.pastedTimes < 1) && copied.region) || []

    return (

        <FlowGrid
          items={_.map(metrics, m => ({key: m.id, location: m.location, component: this.renderMetric(m, selectedMetric)}))}
          onMultipleSelect={this._handleMultipleSelect.bind(this)}
          overflow={overflow}
          hasItemUpdated = {(oldItem, newItem) => hasMetricUpdated(oldItem.props, newItem.props)}
          edges={edges}
          selectedRegion={selectedRegion}
          copiedRegion={copiedRegion}
          selectedCell={selectedCell}
          onUndo={this._handleUndo.bind(this)}
          onRedo={this._handleRedo.bind(this)}
          onSelectItem={this._handleSelect.bind(this)}
          onDeSelectAll={this._handleDeSelectAll.bind(this)}
          onAddItem={this._handleAddMetric.bind(this)}
          onMoveItem={this._handleMoveMetric.bind(this)}
          onRemoveItems={(ids) => {this.props.dispatch(removeMetrics(ids))}}
          onCopy={this.props.onCopy}
          onPaste={this.props.onPaste}
          onCut={this.props.onCut}
          showGridLines={showGridLines}
          canvasState={this.props.canvasState}
        />

    );
  }
}
<commit_msg>Removing an unused import.<commit_after>'use strict';

import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import FlowGrid from 'gComponents/lib/FlowGrid/FlowGrid'
import Metric from 'gComponents/metrics/card/index'

import {denormalizedSpaceSelector} from '../denormalized-space-selector'

import {addMetric, changeMetric, removeMetrics} from 'gModules/metrics/actions'
import {changeSelect, deSelect} from 'gModules/selected_cell/actions'
import {selectRegion, deSelectRegion} from 'gModules/selected_region/actions'
import {runSimulations, deleteSimulations} from 'gModules/simulations/actions'
import * as canvasStateActions from 'gModules/canvas_state/actions'
import {undo, redo} from 'gModules/checkpoints/actions'

import {hasMetricUpdated} from 'gComponents/metrics/card/updated'
import * as canvasStateProps from 'gModules/canvas_state/prop_type'

import './style.css'

import {isLocation, isAtLocation} from 'lib/locationUtils.js'

function mapStateToProps(state) {
  return {
    copied: state.copied,
    canvasState: state.canvasState,
    selectedCell: state.selectedCell,
    selectedRegion: state.selectedRegion,
  }
}

const PT = PropTypes;
@connect(mapStateToProps)
@connect(denormalizedSpaceSelector)
export default class Canvas extends Component{
  static propTypes = {
    canvasState: PT.shape({
      edgeView: canvasStateProps.edgeView,
      metricCardView: canvasStateProps.metricCardView,
      metricClickMode: canvasStateProps.metricClickMode
    }),
    denormalizedSpace: PropTypes.object,
    dispatch: PropTypes.func,
    selectedCell: PropTypes.object,
    embed: PropTypes.bool,
    spaceId: PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ])
  }

  static defaultProps = {
    screenshot: false
  }

  componentDidMount(){
    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    if (!_.isEmpty(metrics) && metrics.length > 19){
      this.props.dispatch(canvasStateActions.change({edgeView: 'hidden'}))
    } else {
      this.props.dispatch(canvasStateActions.change({edgeView: 'visible'}))
    }
    this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))

    if (this.props.screenshot) {
      this.props.dispatch(canvasStateActions.change({metricCardView: 'display'}))
    }
  }

  componentDidUpdate(prevProps) {
    const metrics = _.get(this.props.denormalizedSpace, 'metrics')
    const oldMetrics = _.get(prevProps.denormalizedSpace, 'metrics')
    if ((oldMetrics.length === 0) && (metrics.length > 0)){
      this.props.dispatch(runSimulations({spaceId: this.props.denormalizedSpace.id}))
    }
  }

  componentWillUnmount(){
    this.props.dispatch(deleteSimulations(this.props.denormalizedSpace.metrics.map(m => m.id)))
  }

  _handleUndo() {
    this.props.dispatch(undo(this.props.denormalizedSpace.id))
  }

  _handleRedo() {
    this.props.dispatch(redo(this.props.denormalizedSpace.id))
  }

  _handleSelect(location) {
    this.props.dispatch(changeSelect(location))
    this.props.dispatch(selectRegion(location, location))
  }

  _handleMultipleSelect(corner1, corner2) {
    this.props.dispatch(selectRegion(corner1, corner2))
  }

  _handleDeSelectAll() {
    this.props.dispatch(deSelect())
    this.props.dispatch(deSelectRegion())
  }

  _handleAddMetric(location) {
    this.props.dispatch(addMetric({space: this.props.spaceId, location: location, isNew: true}))
  }

  _handleMoveMetric({prev, next}) {
    const destinationMetric = this.props.denormalizedSpace.metrics.find(f => f.location.row === next.row && f.location.column === next.column)
    if (!!destinationMetric) {
      return
    }
    const metric = this.props.denormalizedSpace.metrics.find(f => f.location.row === prev.row && f.location.column === prev.column)
    this.props.dispatch(changeMetric({id: metric.id, location: next}))
    this.props.dispatch(changeSelect(next))
  }

  _selectedMetric() {
   const {selectedCell} = this.props
   const metrics = _.get(this.props.denormalizedSpace, 'metrics')

   return metrics && isLocation(selectedCell) && metrics.find(m => isAtLocation(m.location, selectedCell));
  }

  _isAnalysisView(props = this.props) {
    return (_.get(props, 'canvasState.metricCardView') === 'analysis')
  }

  renderMetric(metric, selected) {
    const {location} = metric
    const hasSelected = selected && metric && (selected.id !== metric.id)
    const selectedSamples = _.get(selected, 'simulation.sample.values')
    const passSelected = hasSelected && selectedSamples && !_.isEmpty(selectedSamples)
    return (
      <Metric
          canvasState={this.props.canvasState}
          key={metric.id}
          location={location}
          metric={metric}
          selectedMetric={passSelected && selected}
      />
    )
  }

  showEdges() {
    return (this.props.canvasState.edgeView === 'visible')
  }

  edges() {
    let edges = []

    if (this.showEdges()){
      const space = this.props.denormalizedSpace
      const {metrics} = space
      const findMetric = (metricId) => metrics.find(m => m.id === metricId)
      const metricIdToLocation = (metricId) => findMetric(metricId).location

      edges = space.edges.map(e => {
        const [inputMetric, outputMetric] = [findMetric(e.input), findMetric(e.output)]
        let errors = _.get(inputMetric, 'simulation.sample.errors')
        const color = (errors && !!errors.length) ? 'RED' : 'BLUE'
        return {input: inputMetric.location, output: outputMetric.location, color}
      })
    }
    return edges
  }

  render () {
    const {selectedCell, selectedRegion, copied} = this.props
    const {metrics} = this.props.denormalizedSpace
    const {metricCardView} = this.props.canvasState

    const edges = this.edges()
    let className = 'canvas-space'
    const showGridLines = (metricCardView !== 'display')
    this.showEdges() ? className += ' showEdges' : ''
    const selectedMetric = this._isAnalysisView() && this._selectedMetric()
    const overflow = this.props.screenshot ? 'hidden' : 'default'

    const copiedRegion = (copied && (copied.pastedTimes < 1) && copied.region) || []

    return (

        <FlowGrid
          items={_.map(metrics, m => ({key: m.id, location: m.location, component: this.renderMetric(m, selectedMetric)}))}
          onMultipleSelect={this._handleMultipleSelect.bind(this)}
          overflow={overflow}
          hasItemUpdated = {(oldItem, newItem) => hasMetricUpdated(oldItem.props, newItem.props)}
          edges={edges}
          selectedRegion={selectedRegion}
          copiedRegion={copiedRegion}
          selectedCell={selectedCell}
          onUndo={this._handleUndo.bind(this)}
          onRedo={this._handleRedo.bind(this)}
          onSelectItem={this._handleSelect.bind(this)}
          onDeSelectAll={this._handleDeSelectAll.bind(this)}
          onAddItem={this._handleAddMetric.bind(this)}
          onMoveItem={this._handleMoveMetric.bind(this)}
          onRemoveItems={(ids) => {this.props.dispatch(removeMetrics(ids))}}
          onCopy={this.props.onCopy}
          onPaste={this.props.onPaste}
          onCut={this.props.onCut}
          showGridLines={showGridLines}
          canvasState={this.props.canvasState}
        />

    );
  }
}
<|endoftext|>


<commit_before>/* global it, describe */

import assert from 'assert'
import React from 'react'
import {Textfield, Textarea} from '../'
import {mount} from 'enzyme'

describe('Textfield', () => {
  it('should be empty by default', () => {
    const wrapper = mount(<Textfield />)
    assert.equal(wrapper.find('.Textfield-input').node.value, '')
  })

  it('should be able to set a custom value', () => {
    const wrapper = mount(<Textfield value='my custom value' onChange={() => {}} />)
    assert.equal(wrapper.find('.Textfield-input').node.value, 'my custom value')
  })

  it('should be able to set a custom label', () => {
    const wrapper = mount(<Textfield label='my custom label' />)
    assert.equal(wrapper.find('label').text(), 'my custom label')
  })

  it('should be able to set a custom icon', () => {
    const wrapper = mount(<Textfield icon={ICON} />)
    assert.equal(wrapper.find('.Textfield-icon').text(), 'ICON')
  })

  it('should not show label floated up when value is empty', () => {
    const wrapper = mount(<Textfield label='foo' />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 0)
  })

  it('should show label floated up when value is not empty', () => {
    const noop = () => {}
    const wrapper = mount(<Textfield label='foo' defaultValue='bar' onChange={noop} />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 1)
  })

  it('should show label floated up when defaultValue is not empty', () => {
    const noop = () => {}
    const wrapper = mount(<Textfield label='foo' value='bar' onChange={noop} />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 1)
  })

  it('should show label floated up when value is empty and float=false', () => {
    const wrapper = mount(<Textfield label='foo' float={false} />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 1)
  })

  it('should be able to set to disabled', () => {
    const wrapper = mount(<Textfield disabled />)
    assert(wrapper.find('.Textfield-input').node.disabled)
  })

  it('should be able to set to readOnly', () => {
    const wrapper = mount(<Textfield readOnly />)
    assert(wrapper.find('.Textfield-input').node.readOnly)
  })

  it('should callback upon typing', (done) => {
    const callback = (event) => {
      assert.equal(event.target.value, 'hello world')
      done()
    }
    const wrapper = mount(<Textfield onChange={callback} />)
    wrapper.find('.Textfield-input').simulate('change', {
      target: {
        value: 'hello world'
      }
    })
  })

  it('should show an error message', () => {
    const wrapper = mount(<Textfield error='username or password incorrect' />)
    assert.equal(wrapper.find('.Textfield-error').text(), 'username or password incorrect')
  })

  it('should apply error styles', () => {
    const wrapper = mount(<Textfield error='username or password incorrect' />)
    assert(wrapper.find('.Textfield-input').hasClass('Textfield-input--error'))
  })

  it('should have the right type', () => {
    const wrapper = mount(<Textfield type='password' />)
    assert.equal(wrapper.find('.Textfield-input').node.type, 'password')
  })
})

describe('Textarea', () => {
  it('should be empty by default', () => {
    const wrapper = mount(<Textarea />)
    assert.equal(wrapper.find('.Textfield-input').node.value, '')
  })

  it('should render value as text content of textarea', () => {
    const wrapper = mount(<Textarea value='foo bar' onChange={() => {}} />)
    assert.equal(wrapper.find('textarea').node.textContent, 'foo bar')
  })

  it('should have style resize default to "none"', () => {
    const wrapper = mount(<Textarea />)
    assert.equal(wrapper.find('textarea').node.style.resize, 'none')
  })

  it('should accept resizable attribute and set style resize to "vertical"', () => {
    const wrapper = mount(<Textarea resizable />)
    assert.equal(wrapper.find('textarea').node.style.resize, 'vertical')
  })

  it('should default rows = 2', () => {
    const wrapper = mount(<Textarea value={'foo'} onChange={() => {}} />)
    assert.equal(wrapper.find('textarea').node.rows, 2)
  })

  it('should allow seting rows', () => {
    const wrapper = mount(<Textarea value={'foo'} rows={1} onChange={() => {}} />)
    assert.equal(wrapper.find('textarea').node.rows, 1)
  })

  it('should resize', () => {
    let target = {
      style: {
        height: '30px'
      },
      scrollHeight: 60
    }
    const getComputedStyle = () => {
      return {
        'line-height': '22px'
      }
    }
    const wrapper = mount(<Textarea value={'foo\nbar'} onChange={() => {}} getComputedStyle={getComputedStyle} />)
    wrapper.find('textarea').simulate('input', {target})
    assert.equal(target.style.height, '61px') // 1px border
  })

  it('should resize with height < maxRows', () => {
    let target = {
      style: {
        height: '30px'
      },
      scrollHeight: 60
    }
    const getComputedStyle = () => {
      return {
        'line-height': '22px'
      }
    }
    const wrapper = mount(<Textarea value={'foo\nbar'} onChange={() => {}} maxRows={3} getComputedStyle={getComputedStyle} />)
    wrapper.find('textarea').simulate('input', {target})
    assert.equal(target.style.height, '61px') // 1px border
  })

  it('should not resize with height > maxRows', () => {
    let target = {
      style: {
        height: '30px'
      },
      scrollHeight: 90
    }
    const getComputedStyle = () => {
      return {
        'line-height': '22px'
      }
    }
    const wrapper = mount(<Textarea value={'foo\nbar'} onChange={() => {}} maxRows={3} getComputedStyle={getComputedStyle} />)
    wrapper.find('textarea').simulate('input', {target})
    assert.equal(target.style.height, '30px')
  })
})

<commit_msg>Fixed typo<commit_after>/* global it, describe */

import assert from 'assert'
import React from 'react'
import {Textfield, Textarea} from '../'
import {mount} from 'enzyme'

describe('Textfield', () => {
  it('should be empty by default', () => {
    const wrapper = mount(<Textfield />)
    assert.equal(wrapper.find('.Textfield-input').node.value, '')
  })

  it('should be able to set a custom value', () => {
    const wrapper = mount(<Textfield value='my custom value' onChange={() => {}} />)
    assert.equal(wrapper.find('.Textfield-input').node.value, 'my custom value')
  })

  it('should be able to set a custom label', () => {
    const wrapper = mount(<Textfield label='my custom label' />)
    assert.equal(wrapper.find('label').text(), 'my custom label')
  })

  it('should be able to set a custom icon', () => {
    const wrapper = mount(<Textfield icon={ICON} />)
    assert.equal(wrapper.find('.Textfield-icon').text(), 'ICON')
  })

  it('should not show label floated up when value is empty', () => {
    const wrapper = mount(<Textfield label='foo' />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 0)
  })

  it('should show label floated up when value is not empty', () => {
    const noop = () => {}
    const wrapper = mount(<Textfield label='foo' defaultValue='bar' onChange={noop} />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 1)
  })

  it('should show label floated up when defaultValue is not empty', () => {
    const noop = () => {}
    const wrapper = mount(<Textfield label='foo' value='bar' onChange={noop} />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 1)
  })

  it('should show label floated up when value is empty and float=false', () => {
    const wrapper = mount(<Textfield label='foo' float={false} />)
    assert.equal(wrapper.find('.Textfield-label--floatup').length, 1)
  })

  it('should be able to set to disabled', () => {
    const wrapper = mount(<Textfield disabled />)
    assert(wrapper.find('.Textfield-input').node.disabled)
  })

  it('should be able to set to readOnly', () => {
    const wrapper = mount(<Textfield readOnly />)
    assert(wrapper.find('.Textfield-input').node.readOnly)
  })

  it('should callback upon typing', (done) => {
    const callback = (event) => {
      assert.equal(event.target.value, 'hello world')
      done()
    }
    const wrapper = mount(<Textfield onChange={callback} />)
    wrapper.find('.Textfield-input').simulate('change', {
      target: {
        value: 'hello world'
      }
    })
  })

  it('should show an error message', () => {
    const wrapper = mount(<Textfield error='username or password incorrect' />)
    assert.equal(wrapper.find('.Textfield-error').text(), 'username or password incorrect')
  })

  it('should apply error styles', () => {
    const wrapper = mount(<Textfield error='username or password incorrect' />)
    assert(wrapper.find('.Textfield-input').hasClass('Textfield-input--error'))
  })

  it('should have the right type', () => {
    const wrapper = mount(<Textfield type='password' />)
    assert.equal(wrapper.find('.Textfield-input').node.type, 'password')
  })
})

describe('Textarea', () => {
  it('should be empty by default', () => {
    const wrapper = mount(<Textarea />)
    assert.equal(wrapper.find('.Textfield-input').node.value, '')
  })

  it('should render value as text content of textarea', () => {
    const wrapper = mount(<Textarea value='foo bar' onChange={() => {}} />)
    assert.equal(wrapper.find('textarea').node.textContent, 'foo bar')
  })

  it('should have style resize default to "none"', () => {
    const wrapper = mount(<Textarea />)
    assert.equal(wrapper.find('textarea').node.style.resize, 'none')
  })

  it('should accept resizable attribute and set style resize to "vertical"', () => {
    const wrapper = mount(<Textarea resizable />)
    assert.equal(wrapper.find('textarea').node.style.resize, 'vertical')
  })

  it('should default rows = 2', () => {
    const wrapper = mount(<Textarea value={'foo'} onChange={() => {}} />)
    assert.equal(wrapper.find('textarea').node.rows, 2)
  })

  it('should allow setting rows', () => {
    const wrapper = mount(<Textarea value={'foo'} rows={1} onChange={() => {}} />)
    assert.equal(wrapper.find('textarea').node.rows, 1)
  })

  it('should resize', () => {
    let target = {
      style: {
        height: '30px'
      },
      scrollHeight: 60
    }
    const getComputedStyle = () => {
      return {
        'line-height': '22px'
      }
    }
    const wrapper = mount(<Textarea value={'foo\nbar'} onChange={() => {}} getComputedStyle={getComputedStyle} />)
    wrapper.find('textarea').simulate('input', {target})
    assert.equal(target.style.height, '61px') // 1px border
  })

  it('should resize with height < maxRows', () => {
    let target = {
      style: {
        height: '30px'
      },
      scrollHeight: 60
    }
    const getComputedStyle = () => {
      return {
        'line-height': '22px'
      }
    }
    const wrapper = mount(<Textarea value={'foo\nbar'} onChange={() => {}} maxRows={3} getComputedStyle={getComputedStyle} />)
    wrapper.find('textarea').simulate('input', {target})
    assert.equal(target.style.height, '61px') // 1px border
  })

  it('should not resize with height > maxRows', () => {
    let target = {
      style: {
        height: '30px'
      },
      scrollHeight: 90
    }
    const getComputedStyle = () => {
      return {
        'line-height': '22px'
      }
    }
    const wrapper = mount(<Textarea value={'foo\nbar'} onChange={() => {}} maxRows={3} getComputedStyle={getComputedStyle} />)
    wrapper.find('textarea').simulate('input', {target})
    assert.equal(target.style.height, '30px')
  })
})

<|endoftext|>


<commit_before>var spawn = require('child_process').spawn,
  exec = require('child_process').exec,
  uuid = require('node-uuid'),
  path = require('path'),
  fs = require('fs'),
  Promise = require('bluebird'),
  sys = require('sys');

var PC2BIM = module.exports = function(storagePath) {
  this.storagePath = storagePath;
  console.log('[PC2BIM] mounting ' + this.storagePath + ' as "/duraark-storage"');
};

PC2BIM.prototype.extract = function(config) {
  var that = this;
  return new Promise(function(resolve, reject) {
    console.log('[PC2BIM::convert] input file: ' + config.inputFile);

    // docker run --rm -v /duraark-storage:/duraark-storage ubo/pc2bim pc2bim
    //    --input /duraark-storage/files/Nygade_Scan1001.e57
    //    --output /duraark-storage/files/Nygade_Scan1001_RECONSTRUCTED.ifc
    var errorText = '';

    console.log('[PC2BIM::convert] about to run:\n ' + 'docker run --rm -v ' + that.storagePath + ':/duraark-storage ochi/duraark_pc2bim pc2bim --input ' + config.inputFile + ' --output ' + config.outputFile + ' --outputjson ' + config.outputWallJSON);

    var executable = spawn('docker', ['run', '--rm', '-v', that.storagePath + ':/duraark-storage', 'ochi/duraark_pc2bim', 'pc2bim', '--input', config.inputFile, '--output', config.outputFile + ' --outputjson ' + config.outputWallJSON]);

    executable.stdout.on('data', function(data) {
      console.log(data.toString());
    });

    executable.stderr.on('data', function(data) {
      console.log('ERROR: ' + data.toString());
      errorText += data.toString();
    });

    executable.on('close', function(code) {
      // console.log('[PC2BIM-binding] child process exited with code ' + code);

      if (code === 0) {
        console.log('[PC2BIM-binding] successfully finished');
        resolve({
          inputFile: config.inputFile,
          outputFile: config.outputFile,
          outputWallJSON: config.outputWallJSON,
          error: null
        });
      } else {
        console.log('[PC2BIM-binding] finished with error code: ' + code);
        reject(errorText);
      }
    });
  });
};
<commit_msg>fixed error in pc2bim caller array<commit_after>var spawn = require('child_process').spawn,
  exec = require('child_process').exec,
  uuid = require('node-uuid'),
  path = require('path'),
  fs = require('fs'),
  Promise = require('bluebird'),
  sys = require('sys');

var PC2BIM = module.exports = function(storagePath) {
  this.storagePath = storagePath;
  console.log('[PC2BIM] mounting ' + this.storagePath + ' as "/duraark-storage"');
};

PC2BIM.prototype.extract = function(config) {
  var that = this;
  return new Promise(function(resolve, reject) {
    console.log('[PC2BIM::convert] input file: ' + config.inputFile);

    // docker run --rm -v /duraark-storage:/duraark-storage ubo/pc2bim pc2bim
    //    --input /duraark-storage/files/Nygade_Scan1001.e57
    //    --output /duraark-storage/files/Nygade_Scan1001_RECONSTRUCTED.ifc
    var errorText = '';

    console.log('[PC2BIM::convert] about to run:\n ' + 'docker run --rm -v ' + that.storagePath + ':/duraark-storage ochi/duraark_pc2bim pc2bim --input ' + config.inputFile + ' --output ' + config.outputFile + ' --outputjson ' + config.outputWallJSON);

    var executable = spawn('docker', ['run', '--rm', '-v', that.storagePath + ':/duraark-storage', 'ochi/duraark_pc2bim', 'pc2bim', '--input', config.inputFile, '--output', config.outputFile, ' --outputjson ', config.outputWallJSON]);

    executable.stdout.on('data', function(data) {
      console.log(data.toString());
    });

    executable.stderr.on('data', function(data) {
      console.log('ERROR: ' + data.toString());
      errorText += data.toString();
    });

    executable.on('close', function(code) {
      // console.log('[PC2BIM-binding] child process exited with code ' + code);

      if (code === 0) {
        console.log('[PC2BIM-binding] successfully finished');
        resolve({
          inputFile: config.inputFile,
          outputFile: config.outputFile,
          outputWallJSON: config.outputWallJSON,
          error: null
        });
      } else if (code === 132) {
        var err = "'pc2bim' could not start. Are you sure that your CPU is from Intel? AMD is not supported at the moment."
        console.log('[PC2BIM::convert] ' + err);
        reject(err);
      } else {
        console.log('[PC2BIM::convert] ' + errorText);
        reject(errorText);
      }
    });
  });
};
<|endoftext|>


<commit_before>let webpack = require('webpack');

let webpackDefaultConfig = require('./webpack-default');
let webpackEntry = require('./webpack-entry');
let webpackRules = require('./webpack-rules');
let webpackPlugins = require('./webpack-plugins');

process.noDeprecation = true;

class WebpackConfig {
    /**
     * Create a new instance.
     */
    constructor() {
        this.webpackConfig = webpackDefaultConfig();
    }

    /**
     * Build the Webpack configuration object.
     */
    build() {
        this.buildEntry()
            .buildOutput()
            .buildRules()
            .buildPlugins()
            .buildResolving()
            .mergeCustomConfig();

        Mix.dispatch('configReady', this.webpackConfig);

        return this.webpackConfig;
    }

    /**
     * Build the entry object.
     */
    buildEntry() {
        let { entry, extractions } = webpackEntry();

        this.webpackConfig.entry = entry;

        // If we're extracting any vendor libraries, then we
        // need to add the CommonChunksPlugin to strip out
        // all relevant code into its own file.
        if (extractions.length) {
            this.webpackConfig.plugins.push(
                new webpack.optimize.CommonsChunkPlugin({
                    names: extractions,
                    minChunks: Infinity
                })
            );
        }

        return this;
    }

    /**
     * Build the output object.
     */
    buildOutput() {
         let http = process.argv.includes('--https') ? 'https' : 'http';

        this.webpackConfig.output = {
            path: path.resolve(Mix.isUsing('hmr') ? '/' : Config.publicPath),
            filename: '[name].js',
            chunkFilename: '[name].js',
            publicPath: Mix.isUsing('hmr') ? (http + '://localhost:8080/') : ''
        };

        return this;
    }

    /**
     * Build the rules array.
     */
    buildRules() {
        let { rules, extractPlugins } = webpackRules();

        this.webpackConfig.module.rules = this.webpackConfig.module.rules.concat(rules);
        this.webpackConfig.plugins = this.webpackConfig.plugins.concat(extractPlugins);

        return this;
    }

    /**
     * Build the plugins array.
     */
    buildPlugins() {
        this.webpackConfig.plugins = this.webpackConfig.plugins.concat(
            webpackPlugins()
        );

        return this;
    }

    /**
     * Build the resolve object.
     */
    buildResolving() {
        let extensions = ['*', '.js', '.jsx', '.vue'];

        if (Config.typeScript) {
            extensions.push('.ts', '.tsx');
        }

        this.webpackConfig.resolve = {
            extensions,

            alias: {
                'vue$': 'vue/dist/vue.common.js'
            }
        };

        return this;
    }

    /**
     * Merge the user's custom Webpack configuration.
     */
    mergeCustomConfig() {
        if (Config.webpackConfig) {
            this.webpackConfig = require('webpack-merge').smart(
                this.webpackConfig, Config.webpackConfig
            );
        }
    }
}

module.exports = WebpackConfig;
<commit_msg>Load alternative dist file for typescript<commit_after>let webpack = require('webpack');

let webpackDefaultConfig = require('./webpack-default');
let webpackEntry = require('./webpack-entry');
let webpackRules = require('./webpack-rules');
let webpackPlugins = require('./webpack-plugins');

process.noDeprecation = true;

class WebpackConfig {
    /**
     * Create a new instance.
     */
    constructor() {
        this.webpackConfig = webpackDefaultConfig();
    }

    /**
     * Build the Webpack configuration object.
     */
    build() {
        this.buildEntry()
            .buildOutput()
            .buildRules()
            .buildPlugins()
            .buildResolving()
            .mergeCustomConfig();

        Mix.dispatch('configReady', this.webpackConfig);

        return this.webpackConfig;
    }

    /**
     * Build the entry object.
     */
    buildEntry() {
        let { entry, extractions } = webpackEntry();

        this.webpackConfig.entry = entry;

        // If we're extracting any vendor libraries, then we
        // need to add the CommonChunksPlugin to strip out
        // all relevant code into its own file.
        if (extractions.length) {
            this.webpackConfig.plugins.push(
                new webpack.optimize.CommonsChunkPlugin({
                    names: extractions,
                    minChunks: Infinity
                })
            );
        }

        return this;
    }

    /**
     * Build the output object.
     */
    buildOutput() {
         let http = process.argv.includes('--https') ? 'https' : 'http';

        this.webpackConfig.output = {
            path: path.resolve(Mix.isUsing('hmr') ? '/' : Config.publicPath),
            filename: '[name].js',
            chunkFilename: '[name].js',
            publicPath: Mix.isUsing('hmr') ? (http + '://localhost:8080/') : ''
        };

        return this;
    }

    /**
     * Build the rules array.
     */
    buildRules() {
        let { rules, extractPlugins } = webpackRules();

        this.webpackConfig.module.rules = this.webpackConfig.module.rules.concat(rules);
        this.webpackConfig.plugins = this.webpackConfig.plugins.concat(extractPlugins);

        return this;
    }

    /**
     * Build the plugins array.
     */
    buildPlugins() {
        this.webpackConfig.plugins = this.webpackConfig.plugins.concat(
            webpackPlugins()
        );

        return this;
    }

    /**
     * Build the resolve object.
     */
    buildResolving() {
        let extensions = ['*', '.js', '.jsx', '.vue'];

        let buildFile = 'vue/dist/vue.common.js';

        if (Config.typeScript) {
            extensions.push('.ts', '.tsx');

            buildFile = 'vue/dist/vue.esm.js';
        }

        this.webpackConfig.resolve = {
            extensions,

            alias: {
                'vue$': buildFile
            }
        };

        return this;
    }

    /**
     * Merge the user's custom Webpack configuration.
     */
    mergeCustomConfig() {
        if (Config.webpackConfig) {
            this.webpackConfig = require('webpack-merge').smart(
                this.webpackConfig, Config.webpackConfig
            );
        }
    }
}

module.exports = WebpackConfig;
<|endoftext|>


<commit_before>import m from 'mithril';
import _ from 'underscore';
import h from '../h';
import rewardVM from '../vms/reward-vm';
import projectVM from '../vms/project-vm';

const projectRewardList = {
    controller(args) {
        const storeKey = 'selectedReward',
            vm = rewardVM;

        const setInput = (el, isInitialized) => !isInitialized ? el.focus() : false;

        const submitContribution = () => {
            const valueFloat = h.monetaryToFloat(vm.contributionValue);

            if (valueFloat < vm.selectedReward().minimum_value) {
                vm.error(`O valor de apoio para essa recompensa deve ser de no mínimo R$${vm.selectedReward().minimum_value}`);
            } else {
                vm.error('');

                // THIS CHECK IS ONLY NECESSARY IF WHEN WE START ROUTING DIRECTLY TO THE /contributions/edit page
                // if (!h.getUser()) {
                //     h.storeObject(storeKey, {value: valueFloat, reward: vm.selectedReward()});

                //     return h.navigateToDevise('/' + projectVM.currentProject().permalink);
                // } else {
                // vm.contributionValue(valueFloat);
                //h.navigateTo(`/projects/${projectVM.currentproject().project_id}/contributions/new?reward_id=${vm.selectedReward().id}`);
                h.navigateTo(`/projects/${projectVM.currentProject().project_id}/contributions/fallback_create?contribution%5Breward_id%5D=${vm.selectedReward().id}&contribution%5Bvalue%5D=${valueFloat}`);
                // m.route(`/projects/${projectVM.currentproject().project_id}/payment`, {
                //    project_user_id: projectVM.currentProject().user_id
                // });
                // }
            }

            return false;
        };

        if (h.getStoredObject(storeKey)) {
            const {
                value,
                reward
            } = h.getStoredObject(storeKey);

            h.removeStoredObject(storeKey);
            vm.selectedReward(reward);
            vm.contributionValue(h.applyMonetaryMask(`${value},00`));
            submitContribution();
        }

        return {
            applyMask: vm.applyMask,
            error: vm.error,
            submitContribution: submitContribution,
            openedReward: vm.selectedReward,
            selectReward: vm.selectReward,
            contributionValue: vm.contributionValue,
            setInput: setInput
        };
    },
    view(ctrl, args) {
        //FIXME: MISSING ADJUSTS
        // - add draft admin modifications
        const project = args.project() || {
            open_for_contributions: false
        };
        return m('#rewards.u-marginbottom-30', _.map(args.rewardDetails(), (reward) => {

            return m('div[class="' + (h.rewardSouldOut(reward) ? 'card-gone' : 'card-reward ' + (project.open_for_contributions ? 'clickable' : '')) + ' card card-secondary u-marginbottom-10"]', {
                onclick: h.analytics.event({
                    cat: 'contribution_create',
                    act: 'contribution_reward_click',
                    lbl: reward.minimum_value,
                    project: project,
                    extraData: {
                        reward_id: reward.id,
                        reward_value: reward.minimum_value
                    }
                }, ctrl.selectReward(reward))
            }, [
                m('.u-marginbottom-20', [
                    m('.fontsize-base.fontweight-semibold', 'Para R$ ' + h.formatNumber(reward.minimum_value) + ' ou mais'),
                    m('.fontsize-smaller.fontweight-semibold', h.pluralize(reward.paid_count, ' apoio', ' apoios')), (reward.maximum_contributions > 0 ? [
                        (reward.waiting_payment_count > 0 ? m('.maximum_contributions.in_time_to_confirm.clearfix', [
                            m('.pending.fontsize-smallest.fontcolor-secondary', h.pluralize(reward.waiting_payment_count, ' apoio em prazo de confirmação', ' apoios em prazo de confirmação.'))
                        ]) : ''), (h.rewardSouldOut(reward) ? m('.u-margintop-10', [
                            m('span.badge.badge-gone.fontsize-smaller', 'Esgotada')
                        ]) : m('.u-margintop-10', [
                            m('span.badge.badge-attention.fontsize-smaller', [
                                m('span.fontweight-bold', 'Limitada'),
                                ' (' + h.rewardRemaning(reward) + ' de ' + reward.maximum_contributions + ' disponíveis)'
                            ])
                        ]))
                    ] : ''),
                ]),

                m('.fontsize-smaller.u-margintop-20', m.trust(h.simpleFormat(h.strip(reward.description)))),
                (!_.isEmpty(reward.deliver_at) ?
                    m('.fontsize-smaller', [
                        m('b', 'Estimativa de Entrega: '),
                        h.momentify(reward.deliver_at, 'MMM/YYYY')
                    ]) :
                    ''),
                (project.open_for_contributions && !h.rewardSouldOut(reward) ? [
                    ctrl.openedReward().id === reward.id ? m('.w-form', [
                        m('form.u-margintop-30', {
                            onsubmit: ctrl.submitContribution
                        }, [
                            m('.divider.u-marginbottom-20'),
                            m('.fontcolor-secondary.u-marginbottom-10',
                                'Valor do apoio'
                            ),
                            m('.w-row.u-marginbottom-20', [
                                m('.w-col.w-col-3.w-col-small-3.w-col-tiny-3',
                                    m('.back-reward-input-reward.placeholder',
                                        'R$'
                                    )
                                ),
                                m('.w-col.w-col-9.w-col-small-9.w-col-tiny-9',
                                    m('input.w-input.back-reward-input-reward[type="tel"]', {
                                        config: ctrl.setInput,
                                        onkeyup: m.withAttr('value', ctrl.applyMask),
                                        value: ctrl.contributionValue()
                                    })
                                )
                            ]),
                            m('input.w-button.btn.btn-medium[type="submit"][value="Continuar >"]'),
                            ctrl.error().length > 0 ? m('.text-error', [
                                m('br'),
                                m('span.fa.fa-exclamation-triangle'),
                                ` ${ctrl.error()}`
                            ]) : ''
                        ])
                    ]) : '',
                    // m('.project-reward-box-hover', [
                    //     m('.project-reward-box-select-text.u-text-center', 'Selecione essa recompensa')
                    // ])
                ] : '')
            ]);
        }));
    }
};

export default projectRewardList;
<commit_msg>Adds installment tags for reward cards [fix #132137475]<commit_after>import m from 'mithril';
import _ from 'underscore';
import h from '../h';
import rewardVM from '../vms/reward-vm';
import projectVM from '../vms/project-vm';

const projectRewardList = {
    controller(args) {
        const storeKey = 'selectedReward',
            vm = rewardVM;

        const setInput = (el, isInitialized) => !isInitialized ? el.focus() : false;

        const submitContribution = () => {
            const valueFloat = h.monetaryToFloat(vm.contributionValue);

            if (valueFloat < vm.selectedReward().minimum_value) {
                vm.error(`O valor de apoio para essa recompensa deve ser de no mínimo R$${vm.selectedReward().minimum_value}`);
            } else {
                vm.error('');

                // THIS CHECK IS ONLY NECESSARY IF WHEN WE START ROUTING DIRECTLY TO THE /contributions/edit page
                // if (!h.getUser()) {
                //     h.storeObject(storeKey, {value: valueFloat, reward: vm.selectedReward()});

                //     return h.navigateToDevise('/' + projectVM.currentProject().permalink);
                // } else {
                // vm.contributionValue(valueFloat);
                //h.navigateTo(`/projects/${projectVM.currentproject().project_id}/contributions/new?reward_id=${vm.selectedReward().id}`);
                h.navigateTo(`/projects/${projectVM.currentProject().project_id}/contributions/fallback_create?contribution%5Breward_id%5D=${vm.selectedReward().id}&contribution%5Bvalue%5D=${valueFloat}`);
                // m.route(`/projects/${projectVM.currentproject().project_id}/payment`, {
                //    project_user_id: projectVM.currentProject().user_id
                // });
                // }
            }

            return false;
        };

        if (h.getStoredObject(storeKey)) {
            const {
                value,
                reward
            } = h.getStoredObject(storeKey);

            h.removeStoredObject(storeKey);
            vm.selectedReward(reward);
            vm.contributionValue(h.applyMonetaryMask(`${value},00`));
            submitContribution();
        }

        return {
            applyMask: vm.applyMask,
            error: vm.error,
            submitContribution: submitContribution,
            openedReward: vm.selectedReward,
            selectReward: vm.selectReward,
            contributionValue: vm.contributionValue,
            setInput: setInput
        };
    },
    view(ctrl, args) {
        //FIXME: MISSING ADJUSTS
        // - add draft admin modifications
        const project = args.project() || {
            open_for_contributions: false
        };
        return m('#rewards.u-marginbottom-30', _.map(args.rewardDetails(), (reward) => {

            return m('div[class="' + (h.rewardSouldOut(reward) ? 'card-gone' : 'card-reward ' + (project.open_for_contributions ? 'clickable' : '')) + ' card card-secondary u-marginbottom-10"]', {
                onclick: h.analytics.event({
                    cat: 'contribution_create',
                    act: 'contribution_reward_click',
                    lbl: reward.minimum_value,
                    project: project,
                    extraData: {
                        reward_id: reward.id,
                        reward_value: reward.minimum_value
                    }
                }, ctrl.selectReward(reward))
            }, [
                reward.minimum_value >= 100 ? m('.tag-circle-installment', [
                    m('.fontsize-smallest.fontweight-semibold.lineheight-tightest', '3x'),
                    m('.fontsize-mini.lineheight-tightest', 's/ juros')
                ]) : '',
                m('.u-marginbottom-20', [
                    m('.fontsize-base.fontweight-semibold', 'Para R$ ' + h.formatNumber(reward.minimum_value) + ' ou mais'),
                    m('.fontsize-smaller.fontweight-semibold', h.pluralize(reward.paid_count, ' apoio', ' apoios')), (reward.maximum_contributions > 0 ? [
                        (reward.waiting_payment_count > 0 ? m('.maximum_contributions.in_time_to_confirm.clearfix', [
                            m('.pending.fontsize-smallest.fontcolor-secondary', h.pluralize(reward.waiting_payment_count, ' apoio em prazo de confirmação', ' apoios em prazo de confirmação.'))
                        ]) : ''), (h.rewardSouldOut(reward) ? m('.u-margintop-10', [
                            m('span.badge.badge-gone.fontsize-smaller', 'Esgotada')
                        ]) : m('.u-margintop-10', [
                            m('span.badge.badge-attention.fontsize-smaller', [
                                m('span.fontweight-bold', 'Limitada'),
                                ' (' + h.rewardRemaning(reward) + ' de ' + reward.maximum_contributions + ' disponíveis)'
                            ])
                        ]))
                    ] : ''),
                ]),

                m('.fontsize-smaller.u-margintop-20', m.trust(h.simpleFormat(h.strip(reward.description)))),
                (!_.isEmpty(reward.deliver_at) ?
                    m('.fontsize-smaller', [
                        m('b', 'Estimativa de Entrega: '),
                        h.momentify(reward.deliver_at, 'MMM/YYYY')
                    ]) :
                    ''),
                (project.open_for_contributions && !h.rewardSouldOut(reward) ? [
                    ctrl.openedReward().id === reward.id ? m('.w-form', [
                        m('form.u-margintop-30', {
                            onsubmit: ctrl.submitContribution
                        }, [
                            m('.divider.u-marginbottom-20'),
                            m('.fontcolor-secondary.u-marginbottom-10',
                                'Valor do apoio'
                            ),
                            m('.w-row.u-marginbottom-20', [
                                m('.w-col.w-col-3.w-col-small-3.w-col-tiny-3',
                                    m('.back-reward-input-reward.placeholder',
                                        'R$'
                                    )
                                ),
                                m('.w-col.w-col-9.w-col-small-9.w-col-tiny-9',
                                    m('input.w-input.back-reward-input-reward[type="tel"]', {
                                        config: ctrl.setInput,
                                        onkeyup: m.withAttr('value', ctrl.applyMask),
                                        value: ctrl.contributionValue()
                                    })
                                )
                            ]),
                            m('input.w-button.btn.btn-medium[type="submit"][value="Continuar >"]'),
                            ctrl.error().length > 0 ? m('.text-error', [
                                m('br'),
                                m('span.fa.fa-exclamation-triangle'),
                                ` ${ctrl.error()}`
                            ]) : ''
                        ])
                    ]) : '',
                    // m('.project-reward-box-hover', [
                    //     m('.project-reward-box-select-text.u-text-center', 'Selecione essa recompensa')
                    // ])
                ] : '')
            ]);
        }));
    }
};

export default projectRewardList;
<|endoftext|>


<commit_before>window.c.ProjectRewardList = (function(m, h, models, _){
  return {
    controller: function(args) {
      var listVM = m.postgrest.paginationVM(models.rewardDetail.getPage),
          filterVM = m.postgrest.filtersVM({project_id: 'eq'}),
          rewardDetails = m.prop([]);

      filterVM.project_id(args.project.id);

      //FIXME: row_order rank
      listVM.firstPage(filterVM.parameters()).then(rewardDetails);

      return {
        rewardDetails: rewardDetails
      };
    },

    view: function(ctrl, args) {
      //FIXME: MISSING ADJUSTS
      // - add draft admin modifications
      var project = args.project;
      return m('#rewards.u-marginbottom-30', _.map(ctrl.rewardDetails(), function(reward) {
        var contributionUrlWithReward = '/projects/' + project.id + '/contributions/new?reward_id=' + reward.id;

        return m('a[class="' + (h.rewardSouldOut(reward) ? "card-gone" : "card-reward " + (project.open_for_contributions ? 'clickable' : '') ) + ' card card-secondary u-marginbottom-10"][href="' + (project.open_for_contributions ? contributionUrlWithReward : 'js:void(0);') + '"]', [
          m('.u-marginbottom-20', [
            m('.fontsize-base.fontweight-semibold', 'Para R$ ' + h.formatNumber(reward.minimum_value) + ' ou mais'),
            m('.fontsize-smaller.fontweight-semibold', h.pluralize(reward.paid_count, ' apoiador', ' apoiadores')),
            (reward.maximum_contributions > 0 ? [
              (reward.waiting_payment_count > 0 ? m('.maximum_contributions.in_time_to_confirm.clearfix', [
                m('.pending.fontsize-smallest.fontcolor-secondary', h.pluralize(reward.waiting_payment_count, ' apoio em prazo de confirmação', ' apoios em prazo de confirmação.'))
              ]) : ''),
              (h.rewardSouldOut(reward) ? m('.u-margintop-10', [
                m('span.badge.badge-gone.fontsize-smaller', 'Esgotada')
              ]) : m('.u-margintop-10', [
                m('span.badge.badge-attention.fontsize-smaller', [
                  m('span.fontweight-bold', 'Limitada'),
                  ' ( ' + h.rewardRemaning(reward) + ' de ' + reward.maximum_contributions + ' disponíveis)'
                ])
              ]))
            ] : ''),
          ]),
          m('.fontsize-smaller.u-margintop-20', m.trust(h.simpleFormat(reward.description))),
          (!_.isEmpty(reward.deliver_at) ?
            m('.fontsize-smaller', [
              m('b', 'Estimativa de Entrega: '),
              h.momentify(reward.deliver_at, 'MMM/YYYY')
            ])
           : ''),
          (project.open_for_contributions ?
            m('.project-reward-box-hover', [
              m('.project-reward-box-select-text.u-text-center', 'Selecione essa recompensa')
            ]) : '' )
        ]);
      }));
    }
  };
}(window.m, window.c.h, window.c.models, window._));
<commit_msg>use getPage directly<commit_after>window.c.ProjectRewardList = (function(m, h, models, _){
  return {
    controller: function(args) {
      var filterVM = m.postgrest.filtersVM({project_id: 'eq'}),
          rewardDetails = m.prop([]);

      filterVM.project_id(args.project.id);
      filterVM.order(undefined);

      models.rewardDetail.getPage(filterVM.parameters()).then(rewardDetails);

      return {
        rewardDetails: rewardDetails
      };
    },

    view: function(ctrl, args) {
      //FIXME: MISSING ADJUSTS
      // - add draft admin modifications
      var project = args.project;
      return m('#rewards.u-marginbottom-30', _.map(ctrl.rewardDetails(), function(reward) {
        var contributionUrlWithReward = '/projects/' + project.id + '/contributions/new?reward_id=' + reward.id;

        return m('a[class="' + (h.rewardSouldOut(reward) ? "card-gone" : "card-reward " + (project.open_for_contributions ? 'clickable' : '') ) + ' card card-secondary u-marginbottom-10"][href="' + (project.open_for_contributions ? contributionUrlWithReward : 'js:void(0);') + '"]', [
          m('.u-marginbottom-20', [
            m('.fontsize-base.fontweight-semibold', 'Para R$ ' + h.formatNumber(reward.minimum_value) + ' ou mais'),
            m('.fontsize-smaller.fontweight-semibold', h.pluralize(reward.paid_count, ' apoiador', ' apoiadores')),
            (reward.maximum_contributions > 0 ? [
              (reward.waiting_payment_count > 0 ? m('.maximum_contributions.in_time_to_confirm.clearfix', [
                m('.pending.fontsize-smallest.fontcolor-secondary', h.pluralize(reward.waiting_payment_count, ' apoio em prazo de confirmação', ' apoios em prazo de confirmação.'))
              ]) : ''),
              (h.rewardSouldOut(reward) ? m('.u-margintop-10', [
                m('span.badge.badge-gone.fontsize-smaller', 'Esgotada')
              ]) : m('.u-margintop-10', [
                m('span.badge.badge-attention.fontsize-smaller', [
                  m('span.fontweight-bold', 'Limitada'),
                  ' ( ' + h.rewardRemaning(reward) + ' de ' + reward.maximum_contributions + ' disponíveis)'
                ])
              ]))
            ] : ''),
          ]),
          m('.fontsize-smaller.u-margintop-20', m.trust(h.simpleFormat(reward.description))),
          (!_.isEmpty(reward.deliver_at) ?
            m('.fontsize-smaller', [
              m('b', 'Estimativa de Entrega: '),
              h.momentify(reward.deliver_at, 'MMM/YYYY')
            ])
           : ''),
          (project.open_for_contributions ?
            m('.project-reward-box-hover', [
              m('.project-reward-box-select-text.u-text-center', 'Selecione essa recompensa')
            ]) : '' )
        ]);
      }));
    }
  };
}(window.m, window.c.h, window.c.models, window._));
<|endoftext|>


<commit_before>/*global cordova, module*/

module.exports = {
    startfacedetect: function (name, successCallback, errorCallback) {
        cordova.exec(successCallback, errorCallback, "facedetect", "startfacedetect", [name]);
    }
};
<commit_msg>Update facedetect.js<commit_after>/*global cordova, module*/

module.exports = {
    startfacedetect: function (name, successCallback, errorCallback) {
        cordova.exec(successCallback, errorCallback, "facedetect", "startfacedetect", [name]);
    }
};
<|endoftext|>


<commit_before>/*
 * mongo-edu
 *
 * Copyright (c) 2014 Przemyslaw Pluta
 * Licensed under the MIT license.
 * https://github.com/przemyslawpluta/mongo-edu/blob/master/LICENSE
 */

var pkg = require('./package'),
    mdbvideos = require('./lib/login'),
    configure = require('./lib/configure'),
    argsOptions = require('./lib/options'),
    validate = require('./lib/validate'),
    videoHandler = require('./lib/videos'),
    initialize = require('./lib/initialize'),
    yargs = argsOptions.build(),
    url = require('url'),
    path = require('path'),
    colors = require('colors');

process.title = pkg.name;

exports.create = function start() {

    'use strict';

    console.log('\n[ ' + pkg.name.toUpperCase() + ' ' + pkg.version + ' ]\n');

    var argv = yargs.argv, slash = (/^win/.test(process.platform)) ? '\\' : '/';

    if (argv.help) { return yargs.showHelp(); }

    argv.d = path.normalize(argv.d);

    if (argv.d.substr(-1) !== slash) { argv.d += slash; }

    function initRun(data) {
        argv = data;
        validate.init(argv, function init(err, profile) {
            if (err !== null) { throw err; }
            argsOptions.checkIfSave(argv, initAndConfigure, profile);
        });
    }

    function checkProxy(profile) {
        var proxyDetails = url.parse(argv.proxy);

        console.log('i'.magenta + ' Proxy Host: '.bold + proxyDetails.hostname.cyan + ' Port: '.bold + proxyDetails.port.cyan + ' Protocol: '.bold + proxyDetails.protocol.replace(':', '').toUpperCase().cyan);

        mdbvideos.checkProxy(argv.proxy, function get(err, data) {
            if (err !== null) {
                if (argv.verbose) {
                    console.log('i'.red + ' Proxy Error: '.red + err.stack);
                } else {
                    console.log('i'.red + ' Proxy Might By Unusable.'.red);
                }
            }

            if (data) { console.log('i'.magenta + ' ' + data); }
            if (argv.test) { return videoHandler.checkProxyDownload(argv); }

            initialize(profile, argv);
        });
    }

    function initAndConfigure(profile, data) {
        argv = data;
        configure(argv, function conf(err) {
            if (err !== null) { throw err; }

            if (!argv.proxy || argv.h) { return initialize(profile, argv); }

            checkProxy(profile);

        });
    }

    argsOptions.checkIfLoad(argv, initRun);
};
<commit_msg>update<commit_after>/*
 * mongo-edu
 *
 * Copyright (c) 2014 Przemyslaw Pluta
 * Licensed under the MIT license.
 * https://github.com/przemyslawpluta/mongo-edu/blob/master/LICENSE
 */

var pkg = require('./package'),
    mdbvideos = require('./lib/login'),
    configure = require('./lib/configure'),
    argsOptions = require('./lib/options'),
    validate = require('./lib/validate'),
    videoHandler = require('./lib/videos'),
    initialize = require('./lib/initialize'),
    yargs = argsOptions.build(),
    url = require('url'),
    path = require('path'),
    colors = require('colors');

process.title = pkg.name;

exports.create = function start() {

    'use strict';

    console.log('\n[ ' + pkg.name.toUpperCase() + ' ' + pkg.version + ' ]\n');

    var argv = yargs.argv, slash = (/^win/.test(process.platform)) ? '\\' : '/';

    if (argv.help) { return yargs.showHelp(); }

    argv.d = path.normalize(argv.d);

    if (argv.d.substr(-1) !== slash) { argv.d += slash; }

    function initRun(data) {
        argv = data;
        validate.init(argv, function init(err, profile) {
            if (err !== null) { throw err; }
            argsOptions.checkIfSave(argv, initAndConfigure, profile);
        });
    }

    function checkProxy(profile) {
        var proxyDetails = url.parse(argv.proxy);

        console.log('i'.magenta + ' Proxy Host: '.bold + proxyDetails.hostname.cyan + ' Port: '.bold + proxyDetails.port.cyan + ' Protocol: '.bold + proxyDetails.protocol.replace(':', '').toUpperCase().cyan);

        mdbvideos.checkProxy(argv.proxy, function get(err, data) {
            if (err !== null) {
                if (argv.verbose) {
                    console.log('i'.red + ' Proxy Error: '.red + err.stack);
                } else {
                    console.log('i'.red + ' Proxy Might By Unusable.'.red);
                }
            }

            if (data) { console.log('i'.magenta + ' ' + data); }
            if (argv.test) { return videoHandler.checkProxyDownload(argv); }

            initialize(profile, argv);
        });
    }

    function initAndConfigure(profile, data) {
        argv = data;
        configure(argv, function conf(err) {
            if (err !== null) { throw err; }
            if (!argv.proxy || argv.h) { return initialize(profile, argv); }
            checkProxy(profile);
        });
    }

    argsOptions.checkIfLoad(argv, initRun);
};
<|endoftext|>


<commit_before>'use strict'
var RPC = require('socket.io-rpc')
const _ = require('lodash')
// const debug = require('debug')('moonridge:server')
const MRModel = require('./mr-server-model')
var userModel
var moonridgeSingleton

const baucis = require('./utils/baucis')

var models = {}
var mongoose = require('mongoose')
const defaultOpts = {
  server: {
    socketOptions: { keepAlive: 1 }
  },
  replset: {
    socketOptions: { keepAlive: 1 }
  }
}

/**
 * @param {String} connString to mongoDB
 * @param {Object} opts connection options
 * @returns {{model: regNewModel, userModel: registerUserModel, authUser: authUser, bootstrap: createServer}} moonridge
 * instance which allows to register models and bootstrap itself
 */
function connect (connString, opts) {
  _.merge(defaultOpts, opts)
  mongoose.connect(connString, defaultOpts, function (err) {
    if (err) {
      throw err
    } else {
      console.log(`connected to mongo ${connString} succesfully`)
    }
  })
  mongoose.connection.on('error', function (err) {
    console.error('MongoDB error: %s', err)
  })
}
/**
 * @param {String} name
 * @param {Object} schema
 * @param {Object} opts
 * @param {Function} [opts.checkPermission] function which should return true/false depending if the connected socket has/hasn't priviliges
 * @param {Object} [opts.permissions] with 4 properties: 'C', 'R','U', 'D' which each represents one type of operation,
 *                                  values should be numbers indicating which level of privilige is needed

 * @returns {MRModel}
 */
function regNewModel (name, schema, opts) {
  var model = MRModel.apply(moonridgeSingleton, arguments)
  models[name] = model
  return model
}

/**
 *
 * @param schemaExtend
 * @param {Object} opts
 * @returns {MRModel}
 */
function registerUserModel (schemaExtend, opts) {
  if (userModel) {    // if it was already assigned, we throw
    throw new Error('There can only be one user model and it was already registered')
  }
  var userSchema = require('./utils/user-model-base')
  _.extend(userSchema, schemaExtend)
  userModel = MRModel.call(moonridgeSingleton, 'user', userSchema, opts)
  models['user'] = userModel

  return userModel
}

/**
 * Shares the same signature as express.js listen method, because it passes arguments to it
 * @param {Number} port
 * @param {String} [hostname]
 * @param {Function} [Callback]
 * @returns {{rpcNsp: (Emitter), io: {Object}, server: http.Server}}
 */
function bootstrap () {
  var server = RPC.apply(null, arguments)
  var io = server.io

  var allQueries = []

  io.on('connection', function (socket) {
    socket.registeredLQs = []
    socket.on('disconnect', function () {
      // clearing out liveQueries listeners
      for (var LQId in socket.registeredLQs) {
        var LQ = socket.registeredLQs[LQId]
        LQ.removeListener(socket)
      }
    })
  })

  Object.keys(models).forEach(function (modelName) {
    var model = models[modelName]
    baucis.rest(modelName)
    model._exposeCallback(server)
  })

  io.use(function (socket, next) {
    socket.moonridge = {user: {privilege_level: 0}} // default privilege level for any connected client
    next()
  })

  server.allModelGetHandler = function (req, res) {
    res.type('application/javascript charset=utf-8')
    var modelNames = Object.keys(models)
    var clSideScript = 'module.exports = function (MR) {' +
      'var modelsHash = {}' +
      'var models = ' + JSON.stringify(modelNames) + '' +
      'models.forEach(function (modelName) {modelsHash[modelName] = MR.model(modelName)})' +
      'return modelsHash' +
      '}'
    res.send(clSideScript)
    res.end()
  }

  server.expose({
    MR: {
      deAuthorize: function () {
        this.moonridge.user = {privilege_level: 0}	// for logging users out
      }
    }
  })

  if (process.env.MOONRIDGE_HEALTH === '1') {
    // this reveals any data that you use in queries to the public, so it should not be used in production when dealing with sensitive data

    server.expose({
      MR: {
        getHealth: function () {
          var allModels = {}
          var index = allQueries.length
          while (index--) {
            var modelQueriesForSerialization = {}
            var model = allQueries[index]
            for (var LQ in model.queries) {
              modelQueriesForSerialization[LQ] = Object.keys(model.queries[LQ].listeners).length
            }
            allModels[model.modelName] = modelQueriesForSerialization
          }
          return {
            pid: process.pid,
            memory: process.memoryUsage(),
            uptime: process.uptime(),   // in seconds
            liveQueries: allModels  // key is LQ.clientQuery and value is number of listening clients
          }
        }
      }
    })
  }

  return server
}

moonridgeSingleton = {
  model: regNewModel,
  userModel: registerUserModel,
  bootstrap: bootstrap,
  mongoose: mongoose,
  models: models,
  connect: connect,
  baucis: baucis
}

module.exports = moonridgeSingleton
<commit_msg>instead of allModelGetHandler we expose getModels on RPC<commit_after>'use strict'
var RPC = require('socket.io-rpc')
const _ = require('lodash')
// const debug = require('debug')('moonridge:server')
const MRModel = require('./mr-server-model')
var userModel
var moonridgeSingleton

const baucis = require('./utils/baucis')

var models = {}
var mongoose = require('mongoose')
const defaultOpts = {
  server: {
    socketOptions: { keepAlive: 1 }
  },
  replset: {
    socketOptions: { keepAlive: 1 }
  }
}

/**
 * @param {String} connString to mongoDB
 * @param {Object} opts connection options
 * @returns {{model: regNewModel, userModel: registerUserModel, authUser: authUser, bootstrap: createServer}} moonridge
 * instance which allows to register models and bootstrap itself
 */
function connect (connString, opts) {
  _.merge(defaultOpts, opts)
  mongoose.connect(connString, defaultOpts, function (err) {
    if (err) {
      throw err
    } else {
      console.log(`connected to mongo ${connString} succesfully`)
    }
  })
  mongoose.connection.on('error', function (err) {
    console.error('MongoDB error: %s', err)
  })
}
/**
 * @param {String} name
 * @param {Object} schema
 * @param {Object} opts
 * @param {Function} [opts.checkPermission] function which should return true/false depending if the connected socket has/hasn't priviliges
 * @param {Object} [opts.permissions] with 4 properties: 'C', 'R','U', 'D' which each represents one type of operation,
 *                                  values should be numbers indicating which level of privilige is needed

 * @returns {MRModel}
 */
function regNewModel (name, schema, opts) {
  var model = MRModel.apply(moonridgeSingleton, arguments)
  models[name] = model
  return model
}

/**
 *
 * @param schemaExtend
 * @param {Object} opts
 * @returns {MRModel}
 */
function registerUserModel (schemaExtend, opts) {
  if (userModel) {    // if it was already assigned, we throw
    throw new Error('There can only be one user model and it was already registered')
  }
  var userSchema = require('./utils/user-model-base')
  _.extend(userSchema, schemaExtend)
  userModel = MRModel.call(moonridgeSingleton, 'user', userSchema, opts)
  models['user'] = userModel

  return userModel
}

/**
 * Shares the same signature as express.js listen method, because it passes arguments to it
 * @param {Number} port
 * @param {String} [hostname]
 * @param {Function} [Callback]
 * @returns {{rpcNsp: (Emitter), io: {Object}, server: http.Server}}
 */
function bootstrap () {
  var server = RPC.apply(null, arguments)
  var io = server.io

  var allQueries = []

  io.on('connection', function (socket) {
    socket.registeredLQs = []
    socket.on('disconnect', function () {
      // clearing out liveQueries listeners
      for (var LQId in socket.registeredLQs) {
        var LQ = socket.registeredLQs[LQId]
        LQ.removeListener(socket)
      }
    })
  })

  Object.keys(models).forEach(function (modelName) {
    var model = models[modelName]
    baucis.rest(modelName)
    model._exposeCallback(server)
  })

  io.use(function (socket, next) {
    socket.moonridge = {user: {privilege_level: 0}} // default privilege level for any connected client
    next()
  })

  server.expose({
    MR: {
      getModels: function () {
        return Object.keys(models)
      },
      deAuthorize: function () {
        this.moonridge.user = {privilege_level: 0}	// for logging users out
      }
    }
  })

  if (process.env.MOONRIDGE_HEALTH === '1') {
    // this reveals any data that you use in queries to the public, so it should not be used in production when dealing with sensitive data

    server.expose({
      MR: {
        getHealth: function () {
          var allModels = {}
          var index = allQueries.length
          while (index--) {
            var modelQueriesForSerialization = {}
            var model = allQueries[index]
            for (var LQ in model.queries) {
              modelQueriesForSerialization[LQ] = Object.keys(model.queries[LQ].listeners).length
            }
            allModels[model.modelName] = modelQueriesForSerialization
          }
          return {
            pid: process.pid,
            memory: process.memoryUsage(),
            uptime: process.uptime(),   // in seconds
            liveQueries: allModels  // key is LQ.clientQuery and value is number of listening clients
          }
        }
      }
    })
  }

  return server
}

moonridgeSingleton = {
  model: regNewModel,
  userModel: registerUserModel,
  bootstrap: bootstrap,
  mongoose: mongoose,
  models: models,
  connect: connect,
  baucis: baucis
}

module.exports = moonridgeSingleton
<|endoftext|>