<commit_before>/**

The MIT License (MIT)

Copyright (c) 2016 Jacob Lindahl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

 */

(function () {
    window.SimpleStarRating = SimpleStarRating;

    function SimpleStarRating(target) {
        var max = (target.getAttribute('data-stars') ?
                parseInt(target.getAttribute('data-stars')) : 5),
            disabled = false,
            currentRating = (target.getAttribute('data-rating') ?
                parseFloat(target.getAttribute('data-rating')) : 0),
            stars = [];

        target.style.display = 'inline-block';

        for (var s = 0; s < max; s++) {
            var n = document.createElement('span');
            n.className = 'star';
            n.addEventListener('click', starClick);
            if (s > 0)
                stars[s - 1].appendChild(n);
            else
                target.appendChild(n);

            stars.push(n);
        }

        function disable() {
            target.setAttribute('disabled', '');
            disabled = true;
        }
        this.disable = disable;

        function enable() {
            target.removeAttribute('disabled');
            disabled = false;
        }
        this.enable = enable;

        function setCurrentRating(rating) {
            currentRating = rating;
            target.setAttribute('data-rating', currentRating);
        }

        this.setCurrentRating = setCurrentRating;

        this.onrate = function (rating) {};

        target.addEventListener('mouseout', function () {
            disabled = target.getAttribute('disabled') !== null;
            if (!disabled)
                showCurrentRating();
        });

        target.addEventListener('mouseover', function () {
            disabled = target.getAttribute('disabled') !== null;
            if (!disabled)
                clearRating();
        });

        showCurrentRating();

        function showCurrentRating() {
            clearRating();
            currentRating = parseFloat(target.getAttribute('data-rating')) || 0;
            for (var i = 0; i < stars.length; i++) {
                if (i >= currentRating)
                    break;
                if (i === Math.floor(currentRating) && i !== currentRating)
                    stars[i].classList.add('half');
                stars[i].classList.add('active');
            }
        }

        function clearRating() {
            for (var i = 0; i < stars.length; i++) {
                stars[i].classList.remove('active');
                stars[i].classList.remove('half');
            }
        }

        function starClick(e) {
            if (this === e.target) {
                var starClicked = stars.indexOf(e.target);
                if (starClicked !== -1) {
                    var starRating = starClicked + 1;
                    setCurrentRating(starRating);
                    if (typeof this.onrate === 'function')
                        this.onrate(currentRating);
                    var evt = new CustomEvent('rate', {
                        detail: starRating,
                    });
                    target.dispatchEvent(evt);
                }
            }
        }
    }
})();
<commit_msg>sets SimpleStarRating to global instead of property of window<commit_after>/**

The MIT License (MIT)

Copyright (c) 2016 Jacob Lindahl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

 */

var SimpleStarRating = (function () {
    function SimpleStarRating(target) {
        var max = (target.getAttribute('data-stars') ?
                parseInt(target.getAttribute('data-stars')) : 5),
            disabled = false,
            currentRating = (target.getAttribute('data-rating') ?
                parseFloat(target.getAttribute('data-rating')) : 0),
            stars = [];

        target.style.display = 'inline-block';

        for (var s = 0; s < max; s++) {
            var n = document.createElement('span');
            n.className = 'star';
            n.addEventListener('click', starClick);
            if (s > 0)
                stars[s - 1].appendChild(n);
            else
                target.appendChild(n);

            stars.push(n);
        }

        function disable() {
            target.setAttribute('disabled', '');
            disabled = true;
        }
        this.disable = disable;

        function enable() {
            target.removeAttribute('disabled');
            disabled = false;
        }
        this.enable = enable;

        function setCurrentRating(rating) {
            currentRating = rating;
            target.setAttribute('data-rating', currentRating);
        }

        this.setCurrentRating = setCurrentRating;

        this.onrate = function (rating) {};

        target.addEventListener('mouseout', function () {
            disabled = target.getAttribute('disabled') !== null;
            if (!disabled)
                showCurrentRating();
        });

        target.addEventListener('mouseover', function () {
            disabled = target.getAttribute('disabled') !== null;
            if (!disabled)
                clearRating();
        });

        showCurrentRating();

        function showCurrentRating() {
            clearRating();
            currentRating = parseFloat(target.getAttribute('data-rating')) || 0;
            for (var i = 0; i < stars.length; i++) {
                if (i >= currentRating)
                    break;
                if (i === Math.floor(currentRating) && i !== currentRating)
                    stars[i].classList.add('half');
                stars[i].classList.add('active');
            }
        }

        function clearRating() {
            for (var i = 0; i < stars.length; i++) {
                stars[i].classList.remove('active');
                stars[i].classList.remove('half');
            }
        }

        function starClick(e) {
            if (this === e.target) {
                var starClicked = stars.indexOf(e.target);
                if (starClicked !== -1) {
                    var starRating = starClicked + 1;
                    setCurrentRating(starRating);
                    if (typeof this.onrate === 'function')
                        this.onrate(currentRating);
                    var evt = new CustomEvent('rate', {
                        detail: starRating,
                    });
                    target.dispatchEvent(evt);
                }
            }
        }
    }

    return SimpleStarRating;
})();
<|endoftext|>


<commit_before>({
	/*
	 * Invoke with r.js -o build.js
	 * Documentation of available options: https://github.com/jrburke/r.js/blob/master/build/example.build.js
	 */
	baseUrl: "scripts",
	mainConfigFile: 'scripts/includes.js',
	out: "js/main.built.js",
	optimize: 'uglify',
	include : ['main'],
	findNestedDependencies: true,
	preserveLicenseComments: false

})
<commit_msg>Build destination<commit_after>({
	/*
	 * Invoke with r.js -o build.js
	 * Documentation of available options: https://github.com/jrburke/r.js/blob/master/build/example.build.js
	 */
	baseUrl: "scripts",
	mainConfigFile: 'scripts/includes.js',
	out: "dist/aris.js",
	optimize: 'uglify2',
	paths: {
		"inlineRequireJS": 'library/require',
	},
	include : ['inlineRequireJS', 'main'],
	findNestedDependencies: true,
	preserveLicenseComments: false

})
<|endoftext|>


<commit_before>// Libraries for component rendering
import React from 'react';
import {
    Text,
    TouchableOpacity
} from 'react-native';

const IconButton = ({ onPress, children }) => {
    return (
        <TouchableOpacity onPress={onPress} style={styles.transparentBackgroundButton}>
            { children }
        </TouchableOpacity>
    );
};

const styles = {
    transparentBackgroundButton: {
        backgroundColor: "transparent",
        borderRadius: 5,
        borderWidth: 1,
        borderColor: "#E10019",
        paddingLeft: 19,
        paddingRight: 19,
        paddingTop: 10,
        paddingBottom: 10
    }
};

export { IconButton };
<commit_msg>Changed that the common 'IconButton' component also uses the passed 'style' prop<commit_after>// Libraries for component rendering
import React from 'react';
import {
    Text,
    TouchableOpacity
} from 'react-native';

const IconButton = ({ onPress, children, style }) => {
    return (
        <TouchableOpacity onPress={onPress} style={[styles.transparentBackgroundButton, style]}>
            { children }
        </TouchableOpacity>
    );
};

const styles = {
    transparentBackgroundButton: {
        backgroundColor: "transparent",
        borderRadius: 5,
        borderWidth: 1,
        borderColor: "#E10019",
        paddingLeft: 19,
        paddingRight: 19,
        paddingTop: 10,
        paddingBottom: 10
    }
};

export { IconButton };
<|endoftext|>


<commit_before>'use strict';

/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
  , Sequelize = require('../../../index')
  , Promise = Sequelize.Promise
  , expect = chai.expect
  , Support = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , current = Support.sequelize;

chai.config.includeStack = true;

describe(Support.getTestDialectTeaser('Model'), function() {
  if (current.dialect.supports.JSONB) {
    describe('JSONB', function () {
      beforeEach(function () {
        this.Event = this.sequelize.define('Event', {
          data: {
            type: DataTypes.JSONB,
            field: 'event_data',
            index: true
          }
        });

        return this.Event.sync({force: true});
      });

      it('should create an instance with JSONB data', function () {
        return this.Event.create({
          data: {
            name: {
              first: 'Homer',
              last: 'Simpson'
            },
            employment: 'Nuclear Safety Inspector'
          }
        }).bind(this).then(function () {
          return this.Event.findAll().then(function (events) {
            var event = events[0];

            expect(event.get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            });
          });
        });
      });

      it('should be possible to query a nested value', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                employment: 'Housewife'
              }
            }
          }).then(function (events) {
            var event = events[0];

            expect(events.length).to.equal(1);
            expect(event.get('data')).to.eql({
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            });
          });
        });
      });

      it('should be possible to query a nested integer value', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              age: 40
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              age: 37
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                age: {
                  $gt: 38
                }
              }
            }
          }).then(function (events) {
            var event = events[0];

            expect(events.length).to.equal(1);
            expect(event.get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              age: 40
            });
          });
        });
      });

      it('should be possible to query a nested null value', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: null
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                employment: null
              }
            }
          }).then(function (events) {
            var event = events[0];

            expect(events.length).to.equal(1);
            expect(event.get('data')).to.eql({
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: null
            });
          });
        });
      });

      it('should be possible to query multiple nested values', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Bart',
                last: 'Simpson'
              },
              employment: 'None'
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                name: {
                  last: 'Simpson'
                },
                employment: {
                  $ne: 'None'
                }
              }
            },
            order: [
              ['id', 'ASC']
            ]
          }).then(function (events) {
            expect(events.length).to.equal(2);

            expect(events[0].get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            });

            expect(events[1].get('data')).to.eql({
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            });
          });
        });
      });
    });
  }
});<commit_msg>test for instance update on jsonb values<commit_after>'use strict';

/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
  , Sequelize = require('../../../index')
  , Promise = Sequelize.Promise
  , expect = chai.expect
  , Support = require(__dirname + '/../support')
  , DataTypes = require(__dirname + '/../../../lib/data-types')
  , current = Support.sequelize;

chai.config.includeStack = true;

describe(Support.getTestDialectTeaser('Model'), function() {
  if (current.dialect.supports.JSONB) {
    describe('JSONB', function () {
      beforeEach(function () {
        this.Event = this.sequelize.define('Event', {
          data: {
            type: DataTypes.JSONB,
            field: 'event_data',
            index: true
          }
        });

        return this.Event.sync({force: true});
      });

      it('should create an instance with JSONB data', function () {
        return this.Event.create({
          data: {
            name: {
              first: 'Homer',
              last: 'Simpson'
            },
            employment: 'Nuclear Safety Inspector'
          }
        }).bind(this).then(function () {
          return this.Event.findAll().then(function (events) {
            var event = events[0];

            expect(event.get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            });
          });
        });
      });

      it('should update an instance with JSONB data', function () {
        return this.Event.create({
          data: {
            name: {
              first: 'Homer',
              last: 'Simpson'
            },
            employment: 'Nuclear Safety Inspector'
          }
        }).bind(this).then(function (event) {
          return event.update({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: null
            }
          });
        }).then(function () {
          return this.Event.findAll().then(function (events) {
            var event = events[0];

            expect(event.get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: null
            });
          });
        });
      });

      it('should be possible to query a nested value', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                employment: 'Housewife'
              }
            }
          }).then(function (events) {
            var event = events[0];

            expect(events.length).to.equal(1);
            expect(event.get('data')).to.eql({
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            });
          });
        });
      });

      it('should be possible to query a nested integer value', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              age: 40
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              age: 37
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                age: {
                  $gt: 38
                }
              }
            }
          }).then(function (events) {
            var event = events[0];

            expect(events.length).to.equal(1);
            expect(event.get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              age: 40
            });
          });
        });
      });

      it('should be possible to query a nested null value', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: null
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                employment: null
              }
            }
          }).then(function (events) {
            var event = events[0];

            expect(events.length).to.equal(1);
            expect(event.get('data')).to.eql({
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: null
            });
          });
        });
      });

      it('should be possible to query multiple nested values', function () {
        return Promise.join(
          this.Event.create({
            data: {
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            }
          }),
          this.Event.create({
            data: {
              name: {
                first: 'Bart',
                last: 'Simpson'
              },
              employment: 'None'
            }
          })
        ).bind(this).then(function () {
          return this.Event.findAll({
            where: {
              data: {
                name: {
                  last: 'Simpson'
                },
                employment: {
                  $ne: 'None'
                }
              }
            },
            order: [
              ['id', 'ASC']
            ]
          }).then(function (events) {
            expect(events.length).to.equal(2);

            expect(events[0].get('data')).to.eql({
              name: {
                first: 'Homer',
                last: 'Simpson'
              },
              employment: 'Nuclear Safety Inspector'
            });

            expect(events[1].get('data')).to.eql({
              name: {
                first: 'Marge',
                last: 'Simpson'
              },
              employment: 'Housewife'
            });
          });
        });
      });
    });
  }
});<|endoftext|>


<commit_before>import React from "react";
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import Select from "react-select";
import { sidebarField } from "../../globalStyles";
import { controlsWidth, colorByMenuPreferredOrdering } from "../../util/globals";
import { changeColorBy } from "../../actions/colors";
import { analyticsControlsEvent } from "../../util/googleAnalytics";
import { isColorByGenotype, decodeColorByGenotype, encodeColorByGenotype, decodePositions } from "../../util/getGenotype";

/* the reason why we have colorBy as state (here) and in redux
   is for the case where we select genotype, then wait for the
   base to be selected, so we modify state but not yet dispatch */

@connect((state) => {
  return {
    colorBy: state.controls.colorBy,
    geneLength: state.controls.geneLength,
    colorOptions: state.metadata.colorOptions,
    geneMap: state.entropy.geneMap
  };
})
class ColorBy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colorBySelected: props.colorBy,
      geneSelected: "",
      positionSelected: ""
    };
  }
  static propTypes = {
    colorBy: PropTypes.string.isRequired,
    geneLength: PropTypes.object.isRequired,
    colorOptions: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.colorBy !== nextProps.colorBy) {
      if (isColorByGenotype(nextProps.colorBy)) {
        const genotype = decodeColorByGenotype(nextProps.colorBy);

        if (genotype) {
          this.setState({
            colorBySelected: "gt",
            geneSelected: genotype.gene,
            positionSelected: genotype.positions.join(",")
          });
        }
      } else {
        this.setState({
          colorBySelected: nextProps.colorBy,
          geneSelected: "",
          positionSelected: ""
        });
      }
    }
  }

  setColorBy(colorBy) {
    if (!isColorByGenotype(colorBy)) {
      analyticsControlsEvent(`color-by-${colorBy}`);
      this.props.dispatch(changeColorBy(colorBy));
      this.setState({colorBySelected: colorBy});
    } else {
      // don't update colorBy yet, genotype still needs to be specified
      this.setState({colorBySelected: "gt"});
    }
  }

  getGtGeneOptions() {
    let options = [];
    if (this.props.geneMap) {
      options = Object.keys(this.props.geneMap).map((prot) => ({value: prot, label: prot}));
      options[options.length] = {value: "nuc", label: "nucleotide"};
    }
    return options;
  }

  gtGeneSelect() {
    const gtGeneOptions = this.getGtGeneOptions();
    return (
      <Select
        name="selectGenotype"
        id="selectGenotype"
        placeholder="gene…"
        value={this.state.geneSelected}
        options={gtGeneOptions}
        clearable={false}
        searchable={true}
        multi={false}
        onChange={(opt) => {
          const gene = opt.value;
          const position = this.state.positionSelected;
          this.setState({geneSelected: gene});
          this.setGenotypeColoring(gene, position);
        }}
      />
    );
  }

  gtPositionInput() {
    const { geneSelected } = this.state;

    const geneLength = Math.floor(this.props.geneLength[geneSelected]);

    const placeholder = geneSelected
      ? `${geneSelected} position (1–${geneLength})…`
      : `position…`;

    return (
      <input
        type="text"
        style={sidebarField}
        placeholder={placeholder}
        value={this.state.positionSelected}
        onChange={(e) => {
          const gene = this.state.geneSelected;
          const position = e.target.value;
          console.log("gtPositionInput -> ", gene, position);
          this.setState({positionSelected: position});
          this.setGenotypeColoring(gene, position);
        }}
      />
    );
  }

  isNormalInteger(str) {
    const n = Math.floor(Number(str));
    return String(n) === str && n >= 0;
  }

  setGenotypeColoring(gene, position) {
    let positions = decodePositions(position, this.props.geneLength[gene]);
    const colorBy = encodeColorByGenotype({ gene, positions });
    if (colorBy) {
      analyticsControlsEvent("color-by-genotype");
      this.props.dispatch(changeColorBy(colorBy));
    }
  }

  getStyles() {
    return {
      base: {
        width: controlsWidth,
        marginBottom: 0,
        fontSize: 14
      }
    };
  }

  getColorByOptions() {
    return Object.keys(this.props.colorOptions).map((key) => {
      return {
        value: key,
        label: this.props.colorOptions[key].menuItem
      };
    }).sort((a, b) => {
      const [ia, ib] = [colorByMenuPreferredOrdering.indexOf(a.value), colorByMenuPreferredOrdering.indexOf(b.value)];
      if (ia === -1 || ib === -1) {
        if (ia === -1) return 1;
        else if (ib === -1) return -1;
        return 0;
      }
      return ia > ib ? 1 : -1;
    });
  }

  render() {
    const styles = this.getStyles();
    const colorOptions = this.getColorByOptions();
    return (

        <Select
          name="selectColorBy"
          id="selectColorBy"
          value={this.state.colorBySelected}
          options={colorOptions}
          clearable={false}
          searchable={false}
          multi={false}
          onChange={(opt) => {
            this.setColorBy(opt.value);
          }}
        />
        {this.state.colorBySelected === "gt" ?

            {this.gtGeneSelect()}
            {this.gtPositionInput()}

          :
          null
        }

    );
  }
}

export default ColorBy;
<commit_msg>controls/color-by: Reset and replace state entirely when switching color by field<commit_after>import React from "react";
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import Select from "react-select";
import { sidebarField } from "../../globalStyles";
import { controlsWidth, colorByMenuPreferredOrdering } from "../../util/globals";
import { changeColorBy } from "../../actions/colors";
import { analyticsControlsEvent } from "../../util/googleAnalytics";
import { isColorByGenotype, decodeColorByGenotype, encodeColorByGenotype, decodePositions } from "../../util/getGenotype";

/* the reason why we have colorBy as state (here) and in redux
   is for the case where we select genotype, then wait for the
   base to be selected, so we modify state but not yet dispatch */

@connect((state) => {
  return {
    colorBy: state.controls.colorBy,
    geneLength: state.controls.geneLength,
    colorOptions: state.metadata.colorOptions,
    geneMap: state.entropy.geneMap
  };
})
class ColorBy extends React.Component {
  constructor(props) {
    super(props);

    this.BLANK_STATE = {
      // These are values for controlled form components, so cannot be null.
      colorBySelected: "",
      geneSelected: "",
      positionSelected: ""
    };

    this.state = this.newState({
      colorBySelected: props.colorBy
    });
  }
  static propTypes = {
    colorBy: PropTypes.string.isRequired,
    geneLength: PropTypes.object.isRequired,
    colorOptions: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  // Applies the given state to the immutable blank state and replaces the
  // current state with the result.
  replaceState(state) {
    this.setState((oldState, props) => this.newState(state)); // eslint-disable-line no-unused-vars
  }

  newState(state) {
    return {
      ...this.BLANK_STATE,
      ...state
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.colorBy !== nextProps.colorBy) {
      if (isColorByGenotype(nextProps.colorBy)) {
        const genotype = decodeColorByGenotype(nextProps.colorBy);

        if (genotype) {
          this.replaceState({
            colorBySelected: "gt",
            geneSelected: genotype.gene,
            positionSelected: genotype.positions.join(",")
          });
        }
      } else {
        this.replaceState({
          colorBySelected: nextProps.colorBy
        });
      }
    }
  }

  setColorBy(colorBy) {
    if (!isColorByGenotype(colorBy)) {
      analyticsControlsEvent(`color-by-${colorBy}`);
      this.props.dispatch(changeColorBy(colorBy));
      this.replaceState({colorBySelected: colorBy});
    } else {
      // don't update colorBy yet, genotype still needs to be specified
      this.replaceState({colorBySelected: "gt"});
    }
  }

  getGtGeneOptions() {
    let options = [];
    if (this.props.geneMap) {
      options = Object.keys(this.props.geneMap).map((prot) => ({value: prot, label: prot}));
      options[options.length] = {value: "nuc", label: "nucleotide"};
    }
    return options;
  }

  gtGeneSelect() {
    const gtGeneOptions = this.getGtGeneOptions();
    return (
      <Select
        name="selectGenotype"
        id="selectGenotype"
        placeholder="gene…"
        value={this.state.geneSelected}
        options={gtGeneOptions}
        clearable={false}
        searchable={true}
        multi={false}
        onChange={(opt) => {
          const gene = opt.value;
          const position = this.state.positionSelected;
          this.setState({geneSelected: gene});
          this.setGenotypeColoring(gene, position);
        }}
      />
    );
  }

  gtPositionInput() {
    const { geneSelected } = this.state;

    const geneLength = Math.floor(this.props.geneLength[geneSelected]);

    const placeholder = geneSelected
      ? `${geneSelected} position (1–${geneLength})…`
      : `position…`;

    return (
      <input
        type="text"
        style={sidebarField}
        placeholder={placeholder}
        value={this.state.positionSelected}
        onChange={(e) => {
          const gene = this.state.geneSelected;
          const position = e.target.value;
          console.log("gtPositionInput -> ", gene, position);
          this.setState({positionSelected: position});
          this.setGenotypeColoring(gene, position);
        }}
      />
    );
  }

  isNormalInteger(str) {
    const n = Math.floor(Number(str));
    return String(n) === str && n >= 0;
  }

  setGenotypeColoring(gene, position) {
    let positions = decodePositions(position, this.props.geneLength[gene]);
    const colorBy = encodeColorByGenotype({ gene, positions });
    if (colorBy) {
      analyticsControlsEvent("color-by-genotype");
      this.props.dispatch(changeColorBy(colorBy));
    }
  }

  getStyles() {
    return {
      base: {
        width: controlsWidth,
        marginBottom: 0,
        fontSize: 14
      }
    };
  }

  getColorByOptions() {
    return Object.keys(this.props.colorOptions).map((key) => {
      return {
        value: key,
        label: this.props.colorOptions[key].menuItem
      };
    }).sort((a, b) => {
      const [ia, ib] = [colorByMenuPreferredOrdering.indexOf(a.value), colorByMenuPreferredOrdering.indexOf(b.value)];
      if (ia === -1 || ib === -1) {
        if (ia === -1) return 1;
        else if (ib === -1) return -1;
        return 0;
      }
      return ia > ib ? 1 : -1;
    });
  }

  render() {
    const styles = this.getStyles();
    const colorOptions = this.getColorByOptions();
    return (

        <Select
          name="selectColorBy"
          id="selectColorBy"
          value={this.state.colorBySelected}
          options={colorOptions}
          clearable={false}
          searchable={false}
          multi={false}
          onChange={(opt) => {
            this.setColorBy(opt.value);
          }}
        />
        {this.state.colorBySelected === "gt" ?

            {this.gtGeneSelect()}
            {this.gtPositionInput()}

          :
          null
        }

    );
  }
}

export default ColorBy;
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        browserify: {
            debug: true,
            transform: [
                [require('babelify'), {
                    presets: ["env"],
                    ignore: ["**/libs/**"],
                    plugins: ['istanbul']
                }],
                [require('browserify-css'), {global: true}],
                require('browserify-imgify')
            ]
        },

        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            './resources/img/**.png',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            {pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-16820.js', include: false},
            {pattern: '../src/classic/libs/Lang/*.js', include: false},
            {pattern: '../src/classic/theme/default/*.css', include: false},
            /**测试文件**/
            './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/

            './test-main-common.js',

            /***leaflet的源码***/
            {pattern: './libs/workers/TurfWorkerForTest.js', include: false},
            {pattern: '../node_modules/leaflet/dist/leaflet.css', include: false},
            {pattern: '../src/leaflet/**/**/*.css', include: false},
            '../src/leaflet/**/!(index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            {pattern: '../node_modules/openlayers/dist/ol-debug.css', include: false},
            {pattern: '../src/openlayers/**/**/*.css', include: false},
            '../src/openlayers/**/!(index).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            {pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false},
            '../src/mapboxgl/**/!(index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'
        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../node_modules/whatwg-fetch-importable/whatwgFetch.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-16820.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(index).js': ['browserify'],
            './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/openlayers/dist/ol-debug.js': ['browserify'],
            '../src/openlayers/**/!(index).js': ['browserify'],
            './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(index).js': ['browserify'],
            './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [
                {type: 'lcov', subdir: '.'}
            ]
        }
        ,

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity

    })
};
<commit_msg>【update】升级iclient8c  review by liqian<commit_after>// Karma configuration
// Generated on Fri Feb 17 2017 15:57:25 GMT+0800 (中国标准时间)

module.exports = function (config) {
    // 设置测试的超时时间

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'browserify'],

        browserify: {
            debug: true,
            transform: [
                [require('babelify'), {
                    presets: ["env"],
                    ignore: ["**/libs/**"],
                    plugins: ['istanbul']
                }],
                [require('browserify-css'), {global: true}],
                require('browserify-imgify')
            ]
        },

        // list of files  patterns to load in the browser
        // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器，需要自己写代码加载, 注意添加顺序
        files: [
            /***测试文件***/
            './tool/**.js',
            './resources/**.js',
            './resources/img/**.png',
            /***classic的源码***/
            /*由于除了classic其他都不依赖于8c,所以classic 的引入放在最后，以免被common覆盖*/
            {pattern: '../src/classic/libs/SuperMap_Basic-8.1.1-17216.js', include: false},
            {pattern: '../src/classic/libs/Lang/*.js', include: false},
            {pattern: '../src/classic/theme/default/*.css', include: false},
            /**测试文件**/
            './test-main-classic.js',

            /***common的源码***/
            '../src/common/**/*.js',
            /**测试文件**/

            './test-main-common.js',

            /***leaflet的源码***/
            {pattern: './libs/workers/TurfWorkerForTest.js', include: false},
            {pattern: '../node_modules/leaflet/dist/leaflet.css', include: false},
            {pattern: '../src/leaflet/**/**/*.css', include: false},
            '../src/leaflet/**/!(index).js',
            /**测试文件**/
            './test-main-leaflet.js',

            /***openlayers的源码***/
            {pattern: '../node_modules/openlayers/dist/ol-debug.css', include: false},
            {pattern: '../src/openlayers/**/**/*.css', include: false},
            '../src/openlayers/**/!(index).js',
            /**测试文件**/
            './test-main-openlayers.js',

            /***mapboxgl***/
            {pattern: '../node_modules/mapbox-gl/dist/mapbox-gl.css', include: false},
            '../src/mapboxgl/**/!(index).js',
            /**测试文件**/
            './test-main-mapboxgl.js'
        ],

        // list of files to exclude 测试时排除的文件
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            '../node_modules/whatwg-fetch-importable/whatwgFetch.js': ['browserify'],
            '../node_modules/fetch-jsonp/build/fetch-jsonp.js': ['browserify'],
            '../src/classic/libs/SuperMap_Basic-8.1.1-17216.js': ['browserify'],
            '../src/classic/libs/Lang/*.js': ['browserify'],
            '../src/classic/**/!(index).js': ['browserify'],
            './classic/**/*Spec.js': ['browserify'],
            './test-main-classic.js': ['browserify'],

            '../src/common/**/*.js': ['browserify'],
            './common/**/*Spec.js': ['browserify'],
            './test-main-common.js': ['browserify'],

            '../node_modules/leaflet/dist/leaflet-src.js': ['browserify'],
            '../src/leaflet/**/!(index).js': ['browserify'],
            './leaflet/**/*Spec.js': ['browserify'],
            './test-main-leaflet.js': ['browserify'],

            '../node_modules/openlayers/dist/ol-debug.js': ['browserify'],
            '../src/openlayers/**/!(index).js': ['browserify'],
            './openlayers/**/*Spec.js': ['browserify'],
            './test-main-openlayers.js': ['browserify'],

            '../node_modules/mapbox-gl/dist/mapbox-gl-dev.js': ['browserify'],
            '../src/mapboxgl/**/!(index).js': ['browserify'],
            './mapboxgl/**/*Spec.js': ['browserify'],
            './test-main-mapboxgl.js': ['browserify']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage', 'teamcity'],

        //最大超时时间
        captureTimeout: 120000,
        browserNoActivityTimeout: 120000,
        browserDisconnectTimeout: 20000,

        coverageReporter: {
            dir: 'testcoverage/',
            reporters: [
                {type: 'lcov', subdir: '.'}
            ]
        }
        ,

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity

    })
};
<|endoftext|>


<commit_before>const fse = require('fs-extra');
const os = require('os');
const inquirer = require('inquirer');
const crypto = require('crypto')
const zlib = require('zlib');
const fs = require('fs');
const shell = require('shelljs');
const figlet = require('figlet');
const path = require("path");
const replace = require("replace");
const Datauri = require('datauri').sync;
const absolutePath = path.resolve(".");
const algorithm = 'sha1';

function startBuild() {
    console.log(' Preparing for building Jste Framework ');
    shell.rm('-rf', 'tmp');
    shell.mkdir('tmp');
    shell.ln('-sf', absolutePath + '/src', 'tmp/src');
    shell.cd('build');
    shell.rm('-rf', '*');
    shell.mkdir('minified', 'compressed');
    fse.copySync(absolutePath + '/src/JS/Core/analyzeCommand-CompilationTemplate.js', absolutePath + '/tmp/analyzeCommand-Compiled.js');
    fse.copySync(absolutePath + '/src/JS/Core/wordsTranslationsInit-CompilationTemplate.js', absolutePath + '/tmp/wordsTranslationsInit-Compiled.js');
    fse.copySync(absolutePath + '/src/Res.html', absolutePath + '/tmp/Res.html');
    fse.copySync(absolutePath + '/src/Res-LiveVersion.html', absolutePath + '/tmp/Res-LiveVersion.html');
    var langCodes = ['en', 'fr', 'ar', 'arz'];
    for (var i = 0; i < langCodes.length; i++) {
        replace({
            regex: langCodes[i].toUpperCase() + "_RIVESCRIPT",
            replacement: Datauri(absolutePath + '/src/JS/Translations/RiveScript/' + langCodes[i] + '.rive'),
            paths: [absolutePath + '/tmp/analyzeCommand-Compiled.js'],
            recursive: true,
            silent: true,
        });
    }
    replace({
        regex: "DICTIONARY_URL",
        replacement: Datauri(absolutePath + '/src/JS/Translations/words.json'),
        paths: [absolutePath + '/tmp/wordsTranslationsInit-Compiled.js'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src="(?!http)',
        replacement: 'src="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'href="(?!http)',
        replacement: 'href="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/wordsTranslationsInit\.js',
        replacement: 'wordsTranslationsInit-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/analyzeCommand\.js',
        replacement: 'analyzeCommand-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    console.log(' ');
    console.log(' Starting building Jste Framework ');
    var frameworkMinifiedFileInfo = {};
    var frameworkCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework.min.html');
    frameworkMinifiedFileInfo.size = fs.statSync('minified/framework.min.html').size;
    frameworkCompressedFileInfo.size = frameworkMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework.min.html', 'utf8'));
    frameworkMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework.info.json', JSON.stringify(frameworkMinifiedFileInfo));
    shell.rm('-rf', 'framework.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework.min.html');
    var out = fs.createWriteStream('compressed/framework.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework.min.html.gz', 'utf8'));
    frameworkCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework.info.json', JSON.stringify(frameworkCompressedFileInfo));
    console.log(' Jste Framework has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building Jste Framework Live Version ');
    var frameworkLiveVersionMinifiedFileInfo = {};
    var frameworkLiveVersionCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res-LiveVersion.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework-LiveVersion.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework-LiveVersion.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework-LiveVersion.min.html');
    frameworkLiveVersionMinifiedFileInfo.size = fs.statSync('minified/framework-LiveVersion.min.html').size;
    frameworkLiveVersionCompressedFileInfo.size = frameworkLiveVersionMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework-LiveVersion.min.html', 'utf8'));
    frameworkLiveVersionMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionMinifiedFileInfo));
    shell.rm('-rf', 'framework-LiveVersion.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework-LiveVersion.min.html');
    var out = fs.createWriteStream('compressed/framework-LiveVersion.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework-LiveVersion.min.html.gz', 'utf8'));
    frameworkLiveVersionCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionCompressedFileInfo));
    console.log(' Jste Framework Live Version has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building the BLOB DB Manager for Jste Framework Live Version ');
    var dbManagerMinifiedFileInfo = {};
    var dbManagerCompressedFileInfo = {};
    console.log(' Minifying the BLOB DB Manager file ');
    shell.exec('html-minifier ../utils/db-manager.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/db-manager.min.html');
    dbManagerMinifiedFileInfo.size = fs.statSync('minified/db-manager.min.html').size;
    dbManagerCompressedFileInfo.size = dbManagerMinifiedFileInfo.size;
    console.log(' Hashing the BLOB DB Manager minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/db-manager.min.html', 'utf8'));
    dbManagerMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/db-manager.info.json', JSON.stringify(dbManagerMinifiedFileInfo));
    shell.rm('-rf', 'db-manager.html');
    console.log(' Compresssing the BLOB DB Manager minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/db-manager.min.html');
    var out = fs.createWriteStream('compressed/db-manager.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the BLOB DB Manager compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/db-manager.min.html.gz', 'utf8'));
    dbManagerCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/db-manager.info.json', JSON.stringify(dbManagerCompressedFileInfo));
    console.log(' The BLOB DB Manager for Jste Framework Live Version has been built properly ;) ');
    shell.cd('../');
    shell.rm('-rf', 'tmp');
    if (global.gitURLPrefix) {
        console.log(' ');
        console.log(' Updating the index ');
        shell.exec('git add .');
        console.log(' ');
        console.log(' Recording the change to the local repo ');
        shell.exec('git commit -m "' + global.commitMessage + '"');
        console.log(' ');
        console.log(' Pushing the updates to GitHub ');
        shell.exec('git push ' + gitURLPrefix + 'framework.git master');
    }
    if (shell.test('-d', '../manager')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager ');
        shell.cd('../manager');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('-Rf', '../framework/build/compressed/framework.min.html.gz', 'src/assets');
        console.log(' ');
        console.log(' Starting building Jste Manager ');
        shell.exec('node build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager.git master');
        }
    }
    if (shell.test('-d', '../manager-heroku')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager Heroku version ');
        shell.cd('../manager-heroku');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('-Rf', '../framework/build/compressed/framework-LiveVersion.min.html.gz', '../framework/build/compressed/db-manager.min.html.gz', 'assets');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-heroku.git master');
            console.log(' ');
            console.log(' Pushing the updates to Heroku ');
            shell.exec('git push heroku master');
        }
    }
    if (shell.test('-d', '../manager-phone')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager phone version ');
        shell.cd('../manager-phone/src');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('-Rf', '../../framework/build/minified/framework.min.html', 'www/jxcore/assets');
        console.log(' ');
        console.log(' Starting building Jste Manager phone version ');
        shell.exec('cordova build');
        shell.cd('../');
        shell.cp('-Rf', 'src/platforms/android/build/outputs/apk/debug/android-debug.apk', 'build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-phone.git master');
        }
    }
}

figlet('JSTE FRAMEWORK', function (err, data) {
    console.log(data);
    console.log('');
    console.log(' Welcome to Jste Framework builder :) ')
    inquirer
        .prompt([{
            type: 'confirm',
            name: 'deploy',
            message: 'Do you want to deploy this build ?'
        }])
        .then(options => {
            if (options.deploy == true) {
                inquirer
                    .prompt([{
                        type: 'input',
                        name: 'commit_message',
                        message: 'Please enter the commit message '
                    },{
                            type: 'input',
                            name: 'git_username',
                            message: 'Please enter your GitHub username '
                        },
                        {
                            type: 'password',
                            name: 'git_password',
                            mask: '*',
                            message: 'Please enter your GitHub password '
                        }
                    ]).then(git_info => {
                        global.gitURLPrefix = 'https://' + git_info.git_username + ':' + git_info.git_password + '@github.com/project-jste/';
                        global.commitMessage = git_info.commit_message;
                        startBuild();
                    })
            } else {
                startBuild();
            }
        });
});<commit_msg>Bug Fixes<commit_after>const fse = require('fs-extra');
const os = require('os');
const inquirer = require('inquirer');
const crypto = require('crypto')
const zlib = require('zlib');
const fs = require('fs');
const shell = require('shelljs');
const figlet = require('figlet');
const path = require("path");
const replace = require("replace");
const Datauri = require('datauri').sync;
const absolutePath = path.resolve(".");
const algorithm = 'sha1';

function startBuild() {
    console.log(' Preparing for building Jste Framework ');
    shell.rm('-rf', 'tmp');
    shell.mkdir('tmp');
    shell.ln('-sf', absolutePath + '/src', 'tmp/src');
    shell.cd('build');
    shell.rm('-rf', '*');
    shell.mkdir('minified', 'compressed');
    fse.copySync(absolutePath + '/src/JS/Core/analyzeCommand-CompilationTemplate.js', absolutePath + '/tmp/analyzeCommand-Compiled.js');
    fse.copySync(absolutePath + '/src/JS/Core/wordsTranslationsInit-CompilationTemplate.js', absolutePath + '/tmp/wordsTranslationsInit-Compiled.js');
    fse.copySync(absolutePath + '/src/Res.html', absolutePath + '/tmp/Res.html');
    fse.copySync(absolutePath + '/src/Res-LiveVersion.html', absolutePath + '/tmp/Res-LiveVersion.html');
    var langCodes = ['en', 'fr', 'ar', 'arz'];
    for (var i = 0; i < langCodes.length; i++) {
        replace({
            regex: langCodes[i].toUpperCase() + "_RIVESCRIPT",
            replacement: Datauri(absolutePath + '/src/JS/Translations/RiveScript/' + langCodes[i] + '.rive'),
            paths: [absolutePath + '/tmp/analyzeCommand-Compiled.js'],
            recursive: true,
            silent: true,
        });
    }
    replace({
        regex: "DICTIONARY_URL",
        replacement: Datauri(absolutePath + '/src/JS/Translations/words.json'),
        paths: [absolutePath + '/tmp/wordsTranslationsInit-Compiled.js'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src="(?!http)',
        replacement: 'src="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'href="(?!http)',
        replacement: 'href="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/wordsTranslationsInit\.js',
        replacement: 'wordsTranslationsInit-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/analyzeCommand\.js',
        replacement: 'analyzeCommand-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    console.log(' ');
    console.log(' Starting building Jste Framework ');
    var frameworkMinifiedFileInfo = {};
    var frameworkCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework.min.html');
    frameworkMinifiedFileInfo.size = fs.statSync('minified/framework.min.html').size;
    frameworkCompressedFileInfo.size = frameworkMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework.min.html', 'utf8'));
    frameworkMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework.info.json', JSON.stringify(frameworkMinifiedFileInfo));
    shell.rm('-rf', 'framework.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework.min.html');
    var out = fs.createWriteStream('compressed/framework.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework.min.html.gz', 'utf8'));
    frameworkCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework.info.json', JSON.stringify(frameworkCompressedFileInfo));
    console.log(' Jste Framework has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building Jste Framework Live Version ');
    var frameworkLiveVersionMinifiedFileInfo = {};
    var frameworkLiveVersionCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res-LiveVersion.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework-LiveVersion.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework-LiveVersion.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework-LiveVersion.min.html');
    frameworkLiveVersionMinifiedFileInfo.size = fs.statSync('minified/framework-LiveVersion.min.html').size;
    frameworkLiveVersionCompressedFileInfo.size = frameworkLiveVersionMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework-LiveVersion.min.html', 'utf8'));
    frameworkLiveVersionMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionMinifiedFileInfo));
    shell.rm('-rf', 'framework-LiveVersion.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework-LiveVersion.min.html');
    var out = fs.createWriteStream('compressed/framework-LiveVersion.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework-LiveVersion.min.html.gz', 'utf8'));
    frameworkLiveVersionCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionCompressedFileInfo));
    console.log(' Jste Framework Live Version has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building the BLOB DB Manager for Jste Framework Live Version ');
    var dbManagerMinifiedFileInfo = {};
    var dbManagerCompressedFileInfo = {};
    console.log(' Minifying the BLOB DB Manager file ');
    shell.exec('html-minifier ../utils/db-manager.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/db-manager.min.html');
    dbManagerMinifiedFileInfo.size = fs.statSync('minified/db-manager.min.html').size;
    dbManagerCompressedFileInfo.size = dbManagerMinifiedFileInfo.size;
    console.log(' Hashing the BLOB DB Manager minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/db-manager.min.html', 'utf8'));
    dbManagerMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/db-manager.info.json', JSON.stringify(dbManagerMinifiedFileInfo));
    shell.rm('-rf', 'db-manager.html');
    console.log(' Compresssing the BLOB DB Manager minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/db-manager.min.html');
    var out = fs.createWriteStream('compressed/db-manager.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the BLOB DB Manager compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/db-manager.min.html.gz', 'utf8'));
    dbManagerCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/db-manager.info.json', JSON.stringify(dbManagerCompressedFileInfo));
    console.log(' The BLOB DB Manager for Jste Framework Live Version has been built properly ;) ');
    shell.cd('../');
    shell.rm('-rf', 'tmp');
    if (global.gitURLPrefix) {
        console.log(' ');
        console.log(' Updating the index ');
        shell.exec('git add .');
        console.log(' ');
        console.log(' Recording the change to the local repo ');
        shell.exec('git commit -m "' + global.commitMessage + '"');
        console.log(' ');
        console.log(' Pushing the updates to GitHub ');
        shell.exec('git push ' + gitURLPrefix + 'framework.git master');
    }
    if (shell.test('-d', '../manager')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager ');
        shell.cd('../manager');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('../framework/build/compressed/framework.min.html.gz', 'src/assets');
        console.log(' ');
        console.log(' Starting building Jste Manager ');
        shell.exec('node build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager.git master');
        }
    }
    if (shell.test('-d', '../manager-heroku')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager Heroku version ');
        shell.cd('../manager-heroku');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp(['../framework/build/compressed/framework-LiveVersion.min.html.gz', '../framework/build/compressed/db-manager.min.html.gz'], 'assets');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-heroku.git master');
            console.log(' ');
            console.log(' Pushing the updates to Heroku ');
            shell.exec('git push heroku master');
        }
    }
    if (shell.test('-d', '../manager-phone')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager phone version ');
        shell.cd('../manager-phone/src');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('../../framework/build/minified/framework.min.html', 'www/jxcore/assets');
        console.log(' ');
        console.log(' Starting building Jste Manager phone version ');
        shell.exec('cordova build');
        shell.cd('../');
        shell.cp('src/platforms/android/build/outputs/apk/debug/android-debug.apk', 'build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-phone.git master');
        }
    }
}

figlet('JSTE FRAMEWORK', function (err, data) {
    console.log(data);
    console.log('');
    console.log(' Welcome to Jste Framework builder :) ')
    inquirer
        .prompt([{
            type: 'confirm',
            name: 'deploy',
            message: 'Do you want to deploy this build ?'
        }])
        .then(options => {
            if (options.deploy == true) {
                inquirer
                    .prompt([{
                        type: 'input',
                        name: 'commit_message',
                        message: 'Please enter the commit message '
                    },{
                            type: 'input',
                            name: 'git_username',
                            message: 'Please enter your GitHub username '
                        },
                        {
                            type: 'password',
                            name: 'git_password',
                            mask: '*',
                            message: 'Please enter your GitHub password '
                        }
                    ]).then(git_info => {
                        global.gitURLPrefix = 'https://' + git_info.git_username + ':' + git_info.git_password + '@github.com/project-jste/';
                        global.commitMessage = git_info.commit_message;
                        startBuild();
                    })
            } else {
                startBuild();
            }
        });
});<|endoftext|>


<commit_before>var defaultChallenge = {
    //    "userId": 8547899,
    "projectId": -1,
    "tcDirectProjectId": -1,
    "competitionType": "SOFTWARE", //SOFTWARE, STUDIO, ALGORITHM
    "assetDTO": {
        "name": "",
        "productionDate": "" //2016-03-05T09:00:00-04
    },
    "projectHeader": {
        "id": -1,
        "tcDirectProjectId": -1,
        "projectSpec": {
            "projectSpecId": 0,
            "detailedRequirements": "These are the requirements.",
            "finalSubmissionGuidelines": "- Ensure good test coverage on all modules\n- Upload documentation for how to run your submission\n- Upload all your source code as a zip for review\n- Winner will be required to submit a pull request with their winning code. "
        },
        /*
        "projectMMSpecification": {
            "problemId": -1
        },
        */
        "prizes": [{
                "place": 1,
                "prizeAmount": 300,
                "prizeType": {
                    "id": 15,
                    "description": "Contest Prize"
                },
                "numberOfSubmissions": 1
            }
            /*, {
                        "place": 2,
                        "prizeAmount": 150,
                        "prizeType": {
                            "id": 15,
                            "description": "Contest Prize"
                        },
                        "numberOfSubmissions": 1
                    } */
        ],
        "properties": {
            "Billing Project": "0",
            "Confidentiality Type": "public",
            //            "Project Name": "",
            //            "First Place Cost": "450",
            //            "Payments": "300",
            //            "Second Place Cost": "150",
            //            "Review Cost": "1032",
            //            "Reliability Bonus Cost": "420",
            //            "DR points": "630",
            "Digital Run Flag": "Off",
            //            "Checkpoint Bonus Cost": "0",
            //            "Admin Fee": "0",
            //            "Spec Review Cost": "50",
            //            "Cost Level": "B",
            //            "Copilot Cost": "600",
            "Review Type": "COMMUNITY"
        },
        "projectCategory": {
            "id": 39, //CWD-- 38
            "name": "CODE", //CWD-- First2Finish
            "projectType": {
                "id": 2,
                "name": "Application"
            }
        },
        "tcDirectProjectName": "",
        //        "securityGroupId": 0
    },
    //    "directProjectMilestoneId": -1,
    "endDate": "", //2016-04-20T09:00:00-04
    //    "contestCopilotId": -1,
    "contestCopilotName": "",
    "technologies": [
        //        "2"
    ],
    "platforms": [
        //        "4"
    ],
    "hasMulti": false
};

module.exports = function() {
    return defaultChallenge;
};
<commit_msg>defaulting review costs<commit_after>var defaultChallenge = {
    //    "userId": 8547899,
    "projectId": -1,
    "tcDirectProjectId": -1,
    "competitionType": "SOFTWARE", //SOFTWARE, STUDIO, ALGORITHM
    "assetDTO": {
        "name": "",
        "productionDate": "" //2016-03-05T09:00:00-04
    },
    "projectHeader": {
        "id": -1,
        "tcDirectProjectId": -1,
        "projectSpec": {
            "projectSpecId": 0,
            "detailedRequirements": "These are the requirements.",
            "finalSubmissionGuidelines": "- Ensure good test coverage on all modules\n- Upload documentation for how to run your submission\n- Upload all your source code as a zip for review\n- Winner will be required to submit a pull request with their winning code. "
        },
        /*
        "projectMMSpecification": {
            "problemId": -1
        },
        */
        "prizes": [{
                "place": 1,
                "prizeAmount": 300,
                "prizeType": {
                    "id": 15,
                    "description": "Contest Prize"
                },
                "numberOfSubmissions": 1
            }
            /*, {
                        "place": 2,
                        "prizeAmount": 150,
                        "prizeType": {
                            "id": 15,
                            "description": "Contest Prize"
                        },
                        "numberOfSubmissions": 1
                    } */
        ],
        "properties": {
            "Billing Project": "0",
            "Confidentiality Type": "public",
            //            "Project Name": "",
            //            "First Place Cost": "450",
            //            "Payments": "300",
            //            "Second Place Cost": "150",
            "Review Cost": "0",
            //            "Reliability Bonus Cost": "420",
            //            "DR points": "630",
            "Digital Run Flag": "Off",
            //            "Checkpoint Bonus Cost": "0",
            //            "Admin Fee": "0",
            "Spec Review Cost": "0",
            //            "Cost Level": "B",
            //            "Copilot Cost": "600",
            "Review Type": "COMMUNITY"
        },
        "projectCategory": {
            "id": 39, //CWD-- 38
            "name": "CODE", //CWD-- First2Finish
            "projectType": {
                "id": 2,
                "name": "Application"
            }
        },
        "tcDirectProjectName": "",
        //        "securityGroupId": 0
    },
    //    "directProjectMilestoneId": -1,
    "endDate": "", //2016-04-20T09:00:00-04
    //    "contestCopilotId": -1,
    "contestCopilotName": "",
    "technologies": [
        //        "2"
    ],
    "platforms": [
        //        "4"
    ],
    "hasMulti": false
};

module.exports = function() {
    return defaultChallenge;
};
<|endoftext|>


<commit_before>'use strict';

var isCopy   = require('es5-ext/lib/Object/is-copy')
  , resolve  = require('path').resolve
  , readFile = require('fs').readFile
  , inspect  = require('util').inspect

  , testFile = resolve(__dirname, 'parse.txt');

module.exports = function (t, a, d) {
	readFile(testFile, function (err, data) {
		var result, mod1, mod2, copy;
		if (err) {
			d(err);
			return;
		}
		result = t(data, '/one/two');
		mod1 = [{ action: 'add', value: ['bar', 'foo'] }];
		mod2 = [{ action: 'remove', value: ['mala', 'morda'] }];
		mod1.mod = mod2.mod = true;

		copy = {
			root: true,
			"/one/two": {
				adsafe: false,
				bitwise: true,
				devel: true,
				debug: false,
				predef: ['two'],
				eqeq: true
			},
			"/one/two/foo/bar": {
				browser: false,
				cap: true,
				predef: mod1
			},
			"/one/two/marko-zagalo.js": {
				predef: mod2
			}
		};

		a(isCopy(result, copy, Infinity), true);
		d();
	});
};
<commit_msg>Windows support<commit_after>'use strict';

var isCopy   = require('es5-ext/lib/Object/is-copy')
  , path     = require('path')
  , readFile = require('fs').readFile
  , inspect  = require('util').inspect

  , join = path.join, resolve = path.resolve

  , testFile = resolve(__dirname, 'parse.txt');

module.exports = function (t, a, d) {
	readFile(testFile, function (err, data) {
		var result, mod1, mod2, copy;
		if (err) {
			d(err);
			return;
		}
		result = t(data, join('/one/two'));
		mod1 = [{ action: 'add', value: ['bar', 'foo'] }];
		mod2 = [{ action: 'remove', value: ['mala', 'morda'] }];
		mod1.mod = mod2.mod = true;

		copy = { root: true };
		copy[join('/one/two')] = {
			adsafe: false,
			bitwise: true,
			devel: true,
			debug: false,
			predef: ['two'],
			eqeq: true
		};
		copy[join('/one/two/foo/bar')] = {
			browser: false,
			cap: true,
			predef: mod1
		};
		copy[join('/one/two/marko-zagalo.js')] = {
			predef: mod2
		};

		// console.log("DATA", inspect(result, false, Infinity));
		// console.log("COPY", inspect(copy, false, Infinity));
		a(isCopy(result, copy, Infinity), true);
		d();
	});
};
<|endoftext|>


<commit_before>import * as utils from 'base/utils';
import Component from 'base/component';
import Dialog from '../_dialog';

import { simpleslider } from 'components/_index'

/*!
 * VIZABI FIND CONTROL
 * Reusable find dialog
 */

var Find = Dialog.extend({

  init: function(config, parent) {
    this.name = 'find';
    var _this = this;

    this.components = [{
      component: simpleslider,
      placeholder: '.vzb-dialog-bubbleopacity',
      model: ["state.entities"],
      arg: "opacitySelectDim"
    }];

    this.model_binds = {
      "change:state.entities.select": function(evt) {
        _this.ready();
      },
      "change:state.time.value": function(evt) {
        if(!_this.model.state.time.playing && !_this.model.state.time.dragging) {
          _this.ready();
        }
      },
      "change:language.strings": function() {
        _this.translator = _this.model.language.getTFunction();
        _this.input_search.attr("placeholder", _this.translator("placeholder/search") + "...");
      }
    }

    this._super(config, parent);
  },

  /**
   * Grab the list div
   */
  readyOnce: function() {
    this._super();

    this.list = this.element.select(".vzb-find-list");
    this.input_search = this.element.select("#vzb-find-search");
    this.deselect_all = this.element.select("#vzb-find-deselect");
    this.opacity_nonselected = this.element.select(".vzb-dialog-bubbleopacity");

    this.KEY = this.model.state.entities.getDimension();

    var _this = this;
    this.input_search.on("input", function() {
      _this.showHideSearch();
    });

    this.deselect_all.on("click", function() {
      _this.deselectEntities();
    });

    this.translator = this.model.language.getTFunction();
    this.input_search.attr("placeholder", this.translator("placeholder/search") + "...");

    //make sure it refreshes when all is reloaded
    var _this = this;
    this.root.on('ready', function() {
      _this.ready();
    })

  },

  open: function() {
    this._super();

    this.input_search.node().value = "";
    this.showHideSearch();
  },

  /**
   * Build the list everytime it updates
   */
  //TODO: split update in render and update methods
  ready: function() {
    this._super();

    var _this = this;
    var KEY = this.KEY;
    var TIMEDIM = this.model.state.time.getDimension();
    var selected = this.model.state.entities.getSelected();
    var marker = this.model.state.marker;
    var time = this.model.state.time.value;

    var values = marker.getFrame(time);

    var data = marker.getKeys().map(function(d) {
      var pointer = {};
      pointer[KEY] = d[KEY];
      pointer.name = values.label[d[KEY]];
      return pointer;
    }).filter(function(d) {
      var include = true;
      utils.forEach(values, function(hook) {
        if(!hook[d[KEY]]) {
          include = false;
          return false;
        }
      });
      return include;
    })

    //sort data alphabetically
    data.sort(function(a, b) {
      return(a.name < b.name) ? -1 : 1;
    });

    this.list.html("");

    var items = this.list.selectAll(".vzb-find-item")
      .data(data)
      .enter()
      .append("div")
      .attr("class", "vzb-find-item vzb-dialog-checkbox")

    items.append("input")
      .attr("type", "checkbox")
      .attr("class", "vzb-find-item")
      .attr("id", function(d) {
        return "-find-" + d[KEY];
      })
      .property("checked", function(d) {
        return(selected.indexOf(d[KEY]) !== -1);
      })
      .on("change", function(d) {
        var isSelected = _this.model.state.entities.isSelected(d);
        _this.model.state.entities.clearHighlighted();
        _this.model.state.entities.selectEntity(d);
        if(isSelected) _this.model.state.entities.highlightEntity(d);
      });

    items.append("label")
      .attr("for", function(d) {
        return "-find-" + d[KEY];
      })
      .text(function(d) {
        return d.name;
      })
      .on("mouseover", function(d) {
        if(!utils.isTouchDevice()) _this.model.state.entities.highlightEntity(d);
      })
      .on("mouseout", function(d) {
        if(!utils.isTouchDevice()) _this.model.state.entities.clearHighlighted();
      });
    utils.preventAncestorScrolling(_this.element.select('.vzb-dialog-scrollable'));

    this.showHideSearch();
    this.showHideDeselect();
  },
  resize: function() {
    if (this.getLayoutProfile() == 'small') {
      var height = this.root.element.offsetHeight;
      var titleHeight = this.element.select(".vzb-dialog-title").node().offsetHeight;
      var buttonsHeight = this.element.select(".vzb-dialog-buttons").node().offsetHeight;
      this.element.select(".vzb-dialog-content-fixed").style('max-height', height - 90 - titleHeight - buttonsHeight + 'px');
    } else {
      this.element.select(".vzb-dialog-content-fixed").style('max-height', '');
    }
    this._super();
  },
  showHideSearch: function() {
    var search = this.input_search.node().value || "";
    search = search.toLowerCase();

    this.list.selectAll(".vzb-find-item")
      .classed("vzb-hidden", function(d) {
        var lower = d.name.toLowerCase();
        return(lower.indexOf(search) === -1);
      });
  },

  showHideDeselect: function() {
    var someSelected = !!this.model.state.entities.select.length;
    this.deselect_all.classed('vzb-hidden', !someSelected);
    this.opacity_nonselected.classed('vzb-hidden', !someSelected);
  },

  deselectEntities: function() {
    this.model.state.entities.clearSelected();
  },

  transitionEnd: function(event) {
    this._super(event);

    if(!utils.isTouchDevice()) this.input_search.node().focus();
  }

});

export default Find;
<commit_msg>Disable re-highlihgt after click on touch devices. Fixes #1276<commit_after>import * as utils from 'base/utils';
import Component from 'base/component';
import Dialog from '../_dialog';

import { simpleslider } from 'components/_index'

/*!
 * VIZABI FIND CONTROL
 * Reusable find dialog
 */

var Find = Dialog.extend({

  init: function(config, parent) {
    this.name = 'find';
    var _this = this;

    this.components = [{
      component: simpleslider,
      placeholder: '.vzb-dialog-bubbleopacity',
      model: ["state.entities"],
      arg: "opacitySelectDim"
    }];

    this.model_binds = {
      "change:state.entities.select": function(evt) {
        _this.ready();
      },
      "change:state.time.value": function(evt) {
        if(!_this.model.state.time.playing && !_this.model.state.time.dragging) {
          _this.ready();
        }
      },
      "change:language.strings": function() {
        _this.translator = _this.model.language.getTFunction();
        _this.input_search.attr("placeholder", _this.translator("placeholder/search") + "...");
      }
    }

    this._super(config, parent);
  },

  /**
   * Grab the list div
   */
  readyOnce: function() {
    this._super();

    this.list = this.element.select(".vzb-find-list");
    this.input_search = this.element.select("#vzb-find-search");
    this.deselect_all = this.element.select("#vzb-find-deselect");
    this.opacity_nonselected = this.element.select(".vzb-dialog-bubbleopacity");

    this.KEY = this.model.state.entities.getDimension();

    var _this = this;
    this.input_search.on("input", function() {
      _this.showHideSearch();
    });

    this.deselect_all.on("click", function() {
      _this.deselectEntities();
    });

    this.translator = this.model.language.getTFunction();
    this.input_search.attr("placeholder", this.translator("placeholder/search") + "...");

    //make sure it refreshes when all is reloaded
    var _this = this;
    this.root.on('ready', function() {
      _this.ready();
    })

  },

  open: function() {
    this._super();

    this.input_search.node().value = "";
    this.showHideSearch();
  },

  /**
   * Build the list everytime it updates
   */
  //TODO: split update in render and update methods
  ready: function() {
    this._super();

    var _this = this;
    var KEY = this.KEY;
    var TIMEDIM = this.model.state.time.getDimension();
    var selected = this.model.state.entities.getSelected();
    var marker = this.model.state.marker;
    var time = this.model.state.time.value;

    var values = marker.getFrame(time);

    var data = marker.getKeys().map(function(d) {
      var pointer = {};
      pointer[KEY] = d[KEY];
      pointer.name = values.label[d[KEY]];
      return pointer;
    }).filter(function(d) {
      var include = true;
      utils.forEach(values, function(hook) {
        if(!hook[d[KEY]]) {
          include = false;
          return false;
        }
      });
      return include;
    })

    //sort data alphabetically
    data.sort(function(a, b) {
      return(a.name < b.name) ? -1 : 1;
    });

    this.list.html("");

    var items = this.list.selectAll(".vzb-find-item")
      .data(data)
      .enter()
      .append("div")
      .attr("class", "vzb-find-item vzb-dialog-checkbox")

    items.append("input")
      .attr("type", "checkbox")
      .attr("class", "vzb-find-item")
      .attr("id", function(d) {
        return "-find-" + d[KEY];
      })
      .property("checked", function(d) {
        return(selected.indexOf(d[KEY]) !== -1);
      })
      .on("change", function(d) {
        //clear highlight so it doesn't get in the way when selecting an entity
        if(!utils.isTouchDevice()) _this.model.state.entities.clearHighlighted();
        _this.model.state.entities.selectEntity(d);
        //return to highlighted state
        if(!utils.isTouchDevice()) _this.model.state.entities.highlightEntity(d);
      });

    items.append("label")
      .attr("for", function(d) {
        return "-find-" + d[KEY];
      })
      .text(function(d) {
        return d.name;
      })
      .on("mouseover", function(d) {
        if(!utils.isTouchDevice()) _this.model.state.entities.highlightEntity(d);
      })
      .on("mouseout", function(d) {
        if(!utils.isTouchDevice()) _this.model.state.entities.clearHighlighted();
      });
    utils.preventAncestorScrolling(_this.element.select('.vzb-dialog-scrollable'));

    this.showHideSearch();
    this.showHideDeselect();
  },
  resize: function() {
    if (this.getLayoutProfile() == 'small') {
      var height = this.root.element.offsetHeight;
      var titleHeight = this.element.select(".vzb-dialog-title").node().offsetHeight;
      var buttonsHeight = this.element.select(".vzb-dialog-buttons").node().offsetHeight;
      this.element.select(".vzb-dialog-content-fixed").style('max-height', height - 90 - titleHeight - buttonsHeight + 'px');
    } else {
      this.element.select(".vzb-dialog-content-fixed").style('max-height', '');
    }
    this._super();
  },
  showHideSearch: function() {
    var search = this.input_search.node().value || "";
    search = search.toLowerCase();

    this.list.selectAll(".vzb-find-item")
      .classed("vzb-hidden", function(d) {
        var lower = d.name.toLowerCase();
        return(lower.indexOf(search) === -1);
      });
  },

  showHideDeselect: function() {
    var someSelected = !!this.model.state.entities.select.length;
    this.deselect_all.classed('vzb-hidden', !someSelected);
    this.opacity_nonselected.classed('vzb-hidden', !someSelected);
  },

  deselectEntities: function() {
    this.model.state.entities.clearSelected();
  },

  transitionEnd: function(event) {
    this._super(event);

    if(!utils.isTouchDevice()) this.input_search.node().focus();
  }

});

export default Find;
<|endoftext|>