<commit_before>import { argv } from 'yargs';
import fs from 'fs';
import path from 'path';
import mkdirp from 'mkdirp';
import moment from 'moment';
import { ExifImage } from 'exif';
import { parse } from 'exif-date';
import { copy } from 'fs-extra';

const src = argv.s || argv.src || argv.source;
const pictureDir = argv.pictures;
const movieDir = argv.movies;
const recursive = !!(argv.r || argv.recurse || argv.recursive);
const pictureNameFormat = argv.picture || 'YYYY/YYYY-MM/YYYY-MM-DD/YYYY-MM-DD-HH-mm-ss';
const movieNameFormat = argv.movie || 'YYYY-MM-DD-HH-mm-ss';

if (!src || !fs.statSync(src).isDirectory()) {
    console.log('You must specify --src as the path to a directory');
    process.exit(1);
}

if (!pictureDir || !fs.existsSync(pictureDir) || !fs.statSync(pictureDir).isDirectory()) {
    console.log('You must specify --pictures as the path to a directory');
    process.exit(1);
}

if (!movieDir || !fs.existsSync(movieDir) || !fs.statSync(movieDir).isDirectory()) {
    console.log('You must specify --movies as the path to a directory');
    process.exit(1);
}

function processDirectory(srcDirectory, recurse, pictureDir, movieDir, pictureNameFormat, movieNameFormat) {
    console.log(`Processing ${srcDirectory}${recursive && ', recursively'}`);

    fs.readdir(srcDirectory, (dirErr, files) => {
        files.forEach((file) => {
            if (isIgnored(file)) {
                return;
            }

            const filePath = path.join(srcDirectory, file);
            console.log(`Processing ${filePath}`);

            fs.stat(filePath, (statErr, stats) => {
                if (statErr) {
                    console.warn(`Error processing ${filePath}\n${statErr}`);
                } else if (stats) {
                    if (stats.isDirectory()) {
                        if (recurse) {
                            processDirectory(filePath, recurse, pictureDir, movieDir, pictureNameFormat, movieNameFormat);
                        }
                    } else if (stats.isFile()) {
                        switch (path.extname(filePath).toLowerCase()) {
                            case '.jpg':
                            case '.jpeg':
                                processJpeg(filePath, pictureDir, pictureNameFormat);
                                break;

                            case '.mov':
                            case '.avi':
                                processMovie(filePath, movieDir, movieNameFormat);
                                break;

                            default:
                                console.log(`Unrecognized file type for ${filePath}`);
                        }
                    }
                }
            });
        });
    });
}

function processJpeg(image, destDirectory, filenameFormat) {
    console.log(`Processing jpeg file ${image}`);

    new ExifImage({ image }, (imageErr, { exif }) => {
        if (imageErr) {
            console.warn(`Error processing EXIF data for ${image}.\n${imageErr}\n\nUsing file creation date.`);

            fs.stat(image, (statErr, stats) => {
                if (statErr) {
                    console.warn(`Error processing file ${image}.\n${statErr}`);
                    return;
                }

                const { birthtime } = stats;
                copyFile(image, birthtime, destDirectory, filenameFormat);
            });

            return;
        }

        const { DateTimeOriginal } = exif;
        const parsedDate = parse(DateTimeOriginal);

        copyFile(image, parsedDate, destDirectory, filenameFormat);
    });
}

function processMovie(movie, destDirectory, filenameFormat) {
    console.log(`Processing movie file ${movie}`);

    fs.stat(movie, (statErr, stats) => {
        if (statErr) {
            console.warn(`Error processing movie ${movie}.\n${statErr}`);
            return;
        }

        const { birthtime } = stats;
        copyFile(movie, birthtime, destDirectory, filenameFormat);
    });
}

function copyFile(filePath, timestamp, destDirectory, filenameFormat) {
    const ext = path.extname(filePath).toLowerCase();
    const destFileName = moment(timestamp).format(filenameFormat) + ext;
    const destFilePath = path.join(destDirectory, destFileName);
    const destFileDir = path.dirname(destFilePath);

    mkdirp(destFileDir, (mkdirpErr) => {
        fs.exists(destFilePath, (exists) => {
            if (exists) {
                console.log(`${destFilePath} exists. Skipping.`);
            } else {
                copy(filePath, destFilePath, (copyErr) => {
                    if (copyErr) {
                        console.log(`Error creating ${destFilePath}.\n${copyErr}`);
                    } else {
                        console.log(`Created ${destFilePath}`);
                    }
                });
            }
        });
    });
}

function isIgnored(file) {
    if (path.basename(file).toLowerCase() === '.ds_store') {
        return true;
    }

    if (path.extname(file).toLowerCase() === '.thm') {
        return true;
    }

    return false;
}

recursive && console.log('Using recursive mode');

processDirectory(src, recursive, pictureDir, movieDir, pictureNameFormat, movieNameFormat);
<commit_msg>More movie file extensions<commit_after>import { argv } from 'yargs';
import fs from 'fs';
import path from 'path';
import mkdirp from 'mkdirp';
import moment from 'moment';
import { ExifImage } from 'exif';
import { parse } from 'exif-date';
import { copy } from 'fs-extra';

const src = argv.s || argv.src || argv.source;
const pictureDir = argv.pictures;
const movieDir = argv.movies;
const recursive = !!(argv.r || argv.recurse || argv.recursive);
const pictureNameFormat = argv.picture || 'YYYY/YYYY-MM/YYYY-MM-DD/YYYY-MM-DD-HH-mm-ss';
const movieNameFormat = argv.movie || 'YYYY-MM-DD-HH-mm-ss';

if (!src || !fs.statSync(src).isDirectory()) {
    console.log('You must specify --src as the path to a directory');
    process.exit(1);
}

if (!pictureDir || !fs.existsSync(pictureDir) || !fs.statSync(pictureDir).isDirectory()) {
    console.log('You must specify --pictures as the path to a directory');
    process.exit(1);
}

if (!movieDir || !fs.existsSync(movieDir) || !fs.statSync(movieDir).isDirectory()) {
    console.log('You must specify --movies as the path to a directory');
    process.exit(1);
}

function processDirectory(srcDirectory, recurse, pictureDir, movieDir, pictureNameFormat, movieNameFormat) {
    console.log(`Processing ${srcDirectory}${recursive && ', recursively'}`);

    fs.readdir(srcDirectory, (dirErr, files) => {
        files.forEach((file) => {
            if (isIgnored(file)) {
                return;
            }

            const filePath = path.join(srcDirectory, file);
            console.log(`Processing ${filePath}`);

            fs.stat(filePath, (statErr, stats) => {
                if (statErr) {
                    console.warn(`Error processing ${filePath}\n${statErr}`);
                } else if (stats) {
                    if (stats.isDirectory()) {
                        if (recurse) {
                            processDirectory(filePath, recurse, pictureDir, movieDir, pictureNameFormat, movieNameFormat);
                        }
                    } else if (stats.isFile()) {
                        switch (path.extname(filePath).toLowerCase()) {
                            case '.jpg':
                            case '.jpeg':
                                processJpeg(filePath, pictureDir, pictureNameFormat);
                                break;

                            case '.mov':
                            case '.avi':
                            case '.3gp':
                            case '.mp4':
                                processMovie(filePath, movieDir, movieNameFormat);
                                break;

                            default:
                                console.log(`Unrecognized file type for ${filePath}`);
                        }
                    }
                }
            });
        });
    });
}

function processJpeg(image, destDirectory, filenameFormat) {
    console.log(`Processing jpeg file ${image}`);

    new ExifImage({ image }, (imageErr, { exif }) => {
        if (imageErr) {
            console.warn(`Error processing EXIF data for ${image}.\n${imageErr}\n\nUsing file creation date.`);

            fs.stat(image, (statErr, stats) => {
                if (statErr) {
                    console.warn(`Error processing file ${image}.\n${statErr}`);
                    return;
                }

                const { birthtime } = stats;
                copyFile(image, birthtime, destDirectory, filenameFormat);
            });

            return;
        }

        const { DateTimeOriginal } = exif;
        const parsedDate = parse(DateTimeOriginal);

        copyFile(image, parsedDate, destDirectory, filenameFormat);
    });
}

function processMovie(movie, destDirectory, filenameFormat) {
    console.log(`Processing movie file ${movie}`);

    fs.stat(movie, (statErr, stats) => {
        if (statErr) {
            console.warn(`Error processing movie ${movie}.\n${statErr}`);
            return;
        }

        const { birthtime } = stats;
        copyFile(movie, birthtime, destDirectory, filenameFormat);
    });
}

function copyFile(filePath, timestamp, destDirectory, filenameFormat) {
    const ext = path.extname(filePath).toLowerCase();
    const destFileName = moment(timestamp).format(filenameFormat) + ext;
    const destFilePath = path.join(destDirectory, destFileName);
    const destFileDir = path.dirname(destFilePath);

    mkdirp(destFileDir, (mkdirpErr) => {
        fs.exists(destFilePath, (exists) => {
            if (exists) {
                console.log(`${destFilePath} exists. Skipping.`);
            } else {
                copy(filePath, destFilePath, (copyErr) => {
                    if (copyErr) {
                        console.log(`Error creating ${destFilePath}.\n${copyErr}`);
                    } else {
                        console.log(`Created ${destFilePath}`);
                    }
                });
            }
        });
    });
}

function isIgnored(file) {
    if (path.basename(file).toLowerCase() === '.ds_store') {
        return true;
    }

    if (path.extname(file).toLowerCase() === '.thm') {
        return true;
    }

    return false;
}

recursive && console.log('Using recursive mode');

processDirectory(src, recursive, pictureDir, movieDir, pictureNameFormat, movieNameFormat);
<|endoftext|>


<commit_before>'use strict'
// Copyright 2016 Net at Work GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	 http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
let Promise = require('rsvp').Promise;
let asp = require('rsvp').denodeify;
let fs = require('graceful-fs');
let path = require('path');
let gutil = require('gulp-util');
let spawn = require('child_process').spawn;

let dependencyPath = 'jspm_packages/local';

async function getPackageObject(packageFile) {
	try {
		let lookupJSON = await asp(fs.readFile)(packageFile);
		return JSON.parse(lookupJSON.toString());
	}
	catch (e) {
		if (e.code == 'ENOENT' || e instanceof SyntaxError)
			return { notfound: true };
		throw e;
	}
}

function fileExists (filepath) {
	if (!filepath) return false

	try {
		return fs.statSync(filepath).isFile();
	} catch (e) {
		return false;
	}
}

async function processDependency(packagePath, options) {
	let packageName = packagePath.substring(0, packagePath.indexOf('@'));
	gutil.log("Compiling package", gutil.colors.yellow(packageName));

	let project = await getPackageObject(path.resolve('..', path.join(packageName, 'package.json')));
	let projectPath = path.resolve(path.join("..", packageName));

	let npmInstall = (options && options.npmInstall) ||true;
	let jspmInstall = (options && options.jspmInstall) || true;
	let gulpBuild = (otpions && options.gulpBuild) || true;

	if(npmInstall) {
		await executeNpm(projectPath, "install");
	}

	let isJspmPresent = project.devDependencies !== undefined && project.devDependencies["jspm"] != null;
	if (jspmInstall && isJspmPresent) {
		gutil.log(gutil.colors.yellow("jspm"), "is configured in this package. Running", gutil.colors.yellow("jspm install"));
		await executeJspm(projectPath);
	}

	if (gulpBuild && fileExists(path.join(projectPath, "gulpfile.js"))) {
		gutil.log(gutil.colors.yellow("gulp"), "is configured in this package. Running", gutil.colors.yellow("gulp build"));
		await executeGulp(projectPath);
	}
}

export function executeGulp(packagePath, tasks) {
	gutil.log("Processing", gutil.colors.yellow("gulp"), "for", gutil.colors.yellow(packagePath));
	return spawnProcess("gulp", packagePath, tasks || ["build"]);
}

export function executeJspm(packagePath) {
	gutil.log("Processing", gutil.colors.yellow("jspm"), "for", gutil.colors.yellow(packagePath));
	return spawnProcess("jspm", packagePath || path.resolve("."), ["install"]);
}

export function executeNpm(packagePath, action) {
	gutil.log("Processing", gutil.colors.yellow("npm"), "for", gutil.colors.yellow(packagePath));
	return spawnProcess("npm", packagePath || path.resolve("."), [action || "install"]);
}

function spawnProcess(command, workingDirectory, args) {
	let runningOnWindows = /^win/.test(process.platform);
	let nodeModulesPath = path.join(workingDirectory, 'node_modules', '.bin');
	let envCopy = {};
	for (let e in process.env) envCopy[e] = process.env[e];

	if (runningOnWindows) {
		envCopy.Path += ';' + nodeModulesPath;
	} else {
		envCopy.PATH += ':' + nodeModulesPath;
	}

	let opts = {
		cwd: workingDirectory,
		env: envCopy,
		stdio: 'inherit',
		stderr: 'inherit'
	}
	let commandToExecute = command;

	if (runningOnWindows) {
		args = ['/s', '/c',	command + ".cmd"].concat(args);
		commandToExecute = 'cmd';

		opts.windowsVerbatimArguments = true;
	}

	return new Promise((resolve, reject) => {
		let proc = spawn(commandToExecute, args, opts);
		proc.on('close', function(code) {
			let error;

			if (code == 0) {
				resolve();
				return;
			}
			error = new gutil.PluginError(`${command} on ${packagePath} returned ${code}`);
			reject(error);
		});
	});
}

function isDirectory(fileName) {
	let filePath = path.resolve(dependencyPath, fileName);
	return fs.lstatSync(filePath).isDirectory();
}

async function getLocalDependencies() {
	let packageConfig = await getPackageObject("package.json");

	if (!packageConfig.jspm || !packageConfig.jspm.dependencies) throw "package.json does have jspm configured.";

	let localDepedencies = [];

	var dependencies = packageConfig.jspm.dependencies;
	for (let dependency in dependencies)
	{
		var value = dependencies[dependency];
		if (value.indexOf("local:") == 0) {
			localDepedencies.push(value.substring("local:".length))
		}
	}
	return localDepedencies;
}

export async function buildDependencies(options) {
	gutil.log("Building local dependencies");
	let dependencies = await getLocalDependencies();
	for (let entry of dependencies) {
		await processDependency(entry,options);
	}
}
<commit_msg>Fixed code error<commit_after>'use strict'
// Copyright 2016 Net at Work GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	 http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
let Promise = require('rsvp').Promise;
let asp = require('rsvp').denodeify;
let fs = require('graceful-fs');
let path = require('path');
let gutil = require('gulp-util');
let spawn = require('child_process').spawn;

let dependencyPath = 'jspm_packages/local';

async function getPackageObject(packageFile) {
	try {
		let lookupJSON = await asp(fs.readFile)(packageFile);
		return JSON.parse(lookupJSON.toString());
	}
	catch (e) {
		if (e.code == 'ENOENT' || e instanceof SyntaxError)
			return { notfound: true };
		throw e;
	}
}

function fileExists (filepath) {
	if (!filepath) return false

	try {
		return fs.statSync(filepath).isFile();
	} catch (e) {
		return false;
	}
}

async function processDependency(packagePath, options) {
	let packageName = packagePath.substring(0, packagePath.indexOf('@'));
	gutil.log("Compiling package", gutil.colors.yellow(packageName));

	let project = await getPackageObject(path.resolve('..', path.join(packageName, 'package.json')));
	let projectPath = path.resolve(path.join("..", packageName));

	let npmInstall = (options && options.npmInstall) ||true;
	let jspmInstall = (options && options.jspmInstall) || true;
	let gulpBuild = (options && options.gulpBuild) || true;

	if(npmInstall) {
		await executeNpm(projectPath, "install");
	}

	let isJspmPresent = project.devDependencies !== undefined && project.devDependencies["jspm"] != null;
	if (jspmInstall && isJspmPresent) {
		gutil.log(gutil.colors.yellow("jspm"), "is configured in this package. Running", gutil.colors.yellow("jspm install"));
		await executeJspm(projectPath);
	}

	if (gulpBuild && fileExists(path.join(projectPath, "gulpfile.js"))) {
		gutil.log(gutil.colors.yellow("gulp"), "is configured in this package. Running", gutil.colors.yellow("gulp build"));
		await executeGulp(projectPath);
	}
}

export function executeGulp(packagePath, tasks) {
	gutil.log("Processing", gutil.colors.yellow("gulp"), "for", gutil.colors.yellow(packagePath));
	return spawnProcess("gulp", packagePath, tasks || ["build"]);
}

export function executeJspm(packagePath) {
	gutil.log("Processing", gutil.colors.yellow("jspm"), "for", gutil.colors.yellow(packagePath));
	return spawnProcess("jspm", packagePath || path.resolve("."), ["install"]);
}

export function executeNpm(packagePath, action) {
	gutil.log("Processing", gutil.colors.yellow("npm"), "for", gutil.colors.yellow(packagePath));
	return spawnProcess("npm", packagePath || path.resolve("."), [action || "install"]);
}

function spawnProcess(command, workingDirectory, args) {
	let runningOnWindows = /^win/.test(process.platform);
	let nodeModulesPath = path.join(workingDirectory, 'node_modules', '.bin');
	let envCopy = {};
	for (let e in process.env) envCopy[e] = process.env[e];

	if (runningOnWindows) {
		envCopy.Path += ';' + nodeModulesPath;
	} else {
		envCopy.PATH += ':' + nodeModulesPath;
	}

	let opts = {
		cwd: workingDirectory,
		env: envCopy,
		stdio: 'inherit',
		stderr: 'inherit'
	}
	let commandToExecute = command;

	if (runningOnWindows) {
		args = ['/s', '/c',	command + ".cmd"].concat(args);
		commandToExecute = 'cmd';

		opts.windowsVerbatimArguments = true;
	}

	return new Promise((resolve, reject) => {
		let proc = spawn(commandToExecute, args, opts);
		proc.on('close', function(code) {
			let error;

			if (code == 0) {
				resolve();
				return;
			}
			error = new gutil.PluginError(`${command} on ${packagePath} returned ${code}`);
			reject(error);
		});
	});
}

function isDirectory(fileName) {
	let filePath = path.resolve(dependencyPath, fileName);
	return fs.lstatSync(filePath).isDirectory();
}

async function getLocalDependencies() {
	let packageConfig = await getPackageObject("package.json");

	if (!packageConfig.jspm || !packageConfig.jspm.dependencies) throw "package.json does have jspm configured.";

	let localDepedencies = [];

	var dependencies = packageConfig.jspm.dependencies;
	for (let dependency in dependencies)
	{
		var value = dependencies[dependency];
		if (value.indexOf("local:") == 0) {
			localDepedencies.push(value.substring("local:".length))
		}
	}
	return localDepedencies;
}

export async function buildDependencies(options) {
	gutil.log("Building local dependencies");
	let dependencies = await getLocalDependencies();
	for (let entry of dependencies) {
		await processDependency(entry,options);
	}
}
<|endoftext|>


<commit_before>// @flow
const { execSync, spawn } = require('child_process')
const path = require('path')
const { RunJSError, logger } = require('./common')

const loggerAlias = logger

type Options = {
  cwd?: string,
  async?: boolean,
  stdio?: string | Array<any>,
  env?: Object,
  timeout?: number,
  shell?: boolean
}

function runSync (command: string, options: Options) : ?string {
  try {
    const nextOptions = {
      cwd: options.cwd,
      env: options.env,
      stdio: options.stdio,
      timeout: options.timeout
    }
    const buffer = execSync(command, nextOptions)
    if (buffer) {
      return buffer.toString()
    }
    return buffer
  } catch (error) {
    throw new RunJSError(error.message)
  }
}

function runAsync (command: string, options: Options): Promise<?string> {
  return new Promise((resolve, reject) => {
    const nextOptions = {
      cwd: options.cwd,
      env: options.env,
      stdio: options.stdio,
      shell: options.shell
    }
    const asyncProcess = spawn(command, nextOptions)
    let output : ?string = null

    asyncProcess.on('error', (error) => {
      reject(new Error(`Failed to start command: ${command}; ${error}`))
    })

    asyncProcess.on('close', (exitCode) => {
      if (exitCode === 0) {
        resolve(output)
      } else {
        reject(new Error(`Command failed: ${command} with exit code ${exitCode}`))
      }
    })

    if (options.stdio === 'pipe') {
      asyncProcess.stdout.on('data', (buffer: Buffer) => {
        output = buffer.toString()
      })
    }

    if (options.timeout) {
      setTimeout(() => {
        asyncProcess.kill()
        reject(new Error(`Command timeout: ${command}`))
      }, options.timeout)
    }
  })
}

function run (command: string, options: Options = {}, logger = loggerAlias) {
  const binPath = path.resolve('./node_modules/.bin')

  // Pick relevant option keys and set default values
  options = {
    env: options.env || process.env,
    cwd: options.cwd,
    async: !!options.async,
    stdio: options.stdio || 'inherit',
    timeout: options.timeout,
    shell: true
  }

  const env = options.env

  // Include in PATH node_modules bin path
  if (env) {
    env.PATH = [binPath, env.PATH || process.env.PATH].join(path.delimiter)
  }

  logger.info(command)

  // Handle async call
  if (options.async) {
    return runAsync(command, options)
  }

  // Handle sync call by default
  return runSync(command, options)
}

/**
 * @deprecated
 */
function option (thisObj: ?Object, name: string): mixed {
  return (thisObj && thisObj.options && thisObj.options[name]) || null
}

function options (thisObj: ?Object): Object {
  return (thisObj && thisObj.options) || {}
}

module.exports = {
  run,
  option,
  options
}
<commit_msg>Improving type declarations<commit_after>// @flow
const { execSync, spawn } = require('child_process')
const path = require('path')
const { RunJSError, logger } = require('./common')

const loggerAlias = logger

type Options = {
  cwd?: string,
  async?: boolean,
  stdio?: string | Array<any>,
  env?: Object,
  timeout?: number
}

function runSync (command: string, options: Options) : ?string {
  try {
    const nextOptions = {
      cwd: options.cwd,
      env: options.env,
      stdio: options.stdio,
      timeout: options.timeout
    }
    const buffer: string | Buffer = execSync(command, nextOptions)
    if (buffer) {
      return buffer.toString()
    }
    return buffer
  } catch (error) {
    throw new RunJSError(error.message)
  }
}

function runAsync (command: string, options: Options): Promise<?string> {
  return new Promise((resolve, reject) => {
    const nextOptions = {
      cwd: options.cwd,
      env: options.env,
      stdio: options.stdio,
      shell: true
    }
    const asyncProcess = spawn(command, nextOptions)
    let output : ?string = null

    asyncProcess.on('error', (error) => {
      reject(new Error(`Failed to start command: ${command}; ${error}`))
    })

    asyncProcess.on('close', (exitCode) => {
      if (exitCode === 0) {
        resolve(output)
      } else {
        reject(new Error(`Command failed: ${command} with exit code ${exitCode}`))
      }
    })

    if (options.stdio === 'pipe') {
      asyncProcess.stdout.on('data', (buffer: Buffer) => {
        output = buffer.toString()
      })
    }

    if (options.timeout) {
      setTimeout(() => {
        asyncProcess.kill()
        reject(new Error(`Command timeout: ${command}`))
      }, options.timeout)
    }
  })
}

function run (command: string, options: Options = {}, logger = loggerAlias) {
  const binPath = path.resolve('./node_modules/.bin')

  // Pick relevant option keys and set default values
  options = {
    env: options.env || process.env,
    cwd: options.cwd,
    async: !!options.async,
    stdio: options.stdio || 'inherit',
    timeout: options.timeout
  }

  const env = options.env

  // Include in PATH node_modules bin path
  if (env) {
    env.PATH = [binPath, env.PATH || process.env.PATH].join(path.delimiter)
  }

  logger.info(command)

  // Handle async call
  if (options.async) {
    return runAsync(command, options)
  }

  // Handle sync call by default
  return runSync(command, options)
}

/**
 * @deprecated
 */
function option (thisObj: ?Object, name: string): mixed {
  return (thisObj && thisObj.options && thisObj.options[name]) || null
}

function options (thisObj: ?Object): Object {
  return (thisObj && thisObj.options) || {}
}

module.exports = {
  run,
  option,
  options
}
<|endoftext|>


<commit_before>export default function thunkMiddleware({ dispatch, getState }) {
  return next => action =>
    typeof action === 'function' ?
      action(dispatch, getState) :
      next(action);
}
<commit_msg>Use CommonJS until Babel ES3 transforms are fixed<commit_after>function thunkMiddleware({ dispatch, getState }) {
  return next => action =>
    typeof action === 'function' ?
      action(dispatch, getState) :
      next(action);
}

module.exports = thunkMiddleware
<|endoftext|>


<commit_before>'use strict';

const inquirer = require('inquirer');
const run = require('./run');
const getProjectOptions = require('./get-project-options');
const getPackageName = require('./get-package-name');
const getPackageVersion = require('./get-package-version');
const getVersions = require('boilerplate-update/src/get-versions');
const getProjectVersion = require('./get-project-version');
const _getTagVersion = require('./get-tag-version');
const getRemoteUrl = require('./get-remote-url');
const boilerplateUpdate = require('boilerplate-update');
const getStartAndEndCommands = require('./get-start-and-end-commands');
const parseBlueprint = require('./parse-blueprint');
const downloadBlueprint = require('./download-blueprint');
const loadBlueprintFile = require('./load-blueprint-file');
const loadSafeBlueprintFile = require('./load-safe-blueprint-file');
const saveBlueprint = require('./save-blueprint');
const saveDefaultBlueprint = require('./save-default-blueprint');
const checkForBlueprintUpdates = require('./check-for-blueprint-updates');

function formatBlueprintLine(blueprint) {
  return `${blueprint.name}, current: ${blueprint.currentVersion}, latest: ${blueprint.latestVersion}`;
}

module.exports = async function emberCliUpdate({
  blueprint: _blueprint,
  from,
  to,
  resolveConflicts,
  runCodemods,
  reset,
  compareOnly,
  statsOnly,
  listCodemods,
  createCustomDiff,
  wasRunAsExecutable
}) {
  let defaultBlueprint = {
    name: 'ember-cli'
  };

  let cwd = process.cwd();

  let emberCliUpdateJson = await loadSafeBlueprintFile(cwd);

  let blueprint;

  if (_blueprint) {
    blueprint = await parseBlueprint(_blueprint);

    if (from) {
      blueprint.version = from;
    } else {
      let { blueprints } = emberCliUpdateJson;
      let existingBlueprint = blueprints.find(b => b.name === _blueprint);
      if (existingBlueprint) {
        blueprint.location = existingBlueprint.location;
        blueprint.version = existingBlueprint.version;
      }
    }

    if (!blueprint.version) {
      throw new Error('A custom blueprint cannot detect --from. You must supply it.');
    }
  } else {
    let { blueprints } = emberCliUpdateJson;

    if (!blueprints.length) {
      blueprint = defaultBlueprint;
    } else {
      let blueprintUpdates = await checkForBlueprintUpdates(blueprints);

      let areAllUpToDate = blueprintUpdates.every(blueprint => blueprint.isUpToDate);
      if (areAllUpToDate) {
        return `${blueprintUpdates.map(formatBlueprintLine).join(`
`)}

All blueprints are up-to-date!`;
      }

      let choicesByName = blueprintUpdates.reduce((choices, blueprint) => {
        let name = formatBlueprintLine(blueprint);
        choices[name] = {
          realName: blueprint.name,
          choice: {
            name,
            disabled: blueprint.isUpToDate
          }
        };
        return choices;
      }, {});

      let answer = await inquirer.prompt([{
        type: 'list',
        message: 'Blueprint updates have been found. Which one would you like to update?',
        name: 'blueprint',
        choices: Object.values(choicesByName).map(({ choice }) => choice)
      }]);

      let { realName } = choicesByName[answer.blueprint];

      blueprint = blueprints.find(blueprint => blueprint.name === realName);
    }
  }

  if (blueprint && !blueprint.url && blueprint.location) {
    blueprint.url = (await parseBlueprint(blueprint.location)).url;
  }

  let isCustomBlueprint = blueprint.name !== defaultBlueprint.name;

  if (isCustomBlueprint) {
    createCustomDiff = true;
  }

  let endVersion;

  let result = await (await boilerplateUpdate({
    projectOptions: ({ packageJson }) => getProjectOptions(packageJson, blueprint),
    mergeOptions: async function mergeOptions({
      packageJson,
      projectOptions
    }) {
      let startVersion;
      let startBlueprint;
      let endBlueprint;

      if (isCustomBlueprint) {
        startBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, blueprint.version);
        endBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, to);

        startVersion = startBlueprint.version;
        endVersion = endBlueprint.version;

        blueprint.name = startBlueprint.name;
      } else {
        let packageName = getPackageName(projectOptions);
        let packageVersion = getPackageVersion(packageJson, packageName);

        let versions = await getVersions(packageName);

        let getTagVersion = _getTagVersion(versions, packageName);

        if (from) {
          startVersion = await getTagVersion(from);
        } else {
          startVersion = getProjectVersion(packageVersion, versions, projectOptions);
        }

        endVersion = await getTagVersion(to);

        startBlueprint = endBlueprint = blueprint;
      }

      let customDiffOptions;
      if (createCustomDiff) {
        customDiffOptions = getStartAndEndCommands({
          packageJson,
          projectOptions,
          startVersion,
          endVersion,
          startBlueprint,
          endBlueprint
        });
      }

      return {
        startVersion,
        endVersion,
        customDiffOptions
      };
    },
    remoteUrl: ({ projectOptions }) => getRemoteUrl(projectOptions),
    compareOnly,
    resolveConflicts,
    reset,
    statsOnly,
    listCodemods,
    runCodemods,
    codemodsUrl: 'https://raw.githubusercontent.com/ember-cli/ember-cli-update-codemods-manifest/v3/manifest.json',
    createCustomDiff,
    ignoredFiles: ['ember-cli-update.json'],
    wasRunAsExecutable
  })).promise;

  if (_blueprint) {
    let emberCliUpdateJson = await loadBlueprintFile(cwd);

    if (!emberCliUpdateJson && blueprint.name !== defaultBlueprint.name) {
      await saveDefaultBlueprint({
        cwd,
        blueprint: defaultBlueprint
      });
    }

    await saveBlueprint({
      cwd,
      name: blueprint.name,
      location: blueprint.location,
      version: endVersion
    });

    await run('git add ember-cli-update.json');
  } else {
    let { blueprints } = await loadSafeBlueprintFile(cwd);

    let existingBlueprint = blueprints.find(b => b.name === blueprint.name);

    if (existingBlueprint) {
      await saveBlueprint({
        cwd,
        name: blueprint.name,
        version: endVersion
      });

      await run('git add ember-cli-update.json');
    }
  }

  return result;
};
<commit_msg>use isCustomBlueprint<commit_after>'use strict';

const inquirer = require('inquirer');
const run = require('./run');
const getProjectOptions = require('./get-project-options');
const getPackageName = require('./get-package-name');
const getPackageVersion = require('./get-package-version');
const getVersions = require('boilerplate-update/src/get-versions');
const getProjectVersion = require('./get-project-version');
const _getTagVersion = require('./get-tag-version');
const getRemoteUrl = require('./get-remote-url');
const boilerplateUpdate = require('boilerplate-update');
const getStartAndEndCommands = require('./get-start-and-end-commands');
const parseBlueprint = require('./parse-blueprint');
const downloadBlueprint = require('./download-blueprint');
const loadBlueprintFile = require('./load-blueprint-file');
const loadSafeBlueprintFile = require('./load-safe-blueprint-file');
const saveBlueprint = require('./save-blueprint');
const saveDefaultBlueprint = require('./save-default-blueprint');
const checkForBlueprintUpdates = require('./check-for-blueprint-updates');

function formatBlueprintLine(blueprint) {
  return `${blueprint.name}, current: ${blueprint.currentVersion}, latest: ${blueprint.latestVersion}`;
}

module.exports = async function emberCliUpdate({
  blueprint: _blueprint,
  from,
  to,
  resolveConflicts,
  runCodemods,
  reset,
  compareOnly,
  statsOnly,
  listCodemods,
  createCustomDiff,
  wasRunAsExecutable
}) {
  let defaultBlueprint = {
    name: 'ember-cli'
  };

  let cwd = process.cwd();

  let emberCliUpdateJson = await loadSafeBlueprintFile(cwd);

  let blueprint;

  if (_blueprint) {
    blueprint = await parseBlueprint(_blueprint);

    if (from) {
      blueprint.version = from;
    } else {
      let { blueprints } = emberCliUpdateJson;
      let existingBlueprint = blueprints.find(b => b.name === _blueprint);
      if (existingBlueprint) {
        blueprint.location = existingBlueprint.location;
        blueprint.version = existingBlueprint.version;
      }
    }

    if (!blueprint.version) {
      throw new Error('A custom blueprint cannot detect --from. You must supply it.');
    }
  } else {
    let { blueprints } = emberCliUpdateJson;

    if (!blueprints.length) {
      blueprint = defaultBlueprint;
    } else {
      let blueprintUpdates = await checkForBlueprintUpdates(blueprints);

      let areAllUpToDate = blueprintUpdates.every(blueprint => blueprint.isUpToDate);
      if (areAllUpToDate) {
        return `${blueprintUpdates.map(formatBlueprintLine).join(`
`)}

All blueprints are up-to-date!`;
      }

      let choicesByName = blueprintUpdates.reduce((choices, blueprint) => {
        let name = formatBlueprintLine(blueprint);
        choices[name] = {
          realName: blueprint.name,
          choice: {
            name,
            disabled: blueprint.isUpToDate
          }
        };
        return choices;
      }, {});

      let answer = await inquirer.prompt([{
        type: 'list',
        message: 'Blueprint updates have been found. Which one would you like to update?',
        name: 'blueprint',
        choices: Object.values(choicesByName).map(({ choice }) => choice)
      }]);

      let { realName } = choicesByName[answer.blueprint];

      blueprint = blueprints.find(blueprint => blueprint.name === realName);
    }
  }

  if (blueprint && !blueprint.url && blueprint.location) {
    blueprint.url = (await parseBlueprint(blueprint.location)).url;
  }

  let isCustomBlueprint = blueprint.name !== defaultBlueprint.name;

  if (isCustomBlueprint) {
    createCustomDiff = true;
  }

  let endVersion;

  let result = await (await boilerplateUpdate({
    projectOptions: ({ packageJson }) => getProjectOptions(packageJson, blueprint),
    mergeOptions: async function mergeOptions({
      packageJson,
      projectOptions
    }) {
      let startVersion;
      let startBlueprint;
      let endBlueprint;

      if (isCustomBlueprint) {
        startBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, blueprint.version);
        endBlueprint = await downloadBlueprint(blueprint.name, blueprint.url, to);

        startVersion = startBlueprint.version;
        endVersion = endBlueprint.version;

        blueprint.name = startBlueprint.name;
      } else {
        let packageName = getPackageName(projectOptions);
        let packageVersion = getPackageVersion(packageJson, packageName);

        let versions = await getVersions(packageName);

        let getTagVersion = _getTagVersion(versions, packageName);

        if (from) {
          startVersion = await getTagVersion(from);
        } else {
          startVersion = getProjectVersion(packageVersion, versions, projectOptions);
        }

        endVersion = await getTagVersion(to);

        startBlueprint = endBlueprint = blueprint;
      }

      let customDiffOptions;
      if (createCustomDiff) {
        customDiffOptions = getStartAndEndCommands({
          packageJson,
          projectOptions,
          startVersion,
          endVersion,
          startBlueprint,
          endBlueprint
        });
      }

      return {
        startVersion,
        endVersion,
        customDiffOptions
      };
    },
    remoteUrl: ({ projectOptions }) => getRemoteUrl(projectOptions),
    compareOnly,
    resolveConflicts,
    reset,
    statsOnly,
    listCodemods,
    runCodemods,
    codemodsUrl: 'https://raw.githubusercontent.com/ember-cli/ember-cli-update-codemods-manifest/v3/manifest.json',
    createCustomDiff,
    ignoredFiles: ['ember-cli-update.json'],
    wasRunAsExecutable
  })).promise;

  if (_blueprint) {
    let emberCliUpdateJson = await loadBlueprintFile(cwd);

    if (!emberCliUpdateJson && isCustomBlueprint) {
      await saveDefaultBlueprint({
        cwd,
        blueprint: defaultBlueprint
      });
    }

    await saveBlueprint({
      cwd,
      name: blueprint.name,
      location: blueprint.location,
      version: endVersion
    });

    await run('git add ember-cli-update.json');
  } else {
    let { blueprints } = await loadSafeBlueprintFile(cwd);

    let existingBlueprint = blueprints.find(b => b.name === blueprint.name);

    if (existingBlueprint) {
      await saveBlueprint({
        cwd,
        name: blueprint.name,
        version: endVersion
      });

      await run('git add ember-cli-update.json');
    }
  }

  return result;
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function maximalSubArray(array) {
  if (array.length <= 1) {
    return array;
  }
  var max = array[0];
  var previous = max > 0 ? max : 0;
  var start = previous > 0 ? 0 : 1;
  var bestStart = 0;
  var bestEnd = 0;

  for (var i = 1; i < array.length; i++) {
    // is the current sum greater than the previous max sum?
    var current = previous + array[i];
    if (current > max) {
      max = current;
      bestEnd = i;
      bestStart = start;
      previous = current;
    }

    // does the current item keep the sum above zero?
    if (current <= 0) {
      start = i + 1;
      current = 0;
    }

    previous = current;
  }

  return array.slice(bestStart, bestEnd + 1);
};
<commit_msg>maximal sub array<commit_after>'use strict';

module.exports = function maximalSubArray(array) {
  var max = array[0];
  var previousSum = 0;
  var start = 0;
  var bestStart = 0;
  var bestEnd = 0;

  for (var i = 0; i < array.length; i++) {
    // is the current sum greater than the max sum?
    var currentSum = previousSum + array[i];
    if (currentSum > max) {
      max = currentSum;
      bestEnd = i;
      bestStart = start;
    }

    // the current sub-array can't help overall if it's sum is less than zero
    if (currentSum <= 0) {
      start = i + 1;
      currentSum = 0;
    }

    previousSum = currentSum;
  }

  return array.slice(bestStart, bestEnd + 1);
};
<|endoftext|>


<commit_before>import merge from 'lodash/merge';

const request = (path, method, body, requestOptions = {}) => {
  const jsonContentAllowed = method === 'PUT' || method === 'POST';
  const {requestHeaders, requestGateway} = requestOptions;
  const headers = Object.assign({}, requestHeaders);
  if (jsonContentAllowed && body) {
    headers['Content-Type'] = 'application/json';
  }
  const acceptsJson = method === 'GET' || method === 'POST' || method === 'OPTIONS';
  if (acceptsJson) {
    headers.Accept = 'application/json';
  }
  const gateway = (!requestGateway || requestGateway === '/') ? '' : requestGateway;
  const url = `${gateway}${path}`;
  const fetchPromise = fetch(url, {
    method,
    body,
    headers,
    credentials: 'same-origin'
  });
  return fetchPromise.then(response => {
    if (response.status >= 200 && response.status < 300) {
      return response.json().then(null, () => null);
    }
    return response.json().then(err => {
      throw err;
    });
  });
};

const creator = (options) => {
  const middleware = ({dispatch}) => next => action => {
    const {
      types,
      xhr,
      payload = {}
    } = action;

    if (!types) {
      // Normal action: pass it on
      return next(action);
    }

    if (!Array.isArray(types) ||
      types.length !== 3 ||
      !types.every(type => typeof type === 'string')
    ) {
      throw new Error('api: Expected an array of three string types.');
    }

    if ((typeof xhr !== 'object') || !xhr.url || !xhr.method) {
      throw new Error('api: Expected xhr to be an object with at least a url and a method.');
    }

    const [requestType, successType, failType] = types;

    dispatch(merge({}, {
      type: requestType,
      payload
    }));

    const method = xhr.method.toUpperCase();
    return request(xhr.url, method, xhr.data, options).then(
      response => dispatch({
        type: successType,
        payload: Object.assign({}, payload, response)
      }),
      error => {
        dispatch({
          type: failType,
          payload: Object.assign({}, payload, error)
        });
        throw error;
      });
  };
  return middleware;
}

export default creator;
<commit_msg>Refactored transport as xhr with Promise.<commit_after>import merge from 'lodash/merge';

const request = (path, method, body, requestOptions = {}) => {
  const {requestHeaders, requestGateway} = requestOptions;
  const headers = Object.assign({}, requestHeaders);

  const jsonContentAllowed = method === 'PUT' || method === 'POST';
  if (jsonContentAllowed && body) {
    headers['Content-Type'] = 'application/json';
  }

  const acceptsJson = method === 'GET' || method === 'POST' || method === 'OPTIONS';
  if (acceptsJson) {
    headers.Accept = 'application/json';
  }

  const gateway = (!requestGateway || requestGateway === '/') ? '' : requestGateway;
  const url = `${gateway}${path}`;

  return new Promise(function (resolve, reject) {
    const xhrRequest = new XMLHttpRequest();
    for (let header in headers) {
      xhrRequest.setRequestHeader(header, headers[header]);
    }
    xhrRequest.open(url, method);
    xhrRequest.onreadystatechange = () => {
      const {status, statusText, response} = xhrRequest;
      if (status >= 200 && status < 300) {
        resolve(response);
      } else {
        reject({status, statusText});
      }
    };
    xhrRequest.send(body);
  });
};

const creator = (options) => {
  const middleware = ({dispatch}) => next => action => {
    const {
      types,
      xhr,
      payload = {}
    } = action;

    if (!types) {
      // Normal action: pass it on
      return next(action);
    }

    if (!Array.isArray(types) ||
      types.length !== 3 ||
      !types.every(type => typeof type === 'string')
    ) {
      throw new Error('api: Expected an array of three string types.');
    }

    if ((typeof xhr !== 'object') || !xhr.url || !xhr.method) {
      throw new Error('api: Expected xhr to be an object with at least a url and a method.');
    }

    const [requestType, successType, failType] = types;

    dispatch(merge({}, {
      type: requestType,
      payload
    }));

    const method = xhr.method.toUpperCase();
    return request(xhr.url, method, xhr.data, options).then(
      response => dispatch({
        type: successType,
        payload: Object.assign({}, payload, response)
      }),
      error => {
        dispatch({
          type: failType,
          payload: Object.assign({}, payload, error)
        });
        throw error;
      });
  };
  return middleware;
}

export default creator;
<|endoftext|>


<commit_before>/*

Maak een 50x50 grid. Als je klikt op een cel wordt bij alle cellen in
de rij en kolom van de cel 1 opgeteld. Was een cel leeg dan wordt die
op 1 gezet. Na elke verandering licht een cel kort geel op. Als 5
elkaar in de Fibonacci-reeks opvolgende getallen naast elkaar staan,
lichten deze cellen kort groen op en worden ze leeg gemaakt. Gebruik
de programmeertaal die je het beste vindt passen.

*/

//table is niet responsive
// event listener global of per cell?

'use strict';

window.onload = function()
{
  var gridContainer = document.getElementById("grid-container");
  gridContainer.addEventListener('click', whichCellWasClickedAndProcessIt, false);

  var resetButton = document.getElementById("header-button-reset");
  resetButton.addEventListener('click', resetGrid, false);

  var numberOfRows = 50;
  var numberOfColumns = 50;

  var gridArray = [];
  var dynamicFibonacciSequence = [1, 1];

  class Cell
  {
    constructor(row, rowNumber, columnNumber)
    {
      this.divContainer = document.createElement("div");
      this.cellClass = "grid-cell";
      this.cellId = "grid-row-" + rowNumber + "-cell-" + columnNumber;

      this.divContainer.classList.add(this.cellClass);
      this.divContainer.id = this.cellId;

      this.number = 0;

      row.appendChild(this.divContainer);
    }

    addOneToNumber()
    {
      this.number++;
      this.divContainer.innerHTML = this.number;
    }

    toggleColorYellow()
    {
      let thisCell = this;
      this.divContainer.classList.add("grid-cell-color");

      setTimeout(function removeColorYellowClass()
      {
        thisCell.divContainer.classList.remove("grid-cell-color");
      },
      300);
    }

    toggleColorGreen()
    {
      let thisCell = this;
      this.divContainer.classList.add("cell-fibonacci");

      setTimeout(function removeColorGreenClass()
      {
        thisCell.divContainer.classList.remove("cell-fibonacci");
      },
      300);
    }

    resetCell()
    {
      let thisCell = this;

      setTimeout(function resetCells()
      {
        thisCell.number = 0;
        thisCell.divContainer.innerHTML = "";
      },
      300);

    }
  }

  function dynamicFibonacciGenerator(array)
  {
    let lastIndex = array[array.length - 1];
    let secondLastIndex = array[array.length - 2];

    let newFibonacciNumber = lastIndex + secondLastIndex;
    array.push(newFibonacciNumber);
  }

  function expandFibonacciSequence(arrayOfFiveCells)
  {
    let lastIndex = arrayOfFiveCells[4].number;

    if(lastIndex > dynamicFibonacciSequence[dynamicFibonacciSequence.length - 1])
    {
      while(lastIndex > dynamicFibonacciSequence[dynamicFibonacciSequence.length - 1])
      {
        dynamicFibonacciGenerator(dynamicFibonacciSequence);
      }
    }
  }

  function createGridOfTiles()
  {
    gridContainer.innerHTML = "";

    for (let i = 0; i < numberOfRows; i++)
    {
      let rowArray = [];
      let row = document.createElement("div");
      row.classList.add("grid-row");
      row.id = "row-" + i;

      gridContainer.appendChild(row);

      gridArray.push(rowArray);

      for (let j = 0; j < numberOfColumns; j++)
      {
        let cell = new Cell(row, i, j)
        rowArray.push(cell);
      }
    }
  }

  createGridOfTiles()

  function whichCellWasClickedAndProcessIt()
  {
    let e = window.event || event;
    let clickedCell = e.srcElement.id;

    let cell = findCellPositionInArray(clickedCell);

    addOneToConnectedCells(cell[0], cell[1]);
  }

  function findCellPositionInArray(cellId)
  {
    let regex = /\d{1,2}/g; // must change to 1,3 if rows and columns exceed 100
    let stringNumbers = cellId.match(regex);

    let rowPosition = parseInt(stringNumbers[0]);
    let columnPosition = parseInt(stringNumbers[1]);

    let cell = [];
    cell.push(rowPosition, columnPosition);
    return cell;
  }

  function addOneToConnectedCells(rowNumber, columnNumber)
  {
    for (let i = 0; i < numberOfRows; i++)
    {
      let cell = gridArray[i][columnNumber];

      // skip already done in next for loop
      if(cell == gridArray[rowNumber][columnNumber])
      {
        continue;
      }

      cell.toggleColorYellow();
      cell.addOneToNumber();
    }

    for (let j = 0; j < numberOfColumns; j++)
    {
      let cell = gridArray[rowNumber][j];

      cell.toggleColorYellow();
      cell.addOneToNumber();
    }
    horizontalAndVerticalNumberSequences();
  }

  function horizontalAndVerticalNumberSequences()
  {
    for (let i = 0; i < numberOfRows; i++)
    {
      for (let j = 0; j < numberOfColumns; j++)
      {
        let gridSequenceHorizontal = [];
        let gridSequenceVertical = [];

        if(j + 4 < numberOfColumns)
        {
          let firstNumberHorizontal = gridArray[i][j];
          let secondNumberHorizontal = gridArray[i][j + 1];
          let thirdNumberHorizontal = gridArray[i][j + 2];
          let fourthNumberHorizontal = gridArray[i][j + 3];
          let fifthNumberHorizontal = gridArray[i][j + 4];

          gridSequenceHorizontal.push(firstNumberHorizontal, secondNumberHorizontal, thirdNumberHorizontal, fourthNumberHorizontal, fifthNumberHorizontal);
          findFibonacciSequences(gridSequenceHorizontal);
        }

        if(i + 4 < numberOfRows)
        {
          let firstNumberVertical = gridArray[i][j];
          let secondNumberVertical = gridArray[i + 1][j];
          let thirdNumberVertical = gridArray[i + 2][j];
          let fourthNumberVertical = gridArray[i + 3][j];
          let fifthNumberVertical = gridArray[i + 4][j];

          gridSequenceVertical.push(firstNumberVertical, secondNumberVertical, thirdNumberVertical, fourthNumberVertical, fifthNumberVertical);
          findFibonacciSequences(gridSequenceVertical);
        }
      }
    }
  }

  function findFibonacciSequences(gridSequence)
  {
    let fibonacciCache = [];

    for (let i = 0; i < dynamicFibonacciSequence.length; i++)
    {
      fibonacciCache = [];

      expandFibonacciSequence(gridSequence);

      let firstFibonacciNumber = dynamicFibonacciSequence[i];
      let secondFibonacciNumber = dynamicFibonacciSequence[i + 1];
      let thirdFibonacciNumber = dynamicFibonacciSequence[i + 2];
      let fourthFibonacciNumber = dynamicFibonacciSequence[i + 3];
      let fifthFibonacciNumber = dynamicFibonacciSequence[i + 4];

      fibonacciCache.push(firstFibonacciNumber, secondFibonacciNumber, thirdFibonacciNumber, fourthFibonacciNumber, fifthFibonacciNumber);

      if(compareTwoArrays(gridSequence, fibonacciCache) === true)
      {
        gridSequence.forEach(function(cell)
        {
          cell.toggleColorGreen(cell);
          cell.resetCell(cell);
        });

        return;
      }
    }
  }

  function compareTwoArrays(arrayToCompareTo, arrayToBeCompared)
  {
    for (let i = 0; i < arrayToCompareTo.length; i++)
    {
      if(arrayToCompareTo[i].number != arrayToBeCompared[i])
      {
        return false;
      }
    }
    return true;
  }

  function resetGrid()
  {
    gridArray = [];
    createGridOfTiles();
  }
}
<commit_msg>further optimization. Refactored compare Two arrays function : increased time by 20ms!<commit_after>/*

Maak een 50x50 grid. Als je klikt op een cel wordt bij alle cellen in
de rij en kolom van de cel 1 opgeteld. Was een cel leeg dan wordt die
op 1 gezet. Na elke verandering licht een cel kort geel op. Als 5
elkaar in de Fibonacci-reeks opvolgende getallen naast elkaar staan,
lichten deze cellen kort groen op en worden ze leeg gemaakt. Gebruik
de programmeertaal die je het beste vindt passen.

*/

//table is niet responsive
// event listener global of per cell?

'use strict';

window.onload = function()
{
  var gridContainer = document.getElementById("grid-container");
  gridContainer.addEventListener('click', whichCellWasClickedAndProcessIt, false);

  var resetButton = document.getElementById("header-button-reset");
  resetButton.addEventListener('click', resetGrid, false);

  var numberOfRows = 50;
  var numberOfColumns = 50;

  var gridArray = [];
  var dynamicFibonacciSequence = [1, 1];

  class Cell
  {
    constructor(row, rowNumber, columnNumber)
    {
      this.divContainer = document.createElement("div");
      this.cellClass = "grid-cell";
      this.cellId = "grid-row-" + rowNumber + "-cell-" + columnNumber;

      this.divContainer.classList.add(this.cellClass);
      this.divContainer.id = this.cellId;

      this.number = 0;

      row.appendChild(this.divContainer);
    }

    addOneToNumber()
    {
      this.number++;
      this.divContainer.innerHTML = this.number;
    }

    toggleColorYellow()
    {
      let thisCell = this;
      this.divContainer.classList.add("grid-cell-color");

      setTimeout(function removeColorYellowClass()
      {
        thisCell.divContainer.classList.remove("grid-cell-color");
      },
      300);
    }

    toggleColorGreen()
    {
      let thisCell = this;
      this.divContainer.classList.add("cell-fibonacci");

      setTimeout(function removeColorGreenClass()
      {
        thisCell.divContainer.classList.remove("cell-fibonacci");
      },
      300);
    }

    resetCell()
    {
      let thisCell = this;

      setTimeout(function resetCells()
      {
        thisCell.number = 0;
        thisCell.divContainer.innerHTML = "";
      },
      300);

    }
  }

  function dynamicFibonacciGenerator(array)
  {
    let lastIndex = array[array.length - 1];
    let secondLastIndex = array[array.length - 2];

    let newFibonacciNumber = lastIndex + secondLastIndex;
    array.push(newFibonacciNumber);
  }

  function expandFibonacciSequence(biggestNumberInArray)
  {
    while(biggestNumberInArray > dynamicFibonacciSequence[dynamicFibonacciSequence.length - 1])
    {
      dynamicFibonacciGenerator(dynamicFibonacciSequence);
    }
  }

  function createGridOfTiles()
  {
    gridContainer.innerHTML = "";

    for (let i = 0; i < numberOfRows; i++)
    {
      let rowArray = [];
      let row = document.createElement("div");
      row.classList.add("grid-row");
      row.id = "row-" + i;

      gridContainer.appendChild(row);

      gridArray.push(rowArray);

      for (let j = 0; j < numberOfColumns; j++)
      {
        let cell = new Cell(row, i, j)
        rowArray.push(cell);
      }
    }
  }

  createGridOfTiles()

  function whichCellWasClickedAndProcessIt()
  {
    let e = window.event || event;
    let clickedCell = e.srcElement.id;

    if(clickedCell.includes("row") == true && clickedCell.includes("cell") == true)
    {
      let cell = findCellPositionInArray(clickedCell);
      addOneToConnectedCells(cell[0], cell[1]);
    }
  }

  function findCellPositionInArray(cellId)
  {
    let regexFindNumbers = /\d{1,2}/g; // must change to 1,3 if rows and columns exceed 100
    let stringNumbers = cellId.match(regexFindNumbers);

    let rowPosition = parseInt(stringNumbers[0]);
    let columnPosition = parseInt(stringNumbers[1]);

    let cell = [];
    cell.push(rowPosition, columnPosition);
    return cell;
  }

  function addOneToConnectedCells(rowNumber, columnNumber)
  {
    for (let i = 0; i < numberOfRows; i++)
    {
      let cell = gridArray[i][columnNumber];

      // skip. already done in next for loop
      if(cell == gridArray[rowNumber][columnNumber])
      {
        continue;
      }

      cell.toggleColorYellow();
      cell.addOneToNumber();
    }

    for (let j = 0; j < numberOfColumns; j++)
    {
      let cell = gridArray[rowNumber][j];

      cell.toggleColorYellow();
      cell.addOneToNumber();
    }
    horizontalAndVerticalNumberSequences();
  }

  function horizontalAndVerticalNumberSequences()
  {
    let gridSequenceHorizontal = [];
    let gridSequenceVertical = [];

    for (let i = 0; i < numberOfRows; i++)
    {
      for (let j = 0; j < numberOfColumns; j++)
      {
        gridSequenceHorizontal.length = 0;
        gridSequenceVertical.length = 0;

        if(j + 4 < numberOfColumns)
        {
          let firstNumberHorizontal = gridArray[i][j];
          let secondNumberHorizontal = gridArray[i][j + 1];
          let thirdNumberHorizontal = gridArray[i][j + 2];
          let fourthNumberHorizontal = gridArray[i][j + 3];
          let fifthNumberHorizontal = gridArray[i][j + 4];

          gridSequenceHorizontal.push(firstNumberHorizontal,
                                      secondNumberHorizontal,
                                      thirdNumberHorizontal,
                                      fourthNumberHorizontal,
                                      fifthNumberHorizontal);

          findFibonacciSequences(gridSequenceHorizontal);
        }

        if(i + 4 < numberOfRows)
        {
          let firstNumberVertical = gridArray[i][j];
          let secondNumberVertical = gridArray[i + 1][j];
          let thirdNumberVertical = gridArray[i + 2][j];
          let fourthNumberVertical = gridArray[i + 3][j];
          let fifthNumberVertical = gridArray[i + 4][j];

          gridSequenceVertical.push(firstNumberVertical,
                                    secondNumberVertical,
                                    thirdNumberVertical,
                                    fourthNumberVertical,
                                    fifthNumberVertical);

          findFibonacciSequences(gridSequenceVertical);
        }
      }
    }
  }

  function findFibonacciSequences(gridSequence)
  {
    expandFibonacciSequence(gridSequence[4].number);

    let fibonacciCache = [];

    for (let i = 0; i < dynamicFibonacciSequence.length; i++)
    {
      fibonacciCache.length = 0;

      fibonacciCache.push(dynamicFibonacciSequence[i],
                          dynamicFibonacciSequence[i + 1],
                          dynamicFibonacciSequence[i + 2],
                          dynamicFibonacciSequence[i + 3],
                          dynamicFibonacciSequence[i + 4]);

      if(compareTwoArrays(gridSequence, fibonacciCache) === true)
      {
        gridSequence.forEach(function(cell)
        {
          cell.toggleColorGreen(cell);
          cell.resetCell(cell);
        });

        break;
      }
    }
  }

  function compareTwoArrays(arrayToCompareTo, arrayToBeCompared)
  {
    for (let i = 0; i < arrayToCompareTo.length; i++)
    {
      if(arrayToCompareTo[i].number != arrayToBeCompared[i])
      {
        return false;
      }
    }
    return true;
  }

  function resetGrid()
  {
    gridArray = [];
    createGridOfTiles();
  }
}
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-router";
import { Provider } from "react-redux";
import ReduxThunk from "redux-thunk";
import { createStore, applyMiddleware } from "redux";
import { Router, browserHistory } from "react-router";
import routes from "./routes";
import reducers from "./reducers";

const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
window.store = createStoreWithMiddleware(reducers);
const store = createStoreWithMiddleware(reducers);

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>,
  document.querySelector(".container-fluid")
);
<commit_msg>added loader<commit_after>import React from "react";
import ReactDOM from "react-router-dom";
import { Provider } from "react-redux";
import ReduxThunk from "redux-thunk";
import { createStore, applyMiddleware } from "redux";
import { Router, browserHistory } from "react-router";
import routes from "./routes";
import reducers from "./reducers";

const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
window.store = createStoreWithMiddleware(reducers);
const store = createStoreWithMiddleware(reducers);

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>,
  document.querySelector(".container-fluid")
);
<|endoftext|>


<commit_before>/**
 * Babel Starter Kit (https://www.kriasoft.com/babel-starter-kit)
 *
 * Copyright © 2015-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-polyfill';

import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import { host, port } from './config';
import route from './route';

const app = express();

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(cookieParser('my cookie key'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

const morgan = require('morgan');
app.use(morgan('dev'));

/*
注册API
*/
app.use('/route', route);

app.listen(port, () => {
  console.log(`The server is running at http://${host}/`);
});
<commit_msg>add cookie key<commit_after>/**
 * Babel Starter Kit (https://www.kriasoft.com/babel-starter-kit)
 *
 * Copyright © 2015-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-polyfill';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import { host, port, cookieKey } from './config';
import route from './route';

const app = express();

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(cookieParser(cookieKey));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

const morgan = require('morgan');
app.use(morgan('dev'));

/*
注册API
*/
app.use('/route', route);

app.listen(port, () => {
  console.log(`The server is running at http://${host}/`);
});
<|endoftext|>


<commit_before>var restify = require('restify');

var server = new restify.createServer();
server.use(restify.bodyParser());

server.get('/', function(req, res, next) {
    res.send('200 OK');
});

server.post('/submit', function(req, res, next) {
    var api_key = req.body.api_key,
        t1 = req.body.t1,
        t2 = req.body.t2;

    if (process.env.API_KEY === undefined || api_key != process.env.API_KEY) {
        res.send('403 FORBIDDEN');
        return;
    }

    res.send('api %s - t1 %s - t2 %s', api_key, t1, t2);

});

server.listen(process.env.PORT, function() {
    console.log('%s listening at %s', server.name, server.url);
});
<commit_msg>Added logging<commit_after>var restify = require('restify');

var server = new restify.createServer();
server.use(restify.bodyParser());

server.get('/', function(req, res, next) {
    res.send('200 OK');
});

server.post('/submit', function(req, res, next) {
    var api_key = req.body.api_key,
        t1 = req.body.t1,
        t2 = req.body.t2;

    console.log('process.env.API_KEY: %s', process.env.API_KEY);
    console.log('api_key: %s', api_key);

    if (process.env.API_KEY === undefined || api_key != process.env.API_KEY) {
        res.send('403 FORBIDDEN', process.env.API_KEY === undefined, api_key != process.env.API_KEY);
        return;
    }

    res.send('api %s - t1 %s - t2 %s', api_key, t1, t2);

});

server.listen(process.env.PORT, function() {
    console.log('%s listening at %s', server.name, server.url);
});
<|endoftext|>


<commit_before>import Tippy from 'tippy.js/dist/tippy.all'
import './css/themes.css'

window.Tippy = Tippy
const plugin = {
  install (Vue, options) {
    Vue.directive('tippy-html', {
      componentUpdated (el) {
        const els = el._tipppyReferences
        if (els && els.length > 0) {
          Vue.nextTick(() => {
            els.forEach((et) => {
              if (et._tippy) {
                const content = et._tippy.popper.querySelector('.tippy-content')
                content.innerHTML = el.innerHTML
              }
            })
          })
        }
      },
      unbind (el) {
        delete el._tipppyReference
      }
    })

    function createTippy (el, binding, vnode) {
      const handlers = (vnode.data && vnode.data.on) ||
                (vnode.componentOptions && vnode.componentOptions.listeners)

      let opts = binding.value || {}

      opts = Object.assign({ dynamicTitle: true, reactive: false, showOnLoad: false }, options, opts)

      if (handlers && handlers['show']) {
        opts.onShow = function () {
          handlers['show'].fns(vnode)
        }
      }

      if (handlers && handlers['shown']) {
        opts.onShown = function () {
          handlers['shown'].fns(vnode)
        }
      }
      if (handlers && handlers['hidden']) {
        opts.onHidden = function () {
          handlers['hidden'].fns(vnode)
        }
      }

      if (handlers && handlers['hide']) {
        opts.onHide = function () {
          handlers['hide'].fns(vnode)
        }
      }

      if (opts.html) {
        var selector = opts.html
        if (opts.reactive || !(typeof selector === 'string')) {
          opts.html = selector instanceof Element ? selector : (selector instanceof Vue ? selector.$el : document.querySelector(selector))
        } else {
          const htmlElement = document.querySelector(opts.html)
          if (htmlElement) {
            if (htmlElement._tipppyReferences) {
              htmlElement._tipppyReferences.push(el)
            } else {
              htmlElement._tipppyReferences = [el]
            }
          } else {
            console.error(`[VueTippy] Selector ${opts.html} not found`)
            return
          }
        }
      }

      if (opts.html || el.getAttribute('data-tippy-html')) {
        opts.dynamicTitle = false
      }

      if (el.getAttribute('data-tippy-html')) {
        const htmlEl = document.querySelector(el.getAttribute('data-tippy-html'))
        if (htmlEl) {
          if (htmlEl._tipppyReferences) {
            htmlEl._tipppyReferences.push(el)
          } else {
            htmlEl._tipppyReferences = [el]
          }
        } else {
          console.error(`[VueTippy] Selector '${el.getAttribute('data-tippy-html')}' not found`, el)
          return
        }
      }

      new Tippy(el, opts)

      if (opts.showOnLoad) {
        el._tippy.show()
      }
    }

    Vue.directive('tippy', {
      inserted (el, binding, vnode) {
        Vue.nextTick(() => {
          createTippy(el, binding, vnode)
        })
      },
      unbind (el) {
        el._tippy && el._tippy.destroy()
      },
      componentUpdated (el, binding, vnode) {
        const opts = binding.value || {}
        const oldOpts = binding.oldValue || {}

        if (el._tippy && (JSON.stringify(opts) !== JSON.stringify(oldOpts))) {
          Vue.nextTick(() => {
            createTippy(el, binding, vnode)
          })
        }

        if (el._tippy && opts.show) {
          el._tippy.show()
        } else if (el._tippy && !opts.show && opts.trigger === 'manual') {
          el._tippy.hide()
        }
      }
    })

    Vue.component('tippy', {
      template: `<div><slot></slot></div>`,
      props: {
        to: {
          type: String,
          required: true
        },
        placement: {
          type: String,
          default: 'top'
        },
        theme: {
          type: String,
          default: 'light'
        },
        interactive: {
          type: [Boolean, String],
          default: false
        },
        arrow: {
          type: [Boolean, String],
          default: false
        },
        arrowType: {
          type: String,
          default: 'sharp'
        },
        arrowTransform: {
          type: String,
          default: ''
        },
        trigger: {
          type: String,
          default: 'mouseenter focus'
        },
        interactiveBorder: {
          type: Number,
          default: 2
        },
        animation: {
          type: String,
          default: 'shift-away'
        },
        animationFill: {
          type: [Boolean, String],
          default: true
        },
        distance: {
          type: Number,
          default: 10
        },

        offset: {
          type: Number,
          default: 0
        },
        followCursor: {
          type: [Boolean, String],
          default: false
        },
        sticky: {
          type: [Boolean, String],
          default: false
        },
        size: {
          type: String,
          default: 'regular'
        }
      },
      mounted: function () {
        document
                    .querySelectorAll(`[name=${this.to}]`)
                    .forEach(elem => {
                      const value = Object.assign({ reactive: true, html: this.$el }, this.$props)
                      createTippy(elem, { value }, this.$vnode)
                    })
      }
    })
  }
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin)
}

export default plugin
<commit_msg>[TASK] pass element first and node as second argument in callback<commit_after>import Tippy from 'tippy.js/dist/tippy.all'
import './css/themes.css'

window.Tippy = Tippy
const plugin = {
  install (Vue, options) {
    Vue.directive('tippy-html', {
      componentUpdated (el) {
        const els = el._tipppyReferences
        if (els && els.length > 0) {
          Vue.nextTick(() => {
            els.forEach((et) => {
              if (et._tippy) {
                const content = et._tippy.popper.querySelector('.tippy-content')
                content.innerHTML = el.innerHTML
              }
            })
          })
        }
      },
      unbind (el) {
        delete el._tipppyReference
      }
    })

    function createTippy (el, binding, vnode) {
      const handlers = (vnode.data && vnode.data.on) ||
                (vnode.componentOptions && vnode.componentOptions.listeners)

      let opts = binding.value || {}

      opts = Object.assign({ dynamicTitle: true, reactive: false, showOnLoad: false }, options, opts)

      if (handlers && handlers['show']) {
        opts.onShow = function () {
          handlers['show'].fns(el, vnode)
        }
      }

      if (handlers && handlers['shown']) {
        opts.onShown = function () {
          handlers['shown'].fns(el, vnode)
        }
      }
      if (handlers && handlers['hidden']) {
        opts.onHidden = function () {
          handlers['hidden'].fns(el, vnode)
        }
      }

      if (handlers && handlers['hide']) {
        opts.onHide = function () {
          handlers['hide'].fns(el, vnode)
        }
      }

      if (opts.html) {
        var selector = opts.html
        if (opts.reactive || !(typeof selector === 'string')) {
          opts.html = selector instanceof Element ? selector : (selector instanceof Vue ? selector.$el : document.querySelector(selector))
        } else {
          const htmlElement = document.querySelector(opts.html)
          if (htmlElement) {
            if (htmlElement._tipppyReferences) {
              htmlElement._tipppyReferences.push(el)
            } else {
              htmlElement._tipppyReferences = [el]
            }
          } else {
            console.error(`[VueTippy] Selector ${opts.html} not found`)
            return
          }
        }
      }

      if (opts.html || el.getAttribute('data-tippy-html')) {
        opts.dynamicTitle = false
      }

      if (el.getAttribute('data-tippy-html')) {
        const htmlEl = document.querySelector(el.getAttribute('data-tippy-html'))
        if (htmlEl) {
          if (htmlEl._tipppyReferences) {
            htmlEl._tipppyReferences.push(el)
          } else {
            htmlEl._tipppyReferences = [el]
          }
        } else {
          console.error(`[VueTippy] Selector '${el.getAttribute('data-tippy-html')}' not found`, el)
          return
        }
      }

      new Tippy(el, opts)

      if (opts.showOnLoad) {
        el._tippy.show()
      }
    }

    Vue.directive('tippy', {
      inserted (el, binding, vnode) {
        Vue.nextTick(() => {
          createTippy(el, binding, vnode)
        })
      },
      unbind (el) {
        el._tippy && el._tippy.destroy()
      },
      componentUpdated (el, binding, vnode) {
        const opts = binding.value || {}
        const oldOpts = binding.oldValue || {}

        if (el._tippy && (JSON.stringify(opts) !== JSON.stringify(oldOpts))) {
          Vue.nextTick(() => {
            createTippy(el, binding, vnode)
          })
        }

        if (el._tippy && opts.show) {
          el._tippy.show()
        } else if (el._tippy && !opts.show && opts.trigger === 'manual') {
          el._tippy.hide()
        }
      }
    })

    Vue.component('tippy', {
      template: `<div><slot></slot></div>`,
      props: {
        to: {
          type: String,
          required: true
        },
        placement: {
          type: String,
          default: 'top'
        },
        theme: {
          type: String,
          default: 'light'
        },
        interactive: {
          type: [Boolean, String],
          default: false
        },
        arrow: {
          type: [Boolean, String],
          default: false
        },
        arrowType: {
          type: String,
          default: 'sharp'
        },
        arrowTransform: {
          type: String,
          default: ''
        },
        trigger: {
          type: String,
          default: 'mouseenter focus'
        },
        interactiveBorder: {
          type: Number,
          default: 2
        },
        animation: {
          type: String,
          default: 'shift-away'
        },
        animationFill: {
          type: [Boolean, String],
          default: true
        },
        distance: {
          type: Number,
          default: 10
        },

        offset: {
          type: Number,
          default: 0
        },
        followCursor: {
          type: [Boolean, String],
          default: false
        },
        sticky: {
          type: [Boolean, String],
          default: false
        },
        size: {
          type: String,
          default: 'regular'
        }
      },
      mounted: function () {
        document
                    .querySelectorAll(`[name=${this.to}]`)
                    .forEach(elem => {
                      const value = Object.assign({ reactive: true, html: this.$el }, this.$props)
                      createTippy(elem, { value }, this.$vnode)
                    })
      }
    })
  }
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin)
}

export default plugin
<|endoftext|>


<commit_before>/**
 * @file Main file of the whole project.
 */

var config = require(__dirname + '/libs/requireConfig.js');
var port   = process.env.PORT || config.port;

/*
 * General Libraries
 */

var bodyParser   = require('body-parser');
var cookieParser = require('cookie-parser');
var cookies      = require(__dirname + '/libs/cookies.js');
var ejs          = require('ejs');
var http         = require('http');
var https        = require('https');
var lunch        = require(__dirname + '/libs/lunch.js');
var mail         = require(__dirname + '/libs/mail.js');
var request      = require('request');
var weather      = require(__dirname + '/libs/weather.js');
var sass         = require(__dirname + '/libs/sass.js');

/*
 * Frameworks
 */

var express = require('express');
var app     = express();
var server  = http.Server(app);
var io      = require('socket.io')(server);

/**
 * Express Middleware
 */

// Cookies
app.use(cookieParser());

// Sessions
var session = require('express-session')({
    secret           : config.expressSessionSecret,
    resave           : false,
    saveUninitialized: false,
});

app.use(session);

io.use(function(socket, next) {
    session(socket.request, socket.request.res, next);
});

// 'Remember Me' Functionality
app.use(cookies.remember);

// Body Parser for POST Variables
app.use(bodyParser.json());     // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));

// EJS as Default Render Engine
app.set('view engine', 'ejs');

/*
 * Sass Compilation
 */

console.log('Compiling Sass...');
sass.rednerDir(__dirname + '/public/css/scss', __dirname + '/public/css');
sass.watchDir(__dirname + '/public/css/scss', __dirname + '/public/css');

/*
 * Routes
 */

require(__dirname + '/routes/assets.js')(app, express);
require(__dirname + '/routes/login.js')(app);
require(__dirname + '/routes/scheduleConfig.js')(app);

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/html/index.html');
});

app.get('/classes', function(req, res) {
    res.sendFile(__dirname + '/html/classes.html');
});

app.get('/lunch', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    lunch.getLunch(function(lunchJSON) {
        res.send(JSON.stringify(lunchJSON, null, 3));
    });
});

app.get('/start', function(req, res) {
	res.sendFile(__dirname + '/html/start.html');
});

var portal = require(__dirname + '/libs/portal.js');
app.get('/feed', function(req, res) {
    portal.scheduleFeed(config.portalTestFeedURL, function(that) {
        res.setHeader('Content-Type', 'text/html');
        var schedule = that.getSchedule();
        res.end(that.success + '
' + that.message + '

' + JSON.stringify(schedule) + '

');
    });
});

var planner = require(__dirname + '/libs/planner.js');
app.get('/planner', function(req, res) {
    planner.eventsForMonth(req.session.user, function(events) {
        res.json(events);
    });
});

app.get('/test', function(req, res) {
	res.sendFile(__dirname + '/html/test.html');
});

app.get('/iotd', function(req, res) {
	request('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1', function(error, response, body) {
		if(!error && response.statusCode === 200) {
			var json  = JSON.parse(body);
			var imageURL = 'https://www.bing.com/' + json['images'][0]['url'];
			res.json({ 'image': imageURL });
		} else {
			res.json({ 'image': '/images/backgrounds/middleschool/mac.jpg' });
		}
	});
});

/*
 * Socket.io
 */

io.on('connection', function(socket){

    socket.on('username', function() {
        socket.emit('username', socket.request.session.user);
    });

	socket.on('disconnect', function() {
//		console.log('user disconnected');
	});
});

server.listen(port, function() {
    console.log('Server listening on *:' + port);
});
<commit_msg>Michael still can't spell<commit_after>/**
 * @file Main file of the whole project.
 */

var config = require(__dirname + '/libs/requireConfig.js');
var port   = process.env.PORT || config.port;

/*
 * General Libraries
 */

var bodyParser   = require('body-parser');
var cookieParser = require('cookie-parser');
var cookies      = require(__dirname + '/libs/cookies.js');
var ejs          = require('ejs');
var http         = require('http');
var https        = require('https');
var lunch        = require(__dirname + '/libs/lunch.js');
var mail         = require(__dirname + '/libs/mail.js');
var request      = require('request');
var weather      = require(__dirname + '/libs/weather.js');
var sass         = require(__dirname + '/libs/sass.js');

/*
 * Frameworks
 */

var express = require('express');
var app     = express();
var server  = http.Server(app);
var io      = require('socket.io')(server);

/**
 * Express Middleware
 */

// Cookies
app.use(cookieParser());

// Sessions
var session = require('express-session')({
    secret           : config.expressSessionSecret,
    resave           : false,
    saveUninitialized: false,
});

app.use(session);

io.use(function(socket, next) {
    session(socket.request, socket.request.res, next);
});

// 'Remember Me' Functionality
app.use(cookies.remember);

// Body Parser for POST Variables
app.use(bodyParser.json());     // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));

// EJS as Default Render Engine
app.set('view engine', 'ejs');

/*
 * Sass Compilation
 */

console.log('Compiling Sass...');
sass.renderDir(__dirname + '/public/css/scss', __dirname + '/public/css');
sass.watchDir(__dirname + '/public/css/scss', __dirname + '/public/css');

/*
 * Routes
 */

require(__dirname + '/routes/assets.js')(app, express);
require(__dirname + '/routes/login.js')(app);
require(__dirname + '/routes/scheduleConfig.js')(app);

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/html/index.html');
});

app.get('/classes', function(req, res) {
    res.sendFile(__dirname + '/html/classes.html');
});

app.get('/lunch', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    lunch.getLunch(function(lunchJSON) {
        res.send(JSON.stringify(lunchJSON, null, 3));
    });
});

app.get('/start', function(req, res) {
	res.sendFile(__dirname + '/html/start.html');
});

var portal = require(__dirname + '/libs/portal.js');
app.get('/feed', function(req, res) {
    portal.scheduleFeed(config.portalTestFeedURL, function(that) {
        res.setHeader('Content-Type', 'text/html');
        var schedule = that.getSchedule();
        res.end(that.success + '
' + that.message + '

' + JSON.stringify(schedule) + '

');
    });
});

var planner = require(__dirname + '/libs/planner.js');
app.get('/planner', function(req, res) {
    planner.eventsForMonth(req.session.user, function(events) {
        res.json(events);
    });
});

app.get('/test', function(req, res) {
	res.sendFile(__dirname + '/html/test.html');
});

app.get('/iotd', function(req, res) {
	request('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1', function(error, response, body) {
		if(!error && response.statusCode === 200) {
			var json  = JSON.parse(body);
			var imageURL = 'https://www.bing.com/' + json['images'][0]['url'];
			res.json({ 'image': imageURL });
		} else {
			res.json({ 'image': '/images/backgrounds/middleschool/mac.jpg' });
		}
	});
});

/*
 * Socket.io
 */

io.on('connection', function(socket){

    socket.on('username', function() {
        socket.emit('username', socket.request.session.user);
    });

	socket.on('disconnect', function() {
//		console.log('user disconnected');
	});
});

server.listen(port, function() {
    console.log('Server listening on *:' + port);
});
<|endoftext|>


<commit_before>// @flow

import DeepstreamClient from 'deepstream.io-client-js';
import libp2pCrypto from 'libp2p-crypto';
import { jwk2pem } from 'pem-jwk';

export default function (client: DeepstreamClient, name:string, privateKey:libp2pCrypto.keys.supportedKeys.rsa.RsaPrivateKey, defaultValue?: Object = {}) {
  const record = client.record.getRecord(name);
  const readyPromise = new Promise((resolve, reject) => {
    record.once('ready', resolve);
    record.once('error', reject);
  });
  const pemPublicKey = jwk2pem(privateKey.public._key); // eslint-disable-line no-underscore-dangle
  let currentData = {};
  readyPromise.then(() => {
    currentData = record.get();
  });
  const callbacks = {};
  const errbacks = new Set([]);
  const getSignature = (value: Object) => {
    const data = Object.assign({}, value);
    delete data.signature;
    const pairs = Object.keys(data).map((key) => [key, data[key]]);
    pairs.sort((x, y) => (x[0] > y[0] ? 1 : -1));
    return new Promise((resolve, reject) => {
      privateKey.sign(JSON.stringify(pairs), (error, signature) => {
        if (error) {
          reject(error);
          return;
        }
        resolve(signature.toString('base64'));
      });
    });
  };
  record.subscribe(async (value:Object) => {
    try {
      const data = Object.assign({}, value);
      const signature = data.signature;
      delete data.signature;
      if (signature !== (await getSignature(data))) {
        throw new Error(`Invalid signature for record ${name}`);
      }
      Object.keys(currentData).forEach((k) => {
        if (!data[k] && callbacks[k]) {
          callbacks[k].forEach((callback) => callback());
        }
      });
      Object.keys(data).forEach((k) => {
        if (data[k] !== currentData[k] && callbacks[k]) {
          callbacks[k].forEach((callback) => callback(data[k]));
        }
      });
      currentData = data;
    } catch (error) {
      for (const errback of errbacks) { // eslint-disable-line no-restricted-syntax
        errback(error);
      }
    }
  }, true);
  const subscribe = (key: string, callback: Function, errback?: Function) => {
    callbacks[key] = callbacks[key] || [];
    callbacks[key].push(callback);
    if (record.isReady) {
      callback(currentData[key]);
    }
    if (errback) {
      errbacks.add(errback);
    }
  };
  const discard = async () => {
    if (record.isDestroyed) {
      return;
    }
    record.unsubscribe();
    await new Promise((resolve, reject) => {
      record.once('discard', resolve);
      record.once('error', reject);
      record.discard();
    });
  };
  const set = async (key: string, value: any) => {
    await readyPromise;
    let remoteValue = record.get();
    if (Object.keys(remoteValue).length > 0 && remoteValue.signature !== await getSignature(remoteValue)) {
      console.error(`Invalid signature for record ${name}, clearing.`);
      remoteValue = {};
    }
    const data = Object.assign({}, remoteValue, defaultValue, {
      publicKey: pemPublicKey,
    });
    data[key] = value;
    data.signature = await getSignature(data);
    await new Promise((resolve, reject) => {
      record.set(data, (errorMessage:string) => {
        if (errorMessage) {
          reject(new Error(errorMessage));
        } else {
          resolve();
        }
      });
    });
  };
  return { set, subscribe, discard };
}
<commit_msg>Don't test empty objects<commit_after>// @flow

import DeepstreamClient from 'deepstream.io-client-js';
import libp2pCrypto from 'libp2p-crypto';
import { jwk2pem } from 'pem-jwk';

export default function (client: DeepstreamClient, name:string, privateKey:libp2pCrypto.keys.supportedKeys.rsa.RsaPrivateKey, defaultValue?: Object = {}) {
  const record = client.record.getRecord(name);
  const readyPromise = new Promise((resolve, reject) => {
    record.once('ready', resolve);
    record.once('error', reject);
  });
  const pemPublicKey = jwk2pem(privateKey.public._key); // eslint-disable-line no-underscore-dangle
  let currentData = {};
  readyPromise.then(() => {
    currentData = record.get();
  });
  const callbacks = {};
  const errbacks = new Set([]);
  const getSignature = (value: Object) => {
    const data = Object.assign({}, value);
    delete data.signature;
    const pairs = Object.keys(data).map((key) => [key, data[key]]);
    pairs.sort((x, y) => (x[0] > y[0] ? 1 : -1));
    return new Promise((resolve, reject) => {
      privateKey.sign(JSON.stringify(pairs), (error, signature) => {
        if (error) {
          reject(error);
          return;
        }
        resolve(signature.toString('base64'));
      });
    });
  };
  record.subscribe(async (value:Object) => {
    try {
      const data = Object.assign({}, value);
      const signature = data.signature;
      delete data.signature;
      if (Object.keys(data).length > 0 && signature !== (await getSignature(data))) {
        throw new Error(`Invalid signature for record ${name}`);
      }
      Object.keys(currentData).forEach((k) => {
        if (!data[k] && callbacks[k]) {
          callbacks[k].forEach((callback) => callback());
        }
      });
      Object.keys(data).forEach((k) => {
        if (data[k] !== currentData[k] && callbacks[k]) {
          callbacks[k].forEach((callback) => callback(data[k]));
        }
      });
      currentData = data;
    } catch (error) {
      for (const errback of errbacks) { // eslint-disable-line no-restricted-syntax
        errback(error);
      }
    }
  }, true);
  const subscribe = (key: string, callback: Function, errback?: Function) => {
    callbacks[key] = callbacks[key] || [];
    callbacks[key].push(callback);
    if (record.isReady) {
      callback(currentData[key]);
    }
    if (errback) {
      errbacks.add(errback);
    }
  };
  const discard = async () => {
    if (record.isDestroyed) {
      return;
    }
    record.unsubscribe();
    await new Promise((resolve, reject) => {
      record.once('discard', resolve);
      record.once('error', reject);
      record.discard();
    });
  };
  const set = async (key: string, value: any) => {
    await readyPromise;
    let remoteValue = record.get();
    if (Object.keys(remoteValue).length > 0 && remoteValue.signature !== await getSignature(remoteValue)) {
      console.error(`Invalid signature for record ${name}, clearing.`);
      remoteValue = {};
    }
    const data = Object.assign({}, remoteValue, defaultValue, {
      publicKey: pemPublicKey,
    });
    data[key] = value;
    data.signature = await getSignature(data);
    await new Promise((resolve, reject) => {
      record.set(data, (errorMessage:string) => {
        if (errorMessage) {
          reject(new Error(errorMessage));
        } else {
          resolve();
        }
      });
    });
  };
  return { set, subscribe, discard };
}
<|endoftext|>


<commit_before>const colors = require('colors');
const got = require('got');
const logo = require('burgerjs-logo');

if (!global.Intl) {
    global.Intl = require('intl');
}

const IntlRelativeFormat = require('intl-relativeformat');
const rf = new IntlRelativeFormat('en');

got('https://api.meetup.com/burgerjs/events')
    .then(res => JSON.parse(res.body)[0])
    .then(event => {
        const missingTime = rf.format(new Date(event.time + event.utc_offset));
        const message = `\nThe next burger.js is ${missingTime}`;

        logo.print();

        setTimeout(() => {
            // eslint-disable-next-line no-console
            console.log(colors.yellow.bold(message));

            // eslint-disable-next-line no-console
            console.log(`More info: ${event.link}\n`);
        }, 100);
    })
    .catch(error => {
        // eslint-disable-next-line no-console
        console.error(error.response.body);
    });
<commit_msg>Format output to spanish<commit_after>const colors = require('colors');
const got = require('got');
const logo = require('burgerjs-logo');

if (!global.Intl) {
    global.Intl = require('intl');
}

const IntlRelativeFormat = require('intl-relativeformat');
const rf = new IntlRelativeFormat('es-ES');

got('https://api.meetup.com/burgerjs/events')
    .then(res => JSON.parse(res.body)[0])
    .then(event => {
        const missingTime = rf.format(new Date(event.time + event.utc_offset));
        const message = `\nEl próximo burger.js es ${missingTime}`;

        logo.print();

        setTimeout(() => {
            // eslint-disable-next-line no-console
            console.log(colors.yellow.bold(message));

            // eslint-disable-next-line no-console
            console.log(`Más info: ${event.link}\n`);
        }, 100);
    })
    .catch(error => {
        // eslint-disable-next-line no-console
        console.error(error.response.body);
    });
<|endoftext|>


<commit_before>import './sass/index.scss'
import print from './js/init'

const printJS = print.init

if (typeof window !== 'undefined') {
  window.printJS = printJS
}

export default printJS
<commit_msg>use node's module.export instead of ES6 default<commit_after>import './sass/index.scss'
import print from './js/init'

const printJS = print.init

if (typeof window !== 'undefined') {
  window.printJS = printJS
}

module.exports = printJS<|endoftext|>