<commit_before>#!/usr/bin/env node
"use strict";
import * as prompt from 'prompt';
import * as chalk from 'chalk';
import * as request from 'request';
import * as path from 'path';
import * as expandTilde from 'expand-tilde';

import {run} from './run';
import {testRun} from './test-run';
import {success, failure, details, section} from './logging';
import {mkdir, doesntExist} from './fs';

console.log(chalk.bold.cyan('Jupyter dev install tool'));
console.log(chalk.bold.cyan('Wizard for setting up a Jupyter development environment'));

var orgRepos = [
    'ipython/traitlets',
    'ipython/ipython',
    'jupyter/jupyter_core',
    'jupyter/jupyter_client',
    'ipython/ipykernel',
    'jupyter/jupyter_console',
    'jupyter/qtconsole',
    'jupyter/nbformat',
    'jupyter/notebook',
    'ipython/ipywidgets',
    'jupyter/nbconvert'
];
var repos = orgRepos.map(x => x.split('/')[1]);
var orgs = orgRepos.map(x => x.split('/')[0]).filter((x, i, self) => self.indexOf(x) === i);

if (process.argv.length < 4) {
    console.error('Usage: jupyter-devinstall <githubUserName> <installDir> [--overwrite] [--reinstall] [--global]');
    process.exit(1);
}
var githubName = process.argv[2];
var installdir = process.argv[3];

// Get extra flags
let flags = {};
if (process.argv.length > 4) {
    let extraArgs = process.argv.slice(4);
    extraArgs.forEach(arg => {
        if (arg.length>2 && arg.slice(0,2) === '--') {
            flags[arg.slice(2)] = true;
        }
    });
}

let downloaded;
let defaultInstallScope = flags.global ? 'g' : 'l';
if (flags.reinstall) {
    downloaded = Promise.resolve({install: defaultInstallScope});
} else {
    downloaded = Promise.resolve().then(() => {
        section('Checking github repositories');

        function findRepo(org, repo, original) {
            let orgRepo = org + '/' + repo;
            return new Promise((resolve, reject) => {
                request('http://github.com/' + orgRepo, function(error, response, body) {
                    if (!error && response.statusCode == 200) {
                        success(orgRepo + ' on GitHub');
                        resolve(body);
                    } else {
                        failure(orgRepo + ' on GitHub');
                        details('Use github.com to fork ' + original + ' to ' + orgRepo);
                        reject(error || response.statusCode);
                    }
                });
            });
        }

        return Promise.all(repos.map((x, i) => findRepo(githubName, x, orgRepos[i])));
    }).catch(err => {
        process.exit(1);
    }).then(() => {
        section('Checking system requirements');

        return Promise.all([
            testRun('git --version'),
            testRun('python --version'),
            testRun('python -m pip --version', 'pip'),
            testRun('node --version'),
            testRun('npm --version'),
            testRun(`python -c "import zmq"`, 'pyzmq', `\`pyzmq\` not installed for \`python\`.  Please install pyzmq for python.
    Before installing pyzmq, you may need to install python and zmq dev packages (\`python-dev\` and \`libzmq-dev\` on debian based distros).`),
            testRun(`python -c "import pycurl"`, 'pycurl', `\`pycurl\` not installed for \`python\`.  Please install pycurl for python.
    Before installing pycurl, you may need \`libcurl4-openssl-dev\` on debian based distros or \`libcurl-devel\` on slackware based distros.`)
        ]);

    }).then(() => {
        if (flags.overwrite) {
            return;
        }

        section('Checking destination');

        return Promise.all(orgs.map(org => {

            return doesntExist(path.resolve(expandTilde(installdir), org)).then(() => {
                success(org + ' doesn\'t exist yet');
            }).catch(err => {
                // failure(org + ' doesn\'t exist yet');
                return new Promise(resolve => {
                    prompt.start();
                    prompt.get({
                        properties: {
                            overwrite: {
                                description: 'ipython and/or jupyter already exist in the destination, overwrite them? (y)es or (n)o',
                                required: true,
                                pattern: /[yn]/,
                                message: '(y)es or (n)o',
                                default: 'n'
                            },
                        }
                    }, function (err, result) {
                        if (err || result.overwrite !== 'y') {
                            console.error('\nUser exit');
                            process.exit(1);
                        }
                        resolve();
                    });
                });
            });
        }));
    }).then(() => {
        section('Config');

        return new Promise(resolve => {
            prompt.start();
            prompt.get({
                properties: {
                    upstream: {
                        description: 'Enter the name you want to use for the git remote that targets upstream',
                        required: false,
                        default: 'upstream'
                    },
                    install: {
                        description: 'Do you want the Python contents to be installed (l)ocally, (g)lobally, or (n)ot at all?',
                        required: false,
                        pattern: /[lgn]/,
                        message: '(l)ocally, (g)lobally, or (n)ot at all',
                        default: defaultInstallScope
                    }
                }
            }, function (err, result) {
                if (err) {
                    console.error('\nUser exit');
                    process.exit(1);
                }
                resolve(result);
            });
        }).catch((err) => {
            console.error(chalk.bgRed('error while configuring'), err);
        });

    }).then(config => {
        section('Downloading');

        return Promise.all(orgs.map(org => {
            return mkdir(path.resolve(expandTilde(installdir), org)).then(() => {
                success(org + ' org dir exists');
            }).catch(err => {
                failure(org + ' org dir exists');
                throw Error();
            });
        })).then(() => config);
    }).then(config => {

        return Promise.all(orgRepos.map((orgRepo, i) => {
            let url;
            // url = 'git@github.com:' + githubName + '/' + repos[i] + '.git';
            url = 'https://github.com/' + githubName + '/' + repos[i] + '.git';

            let dir = path.resolve(expandTilde(installdir), orgRepo);
            return run('git clone ' + url + ' ' + dir).then(() => {
                success(orgRepo + ' cloned');
            }).catch(err => {
                failure(orgRepo + ' cloned');
            }).then(() => {
                return run('git -C ' + dir + ' remote add ' + config.upstream + ' https://github.com/' + orgRepo + '.git');
            }).then(() => {
                success(orgRepo + ' ' + config.upstream + ' remote added');
            }).catch(err => {
                failure(orgRepo + ' ' + config.upstream + ' remote added');
            }).then(() => {
                return run('git -C ' + dir + ' remote update');
            }).then(() => {
                success(orgRepo + ' remotes updated');
            }).catch(err => {
                failure(orgRepo + ' remotes updated');
            }).then(() => {
                return run('git -C ' + dir + ' checkout ' + config.upstream + '/master');
            }).then(() => {
                success(orgRepo + ' master checked out');
            }).catch(err => {
                failure(orgRepo + ' master checked out');
            });
        })).then(() => config);
    }).catch(err => {
        console.error('Unhandled error');
        console.error(err);
        process.exit(1);

    });
}

downloaded.then(config => {
    if (config.install === 'l' || config.install === 'g') {
        let chain = Promise.resolve();
        for (let i = 0; i < orgRepos.length; i++) {
            let orgRepo = orgRepos[i];
            let localFlag = (config.install === 'l') ? '--user ' : '';
            let shell = 'python -m pip install ' + localFlag + '-e ' + path.resolve(expandTilde(installdir), orgRepo);
            chain = chain.then(() => run(shell)).then(stdout => {
                success(orgRepo + ' installed');
                details(stdout);
            }).catch(err => {
                failure(orgRepo + ' installed');
                console.error(err);
                process.exit(1);
            });
        }

        chain.then(() => {
            console.log(chalk.green.bold('Installation was a success!  You can launch the notebook by running `python -m notebook`'));
        });
    }
});
<commit_msg>jupyter metapackage and devinstall<commit_after>#!/usr/bin/env node
"use strict";
import * as prompt from 'prompt';
import * as chalk from 'chalk';
import * as request from 'request';
import * as path from 'path';
import * as expandTilde from 'expand-tilde';

import {run} from './run';
import {testRun} from './test-run';
import {success, failure, details, section} from './logging';
import {mkdir, doesntExist} from './fs';

console.log(chalk.bold.cyan('Jupyter dev install tool'));
console.log(chalk.bold.cyan('Wizard for setting up a Jupyter development environment'));

var orgRepos = [
    'ipython/traitlets',
    'ipython/ipython',
    'jupyter/jupyter_core',
    'jupyter/jupyter_client',
    'ipython/ipykernel',
    'jupyter/jupyter_console',
    'jupyter/qtconsole',
    'jupyter/nbformat',
    'jupyter/notebook',
    'ipython/ipywidgets',
    'jupyter/jupyter',
    'jovyan/jupyter-devinstall',
];
var repos = orgRepos.map(x => x.split('/')[1]);
var orgs = orgRepos.map(x => x.split('/')[0]).filter((x, i, self) => self.indexOf(x) === i);

if (process.argv.length < 4) {
    console.error('Usage: jupyter-devinstall <githubUserName> <installDir> [--overwrite] [--reinstall] [--global]');
    process.exit(1);
}
var githubName = process.argv[2];
var installdir = process.argv[3];

// Get extra flags
let flags = {};
if (process.argv.length > 4) {
    let extraArgs = process.argv.slice(4);
    extraArgs.forEach(arg => {
        if (arg.length>2 && arg.slice(0,2) === '--') {
            flags[arg.slice(2)] = true;
        }
    });
}

let downloaded;
let defaultInstallScope = flags.global ? 'g' : 'l';
if (flags.reinstall) {
    downloaded = Promise.resolve({install: defaultInstallScope});
} else {
    downloaded = Promise.resolve().then(() => {
        section('Checking github repositories');

        function findRepo(org, repo, original) {
            let orgRepo = org + '/' + repo;
            return new Promise((resolve, reject) => {
                request('http://github.com/' + orgRepo, function(error, response, body) {
                    if (!error && response.statusCode == 200) {
                        success(orgRepo + ' on GitHub');
                        resolve(body);
                    } else {
                        failure(orgRepo + ' on GitHub');
                        details('Use github.com to fork ' + original + ' to ' + orgRepo);
                        reject(error || response.statusCode);
                    }
                });
            });
        }

        return Promise.all(repos.map((x, i) => findRepo(githubName, x, orgRepos[i])));
    }).catch(err => {
        process.exit(1);
    }).then(() => {
        section('Checking system requirements');

        return Promise.all([
            testRun('git --version'),
            testRun('python --version'),
            testRun('python -m pip --version', 'pip'),
            testRun('node --version'),
            testRun('npm --version'),
            testRun(`python -c "import zmq"`, 'pyzmq', `\`pyzmq\` not installed for \`python\`.  Please install pyzmq for python.
    Before installing pyzmq, you may need to install python and zmq dev packages (\`python-dev\` and \`libzmq-dev\` on debian based distros).`),
            testRun(`python -c "import pycurl"`, 'pycurl', `\`pycurl\` not installed for \`python\`.  Please install pycurl for python.
    Before installing pycurl, you may need \`libcurl4-openssl-dev\` on debian based distros or \`libcurl-devel\` on slackware based distros.`)
        ]);

    }).then(() => {
        if (flags.overwrite) {
            return;
        }

        section('Checking destination');

        return Promise.all(orgs.map(org => {

            return doesntExist(path.resolve(expandTilde(installdir), org)).then(() => {
                success(org + ' doesn\'t exist yet');
            }).catch(err => {
                // failure(org + ' doesn\'t exist yet');
                return new Promise(resolve => {
                    prompt.start();
                    prompt.get({
                        properties: {
                            overwrite: {
                                description: 'ipython and/or jupyter and/or jovyan already exist in the destination, overwrite them? (y)es or (n)o',
                                required: true,
                                pattern: /[yn]/,
                                message: '(y)es or (n)o',
                                default: 'n'
                            },
                        }
                    }, function (err, result) {
                        if (err || result.overwrite !== 'y') {
                            console.error('\nUser exit');
                            process.exit(1);
                        }
                        resolve();
                    });
                });
            });
        }));
    }).then(() => {
        section('Config');

        return new Promise(resolve => {
            prompt.start();
            prompt.get({
                properties: {
                    upstream: {
                        description: 'Enter the name you want to use for the git remote that targets upstream',
                        required: false,
                        default: 'upstream'
                    },
                    install: {
                        description: 'Do you want the Python contents to be installed (l)ocally, (g)lobally, or (n)ot at all?',
                        required: false,
                        pattern: /[lgn]/,
                        message: '(l)ocally, (g)lobally, or (n)ot at all',
                        default: defaultInstallScope
                    }
                }
            }, function (err, result) {
                if (err) {
                    console.error('\nUser exit');
                    process.exit(1);
                }
                resolve(result);
            });
        }).catch((err) => {
            console.error(chalk.bgRed('error while configuring'), err);
        });

    }).then(config => {
        section('Downloading');

        return Promise.all(orgs.map(org => {
            return mkdir(path.resolve(expandTilde(installdir), org)).then(() => {
                success(org + ' org dir exists');
            }).catch(err => {
                failure(org + ' org dir exists');
                throw Error();
            });
        })).then(() => config);
    }).then(config => {

        return Promise.all(orgRepos.map((orgRepo, i) => {
            let url;
            // url = 'git@github.com:' + githubName + '/' + repos[i] + '.git';
            url = 'https://github.com/' + githubName + '/' + repos[i] + '.git';

            let dir = path.resolve(expandTilde(installdir), orgRepo);
            return run('git clone ' + url + ' ' + dir).then(() => {
                success(orgRepo + ' cloned');
            }).catch(err => {
                failure(orgRepo + ' cloned');
            }).then(() => {
                return run('git -C ' + dir + ' remote add ' + config.upstream + ' https://github.com/' + orgRepo + '.git');
            }).then(() => {
                success(orgRepo + ' ' + config.upstream + ' remote added');
            }).catch(err => {
                failure(orgRepo + ' ' + config.upstream + ' remote added');
            }).then(() => {
                return run('git -C ' + dir + ' remote update');
            }).then(() => {
                success(orgRepo + ' remotes updated');
            }).catch(err => {
                failure(orgRepo + ' remotes updated');
            }).then(() => {
                return run('git -C ' + dir + ' checkout ' + config.upstream + '/master');
            }).then(() => {
                success(orgRepo + ' master checked out');
            }).catch(err => {
                failure(orgRepo + ' master checked out');
            });
        })).then(() => config);
    }).catch(err => {
        console.error('Unhandled error');
        console.error(err);
        process.exit(1);

    });
}

downloaded.then(config => {
    if (config.install === 'l' || config.install === 'g') {
        let chain = Promise.resolve();
        for (let i = 0; i < orgRepos.length; i++) {
            let orgRepo = orgRepos[i];
            let localFlag = (config.install === 'l') ? '--user ' : '';
            let shell = 'python -m pip install ' + localFlag + '-e ' + path.resolve(expandTilde(installdir), orgRepo);
            chain = chain.then(() => run(shell)).then(stdout => {
                success(orgRepo + ' installed');
                details(stdout);
            }).catch(err => {
                failure(orgRepo + ' installed');
                console.error(err);
                process.exit(1);
            });
        }

        chain.then(() => {
            console.log(chalk.green.bold('Installation was a success!  You can launch the notebook by running `python -m notebook`'));
        });
    }
});
<|endoftext|>


<commit_before>require('../node_modules/openlayers/dist/ol.css');
require('./index.css');

var ol = require('openlayers');

var map = new ol.Map({
  controls: ol.control.defaults({attributionOptions: {collapsible: false}}),
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([16.373064, 48.20833]),
    zoom: 13
  })
});
<commit_msg>WFS-T and Geoserver insteadt of php to save the form<commit_after>require('../node_modules/openlayers/dist/ol.css');
require('./index.css');

var ol = require('openlayers');

var map = new ol.Map({
  controls: ol.control.defaults({attributionOptions: {collapsible: false}}),
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([16.373064, 48.20833]),
    zoom: 13
  })
});

var url = 'http://student.ifip.tuwien.ac.at/geoserver/wfs';
var layer = 'feedback';
var prefix = 'g04_2015'; // Ersetzen durch euren Arbeitsbereich-Namen
var featureNS = 'http://g04/2015'; // Ersetzen durch eure Namensraum-URI
var form = document.getElementById('feedback');

var feature = new ol.Feature();
feature.setGeometryName('geom');
feature.setGeometry(new ol.geom.Point(map.getView().getCenter()));

var send = require('./feedback_send');
send(form, feature, url, {
  featureType: layer,
  featurePrefix: prefix,
  featureNS: featureNS,
  srsName: map.getView().getProjection().getCode()
});
<|endoftext|>


<commit_before>/* global process */
'use strict'

process.env.FORCE_COLOR = true // Force colors for packages that depend on https://www.npmjs.com/package/supports-color

const sgf = require('staged-git-files')
const minimatch = require('minimatch')
const assign = require('object-assign')
const appRoot = require('app-root-path')
const config = require(appRoot.resolve('package.json'))
const runScript = require('./runScript')
const Listr = require('listr')
const path = require('path')

const defaultLinters = {}
const customLinters = config['lint-staged']['linters'] !== undefined ? config['lint-staged']['linters'] : config['lint-staged']
const linters = assign(defaultLinters, customLinters)

// If git root is defined -> Set git root as sgf's cwd
if (config['lint-staged']['git-root'] !== undefined) {
    sgf.cwd = path.resolve(config['lint-staged']['git-root'])
}
sgf('ACM', function (err, results) {
    if (err) {
        console.error(err)
    }
    const filePaths = results.map(file => file.filename)
    const tasks = Object.keys(linters).map(key => {
        const linter = linters[key]
        const fileList = filePaths.filter(minimatch.filter(key, { matchBase: true }))
        if (fileList.length) {
            // If current working directory is not the git root -> resolve file paths accordingly
            if (sgf.cwd !== process.cwd()) {
                var relpath = path.relative(process.cwd(), sgf.cwd) + '/'
                for (var i in fileList) {
                    fileList[i] = path.resolve(relpath + fileList[i])
                }
            }
            return {
                title: `Running tasks for ${key}`,
                task: () => {
                    return new Listr(runScript(linter, fileList, config))
                }
            }
        }
    }).filter(task => typeof task !== 'undefined') // Filter undefined values

    if (tasks.length) {
        new Listr(tasks).run().catch(err => {
            console.error(err)
            process.exit(1)
        })
    }
})

<commit_msg>Slight changes to avoid problems for windows users<commit_after>/* global process */
'use strict'

process.env.FORCE_COLOR = true // Force colors for packages that depend on https://www.npmjs.com/package/supports-color

const sgf = require('staged-git-files')
const minimatch = require('minimatch')
const assign = require('object-assign')
const appRoot = require('app-root-path')
const config = require(appRoot.resolve('package.json'))
const runScript = require('./runScript')
const Listr = require('listr')
const path = require('path')

const defaultLinters = {}
const customLinters = config['lint-staged']['linters'] !== undefined ? config['lint-staged']['linters'] : config['lint-staged']
const linters = assign(defaultLinters, customLinters)

// If git root is defined -> Set git root as sgf's cwd
if (config['lint-staged']['git-root'] !== undefined) {
    sgf.cwd = path.resolve(config['lint-staged']['git-root'])
}
sgf('ACM', function (err, results) {
    if (err) {
        console.error(err)
    }
    const filePaths = results.map(file => file.filename)
    const tasks = Object.keys(linters).map(key => {
        const linter = linters[key]
        const fileList = filePaths.filter(minimatch.filter(key, { matchBase: true }))
        if (fileList.length) {
            // If current working directory is not the git root -> resolve file paths accordingly
            if (sgf.cwd !== process.cwd()) {
                var relpath = path.relative(process.cwd(), sgf.cwd)
                for (var i in fileList) {
                    fileList[i] = path.resolve(relpath, fileList[i])
                }
            }
            return {
                title: `Running tasks for ${key}`,
                task: () => {
                    return new Listr(runScript(linter, fileList, config))
                }
            }
        }
    }).filter(task => typeof task !== 'undefined') // Filter undefined values

    if (tasks.length) {
        new Listr(tasks).run().catch(err => {
            console.error(err)
            process.exit(1)
        })
    }
})

<|endoftext|>


<commit_before>import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import configureStore from './configureStore';
import Root from './Root';
import { okapi, config } from 'stripes-loader!'; // eslint-disable-line

const initialState = { okapi };
const store = configureStore(initialState, config);

render(
  <Root store={store} />,
  document.getElementById('root'),
);
<commit_msg>Pass config.disableAuth down into <Root>. Provides information for STRIPES-168.<commit_after>import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import configureStore from './configureStore';
import Root from './Root';
import { okapi, config } from 'stripes-loader!'; // eslint-disable-line

const initialState = { okapi };
const store = configureStore(initialState, config);

render(
  <Root store={store} disableAuth={config.disableAuth || false}/>,
  document.getElementById('root'),
);
<|endoftext|>


<commit_before>var os       = require('os');
var path     = require('path');
var glob     = require('glob');
var async    = require('async');
var mkdirp   = require('mkdirp');
var patterns = require('./patterns');
var tasks    = require('./tasks');

module.exports = function(opts, callback) {

  function createTask(file) {
    return {
      src:  path.resolve(opts.cwd, file),
      dest: path.resolve(opts.cwd, opts.dest(file))
    };
  }

  if (typeof opts.dest === 'string') {
    opts.dest = pattern.dest(opts.dest);
  }

  if (typeof opts.process === 'string') {
    opts.process = patterns.process(opts.process);
  }

  var globOptions = {
    cwd: opts.cwd,
    nonull: false,
    nocase: true
  };

  glob(opts.src, globOptions, function (err, files) {

    if (err) return callback(err);

    // list of tasks that need rebuilding
    var all = files.map(createTask)
                   .filter(tasks.outOfDate);

    // create any required folders
    var folders = tasks.destinationFolders(all);
    folders.forEach(function(f) { mkdirp.sync(f, 0777); });

    // run all tasks in parallel
    var fns = all.map(tasks.run(opts.process));
    async.parallelLimit(fns, os.cpus().length, callback);

  });

};
<commit_msg>Fix broken index<commit_after>var os       = require('os');
var path     = require('path');
var glob     = require('glob');
var async    = require('async');
var mkdirp   = require('mkdirp');
var patterns = require('./patterns');
var tasks    = require('./tasks');

module.exports = function(opts, callback) {

  function createTask(file) {
    return {
      src:  path.resolve(opts.cwd, file),
      dest: path.resolve(opts.cwd, opts.dest(file))
    };
  }

  if (typeof opts.dest === 'string') {
    opts.dest = patterns.dest(opts.dest);
  }

  if (typeof opts.process === 'string') {
    opts.process = patterns.process(opts.process);
  }

  var globOptions = {
    cwd: opts.cwd,
    nonull: false,
    nocase: true
  };

  glob(opts.src, globOptions, function (err, files) {

    if (err) return callback(err);

    // list of tasks that need rebuilding
    var all = files.map(createTask)
                   .filter(tasks.outOfDate);

    // create any required folders
    var folders = tasks.destinationFolders(all);
    folders.forEach(function(f) { mkdirp.sync(f, 0777); });

    // run all tasks in parallel
    var fns = all.map(tasks.run(opts.process));
    async.parallelLimit(fns, os.cpus().length, callback);

  });

};
<|endoftext|>


<commit_before>import fs from 'fs'
import _ from 'lodash'
import BookDownloader from './BookDownloader'

const readFile = (path, encoding) => {
	return new Promise((resolve, reject) => {
		fs.readFile(path, encoding, (err, data) => {
			if (err) {
				reject(err)
			} else {
				resolve(data)
			}
		})
	})
}

readFile('settings.json', 'utf8').then((str) => {
	const {asin, queries, booksPath, auths} = JSON.parse(str)

	const auth = _.sample(auths)

	console.log(`== booksPath: ${booksPath} ==`);
	console.log(`== asin: ${asin} ==`);
	console.log(`== auth: ${JSON.stringify(auth)} ==`);

	const downloader = new BookDownloader({booksPath, asin, timeout: 10000})
	downloader.init().then((value) => {
		downloader.printInfo()
		return downloader.useQuery(queries[0])
	}).then(() => {
		downloader.printInfo()
		return downloader.useSuggestedQueries(10)
	}).then(() => {
		downloader.printInfo()
		return downloader.retrieveImageUrls({auth})
	}).then(() => {
		downloader.printInfo()
		return downloader.saveImages()
	}).then(() => {
		downloader.printInfo()
	}).catch((e) => {
		console.log('error: ', e)
	})
})
<commit_msg>Refactoring<commit_after>import fs from 'fs';
import _ from 'lodash';
import BookDownloader from './BookDownloader';

const readFile = async (path, encoding) => {
	return new Promise((resolve, reject) => {
		fs.readFile(path, encoding, (err, data) => {
			if (err) {
				reject(err);
			} else {
				resolve(data);
			}
		});
	});
};

(async () => {
	try {
		for (let i = 0; i < 100; ++i) {
			const str = await readFile('settings.json', 'utf8');

			const {asin, queries, booksPath, auths} = JSON.parse(str);

			const auth = _.sample(auths);

			console.log(`== booksPath: ${booksPath} ==`);
			console.log(`== asin: ${asin} ==`);
			console.log(`== auth: ${JSON.stringify(auth)} ==`);

			const downloader = new BookDownloader({booksPath, asin, timeout: 20000});

			const value = await downloader.init();
			downloader.printInfo();

			await downloader.addSuggestedQueries(queries);
			await downloader.useSuggestedQueries(10);
			downloader.printInfo();

			await downloader.retrieveImageUrls({
				auth,
				maxQueries: 5
			});
			downloader.printInfo();

			await downloader.saveImages();
			downloader.printInfo();
		}
	} catch (e) {
		console.log('error: ', e);
	}
})();
<|endoftext|>


<commit_before>import 'source-map-support/register';
import {Nextion} from './nextion';
import {NextionProtocol} from './protocol';
import {UART} from './uart';

Nextion.from = Nextion.create = async function from (port, opts = {}) {
  const uart = await UART.from(port, opts);
  return new Nextion(uart);
};

Nextion.fromSerial = async function fromSerial (serialPort, opts = {}) {
  const uart = await UART.fromSerial(serialPort, opts);
  return new Nextion(uart);
};

Nextion.fromPort = async function fromPort (portName, opts = {}) {
  const uart = await UART.fromPort(portName, opts);
  return new Nextion(uart);
};

Nextion.NextionProtocol = NextionProtocol;
Nextion.UART = UART;

export default Nextion;
<commit_msg>don't use source-map-support for bundle<commit_after>import {Nextion} from './nextion';
import {NextionProtocol} from './protocol';
import {UART} from './uart';

Nextion.from = Nextion.create = async function from (port, opts = {}) {
  const uart = await UART.from(port, opts);
  return new Nextion(uart);
};

Nextion.fromSerial = async function fromSerial (serialPort, opts = {}) {
  const uart = await UART.fromSerial(serialPort, opts);
  return new Nextion(uart);
};

Nextion.fromPort = async function fromPort (portName, opts = {}) {
  const uart = await UART.fromPort(portName, opts);
  return new Nextion(uart);
};

Nextion.NextionProtocol = NextionProtocol;
Nextion.UART = UART;

export default Nextion;
<|endoftext|>


<commit_before>import $ from 'jquery';
import Util from './util';

const MetisMenu = (($) => { // eslint-disable-line no-shadow
  const NAME = 'metisMenu';
  const DATA_KEY = 'metisMenu';
  const EVENT_KEY = `.${DATA_KEY}`;
  const DATA_API_KEY = '.data-api';
  const JQUERY_NO_CONFLICT = $.fn[NAME];
  const TRANSITION_DURATION = 350;

  const Default = {
    toggle: true,
    preventDefault: true,
    activeClass: 'active',
    collapseClass: 'collapse',
    collapseInClass: 'in',
    collapsingClass: 'collapsing',
    triggerElement: 'a',
    parentTrigger: 'li',
    subMenu: 'ul',
  };

  const Event = {
    SHOW: `show${EVENT_KEY}`,
    SHOWN: `shown${EVENT_KEY}`,
    HIDE: `hide${EVENT_KEY}`,
    HIDDEN: `hidden${EVENT_KEY}`,
    CLICK_DATA_API: `click${EVENT_KEY}${DATA_API_KEY}`,
  };

  class MetisMenu { // eslint-disable-line no-shadow
    constructor(element, config) {
      this.element = element;
      this.config = { ...Default, ...config };
      this.transitioning = null;

      this.init();
    }
    init() {
      const self = this;
      const conf = this.config;
      $(this.element)
        .find(`${conf.parentTrigger}.${conf.activeClass}`)
        .has(conf.subMenu)
        .children(conf.subMenu)
        .addClass(`${conf.collapseClass} ${conf.collapseInClass}`);

      $(this.element)
        .find(conf.parentTrigger)
        .not(`.${conf.activeClass}`)
        .has(conf.subMenu)
        .children(conf.subMenu)
        .addClass(conf.collapseClass);

      $(this.element)
        .find(conf.parentTrigger)
        .has(conf.subMenu)
        .children(conf.triggerElement)
        .on(Event.CLICK_DATA_API, function (e) { // eslint-disable-line func-names
          const eTar = $(this);
          const paRent = eTar.parent(conf.parentTrigger);
          const sibLings = paRent
            .siblings(conf.parentTrigger)
            .children(conf.triggerElement);
          const List = paRent.children(conf.subMenu);
          if (conf.preventDefault) {
            e.preventDefault();
          }
          if (eTar.attr('aria-disabled') === 'true') {
            return;
          }
          if (paRent.hasClass(conf.activeClass)) {
            eTar.attr('aria-expanded', false);
            self.hide(List);
          } else {
            self.show(List);
            eTar.attr('aria-expanded', true);
            if (conf.toggle) {
              sibLings.attr('aria-expanded', false);
            }
          }

          if (conf.onTransitionStart) {
            conf.onTransitionStart(e);
          }
        });
    }

    show(element) {
      if (this.transitioning ||
        $(element).hasClass(this.config.collapsingClass)) {
        return;
      }
      const elem = $(element);

      const startEvent = $.Event(Event.SHOW);
      elem.trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      elem
        .parent(this.config.parentTrigger)
        .addClass(this.config.activeClass);

      if (this.config.toggle) {
        this
          .hide(elem
            .parent(this.config.parentTrigger)
            .siblings()
            .children(`${this.config.subMenu}.${this.config.collapseInClass}`));
      }

      elem
        .removeClass(this.config.collapseClass)
        .addClass(this.config.collapsingClass)
        .height(0);

      this.setTransitioning(true);

      const complete = () => {
        // check if disposed
        if (!this.config || !this.element) {
          return;
        }
        elem
          .removeClass(this.config.collapsingClass)
          .addClass(`${this.config.collapseClass} ${this.config.collapseInClass}`)
          .height('');

        this.setTransitioning(false);

        elem.trigger(Event.SHOWN);
      };

      elem
        .height(element[0].scrollHeight)
        .one(Util.TRANSITION_END, complete)
        .mmEmulateTransitionEnd(TRANSITION_DURATION);
    }

    hide(element) {
      if (this.transitioning || !$(element).hasClass(this.config.collapseInClass)) {
        return;
      }

      const elem = $(element);

      const startEvent = $.Event(Event.HIDE);
      elem.trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      elem.parent(this.config.parentTrigger).removeClass(this.config.activeClass);
      // eslint-disable-next-line no-unused-expressions
      elem.height(elem.height())[0].offsetHeight;

      elem
        .addClass(this.config.collapsingClass)
        .removeClass(this.config.collapseClass)
        .removeClass(this.config.collapseInClass);

      this.setTransitioning(true);

      const complete = () => {
        // check if disposed
        if (!this.config || !this.element) {
          return;
        }
        if (this.transitioning && this.config.onTransitionEnd) {
          this.config.onTransitionEnd();
        }

        this.setTransitioning(false);
        elem.trigger(Event.HIDDEN);

        elem
          .removeClass(this.config.collapsingClass)
          .addClass(this.config.collapseClass);
      };

      if (elem.height() === 0 || elem.css('display') === 'none') {
        complete();
      } else {
        elem
          .height(0)
          .one(Util.TRANSITION_END, complete)
          .mmEmulateTransitionEnd(TRANSITION_DURATION);
      }
    }

    setTransitioning(isTransitioning) {
      this.transitioning = isTransitioning;
    }

    dispose() {
      $.removeData(this.element, DATA_KEY);

      $(this.element)
        .find(this.config.parentTrigger)
        .has(this.config.subMenu)
        .children(this.config.triggerElement)
        .off('click');

      this.transitioning = null;
      this.config = null;
      this.element = null;
    }

    static jQueryInterface(config) {
      // eslint-disable-next-line func-names
      return this.each(function () {
        const $this = $(this);
        let data = $this.data(DATA_KEY);
        const conf = {
          ...Default,
          ...$this.data(),
          ...typeof config === 'object' && config ? config : {},
        };

        if (!data && /dispose/.test(config)) {
          this.dispose();
        }

        if (!data) {
          data = new MetisMenu(this, conf);
          $this.data(DATA_KEY, data);
        }

        if (typeof config === 'string') {
          if (data[config] === undefined) {
            throw new Error(`No method named "${config}"`);
          }
          data[config]();
        }
      });
    }
  }
  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */

  $.fn[NAME] = MetisMenu.jQueryInterface; // eslint-disable-line no-param-reassign
  $.fn[NAME].Constructor = MetisMenu; // eslint-disable-line no-param-reassign
  $.fn[NAME].noConflict = () => { // eslint-disable-line no-param-reassign
    $.fn[NAME] = JQUERY_NO_CONFLICT; // eslint-disable-line no-param-reassign
    return MetisMenu.jQueryInterface;
  };
  return MetisMenu;
})($);

export default MetisMenu;
<commit_msg>Fix dispose option.<commit_after>import $ from 'jquery';
import Util from './util';

const MetisMenu = (($) => { // eslint-disable-line no-shadow
  const NAME = 'metisMenu';
  const DATA_KEY = 'metisMenu';
  const EVENT_KEY = `.${DATA_KEY}`;
  const DATA_API_KEY = '.data-api';
  const JQUERY_NO_CONFLICT = $.fn[NAME];
  const TRANSITION_DURATION = 350;

  const Default = {
    toggle: true,
    preventDefault: true,
    activeClass: 'active',
    collapseClass: 'collapse',
    collapseInClass: 'in',
    collapsingClass: 'collapsing',
    triggerElement: 'a',
    parentTrigger: 'li',
    subMenu: 'ul',
  };

  const Event = {
    SHOW: `show${EVENT_KEY}`,
    SHOWN: `shown${EVENT_KEY}`,
    HIDE: `hide${EVENT_KEY}`,
    HIDDEN: `hidden${EVENT_KEY}`,
    CLICK_DATA_API: `click${EVENT_KEY}${DATA_API_KEY}`,
  };

  class MetisMenu { // eslint-disable-line no-shadow
    constructor(element, config) {
      this.element = element;
      this.config = { ...Default, ...config };
      this.transitioning = null;

      this.init();
    }
    init() {
      const self = this;
      const conf = this.config;
      $(this.element)
        .find(`${conf.parentTrigger}.${conf.activeClass}`)
        .has(conf.subMenu)
        .children(conf.subMenu)
        .addClass(`${conf.collapseClass} ${conf.collapseInClass}`);

      $(this.element)
        .find(conf.parentTrigger)
        .not(`.${conf.activeClass}`)
        .has(conf.subMenu)
        .children(conf.subMenu)
        .addClass(conf.collapseClass);

      $(this.element)
        .find(conf.parentTrigger)
        .has(conf.subMenu)
        .children(conf.triggerElement)
        .on(Event.CLICK_DATA_API, function (e) { // eslint-disable-line func-names
          const eTar = $(this);
          const paRent = eTar.parent(conf.parentTrigger);
          const sibLings = paRent
            .siblings(conf.parentTrigger)
            .children(conf.triggerElement);
          const List = paRent.children(conf.subMenu);
          if (conf.preventDefault) {
            e.preventDefault();
          }
          if (eTar.attr('aria-disabled') === 'true') {
            return;
          }
          if (paRent.hasClass(conf.activeClass)) {
            eTar.attr('aria-expanded', false);
            self.hide(List);
          } else {
            self.show(List);
            eTar.attr('aria-expanded', true);
            if (conf.toggle) {
              sibLings.attr('aria-expanded', false);
            }
          }

          if (conf.onTransitionStart) {
            conf.onTransitionStart(e);
          }
        });
    }

    show(element) {
      if (this.transitioning ||
        $(element).hasClass(this.config.collapsingClass)) {
        return;
      }
      const elem = $(element);

      const startEvent = $.Event(Event.SHOW);
      elem.trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      elem
        .parent(this.config.parentTrigger)
        .addClass(this.config.activeClass);

      if (this.config.toggle) {
        this
          .hide(elem
            .parent(this.config.parentTrigger)
            .siblings()
            .children(`${this.config.subMenu}.${this.config.collapseInClass}`));
      }

      elem
        .removeClass(this.config.collapseClass)
        .addClass(this.config.collapsingClass)
        .height(0);

      this.setTransitioning(true);

      const complete = () => {
        // check if disposed
        if (!this.config || !this.element) {
          return;
        }
        elem
          .removeClass(this.config.collapsingClass)
          .addClass(`${this.config.collapseClass} ${this.config.collapseInClass}`)
          .height('');

        this.setTransitioning(false);

        elem.trigger(Event.SHOWN);
      };

      elem
        .height(element[0].scrollHeight)
        .one(Util.TRANSITION_END, complete)
        .mmEmulateTransitionEnd(TRANSITION_DURATION);
    }

    hide(element) {
      if (this.transitioning || !$(element).hasClass(this.config.collapseInClass)) {
        return;
      }

      const elem = $(element);

      const startEvent = $.Event(Event.HIDE);
      elem.trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      elem.parent(this.config.parentTrigger).removeClass(this.config.activeClass);
      // eslint-disable-next-line no-unused-expressions
      elem.height(elem.height())[0].offsetHeight;

      elem
        .addClass(this.config.collapsingClass)
        .removeClass(this.config.collapseClass)
        .removeClass(this.config.collapseInClass);

      this.setTransitioning(true);

      const complete = () => {
        // check if disposed
        if (!this.config || !this.element) {
          return;
        }
        if (this.transitioning && this.config.onTransitionEnd) {
          this.config.onTransitionEnd();
        }

        this.setTransitioning(false);
        elem.trigger(Event.HIDDEN);

        elem
          .removeClass(this.config.collapsingClass)
          .addClass(this.config.collapseClass);
      };

      if (elem.height() === 0 || elem.css('display') === 'none') {
        complete();
      } else {
        elem
          .height(0)
          .one(Util.TRANSITION_END, complete)
          .mmEmulateTransitionEnd(TRANSITION_DURATION);
      }
    }

    setTransitioning(isTransitioning) {
      this.transitioning = isTransitioning;
    }

    dispose() {
      $.removeData(this.element, DATA_KEY);

      $(this.element)
        .find(this.config.parentTrigger)
        .has(this.config.subMenu)
        .children(this.config.triggerElement)
        .off('click');

      this.transitioning = null;
      this.config = null;
      this.element = null;
    }

    static jQueryInterface(config) {
      // eslint-disable-next-line func-names
      return this.each(function () {
        const $this = $(this);
        let data = $this.data(DATA_KEY);
        const conf = {
          ...Default,
          ...$this.data(),
          ...typeof config === 'object' && config ? config : {},
        };

        if (data && /dispose/.test(config)) {
          this.dispose();
        }

        if (!data) {
          data = new MetisMenu(this, conf);
          $this.data(DATA_KEY, data);
        }

        if (typeof config === 'string') {
          if (data[config] === undefined) {
            throw new Error(`No method named "${config}"`);
          }
          data[config]();
        }
      });
    }
  }
  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */

  $.fn[NAME] = MetisMenu.jQueryInterface; // eslint-disable-line no-param-reassign
  $.fn[NAME].Constructor = MetisMenu; // eslint-disable-line no-param-reassign
  $.fn[NAME].noConflict = () => { // eslint-disable-line no-param-reassign
    $.fn[NAME] = JQUERY_NO_CONFLICT; // eslint-disable-line no-param-reassign
    return MetisMenu.jQueryInterface;
  };
  return MetisMenu;
})($);

export default MetisMenu;
<|endoftext|>


<commit_before>var environment = module.exports;

environment.browser = !!(
    typeof(window) !== "undefined" &&
    typeof(navigator) !== "undefined" &&
    window.document
);

environment.node = !environment.browser;

environment.window = (
    typeof(window) !== "undefined" ? window :
    typeof(global) !== "undefined" ? global :
    typeof(self) !== "undefined" ? self : {}
);

environment.document = typeof(document) !== "undefined" ? document : {};

environment.canUseDOM = !!(typeof(window) !== "undefined" && window.document && window.document.createElement);

environment.canUseWorkers = typeof(Worker) !== "undefined";

environment.canUseEventListeners = environment.canUseDOM && !!(window.addEventListener || window.attachEvent);

environment.canUseViewport = environment.canUseDOM && !!window.screen;

environment.isInWorker = typeof(importScripts) !== "undefined";
<commit_msg>updates<commit_after>var environment = module.exports,

    hasWindow = typeof(window) !== "undefined",
    userAgent = hasWindow ? window.navigator.userAgent : "";

environment.browser = !!(
    hasWindow &&
    typeof(navigator) !== "undefined" &&
    window.document
);

environment.node = !environment.browser;

environment.mobile = environment.browser && /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent.toLowerCase());

environment.window = (
    hasWindow ? window :
    typeof(global) !== "undefined" ? global :
    typeof(self) !== "undefined" ? self : {}
);

environment.document = typeof(document) !== "undefined" ? document : {};

environment.canUseDOM = !!(typeof(window) !== "undefined" && window.document && window.document.createElement);

environment.canUseWorkers = typeof(Worker) !== "undefined";

environment.canUseEventListeners = environment.canUseDOM && !!(window.addEventListener || window.attachEvent);

environment.canUseViewport = environment.canUseDOM && !!window.screen;

environment.isInWorker = typeof(importScripts) !== "undefined";
<|endoftext|>


<commit_before>import {Observable as O} from "rx"
import dom from "./dom"
import {isVNode, VNode} from "./vnode"
import {zipObj, isPlainObj, isStr, isArray, isPrimitive, keys} from "./util"
import {EventListener, EventSource} from "./events"

const htmlAttrs =
  "accept accept-charset accesskey action align alt async autocomplete autofocus " +
  "autoplay autosave bgcolor buffered challenge charset checked cite code " +
  "codebase color cols colspan content contenteditable contextmenu controls coords " +
  "data data- datetime default defer dir dirname disabled download draggable dropzone " +
  "enctype for form formaction headers height hidden high href hreflang http-equiv " +
  "icon id ismap itemprop keytype kind label lang language list loop low manifest " +
  "max maxlength media method min multiple muted name novalidate open optimum pattern " +
  "ping placeholder poster preload radiogroup readonly rel required reversed rows " +
  "rowspan sandbox scope scoped seamless selected shape size sizes span spellcheck " +
  "src srcdoc srclang srcset start step summary tabindex target title type " +
  "usemap width wrap"

const boolAttrs =
  "allowfullscreen async autofocus autoplay checked compact controls declare default " +
  "defaultchecked defaultmuted defaultselected defer disabled draggable enabled " +
  "formnovalidate hidden indeterminate inert ismap itemscope loop multiple muted " +
  "nohref noresize noshade novalidate nowrap open pauseonexit readonly required reversed " +
  "scoped seamless selected sortable spellcheck translate truespeed typemustmatch visible"

const noBubbleEvents =
  "load unload scroll focus blur DOMNodeRemovedFromDocument DOMNodeInsertedIntoDocument " +
  "loadstart progress error abort load loadend"

const htmlProps =
  "value"

const attrByName =
  zipObj(htmlAttrs.split(" ").map(a => [a.trim(), true]))

const boolAttrByName =
  zipObj(boolAttrs.split(" ").map(a => [a.trim(), true]))

const propsByName =
  zipObj(htmlProps.split(" ").map(a => [a.trim(), true]))

const noBubblesByName =
  zipObj(noBubbleEvents.split(" ").map(a => [a.trim(), true]))

const isHtmlProp = key => propsByName[key]

const isAttr = attr => {
  return attrByName[attr] || (attr.indexOf("data-") === 0 && attr.length > 5)
}

const bubbles = event => {
  return !noBubblesByName[event]
}

const toClassObj = (klass) => {
  let i, list, c, res = {}
  for (i = 0, list = (klass || "").split(" "); i < list.length; i++) {
    if (c = list[i].trim()) res[c] = true   // eslint-disable-line
  }
  return res
}

function h(tag, props, children) {
  if (arguments.length === 1) {
    props = {}
    children = []
  } else if (arguments.length === 2) {
    if (isPlainObj(props)) {
      children = []
    } else {
      children = props
      props = {}
    }
  }

  if (!isStr(tag)) {
    throw new Error("Tag selector must be a string")
  }

  // parse children
  if (!isArray(children)) {
    children = [children]
  }
  let temp = []
  for (var i = 0; i < children.length; i++) {
    const child = children[i]
    if (child === undefined || child === null || child === false) continue
    if (isVNode(child)) {
      temp.push(child)
    } else if (isPrimitive(child)) {
      temp.push(VNode(undefined, undefined, undefined, `${child}`))
    } else {
      throw new Error(`Invalid virtual node: ${child}`)
    }
  }
  children = temp

  // parse props
  const key = props.key
  const attrs = {}, htmlProps = {}
  const style = props.style || {}
  const klass = toClassObj(props.class || props.className)
  keys(props).forEach(k => {
    isAttr(k) && (attrs[k] = props[k])
    isHtmlProp(k) && (htmlProps[k] = props[k])
  })

  const data = {
    key, attrs, style, klass, props: htmlProps
  }

  return VNode(tag, data, children)
}

const updateAttrs = (old, cur) => {
  const {elm} = cur
  let key, oldAttrs = old.data.attrs || {}, attrs = cur.data.attrs || {}
  for (key in attrs) {
    var c = attrs[key], o = oldAttrs[key]
    if (o !== c) {
      !c && boolAttrByName[key] ? elm.removeAttribute(key) : elm.setAttribute(key, c)
    }
  }
  for (key in oldAttrs) {
    if (!(key in attrs)) elm.removeAttribute(key)
  }
}

const updateProps = (old, cur) => {
  const {elm} = cur
  let key, oldProps = old.data.props || {}, props = cur.data.props || {}
  for (key in props) {
    var c = props[key], o = oldProps[key]
    o !== c && (elm[key] = c)
  }
  for (key in oldProps) {
    if (!(key in props)) delete elm[key]
  }
}

const updateKlass = (old, cur) => {
  const {elm} = cur
  let kl, oldKlass = old.data.klass || {}, klass = cur.data.klass || {}
  for (kl in oldKlass) {
    if (!(kl in klass)) elm.classList.remove(kl)
  }
  for (kl in klass) {
    if (!(kl in oldKlass)) elm.classList.add(kl)
  }
}

const updateStyle = (old, cur) => {
  const {elm} = cur
  let s, oldStyle = old.data.style || {}, style = cur.data.style || {}
  for (s in style) {
    var c = style[s], o = style[s]
    if (c !== o) elm.style[s] = c
  }
  for (s in oldStyle) {
    if (!(s in style)) elm.style[s] = ""
  }
}

const attachEvents = vnode => {
  if (vnode.data && vnode.data.eventSource) {
    vnode.data.eventSource.attach(vnode.elm)
  }
}

const reattachEvents = (old, cur) => {
  const curSrc = (cur.data || {}).eventSource
  const oldSrc = (old.data || {}).eventSource
  if (curSrc !== oldSrc) {
    oldSrc && oldSrc.detach(cur.elm)
    curSrc && curSrc.reattach(cur.elm)
  }
}
const detachEvents = vnode => {
  if (vnode.data && vnode.data.eventSource) {
    vnode.data.eventSource.detach(vnode.elm)
  }
}

export default function makeSnabbdom(rootElem) {
  return function snabbdom() {
    const patch = dom.init([
      {
        create(old, cur) {
          updateAttrs(old, cur)
          updateProps(old, cur)
          updateKlass(old, cur)
          updateStyle(old, cur)
          attachEvents(cur)
        },
        update(old, cur) {
          updateAttrs(old, cur)
          updateProps(old, cur)
          updateKlass(old, cur)
          updateStyle(old, cur)
        },
        postpatch(old, cur) {
          reattachEvents(old, cur)
        },
        destroy(vnode) {
          detachEvents(vnode)
        }
      }
    ])

    function cloneTree(vnode) {
      return {
        sel: vnode.sel,
        data: vnode.data,
        children: vnode.children && vnode.children.map(cloneTree),
        text: vnode.text,
        key: vnode.key,
        ID: vnode.ID,
        _id: vnode._id
      }
    }

    function prepare(vdom$) {
      const newSource = () => new EventSource()
      const withSource = src => vdom$
        .merge(O.never())
        .map(vnode => (vnode.data.eventSource = vnode.data.eventSource || src) && vnode)
      return O.using(newSource, withSource).shareReplay(1)
    }

    function events(vdom$, selector, eventName, useCapture) {
      useCapture = useCapture === undefined ? !bubbles(eventName) : !!useCapture
      const newListener = () => new EventListener(selector, eventName, useCapture)
      const listen = listener => vdom$
        .distinctUntilChanged(vnode => vnode.data.eventSource)
        .map(vnode => {
          if (!vnode.data.eventSource) {
            console.warn(                                 // eslint-disable-line
              "DOM.events :: VDOM is not prepared for event listening.",
              "Perhaps you forgot to call DOM.prepare(vdom$)?"
            )
            return O.never()
          }
          return vnode.data.eventSource.listen(listener)
        })
      return O.using(newListener, listen).switch().share()
    }

    const Transforms = {
      h,
      events,
      prepare
    }

    function executor(vdom$) {
      const elm = isStr(rootElem) ? document.querySelector(rootElem) : rootElem
      let prev = elm
      const dispose = vdom$.subscribe(vnode => {
        vnode = cloneTree(vnode)
        patch(prev, vnode)
        prev = vnode
      })
      return {
        dispose: () => {
          dispose();
          prev = null
        }
      }
    }

    return [Transforms, executor]
  }
}
<commit_msg>Add DOM transform for convenience<commit_after>import {Observable as O} from "rx"
import dom from "./dom"
import {isVNode, VNode} from "./vnode"
import {zipObj, isPlainObj, isStr, isArray, isPrimitive, keys} from "./util"
import {EventListener, EventSource} from "./events"

const htmlAttrs =
  "accept accept-charset accesskey action align alt async autocomplete autofocus " +
  "autoplay autosave bgcolor buffered challenge charset checked cite code " +
  "codebase color cols colspan content contenteditable contextmenu controls coords " +
  "data data- datetime default defer dir dirname disabled download draggable dropzone " +
  "enctype for form formaction headers height hidden high href hreflang http-equiv " +
  "icon id ismap itemprop keytype kind label lang language list loop low manifest " +
  "max maxlength media method min multiple muted name novalidate open optimum pattern " +
  "ping placeholder poster preload radiogroup readonly rel required reversed rows " +
  "rowspan sandbox scope scoped seamless selected shape size sizes span spellcheck " +
  "src srcdoc srclang srcset start step summary tabindex target title type " +
  "usemap width wrap"

const boolAttrs =
  "allowfullscreen async autofocus autoplay checked compact controls declare default " +
  "defaultchecked defaultmuted defaultselected defer disabled draggable enabled " +
  "formnovalidate hidden indeterminate inert ismap itemscope loop multiple muted " +
  "nohref noresize noshade novalidate nowrap open pauseonexit readonly required reversed " +
  "scoped seamless selected sortable spellcheck translate truespeed typemustmatch visible"

const noBubbleEvents =
  "load unload scroll focus blur DOMNodeRemovedFromDocument DOMNodeInsertedIntoDocument " +
  "loadstart progress error abort load loadend"

const htmlProps =
  "value"

const attrByName =
  zipObj(htmlAttrs.split(" ").map(a => [a.trim(), true]))

const boolAttrByName =
  zipObj(boolAttrs.split(" ").map(a => [a.trim(), true]))

const propsByName =
  zipObj(htmlProps.split(" ").map(a => [a.trim(), true]))

const noBubblesByName =
  zipObj(noBubbleEvents.split(" ").map(a => [a.trim(), true]))

const isHtmlProp = key => propsByName[key]

const isAttr = attr => {
  return attrByName[attr] || (attr.indexOf("data-") === 0 && attr.length > 5)
}

const bubbles = event => {
  return !noBubblesByName[event]
}

const toClassObj = (klass) => {
  let i, list, c, res = {}
  for (i = 0, list = (klass || "").split(" "); i < list.length; i++) {
    if (c = list[i].trim()) res[c] = true   // eslint-disable-line
  }
  return res
}

function h(tag, props, children) {
  if (arguments.length === 1) {
    props = {}
    children = []
  } else if (arguments.length === 2) {
    if (isPlainObj(props)) {
      children = []
    } else {
      children = props
      props = {}
    }
  }

  if (!isStr(tag)) {
    throw new Error("Tag selector must be a string")
  }

  // parse children
  if (!isArray(children)) {
    children = [children]
  }
  let temp = []
  for (var i = 0; i < children.length; i++) {
    const child = children[i]
    if (child === undefined || child === null || child === false) continue
    if (isVNode(child)) {
      temp.push(child)
    } else if (isPrimitive(child)) {
      temp.push(VNode(undefined, undefined, undefined, `${child}`))
    } else {
      throw new Error(`Invalid virtual node: ${child}`)
    }
  }
  children = temp

  // parse props
  const key = props.key
  const attrs = {}, htmlProps = {}
  const style = props.style || {}
  const klass = toClassObj(props.class || props.className)
  keys(props).forEach(k => {
    isAttr(k) && (attrs[k] = props[k])
    isHtmlProp(k) && (htmlProps[k] = props[k])
  })

  const data = {
    key, attrs, style, klass, props: htmlProps
  }

  return VNode(tag, data, children)
}

const updateAttrs = (old, cur) => {
  const {elm} = cur
  let key, oldAttrs = old.data.attrs || {}, attrs = cur.data.attrs || {}
  for (key in attrs) {
    var c = attrs[key], o = oldAttrs[key]
    if (o !== c) {
      !c && boolAttrByName[key] ? elm.removeAttribute(key) : elm.setAttribute(key, c)
    }
  }
  for (key in oldAttrs) {
    if (!(key in attrs)) elm.removeAttribute(key)
  }
}

const updateProps = (old, cur) => {
  const {elm} = cur
  let key, oldProps = old.data.props || {}, props = cur.data.props || {}
  for (key in props) {
    var c = props[key], o = oldProps[key]
    o !== c && (elm[key] = c)
  }
  for (key in oldProps) {
    if (!(key in props)) delete elm[key]
  }
}

const updateKlass = (old, cur) => {
  const {elm} = cur
  let kl, oldKlass = old.data.klass || {}, klass = cur.data.klass || {}
  for (kl in oldKlass) {
    if (!(kl in klass)) elm.classList.remove(kl)
  }
  for (kl in klass) {
    if (!(kl in oldKlass)) elm.classList.add(kl)
  }
}

const updateStyle = (old, cur) => {
  const {elm} = cur
  let s, oldStyle = old.data.style || {}, style = cur.data.style || {}
  for (s in style) {
    var c = style[s], o = style[s]
    if (c !== o) elm.style[s] = c
  }
  for (s in oldStyle) {
    if (!(s in style)) elm.style[s] = ""
  }
}

const attachEvents = vnode => {
  if (vnode.data && vnode.data.eventSource) {
    vnode.data.eventSource.attach(vnode.elm)
  }
}

const reattachEvents = (old, cur) => {
  const curSrc = (cur.data || {}).eventSource
  const oldSrc = (old.data || {}).eventSource
  if (curSrc !== oldSrc) {
    oldSrc && oldSrc.detach(cur.elm)
    curSrc && curSrc.reattach(cur.elm)
  }
}
const detachEvents = vnode => {
  if (vnode.data && vnode.data.eventSource) {
    vnode.data.eventSource.detach(vnode.elm)
  }
}

export default function makeSnabbdom(rootElem) {
  return function snabbdom() {
    const patch = dom.init([
      {
        create(old, cur) {
          updateAttrs(old, cur)
          updateProps(old, cur)
          updateKlass(old, cur)
          updateStyle(old, cur)
          attachEvents(cur)
        },
        update(old, cur) {
          updateAttrs(old, cur)
          updateProps(old, cur)
          updateKlass(old, cur)
          updateStyle(old, cur)
        },
        postpatch(old, cur) {
          reattachEvents(old, cur)
        },
        destroy(vnode) {
          detachEvents(vnode)
        }
      }
    ])

    function cloneTree(vnode) {
      return {
        sel: vnode.sel,
        data: vnode.data,
        children: vnode.children && vnode.children.map(cloneTree),
        text: vnode.text,
        key: vnode.key,
        ID: vnode.ID,
        _id: vnode._id
      }
    }

    function prepare(vdom$) {
      const newSource = () => new EventSource()
      const withSource = src => vdom$
        .merge(O.never())
        .map(vnode => (vnode.data.eventSource = vnode.data.eventSource || src) && vnode)
      return O.using(newSource, withSource).shareReplay(1)
    }

    function events(vdom$, selector, eventName, useCapture) {
      useCapture = useCapture === undefined ? !bubbles(eventName) : !!useCapture
      const newListener = () => new EventListener(selector, eventName, useCapture)
      const listen = listener => vdom$
        .distinctUntilChanged(vnode => vnode.data.eventSource)
        .map(vnode => {
          if (!vnode.data.eventSource) {
            console.warn(                                 // eslint-disable-line
              "DOM.events :: VDOM is not prepared for event listening.",
              "Perhaps you forgot to call DOM.prepare(vdom$)?"
            )
            return O.never()
          }
          return vnode.data.eventSource.listen(listener)
        })
      return O.using(newListener, listen).switch().share()
    }

    const Transforms = {
      h,
      events,
      prepare
    }
    // for convenience
    Transforms.DOM = Transforms

    function executor(vdom$) {
      const elm = isStr(rootElem) ? document.querySelector(rootElem) : rootElem
      let prev = elm
      const dispose = vdom$.subscribe(vnode => {
        vnode = cloneTree(vnode)
        patch(prev, vnode)
        prev = vnode
      })
      return {
        dispose: () => {
          dispose();
          prev = null
        }
      }
    }

    return [Transforms, executor]
  }
}
<|endoftext|>


<commit_before>import _ from 'lodash'
import gulp from 'gulp'
import utils from './lib/utils'
import help from './tasks/help'

let factories = {}
let options = {}

function bucket (taskName, taskFactory, configs) {
  factories[taskName] = taskFactory

  if (configs == null) configs = [{}]
  if (!_.isArray(configs)) configs = [configs]

  let tasks = _.map(configs, (config) => addTask(taskName, config))
  if (!utils.hasTask(gulp, taskName)) utils.createRootTask(gulp, taskName)

  return tasks
}

function addTask (taskName, config) {
  let factory = factories[taskName]
  let sequence = _.flatten(factory(config, options), true)
  let task = sequence.pop()
  let deps = _.filter(sequence, _.isString)

  if (config.alias != null) taskName += ':' + config.alias

  gulp.task(taskName, deps, task)
  return taskName
}

function setOptions () {
  if (arguments.length) options = arguments[0]
  return options
}

function setDefaultTask (...deps) {
  gulp.task('default', _.flatten(deps, true))
}

bucket.options = setOptions
bucket.setDefaultTask = setDefaultTask
bucket('help', help)

export default bucket
<commit_msg>add addTask to the public API<commit_after>import _ from 'lodash'
import gulp from 'gulp'
import utils from './lib/utils'
import help from './tasks/help'

let factories = {}
let options = {}

function bucket (taskName, taskFactory, configs) {
  factories[taskName] = taskFactory

  if (configs == null) configs = [{}]
  if (!_.isArray(configs)) configs = [configs]

  let tasks = _.map(configs, (config) => addTask(taskName, config))
  if (!utils.hasTask(gulp, taskName)) utils.createRootTask(gulp, taskName)

  return tasks
}

function addTask (taskName, config) {
  let factory = factories[taskName]
  let sequence = _.flatten(factory(config, options), true)
  let task = sequence.pop()
  let deps = _.filter(sequence, _.isString)

  if (config.alias != null) taskName += ':' + config.alias

  gulp.task(taskName, deps, task)
  return taskName
}

function setOptions () {
  if (arguments.length) options = arguments[0]
  return options
}

function setDefaultTask (...deps) {
  gulp.task('default', _.flatten(deps, true))
}

bucket.addTask = addTask
bucket.options = setOptions
bucket.setDefaultTask = setDefaultTask
bucket('help', help)

export default bucket
<|endoftext|>


<commit_before>import $ from "jquery";

class elitejax {
  // get config via object for elitejax constructor
  constructor (config = {}) {
    this.config = config;
    this.ajaxForm(this.getEl());
  };

  // gets elements that has been marked for elitejax
  getEl () {
    let res = [];
    let elem = document.querySelectorAll('form');
    Array.from(elem).forEach((v, i)=> {
      if (v.getAttribute('data-elitejax')) {
        res.push(v);
      }
    });
    return res;
  }

  // gets value from form elements
  getElVal(formEl) {
    let res = {};
    let num = formEl.length;
    for (let i = 0; i < num; i++) {
      let valid = this.validInput(formEl[i]);
      if(valid[0]) {
        res[valid[1]] = valid[2];
      }
    }
    return res;
  }

  // validate user inputs according to input types
  validInput (inputEl) {
    let val = [true, '', ''];
    let name = inputEl.name.toLowerCase();
    let value = inputEl.value;
    if (name !== '' && value !== '' && name !== 'submit' && value !== 'submit') {
      val[1] = name;
      val[2] = value;
    } else {
      val[0] = false;
    }
    return val;
  }

  ajaxForm (el) {
    // Loop through all the elements
    el.forEach((v, i) => {
      // add on submit event listener to all of them
      v.addEventListener(v.getAttribute('data-listen'), (e) => {
        e.preventDefault(); // stop submission
        let action = e.target.getAttribute('action');
        let method = e.target.getAttribute('method').toUpperCase();
        let data = this.getElVal(e.target.elements); // data for ajax
        let callback = this.config.cb;
        // get AJAX ready
        $.ajax({
          method: method,
          contentType: this.config.cType,
          url: action,
          data: data,
          dataType: this.config.resType
        })
        .done(function (x) {
          callback(x);
        });

      });
    });
  }

}

let ej = (config = {
  async: true,
  cType: "application/json",
  resType: 'json',
  cb: function (data) {
    console.log(data);
  }
}) => {
  return new elitejax(config);
}

window.ej = window.elitejax = ej;
<commit_msg>renamed index file<commit_after><|endoftext|>


<commit_before>import classNames from 'classnames';
import getHeight from 'dom-helpers/query/height';
import getOffset from 'dom-helpers/query/offset';
import getOffsetParent from 'dom-helpers/query/offsetParent';
import getScrollTop from 'dom-helpers/query/scrollTop';
import requestAnimationFrame from 'dom-helpers/util/requestAnimationFrame';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';

import addEventListener from './utils/addEventListener';
import getDocumentHeight from './utils/getDocumentHeight';
import ownerDocument from './utils/ownerDocument';
import ownerWindow from './utils/ownerWindow';

/**
 * The `<Affix/>` component toggles `position: fixed;` on and off, emulating
 * the effect found with `position: sticky;`.
 */
class Affix extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      affixed: 'top',
      position: null,
      top: null
    };

    this._needPositionUpdate = false;
  }

  componentDidMount() {
    this._isMounted = true;

    this._windowScrollListener = addEventListener(
      ownerWindow(this), 'scroll', () => this.onWindowScroll()
    );
    this._documentClickListener = addEventListener(
      ownerDocument(this), 'click', () => this.onDocumentClick()
    );

    this.onUpdate();
  }

  componentWillReceiveProps() {
    this._needPositionUpdate = true;
  }

  componentDidUpdate() {
    if (this._needPositionUpdate) {
      this._needPositionUpdate = false;
      this.onUpdate();
    }
  }

  componentWillUnmount() {
    this._isMounted = false;

    if (this._windowScrollListener) {
      this._windowScrollListener.remove();
    }
    if (this._documentClickListener) {
      this._documentClickListener.remove();
    }
  }

  onWindowScroll = () => {
    this.onUpdate();
  }

  onDocumentClick = () => {
    requestAnimationFrame(() => this.onUpdate());
  }

  onUpdate = () => {
    if (!this._isMounted) {
      return;
    }

    const {offsetTop, viewportOffsetTop} = this.props;
    const scrollTop = getScrollTop(ownerWindow(this));
    const positionTopMin = scrollTop + (viewportOffsetTop || 0);

    if (positionTopMin <= offsetTop) {
      this.updateState('top', null, null);
      return;
    }

    if (positionTopMin > this.getPositionTopMax()) {
      if (this.state.affixed === 'bottom') {
        this.updateStateAtBottom();
      } else {
        // Setting position away from `fixed` can change the offset parent of
        // the affix, so we can't calculate the correct position until after
        // we've updated its position.
        this.setState({
          affixed: 'bottom',
          position: 'absolute',
          top: null
        }, () => {
          if (!this._isMounted) {
            return;
          }

          this.updateStateAtBottom();
        });
      }
      return;
    }

    this.updateState('affix', 'fixed', viewportOffsetTop);
  }

  getPositionTopMax = () => {
    const documentHeight = getDocumentHeight(ownerDocument(this));
    const height = getHeight(ReactDOM.findDOMNode(this));

    return documentHeight - height - this.props.offsetBottom;
  }

  updateState = (affixed, position, top) => {
    if (
      affixed === this.state.affixed &&
      position === this.state.position &&
      top === this.state.top
    ) {
      return;
    }

    let upperName = affixed === 'affix'
      ? '' : affixed.charAt(0).toUpperCase() + affixed.substr(1);

    if (this.props['onAffix' + upperName]) {
      this.props['onAffix' + upperName]();
    }

    this.setState({affixed, position, top}, ()=>{
      if (this.props['onAffixed' + upperName]) {
        this.props['onAffixed' + upperName]();
      }
    });
  }

  updateStateAtBottom = () => {
    const positionTopMax = this.getPositionTopMax();
    const offsetParent = getOffsetParent(ReactDOM.findDOMNode(this));
    const parentTop = getOffset(offsetParent).top;

    this.updateState('bottom', 'absolute', positionTopMax - parentTop);
  }

  render() {
    const child = React.Children.only(this.props.children);
    const {className, style} = child.props;

    const {affixed, position, top} = this.state;
    const positionStyle = {position, top};

    let affixClassName;
    let affixStyle;
    if (affixed === 'top') {
      affixClassName = this.props.topClassName;
      affixStyle = this.props.topStyle;
    } else if (affixed === 'bottom') {
      affixClassName = this.props.bottomClassName;
      affixStyle = this.props.bottomStyle;
    } else {
      affixClassName = this.props.affixClassName;
      affixStyle = this.props.affixStyle;
    }

    return React.cloneElement(child, {
      className: classNames(affixClassName, className),
      style: {...positionStyle, ...affixStyle, ...style}
    });
  }
}

Affix.propTypes = {
  /**
   * Pixels to offset from top of screen when calculating position
   */
  offsetTop: PropTypes.number,

  /**
   * When affixed, pixels to offset from top of viewport
   */
  viewportOffsetTop: PropTypes.number,

  /**
   * Pixels to offset from bottom of screen when calculating position
   */
  offsetBottom: PropTypes.number,

  /**
   * CSS class or classes to apply when at top
   */
  topClassName: PropTypes.string,

  /**
   * Style to apply when at top
   */
  topStyle: PropTypes.object,

  /**
   * CSS class or classes to apply when affixed
   */
  affixClassName: PropTypes.string,
  /**
   * Style to apply when affixed
   */
  affixStyle: PropTypes.object,

  /**
   * CSS class or classes to apply when at bottom
   */
  bottomClassName: PropTypes.string,

  /**
   * Style to apply when at bottom
   */
  bottomStyle: PropTypes.object,

  /**
   * Callback fired when the right before the `affixStyle` and `affixStyle` props are rendered
   */
  onAffix: PropTypes.func,
  /**
   * Callback fired after the component `affixStyle` and `affixClassName` props have been rendered.
   */
  onAffixed: PropTypes.func,

  /**
   * Callback fired when the right before the `topStyle` and `topClassName` props are rendered
   */
  onAffixTop: PropTypes.func,

  /**
   * Callback fired after the component `topStyle` and `topClassName` props have been rendered.
   */
  onAffixedTop: PropTypes.func,

  /**
   * Callback fired when the right before the `bottomStyle` and `bottomClassName` props are rendered
   */
  onAffixBottom: PropTypes.func,

  /**
   * Callback fired after the component `bottomStyle` and `bottomClassName` props have been rendered.
   */
  onAffixedBottom: PropTypes.func
};

Affix.defaultProps = {
  offsetTop: 0,
  viewportOffsetTop: null,
  offsetBottom: 0
};

export default Affix;
<commit_msg>Fixing affix docs<commit_after>import classNames from 'classnames';
import getHeight from 'dom-helpers/query/height';
import getOffset from 'dom-helpers/query/offset';
import getOffsetParent from 'dom-helpers/query/offsetParent';
import getScrollTop from 'dom-helpers/query/scrollTop';
import requestAnimationFrame from 'dom-helpers/util/requestAnimationFrame';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';

import addEventListener from './utils/addEventListener';
import getDocumentHeight from './utils/getDocumentHeight';
import ownerDocument from './utils/ownerDocument';
import ownerWindow from './utils/ownerWindow';

/**
 * The `<Affix/>` component toggles `position: fixed;` on and off, emulating
 * the effect found with `position: sticky;`.
 */
class Affix extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      affixed: 'top',
      position: null,
      top: null
    };

    this._needPositionUpdate = false;
  }

  componentDidMount() {
    this._isMounted = true;

    this._windowScrollListener = addEventListener(
      ownerWindow(this), 'scroll', () => this.onWindowScroll()
    );
    this._documentClickListener = addEventListener(
      ownerDocument(this), 'click', () => this.onDocumentClick()
    );

    this.onUpdate();
  }

  componentWillReceiveProps() {
    this._needPositionUpdate = true;
  }

  componentDidUpdate() {
    if (this._needPositionUpdate) {
      this._needPositionUpdate = false;
      this.onUpdate();
    }
  }

  componentWillUnmount() {
    this._isMounted = false;

    if (this._windowScrollListener) {
      this._windowScrollListener.remove();
    }
    if (this._documentClickListener) {
      this._documentClickListener.remove();
    }
  }

  onWindowScroll = () => {
    this.onUpdate();
  }

  onDocumentClick = () => {
    requestAnimationFrame(() => this.onUpdate());
  }

  onUpdate = () => {
    if (!this._isMounted) {
      return;
    }

    const {offsetTop, viewportOffsetTop} = this.props;
    const scrollTop = getScrollTop(ownerWindow(this));
    const positionTopMin = scrollTop + (viewportOffsetTop || 0);

    if (positionTopMin <= offsetTop) {
      this.updateState('top', null, null);
      return;
    }

    if (positionTopMin > this.getPositionTopMax()) {
      if (this.state.affixed === 'bottom') {
        this.updateStateAtBottom();
      } else {
        // Setting position away from `fixed` can change the offset parent of
        // the affix, so we can't calculate the correct position until after
        // we've updated its position.
        this.setState({
          affixed: 'bottom',
          position: 'absolute',
          top: null
        }, () => {
          if (!this._isMounted) {
            return;
          }

          this.updateStateAtBottom();
        });
      }
      return;
    }

    this.updateState('affix', 'fixed', viewportOffsetTop);
  }

  getPositionTopMax = () => {
    const documentHeight = getDocumentHeight(ownerDocument(this));
    const height = getHeight(ReactDOM.findDOMNode(this));

    return documentHeight - height - this.props.offsetBottom;
  }

  updateState = (affixed, position, top) => {
    if (
      affixed === this.state.affixed &&
      position === this.state.position &&
      top === this.state.top
    ) {
      return;
    }

    let upperName = affixed === 'affix'
      ? '' : affixed.charAt(0).toUpperCase() + affixed.substr(1);

    if (this.props['onAffix' + upperName]) {
      this.props['onAffix' + upperName]();
    }

    this.setState({affixed, position, top}, ()=>{
      if (this.props['onAffixed' + upperName]) {
        this.props['onAffixed' + upperName]();
      }
    });
  }

  updateStateAtBottom = () => {
    const positionTopMax = this.getPositionTopMax();
    const offsetParent = getOffsetParent(ReactDOM.findDOMNode(this));
    const parentTop = getOffset(offsetParent).top;

    this.updateState('bottom', 'absolute', positionTopMax - parentTop);
  }

  render() {
    const child = React.Children.only(this.props.children);
    const {className, style} = child.props;

    const {affixed, position, top} = this.state;
    const positionStyle = {position, top};

    let affixClassName;
    let affixStyle;
    if (affixed === 'top') {
      affixClassName = this.props.topClassName;
      affixStyle = this.props.topStyle;
    } else if (affixed === 'bottom') {
      affixClassName = this.props.bottomClassName;
      affixStyle = this.props.bottomStyle;
    } else {
      affixClassName = this.props.affixClassName;
      affixStyle = this.props.affixStyle;
    }

    return React.cloneElement(child, {
      className: classNames(affixClassName, className),
      style: {...positionStyle, ...affixStyle, ...style}
    });
  }
}

Affix.propTypes = {
  /**
   * Pixels to offset from top of screen when calculating position
   */
  offsetTop: PropTypes.number,

  /**
   * When affixed, pixels to offset from top of viewport
   */
  viewportOffsetTop: PropTypes.number,

  /**
   * Pixels to offset from bottom of screen when calculating position
   */
  offsetBottom: PropTypes.number,

  /**
   * CSS class or classes to apply when at top
   */
  topClassName: PropTypes.string,

  /**
   * Style to apply when at top
   */
  topStyle: PropTypes.object,

  /**
   * CSS class or classes to apply when affixed
   */
  affixClassName: PropTypes.string,

  /**
   * Style to apply when affixed
   */
  affixStyle: PropTypes.object,

  /**
   * CSS class or classes to apply when at bottom
   */
  bottomClassName: PropTypes.string,

  /**
   * Style to apply when at bottom
   */
  bottomStyle: PropTypes.object,

  /**
   * Callback fired right before the `affixStyle` and `affixClassName` props are rendered
   */
  onAffix: PropTypes.func,

  /**
   * Callback fired after the component `affixStyle` and `affixClassName` props have been rendered
   */
  onAffixed: PropTypes.func,

  /**
   * Callback fired right before the `topStyle` and `topClassName` props are rendered
   */
  onAffixTop: PropTypes.func,

  /**
   * Callback fired after the component `topStyle` and `topClassName` props have been rendered
   */
  onAffixedTop: PropTypes.func,

  /**
   * Callback fired right before the `bottomStyle` and `bottomClassName` props are rendered
   */
  onAffixBottom: PropTypes.func,

  /**
   * Callback fired after the component `bottomStyle` and `bottomClassName` props have been rendered
   */
  onAffixedBottom: PropTypes.func
};

Affix.defaultProps = {
  offsetTop: 0,
  viewportOffsetTop: null,
  offsetBottom: 0
};

export default Affix;
<|endoftext|>


<commit_before>const serve = require('serve/lib/server')
const relativePaths = require('./relative-paths')

// taken from serve cli!
process.env.ASSET_DIR = '/' + Math.random().toString(36).substr(2, 10)

module.exports = (cookieName) => {
  const baseURL = process.env.PUBLIC_URL || ''
  const uiPath = process.env.REACT_APP_BUILD
  const uiIgnored = [ '.DS_Store', '.git/', 'node_modules' ]
  let rootUrls = []

  route.buildRelativePaths = () => {
    return (
      relativePaths(uiPath)
      .then((urls) => { rootUrls = urls })
    )
  }

  return route

  function route (req, res) {
    if (cookieName && baseURL) {
      const cookieValue = encodeURIComponent(baseURL)
      const cookie = `${cookieName}=${cookieValue}; Path=/;`
      res.setHeader('Set-Cookie', cookie)
    }
    const uiFlags = { single: true, auth: !!process.env.SERVE_USER }
    const overrideUrl = rootUrls.find((x) => req.url.indexOf(x) !== -1)
    if (req.url.startsWith(baseURL)) req.url = req.url.slice(baseURL)
    if (overrideUrl) req.url = overrideUrl
    serve(req, res, uiFlags, uiPath, uiIgnored)
  }
}
<commit_msg>Remove slash after baseUrl and make sure entire url is not removed<commit_after>const serve = require('serve/lib/server')
const relativePaths = require('./relative-paths')

// taken from serve cli!
process.env.ASSET_DIR = '/' + Math.random().toString(36).substr(2, 10)

module.exports = (cookieName) => {
  const baseURL = process.env.PUBLIC_URL || ''
  const uiPath = process.env.REACT_APP_BUILD
  const uiIgnored = [ '.DS_Store', '.git/', 'node_modules' ]
  let rootUrls = []

  route.buildRelativePaths = () => {
    return (
      relativePaths(uiPath)
      .then((urls) => { rootUrls = urls })
    )
  }

  return route

  function route (req, res) {
    if (cookieName && baseURL) {
      const cookieValue = encodeURIComponent(baseURL)
      const cookie = `${cookieName}=${cookieValue}; Path=/;`
      res.setHeader('Set-Cookie', cookie)
    }
    const uiFlags = { single: true, auth: !!process.env.SERVE_USER }
    const overrideUrl = rootUrls.find((x) => req.url.indexOf(x) !== -1)
    if (req.url.startsWith(baseURL) && req.url.length > baseUrl.length + 1) {
      req.url = req.url.slice(baseURL.length + 1)
    }
    if (overrideUrl) req.url = overrideUrl
    serve(req, res, uiFlags, uiPath, uiIgnored)
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import App from './containers/App'
import Chat from './containers/Chat'
import NoMatch from './containers/NoMatch'
import './index.css'
import { createStore, applyMiddleware } from 'redux'
import reducer from './reducers/index'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import thunkMiddleware from 'redux-thunk'

const store = createStore(
  reducer,
  applyMiddleware(
    thunkMiddleware
  )
)

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path='/examples/react-redux-websocket/' component={App} />
      <Route path='/examples/react-redux-websocket/chat/:chatid/participant/:participantid' component={Chat} />
      <Route path='/examples/react-redux-websocket/chat/:chatid' component={Chat} />
      <Route path='/examples/react-redux-websocket/*' component={NoMatch} />
    </Router>
  </Provider>,
  document.getElementById('root')
)
<commit_msg>Bug fixed<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import App from './containers/App'
import Chat from './containers/Chat'
import NoMatch from './containers/NoMatch'
import './index.css'
import { createStore, applyMiddleware } from 'redux'
import reducer from './reducers/index'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import thunkMiddleware from 'redux-thunk'

const store = createStore(
  reducer,
  applyMiddleware(
    thunkMiddleware
  )
)

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path='/examples/react-redux-websocket' component={App} />
      <Route path='/examples/react-redux-websocket/chat/:chatid/participant/:participantid' component={Chat} />
      <Route path='/examples/react-redux-websocket/chat/:chatid' component={Chat} />
      <Route path='/examples/react-redux-websocket/*' component={NoMatch} />
    </Router>
  </Provider>,
  document.getElementById('root')
)
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory } from 'react-router'

import Home from './Home.react.js';
import BookList from './BookList.react.js';
import App from './App';

import ReactGA from 'react-ga';
ReactGA.initialize('UA-79927051-1');

import '../styles/styles.scss';

function logPageView() {
  ReactGA.set({ page: window.location.pathname });
  ReactGA.pageview(window.location.pathname);
}

ReactDOM.render((
  <Router history={hashHistory} onUpdate={logPageView}>
    <Route path="/" component={Home} />
    <Route path="/books" component={BookList} />
    <Route path="/books/:bookId" component={App}>
    </Route>
  </Router>
), document.getElementById('root'));
<commit_msg>Add Google Analytics tracking id<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory } from 'react-router'

import Home from './Home.react.js';
import BookList from './BookList.react.js';
import App from './App';

import ReactGA from 'react-ga';
ReactGA.initialize('UA-97640185-1');

import '../styles/styles.scss';

function logPageView() {
  ReactGA.set({ page: window.location.pathname });
  ReactGA.pageview(window.location.pathname);
}

ReactDOM.render((
  <Router history={hashHistory} onUpdate={logPageView}>
    <Route path="/" component={Home} />
    <Route path="/books" component={BookList} />
    <Route path="/books/:bookId" component={App}>
    </Route>
  </Router>
), document.getElementById('root'));
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var fs = require('fs');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var helmet = require('helmet');
var minimist = require('minimist');

// Config variables.
var args = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
  },
  boolean: [
    'geometry',
    'libosrm',
    'override'
  ],
  default: {
    port: 3000,                 // expressjs port
    path: '',                   // VROOM path (if not in $PATH)
    maxjobs: '1000',            // max number of jobs
    geometry: false,            // retrieve geometry (-g)
    libosrm: false,             // use libosrm (-l)
    osrm_address: "0.0.0.0",
    osrm_port: 5000,
    override: true,             // allow cl option override (-g only so far)
    logdir: __dirname + '/..',  // put logs in there
    limit: '1mb',               // max request size
    timeout: 5 * 60 * 1000      // milli-seconds.
  }
});

// App and loaded modules.
var app = express();

// Enable cross-origin ressource sharing.
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
             "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(bodyParser.json({limit: args['limit']}));
app.use(bodyParser.urlencoded({limit: args['limit'], extended: true}));

var accessLogStream = fs.createWriteStream(args['logdir'] + '/access.log',
                                           {flags: 'a'});

app.use(morgan('combined', {stream: accessLogStream}));

app.use(helmet());

app.use(function(err, req, res, next) {
  res.setHeader('Content-Type', 'application/json');
  if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
    console.log(now() + ' - ' + 'Invalid JSON');
    res.send({code: 1, error: 'Invalid json.'});
  }
});

// Simple date generator for console output.
var now = function() {
  var date = new Date();
  return date.toUTCString();
}

// Callback for size and some input validity checks.
var sizeCheckCallback = function(maxJobNumber) {
  return function (req, res, next) {
    var correctInput = ('jobs' in req.body)
        && ('vehicles' in req.body)
        && (req.body['vehicles'].length >= 1);

    if (!correctInput) {
      res.send({code: 1, error: 'Invalid query.'});
      return;
    }

    if (req.body['jobs'].length > maxJobNumber) {
      console.log(now()
                  + ' - Too many jobs in query ('
                  + req.body['jobs'].length + ')');
      res.send({code: 1, error: 'Too many jobs.'});
      return;
    }
    next();
  }
}

// Cli wrapper and associated callback.
var spawn = require('child_process').spawn;

var vroomCommand = args['path'] + 'vroom';
var options = [];
if (args['libosrm']) {
  options.push('-l');
} else {
  options.push('-a', args['osrm_address']);
  options.push('-p', args['osrm_port']);
}
if (args['geometry']) {
  options.push('-g');
}

// As of v5.1.0, profile name doesn't matter, so car will do until it
// should be made into a variable.
options.push('-m', 'car');

var execCallback = function (req, res) {
  var reqOptions = options.slice();
  if (!args['geometry'] && args['override']
     && 'options' in req.body && 'g' in req.body['options']
     && req.body['options']['g']) {
    reqOptions.push('-g');
  }

  reqOptions.push(JSON.stringify(req.body));
  var vroom = spawn(vroomCommand, reqOptions);

  vroom.on('error', function(err) {
    console.log(now() + ' - ' + err);
    res.send({code: 1, error: 'Unfound command: ' + vroomCommand});
  });

  vroom.stdout.pipe(res);

  vroom.stderr.on('data', function (data) {
    console.log(now() + ' - ' + data.toString());
  });
}

app.post('/', [sizeCheckCallback(args['maxjobs']), execCallback]);

var server = app.listen(args['port'], function () {
  console.log('vroom-express listening on port ' + args['port'] + '!');
});

server.setTimeout(args['timeout']);
<commit_msg>Update to new CLI introduced with profile selection.<commit_after>'use strict';

var express = require('express');
var fs = require('fs');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var helmet = require('helmet');
var minimist = require('minimist');

// Config variables.
var args = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    r: 'router',
  },
  boolean: [
    'geometry',
    'override'
  ],
  default: {
    port: 3000,                 // expressjs port
    path: '',                   // VROOM path (if not in $PATH)
    maxjobs: '1000',            // max number of jobs
    geometry: false,            // retrieve geometry (-g)
    router: "osrm",             // routing backend
    router_address: "0.0.0.0",
    router_port: 5000,
    override: true,             // allow cl option override (-g only so far)
    logdir: __dirname + '/..',  // put logs in there
    limit: '1mb',               // max request size
    timeout: 5 * 60 * 1000      // milli-seconds.
  }
});

// App and loaded modules.
var app = express();

// Enable cross-origin ressource sharing.
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
             "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(bodyParser.json({limit: args['limit']}));
app.use(bodyParser.urlencoded({limit: args['limit'], extended: true}));

var accessLogStream = fs.createWriteStream(args['logdir'] + '/access.log',
                                           {flags: 'a'});

app.use(morgan('combined', {stream: accessLogStream}));

app.use(helmet());

app.use(function(err, req, res, next) {
  res.setHeader('Content-Type', 'application/json');
  if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
    console.log(now() + ' - ' + 'Invalid JSON');
    res.send({code: 1, error: 'Invalid json.'});
  }
});

// Simple date generator for console output.
var now = function() {
  var date = new Date();
  return date.toUTCString();
}

// Callback for size and some input validity checks.
var sizeCheckCallback = function(maxJobNumber) {
  return function (req, res, next) {
    var correctInput = ('jobs' in req.body)
        && ('vehicles' in req.body)
        && (req.body['vehicles'].length >= 1);

    if (!correctInput) {
      res.send({code: 1, error: 'Invalid query.'});
      return;
    }

    if (req.body['jobs'].length > maxJobNumber) {
      console.log(now()
                  + ' - Too many jobs in query ('
                  + req.body['jobs'].length + ')');
      res.send({code: 1, error: 'Too many jobs.'});
      return;
    }
    next();
  }
}

// Cli wrapper and associated callback.
var spawn = require('child_process').spawn;

var vroomCommand = args['path'] + 'vroom';
var options = [];
options.push('-r', args['router']);
options.push('-a', args['router_address']);
options.push('-p', args['router_port']);
if (args['geometry']) {
  options.push('-g');
}

var execCallback = function (req, res) {
  var reqOptions = options.slice();
  if (!args['geometry'] && args['override']
     && 'options' in req.body && 'g' in req.body['options']
     && req.body['options']['g']) {
    reqOptions.push('-g');
  }

  reqOptions.push(JSON.stringify(req.body));
  var vroom = spawn(vroomCommand, reqOptions);

  vroom.on('error', function(err) {
    console.log(now() + ' - ' + err);
    res.send({code: 1, error: 'Unfound command: ' + vroomCommand});
  });

  vroom.stdout.pipe(res);

  vroom.stderr.on('data', function (data) {
    console.log(now() + ' - ' + data.toString());
  });
}

app.post('/', [sizeCheckCallback(args['maxjobs']), execCallback]);

var server = app.listen(args['port'], function () {
  console.log('vroom-express listening on port ' + args['port'] + '!');
});

server.setTimeout(args['timeout']);
<|endoftext|>


<commit_before>var m = require('mithril');

exports.controller = function () {
  var ctrl = this;
  ctrl.allApps;

  m.request({ method: 'GET', url: '/api/allApps'})
    .then(function(apps) {
      ctrl.allApps = m.prop({1:[],2:[],3:[]});
      console.log(apps, 'APPS from server')
      apps.Applications.forEach(function(app){
        ctrl.allApps()[app.phase].push(app)
      })

      console.log(ctrl.allApps()[1], 'asdfsdf')
      return ctrl.allApps();
    });
}

exports.view = function (ctrl) {
  return m('.col.m9.s12', [
    m('h1.center-align', 'Phase I'),
    m('ul.collection', [
      ctrl.allApps()[1].map(function(app){
        if(app.phase === '1'){
          return m('li.collection-item avatar', [
            m('img[' + app.avatar_url + '].circle'),
            m('span.title', 'WILL BE NAME: ' + app.user_id),
            m('p', 'Title: ' + app.title),
            m('p', 'Company: ' + app.name),
            // m('a.waves-effect.waves-light.secondary-content.btn[href=#]', 'update')
          ])
        }
      })
    ]),
    m('h1.center-align', 'Phase II'),
    m('ul.collection', [
      ctrl.allApps()[2].map(function(app){
        if(app.phase === '2'){
          return m('li.collection-item avatar', [
            m('img[src=https://avatars.githubusercontent.com/u/5953350?v=3].circle'),
            m('span.title', 'WILL BE NAME: ' + app.user_id),
            m('p', 'Title: ' + app.title),
            m('p', 'Company: ' + app.name),
            m('a.waves-effect.waves-light.secondary-content.btn[href=#]', 'update')
          ])
        }
      })
    ]),
    m('h1.center-align', 'Phase III'),
    m('ul.collection', [
      ctrl.allApps()[3].map(function(app){
        if(app.phase === '3'){
          return m('li.collection-item avatar', [
            m('img[src=https://avatars.githubusercontent.com/u/5953350?v=3].circle'),
            m('span.title', 'WILL BE NAME: ' + app.user_id),
            m('p', 'Title: ' + app.title),
            m('p', 'Company: ' + app.name),
            m('a.waves-effect.waves-light.secondary-content.btn[href=#]', 'update')
          ])
        }
      })
    ])
  ])
};<commit_msg>Added name outcomes apps<commit_after>var m = require('mithril');

exports.controller = function () {
  var ctrl = this;
  ctrl.allApps;

  m.request({ method: 'GET', url: '/api/allApps'})
    .then(function(apps) {
      ctrl.allApps = m.prop({1:[],2:[],3:[]});
      console.log(apps, 'APPS from server')
      apps.Applications.forEach(function(app){
        ctrl.allApps()[app.phase].push(app)
      })

      console.log(ctrl.allApps()[1], 'asdfsdf')
      return ctrl.allApps();
    });
}

exports.view = function (ctrl) {
  return m('.col.m9.s12', [
    m('h1.center-align', 'Phase I'),
    m('ul.collection', [
      ctrl.allApps()[1].map(function(app){
        if(app.phase === '1'){
          return m('li.collection-item avatar', [
            m('img[src=' + app.avatar_url + '].circle'),
            m('span.title', app.name),
            m('p', 'Title: ' + app.title),
            m('p', 'Company: ' + app.name),
            // m('a.waves-effect.waves-light.secondary-content.btn[href=#]', 'update')
          ])
        }
      })
    ]),
    m('h1.center-align', 'Phase II'),
    m('ul.collection', [
      ctrl.allApps()[2].map(function(app){
        if(app.phase === '2'){
          return m('li.collection-item avatar', [
            m('img[src=https://avatars.githubusercontent.com/u/5953350?v=3].circle'),
            m('span.title', 'WILL BE NAME: ' + app.user_id),
            m('p', 'Title: ' + app.title),
            m('p', 'Company: ' + app.name),
            m('a.waves-effect.waves-light.secondary-content.btn[href=#]', 'update')
          ])
        }
      })
    ]),
    m('h1.center-align', 'Phase III'),
    m('ul.collection', [
      ctrl.allApps()[3].map(function(app){
        if(app.phase === '3'){
          return m('li.collection-item avatar', [
            m('img[src=https://avatars.githubusercontent.com/u/5953350?v=3].circle'),
            m('span.title', 'WILL BE NAME: ' + app.user_id),
            m('p', 'Title: ' + app.title),
            m('p', 'Company: ' + app.name),
            m('a.waves-effect.waves-light.secondary-content.btn[href=#]', 'update')
          ])
        }
      })
    ])
  ])
};<|endoftext|>