<commit_before>function OverviewsMetadataApi(pgQueryRunner) {
   this.pgQueryRunner = pgQueryRunner;
}

module.exports = OverviewsMetadataApi;

// TODO: share this with QueryTablesApi? ... or maintain independence?
var affectedTableRegexCache = {
    bbox: /!bbox!/g,
    scale_denominator: /!scale_denominator!/g,
    pixel_width: /!pixel_width!/g,
    pixel_height: /!pixel_height!/g
};

function prepareSql(sql) {
    return sql
        .replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)')
        .replace(affectedTableRegexCache.scale_denominator, '0')
        .replace(affectedTableRegexCache.pixel_width, '1')
        .replace(affectedTableRegexCache.pixel_height, '1')
    ;
}

OverviewsMetadataApi.prototype.getOverviewsMetadata = function (username, sql, callback) {
    // FIXME: Currently using internal function parsed_table
    //        CDB_Overviews should provide the schema information directly.
    var query = 'SELECT *, _cdb_schema_name(base_table)' +
                '  FROM CDB_Overviews(CDB_QueryTablesText($windshaft$' + prepareSql(sql) + '$windshaft$))';
    this.pgQueryRunner.run(username, query, function handleOverviewsRows(err, rows) {
        if (err){
            callback(err);
            return;
        }
        var metadata = {};
        rows.forEach(function(row) {
            var table = row.base_table;
            var schema = row._cdb_schema_name;
            var table_metadata = metadata[table];
            if ( !table_metadata ) {
              table_metadata = metadata[table] = {};
            }
            table_metadata[row.z] = { table: row.overview_table };
            table_metadata.schema = schema;
        });
        return callback(null, metadata);
    });

};
<commit_msg>Fix comment<commit_after>function OverviewsMetadataApi(pgQueryRunner) {
   this.pgQueryRunner = pgQueryRunner;
}

module.exports = OverviewsMetadataApi;

// TODO: share this with QueryTablesApi? ... or maintain independence?
var affectedTableRegexCache = {
    bbox: /!bbox!/g,
    scale_denominator: /!scale_denominator!/g,
    pixel_width: /!pixel_width!/g,
    pixel_height: /!pixel_height!/g
};

function prepareSql(sql) {
    return sql
        .replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)')
        .replace(affectedTableRegexCache.scale_denominator, '0')
        .replace(affectedTableRegexCache.pixel_width, '1')
        .replace(affectedTableRegexCache.pixel_height, '1')
    ;
}

OverviewsMetadataApi.prototype.getOverviewsMetadata = function (username, sql, callback) {
    // FIXME: Currently using internal function _cdb_schema_name
    //        CDB_Overviews should provide the schema information directly.
    var query = 'SELECT *, _cdb_schema_name(base_table)' +
                '  FROM CDB_Overviews(CDB_QueryTablesText($windshaft$' + prepareSql(sql) + '$windshaft$))';
    this.pgQueryRunner.run(username, query, function handleOverviewsRows(err, rows) {
        if (err){
            callback(err);
            return;
        }
        var metadata = {};
        rows.forEach(function(row) {
            var table = row.base_table;
            var schema = row._cdb_schema_name;
            var table_metadata = metadata[table];
            if ( !table_metadata ) {
              table_metadata = metadata[table] = {};
            }
            table_metadata[row.z] = { table: row.overview_table };
            table_metadata.schema = schema;
        });
        return callback(null, metadata);
    });

};
<|endoftext|>


<commit_before>/*
View block that includes audio recording button and progression bar.
*/

import React, {PropTypes} from 'react';
import {getSizeByHeight, getImage} from '../services/graphics';
import {
  View,
  Image,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
import ProgressBarClassic from 'react-native-progress-bar-classic';

import {
  Recorder,
  Player
} from 'react-native-audio-toolkit';

let filename = 'test.mp4';
var TimerMixin = require('react-timer-mixin');

const AudioRecorder = React.createClass({
  propTypes: {
    save: PropTypes.func.isRequired,
    phase: PropTypes.string,
    toggleWritingButton: PropTypes.func
  },

  mixins: [TimerMixin],

  getInitialState() {
    return {
      recordButton: 'Preparing...',
      recordButtonDisabled: true,
      progress: 0,
      filePath: null,
      recording: false,
      error: null
    };
  },

  componentWillMount() {
    this.recorder = null;
    this.lastSeek = 0;

    this._reloadRecorder();

    this._progressInterval = setInterval(() => {
      if (this.recorder && this.recorder.isRecording) {
        if (this.state.progress >= 100) {
          this._toggleRecord();
        }
        else {
          this.setState({progress: this.state.progress + 1});
        }
      }
    }, 1200);
  },

  componentWillUnmount() {
    this.recorder.destroy();
    if (this.player) {
      this.player.destroy();
    }
    clearInterval(this._progressInterval);
  },

  _updateState() {
    this.setState({
      recordButton: this.recorder && this.recorder.isRecording ? 'Stop' : 'Record',
      recording: this.recorder && this.recorder.isRecording ? true : false,
      recordButtonDisabled: !this.recorder
    });

    this.props.toggleWritingButton(this.state.recording);
  },

  _reloadRecorder() {
    if (this.recorder) {
      this.recorder.destroy();
    }

    this.recorder = new Recorder(filename, {
      bitrate: 256000,
      channels: 2,
      sampleRate: 44100,
      quality: 'max'
      //format: 'ac3', // autodetected
      //encoder: 'aac', // autodetected
    }).prepare((err, filePath) => {
      if (err) {
        console.error(err);
      }

      this.setState({filePath});
    });

    this._updateState();
  },

  _reloadPlayer() {
    if (this.player) {
      this.player.destroy();
    }
    if (this.recorder) {
      this.recorder.destroy();
    }

    this.player = new Player(filename, {
      autoDestroy: false
    }).prepare((err) => {
      if (err) {
        console.log(err);
      } else {
        this.player.looping = this.state.loopButtonStatus;
      }

      this._updateState();
    });

    this.player.play();
  },

  _toggleRecord() {

    this.recorder.toggleRecord((err, stopped) => {
      if (err) {
        this.setState({
          error: err.message
        });
        this._updateState();
      }
      if (stopped) {
        this._updateState();
        this.setState({progress: 0});
        this.recorder.destroy();
        this.props.save(this.props.phase, 'audio', this.state.filePath);
      }
      else {
        this._updateState();
      }
    });
  },

  renderRecordButton() {
    if (this.state.recordButton === 'Record') {
      return (
        <TouchableOpacity
          onPress={() => this._toggleRecord()}
          style={[styles.highlightCircle, getSizeByHeight('nappula_rec', 0.35)]}>
          <Image source={getImage('nappula_rec')} style={getSizeByHeight('nappula_rec', 0.35)}/>
        </TouchableOpacity>);
    }
    else if (this.state.recordButton === 'Stop') {
      return (
        <TouchableOpacity
          onPress={() => this._toggleRecord()}
          style={[styles.highlightSquare, getSizeByHeight('nappula_stop', 0.35)]}>
          <Image source={getImage('nappula_stop')} style={getSizeByHeight('nappula_stop', 0.35)}/>
        </TouchableOpacity>);
    }
    else {
      return null;
    }
  },

  render() {
    var button = this.renderRecordButton();

    return (
      <View style={styles.recordRow}>
        {button}
        <View style={{flex: 1, marginLeft: 20}}>
          <ProgressBarClassic style={styles.progressBar} valueStyle={'none'} progress={this.state.progress} />
        </View>
      </View>
    );
  }
});

const styles = StyleSheet.create({
  recordRow: {
    flex: 2,
    marginLeft: 10,
    padding: 20,
    flexDirection: 'row',
    alignItems: 'center'
  },
  highlightCircle: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  highlightSquare: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  progressBar: {
    borderColor: 'black'
  }
});

export default AudioRecorder;
<commit_msg>Refactor AudioRecorder<commit_after>/*
View block that includes audio recording button and progression bar.
*/

import React, {PropTypes, Component} from 'react';
import {getSizeByHeight, getImage} from '../services/graphics';
import {
  View,
  Image,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
import ProgressBarClassic from 'react-native-progress-bar-classic';
import TimerMixin from 'react-timer-mixin';
import {
  Recorder,
  Player
} from 'react-native-audio-toolkit';

const styles = StyleSheet.create({
  recordRow: {
    flex: 2,
    marginLeft: 10,
    padding: 20,
    flexDirection: 'row',
    alignItems: 'center'
  },
  highlightCircle: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  highlightSquare: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  progressBar: {
    borderColor: 'black'
  }
});

let reactMixin = require('react-mixin');
let filename = 'test.mp4';

@reactMixin.decorate(TimerMixin)
export default class AudioRecorder extends Component {

  static propTypes = {
    save: PropTypes.func.isRequired,
    phase: PropTypes.string,
    toggleWritingButton: PropTypes.func
  };

  state = {
    recordButton: 'Preparing...',
    recordButtonDisabled: true,
    progress: 0,
    filePath: null,
    recording: false,
    error: null
  };

  componentWillMount() {
    this.recorder = null;
    this.lastSeek = 0;

    this._reloadRecorder();

    this._progressInterval = setInterval(() => {
      if (this.recorder && this.recorder.isRecording) {
        if (this.state.progress >= 100) {
          this._toggleRecord();
        }
        else {
          this.setState({progress: this.state.progress + 1});
        }
      }
    }, 1200);
  }

  componentWillUnmount() {
    this.recorder.destroy();

    if (this.player) {
      this.player.destroy();
    }

    clearInterval(this._progressInterval);
  }

  _updateState = () => {
    this.setState({
      recordButton: this.recorder && this.recorder.isRecording ? 'Stop' : 'Record',
      recording: this.recorder && this.recorder.isRecording ? true : false,
      recordButtonDisabled: !this.recorder
    });

    this.props.toggleWritingButton(this.state.recording);
  };

  _reloadRecorder = () => {
    if (this.recorder) {
      this.recorder.destroy();
    }

    this.recorder = new Recorder(filename, {
      bitrate: 256000,
      channels: 2,
      sampleRate: 44100,
      quality: 'max'
      //format: 'ac3', // autodetected
      //encoder: 'aac', // autodetected
    }).prepare((err, filePath) => {
      if (err) {
        console.error(err);
      }

      this.setState({filePath});
    });

    this._updateState();
  };

  _reloadPlayer = () => {
    if (this.player) {
      this.player.destroy();
    }
    if (this.recorder) {
      this.recorder.destroy();
    }

    this.player = new Player(filename, {
      autoDestroy: false
    }).prepare((err) => {
      if (err) {
        console.log(err);
      } else {
        this.player.looping = this.state.loopButtonStatus;
      }

      this._updateState();
    });

    this.player.play();
  };

  _toggleRecord = () => {
    this.recorder.toggleRecord((err, stopped) => {
      if (err) {
        this.setState({
          error: err.message
        });
        this._updateState();
      }
      if (stopped) {
        this._updateState();
        this.setState({progress: 0});
        this.recorder.destroy();
        this.props.save(this.props.phase, 'audio', this.state.filePath);
      }
      else {
        this._updateState();
      }
    });
  };

  renderStartRecordButton = () => {
    return (
      <TouchableOpacity
        onPress={() => this._toggleRecord()}
        style={[styles.highlightCircle, getSizeByHeight('nappula_rec', 0.35)]}>
        <Image source={getImage('nappula_rec')} style={getSizeByHeight('nappula_rec', 0.35)}/>
      </TouchableOpacity>
    );
  };

  renderStopRecordButton = () => {
    return (
      <TouchableOpacity
        onPress={() => this._toggleRecord()}
        style={[styles.highlightSquare, getSizeByHeight('nappula_stop', 0.35)]}>
        <Image source={getImage('nappula_stop')} style={getSizeByHeight('nappula_stop', 0.35)}/>
      </TouchableOpacity>
    );
  };

  renderRecordButton = () => {
    if (this.state.recordButton === 'Record') {
      return this.renderStartRecordButton();
    }
    else if (this.state.recordButton === 'Stop') {
      return this.renderStopRecordButton();
    }
    else {
      return null;
    }
  };

  render() {
    return (
      <View style={styles.recordRow}>
        {this.renderRecordButton()}
        <View style={{flex: 1, marginLeft: 20}}>
          <ProgressBarClassic style={styles.progressBar} valueStyle={'none'} progress={this.state.progress} />
        </View>
      </View>
    );
  }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { SimpleSelect } from 'react-selectize';
import { browserHistory, Link } from 'react-router';
import Alert from 'react-s-alert';

class Searcher extends Component {
  constructor() {
    super();

    this.state = {
      bookName: '',
      chapter: '',
      subchapter: '',
      exercise: '',
      exercises: [],
      chapters: [],
      subchapters: []
    };

    this.onChangeBook = this.onChangeBook.bind(this);
    this.onSelectedBook = this.onSelectedBook.bind(this);
    this.onSelectedChapter = this.onSelectedChapter.bind(this);
    this.onSelectedSubchapter = this.onSelectedSubchapter.bind(this);
    this.onSelectedExercise = this.onSelectedExercise.bind(this);
    this.onSubmitSearchForm = this.onSubmitSearchForm.bind(this);
    this.setImage = this.setImage.bind(this);
  }

  componentDidMount() {
    const bookNameRoute = this.props.bookNameUrl;
    let existingBook = false;
    let bookName = '';
    const { solutionManuals } = this.props;

    solutionManuals.forEach((book) => {
      if(book.urlName === bookNameRoute) {
        existingBook = true;
        bookName = book.name;
      }
    });
    if (!existingBook) browserHistory.push('/');
    this.onChangeBook(bookName);
  }

  setImage() {
    const { exercise, exercises } = this.state;
    this.props.onSetStatusRequestFalse();
    const imageUrl = exercises[parseInt(exercise.value) - 1].imageUrl;
    this.props.onSetImageUrl(imageUrl);
  }

  onSubmitSearchForm(e) {
    e.preventDefault();
    const { bookName, chapter, subchapter, exercise, subchapters } = this.state;
    if (!bookName || !chapter || (!subchapter && subchapters && subchapters.length < 0) || !exercise) {
      Alert.error(`Debes seleccionar todos los campos.`);
    } else {
      this.props.onSetImageUrl('loading');
      this.props.onSetStatusRequestTrue();
      setTimeout(this.setImage, 200);
    }
  }

  onChangeBook(bookName) {
    const { solutionManuals, onSetSolutionManual, onSetSelections } = this.props;
    const book = solutionManuals.filter(bookItem => bookItem.name === bookName);
    const chapters = book && book[0] && book[0].chapters;
    onSetSolutionManual(book[0]);
    onSetSelections({
      bookName: bookName || '',
      chapter: '',
      subchapter: '',
      exercise: '',
    });
    this.setState({
      bookName: bookName ? {label: bookName, value: bookName} : '',
      chapters,
      chapter: '',
      subchapter: '',
      exercise: '',
      exercises: [],
    });
  }

  onSelectedBook(option) {
    const bookName = option && option.label;
    const urlName = option && option.value;
    this.onChangeBook(bookName);
    if (bookName) {
      browserHistory.push(`/libro/${urlName}`);
    }
  }

  onSelectedChapter(option) {
    const { onSetSelections } = this.props;
    const selectedChapter = option && option.value;
    const stateChapters = this.state.chapters;
    const chapters = stateChapters && stateChapters.filter(chapter => chapter.number === parseInt(selectedChapter));
    const subchapters = chapters && chapters[0] && chapters[0].subchapters;
    let exercises = [];
    if (!subchapters) {
      exercises = chapters && chapters[0] && chapters[0].exercises;
    }
    onSetSelections({
      chapter: option ? selectedChapter : '',
      subchapter: '',
      exercise: '',
    });
    this.setState({
      chapter: option ? {label: selectedChapter, value: selectedChapter} : '',
      subchapters,
      subchapter: '',
      exercise: '',
      exercises: !subchapters && exercises ? exercises : [],
    });
  }

  onSelectedSubchapter(option) {
    const { onSetSelections } = this.props;
    const selectedSubchapter = option && option.value;
    const stateSubchapters = this.state.subchapters;
    const subchapters = stateSubchapters && stateSubchapters.filter(subchapter => subchapter.number === parseInt(selectedSubchapter));
    const exercises = subchapters && subchapters[0] && subchapters[0].exercises;
    onSetSelections({
      subchapter: option ? selectedSubchapter : '',
      exercise: '',
    });
    this.setState({
      subchapter: option ? {label: selectedSubchapter, value: selectedSubchapter} : '',
      exercises,
      exercise: '',
    });
  }

  onSelectedExercise(option) {
    const { onSetSelections } = this.props;
    const exercise = option && option.value;
    onSetSelections({ exercise: option ? exercise : '' });
    this.setState({
      exercise: option ? {label: exercise, value: exercise} : '',
    });
  }

  render() {
    const { bookName, chapter, subchapter, exercise, chapters, subchapters, exercises } = this.state;
    const { solutionManuals } = this.props;
    return (

              <Link to="/">ElSolucionario.io</Link>

            <form className="search__form" onSubmit={this.onSubmitSearchForm}>

                <SimpleSelect
                  placeholder="Selecciona un libro"
                  className="search__main-input"
                  options={solutionManuals && solutionManuals.map(book => ({label: book.name, value: book.urlName}))}
                  onValueChange={this.onSelectedBook}
                  value={bookName}
                />

                    <SimpleSelect
                      placeholder="Capítulo"
                      className="search__subsection-input"
                      options={chapters && chapters.map(chapter => ({label: (`${chapter.number.toString()} - ${chapter.name}`), value: (`${chapter.number.toString()} - ${chapter.name}`)}))}
                      onValueChange={this.onSelectedChapter}
                      disabled={!bookName}
                      value={chapter}
                    />

                    <SimpleSelect
                      placeholder="Subcapítulo"
                      className="search__subsection-input"
                      options={subchapters && subchapters.map(subchapter => ({label: (`${subchapter.number.toString()} - ${subchapter.name}`), value: (`${subchapter.number.toString()} - ${subchapter.name}`)}))}
                      disabled={!chapter || !subchapters}
                      onValueChange={this.onSelectedSubchapter}
                      value={subchapter}
                    />

                    <SimpleSelect
                      placeholder="Ejercicio"
                      className="search__subsection-input search__subsection-input--small"
                      options={exercises && exercises.map(exercise => ({label: exercise.number.toString(), value: exercise.number.toString()}))}
                      disabled={exercises && exercises.length === 0}
                      onValueChange={this.onSelectedExercise}
                      value={exercise}
                    />

                <button
                  className="button button--wide button--gray bold"
                >Buscar</button>

            </form>

    );
  }
}

Searcher.propTypes = {
  bookNameUrl: PropTypes.string,
  onSetImageUrl: PropTypes.func,
  onSetStatusRequestFalse: PropTypes.func,
  onSetStatusRequestTrue: PropTypes.func,
  onSetSolutionManual: PropTypes.func,
  onSetSelections: PropTypes.func,
  solutionManuals: PropTypes.array,
};

export default Searcher;
<commit_msg>Show exercise image when an exercise is selected<commit_after>import React, { Component, PropTypes } from 'react';
import { SimpleSelect } from 'react-selectize';
import { browserHistory, Link } from 'react-router';
import Alert from 'react-s-alert';

class Searcher extends Component {
  constructor() {
    super();

    this.state = {
      bookName: '',
      chapter: '',
      subchapter: '',
      exercise: '',
      exercises: [],
      chapters: [],
      subchapters: []
    };

    this.onChangeBook = this.onChangeBook.bind(this);
    this.onSelectedBook = this.onSelectedBook.bind(this);
    this.onSelectedChapter = this.onSelectedChapter.bind(this);
    this.onSelectedSubchapter = this.onSelectedSubchapter.bind(this);
    this.onSelectedExercise = this.onSelectedExercise.bind(this);
    this.onSubmitSearchForm = this.onSubmitSearchForm.bind(this);
    this.setImage = this.setImage.bind(this);
  }

  componentDidMount() {
    const bookNameRoute = this.props.bookNameUrl;
    let existingBook = false;
    let bookName = '';
    const { solutionManuals } = this.props;

    solutionManuals.forEach((book) => {
      if(book.urlName === bookNameRoute) {
        existingBook = true;
        bookName = book.name;
      }
    });
    if (!existingBook) browserHistory.push('/');
    this.onChangeBook(bookName);
  }

  setImage() {
    const { exercise, exercises } = this.state;
    this.props.onSetStatusRequestFalse();
    const imageUrl = exercises[parseInt(exercise.value) - 1].imageUrl;
    this.props.onSetImageUrl(imageUrl);
  }

  onSubmitSearchForm(e) {
    e.preventDefault();
    const { bookName, chapter, subchapter, exercise, subchapters } = this.state;
    if (!bookName || !chapter || (!subchapter && subchapters && subchapters.length < 0) || !exercise) {
      Alert.error(`Debes seleccionar todos los campos.`);
    }
  }

  onChangeBook(bookName) {
    const { solutionManuals, onSetSolutionManual, onSetSelections } = this.props;
    const book = solutionManuals.filter(bookItem => bookItem.name === bookName);
    const chapters = book && book[0] && book[0].chapters;
    onSetSolutionManual(book[0]);
    onSetSelections({
      bookName: bookName || '',
      chapter: '',
      subchapter: '',
      exercise: '',
    });
    this.setState({
      bookName: bookName ? {label: bookName, value: bookName} : '',
      chapters,
      chapter: '',
      subchapter: '',
      exercise: '',
      exercises: [],
    });
  }

  onSelectedBook(option) {
    const bookName = option && option.label;
    const urlName = option && option.value;
    this.onChangeBook(bookName);
    if (bookName) {
      browserHistory.push(`/libro/${urlName}`);
    }
  }

  onSelectedChapter(option) {
    const { onSetSelections } = this.props;
    const selectedChapter = option && option.value;
    const stateChapters = this.state.chapters;
    const chapters = stateChapters && stateChapters.filter(chapter => chapter.number === parseInt(selectedChapter));
    const subchapters = chapters && chapters[0] && chapters[0].subchapters;
    let exercises = [];
    if (!subchapters) {
      exercises = chapters && chapters[0] && chapters[0].exercises;
    }
    onSetSelections({
      chapter: option ? selectedChapter : '',
      subchapter: '',
      exercise: '',
    });
    this.setState({
      chapter: option ? {label: selectedChapter, value: selectedChapter} : '',
      subchapters,
      subchapter: '',
      exercise: '',
      exercises: !subchapters && exercises ? exercises : [],
    });
  }

  onSelectedSubchapter(option) {
    const { onSetSelections } = this.props;
    const selectedSubchapter = option && option.value;
    const stateSubchapters = this.state.subchapters;
    const subchapters = stateSubchapters && stateSubchapters.filter(subchapter => subchapter.number === parseInt(selectedSubchapter));
    const exercises = subchapters && subchapters[0] && subchapters[0].exercises;
    onSetSelections({
      subchapter: option ? selectedSubchapter : '',
      exercise: '',
    });
    this.setState({
      subchapter: option ? {label: selectedSubchapter, value: selectedSubchapter} : '',
      exercises,
      exercise: '',
    });
  }

  onSelectedExercise(option) {
    const { onSetSelections } = this.props;
    const exercise = option && option.value;
    onSetSelections({ exercise: option ? exercise : '' });
    this.setState({
      exercise: option ? {label: exercise, value: exercise} : '',
    });
    this.props.onSetImageUrl('loading');
    this.props.onSetStatusRequestTrue();
    setTimeout(this.setImage, 100);
  }

  render() {
    const { bookName, chapter, subchapter, exercise, chapters, subchapters, exercises } = this.state;
    const { solutionManuals } = this.props;
    return (

              <Link to="/">ElSolucionario.io</Link>

            <form className="search__form" onSubmit={this.onSubmitSearchForm}>

                <SimpleSelect
                  placeholder="Selecciona un libro"
                  className="search__main-input"
                  options={solutionManuals && solutionManuals.map(book => ({label: book.name, value: book.urlName}))}
                  onValueChange={this.onSelectedBook}
                  value={bookName}
                />

                    <SimpleSelect
                      placeholder="Capítulo"
                      className="search__subsection-input"
                      options={chapters && chapters.map(chapter => ({label: (`${chapter.number.toString()} - ${chapter.name}`), value: (`${chapter.number.toString()} - ${chapter.name}`)}))}
                      onValueChange={this.onSelectedChapter}
                      disabled={!bookName}
                      value={chapter}
                    />

                    <SimpleSelect
                      placeholder="Subcapítulo"
                      className="search__subsection-input"
                      options={subchapters && subchapters.map(subchapter => ({label: (`${subchapter.number.toString()} - ${subchapter.name}`), value: (`${subchapter.number.toString()} - ${subchapter.name}`)}))}
                      disabled={!chapter || !subchapters}
                      onValueChange={this.onSelectedSubchapter}
                      value={subchapter}
                    />

                    <SimpleSelect
                      placeholder="Ejercicio"
                      className="search__subsection-input search__subsection-input--small"
                      options={exercises && exercises.map(exercise => ({label: exercise.number.toString(), value: exercise.number.toString()}))}
                      disabled={exercises && exercises.length === 0}
                      onValueChange={this.onSelectedExercise}
                      value={exercise}
                    />

                <button
                  className="button button--wide button--gray bold"
                >Buscar</button>

            </form>

    );
  }
}

Searcher.propTypes = {
  bookNameUrl: PropTypes.string,
  onSetImageUrl: PropTypes.func,
  onSetStatusRequestFalse: PropTypes.func,
  onSetStatusRequestTrue: PropTypes.func,
  onSetSolutionManual: PropTypes.func,
  onSetSelections: PropTypes.func,
  solutionManuals: PropTypes.array,
};

export default Searcher;
<|endoftext|>


<commit_before>import { select } from 'd3-selection'
import { wrap } from './wrap-row'

export function createUnpackNestedRows() {

  let cache = null
    , filters = null

  function unpackNestedRows(s) {
    s.each(unpackNestedRowsEach)
  }

  return unpackNestedRows

  function unpackNestedRowsEach(d, i) {
    if (d.serverSideFilterAndSort) return
    filters = d.filters
    if (!cache) cache = unpackRows(d)
    select(this).on('data-dirty.unpack-nested-rows', onDataDirty)
    d.rows = cache
  }

  function onDataDirty() {
    console.debug('onDataDirty (from unpack nested rows)')
    cache = null
  }

  function unpackRows(d) {

    let hasNestedRows = false

    const rows = d.rows
        , rowsTop = rows.top.reduce(unpackNestedRowsForLevel(0), [])
        , rowsFree = rows.free.reduce(unpackNestedRowsForLevel(0), [])
        , rowsBottom = rows.bottom.reduce(unpackNestedRowsForLevel(0), [])
        , result = rowsTop.concat(rowsFree).concat(rowsBottom)

    result.top = rowsTop
    result.free = rowsFree
    result.bottom = rowsBottom
    result.hasNestedRows = hasNestedRows

    return result

    function unpackNestedRowsForLevel(level) {

      return function unpack(acc, row, i, a) {
        const children = row.children

        row.nestLevel = level
        acc.push(row)

        if (!children) {
          return acc
        } else {
          hasNestedRows = true
        }

        if (row.expanded) {
          children
              .map(wrap)
              .filter(filterChild)
              .map(updateNestedAttributes)
              .reduce(unpackNestedRowsForLevel(level + 1), acc)
        }

        return acc

        function filterChild(childRow) {
          childRow.parentRow = row
          return filters.every(runFilter.bind(null, childRow, i, a))
        }

        function updateNestedAttributes(d, i, a) {
          d.locked = row.locked
          d.isLast = i == (a.length - 1)
          return d
        }
      }

      function runFilter(row, i, a, f) {
        return f(row, i, a)
      }
    }
  }
}
<commit_msg>Min cleanup.<commit_after>import { select } from 'd3-selection'
import { wrap } from './wrap-row'

export function createUnpackNestedRows() {

  let cache = null
    , filters = null

  function unpackNestedRows(s) {
    s.each(unpackNestedRowsEach)
  }

  return unpackNestedRows

  function unpackNestedRowsEach(d, i) {
    if (d.serverSideFilterAndSort) return
    filters = d.filters
    if (!cache) cache = unpackRows(d)
    select(this).on('data-dirty.unpack-nested-rows', onDataDirty)
    d.rows = cache
  }

  function onDataDirty() {
    cache = null
  }

  function unpackRows(d) {

    let hasNestedRows = false

    const rows = d.rows
        , rowsTop = rows.top.reduce(unpackNestedRowsForLevel(0), [])
        , rowsFree = rows.free.reduce(unpackNestedRowsForLevel(0), [])
        , rowsBottom = rows.bottom.reduce(unpackNestedRowsForLevel(0), [])
        , result = rowsTop.concat(rowsFree).concat(rowsBottom)

    result.top = rowsTop
    result.free = rowsFree
    result.bottom = rowsBottom
    result.hasNestedRows = hasNestedRows

    return result

    function unpackNestedRowsForLevel(level) {

      return function unpack(acc, row, i, a) {
        const children = row.children

        row.nestLevel = level
        acc.push(row)

        if (!children) {
          return acc
        } else {
          hasNestedRows = true
        }

        if (row.expanded) {
          children
              .map(wrap)
              .filter(filterChild)
              .map(updateNestedAttributes)
              .reduce(unpackNestedRowsForLevel(level + 1), acc)
        }

        return acc

        function filterChild(childRow) {
          childRow.parentRow = row
          return filters.every(runFilter.bind(null, childRow, i, a))
        }

        function updateNestedAttributes(d, i, a) {
          d.locked = row.locked
          d.isLast = i == (a.length - 1)
          return d
        }
      }

      function runFilter(row, i, a, f) {
        return f(row, i, a)
      }
    }
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, ViewPropTypes } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';

import variable from '../theme/variables/platform';
import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';

class Footer extends Component {
  static contextTypes = {
    theme: PropTypes.object
  };
  constructor(props) {
    super(props);
    this.state = {
      orientation:
        variable.deviceHeight > variable.deviceWidth ? 'portrait' : 'landscape'
    };
  }
  layoutChange(val) {
    const maxComp = Math.max(variable.deviceWidth, variable.deviceHeight);
    if (val.width >= maxComp) this.setState({ orientation: 'landscape' });
    else {
      this.setState({ orientation: 'portrait' });
    }
  }

  calculateHeight(mode, inSet) {
    let inset = null;
    if (inSet !== undefined) {
      inset = inSet;
    } else {
      inset = variable.Inset;
    }
    const InsetValues = mode === 'portrait' ? inset.portrait : inset.landscape;
    let oldHeight = null;
    if (this.props.style.height !== undefined) {
      oldHeight = this.props.style.height;
    } else if (this.props.style[1]) {
      oldHeight = this.props.style[1].height
        ? this.props.style[1].height
        : this.props.style[0].height;
    } else {
      oldHeight = this.props.style[0].height;
    }
    const height = oldHeight + InsetValues.bottomInset;
    return height;
  }

  calculatePadder(mode, inSet) {
    let inset = null;
    if (inSet !== undefined) {
      inset = inSet;
    } else {
      inset = variable.Inset;
    }
    const InsetValues = mode === 'portrait' ? inset.portrait : inset.landscape;
    let bottomPadder = null;
    if (this.props.style[1] !== undefined) {
      if (
        this.props.style[1].padding !== undefined ||
        this.props.style[1].paddingTop !== undefined
      ) {
        bottomPadder =
          (this.props.style[1].paddingTop
            ? this.props.style[1].paddingTop
            : this.props.style[1].padding) + InsetValues.bottomInset;
      }
    } else if (
      this.props.style.padding !== undefined &&
      this.props.style.paddingTop !== undefined
    ) {
      bottomPadder =
        (this.props.style.paddingTop
          ? this.props.style.paddingTop
          : this.props.style.padding) + InsetValues.bottomInset;
    } else {
      bottomPadder = InsetValues.bottomInset;
    }
    return bottomPadder;
  }
  render() {
    const variables = this.context.theme
      ? this.context.theme['@@shoutem.theme/themeStyle'].variables
      : variable;
    return variables.isIphoneX ? (
      <View
        ref={c => (this._root = c)}
        {...this.props}
        onLayout={e => this.layoutChange(e.nativeEvent.layout)}
        style={[
          this.props.style,
          {
            height: this.calculateHeight(
              this.state.orientation,
              variables.Inset
            ),
            paddingBottom: this.calculatePadder(
              this.state.orientation,
              variables.Inset
            )
          }
        ]}
      />
    ) : (
      <View ref={c => (this._root = c)} {...this.props} />
    );
  }
}

Footer.propTypes = {
  ...ViewPropTypes,
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number,
    PropTypes.array
  ])
};

const StyledFooter = connectStyle(
  'NativeBase.Footer',
  {},
  mapPropsToStyleNames
)(Footer);
export { StyledFooter as Footer };
<commit_msg>Footer cleanup (#2782)<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, ViewPropTypes } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';

import variable from '../theme/variables/platform';
import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';

class Footer extends Component {
  static contextTypes = {
    theme: PropTypes.object
  };
  constructor(props) {
    super(props);
    this.state = {
      orientation:
        variable.deviceHeight > variable.deviceWidth ? 'portrait' : 'landscape'
    };
  }
  layoutChange(val) {
    const maxComp = Math.max(variable.deviceWidth, variable.deviceHeight);
    if (val.width >= maxComp) this.setState({ orientation: 'landscape' });
    else {
      this.setState({ orientation: 'portrait' });
    }
  }

  calculateHeight(mode, inSet) {
    const { style } = this.props;
    let inset = null;
    if (inSet !== undefined) {
      inset = inSet;
    } else {
      inset = variable.Inset;
    }
    const InsetValues = mode === 'portrait' ? inset.portrait : inset.landscape;
    let oldHeight = null;
    if (style.height !== undefined) {
      oldHeight = style.height;
    } else if (style[1]) {
      oldHeight = style[1].height || style[0].height;
    } else {
      oldHeight = style[0].height;
    }
    const height = oldHeight + InsetValues.bottomInset;
    return height;
  }

  calculatePadder(mode, inSet) {
    const { style } = this.props;
    let inset = null;
    if (inSet !== undefined) {
      inset = inSet;
    } else {
      inset = variable.Inset;
    }
    const InsetValues = mode === 'portrait' ? inset.portrait : inset.landscape;
    let bottomPadder = null;
    if (style[1] !== undefined) {
      if (style[1].padding !== undefined || style[1].paddingTop !== undefined) {
        bottomPadder =
          (style[1].paddingTop || style[1].padding) + InsetValues.bottomInset;
      }
    } else if (style.padding !== undefined && style.paddingTop !== undefined) {
      bottomPadder =
        (style.paddingTop || style.padding) + InsetValues.bottomInset;
    } else {
      bottomPadder = InsetValues.bottomInset;
    }
    return bottomPadder;
  }
  render() {
    const { style } = this.props;
    const variables = this.context.theme
      ? this.context.theme['@@shoutem.theme/themeStyle'].variables
      : variable;
    return variables.isIphoneX ? (
      <View
        ref={c => (this._root = c)}
        {...this.props}
        onLayout={e => this.layoutChange(e.nativeEvent.layout)}
        style={[
          style,
          {
            height: this.calculateHeight(
              this.state.orientation,
              variables.Inset
            ),
            paddingBottom: this.calculatePadder(
              this.state.orientation,
              variables.Inset
            )
          }
        ]}
      />
    ) : (
      <View ref={c => (this._root = c)} {...this.props} />
    );
  }
}

Footer.propTypes = {
  ...ViewPropTypes,
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number,
    PropTypes.array
  ])
};

const StyledFooter = connectStyle(
  'NativeBase.Footer',
  {},
  mapPropsToStyleNames
)(Footer);
export { StyledFooter as Footer };
<|endoftext|>


<commit_before>import Campaign from "./campaign.js";
import MailChimpList from "./mailchimp.js";

Meteor.methods({
  sendCampaign: function () {
    if(Users.is.adminById(this.userId))
      return Campaign.scheduleNextWithMailChimp(false);
  },
  testCampaign: function () {
    if(Users.is.adminById(this.userId))
      return Campaign.scheduleNextWithMailChimp(true);
  },
  'newsletter.addUser'(user){
    if (!user || !Users.can.editById(this.userId, user)) {
      throw new Meteor.Error(601, __('sorry_you_cannot_edit_this_user'));
    }

    try {
      return MailChimpList.add(user, false);
    } catch (error) {
      throw new Meteor.Error(500, error.message);
    }
  },
  'newsletter.removeUser'(user) {
    if (!user || !Users.can.editById(this.userId, user)) {
      throw new Meteor.Error(601, __('sorry_you_cannot_edit_this_user'));
    }

    try {
      return MailChimpList.remove(user);
    } catch (error) {
      throw new Meteor.Error(500, error.message);
    }
  },
  'newsletter.addEmail'(email) {
    if(Users.is.adminById(this.userId)) {
      try {
        return MailChimpList.add(email, true);
      } catch (error) {
        throw new Meteor.Error(500, error.message);
      }
    }
  }
});
<commit_msg>remove excess of validation (doesn't make any sense..)<commit_after>import Campaign from "./campaign.js";
import MailChimpList from "./mailchimp.js";

Meteor.methods({
  sendCampaign: function () {
    if(Users.is.adminById(this.userId))
      return Campaign.scheduleNextWithMailChimp(false);
  },
  testCampaign: function () {
    if(Users.is.adminById(this.userId))
      return Campaign.scheduleNextWithMailChimp(true);
  },
  'newsletter.addUser'(user){
    if (!user || !Users.can.editById(this.userId, user)) {
      throw new Meteor.Error(601, __('sorry_you_cannot_edit_this_user'));
    }

    try {
      return MailChimpList.add(user, false);
    } catch (error) {
      throw new Meteor.Error(500, error.message);
    }
  },
  'newsletter.removeUser'(user) {
    if (!user || !Users.can.editById(this.userId, user)) {
      throw new Meteor.Error(601, __('sorry_you_cannot_edit_this_user'));
    }

    try {
      return MailChimpList.remove(user);
    } catch (error) {
      throw new Meteor.Error(500, error.message);
    }
  },
  'newsletter.addEmail'(email) {
    try {
      return MailChimpList.add(email, true);
    } catch (error) {
      throw new Meteor.Error(500, error.message);
    }
  }
});
<|endoftext|>


<commit_before>/*    Copyright 2016-2020 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename);

const Intel = require('./Intel.js');

const IntelTool = require('../net2/IntelTool.js')
const intelTool = new IntelTool()

const IntelManager = require('../net2/IntelManager.js')
const intelManager = new IntelManager();

const sysManager = require('../net2/SysManager.js');
const DNSManager = require('../net2/DNSManager.js');
const dnsManager = new DNSManager('info');
const getPreferredName = require('../util/util.js').getPreferredName
const f = require('../net2/Firewalla.js');

function formatBytes(bytes, decimals) {
  if (bytes == 0) return '0 Bytes';
  var k = 1000,
    dm = decimals || 2,
    sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

class DestInfoIntel extends Intel {

  async enrichAlarm(alarm) {
    if (alarm["p.ignoreDestIntel"] == "1")
      return alarm;
    if (alarm["p.transfer.outbound.size"]) {
      alarm["p.transfer.outbound.humansize"] = formatBytes(alarm["p.transfer.outbound.size"]);
    }

    if (alarm["p.transfer.inbound.size"]) {
      alarm["p.transfer.inbound.humansize"] = formatBytes(alarm["p.transfer.inbound.size"]);
    }
    if (alarm["p.totalUsage"]) {
      alarm["p.totalUsage.humansize"] = formatBytes(alarm["p.totalUsage"]);
    }
    if (alarm["p.planUsage"]) {
      alarm["p.planUsage.humansize"] = formatBytes(alarm["p.planUsage"]);
    }

    let destIP = alarm["p.dest.ip"];

    if (!destIP) {
      return alarm;
    }
    if (sysManager.isLocalIP(destIP)) {
      try {
        if (sysManager.isMyIP(destIP) || sysManager.isMyIP6(destIP)) {
          Object.assign(alarm, {
            "p.dest.name": await f.getBoxName() || "Firewalla",
            "p.dest.macVendor": "FIREWALLA INC",
            "p.dest.isLocal": "1"
          })
        } else {
          const result = await dnsManager.resolveLocalHostAsync(destIP);
          Object.assign(alarm, {
            "p.dest.name": getPreferredName(result),
            "p.dest.id": result.mac,
            "p.dest.mac": result.mac,
            "p.dest.macVendor": result.macVendor || "Unknown",
            "p.dest.isLocal": "1"
          });
        }
      } catch (err) {
        log.error("Failed to find host " + destIP + " in database: " + err);
      }
      return alarm;
    }

    // intel
    const intel = await intelTool.getIntel(destIP)
    if (intel && intel.app) {
      alarm["p.dest.app"] = intel.app
    }

    switch (alarm["type"]) {
      case 'ALARM_VIDEO':
        alarm["p.dest.category"] = 'av';
        break;
      case 'ALARM_GAME':
        alarm["p.dest.category"] = 'games';
        break;
      case 'ALARM_PORN':
        alarm["p.dest.category"] = 'porn';
        break;
      default:
        // some alarm types are determined by combination of values in intel.category and intel.cs
        // there may be multiple categories in intel.cs, and p.dest.category should reflect the reason why this alarm is generated.
        if (intel && intel.category)
          alarm["p.dest.category"] = intel.category;
    }

    if (intel && intel.host) {
      alarm["p.dest.name"] = intel.host
    } else {
      alarm["p.dest.name"] = alarm["p.dest.name"] || alarm["p.dest.ip"];
    }

    // location
    if (intel && intel.country && intel.latitude && intel.longitude) {
      alarm["p.dest.country"] = intel.country; // FIXME: need complete location info
      alarm["p.dest.latitude"] = parseFloat(intel.latitude)
      alarm["p.dest.longitude"] = parseFloat(intel.longitude)
    } else {
      const loc = await intelManager.ipinfo(destIP)
      if (loc && loc.loc) {
        const ll = loc.loc.split(",");
        if (ll.length === 2) {
          alarm["p.dest.latitude"] = parseFloat(ll[0]);
          alarm["p.dest.longitude"] = parseFloat(ll[1]);
        }
        alarm["p.dest.country"] = loc.country; // FIXME: need complete location info
      }
    }

    return alarm;
  }

}

module.exports = DestInfoIntel
<commit_msg>do not change p.dest.name if it is not an ip address in DestInfoIntel.js<commit_after>/*    Copyright 2016-2020 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename);

const Intel = require('./Intel.js');

const IntelTool = require('../net2/IntelTool.js')
const intelTool = new IntelTool()

const IntelManager = require('../net2/IntelManager.js')
const intelManager = new IntelManager();

const sysManager = require('../net2/SysManager.js');
const DNSManager = require('../net2/DNSManager.js');
const dnsManager = new DNSManager('info');
const getPreferredName = require('../util/util.js').getPreferredName
const f = require('../net2/Firewalla.js');

function formatBytes(bytes, decimals) {
  if (bytes == 0) return '0 Bytes';
  var k = 1000,
    dm = decimals || 2,
    sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

class DestInfoIntel extends Intel {

  async enrichAlarm(alarm) {
    if (alarm["p.ignoreDestIntel"] == "1")
      return alarm;
    if (alarm["p.transfer.outbound.size"]) {
      alarm["p.transfer.outbound.humansize"] = formatBytes(alarm["p.transfer.outbound.size"]);
    }

    if (alarm["p.transfer.inbound.size"]) {
      alarm["p.transfer.inbound.humansize"] = formatBytes(alarm["p.transfer.inbound.size"]);
    }
    if (alarm["p.totalUsage"]) {
      alarm["p.totalUsage.humansize"] = formatBytes(alarm["p.totalUsage"]);
    }
    if (alarm["p.planUsage"]) {
      alarm["p.planUsage.humansize"] = formatBytes(alarm["p.planUsage"]);
    }

    let destIP = alarm["p.dest.ip"];

    if (!destIP) {
      return alarm;
    }
    if (sysManager.isLocalIP(destIP)) {
      try {
        if (sysManager.isMyIP(destIP) || sysManager.isMyIP6(destIP)) {
          Object.assign(alarm, {
            "p.dest.name": await f.getBoxName() || "Firewalla",
            "p.dest.macVendor": "FIREWALLA INC",
            "p.dest.isLocal": "1"
          })
        } else {
          const result = await dnsManager.resolveLocalHostAsync(destIP);
          Object.assign(alarm, {
            "p.dest.name": getPreferredName(result),
            "p.dest.id": result.mac,
            "p.dest.mac": result.mac,
            "p.dest.macVendor": result.macVendor || "Unknown",
            "p.dest.isLocal": "1"
          });
        }
      } catch (err) {
        log.error("Failed to find host " + destIP + " in database: " + err);
      }
      return alarm;
    }

    // intel
    const intel = await intelTool.getIntel(destIP)
    if (intel && intel.app) {
      alarm["p.dest.app"] = intel.app
    }

    switch (alarm["type"]) {
      case 'ALARM_VIDEO':
        alarm["p.dest.category"] = 'av';
        break;
      case 'ALARM_GAME':
        alarm["p.dest.category"] = 'games';
        break;
      case 'ALARM_PORN':
        alarm["p.dest.category"] = 'porn';
        break;
      default:
        // some alarm types are determined by combination of values in intel.category and intel.cs
        // there may be multiple categories in intel.cs, and p.dest.category should reflect the reason why this alarm is generated.
        if (intel && intel.category)
          alarm["p.dest.category"] = intel.category;
    }

    if (intel && intel.host && alarm["p.dest.name"] === alarm["p.dest.ip"]) { // do not change p.dest.name if it is already a domain, host in intel:ip may be incorrect in case of cache conflict
      alarm["p.dest.name"] = intel.host
    } else {
      alarm["p.dest.name"] = alarm["p.dest.name"] || alarm["p.dest.ip"];
    }

    // location
    if (intel && intel.country && intel.latitude && intel.longitude) {
      alarm["p.dest.country"] = intel.country; // FIXME: need complete location info
      alarm["p.dest.latitude"] = parseFloat(intel.latitude)
      alarm["p.dest.longitude"] = parseFloat(intel.longitude)
    } else {
      const loc = await intelManager.ipinfo(destIP)
      if (loc && loc.loc) {
        const ll = loc.loc.split(",");
        if (ll.length === 2) {
          alarm["p.dest.latitude"] = parseFloat(ll[0]);
          alarm["p.dest.longitude"] = parseFloat(ll[1]);
        }
        alarm["p.dest.country"] = loc.country; // FIXME: need complete location info
      }
    }

    return alarm;
  }

}

module.exports = DestInfoIntel
<|endoftext|>


<commit_before>var $ = require('jquery');
var BaseComponent = require('./component.js');

/**
 * Web container for all components and services.
 */
var core = core || (function() {
    'use strict';

    return {
        /**
         * Registered services
         * @property services
         * @private
         */
        services: {},

        /**
         * Registered components
         * @property components
         * @private
         */
        components: {},

        /**
         * Started components
         * @property componentInstances
         * @private
         */
        componentInstances: {},

        /**
         * Defines a new service
         * @params {String} name
         * @params {Object} service
         * @return {Object} this
         */
        registerService: function(name, Service) {
            if (!this.services[name]) {
                this.services[name] = Service;
            }
            return this;
        },

        /**
         * Get the service by name
         * @params {String} name
         * @return {Object} service instance
         */
        getService: function(name) {
            var Service = this.services[name] || null;
            if (typeof Service === 'function') {
                Service = this.services[name] = new Service(this);
            }
            return Service;
        },

        /**
         * Extend from the base component class and store the reference
         * @param {String} name - Component blueprint
         * @param {Object} protoProps - Properties of our defined component
         * @return {Object} this
         */
        registerComponent: function(name, protoProps) {
            var parent = BaseComponent;
            var component, Surrogate;
            component = function() {
                parent.apply(this, arguments);
            };
            $.extend(component, parent);
            Surrogate = function() {
                this.constructor = component;
            };
            Surrogate.prototype = parent.prototype;
            component.prototype = new Surrogate();
            $.extend(component.prototype, protoProps);
            component.__super__ = parent.prototype;
            this.components[name] = component;
            return this;
        },

        /**
         * Stats a new component from the component blueprint and returns the reference
         * @param {String} name
         * @param {String} instanceId
         * @param {Object} options
         * @return {Object} component instance
         */
        startComponent: function(name, instanceId, options) {
            options = options || {};
            var Component = this.components[name];
            var instance;
            if (!!Component) {
                instance = new Component(instanceId, options, this);
                this.componentInstances[instanceId] = instance;
            } else {
                throw new Error('Component with the type: ' + name + ' is not defined.');
            }
            return instance;
        },

        /**
         * Stats a new component from the component blueprint and returns the reference
         * @param {Array} components
         * @return {Object} component instance
         */
        startComponents: function(components) {
            var instances = [];

            $.each(components, function(index, component) {
                try {
                    instances[index] = this.startComponent(component.name, component.instanceId, component.options);
                } catch(e) {
                    console.error('Start of component failed: ' + component.instanceId);
                    console.error(e);
                }
            }.bind(this));
            return instances;
        },

        /**
         * Get a Component instance by instanceId
         * @param {String} instanceId - component instance identifier defined with the "startComponent" method
         * @return {Object} component instance
         */
        getComponent: function(instanceId) {
            return this.componentInstances[instanceId] || null;
        },

        /**
         * Facade for destroying a component
         * @param {Object|String} component Could be an instance or the component id
         * @return {Object}
         */
        removeComponent: function(component) {
            if (typeof component === 'string') {
                this.destroyComponent(component);
            } else {
                this.destroyComponent(component.id);
            }
            return this;
        },

        /**
         * Destroys a component and removes its DOM element
         * @param {String} instanceId
         * @private
         */
        destroyComponent: function(instanceId) {
            var instance = this.componentInstances[instanceId];
            if (!!instance) {
                instance.destroy.call(instance);
                delete this.componentInstances[instanceId];
            }
            return this;
        }
    };
})();

module.exports = core;
<commit_msg>rename instanceId to id<commit_after>var $ = require('jquery');
var BaseComponent = require('./component.js');

/**
 * Web container for all components and services.
 */
var core = core || (function() {
    'use strict';

    return {
        /**
         * Registered services
         * @property services
         * @private
         */
        services: {},

        /**
         * Registered components
         * @property components
         * @private
         */
        components: {},

        /**
         * Started components
         * @property componentInstances
         * @private
         */
        componentInstances: {},

        /**
         * Defines a new service
         * @params {String} name
         * @params {Object} service
         * @return {Object} this
         */
        registerService: function(name, Service) {
            if (!this.services[name]) {
                this.services[name] = Service;
            }
            return this;
        },

        /**
         * Get the service by name
         * @params {String} name
         * @return {Object} service instance
         */
        getService: function(name) {
            var Service = this.services[name] || null;
            if (typeof Service === 'function') {
                Service = this.services[name] = new Service(this);
            }
            return Service;
        },

        /**
         * Extend from the base component class and store the reference
         * @param {String} name - Component blueprint
         * @param {Object} protoProps - Properties of our defined component
         * @return {Object} this
         */
        registerComponent: function(name, protoProps) {
            var parent = BaseComponent;
            var component, Surrogate;
            component = function() {
                parent.apply(this, arguments);
            };
            $.extend(component, parent);
            Surrogate = function() {
                this.constructor = component;
            };
            Surrogate.prototype = parent.prototype;
            component.prototype = new Surrogate();
            $.extend(component.prototype, protoProps);
            component.__super__ = parent.prototype;
            this.components[name] = component;
            return this;
        },

        /**
         * Stats a new component from the component blueprint and returns the reference
         * @param {String} name
         * @param {String} id
         * @param {Object} options
         * @return {Object} component instance
         */
        startComponent: function(name, id, options) {
            options = options || {};
            var Component = this.components[name];
            var instance;
            if (!!Component) {
                instance = new Component(id, options, this);
                this.componentInstances[id] = instance;
            } else {
                throw new Error('Component with the type: ' + name + ' is not defined.');
            }
            return instance;
        },

        /**
         * Stats a new component from the component blueprint and returns the reference
         * @param {Array} components
         * @return {Object} component instance
         */
        startComponents: function(components) {
            var instances = [];

            $.each(components, function(index, component) {
                try {
                    instances[index] = this.startComponent(component.name, component.id, component.options);
                } catch(e) {
                    console.error('Start of component failed: ' + component.id);
                    console.error(e);
                }
            }.bind(this));
            return instances;
        },

        /**
         * Get a Component instance by id
         * @param {String} id - component instance identifier defined with the "startComponent" method
         * @return {Object} component instance
         */
        getComponent: function(id) {
            return this.componentInstances[id] || null;
        },

        /**
         * Facade for destroying a component
         * @param {Object|String} component Could be an instance or the component id
         * @return {Object}
         */
        removeComponent: function(component) {
            if (typeof component === 'string') {
                this.destroyComponent(component);
            } else {
                this.destroyComponent(component.id);
            }
            return this;
        },

        /**
         * Destroys a component and removes its DOM element
         * @param {String} id
         * @private
         */
        destroyComponent: function(id) {
            var instance = this.componentInstances[id];
            if (!!instance) {
                instance.destroy.call(instance);
                delete this.componentInstances[id];
            }
            return this;
        }
    };
})();

module.exports = core;
<|endoftext|>


<commit_before>// itertool.js
// (c) 2011 OnesimusUnbound <marcelino dat deseo aet gmail dat com>
// itertools.js is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/OnesimusUnbound/itertool.js

// Version 0.0.1

(function(){
    // ------------------------- Baseline setup ---------------------------------

    var ObjectProto = Object.prototype,
        ArrayProto = Array.prototype;

    var __owns = ObjectProto.hasOwnProperty,

        __type = function(obj){
            if (typeof obj === 'undefined') {
                return "Undefined";
            } else if (obj === null) {
                return "Null";
            } else if (typeof obj.next === 'function') {
                return "Iterator";
            } else {
                return ObjectProto.toString.call(obj).match(/^\[object (.*)\]$/)[1];
            }
        },

        __extend = function(obj, other){
            for (var prop in other){
                if (__owns.call(other, prop)) {
                    obj[prop] = other[prop];
                }
            }
            return obj;
        },

        __map = function(items, callback){
            var result = [];

            for (var i = 0; i < items.length; i++){
                result[i] = callback(items[i]);
            }

            return result;
        },

        __slice = ArrayProto.slice;

    var root = this;
    var __previous_itertool = root.itertool;
    var itertool = {};

    var StopIteration;
    if (!root.StopIteration) {
        StopIteration = root.StopIteration = Error('StopIteration');
    } else {
        StopIteration = root.StopIteration;
    }
    itertool.StopIteration = StopIteration;
    var Iterator = itertool.Iterator = function(){};

    Iterator.prototype.next = function(){ throw StopIteration; };
    Iterator.prototype.__iterator__ = function(){ return this; };

    var extendIterator = function(nextImpl) {
        return __extend(new Iterator, {next: nextImpl});
    };

    itertool.ArrayIterator = ArrayIterator = function(array) {
        if(__type(array) === 'Undefined') throw new TypeError;

        var size = array.length,
            idx = 0;

        return extendIterator(function(){
            if (size > idx) {
                return array[idx++];
            }

            throw StopIteration;
        });
    };

    itertool.StringIterator = StringIterator = function(string, option){
        if(__type(string) === 'Undefined') throw new TypeError;

        var items = [];
        option = option || "";

        switch(__type(option)){
            case 'String':
            case 'RegExp':
                items = string.split(option);
                break;
        }

        return ArrayIterator(items);
    }

    itertool.ObjectIterator = ObjectIterator = function(obj, option) {
        if(__type(obj) === 'Undefined') throw new TypeError;

        var items = [];
        for (var key in obj){
            if (__owns.call(obj, key)){
                switch(option){
                    case 'keys' : items.push(key); break;
                    case 'all'  : items.push([key, obj[key]]); break;
                    default     : items.push(obj[key]);
                }
            }
        }

        return ArrayIterator(items);
    };

    itertool.toIterator = toIterator = function(obj){
        switch(__type(obj)){
            case 'String':
                return StringIterator.apply(root, arguments);

            case 'Array':
                return ArrayIterator.apply(root, arguments);

            case 'Iterator':
                return obj;

            default:
                return ObjectIterator.apply(root, arguments);
        }
    };

    // Infinite Iterators
    // ==================

    // counter
    itertool.counter = function(start, step){
        start = start || 0;
        step  = step  || 1;
        start -= step;

        return extendIterator(function(){
            return (start += step);
        });
    };

    // cycle
    itertool.cycle = function(obj){
        var type = __type(obj);

        if (type === 'Number' || type === 'RegExp' || type === 'Null')
            throw new TypeError;

        var iter = toIterator(obj),
            gen, size, idx, items = [];

        gen = extendIterator(function(){
            try {
                var item = iter.next();
                items.push(item);
                return item;
            } catch (err) {
                if (err === StopIteration) {
                    size = items.length;
                    if (!size) throw err;

                    idx = 0;
                    gen.next = function(){
                        if (idx >= size) idx = 0;
                        return items[idx++];
                    };

                    return gen.next();
                } else {
                    throw err;
                }
            }
        });

        return gen;
    };

    // repeat
    itertool.repeat = function(element, n){
        var count = 0;

        return extendIterator(n !== void 0
            ? function(){
                if (count < n) {
                    count++;
                    return element;
                }
                throw StopIteration;
            }
            : function() {
                return element;
            }
        );
    };

    // Terminating Iterators
    // =====================
    // chain
    itertool.chain = function(){
        var iterables = __slice.call(arguments),
            concatIters = [],
            size, iterIdx = 0, currentIter;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);
            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable)
        });

        size = iterables.length;
        currentIter = iterables[iterIdx++];

        gen = extendIterator(function(){
            try {
                return currentIter.next();
            } catch (err) {
                if (err === StopIteration) {
                    if (size > iterIdx) {
                        currentIter = iterables[iterIdx++];
                        return gen.next();
                    }
                    throw StopIteration;
                } else {
                    throw err;
                }
            }
        });

        return gen;
    };

    // irange
    itertool.irange = function(start, stop, step) {
        if (arguments.length <= 1) {
            stop = start || 0;
            start = 0;
        }
        step = step || 1;

        var len = Math.max(Math.ceil((stop - start) / step), 0);
        var idx = 0;

        start -= step;
        return extendIterator(function(){
            if (idx < len) {
                idx++;
                return (start += step);
            }
            throw StopIteration;
        });
    };

    itertool.compress = function(data, selectors) {
        var iterData = toIterator(data),
            iterSelector = toIterator(selectors);

        return extendIterator(function(){
            while(!iterSelector.next()) {
                iterData.next();
            }
            return iterData.next();
        });
    };

    itertool.dropwhile = function(predicate, iterable) {
        if (typeof predicate !== 'function') throw new TypeError;

        iterable = toIterator(iterable);
        var firstValid,
            gen = extendIterator(function(){
                while(predicate(firstValid = iterable.next()));
                gen.next = function(){
                    return iterable.next();
                };
                return firstValid;
            });

        return gen;
    };

    itertool.takewhile = function(predicate, iterable) {
        if (typeof predicate !== 'function') throw new TypeError;

        iterable = toIterator(iterable);
        var takenItem,
            gen = extendIterator(function(){
                if (predicate(takenItem = iterable.next()))
                    return takenItem;

                throw StopIteration;
            });

        return gen;
    };

    itertool.ifilter = function() {
        var iterable, predicate;

        if (arguments.length === 2) {
            iterable = arguments[1];
            predicate = arguments[0];
            if (typeof predicate !== 'function') throw new TypeError;

        } else if (arguments.length === 1) {
            iterable = arguments[0];
            predicate = function(item){ return !!item; };

        }

        iterable = toIterator(iterable);
        var validItem;

        return extendIterator(function(){
            while(!predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    itertool.ifilterfalse = function() {
        var iterable, predicate;

        if (arguments.length === 2) {
            iterable = arguments[1];
            predicate = arguments[0];
            if (typeof predicate !== 'function') throw new TypeError;

        } else if (arguments.length === 1) {
            iterable = arguments[0];
            predicate = function(item){ return !!item; };

        }

        iterable = toIterator(iterable);
        var validItem;

        return extendIterator(function(){
            while(predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    itertool.imap = function() {
        var callback = arguments[0],
            iterables = __slice.call(arguments, 1),
            size = iterables.length;

        if (typeof callback !== 'function') throw new TypeError;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var args = __map(iterables, function(iterable){
                return iterable.next();
            });

            return callback.apply(root, args);
        });
    };

    itertool.islice = function(iterable, start, stop, step) {
        if (arguments.length <= 1) {
            stop = start || 0;
            start = 0;
        }
        step = step || 1;
        iterable = toIterator(iterable);
        var iterRange = itertool.irange(start, stop, step),
            validIdx = iterRange.next(),
            idx = 0;

        return extendIterator(function(){
            while (idx < validIdx) {
                iterable.next();
                idx++;
            }
            validIdx = iterRange.next();
            return iterable.next();
        });
    };

    itertool.izip = function() {
        var iterables = __slice.call(arguments),
            size = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            if (size > 0)
                return __map(iterables, function(iterable){
                    return iterable.next();
                });

            throw StopIteration;
        });
    };

    itertool.izip_longest = function() {
        var iterables = __slice.call(arguments, 1),
            fillvalue = arguments[0] || "";
            numIterables = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var numEndedIter = 0;
            if (numIterables > 0)
                result = __map(iterables, function(iterable){
                    try {
                        return iterable.next();
                    } catch(err) {
                        if (err === StopIteration) {
                            if (numEndedIter < numIterables) {
                                numEndedIter++;
                                return fillvalue;
                            }
                        }
                    }
                });

            if (numEndedIter < numIterables)
                return result;

            throw StopIteration;
        });
    };

    itertool.noConflict = function() {
        root.itertool = __previous_itertool;
        return this;
    };

    // CommonJS module is defined
    if (typeof window === 'undefined' && typeof module !== 'undefined') {
        // Export module
        module.exports = itertool;

    } else {
        root.itertool = itertool;
    }
}());
<commit_msg>Updated islice. Still failing the test<commit_after>// itertool.js
// (c) 2011 OnesimusUnbound <marcelino dat deseo aet gmail dat com>
// itertools.js is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/OnesimusUnbound/itertool.js

// Version 0.0.1

(function(){
    // ------------------------- Baseline setup ---------------------------------

    var ObjectProto = Object.prototype,
        ArrayProto = Array.prototype;

    var __owns = ObjectProto.hasOwnProperty,

        __type = function(obj){
            if (typeof obj === 'undefined') {
                return "Undefined";
            } else if (obj === null) {
                return "Null";
            } else if (typeof obj.next === 'function') {
                return "Iterator";
            } else {
                return ObjectProto.toString.call(obj).match(/^\[object (.*)\]$/)[1];
            }
        },

        __extend = function(obj, other){
            for (var prop in other){
                if (__owns.call(other, prop)) {
                    obj[prop] = other[prop];
                }
            }
            return obj;
        },

        __map = function(items, callback){
            var result = [];

            for (var i = 0; i < items.length; i++){
                result[i] = callback(items[i]);
            }

            return result;
        },

        __slice = ArrayProto.slice;

    var root = this;
    var __previous_itertool = root.itertool;
    var itertool = {};

    var StopIteration;
    if (!root.StopIteration) {
        StopIteration = root.StopIteration = Error('StopIteration');
    } else {
        StopIteration = root.StopIteration;
    }
    itertool.StopIteration = StopIteration;
    var Iterator = itertool.Iterator = function(){};

    Iterator.prototype.next = function(){ throw StopIteration; };
    Iterator.prototype.__iterator__ = function(){ return this; };

    var extendIterator = function(nextImpl) {
        return __extend(new Iterator, {next: nextImpl});
    };

    itertool.ArrayIterator = ArrayIterator = function(array) {
        if(__type(array) === 'Undefined') throw new TypeError;

        var size = array.length,
            idx = 0;

        return extendIterator(function(){
            if (size > idx) {
                return array[idx++];
            }

            throw StopIteration;
        });
    };

    itertool.StringIterator = StringIterator = function(string, option){
        if(__type(string) === 'Undefined') throw new TypeError;

        var items = [];
        option = option || "";

        switch(__type(option)){
            case 'String':
            case 'RegExp':
                items = string.split(option);
                break;
        }

        return ArrayIterator(items);
    }

    itertool.ObjectIterator = ObjectIterator = function(obj, option) {
        if(__type(obj) === 'Undefined') throw new TypeError;

        var items = [];
        for (var key in obj){
            if (__owns.call(obj, key)){
                switch(option){
                    case 'keys' : items.push(key); break;
                    case 'all'  : items.push([key, obj[key]]); break;
                    default     : items.push(obj[key]);
                }
            }
        }

        return ArrayIterator(items);
    };

    itertool.toIterator = toIterator = function(obj){
        switch(__type(obj)){
            case 'String':
                return StringIterator.apply(root, arguments);

            case 'Array':
                return ArrayIterator.apply(root, arguments);

            case 'Iterator':
                return obj;

            default:
                return ObjectIterator.apply(root, arguments);
        }
    };

    // Infinite Iterators
    // ==================

    // counter
    itertool.counter = function(start, step){
        start = start || 0;
        step  = step  || 1;
        start -= step;

        return extendIterator(function(){
            return (start += step);
        });
    };

    // cycle
    itertool.cycle = function(obj){
        var type = __type(obj);

        if (type === 'Number' || type === 'RegExp' || type === 'Null')
            throw new TypeError;

        var iter = toIterator(obj),
            gen, size, idx, items = [];

        gen = extendIterator(function(){
            try {
                var item = iter.next();
                items.push(item);
                return item;
            } catch (err) {
                if (err === StopIteration) {
                    size = items.length;
                    if (!size) throw err;

                    idx = 0;
                    gen.next = function(){
                        if (idx >= size) idx = 0;
                        return items[idx++];
                    };

                    return gen.next();
                } else {
                    throw err;
                }
            }
        });

        return gen;
    };

    // repeat
    itertool.repeat = function(element, n){
        var count = 0;

        return extendIterator(n !== void 0
            ? function(){
                if (count < n) {
                    count++;
                    return element;
                }
                throw StopIteration;
            }
            : function() {
                return element;
            }
        );
    };

    // Terminating Iterators
    // =====================
    // chain
    itertool.chain = function(){
        var iterables = __slice.call(arguments),
            concatIters = [],
            size, iterIdx = 0, currentIter;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);
            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable)
        });

        size = iterables.length;
        currentIter = iterables[iterIdx++];

        gen = extendIterator(function(){
            try {
                return currentIter.next();
            } catch (err) {
                if (err === StopIteration) {
                    if (size > iterIdx) {
                        currentIter = iterables[iterIdx++];
                        return gen.next();
                    }
                    throw StopIteration;
                } else {
                    throw err;
                }
            }
        });

        return gen;
    };

    // irange
    itertool.irange = function(start, stop, step) {
        if (arguments.length <= 1) {
            stop = start || 0;
            start = 0;
        }
        step = step || 1;

        var len = Math.max(Math.ceil((stop - start) / step), 0);
        var idx = 0;

        start -= step;
        return extendIterator(function(){
            if (idx < len) {
                idx++;
                return (start += step);
            }
            throw StopIteration;
        });
    };

    itertool.compress = function(data, selectors) {
        var iterData = toIterator(data),
            iterSelector = toIterator(selectors);

        return extendIterator(function(){
            while(!iterSelector.next()) {
                iterData.next();
            }
            return iterData.next();
        });
    };

    itertool.dropwhile = function(predicate, iterable) {
        if (typeof predicate !== 'function') throw new TypeError;

        iterable = toIterator(iterable);
        var firstValid,
            gen = extendIterator(function(){
                while(predicate(firstValid = iterable.next()));
                gen.next = function(){
                    return iterable.next();
                };
                return firstValid;
            });

        return gen;
    };

    itertool.takewhile = function(predicate, iterable) {
        if (typeof predicate !== 'function') throw new TypeError;

        iterable = toIterator(iterable);
        var takenItem,
            gen = extendIterator(function(){
                if (predicate(takenItem = iterable.next()))
                    return takenItem;

                throw StopIteration;
            });

        return gen;
    };

    itertool.ifilter = function() {
        var iterable, predicate;

        if (arguments.length === 2) {
            iterable = arguments[1];
            predicate = arguments[0];
            if (typeof predicate !== 'function') throw new TypeError;

        } else if (arguments.length === 1) {
            iterable = arguments[0];
            predicate = function(item){ return !!item; };

        }

        iterable = toIterator(iterable);
        var validItem;

        return extendIterator(function(){
            while(!predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    itertool.ifilterfalse = function() {
        var iterable, predicate;

        if (arguments.length === 2) {
            iterable = arguments[1];
            predicate = arguments[0];
            if (typeof predicate !== 'function') throw new TypeError;

        } else if (arguments.length === 1) {
            iterable = arguments[0];
            predicate = function(item){ return !!item; };

        }

        iterable = toIterator(iterable);
        var validItem;

        return extendIterator(function(){
            while(predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    itertool.imap = function() {
        var callback = arguments[0],
            iterables = __slice.call(arguments, 1),
            size = iterables.length;

        if (typeof callback !== 'function') throw new TypeError;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var args = __map(iterables, function(iterable){
                return iterable.next();
            });

            return callback.apply(root, args);
        });
    };

    itertool.islice = function(iterable) {
        iterable = toIterator(iterable);
        var iterRange = itertool.irange.apply(root, __slice.call(arguments, 1)),
            validIdx,
            idx = 0;

        return extendIterator(function(){
            validIdx = iterRange.next();
            while (idx  !== validIdx) {
                iterable.next();
                idx++;
            }
            idx++;
            return iterable.next();
        });
    };

    itertool.izip = function() {
        var iterables = __slice.call(arguments),
            size = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            if (size > 0)
                return __map(iterables, function(iterable){
                    return iterable.next();
                });

            throw StopIteration;
        });
    };

    itertool.izip_longest = function() {
        var iterables = __slice.call(arguments, 1),
            fillvalue = arguments[0] || "";
            numIterables = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var numEndedIter = 0;
            if (numIterables > 0)
                result = __map(iterables, function(iterable){
                    try {
                        return iterable.next();
                    } catch(err) {
                        if (err === StopIteration) {
                            if (numEndedIter < numIterables) {
                                numEndedIter++;
                                return fillvalue;
                            }
                        }
                    }
                });

            if (numEndedIter < numIterables)
                return result;

            throw StopIteration;
        });
    };

    itertool.noConflict = function() {
        root.itertool = __previous_itertool;
        return this;
    };

    // CommonJS module is defined
    if (typeof window === 'undefined' && typeof module !== 'undefined') {
        // Export module
        module.exports = itertool;

    } else {
        root.itertool = itertool;
    }
}());
<|endoftext|>


<commit_before>// constructor
function Player(name) {
	this.name = name;
	this.cards = [];
	this.score = 0;
}

// constructor
function PlayerUI(){
  	this.cardDom = undefined;
  	this.scoreDom = undefined;
}

function Card() {
	this.suit = undefined;
	this.symbol = undefined;
	this.color = undefined;
	this.face = undefined;
	this.name = undefined;
	this.value = undefined;
}

function Deck(){
	this.suits = {
		0: {
			'suit': 'diamonds',
			'symbol': '♦',
			'color': 'red'
		},

		1: {
			'suit': 'hearts',
			'symbol': '♥',
			'color': 'red'
		},

		2: {
			'suit': 'clubs',
			'symbol': '♣',
			'color': 'black'
		},

		3: {
			'suit': 'spades',
			'symbol': '♠',
			'color': 'black'
		}
	}; // close suits

	this.cards = {
		1: {
			'name': 'ace',
			'face': 'A',
			'value': 1
		},

		2: {
			'name': 'two',
			'face': '2',
			'value': 2
		},

		3: {
			'name': 'three',
			'face': 3,
			'value': 3
		},

		4: {
			'name': 'four',
			'face': '4',
			'value': 4
		},

		5: {
			'name': 'five',
			'face': '5',
			'value': 5
		},

		6: {
			'name': 'six',
			'face': '6',
			'value': 6
		},

		7: {
			'name': 'seven',
			'face': '7',
			'value': 7
		},

		8: {
			'name': 'eight',
			'face': '8',
			'value': 8
		},

		9: {
			'name': 'nine',
			'face': '9',
			'value': 9
		},

		10: {
			'name': 'ten',
			'face': '10',
			'value': 10
		},

		11: {
			'name': 'jack',
			'face': 'J',
			'value': 10
		},

		12: {
			'name': 'queen',
			'face': 'Q',
			'value': 10
		},

		13: {
			'name': 'king',
			'face': 'K',
			'value': 10
		},

		14: {
			'name': 'ace',
			'face': 'A',
			'value': 11
		}
	}; // close cards
}

var playerOne = new Player('Bobby');

console.log(playerOne.name);<commit_msg>got a basic prototype/instance example working. just reading a basic name passed through an object<commit_after>// constructor
function Player(name) {
	this.name = name;
	this.cards = [];
	this.score = 0;
}

// constructor
function PlayerUI(){
  	this.cardDom = undefined;
  	this.scoreDom = undefined;
}

function Card() {
	this.suit = undefined;
	this.symbol = undefined;
	this.color = undefined;
	this.face = undefined;
	this.name = undefined;
	this.value = undefined;
}

function Deck(){
	this.suits = {
		0: {
			'suit': 'diamonds',
			'symbol': '♦',
			'color': 'red'
		},

		1: {
			'suit': 'hearts',
			'symbol': '♥',
			'color': 'red'
		},

		2: {
			'suit': 'clubs',
			'symbol': '♣',
			'color': 'black'
		},

		3: {
			'suit': 'spades',
			'symbol': '♠',
			'color': 'black'
		}
	}; // close suits

	this.cards = {
		1: {
			'name': 'ace',
			'face': 'A',
			'value': 1
		},

		2: {
			'name': 'two',
			'face': '2',
			'value': 2
		},

		3: {
			'name': 'three',
			'face': 3,
			'value': 3
		},

		4: {
			'name': 'four',
			'face': '4',
			'value': 4
		},

		5: {
			'name': 'five',
			'face': '5',
			'value': 5
		},

		6: {
			'name': 'six',
			'face': '6',
			'value': 6
		},

		7: {
			'name': 'seven',
			'face': '7',
			'value': 7
		},

		8: {
			'name': 'eight',
			'face': '8',
			'value': 8
		},

		9: {
			'name': 'nine',
			'face': '9',
			'value': 9
		},

		10: {
			'name': 'ten',
			'face': '10',
			'value': 10
		},

		11: {
			'name': 'jack',
			'face': 'J',
			'value': 10
		},

		12: {
			'name': 'queen',
			'face': 'Q',
			'value': 10
		},

		13: {
			'name': 'king',
			'face': 'K',
			'value': 10
		},

		14: {
			'name': 'ace',
			'face': 'A',
			'value': 11
		}
	}; // close cards
}

var playerOne = new Player('Bobby');
console.log(playerOne.name);<|endoftext|>