<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { remote } from 'electron'
import { copyFileSync, removeSync, existsSync } from 'fs-plus'
import path from 'path'
import { updateSettings, loadTodos } from '../actions'
import Header from '../components/Header'

const dialog = remote.dialog

const dialogOptions = {
  title: 'Select todoo.json directory',
  properties: ['openDirectory']
}

const style = {
  aboutBlock: {
    lineHeight: '1.8rem'
  },
  block: {
    color: '#999'
  },
  link: {
    color: '#dcdcdc'
  },
  input: {
    outline: 'none',
    width: '90%',
    color: '#999',
    border: '1px solid #181a1f',
    backgroundColor: '#1b1d23'

  },
  label: {
    fontSize: '1.1rem',
    color: '#fff'
  }
}

class Settings extends Component {
  constructor (props) {
    super(props)
    this.openDialog = this.openDialog.bind(this)
  }

  openDialog () {
    dialog.showOpenDialog(remote.getCurrentWindow(), dialogOptions, (filenames) => {
      if (!Array.isArray(filenames)) return
      try {
        if (existsSync(path.resolve(filenames[0], 'todoo.json'))) {
          const confirm = dialog.showMessageBox({
            type: 'info',
            title: 'File already exists',
            message: 'todoo.json file already exists',
            detail: 'Do you want to overwrite it?',
            buttons: ['Yes', 'No']
          })
          if (confirm === 0) {
            console.log('overwriting existing file')
            copyFileSync(path.resolve(this.props.todooJsonDir, 'todoo.json'), path.resolve(filenames[0], 'todoo.json'))
            // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json'))
          } else {
            console.log('not overwriting existing file')
            // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json'))
          }
        } else {
          console.log('move the file to a new location')
          copyFileSync(path.resolve(this.props.todooJsonDir, 'todoo.json'), path.resolve(filenames[0], 'todoo.json'))
          // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json'))
        }
        this.props.dispatch(updateSettings({
          todooJsonDir: filenames[0]
        }))
        this.props.dispatch(loadTodos())
      } catch (e) {
        console.error(e)
        dialog.showErrorBox('Error', e.message || 'An error has occoured')
      }
    })
  }

  render () {
    const { todooJsonDir, version, currentPage, dispatch } = this.props
    return (

              Relocate todoo.json in a different directory

              <input
                className='db pa2'
                style={style.input}
                type='text'
                readOnly='readonly'
                id='todooJsonDir'
                onClick={this.openDialog}
                value={todooJsonDir} />
              <button onClick={this.openDialog} className='task-item__button' type='button' key='bs'>
                <svg className='icon' fill='#000000' height='24' viewBox='0 0 24 24' width='24'>
                  <path d='M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z' />
                </svg>
              </button>

              Global shortcut

              <input
                className='db pa2'
                style={style.input}
                type='text'
                disabled='disabled'
                id='shortcut'
                value={this.props.shortcut} />

              About

                Version {version}

                MIT Licensed Copyright (c) 2016-present Alessandro Arnodo

                Follow me on twitter @vesparny

                Code available on GitHub

                Share on Twitter

    )
  }
}

const selector = (state) => state.settings

export default connect(selector)(Settings)
<commit_msg>chore(app): fix lint<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { remote } from 'electron'
import { copyFileSync, existsSync } from 'fs-plus'
import path from 'path'
import { updateSettings, loadTodos } from '../actions'
import Header from '../components/Header'

const dialog = remote.dialog

const dialogOptions = {
  title: 'Select todoo.json directory',
  properties: ['openDirectory']
}

const style = {
  aboutBlock: {
    lineHeight: '1.8rem'
  },
  block: {
    color: '#999'
  },
  link: {
    color: '#dcdcdc'
  },
  input: {
    outline: 'none',
    width: '90%',
    color: '#999',
    border: '1px solid #181a1f',
    backgroundColor: '#1b1d23'

  },
  label: {
    fontSize: '1.1rem',
    color: '#fff'
  }
}

class Settings extends Component {
  constructor (props) {
    super(props)
    this.openDialog = this.openDialog.bind(this)
  }

  openDialog () {
    dialog.showOpenDialog(remote.getCurrentWindow(), dialogOptions, (filenames) => {
      if (!Array.isArray(filenames)) return
      try {
        if (existsSync(path.resolve(filenames[0], 'todoo.json'))) {
          const confirm = dialog.showMessageBox({
            type: 'info',
            title: 'File already exists',
            message: 'todoo.json file already exists',
            detail: 'Do you want to overwrite it?',
            buttons: ['Yes', 'No']
          })
          if (confirm === 0) {
            console.log('overwriting existing file')
            copyFileSync(path.resolve(this.props.todooJsonDir, 'todoo.json'), path.resolve(filenames[0], 'todoo.json'))
            // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json'))
          } else {
            console.log('not overwriting existing file')
            // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json'))
          }
        } else {
          console.log('move the file to a new location')
          copyFileSync(path.resolve(this.props.todooJsonDir, 'todoo.json'), path.resolve(filenames[0], 'todoo.json'))
          // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json'))
        }
        this.props.dispatch(updateSettings({
          todooJsonDir: filenames[0]
        }))
        this.props.dispatch(loadTodos())
      } catch (e) {
        console.error(e)
        dialog.showErrorBox('Error', e.message || 'An error has occoured')
      }
    })
  }

  render () {
    const { todooJsonDir, version, currentPage, dispatch } = this.props
    return (

              Relocate todoo.json in a different directory

              <input
                className='db pa2'
                style={style.input}
                type='text'
                readOnly='readonly'
                id='todooJsonDir'
                onClick={this.openDialog}
                value={todooJsonDir} />
              <button onClick={this.openDialog} className='task-item__button' type='button' key='bs'>
                <svg className='icon' fill='#000000' height='24' viewBox='0 0 24 24' width='24'>
                  <path d='M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z' />
                </svg>
              </button>

              Global shortcut

              <input
                className='db pa2'
                style={style.input}
                type='text'
                disabled='disabled'
                id='shortcut'
                value={this.props.shortcut} />

              About

                Version {version}

                MIT Licensed Copyright (c) 2016-present Alessandro Arnodo

                Follow me on twitter @vesparny

                Code available on GitHub

                Share on Twitter

    )
  }
}

const selector = (state) => state.settings

export default connect(selector)(Settings)
<|endoftext|>


<commit_before>var Munchkin, baseUrl; // pre-existing globals
(function () {

    var cjsConfig = {
        loader: 'curl/loader/cjsm11'
    };

    curl.config({
        baseUrl: baseUrl,
        packages: {
            app: { location: 'app', config: cjsConfig, main: 'main' },
            feature: { location: 'feature', config: cjsConfig },
            component: { location: 'component', config: cjsConfig },
            platform: { location: 'platform', config: cjsConfig },
            curl: { location: 'lib/curl/src/curl/' },
            when: { location: 'lib/when', main: 'when' },
            most: { location: 'lib/most', main: 'most', config: cjsConfig },
            poly: { location: 'lib/poly' },
            leaflet: { location: 'lib/leaflet', main: 'dist/leaflet-src', config: cjsConfig }
        },
        paths: {
            ZeroClipboard: 'lib/zeroclipboard/ZeroClipboard',
            jquery: 'lib/jquery/jquery.min',
            'prettify': 'lib/google-code-prettify/src/prettify',
            bootstrap: {
                // FIXME: Find a better way to pull in bootstrap dependency
                // For now, load bootstrap from sagan-site, since pulling it in via
                // bower pulls the sources, and NOT the built .min.js file that we need
                location: 'lib/bootstrap/js/bootstrap',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'jquery' ],
                    // there is no global `bootstrap` var anywhere?
                    exports: '$.fn.tooltip'
                }
            },
            'bootstrap-datetimepicker': {
                location: 'lib/bootstrap-datetimepicker/src/js/bootstrap-datetimepicker',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'bootstrap' ],
                    exports: '$.fn.datetimepicker'
                }
            },
            'jquery-migrate': {
                location: '//code.jquery.com/jquery-migrate-1.2.1',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'jquery' ],
                    exports: '$.migrateWarnings'
                }
            },
            munchkin: {
                location: '//munchkin.marketo.net/munchkin',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'jquery', 'jquery-migrate' ],
                    factory: function() {
                        Munchkin.init('625-IUJ-009');
                        return Munchkin;
                    }
                }
            }
        },
        preloads: ['poly/es5']
    });

    // Can't document this in bower.json, so I'm documenting it here:
    // munchkin.js has a bug that incorrectly detects jquery 1.10.x as
    // being 1.1.x, below its required 1.3.x.  It proceeds to download jquery
    // 1.7.1 ("jquery-latest") which overwrites any existing jquery in
    // curl.js's cache. The newer jquery doesn't have any plugins
    // registered, so calls to $().tooltip, etc. fail.
    // To fix this, the bower.json cannot specify anything over ~1.9.  However,
    // munchkin has another bug: it uses an obsolete feature: $.browser.
    // This was deprecated as of 1.3.0 and removed in 1.9.0, but is still
    // used in munchkin.js.  Therefore, we must use the jquery-migrate plugin.
    // Also: I'm ensuring munchkin.js gets loaded last!

    curl(['app', 'jquery']).then(start, fail);

    function start(main, $) {
        // tell the jquery migrate plugin to be quiet
        $.migrateMute = true;
        // load munchkin once our page is loaded
        curl(['munchkin']);
    }

    function fail(ex) {
        // TODO: show a meaningful error to the user.
        //document.location.href = '/500';
        throw ex;
    }

}());
<commit_msg>Configure leaflet as a path, not a package, since it's a module-is-a-package kind of package.<commit_after>var Munchkin, baseUrl; // pre-existing globals
(function () {

    var cjsConfig = {
        loader: 'curl/loader/cjsm11'
    };

    curl.config({
        baseUrl: baseUrl || '',
        packages: {
            app: { location: 'app', config: cjsConfig, main: 'main' },
            feature: { location: 'feature', config: cjsConfig },
            component: { location: 'component', config: cjsConfig },
            platform: { location: 'platform', config: cjsConfig },
            curl: { location: 'lib/curl/src/curl/' },
            when: { location: 'lib/when', main: 'when' },
            most: { location: 'lib/most', main: 'most', config: cjsConfig },
            poly: { location: 'lib/poly' }
        },
        paths: {
            leaflet: { location: 'lib/leaflet/dist/leaflet-src', config: cjsConfig },
            ZeroClipboard: 'lib/zeroclipboard/ZeroClipboard',
            jquery: 'lib/jquery/jquery.min',
            'prettify': 'lib/google-code-prettify/src/prettify',
            bootstrap: {
                // FIXME: Find a better way to pull in bootstrap dependency
                // For now, load bootstrap from sagan-site, since pulling it in via
                // bower pulls the sources, and NOT the built .min.js file that we need
                location: 'lib/bootstrap/js/bootstrap',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'jquery' ],
                    // there is no global `bootstrap` var anywhere?
                    exports: '$.fn.tooltip'
                }
            },
            'bootstrap-datetimepicker': {
                location: 'lib/bootstrap-datetimepicker/src/js/bootstrap-datetimepicker',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'bootstrap' ],
                    exports: '$.fn.datetimepicker'
                }
            },
            'jquery-migrate': {
                location: '//code.jquery.com/jquery-migrate-1.2.1',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'jquery' ],
                    exports: '$.migrateWarnings'
                }
            },
            munchkin: {
                location: '//munchkin.marketo.net/munchkin',
                config: {
                    loader: 'curl/loader/legacy',
                    requires: [ 'jquery', 'jquery-migrate' ],
                    factory: function() {
                        Munchkin.init('625-IUJ-009');
                        return Munchkin;
                    }
                }
            }
        },
        preloads: ['poly/es5']
    });

    // Can't document this in bower.json, so I'm documenting it here:
    // munchkin.js has a bug that incorrectly detects jquery 1.10.x as
    // being 1.1.x, below its required 1.3.x.  It proceeds to download jquery
    // 1.7.1 ("jquery-latest") which overwrites any existing jquery in
    // curl.js's cache. The newer jquery doesn't have any plugins
    // registered, so calls to $().tooltip, etc. fail.
    // To fix this, the bower.json cannot specify anything over ~1.9.  However,
    // munchkin has another bug: it uses an obsolete feature: $.browser.
    // This was deprecated as of 1.3.0 and removed in 1.9.0, but is still
    // used in munchkin.js.  Therefore, we must use the jquery-migrate plugin.
    // Also: I'm ensuring munchkin.js gets loaded last!

    curl(['app', 'jquery']).then(start, fail);

    function start(main, $) {
        // tell the jquery migrate plugin to be quiet
        $.migrateMute = true;
        // load munchkin once our page is loaded
        curl(['munchkin']);
    }

    function fail(ex) {
        // TODO: show a meaningful error to the user.
        //document.location.href = '/500';
        throw ex;
    }

}());
<|endoftext|>


<commit_before>//Imports
import React from "react";
import { Container, Row, Col } from "reactstrap";
import i18n from "../../../../../both/i18n/en";
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Content = (props) => {
  return (
    <React.Fragment>
      <Container className="mt-5">

Looking for answers?

          Take a look at frequently asked questions

      </Container>
      {i18n.Faq.faq.map((item, index) => {
        return (
          <Col key={index} className="ml-5 pl-5 mt-5" xs={11}>

{item.heading}

            <DCSBalloon title=" " subtitle=" " balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

{item.text}

          </Col>
        );
      })}
    </React.Fragment>
  );
};

export default Content;
<commit_msg>moved Docus balloons<commit_after>//Imports
import React from "react";
import { Container, Row, Col } from "reactstrap";
import i18n from "../../../../../both/i18n/en";
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Content = (props) => {
  return (
    <React.Fragment>
      <Container className="mt-5">

Looking for answers?

          Take a look at frequently asked questions

      </Container>
      {i18n.Faq.faq.map((item, index) => {
        return (
          <Col key={index} className="ml-5 pl-5 mt-5" xs={11}>

{item.heading}

{item.text}

            <DCSBalloon title=" " subtitle=" " balloonId="bal1" display="inline" dcsTags={props.dcsTags} />
          </Col>
        );
      })}
    </React.Fragment>
  );
};

export default Content;
<|endoftext|>


<commit_before>export { InputsOutputs } from "./BoundsArraySet/BoundsArraySet_InputsOutputs.js";
export { ConvBiasActivation } from "./BoundsArraySet/BoundsArraySet_ConvBiasActivation.js";
export { Pointwise } from "./BoundsArraySet/BoundsArraySet_Pointwise.js";
export { Depthwise } from "./BoundsArraySet/BoundsArraySet_Depthwise.js";
<commit_msg>Update BoundsArraySet.js<commit_after>export { InputsOutputs } from "./BoundsArraySet/BoundsArraySet_InputsOutputs.js";
export { InputsOutputsPool } from "./BoundsArraySet/BoundsArraySet_InputsOutputs.js";
export { ConvBiasActivation } from "./BoundsArraySet/BoundsArraySet_ConvBiasActivation.js";
export { ConvBiasActivationPool } from "./BoundsArraySet/BoundsArraySet_ConvBiasActivation.js";
export { Pointwise } from "./BoundsArraySet/BoundsArraySet_Pointwise.js";
export { PointwisePool } from "./BoundsArraySet/BoundsArraySet_Pointwise.js";
export { Depthwise } from "./BoundsArraySet/BoundsArraySet_Depthwise.js";
export { DepthwisePool } from "./BoundsArraySet/BoundsArraySet_Depthwise.js";
<|endoftext|>


<commit_before>(function () {
    var acapela = null;
    try {
        if (process.arch == 'ia32') {
            acapela = require('acapela/acapela.32');
        } else {
            acapela = require('acapela/acapela.64');
        }
    } catch (e) { }
    var extract = require('extract-zip');
    var request = require('request');
    var rimraf = require('rimraf');
    var fs = require('fs');
    var path = require('path');

    var tts = {
        exec: function () {
        },
        enabled: false
    };

    if (acapela) {
        tts.enabled = true;
        tts.acapela = acapela;
        var speaker = {
            listen: function (callback) {
                speaker.listeners = speaker.listeners || [];
                speaker.listeners.push(callback);
                if (!speaker.pinging) {
                    speaker.pinging = true;
                    setTimeout(speaker.ping, 100);
                }
            },
            ping: function () {
                // There is a callback on the native speak method, but I'm not smart
                // enough to figure out how to trigger a javascript callback from
                // a c callback, so I poll instead. Don't judge.
                var res = acapela.isSpeaking();
                if (res) {
                    setTimeout(speaker.ping, 50);
                } else {
                    speaker.pinging = false;
                    while (speaker.listeners && speaker.listeners.length > 0) {
                        var cb = speaker.listeners.shift();
                        cb();
                    }
                }
            }
        };
        var downloader = {
            download_file_to_location(url, file_path, progress) {
                var size = 0;
                request({
                    uri: url
                }, function (err, res, body) {
                  if(err) {
                    console.log("error downloading " + url);
                    console.log(err);
                    progress(null, null, "error downloading " + url);
                  } else {
                    console.log("got a response");
                    progress(null, null, "got a response");
                  }
                }).on('data', function (data) {
                    size = size + data.length;
                    progress(size, false, null);
                }).pipe(fs.createWriteStream(file_path)).on('close', function () {
                    progress(0, true, null);
                });
            },
            download_file: function(url, expected_size, percent_pre, percent_amount, done) {
                downloader.download_file_to_location(url, downloader.tmp_file, function (size, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + Math.min(1.0, size / expected_size) * percent_amount,
                      done: false
                    });
                  }
                });
            },
            assert_directory: function(dir, done) {
                fs.stat(dir, function(err, stats) {
                    if(err && err.code == 'ENOENT') {
                        fs.mkdir(dir, {recursive: true}, function() {
                            done();
                        });
                    } else {
                        done();
                    }
                });
            },
            unzip_file_to_location: function(file_path, dir, progress) {
                var entries = 0;
                downloader.assert_directory(dir, function () {
                    var full_path = path.resolve(dir);
                    console.log("unzipping to " + full_path);
                    extract(downloader.tmp_file, {
                        dir: full_path, onEntry: function () {
                            entries++;
                            progress(entries, false, null);
                        }
                    }, function (err) {
                        if (err) {
                            console.log("unzip error", err);
                        }
                        fs.unlink(downloader.tmp_file);
                        progress(0, true, null);
                    });
                });
            },
            unzip_file: function(language_dir, n_entries, percent_pre, percent_amount, done) {
                downloader.unzip_file_to_location(downloader.tmp_file, language_dir, function(entries, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + (Math.min(1.0, (entries / n_entries)) * percent_amount),
                      done: false
                    });
                  }
                });
            },
            download_voice: function (opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var base_dir = opts.base_dir || './data';
                var bin_dir = path.resolve(base_dir, 'bin');
                var data_dir = path.resolve(base_dir, 'data');
                var language_dir = path.resolve(base_dir, 'data', opts.language_dir);
                downloader.tmp_file = path.resolve(base_dir, 'tmp_download' + Math.round(Math.random() * 99999) + '.zip');
                downloader.watcher = downloader.watcher || function() { };

                fs.unlink(downloader.tmp_file, function () {
                    var assert_base_dir = function() {
                        console.log("asserting base directory");
                        downloader.assert_directory(base_dir, assert_data_directory);
                    };
                    var assert_data_directory = function() {
                        console.log("asserting data directory");
                        downloader.assert_directory(data_dir, assert_bin_directory);
                    };
                    var assert_bin_directory = function() {
                        console.log("asserting bin directory");
                        downloader.assert_directory(bin_dir, function() {
                            console.log("checking for existing bin files");
                            fs.readdir(bin_dir, function(err, list) {
                                if(list.indexOf('Selector2.conf') !== -1) {
                                    fs.readFile(path.resolve(bin_dir, 'Selector2.conf'), 'utf-8', function(err, data) {
                                        // check version number
                                        console.log(data);
                                        var version = data.match(/Version=([\d_]+)/)[1];
                                        version = parseFloat(version.split(/_/).slice(0, 1).join('.'));
                                        check_for_binaries({version: version});
                                    });
                                } else {
                                    console.log("no bin version data found");
                                    check_for_binaries();
                                }
                            })
                        })
                    }
                    var check_for_binaries = function(data) {
                        // if binaries are defined and match, continue,
                        // otherwise download and unzip them
                        if(data && opts.acapela_version && data.version == opts.acapela_version) {
                            console.log("binaries already in place");
                            download_language();
                        } else {
                            var download_binaries = function() {
                                console.log("downloading binaries...");
                                downloader.download_file(opts.binary_url, 0, 0, unzip_binaries);
                            };
                            var unzip_binaries = function() {
                                console.log("unzipping binaries...");
                                download_bin.unzip_file(bin_dir, 0, 0, download_language);
                            };
                            download_binaries();
                        }
                    };
                    var download_language = function () {
                        console.log('downloading language...');
                        downloader.download_file(opts.language_url, (5 * 1024 * 1024), 0, 0.10, unzip_language);
                    };
                    var unzip_language = function() {
                        console.log('unzipping language...');
                        downloader.unzip_file(language_dir, 10, 0.10, 0.05, download_voice);
                    };
                    var download_voice = function() {
                        console.log('downloading voice...');
                        downloader.download_file(opts.voice_url, (50 * 1024 * 1024), 0.15, 0.65, unzip_voice);
                    };
                    var unzip_voice = function() {
                        console.log('unzipping voice...');
                        downloader.unzip_file(language_dir, 20, 0.85, 0.15, done);
                    };
                    var done = function() {
                        downloader.watcher({
                            percent: 1.0,
                            done: true
                        });
                    };
                    assert_base_dir();
                });
            },
            delete_voice: function(opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var found_dir = null;
                var language_dir = path.resolve(opts.base_dir || './data', opts.language_dir);
                fs.readdir(language_dir, function(err, list) {
                    for(var idx = 0; idx < list.length; idx++) {
                        var fn = list[idx];
                        var re = new RegExp(dir_id + "[^A-Za-z]", 'i');
                        if(fn.match(re)) {
                            found_dir = fn;
                        }
                    }
                    if (found_dir) {
                        rimraf(language_dir + '/' + found_dir, function () {
                            if (opts.success) {
                                opts.success();
                            }
                        });
                    } else {
                        if (opts.success) {
                            opts.success({ message: "no matching directory found" });
                        }
                    }
                });
            },
            watch: function (callback) {
                downloader.watcher = callback;
            }
        };
        tts.exec = function (method, opts) {
            opts = opts || {};
            if (method == 'speakText') {
                speaker.listen(opts.success);
                if (!tts.voice_id_map) {
                    tts.getAvailableVoices();
                }
                if (tts.voice_id_map && tts.voice_id_map[opts.voice_id]) {
                    opts.voice_key = tts.voice_id_map[opts.voice_id];
                    acapela.openVoice(opts.voice_key);
                }
                if (opts.volume) {
                    opts.volume = Math.min(Math.max(0, opts.volume * 100), 150);
                }
                if (opts.rate) {
                    opts.rate = Math.min(Math.max(30, opts.rate * 100), 300);
                }
                if (opts.pitch) {
                    opts.pitch = Math.min(Math.max(50, opts.pitch * 100), 150);
                }
                opts.success = function (res) { };
            }
            var res = acapela[method](opts);
            if (res && res.ready !== false) {
                if (opts.success) {
                    opts.success(res);
                }
            } else {
                if (opts.error) {
                    opts.error({ error: "negative response to " + method });
                }
            }
        }
        var keys = ['init', 'status', 'getAvailableVoices', 'downloadVoice', 'deleteVoice', 'speakText', 'stopSpeakingText'];
        for (var idx = 0; idx < keys.length; idx++) {
            (function (method) {
                tts[method] = function (opts) {
                    tts.exec(method, opts);
                }
            })(keys[idx]);
        }
        tts.reload = function (opts) {
          var teardown = tts.exec('teardown');
          var init = tts.exec('init');
          if(opts && opts.success) {
            opts.success({
              teardown: teardown,
              setup: setup
            });
          }
        };
        tts.getAvailableVoices = function (opts) {
            opts = opts || {};
            console.log("getting available voices");
            var raw_list = acapela.getAvailableVoices();
            var new_list = [];
            tts.voice_id_map = {};
            for (var idx = 0; idx < raw_list.length; idx++) {
                var voice = raw_list[idx];
                voice.raw_voice_id = voice.voice_id;
                voice.voice_id = 'acap:' + voice.raw_voice_id.split(/[^A-Za-z-]/)[0];
                tts.voice_id_map[voice.voice_id] = voice.raw_voice_id;
                new_list.push(voice);
            }
            if (opts.success) {
                opts.success(new_list);
            }
        };
        tts.downloadVoice = function(opts) {
            downloader.watch(opts.progress || opts.success);
            downloader.download_voice(opts || {});
        };
        tts.deleteVoice = function(opts) {
            downloader.delete_voice(opts || {});
        };
        tts.download_file = function(url, file_path, progress) {
            downloader.download_file_to_location(url, file_path, progress);
        };
        tts.unzip_file = function(file_path, dir_path, progress) {
            downloader.unzip_file_to_location(file_path, dir_path, progress);
        };
    }

    module.exports = tts;
})();<commit_msg>fallbacks<commit_after>(function () {
    var acapela = null;
    try {
        if (process.arch == 'ia32') {
            acapela = require('acapela/acapela.32');
        } else {
            acapela = require('acapela/acapela.64');
        }
    } catch (e) { }
    var extract = require('extract-zip');
    var request = require('request');
    var rimraf = require('rimraf');
    var fs = require('fs');
    var path = require('path');

    var tts = {
        exec: function () {
        },
        enabled: false
    };

    if (acapela) {
        tts.enabled = true;
        tts.acapela = acapela;
        var speaker = {
            listen: function (callback) {
                speaker.listeners = speaker.listeners || [];
                speaker.listeners.push(callback);
                if (!speaker.pinging) {
                    speaker.pinging = true;
                    setTimeout(speaker.ping, 100);
                }
            },
            ping: function () {
                // There is a callback on the native speak method, but I'm not smart
                // enough to figure out how to trigger a javascript callback from
                // a c callback, so I poll instead. Don't judge.
                var res = acapela.isSpeaking();
                if (res) {
                    setTimeout(speaker.ping, 50);
                } else {
                    speaker.pinging = false;
                    while (speaker.listeners && speaker.listeners.length > 0) {
                        var cb = speaker.listeners.shift();
                        cb();
                    }
                }
            }
        };
        var downloader = {
            download_file_to_location(url, file_path, progress) {
                var size = 0;
                request({
                    uri: url
                }, function (err, res, body) {
                  if(err) {
                    console.log("error downloading " + url);
                    console.log(err);
                    progress(null, null, "error downloading " + url);
                  } else {
                    console.log("got a response");
                    progress(null, null, "got a response");
                  }
                }).on('data', function (data) {
                    size = size + data.length;
                    progress(size, false, null);
                }).pipe(fs.createWriteStream(file_path)).on('close', function () {
                    progress(0, true, null);
                });
            },
            download_file: function(url, expected_size, percent_pre, percent_amount, done) {
                downloader.download_file_to_location(url, downloader.tmp_file, function (size, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + Math.min(1.0, size / expected_size) * percent_amount,
                      done: false
                    });
                  }
                });
            },
            assert_directory: function(dir, done) {
                fs.stat(dir, function(err, stats) {
                    if(err && err.code == 'ENOENT') {
                        fs.mkdir(dir, {recursive: true}, function() {
                            done();
                        });
                    } else {
                        done();
                    }
                });
            },
            unzip_file_to_location: function(file_path, dir, progress) {
                var entries = 0;
                downloader.assert_directory(dir, function () {
                    var full_path = path.resolve(dir);
                    console.log("unzipping to " + full_path);
                    extract(downloader.tmp_file, {
                        dir: full_path, onEntry: function () {
                            entries++;
                            progress(entries, false, null);
                        }
                    }, function (err) {
                        if (err) {
                            console.log("unzip error", err);
                        }
                        fs.unlink(downloader.tmp_file);
                        progress(0, true, null);
                    });
                });
            },
            unzip_file: function(language_dir, n_entries, percent_pre, percent_amount, done) {
                downloader.unzip_file_to_location(downloader.tmp_file, language_dir, function(entries, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + (Math.min(1.0, (entries / n_entries)) * percent_amount),
                      done: false
                    });
                  }
                });
            },
            download_voice: function (opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var base_dir = opts.base_dir || './data';
                var bin_dir = path.resolve(base_dir, 'bin');
                var data_dir = path.resolve(base_dir, 'data');
                var language_dir = path.resolve(base_dir, 'data', opts.language_dir);
                downloader.tmp_file = path.resolve(base_dir, 'tmp_download' + Math.round(Math.random() * 99999) + '.zip');
                downloader.watcher = downloader.watcher || function() { };

                fs.unlink(downloader.tmp_file, function () {
                    var assert_base_dir = function() {
                        console.log("asserting base directory");
                        downloader.assert_directory(base_dir, assert_data_directory);
                    };
                    var assert_data_directory = function() {
                        console.log("asserting data directory");
                        downloader.assert_directory(data_dir, assert_bin_directory);
                    };
                    var assert_bin_directory = function() {
                        console.log("asserting bin directory");
                        downloader.assert_directory(bin_dir, function() {
                            console.log("checking for existing bin files");
                            fs.readdir(bin_dir, function(err, list) {
                                if(list.indexOf('Selector2.conf') !== -1) {
                                    fs.readFile(path.resolve(bin_dir, 'Selector2.conf'), 'utf-8', function(err, data) {
                                        // check version number
                                        console.log(data);
                                        var version = data.match(/Version=([\d_]+)/)[1];
                                        version = parseFloat(version.split(/_/).slice(0, 1).join('.'));
                                        check_for_binaries({version: version});
                                    });
                                } else {
                                    console.log("no bin version data found");
                                    check_for_binaries();
                                }
                            })
                        })
                    }
                    var check_for_binaries = function(data) {
                        // if binaries are defined and match, continue,
                        // otherwise download and unzip them
                        if(data && opts.acapela_version && data.version == opts.acapela_version) {
                            console.log("binaries already in place");
                            download_language();
                        } else {
                            var download_binaries = function() {
                                console.log("downloading binaries...");
                                downloader.download_file(opts.binary_url, 0, 0, unzip_binaries);
                            };
                            var unzip_binaries = function() {
                                console.log("unzipping binaries...");
                                download_bin.unzip_file(bin_dir, 0, 0, download_language);
                            };
                            download_binaries();
                        }
                    };
                    var download_language = function () {
                        console.log('downloading language...');
                        downloader.download_file(opts.language_url, (5 * 1024 * 1024), 0, 0.10, unzip_language);
                    };
                    var unzip_language = function() {
                        console.log('unzipping language...');
                        downloader.unzip_file(language_dir, 10, 0.10, 0.05, download_voice);
                    };
                    var download_voice = function() {
                        console.log('downloading voice...');
                        downloader.download_file(opts.voice_url, (50 * 1024 * 1024), 0.15, 0.65, unzip_voice);
                    };
                    var unzip_voice = function() {
                        console.log('unzipping voice...');
                        downloader.unzip_file(language_dir, 20, 0.85, 0.15, done);
                    };
                    var done = function() {
                        downloader.watcher({
                            percent: 1.0,
                            done: true
                        });
                    };
                    assert_base_dir();
                });
            },
            delete_voice: function(opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var found_dir = null;
                var language_dir = path.resolve(opts.base_dir || './data', opts.language_dir);
                fs.readdir(language_dir, function(err, list) {
                    list = list || [];
                    for(var idx = 0; idx < list.length; idx++) {
                        var fn = list[idx];
                        var re = new RegExp(dir_id + "[^A-Za-z]", 'i');
                        if(fn.match(re)) {
                            found_dir = fn;
                        }
                    }
                    if (found_dir) {
                        rimraf(language_dir + '/' + found_dir, function () {
                            if (opts.success) {
                                opts.success();
                            }
                        });
                    } else {
                        // check in the legacy location before giving up
                        if(!opts.last_try) {
                            return downloader.delete_voice({
                                voice_id: opts.voice_id,
                                language_dir: opts.language_dir,
                                success: opts.success,
                                last_try: true
                            })
                        }
                        if (opts.success) {
                            opts.success({ message: "no matching directory found" });
                        }
                    }
                });
            },
            watch: function (callback) {
                downloader.watcher = callback;
            }
        };
        tts.exec = function (method, opts) {
            opts = opts || {};
            if (method == 'speakText') {
                speaker.listen(opts.success);
                if (!tts.voice_id_map) {
                    tts.getAvailableVoices();
                }
                if (tts.voice_id_map && tts.voice_id_map[opts.voice_id]) {
                    opts.voice_key = tts.voice_id_map[opts.voice_id];
                    acapela.openVoice(opts.voice_key);
                }
                if (opts.volume) {
                    opts.volume = Math.min(Math.max(0, opts.volume * 100), 150);
                }
                if (opts.rate) {
                    opts.rate = Math.min(Math.max(30, opts.rate * 100), 300);
                }
                if (opts.pitch) {
                    opts.pitch = Math.min(Math.max(50, opts.pitch * 100), 150);
                }
                opts.success = function (res) { };
            }
            var res = acapela[method](opts);
            if (res && res.ready !== false) {
                if (opts.success) {
                    opts.success(res);
                }
            } else {
                if (opts.error) {
                    opts.error({ error: "negative response to " + method });
                }
            }
        }
        var keys = ['init', 'status', 'getAvailableVoices', 'downloadVoice', 'deleteVoice', 'speakText', 'stopSpeakingText'];
        for (var idx = 0; idx < keys.length; idx++) {
            (function (method) {
                tts[method] = function (opts) {
                    tts.exec(method, opts);
                }
            })(keys[idx]);
        }
        tts.reload = function (opts) {
          var teardown = tts.exec('teardown');
          var init = tts.exec('init');
          if(opts && opts.success) {
            opts.success({
              teardown: teardown,
              setup: setup
            });
          }
        };
        tts.getAvailableVoices = function (opts) {
            opts = opts || {};
            console.log("getting available voices");
            var raw_list = acapela.getAvailableVoices();
            var new_list = [];
            tts.voice_id_map = {};
            for (var idx = 0; idx < raw_list.length; idx++) {
                var voice = raw_list[idx];
                voice.raw_voice_id = voice.voice_id;
                voice.voice_id = 'acap:' + voice.raw_voice_id.split(/[^A-Za-z-]/)[0];
                tts.voice_id_map[voice.voice_id] = voice.raw_voice_id;
                new_list.push(voice);
            }
            if (opts.success) {
                opts.success(new_list);
            }
        };
        tts.downloadVoice = function(opts) {
            downloader.watch(opts.progress || opts.success);
            downloader.download_voice(opts || {});
        };
        tts.deleteVoice = function(opts) {
            downloader.delete_voice(opts || {});
        };
        tts.download_file = function(url, file_path, progress) {
            downloader.download_file_to_location(url, file_path, progress);
        };
        tts.unzip_file = function(file_path, dir_path, progress) {
            downloader.unzip_file_to_location(file_path, dir_path, progress);
        };
    }

    module.exports = tts;
})();<|endoftext|>


<commit_before>Meteor.methods({
  report: function (url, reports) {
    console.log("reporting to ", url);
    Meteor.http.post(url, {
      data: reports
    });
    return null;
  }
});
<commit_msg>Remove console.log on report again<commit_after>Meteor.methods({
  report: function (url, reports) {
    Meteor.http.post(url, {
      data: reports
    });
    return null;
  }
});
<|endoftext|>


<commit_before>import _pick from 'lodash/pick'
import {all, call, put, delay} from 'redux-saga/effects'

import consoleLogger from '../consoleLogger'

/**
 * Sends a request to a location in a repetitive manner until the response has another status
 * than the one given by retryStatus.
 * @param {string} location Url that the request gets send to
 * @param {string} retryStatus As long as the body.status equals the retryStatus, the request gets repeated
 * @returns {object} response Request response
 */
export function* checkStatusLoop(requestSaga, location, retryStatus) {
  let delayer = 1
  while (true) {
    const response = yield call(requestSaga, location)
    if (response.body.status === retryStatus) {
      yield delay(500 * delayer)
      if (delayer < 10) {
        delayer++
      }
    } else {
      return response
    }
  }
}

/**
 * Starts the saga again if an exception is thrown
 * @param generator Saga
 * @param config Optional object with additional information
 * @param logErrorAction Action that gets dispatched in case of an exception
 * @returns {autoRestarting}
 */
export const autoRestartSaga = (generator, config, logErrorAction) => {
  return function* autoRestarting(...args) {
    while (true) {
      try {
        yield call(generator, config, ...args)
      } catch (error) {
        if (logErrorAction) {
          const errorObj = {..._pick(error, ['message', 'stack'])}
          yield put(logErrorAction('client.common.unexpectedError', 'client.common.unexpectedError', errorObj))
        } else {
          consoleLogger.logError('error', error)
        }
      }
    }
  }
}

/**
 * Transforms a list of sagas to a generator
 */
export const createGenerator = sagas => {
  return function* rootSaga() {
    yield all(sagas)
  }
}

/**
 * Add a saga to the store and runs it
 */
export const injectSaga = (store, saga, logErrorAction) => {
  if (!store.sagas.includes(saga)) {
    store.sagas.push(saga)
    store.sagaMiddleware.run(autoRestartSaga(saga, null, logErrorAction))
  }
}
<commit_msg>refactor(tocco-util): keep error object<commit_after>import {all, call, put, delay} from 'redux-saga/effects'

import consoleLogger from '../consoleLogger'

/**
 * Sends a request to a location in a repetitive manner until the response has another status
 * than the one given by retryStatus.
 * @param {string} location Url that the request gets send to
 * @param {string} retryStatus As long as the body.status equals the retryStatus, the request gets repeated
 * @returns {object} response Request response
 */
export function* checkStatusLoop(requestSaga, location, retryStatus) {
  let delayer = 1
  while (true) {
    const response = yield call(requestSaga, location)
    if (response.body.status === retryStatus) {
      yield delay(500 * delayer)
      if (delayer < 10) {
        delayer++
      }
    } else {
      return response
    }
  }
}

/**
 * Starts the saga again if an exception is thrown
 * @param generator Saga
 * @param config Optional object with additional information
 * @param logErrorAction Action that gets dispatched in case of an exception
 * @returns {autoRestarting}
 */
export const autoRestartSaga = (generator, config, logErrorAction) => {
  return function* autoRestarting(...args) {
    while (true) {
      try {
        yield call(generator, config, ...args)
      } catch (error) {
        if (logErrorAction) {
          yield put(logErrorAction('client.common.unexpectedError', 'client.common.unexpectedError', error))
        } else {
          consoleLogger.logError('error', error)
        }
      }
    }
  }
}

/**
 * Transforms a list of sagas to a generator
 */
export const createGenerator = sagas => {
  return function* rootSaga() {
    yield all(sagas)
  }
}

/**
 * Add a saga to the store and runs it
 */
export const injectSaga = (store, saga, logErrorAction) => {
  if (!store.sagas.includes(saga)) {
    store.sagas.push(saga)
    store.sagaMiddleware.run(autoRestartSaga(saga, null, logErrorAction))
  }
}
<|endoftext|>


<commit_before>var Schema = require("truffle-contract-schema");
var fs = require("fs-extra");
var path = require("path");
var _ = require("lodash");
var debug = require("debug")("artifactor");

function Artifactor(destination) {
  this.destination = destination;
}

Artifactor.prototype.save = function(artifactObject) {
  const self = this;

  const normalizedArtifact = Schema.normalize(artifactObject);
  const contractName = normalizedArtifact.contractName;

  if (!contractName) throw new Error("You must specify a contract name.");

  const output_path = path.join(self.destination, `${contractName}.json`);
  let completeArtifact = {};

  // helper for writing artifacts
  const writeArtifact = _completeArtifact => {
    _completeArtifact.updatedAt = new Date().toISOString();
    fs.writeFileSync(
      output_path,
      JSON.stringify(_completeArtifact, null, 2),
      "utf8"
    );
  };

  try {
    const existingArtifact = fs.readFileSync(output_path, "utf8"); // check if artifact already exists
    const existingArtifactObject = JSON.parse(existingArtifact); // parse existing artifact
    const normalizedExistingArtifact = Schema.normalize(existingArtifactObject);
    _.merge(completeArtifact, normalizedExistingArtifact, normalizedArtifact);
    writeArtifact(completeArtifact);
  } catch (e) {
    if (e.code === "ENOENT") return writeArtifact(normalizedArtifact);
    // if artifact doesn't already exist, write new file
    else if (e instanceof SyntaxError) throw new Error(e); // catches improperly formatted artifact json
    throw new Error(e); // catch all other errors
  }
};

Artifactor.prototype.saveAll = function(artifactObjects) {
  const self = this;
  let newArtifactObjects = {};

  if (Array.isArray(artifactObjects)) {
    const tmpArtifactArray = artifactObjects;

    tmpArtifactArray.forEach(function(artifactObj) {
      newArtifactObjects[artifactObj.contract_name] = artifactObj;
    });
  } else {
    newArtifactObjects = artifactObjects;
  }

  try {
    fs.statSync(self.destination);
  } catch (e) {
    if (e.code === "ENOENT")
      throw new Error(`Destination "${self.destination}" doesn't exist!`);
    throw new Error(e);
  }

  Object.keys(newArtifactObjects).forEach(contractName => {
    let artifactObject = newArtifactObjects[contractName];
    self.save(artifactObject);
  });
};

module.exports = Artifactor;
<commit_msg>es6 it<commit_after>var Schema = require("truffle-contract-schema");
var fs = require("fs-extra");
var path = require("path");
var _ = require("lodash");
var debug = require("debug")("artifactor");

class Artifactor {
  constructor(destination) {
    this.destination = destination;
  }

  save(artifactObject) {
    const self = this;

    const normalizedArtifact = Schema.normalize(artifactObject);
    const contractName = normalizedArtifact.contractName;

    if (!contractName) throw new Error("You must specify a contract name.");

    const output_path = path.join(self.destination, `${contractName}.json`);
    let completeArtifact = {};

    // helper for writing artifacts
    const writeArtifact = _completeArtifact => {
      _completeArtifact.updatedAt = new Date().toISOString();
      fs.writeFileSync(
        output_path,
        JSON.stringify(_completeArtifact, null, 2),
        "utf8"
      );
    };

    try {
      const existingArtifact = fs.readFileSync(output_path, "utf8"); // check if artifact already exists
      const existingArtifactObject = JSON.parse(existingArtifact); // parse existing artifact
      const normalizedExistingArtifact = Schema.normalize(
        existingArtifactObject
      );
      _.merge(completeArtifact, normalizedExistingArtifact, normalizedArtifact);
      writeArtifact(completeArtifact);
    } catch (e) {
      if (e.code === "ENOENT") return writeArtifact(normalizedArtifact);
      // if artifact doesn't already exist, write new file
      else if (e instanceof SyntaxError) throw new Error(e); // catches improperly formatted artifact json
      throw new Error(e); // catch all other errors
    }
  }

  saveAll(artifactObjects) {
    const self = this;
    let newArtifactObjects = {};

    if (Array.isArray(artifactObjects)) {
      const tmpArtifactArray = artifactObjects;

      tmpArtifactArray.forEach(artifactObj => {
        newArtifactObjects[artifactObj.contract_name] = artifactObj;
      });
    } else {
      newArtifactObjects = artifactObjects;
    }

    try {
      fs.statSync(self.destination);
    } catch (e) {
      if (e.code === "ENOENT")
        throw new Error(`Destination "${self.destination}" doesn't exist!`);
      throw new Error(e);
    }

    Object.keys(newArtifactObjects).forEach(contractName => {
      let artifactObject = newArtifactObjects[contractName];
      self.save(artifactObject);
    });
  }
}

module.exports = Artifactor;
<|endoftext|>


<commit_before>var request = require('request');
var $ = require('jquery');
var h = require('../../lib/helpers.js');

exports.setup = function(server){
	server.get({path: '/car', version: '1.0.0'}, lookup);
	server.post({path: '/car', version: '1.0.0'}, lookup);
}

var lookup = function(req, res, next){
	res.header("Access-Control-Allow-Origin", "*");
  	res.header("Access-Control-Allow-Headers", "X-Requested-With");

	var data = req.params;

	if(!data.number){
		res.json(431,{error:'Please provide a valid number to lookup'});
		return next();
	}

	request.get({
		headers: {'User-Agent': h.browser()},
		url: 'http://www.us.is/upplysingar_um_bil?vehinumber='+data.number
	}, function(error, response, body){
		if(error || response.statusCode !== 200) {
			throw new Error("www.us.is refuses to respond or give back data");
		}
		var data = $(body),
			obj = { results: []},
			car = {
				'registryNumber': 0,
				'number': 0,
				'factoryNumber': 0,
				'type': '',
				'subType': '',
				'color': '',
				'registeredAt': '',
				'status': '',
				'nextCheck': '',
				'pollution': '',
				'weight': 0
			}

		var fields = ['registryNumber','number','factoryNumber','type','subType','color','registeredAt','status','nextCheck','pollution','weight'];
		var nothingFound = data.find('table tr td').html();
		if( nothingFound.indexOf('Ekkert ökutæki fannst') == -1){
			//Found something
			data.find('table tr').each(function(key){
				var val = $(this).find('b').html();
				if(val != '' && val != 0){ //Perform check and add to car array if it passes
					car[fields[key]] = val;
				}
			});
			obj.results.push(car);
		}
		res.json(200,obj)
		return next();
	});
}<commit_msg>For some reason us.is moved their website from www.us.is to ww2.us.is ??? Fixed car api to use the new url<commit_after>var request = require('request');
var $ = require('jquery');
var h = require('../../lib/helpers.js');

exports.setup = function(server){
	server.get({path: '/car', version: '1.0.0'}, lookup);
	server.post({path: '/car', version: '1.0.0'}, lookup);
}

var lookup = function(req, res, next){
	res.header("Access-Control-Allow-Origin", "*");
  	res.header("Access-Control-Allow-Headers", "X-Requested-With");

	var data = req.params;

	if(!data.number){
		res.json(431,{error:'Please provide a valid number to lookup'});
		return next();
	}

	request.get({
		headers: {'User-Agent': h.browser()},
		url: 'http://ww2.us.is/upplysingar_um_bil?vehinumber='+data.number
	}, function(error, response, body){
		if(error || response.statusCode !== 200) {
			throw new Error("www.us.is refuses to respond or give back data");
		}
		var data = $(body),
			obj = { results: []},
			car = {
				'registryNumber': 0,
				'number': 0,
				'factoryNumber': 0,
				'type': '',
				'subType': '',
				'color': '',
				'registeredAt': '',
				'status': '',
				'nextCheck': '',
				'pollution': '',
				'weight': 0
			}

		var fields = ['registryNumber','number','factoryNumber','type','subType','color','registeredAt','status','nextCheck','pollution','weight'];
		var nothingFound = data.find('table tr td').html();
		if( nothingFound.indexOf('Ekkert ökutæki fannst') == -1){
			//Found something
			data.find('table tr').each(function(key){
				var val = $(this).find('b').html();
				if(val != '' && val != 0){ //Perform check and add to car array if it passes
					car[fields[key]] = val;
				}
			});
			obj.results.push(car);
		}
		res.json(200,obj)
		return next();
	});
}<|endoftext|>


<commit_before>/*
	nlehuby
*/

var osm_route_id = getParameterByName('osm_route_id');
var navitia_route_id = getParameterByName('navitia_route_id');
//var osm_route_id = 1103965;
//var navitia_route_id = 'route:OIF:014014011:11';

var tag_to_match = "ref:FR:STIF";
var JOSM_url_base = "https://localhost:8112/load_object?objects="
main()

function find_opendata_closer_stop(osm_stop_pos, opendata_stops) {
    var sorted_opendata_stops = opendata_stops.sort(function(a, b) {
        var locA = turf.point([a.lon, a.lat]);
        var locB = turf.point([b.lon, b.lat]);

        var distanceA = turf.distance(osm_stop_pos, locA, 'kilometers');
        var distanceB = turf.distance(osm_stop_pos, locB, 'kilometers');
        return distanceA - distanceB;
    })
    return {
        'opendata_candidate': sorted_opendata_stops[0],
        'distance': turf.distance(osm_stop_pos, turf.point([sorted_opendata_stops[0].lon, sorted_opendata_stops[0].lat]), 'kilometers') * 1000
    }
}

async function main() {
    var osm_stop_list = await get_osm_info(osm_route_id);
    var opendata_stops = await get_navitia_info(navitia_route_id)

    function extract_ref(elem) {
        return elem['ref'];
    }

    var ref_ok = opendata_stops['opendata_ok'].map(extract_ref);
    var rek_ko = opendata_stops['opendata_ko'].map(extract_ref);

    var stops_div = document.getElementById("stops_details")

    osm_stop_list.forEach(function(current_osm_stop) {

        var balise = document.createElement("DT");
        balise.innerHTML=`<a href='stop.html?osm_stop_id=${current_osm_stop['id']}' target='_blank'>${current_osm_stop['name']}</a>`
        stops_div.appendChild(balise);
        var balise_ext = document.createElement("DD");

        var osm_location = turf.point([current_osm_stop['lon'], current_osm_stop['lat']]);

        if (!current_osm_stop['ref']) {
            var opendata_candidate = find_opendata_closer_stop(osm_location, opendata_stops['opendata_ok'])
            var ref_to_add = opendata_candidate['opendata_candidate']['ref']

            balise_ext.innerHTML=`

            pas encore de ref:FR:STIF

            proposition ${opendata_candidate['opendata_candidate']['name']} à ${opendata_candidate['distance']} mètres

            Ajouter dans JOSM

            `
            stops_div.appendChild(balise_ext);

        } else {
            var refs = current_osm_stop['ref'].split(';')
            var found_match = false;
            balise_ext.innerHTML=""
            refs.forEach(function(one_ref) {
                if (ref_ok.includes(one_ref)) {
                    found_match = true;
                    var opendata_match = opendata_stops['opendata_ok'].filter(function has_this_ref(elem) {
                        return elem['ref'] == one_ref
                    })
                    var opendata_location = turf.point([opendata_match[0]['lon'], opendata_match[0]['lat']]);
                    var distance = turf.distance(osm_location, opendata_location, 'kilometers');

                    balise_ext.innerHTML+=`

                    ref:FR:STIF ${one_ref}

                    arrêt opendata : ${opendata_match[0]['name']}, à ${distance * 1000} m

                    `

                } else if (rek_ko.includes(one_ref)) {
                    balise_ext.innerHTML+=`

                    Ce ref:FR:STIF ${one_ref} appartient à cette ligne mais dans la direction opposée !!

                    Charger cet arrêt dans JOSM

                    `
                } else {
                    balise_ext.innerHTML+=`

                    ref:FR:STIF ${one_ref} d'une autre ligne

                    `
                }
            });
            if (!found_match){
                var opendata_candidate = find_opendata_closer_stop(osm_location, opendata_stops['opendata_ok'])
                var ref_to_add = current_osm_stop['ref'] + ";" + opendata_candidate['opendata_candidate']['ref']
                balise_ext.innerHTML+=`

                proposition ${opendata_candidate['opendata_candidate']['name']} à ${opendata_candidate['distance']} mètres

                Ajouter dans JOSM

                `
            }
            stops_div.appendChild(balise_ext);
        }
    });
}

async function get_osm_info() {
    //TODO : aussi récupérer de quoi afficher des infos sur le parcours
    var stops_params = await get_osm_info_for_this_route(osm_route_id);
    var osm_stop_list = await get_stops_from_osm_routes(stops_params);

    function has_ref(element) {
        return (element['ref'] !== undefined);
    }
    var stops_with_ref = osm_stop_list.filter(has_ref);

    var ref_count = document.createElement("P");
    var t = document.createTextNode(`${stops_with_ref.length} arrêts sur ${osm_stop_list.length} ont un code STIF`);
    ref_count.appendChild(t);
    document.getElementById("route_info").appendChild(ref_count);

    return osm_stop_list

}

async function get_navitia_info() {

    if (navitia_route_id.substr(-2) === "_R" ) {
        var navitia_opposite_route_id = navitia_route_id.substring(0, navitia_route_id.length - 2)
    } else {
        var navitia_opposite_route_id = navitia_route_id + '_R'
    }

    var navitia_stop_list = await get_stops_from_navitia_route(navitia_route_id);
    var navitia_wrong_stop_list = await get_stops_from_navitia_route(navitia_opposite_route_id) || [];
    return {
        'opendata_ok': navitia_stop_list,
        'opendata_ko': navitia_wrong_stop_list
    }
}

async function get_osm_info_for_this_route(osm_relation_route_id) {
    // on vérifie si c'est du transport v1 ou v2
    try {
        var overpass_url = 'https://overpass-api.de/api/interpreter?data=[out:json][timeout:25]; relation(' + osm_relation_route_id + ');out tags;'
        var overpass_response = await fetch(overpass_url);
        var overpass_data = await overpass_response.json();

        var params_appel = []
        for (i = 0; i < overpass_data['elements'].length; i++) {
            var relation_data = overpass_data['elements'][i]
            if (relation_data['tags']['public_transport:version'] == "2") {
                params_appel.push({
                    'id': relation_data['id'],
                    'role': 'platform'
                })
            } else if (relation_data['tags']['public_transport:version'] == "1") {
                params_appel.push({
                    'id': relation_data['id'],
                    'role': 'stop'
                })
            } else {
                alert("Le tag public_transport:version n'est pas renseigné. Il est pourtant nécessaire pour récupérer les arrêts de ce parcours !");
                document.location.href = "http://makinacorpus.github.io/osm-transport-editor/#/" + osm_route_id;
            }
        }
        return (params_appel)

    } catch (err) {
        console.log("erreur en récupérant les infos de la ligne sur OSM via Overpass : " + err)
    }
}

async function get_stops_from_osm_routes(array_with_routes_and_roles) {
    // on reconstruit un appel overpass pour récupérer tous les arrêts des parcours, avec les rôles qu'on a déterminé précédemment
    try {
        //[out:json][timeout:25]; (relation(1103949);node(r:"stop");)->.a;rel(bn);out body;.a out body; (relation(1103948);node(r:"stop");)->.a;rel(bn);out body;.a out body;
        var overpass_url = "https://overpass-api.de/api/interpreter?data=[out:json][timeout:25]; ";
        for (i = 0; i < array_with_routes_and_roles.length; i++) {
            overpass_url += '(relation(' + array_with_routes_and_roles[i]['id'] + ');node(r:"' + array_with_routes_and_roles[i]['role'] + '");)->.a;rel(bn);out body;.a out body;'
        }

        var overpass_response = await fetch(overpass_url);
        var overpass_data = await overpass_response.json();

        var stop_list = []
        var geo = osmtogeojson(overpass_data);
        for (var i = 0; i < geo.features.length; i++) {
            if (geo.features[i].properties['type'] == 'node') {
                var stop_content = {}
                stop_content['id'] = geo.features[i].properties['id'];
                stop_content['name'] = geo.features[i].properties.tags.name || ' pas de nom ';
                stop_content['ref'] = geo.features[i].properties.tags[tag_to_match]
                stop_content['lat'] = geo.features[i]['geometry']['coordinates'][1]
                stop_content['lon'] = geo.features[i]['geometry']['coordinates'][0]

                //récupération des parcours desservis d'après OSM
                stop_content['relations'] = "";
                var deduplicate = [];
                for (j = 0; j < geo.features[i].properties['relations'].length; j++) {
                    if (geo.features[i].properties['relations'][j]['reltags']['type'] == 'route') {
                        rel_name = '[' + (geo.features[i].properties['relations'][j]['reltags']['network'] || '') + '] '
                        rel_name += geo.features[i].properties['relations'][j]['reltags']['ref'] + ' > ' + geo.features[i].properties['relations'][j]['reltags']['to']
                        rel_name += '
'
                        if (deduplicate.indexOf(geo.features[i].properties['relations'][j]['rel']) == -1) {
                            deduplicate.push(geo.features[i].properties['relations'][j]['rel'])
                            stop_content['relations'] += rel_name
                        }
                    }
                }
                stop_list.push(stop_content)
            }
        }

        return stop_list

    } catch (err) {
        console.log("erreur en récupérant les infos de la ligne sur OSM via Overpass : " + err)
    }

}

async function get_stops_from_navitia_route(navitia_route_id) {
    //on récupère tous les arrêts du parcours navitia
    try {
        var navitia_url = "https://api.navitia.io/v1/coverage/fr-idf/routes/" + navitia_route_id + "/stop_points?count=500";
        var navitia_response = await fetch(navitia_url, {
            headers: {
                "Authorization": "Basic " + btoa(navitia_api_key + ":")
            },
        });
        var navitia_data = await navitia_response.json();

        var stop_list = []

        for (var i = 0; i < navitia_data['stop_points'].length; i++) {
            var stop_content = {}
            stop_content['id'] = navitia_data['stop_points'][i]['id'];
            stop_content['name'] = navitia_data['stop_points'][i]['name'];
            stop_content['ref'] = ""
            for (j = 0; j < navitia_data['stop_points'][i]['codes'].length; j++) {
                if (navitia_data['stop_points'][i]['codes'][j]['type'] == "ZDEr_ID_REF_A") {
                    stop_content['ref'] = navitia_data['stop_points'][i]['codes'][j]['value']
                }
            }
            stop_content['lat'] = navitia_data['stop_points'][i]['coord']['lat']
            stop_content['lon'] = navitia_data['stop_points'][i]['coord']['lon']
            stop_list.push(stop_content)
        }
        return (stop_list)

    } catch (err) {
        console.log("erreur en récupérant les infos de la ligne dans l'opendata via navitia : " + err)
    }

}

async function send_to_josm(osm_id, ref_to_add){
    try {
        var josm_url = JOSM_url_base + "n" + osm_id
        if (ref_to_add){
            josm_url += '&addtags=ref:FR:STIF=' + ref_to_add;
        }
        var josm_response = await fetch(josm_url);
    } catch (err) {
        alert("Erreur au chargement dans JOSM (avez-vous lancé JOSM et activé le contrôle à distance ?)")
        console.error(err)
    }

}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.href);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
<commit_msg>ref lignes stif - changement dans les données sources<commit_after>/*
	nlehuby
*/

var osm_route_id = getParameterByName('osm_route_id');
var navitia_route_id = getParameterByName('navitia_route_id');
//var osm_route_id = 1103965;
//var navitia_route_id = 'route:OIF:014014011:11';

var tag_to_match = "ref:FR:STIF";
var JOSM_url_base = "https://localhost:8112/load_object?objects="
main()

function find_opendata_closer_stop(osm_stop_pos, opendata_stops) {
    var sorted_opendata_stops = opendata_stops.sort(function(a, b) {
        var locA = turf.point([a.lon, a.lat]);
        var locB = turf.point([b.lon, b.lat]);

        var distanceA = turf.distance(osm_stop_pos, locA, 'kilometers');
        var distanceB = turf.distance(osm_stop_pos, locB, 'kilometers');
        return distanceA - distanceB;
    })
    return {
        'opendata_candidate': sorted_opendata_stops[0],
        'distance': turf.distance(osm_stop_pos, turf.point([sorted_opendata_stops[0].lon, sorted_opendata_stops[0].lat]), 'kilometers') * 1000
    }
}

async function main() {
    var osm_stop_list = await get_osm_info(osm_route_id);
    var opendata_stops = await get_navitia_info(navitia_route_id)

    function extract_ref(elem) {
        return elem['ref'];
    }

    var ref_ok = opendata_stops['opendata_ok'].map(extract_ref);
    var rek_ko = opendata_stops['opendata_ko'].map(extract_ref);

    var stops_div = document.getElementById("stops_details")

    osm_stop_list.forEach(function(current_osm_stop) {

        var balise = document.createElement("DT");
        balise.innerHTML=`<a href='stop.html?osm_stop_id=${current_osm_stop['id']}' target='_blank'>${current_osm_stop['name']}</a>`
        stops_div.appendChild(balise);
        var balise_ext = document.createElement("DD");

        var osm_location = turf.point([current_osm_stop['lon'], current_osm_stop['lat']]);

        if (!current_osm_stop['ref']) {
            var opendata_candidate = find_opendata_closer_stop(osm_location, opendata_stops['opendata_ok'])
            var ref_to_add = opendata_candidate['opendata_candidate']['ref']

            balise_ext.innerHTML=`

            pas encore de ref:FR:STIF

            proposition ${opendata_candidate['opendata_candidate']['name']} à ${opendata_candidate['distance']} mètres

            Ajouter dans JOSM

            `
            stops_div.appendChild(balise_ext);

        } else {
            var refs = current_osm_stop['ref'].split(';')
            var found_match = false;
            balise_ext.innerHTML=""
            refs.forEach(function(one_ref) {
                if (ref_ok.includes(one_ref)) {
                    found_match = true;
                    var opendata_match = opendata_stops['opendata_ok'].filter(function has_this_ref(elem) {
                        return elem['ref'] == one_ref
                    })
                    var opendata_location = turf.point([opendata_match[0]['lon'], opendata_match[0]['lat']]);
                    var distance = turf.distance(osm_location, opendata_location, 'kilometers');

                    balise_ext.innerHTML+=`

                    ref:FR:STIF ${one_ref}

                    arrêt opendata : ${opendata_match[0]['name']}, à ${distance * 1000} m

                    `

                } else if (rek_ko.includes(one_ref)) {
                    balise_ext.innerHTML+=`

                    Ce ref:FR:STIF ${one_ref} appartient à cette ligne mais dans la direction opposée !!

                    Charger cet arrêt dans JOSM

                    `
                } else {
                    balise_ext.innerHTML+=`

                    ref:FR:STIF ${one_ref} d'une autre ligne

                    `
                }
            });
            if (!found_match){
                var opendata_candidate = find_opendata_closer_stop(osm_location, opendata_stops['opendata_ok'])
                var ref_to_add = current_osm_stop['ref'] + ";" + opendata_candidate['opendata_candidate']['ref']
                balise_ext.innerHTML+=`

                proposition ${opendata_candidate['opendata_candidate']['name']} à ${opendata_candidate['distance']} mètres

                Ajouter dans JOSM

                `
            }
            stops_div.appendChild(balise_ext);
        }
    });
}

async function get_osm_info() {
    //TODO : aussi récupérer de quoi afficher des infos sur le parcours
    var stops_params = await get_osm_info_for_this_route(osm_route_id);
    var osm_stop_list = await get_stops_from_osm_routes(stops_params);

    function has_ref(element) {
        return (element['ref'] !== undefined);
    }
    var stops_with_ref = osm_stop_list.filter(has_ref);

    var ref_count = document.createElement("P");
    var t = document.createTextNode(`${stops_with_ref.length} arrêts sur ${osm_stop_list.length} ont un code STIF`);
    ref_count.appendChild(t);
    document.getElementById("route_info").appendChild(ref_count);

    return osm_stop_list

}

async function get_navitia_info() {

    if (navitia_route_id.substr(-1) === "R" ) {
        var navitia_opposite_route_id = navitia_route_id.substring(0, navitia_route_id.length - 1) + "A"
    } else {
        var navitia_opposite_route_id = navitia_route_id.substring(0, navitia_route_id.length - 1) + "R"
    }

    var navitia_stop_list = await get_stops_from_navitia_route(navitia_route_id);
    var navitia_wrong_stop_list = await get_stops_from_navitia_route(navitia_opposite_route_id) || [];
    return {
        'opendata_ok': navitia_stop_list,
        'opendata_ko': navitia_wrong_stop_list
    }
}

async function get_osm_info_for_this_route(osm_relation_route_id) {
    // on vérifie si c'est du transport v1 ou v2
    try {
        var overpass_url = 'https://overpass-api.de/api/interpreter?data=[out:json][timeout:25]; relation(' + osm_relation_route_id + ');out tags;'
        var overpass_response = await fetch(overpass_url);
        var overpass_data = await overpass_response.json();

        var params_appel = []
        for (i = 0; i < overpass_data['elements'].length; i++) {
            var relation_data = overpass_data['elements'][i]
            if (relation_data['tags']['public_transport:version'] == "2") {
                params_appel.push({
                    'id': relation_data['id'],
                    'role': 'platform'
                })
            } else if (relation_data['tags']['public_transport:version'] == "1") {
                params_appel.push({
                    'id': relation_data['id'],
                    'role': 'stop'
                })
            } else {
                alert("Le tag public_transport:version n'est pas renseigné. Il est pourtant nécessaire pour récupérer les arrêts de ce parcours !");
                document.location.href = "http://makinacorpus.github.io/osm-transport-editor/#/" + osm_route_id;
            }
        }
        return (params_appel)

    } catch (err) {
        console.log("erreur en récupérant les infos de la ligne sur OSM via Overpass : " + err)
    }
}

async function get_stops_from_osm_routes(array_with_routes_and_roles) {
    // on reconstruit un appel overpass pour récupérer tous les arrêts des parcours, avec les rôles qu'on a déterminé précédemment
    try {
        //[out:json][timeout:25]; (relation(1103949);node(r:"stop");)->.a;rel(bn);out body;.a out body; (relation(1103948);node(r:"stop");)->.a;rel(bn);out body;.a out body;
        var overpass_url = "https://overpass-api.de/api/interpreter?data=[out:json][timeout:25]; ";
        for (i = 0; i < array_with_routes_and_roles.length; i++) {
            overpass_url += '(relation(' + array_with_routes_and_roles[i]['id'] + ');node(r:"' + array_with_routes_and_roles[i]['role'] + '");)->.a;rel(bn);out body;.a out body;'
        }

        var overpass_response = await fetch(overpass_url);
        var overpass_data = await overpass_response.json();

        var stop_list = []
        var geo = osmtogeojson(overpass_data);
        for (var i = 0; i < geo.features.length; i++) {
            if (geo.features[i].properties['type'] == 'node') {
                var stop_content = {}
                stop_content['id'] = geo.features[i].properties['id'];
                stop_content['name'] = geo.features[i].properties.tags.name || ' pas de nom ';
                stop_content['ref'] = geo.features[i].properties.tags[tag_to_match]
                stop_content['lat'] = geo.features[i]['geometry']['coordinates'][1]
                stop_content['lon'] = geo.features[i]['geometry']['coordinates'][0]

                //récupération des parcours desservis d'après OSM
                stop_content['relations'] = "";
                var deduplicate = [];
                for (j = 0; j < geo.features[i].properties['relations'].length; j++) {
                    if (geo.features[i].properties['relations'][j]['reltags']['type'] == 'route') {
                        rel_name = '[' + (geo.features[i].properties['relations'][j]['reltags']['network'] || '') + '] '
                        rel_name += geo.features[i].properties['relations'][j]['reltags']['ref'] + ' > ' + geo.features[i].properties['relations'][j]['reltags']['to']
                        rel_name += '
'
                        if (deduplicate.indexOf(geo.features[i].properties['relations'][j]['rel']) == -1) {
                            deduplicate.push(geo.features[i].properties['relations'][j]['rel'])
                            stop_content['relations'] += rel_name
                        }
                    }
                }
                stop_list.push(stop_content)
            }
        }

        return stop_list

    } catch (err) {
        console.log("erreur en récupérant les infos de la ligne sur OSM via Overpass : " + err)
    }

}

async function get_stops_from_navitia_route(navitia_route_id) {
    //on récupère tous les arrêts du parcours navitia
    try {
        var navitia_url = "https://api.navitia.io/v1/coverage/fr-idf/routes/" + navitia_route_id + "/stop_points?count=500";
        var navitia_response = await fetch(navitia_url, {
            headers: {
                "Authorization": "Basic " + btoa(navitia_api_key + ":")
            },
        });
        var navitia_data = await navitia_response.json();

        var stop_list = []

        for (var i = 0; i < navitia_data['stop_points'].length; i++) {
            var stop_content = {}
            stop_content['id'] = navitia_data['stop_points'][i]['id'];
            stop_content['name'] = navitia_data['stop_points'][i]['name'];
            stop_content['ref'] = ""
            for (j = 0; j < navitia_data['stop_points'][i]['codes'].length; j++) {
                if (navitia_data['stop_points'][i]['codes'][j]['type'] == "ZDEr_ID_REF_A") {
                    stop_content['ref'] = navitia_data['stop_points'][i]['codes'][j]['value']
                }
            }
            stop_content['lat'] = navitia_data['stop_points'][i]['coord']['lat']
            stop_content['lon'] = navitia_data['stop_points'][i]['coord']['lon']
            stop_list.push(stop_content)
        }
        return (stop_list)

    } catch (err) {
        console.log("erreur en récupérant les infos de la ligne dans l'opendata via navitia : " + err)
    }

}

async function send_to_josm(osm_id, ref_to_add){
    try {
        var josm_url = JOSM_url_base + "n" + osm_id
        if (ref_to_add){
            josm_url += '&addtags=ref:FR:STIF=' + ref_to_add;
        }
        var josm_response = await fetch(josm_url);
    } catch (err) {
        alert("Erreur au chargement dans JOSM (avez-vous lancé JOSM et activé le contrôle à distance ?)")
        console.error(err)
    }

}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.href);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
<|endoftext|>


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

const yargs = require('yargs')
const scriptUtil = require('./script-util.js')

let startTime = process.hrtime()

let arg = yargs
  .option('zcl', {
    desc: 'Specifies zcl metafile file to be used.',
    alias: 'z',
    type: 'string',
    demandOption: true,
  })
  .option('out', {
    desc: 'Output directory where the generated files will go.',
    alias: 'o',
    type: 'string',
    demandOption: true,
  })
  .option('generationTemplate', {
    desc: 'Specifies gen-template.json file to be used.',
    alias: 'g',
    type: 'string',
    demandOption: true,
  })
  .option('in', {
    desc: 'Input .zap file from which to read configuration.',
    alias: 'i',
    type: 'string',
    demandOption: false,
  })
  .option('stateDirectory', {
    desc: 'State directory',
    type: 'string',
    demandOption: false,
    default: '~/.zap',
  })
  .demandOption(
    ['zcl', 'out', 'generationTemplate'],
    'Please provide required options!'
  )
  .help()
  .wrap(null).argv

let ctx = {}

let cli = [
  'src-electron/main-process/electron-main.js',
  'generate',
  '--noUi',
  '--reuseZapInstance',
  '--zcl',
  arg.zcl,
  '--generationTemplate',
  arg.generationTemplate,
  '--out',
  arg.out,
]
if (arg.in != null) {
  cli.push(arg.in)
}

scriptUtil
  .stampVersion()
  .then(() => scriptUtil.executeCmd(ctx, 'electron', cli))
  .then(() => {
    let endTime = process.hrtime(startTime)
    console.log(
      `😎 All done: ${endTime[0]}s, ${Math.round(endTime[1] / 1000000)}ms.`
    )
    process.exit(0)
  })
  .catch((code) => {
    process.exit(code)
  })
<commit_msg>Fix the multi-generation issue.<commit_after>#!/usr/bin/env node
/**
 *
 *    Copyright (c) 2020 Silicon Labs
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

const yargs = require('yargs')
const scriptUtil = require('./script-util.js')

let startTime = process.hrtime()

let arg = yargs
  .option('zcl', {
    desc: 'Specifies zcl metafile file to be used.',
    alias: 'z',
    type: 'string',
    demandOption: true,
  })
  .option('out', {
    desc: 'Output directory where the generated files will go.',
    alias: 'o',
    type: 'string',
    demandOption: true,
  })
  .option('generationTemplate', {
    desc: 'Specifies gen-template.json file to be used.',
    alias: 'g',
    type: 'string',
    demandOption: true,
  })
  .option('in', {
    desc: 'Input .zap file from which to read configuration.',
    alias: 'i',
    type: 'string',
    demandOption: false,
  })
  .option('stateDirectory', {
    desc: 'State directory',
    type: 'string',
    demandOption: false,
    default: '~/.zap',
  })
  .demandOption(
    ['zcl', 'out', 'generationTemplate'],
    'Please provide required options!'
  )
  .help()
  .wrap(null).argv

let ctx = {}

let cli = [
  'src-electron/main-process/electron-main.js',
  'generate',
  '--noUi',
  '--zcl',
  arg.zcl,
  '--generationTemplate',
  arg.generationTemplate,
  '--out',
  arg.out,
]
if (arg.in != null) {
  cli.push(arg.in)
}

scriptUtil
  .stampVersion()
  .then(() => scriptUtil.executeCmd(ctx, 'node', cli))
  .then(() => {
    let endTime = process.hrtime(startTime)
    console.log(
      `😎 All done: ${endTime[0]}s, ${Math.round(endTime[1] / 1000000)}ms.`
    )
    process.exit(0)
  })
  .catch((code) => {
    process.exit(code)
  })
<|endoftext|>


<commit_before>// TODO: Move state to somewhere more appropriate
import mapValues from 'lodash/mapValues'

export const FRYER_CONNECTED = 'FRYER_CONNECTED'

export const connected = () => ({
  payload: null,
  type: FRYER_CONNECTED
})

export const FRYER_DISCONNECTED = 'FRYER_DISCONNECTED'

export const disconnected = () => ({
  payload: null,
  type: FRYER_DISCONNECTED
})

export const FRYER_ADD_DONUTS = 'FRYER_ADD_DONUTS'

export const addDonuts = (donuts) => ({
  payload: donuts,
  type: FRYER_ADD_DONUTS
})

export const FRYER_ADD_ERROR = 'FRYER_ADD_ERROR'

export const addError = (error) => ({
  payload: error,
  type: FRYER_ADD_ERROR
})

export const FRYER_REMOVE_ERROR = 'FRYER_REMOVE_ERROR'

export const removeError = (index) => ({
  payload: index,
  type: FRYER_REMOVE_ERROR
})

export const FRYER_SET_MODELS = 'FRYER_SET_MODELS'

export const setModels = (models) => ({
  payload: models,
  type: FRYER_SET_MODELS
})

const initialState = {
  connected: false,
  donuts: [],
  errors: [],
  models: null
}

export default function reducer (state = initialState, { payload, type }) {
  switch (type) {
    case FRYER_CONNECTED:
      return {
        ...state,
        connected: true
      }
    case FRYER_DISCONNECTED:
      return {
        ...state,
        connected: false
      }
    case FRYER_REMOVE_ERROR:
      return {
        ...state,
        errors: state.errors.filter((e, index) => index !== payload)
      }
    case FRYER_ADD_ERROR:
      return {
        ...state,
        errors: [...state.errors, payload]
      }
    case FRYER_ADD_DONUTS:
      return {
        ...state,
        donuts: payload
      }
    case FRYER_SET_MODELS:
      return {
        ...state,
        models: mapValues(payload, (model, name) => {
          const oldModel = state.models && state.models[name]

          // Only use a model if it's better than its previous iteration
          return !oldModel || model.score > oldModel.score
            ? model
            : oldModel
        })
      }
    default:
      return state
  }
}
<commit_msg>fix(ui): correct model freshness to work from indicator<commit_after>// TODO: Move state to somewhere more appropriate
import mapValues from 'lodash/mapValues'
import { getIndicator } from 'donut-common/src/rater'

export const FRYER_CONNECTED = 'FRYER_CONNECTED'

export const connected = () => ({
  payload: null,
  type: FRYER_CONNECTED
})

export const FRYER_DISCONNECTED = 'FRYER_DISCONNECTED'

export const disconnected = () => ({
  payload: null,
  type: FRYER_DISCONNECTED
})

export const FRYER_ADD_DONUTS = 'FRYER_ADD_DONUTS'

export const addDonuts = (donuts) => ({
  payload: donuts,
  type: FRYER_ADD_DONUTS
})

export const FRYER_ADD_ERROR = 'FRYER_ADD_ERROR'

export const addError = (error) => ({
  payload: error,
  type: FRYER_ADD_ERROR
})

export const FRYER_REMOVE_ERROR = 'FRYER_REMOVE_ERROR'

export const removeError = (index) => ({
  payload: index,
  type: FRYER_REMOVE_ERROR
})

export const FRYER_SET_MODELS = 'FRYER_SET_MODELS'

export const setModels = (models) => ({
  payload: models,
  type: FRYER_SET_MODELS
})

const initialState = {
  connected: false,
  donuts: [],
  errors: [],
  models: null
}

export default function reducer (state = initialState, { payload, type }) {
  switch (type) {
    case FRYER_CONNECTED:
      return {
        ...state,
        connected: true
      }
    case FRYER_DISCONNECTED:
      return {
        ...state,
        connected: false
      }
    case FRYER_REMOVE_ERROR:
      return {
        ...state,
        errors: state.errors.filter((e, index) => index !== payload)
      }
    case FRYER_ADD_ERROR:
      return {
        ...state,
        errors: [...state.errors, payload]
      }
    case FRYER_ADD_DONUTS:
      return {
        ...state,
        donuts: payload
      }
    case FRYER_SET_MODELS:
      return {
        ...state,
        models: mapValues(payload, (model, name) => {
          const oldModel = state.models && state.models[name]

          // Only use a model if it's better than its previous iteration
          return !oldModel || (getIndicator(model.donut) > getIndicator(oldModel.donut))
            ? model
            : oldModel
        })
      }
    default:
      return state
  }
}
<|endoftext|>


<commit_before>var gulp         = require('gulp'),
    gulpSequence = require('gulp-sequence'),
    colors       = require('colors'),
    del          = require('del'),
    config       = require('../config');

gulp.task('build', function(cb) {
  process.env.NODE_ENV = 'production';
  gulpSequence(
    'karma',
    'clean',
    ['fonts', 'images', 'iconFont'],
    ['postCss', 'jade', 'webpack:production'],
    'rev',
    'cleanTemp',
    'complete',
    cb)
});

gulp.task('cleanTemp', function (cb) {
  del([
    config.publicTemp,
  ], cb);
});

gulp.task('complete', function() {
  console.log('Project Succsess.'.bold.bgRed);
  console.log('Project Succsess.'.bold.bgWhite);
  console.log('Project Succsess.'.bold.bgBlue);
});

<commit_msg>end process upon build<commit_after>var gulp         = require('gulp'),
    gulpSequence = require('gulp-sequence'),
    colors       = require('colors'),
    del          = require('del'),
    config       = require('../config');

gulp.task('build', function(cb) {
  process.env.NODE_ENV = 'production';
  gulpSequence(
    'karma',
    'clean',
    ['fonts', 'images', 'iconFont'],
    ['postCss', 'jade', 'webpack:production'],
    'rev',
    'cleanTemp',
    'complete',
    cb)
});

gulp.task('cleanTemp', function (cb) {
  del([
    config.publicTemp,
  ], cb);
});

gulp.task('complete', function() {
  console.log('Project Succsess.'.bold.bgRed);
  console.log('Project Succsess.'.bold.bgWhite);
  console.log('Project Succsess.'.bold.bgBlue);
  process.exit();
});

<|endoftext|>