<commit_before>'use strict';

const aws = require('aws-sdk');
const rds = new aws.RDS();
const DBInstanceIdentifier = process.env.AWS_DB_INSTANCE_IDENTIFIER;

const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
});

const plpr = require('plpr');

exports.handler = (event, context, callback) => {
  downloadLogFile().then(data => {
    const logs = plpr(data);
    logs.forEach((element, index, array) => {
      client.index({
        index: 'rds_log',
        type: DBInstanceIdentifier,
        body: {
          timestamp: Date.parse(element.timestamp),
          duration: element.duration,
          query: element.query
        },
      });
    });
  });
  return callback(null, 'success');
}

function getLogFiles() {
  const params = {
    DBInstanceIdentifier: DBInstanceIdentifier,
  };

  const describeDBLogFilesPromise = rds.describeDBLogFiles(params).promise();
  return describeDBLogFilesPromise.then(data => {
    const obj = JSON.parse(JSON.stringify(data))['DescribeDBLogFiles']
    return obj.map((element, index, array) => {
      return element['LogFileName'];
    });
  });
}

function downloadLogFile() {
  return getLogFiles().then(data => {
    const params = {
      DBInstanceIdentifier: DBInstanceIdentifier,
      LogFileName: data[data.length-1],
    };

    const downloadLogFilePortionPromise = rds.downloadDBLogFilePortion(params).promise();
    return downloadLogFilePortionPromise.then((data, err) => {
      return JSON.parse(JSON.stringify(data))['LogFileData'];
    });
  });
}
<commit_msg>Support bulk insert<commit_after>'use strict';

const aws = require('aws-sdk');
const rds = new aws.RDS();
const DBInstanceIdentifier = process.env.AWS_DB_INSTANCE_IDENTIFIER;
const esIndex = 'psql_query_log'

const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
  host: 'localhost:9200'
});

const plpr = require('plpr');

exports.handler = (event, context, callback) => {
  downloadLogFile().then(data => {
    const logs = plpr(data);
    console.log('Insert data length: ' + logs.length);
    var body = [];
    const description = JSON.stringify({index: {_index: esIndex, _type: DBInstanceIdentifier}});
    logs.forEach((element, index, array) => {
      body.push(description);
      body.push(JSON.stringify({timestamp: Date.parse(element.timestamp), duration: element.duration, query: element.query}));
    });

    client.bulk({
      body: body
    }, (error, response) => {
      if (error) return callback(error, error);
      else return callback(null, 'success');
    });
  });
}

function getLogFiles() {
  const params = {
    DBInstanceIdentifier: DBInstanceIdentifier,
  };

  const describeDBLogFilesPromise = rds.describeDBLogFiles(params).promise();
  return describeDBLogFilesPromise.then(data => {
    const obj = JSON.parse(JSON.stringify(data))['DescribeDBLogFiles']
    return obj.map((element, index, array) => {
      return element['LogFileName'];
    });
  });
}

function downloadLogFile() {
  return getLogFiles().then(data => {
    const params = {
      DBInstanceIdentifier: DBInstanceIdentifier,
      LogFileName: data[data.length-1],
    };

    const downloadLogFilePortionPromise = rds.downloadDBLogFilePortion(params).promise();
    console.log('Downloading ' + DBInstanceIdentifier + ':' + data[data.length-2] +  '...')
    return downloadLogFilePortionPromise.then((data, err) => {
      return JSON.parse(JSON.stringify(data))['LogFileData'];
    });
  });
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

// nS - No Space
// lC - Lowercase

import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import program from 'commander';
import replace from 'node-replace';
import shell from 'shelljs';
import pjson from '../package.json';
import path from 'path';
import { foldersAndFiles } from './config/foldersAndFiles';
import { filesToModifyContent } from './config/filesToModifyContent';
import { bundleIdentifiers } from './config/bundleIdentifiers';

const devTestRNProject = ''; // For Development eg '/Users/junedomingo/Desktop/RN49'
const __dirname = devTestRNProject || process.cwd();
const projectName = pjson.name;
const replaceOptions = {
  recursive: true,
  silent: true,
};

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

function replaceContent(regex, replacement, paths) {
  replace({
    regex,
    replacement,
    paths,
    ...replaceOptions,
  });

  for (const filePath of paths) {
    console.log(`${filePath.replace(__dirname, '')} ${colors.green('MODIFIED')}`);
  }
}

const deletePreviousBundleDirectory = ({ oldBundleNameDir, shouldDelete }) => {
  if (shouldDelete) {
    const dir = oldBundleNameDir.replace(/\./g, '/');
    const deleteDirectory = shell.rm('-rf', dir);
    Promise.resolve(deleteDirectory);
    console.log('Done removing previous bundle directory.'.green);
  } else {
    Promise.resolve();
    console.log('Bundle directory was not changed. Keeping...'.yellow);
  }
};

const cleanBuilds = () => {
  const deleteDirectories = shell.rm('-rf', [
    path.join(__dirname, 'ios/build/*'),
    path.join(__dirname, 'android/.gradle/*'),
    path.join(__dirname, 'android/app/build/*'),
    path.join(__dirname, 'android/build/*'),
  ]);
  Promise.resolve(deleteDirectories);
  console.log('Done removing builds.'.green);
};

readFile(path.join(__dirname, 'android/app/src/main/res/values/strings.xml'))
  .then(data => {
    const $ = cheerio.load(data);
    const currentAppName = $('string[name=app_name]').text();
    const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
    const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();

    program
      .version('2.4.1')
      .arguments('<newName>')
      .option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
      .action(newName => {
        const nS_NewName = newName.replace(/\s/g, '');
        const pattern = /^([\p{Letter}\p{Number}])+([\p{Letter}\p{Number}\s]+)$/u;
        const lC_Ns_NewAppName = nS_NewName.toLowerCase();
        const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
        let newBundlePath;
        const listOfFoldersAndFiles = foldersAndFiles(currentAppName, newName);
        const listOfFilesToModifyContent = filesToModifyContent(currentAppName, newName, projectName);

        if (bundleID) {
          newBundlePath = bundleID.replace(/\./g, '/');
          const id = bundleID.split('.');
          if (id.length < 2)
            return console.log(
              'Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"'
            );
        }

        if (!pattern.test(newName)) {
          return console.log(
            `"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`
          );
        }

        if (newName === currentAppName || newName === nS_CurrentAppName || newName === lC_Ns_CurrentAppName) {
          return console.log('Please try a different name.');
        }

        // Move files and folders from ./config/foldersAndFiles.js
        const resolveFoldersAndFiles = new Promise(resolve => {
          listOfFoldersAndFiles.forEach((element, index) => {
            const dest = element.replace(new RegExp(nS_CurrentAppName, 'i'), nS_NewName);
            let itemsProcessed = 1;
            const successMsg = `/${dest} ${colors.green('RENAMED')}`;

            setTimeout(() => {
              itemsProcessed += index;

              if (fs.existsSync(path.join(__dirname, element)) || !fs.existsSync(path.join(__dirname, element))) {
                const move = shell.exec(
                  `git mv "${path.join(__dirname, element)}" "${path.join(__dirname, dest)}" 2>/dev/null`
                );

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', path.join(__dirname, element), path.join(__dirname, dest)).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log("Ignore above error if this file doesn't exist");
                  }
                }
              }

              if (itemsProcessed === listOfFoldersAndFiles.length) {
                resolve();
              }
            }, 200 * index);
          });
        });

        // Modify file content from ./config/filesToModifyContent.js
        const resolveFilesToModifyContent = () =>
          new Promise(resolve => {
            let filePathsCount = 0;
            let itemsProcessed = 0;
            listOfFilesToModifyContent.map(file => {
              filePathsCount += file.paths.length;

              file.paths.map((filePath, index) => {
                const newPaths = [];

                setTimeout(() => {
                  itemsProcessed++;
                  if (fs.existsSync(path.join(__dirname, filePath))) {
                    newPaths.push(path.join(__dirname, filePath));
                    replaceContent(file.regex, file.replacement, newPaths);
                  }
                  if (itemsProcessed === filePathsCount) {
                    resolve();
                  }
                }, 200 * index);
              });
            });
          });

        const resolveJavaFiles = () =>
          new Promise(resolve => {
            readFile(path.join(__dirname, 'android/app/src/main/AndroidManifest.xml')).then(data => {
              const $ = cheerio.load(data);
              const currentBundleID = $('manifest').attr('package');
              const newBundleID = program.bundleID ? bundleID : `com.${lC_Ns_NewAppName}`;
              const javaFileBase = '/android/app/src/main/java';
              const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
              const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;

              if (bundleID) {
                newBundlePath = newJavaPath;
              } else {
                newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
                newBundlePath = `${javaFileBase}/${newBundlePath}`;
              }

              const fullCurrentBundlePath = path.join(__dirname, currentJavaPath);
              const fullNewBundlePath = path.join(__dirname, newBundlePath);

              // Create new bundle folder if doesn't exist yet
              if (!fs.existsSync(fullNewBundlePath)) {
                shell.mkdir('-p', fullNewBundlePath);
                const move = shell.exec(`git mv "${fullCurrentBundlePath}/"* "${fullNewBundlePath}" 2>/dev/null`);
                const successMsg = `${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`;

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', fullCurrentBundlePath + '/*', fullNewBundlePath).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log(`Error moving: "${currentJavaPath}" "${newBundlePath}"`);
                  }
                }
              }

              const vars = {
                currentBundleID,
                newBundleID,
                newBundlePath,
                javaFileBase,
                currentJavaPath,
                newJavaPath,
              };
              resolve(vars);
            });
          });

        const resolveBundleIdentifiers = params =>
          new Promise(resolve => {
            let filePathsCount = 0;
            const { currentBundleID, newBundleID, newBundlePath, javaFileBase, currentJavaPath, newJavaPath } = params;

            bundleIdentifiers(
              currentAppName,
              newName,
              projectName,
              currentBundleID,
              newBundleID,
              newBundlePath
            ).map(file => {
              filePathsCount += file.paths.length - 1;
              let itemsProcessed = 0;

              file.paths.map((filePath, index) => {
                const newPaths = [];
                if (fs.existsSync(path.join(__dirname, filePath))) {
                  newPaths.push(path.join(__dirname, filePath));

                  setTimeout(() => {
                    itemsProcessed += index;
                    replaceContent(file.regex, file.replacement, newPaths);
                    if (itemsProcessed === filePathsCount) {
                      const oldBundleNameDir = path.join(__dirname, javaFileBase, currentBundleID);
                      resolve({ oldBundleNameDir, shouldDelete: currentJavaPath !== newJavaPath });
                    }
                  }, 200 * index);
                }
              });
            });
          });

        const rename = () => {
          resolveFoldersAndFiles
            .then(resolveFilesToModifyContent)
            .then(resolveJavaFiles)
            .then(resolveBundleIdentifiers)
            .then(deletePreviousBundleDirectory)
            .then(cleanBuilds)
            .then(() => console.log(`APP SUCCESSFULLY RENAMED TO "${newName}"! 🎉 🎉 🎉`.green))
            .then(() => {
              if (fs.existsSync(path.join(__dirname, 'ios', 'Podfile'))) {
                console.log(
                  `${colors.yellow('Podfile has been modified, please run "pod install" inside ios directory.')}`
                );
              }
            })
            .then(() =>
              console.log(
                `${colors.yellow(
                  'Please make sure to run "watchman watch-del-all" and "npm start --reset-cache" before running the app. '
                )}`
              )
            );
        };

        rename();
      })
      .parse(process.argv);
    if (!process.argv.slice(2).length) program.outputHelp();
  })
  .catch(err => {
    if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');

    return console.log('Something went wrong: ', err);
  });
<commit_msg>Start using app.json as a source of trust.<commit_after>#!/usr/bin/env node

// nS - No Space
// lC - Lowercase

import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import program from 'commander';
import replace from 'node-replace';
import shell from 'shelljs';
import pjson from '../package.json';
import path from 'path';
import { foldersAndFiles } from './config/foldersAndFiles';
import { filesToModifyContent } from './config/filesToModifyContent';
import { bundleIdentifiers } from './config/bundleIdentifiers';

const devTestRNProject = ''; // For Development eg '/Users/junedomingo/Desktop/RN49'
const __dirname = devTestRNProject || process.cwd();
const projectName = pjson.name;
const replaceOptions = {
  recursive: true,
  silent: true,
};

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

function replaceContent(regex, replacement, paths) {
  replace({
    regex,
    replacement,
    paths,
    ...replaceOptions,
  });

  for (const filePath of paths) {
    console.log(`${filePath.replace(__dirname, '')} ${colors.green('MODIFIED')}`);
  }
}

const deletePreviousBundleDirectory = ({ oldBundleNameDir, shouldDelete }) => {
  if (shouldDelete) {
    const dir = oldBundleNameDir.replace(/\./g, '/');
    const deleteDirectory = shell.rm('-rf', dir);
    Promise.resolve(deleteDirectory);
    console.log('Done removing previous bundle directory.'.green);
  } else {
    Promise.resolve();
    console.log('Bundle directory was not changed. Keeping...'.yellow);
  }
};

const cleanBuilds = () => {
  const deleteDirectories = shell.rm('-rf', [
    path.join(__dirname, 'ios/build/*'),
    path.join(__dirname, 'android/.gradle/*'),
    path.join(__dirname, 'android/app/build/*'),
    path.join(__dirname, 'android/build/*'),
  ]);
  Promise.resolve(deleteDirectories);
  console.log('Done removing builds.'.green);
};

const loadAppConfig = () => {
  return readFile(path.join(__dirname, 'app.json')).then(data => JSON.parse(data));
}

loadAppConfig()
  .then(appConfig => {
    const currentAppName = appConfig.name;
    const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
    const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();

    program
      .version('2.4.1')
      .arguments('<newName>')
      .option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
      .action(newName => {
        const nS_NewName = newName.replace(/\s/g, '');
        const pattern = /^([\p{Letter}\p{Number}])+([\p{Letter}\p{Number}\s]+)$/u;
        const lC_Ns_NewAppName = nS_NewName.toLowerCase();
        const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
        let newBundlePath;
        const listOfFoldersAndFiles = foldersAndFiles(currentAppName, newName);
        const listOfFilesToModifyContent = filesToModifyContent(currentAppName, newName, projectName);

        if (bundleID) {
          newBundlePath = bundleID.replace(/\./g, '/');
          const id = bundleID.split('.');
          if (id.length < 2)
            return console.log(
              'Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"'
            );
        }

        if (!pattern.test(newName)) {
          return console.log(
            `"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`
          );
        }

        if (newName === currentAppName || newName === nS_CurrentAppName || newName === lC_Ns_CurrentAppName) {
          return console.log('Please try a different name.');
        }

        // Move files and folders from ./config/foldersAndFiles.js
        const resolveFoldersAndFiles = new Promise(resolve => {
          listOfFoldersAndFiles.forEach((element, index) => {
            const dest = element.replace(new RegExp(nS_CurrentAppName, 'i'), nS_NewName);
            let itemsProcessed = 1;
            const successMsg = `/${dest} ${colors.green('RENAMED')}`;

            setTimeout(() => {
              itemsProcessed += index;

              if (fs.existsSync(path.join(__dirname, element)) || !fs.existsSync(path.join(__dirname, element))) {
                const move = shell.exec(
                  `git mv "${path.join(__dirname, element)}" "${path.join(__dirname, dest)}" 2>/dev/null`
                );

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', path.join(__dirname, element), path.join(__dirname, dest)).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log("Ignore above error if this file doesn't exist");
                  }
                }
              }

              if (itemsProcessed === listOfFoldersAndFiles.length) {
                resolve();
              }
            }, 200 * index);
          });
        });

        // Modify file content from ./config/filesToModifyContent.js
        const resolveFilesToModifyContent = () =>
          new Promise(resolve => {
            let filePathsCount = 0;
            let itemsProcessed = 0;
            listOfFilesToModifyContent.map(file => {
              filePathsCount += file.paths.length;

              file.paths.map((filePath, index) => {
                const newPaths = [];

                setTimeout(() => {
                  itemsProcessed++;
                  if (fs.existsSync(path.join(__dirname, filePath))) {
                    newPaths.push(path.join(__dirname, filePath));
                    replaceContent(file.regex, file.replacement, newPaths);
                  }
                  if (itemsProcessed === filePathsCount) {
                    resolve();
                  }
                }, 200 * index);
              });
            });
          });

        const resolveJavaFiles = () =>
          new Promise(resolve => {
            readFile(path.join(__dirname, 'android/app/src/main/AndroidManifest.xml')).then(data => {
              const $ = cheerio.load(data);
              const currentBundleID = $('manifest').attr('package');
              const newBundleID = program.bundleID ? bundleID : `com.${lC_Ns_NewAppName}`;
              const javaFileBase = '/android/app/src/main/java';
              const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
              const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;

              if (bundleID) {
                newBundlePath = newJavaPath;
              } else {
                newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
                newBundlePath = `${javaFileBase}/${newBundlePath}`;
              }

              const fullCurrentBundlePath = path.join(__dirname, currentJavaPath);
              const fullNewBundlePath = path.join(__dirname, newBundlePath);

              // Create new bundle folder if doesn't exist yet
              if (!fs.existsSync(fullNewBundlePath)) {
                shell.mkdir('-p', fullNewBundlePath);
                const move = shell.exec(`git mv "${fullCurrentBundlePath}/"* "${fullNewBundlePath}" 2>/dev/null`);
                const successMsg = `${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`;

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', fullCurrentBundlePath + '/*', fullNewBundlePath).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log(`Error moving: "${currentJavaPath}" "${newBundlePath}"`);
                  }
                }
              }

              const vars = {
                currentBundleID,
                newBundleID,
                newBundlePath,
                javaFileBase,
                currentJavaPath,
                newJavaPath,
              };
              resolve(vars);
            });
          });

        const resolveBundleIdentifiers = params =>
          new Promise(resolve => {
            let filePathsCount = 0;
            const { currentBundleID, newBundleID, newBundlePath, javaFileBase, currentJavaPath, newJavaPath } = params;

            bundleIdentifiers(
              currentAppName,
              newName,
              projectName,
              currentBundleID,
              newBundleID,
              newBundlePath
            ).map(file => {
              filePathsCount += file.paths.length - 1;
              let itemsProcessed = 0;

              file.paths.map((filePath, index) => {
                const newPaths = [];
                if (fs.existsSync(path.join(__dirname, filePath))) {
                  newPaths.push(path.join(__dirname, filePath));

                  setTimeout(() => {
                    itemsProcessed += index;
                    replaceContent(file.regex, file.replacement, newPaths);
                    if (itemsProcessed === filePathsCount) {
                      const oldBundleNameDir = path.join(__dirname, javaFileBase, currentBundleID);
                      resolve({ oldBundleNameDir, shouldDelete: currentJavaPath !== newJavaPath });
                    }
                  }, 200 * index);
                }
              });
            });
          });

        const rename = () => {
          resolveFoldersAndFiles
            .then(resolveFilesToModifyContent)
            .then(resolveJavaFiles)
            .then(resolveBundleIdentifiers)
            .then(deletePreviousBundleDirectory)
            .then(cleanBuilds)
            .then(() => console.log(`APP SUCCESSFULLY RENAMED TO "${newName}"! 🎉 🎉 🎉`.green))
            .then(() => {
              if (fs.existsSync(path.join(__dirname, 'ios', 'Podfile'))) {
                console.log(
                  `${colors.yellow('Podfile has been modified, please run "pod install" inside ios directory.')}`
                );
              }
            })
            .then(() =>
              console.log(
                `${colors.yellow(
                  'Please make sure to run "watchman watch-del-all" and "npm start --reset-cache" before running the app. '
                )}`
              )
            );
        };

        rename();
      })
      .parse(process.argv);
    if (!process.argv.slice(2).length) program.outputHelp();
  })
  .catch(err => {
    if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');

    return console.log('Something went wrong: ', err);
  });
<|endoftext|>


<commit_before>import React from 'react';
import Mousetrap from 'mousetrap';

/*
 * Compare two keymaps
 */
function areKeyMapsEqual(a, b) {
    const aKeys = Object.keys(a);
    const aSize = aKeys.length;
    const bSize = Object.keys(b).length;

    if (aSize != bSize) {
        return false;
    }

    for (let i = 0; i < aSize; i++) {
        const aKey = aKeys[i];
        const aValue = a[aKey];
        const bValue = b[aKey];

        if (aValue != bValue) {
            return false;
        }
    }

    return true;
}

/*
 * Bind a keymap using mousetrap.
 */
class ComboKeys extends React.Component {
    constructor(props) {
        super(props);

        this.mousetrap = Mousetrap();

        const _stopCallback = this.mousetrap.stopCallback;
        this.mousetrap.stopCallback = function(e, element, combo) {
            let result = _stopCallback(e, element, combo);

            if (result) {
                result = this.props.stopAt(e, element, combo);
            }

            return result;
        };
    }

    componentDidMount() {
        this.bindKeyMap(
            this.props.keyMap
        );
    }

    componentDidUpdate(prevProps) {
        if (areKeyMapsEqual(prevProps.keyMap, this.props.keyMap)) {
            return;
        }

        this.unbindKeyMap(prevProps.keyMap);
        this.bindKeyMap(this.props.keyMap);
    }

    componentWillUnmount() {
        this.unbindKeyMap(
            this.props.keyMap
        );
    }

    unbindKeyMap(keyMap) {
        Object.keys(keyMap)
        .forEach((combo) => {
            this.mousetrap.unbind(combo);
        });
    }

    bindKeyMap(keyMap) {
        Object.keys(keyMap)
        .forEach((combo) => {
            const onTrigger = keyMap[combo];
            this.mousetrap.bind(combo, onTrigger);
        });
    }

    render() {
        const { children } = this.props;
        return children ? React.Children.only(children) : null;
    }
}

ComboKeys.propTypes = {
    children: React.PropTypes.node,
    keyMap: React.PropTypes.objectOf(
        React.PropTypes.func
    ).isRequired,
    stopAt: React.PropTypes.func
};

/*
 * Component to bind a single handler. This is a wrapper around ComboKeys.
 */
class ComboKey extends React.PureComponent {
    render() {
        const { children, combo, onTrigger } = this.props;
        const keyMap = { [combo]: onTrigger };

        return (
            <ComboKeys keyMap={keyMap}>
                {children}
            </ComboKeys>
        );
    }
}

ComboKey.propTypes = {
    children: React.PropTypes.node,
    combo: React.PropTypes.string.isRequired,
    onTrigger: React.PropTypes.func.isRequired
};

export {
    ComboKey,
    ComboKeys
};
<commit_msg>Fix error with stopCallback<commit_after>import React from 'react';
import Mousetrap from 'mousetrap';

/*
 * Compare two keymaps
 */
function areKeyMapsEqual(a, b) {
    const aKeys = Object.keys(a);
    const aSize = aKeys.length;
    const bSize = Object.keys(b).length;

    if (aSize != bSize) {
        return false;
    }

    for (let i = 0; i < aSize; i++) {
        const aKey = aKeys[i];
        const aValue = a[aKey];
        const bValue = b[aKey];

        if (aValue != bValue) {
            return false;
        }
    }

    return true;
}

/*
 * Bind a keymap using mousetrap.
 */
class ComboKeys extends React.Component {
    constructor(props) {
        super(props);

        const self = this;
        this.mousetrap = Mousetrap();

        const _stopCallback = this.mousetrap.stopCallback;
        this.mousetrap.stopCallback = (e, element, combo) => {
            let result = _stopCallback(e, element, combo);

            if (result) {
                result = self.props.stopAt(e, element, combo);
            }

            return result;
        };
    }

    componentDidMount() {
        this.bindKeyMap(
            this.props.keyMap
        );
    }

    componentDidUpdate(prevProps) {
        if (areKeyMapsEqual(prevProps.keyMap, this.props.keyMap)) {
            return;
        }

        this.unbindKeyMap(prevProps.keyMap);
        this.bindKeyMap(this.props.keyMap);
    }

    componentWillUnmount() {
        this.unbindKeyMap(
            this.props.keyMap
        );
    }

    unbindKeyMap(keyMap) {
        Object.keys(keyMap)
        .forEach((combo) => {
            this.mousetrap.unbind(combo);
        });
    }

    bindKeyMap(keyMap) {
        Object.keys(keyMap)
        .forEach((combo) => {
            const onTrigger = keyMap[combo];
            this.mousetrap.bind(combo, onTrigger);
        });
    }

    render() {
        const { children } = this.props;
        return children ? React.Children.only(children) : null;
    }
}

ComboKeys.propTypes = {
    children: React.PropTypes.node,
    keyMap: React.PropTypes.objectOf(
        React.PropTypes.func
    ).isRequired,
    stopAt: React.PropTypes.func
};

/*
 * Component to bind a single handler. This is a wrapper around ComboKeys.
 */
class ComboKey extends React.PureComponent {
    render() {
        const { children, combo, onTrigger } = this.props;
        const keyMap = { [combo]: onTrigger };

        return (
            <ComboKeys keyMap={keyMap}>
                {children}
            </ComboKeys>
        );
    }
}

ComboKey.propTypes = {
    children: React.PropTypes.node,
    combo: React.PropTypes.string.isRequired,
    onTrigger: React.PropTypes.func.isRequired
};

export {
    ComboKey,
    ComboKeys
};
<|endoftext|>


<commit_before>'use strict';

const debug = require('debug')('webpack-hot-server-middleware');
const path = require('path');
const requireFromString = require('require-from-string');
const MultiCompiler = require('webpack/lib/MultiCompiler');
const sourceMapSupport = require('source-map-support');

const DEFAULTS = {
    chunkName: 'main'
};

function interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj.default : obj;
}

function findCompiler(multiCompiler, name) {
    return multiCompiler.compilers.find(compiler => compiler.name === name);
}

function findStats(multiStats, name) {
    return multiStats.stats.find(stats => stats.compilation.name === name);
}

function getFilename(serverStats, outputPath, chunkName) {
    const assetsByChunkName = serverStats.toJson().assetsByChunkName;
    let filename = assetsByChunkName[chunkName] || '';
    // If source maps are generated `assetsByChunkName.main`
    // will be an array of filenames.
    return path.join(
        outputPath,
        Array.isArray(filename) ?
            filename.find(asset => /\.js$/.test(asset)) : filename
    );
}

function getServerRenderer(filename, buffer, clientStats) {
    const errMessage = `The 'server' compiler must export a function in the form of \`(stats) => (req, res, next) => void 0\``;

    let serverRenderer = interopRequireDefault(
        requireFromString(buffer.toString(), filename)
    );
    if (typeof serverRenderer !== 'function') {
        throw new Error(errMessage);
    }

    serverRenderer = serverRenderer(clientStats.toJson());
    if (typeof serverRenderer !== 'function') {
        throw new Error(errMessage);
    }

    return serverRenderer;
}

function installSourceMapSupport(fs) {
    sourceMapSupport.install({
        // NOTE: If https://github.com/evanw/node-source-map-support/pull/149
        // lands we can be less aggressive and explicitly invalidate the source
        // map cache when Webpack recompiles.
        emptyCacheBetweenOperations: true,
        retrieveFile(source) {
            try {
                return fs.readFileSync(source, 'utf8');
            } catch(ex) {
                // Doesn't exist
            }
        }
    });
}

/**
 * Passes the request to the most up to date 'server' bundle.
 * NOTE: This must be mounted after webpackDevMiddleware to ensure this
 * middleware doesn't get called until the compilation is complete.
 * @param   {MultiCompiler} multiCompiler      e.g webpack([clientConfig, serverConfig])
 * @options {String}        options.chunkName  The name of the main server chunk.
 * @return  {Function}                         Middleware fn.
 */
function webpackHotServerMiddleware(multiCompiler, options) {
    debug('Using webpack-hot-server-middleware');

    options = Object.assign({}, DEFAULTS, options);

    if (!(multiCompiler instanceof MultiCompiler)) {
        throw new Error(`Expected webpack compiler to contain both a 'client' and 'server' config`);
    }

    const serverCompiler = findCompiler(multiCompiler, 'server');
    const clientCompiler = findCompiler(multiCompiler, 'client');

    if (!serverCompiler) {
        throw new Error(`Expected a webpack compiler named 'server'`);
    }
    if (!clientCompiler) {
        throw new Error(`Expected a webpack compiler named 'client'`);
    }

    const outputFs = serverCompiler.outputFileSystem;
    const outputPath = serverCompiler.outputPath;

    installSourceMapSupport(outputFs);

    let serverRenderer;
    let error = false;

    multiCompiler.plugin('done', multiStats => {
        error = false;
        const clientStats = findStats(multiStats, 'client');
        const serverStats = findStats(multiStats, 'server');
        // Server compilation errors need to be propagated to the client.
        if (serverStats.compilation.errors.length) {
            error = serverStats.compilation.errors[0];
            return;
        }
        const filename = getFilename(serverStats, outputPath, options.chunkName);
        const buffer = outputFs.readFileSync(filename);
        try {
            serverRenderer = getServerRenderer(filename, buffer, clientStats);
        } catch (ex) {
            debug(ex);
            error = ex;
        }
    });

    return (req, res, next) => {
        debug(`Receive request ${req.url}`);
        if (error) {
            return next(error);
        }
        serverRenderer(req, res, next);
    };
}

module.exports = webpackHotServerMiddleware;
<commit_msg>Pass server stats to serverRenderer (#18)<commit_after>'use strict';

const debug = require('debug')('webpack-hot-server-middleware');
const path = require('path');
const requireFromString = require('require-from-string');
const MultiCompiler = require('webpack/lib/MultiCompiler');
const sourceMapSupport = require('source-map-support');

const DEFAULTS = {
    chunkName: 'main'
};

function interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj.default : obj;
}

function findCompiler(multiCompiler, name) {
    return multiCompiler.compilers.find(compiler => compiler.name === name);
}

function findStats(multiStats, name) {
    return multiStats.stats.find(stats => stats.compilation.name === name);
}

function getFilename(serverStats, outputPath, chunkName) {
    const assetsByChunkName = serverStats.toJson().assetsByChunkName;
    let filename = assetsByChunkName[chunkName] || '';
    // If source maps are generated `assetsByChunkName.main`
    // will be an array of filenames.
    return path.join(
        outputPath,
        Array.isArray(filename) ?
            filename.find(asset => /\.js$/.test(asset)) : filename
    );
}

function getServerRenderer(filename, buffer, clientStats, serverStats, options) {
    const errMessage = `The 'server' compiler must export a function in the form of \`(stats) => (req, res, next) => void 0\``;

    let serverRenderer = interopRequireDefault(
        requireFromString(buffer.toString(), filename)
    );
    if (typeof serverRenderer !== 'function') {
        throw new Error(errMessage);
    }

    serverRenderer = serverRenderer(clientStats.toJson(), serverStats.toJson(), options);
    if (typeof serverRenderer !== 'function') {
        throw new Error(errMessage);
    }

    return serverRenderer;
}

function installSourceMapSupport(fs) {
    sourceMapSupport.install({
        // NOTE: If https://github.com/evanw/node-source-map-support/pull/149
        // lands we can be less aggressive and explicitly invalidate the source
        // map cache when Webpack recompiles.
        emptyCacheBetweenOperations: true,
        retrieveFile(source) {
            try {
                return fs.readFileSync(source, 'utf8');
            } catch(ex) {
                // Doesn't exist
            }
        }
    });
}

/**
 * Passes the request to the most up to date 'server' bundle.
 * NOTE: This must be mounted after webpackDevMiddleware to ensure this
 * middleware doesn't get called until the compilation is complete.
 * @param   {MultiCompiler} multiCompiler      e.g webpack([clientConfig, serverConfig])
 * @options {String}        options.chunkName  The name of the main server chunk.
 * @return  {Function}                         Middleware fn.
 */
function webpackHotServerMiddleware(multiCompiler, options) {
    debug('Using webpack-hot-server-middleware');

    options = Object.assign({}, DEFAULTS, options);

    if (!(multiCompiler instanceof MultiCompiler)) {
        throw new Error(`Expected webpack compiler to contain both a 'client' and 'server' config`);
    }

    const serverCompiler = findCompiler(multiCompiler, 'server');
    const clientCompiler = findCompiler(multiCompiler, 'client');

    if (!serverCompiler) {
        throw new Error(`Expected a webpack compiler named 'server'`);
    }
    if (!clientCompiler) {
        throw new Error(`Expected a webpack compiler named 'client'`);
    }

    const outputFs = serverCompiler.outputFileSystem;
    const outputPath = serverCompiler.outputPath;

    installSourceMapSupport(outputFs);

    let serverRenderer;
    let error = false;

    multiCompiler.plugin('done', multiStats => {
        error = false;
        const clientStats = findStats(multiStats, 'client');
        const serverStats = findStats(multiStats, 'server');
        // Server compilation errors need to be propagated to the client.
        if (serverStats.compilation.errors.length) {
            error = serverStats.compilation.errors[0];
            return;
        }
        const filename = getFilename(serverStats, outputPath, options.chunkName);
        const buffer = outputFs.readFileSync(filename);
        try {
            options.config = {
                client: clientCompiler.options,
                server: serverCompiler.options
            }
            serverRenderer = getServerRenderer(filename, buffer, clientStats, serverStats, options);
        } catch (ex) {
            debug(ex);
            error = ex;
        }
    });

    return (req, res, next) => {
        debug(`Receive request ${req.url}`);
        if (error) {
            return next(error);
        }
        serverRenderer(req, res, next);
    };
}

module.exports = webpackHotServerMiddleware;
<|endoftext|>


<commit_before>import core from 'core-js';
import {Aurelia, LogManager} from 'aurelia-framework';
import {ConsoleAppender} from 'aurelia-logging-console';

var logger = LogManager.getLogger('bootstrapper');

var readyQueue = [];
var isReady = false;

function onReady(callback) {
  return new Promise((resolve, reject) => {
    if (!isReady) {
      readyQueue.push(() => {
        try {
          resolve(callback());
        } catch(e) {
          reject(e);
        }
      });
    } else {
      resolve(callback());
    }
  });
}

export function bootstrap(configure) {
  return onReady(() => {
    var loader = new window.AureliaLoader(),
        aurelia = new Aurelia(loader);

    return configureAurelia(aurelia).then(() => { return configure(aurelia); });
  });
}

function ready(global) {
  return new Promise((resolve, reject) =>{
    if (global.document.readyState === "complete" ) {
      resolve(global.document);
    } else {
      global.document.addEventListener("DOMContentLoaded", completed, false);
      global.addEventListener("load", completed, false);
    }

    function completed() {
      global.document.removeEventListener("DOMContentLoaded", completed, false);
      global.removeEventListener("load", completed, false);
      resolve(global.document);
    }
  });
}

function ensureLoader(){
  if(!window.AureliaLoader){
    return System.normalize('aurelia-bootstrapper').then(function(bootstrapperName){
      return System.normalize('aurelia-loader-default', bootstrapperName).then(function(loaderName){
        return System.import(loaderName);
      })
    });
  }

  return Promise.resolve();
}

function preparePlatform(){
  return System.normalize('aurelia-bootstrapper').then(function(bootstrapperName){
    return System.normalize('aurelia-framework', bootstrapperName).then(function(frameworkName){
      System.map['aurelia-framework'] = frameworkName;

      return System.normalize('aurelia-loader', frameworkName).then(function(loaderName){
        var toLoad = [];

        if(!System.polyfilled){
          logger.debug('loading core-js');
          toLoad.push(System.normalize('core-js', loaderName).then(function(name){
            return System.import(name);
          }));
        }

        toLoad.push(System.normalize('aurelia-dependency-injection', frameworkName).then(function(name){
          System.map['aurelia-dependency-injection'] = name;
        }));

        toLoad.push(System.normalize('aurelia-router', bootstrapperName).then(function(name){
          System.map['aurelia-router'] = name;
        }));

        toLoad.push(System.normalize('aurelia-logging-console', bootstrapperName).then(function(name){
          System.map['aurelia-logging-console'] = name;
        }));

        if(!('import' in document.createElement('link'))){
          logger.debug('loading the HTMLImports polyfill');
          toLoad.push(System.normalize('webcomponentsjs/HTMLImports.min', loaderName).then(function(name){
            return System.import(name);
          }));
        }

        if(!("content" in document.createElement("template"))){
          logger.debug('loading the HTMLTemplateElement polyfill');
          toLoad.push(System.normalize('aurelia-html-template-element', loaderName).then(function(name){
            return System.import(name);
          }));
        }

        return Promise.all(toLoad);
      });
    });
  });
}

var installedDevelopmentLogging = false;

function configureAurelia(aurelia){
  return System.normalize('aurelia-bootstrapper').then(function(bName){
    var toLoad = [];

    toLoad.push(System.normalize('aurelia-templating-binding', bName).then(templatingBinding => {
      aurelia.use.defaultBindingLanguage = function(){
        aurelia.use.plugin(templatingBinding);
        return this;
      };
    }));

    toLoad.push(System.normalize('aurelia-templating-router', bName).then(templatingRouter => {
      aurelia.use.router = function(){
        aurelia.use.plugin(templatingRouter);
        return this;
      };
    }));

    toLoad.push(System.normalize('aurelia-history-browser', bName).then(historyBrowser => {
      aurelia.use.history = function(){
        aurelia.use.plugin(historyBrowser);
        return this;
      };
    }));

    toLoad.push(System.normalize('aurelia-templating-resources', bName).then(name => {
      System.map['aurelia-templating-resources'] = name;
      aurelia.use.defaultResources = function(){
        aurelia.use.plugin(name);
        return this;
      }
    }));

    toLoad.push(System.normalize('aurelia-event-aggregator', bName).then(eventAggregator => {
      System.map['aurelia-event-aggregator'] = eventAggregator;
      aurelia.use.eventAggregator = function(){
        aurelia.use.plugin(eventAggregator);
        return this;
      };
    }));

    aurelia.use.standardConfiguration = function(){
      aurelia.use
        .defaultBindingLanguage()
        .defaultResources()
        .history()
        .router()
        .eventAggregator();
      return this;
    };

    aurelia.use.developmentLogging = function(){
      if(!installedDevelopmentLogging){
        installedDevelopmentLogging = true;
        LogManager.addAppender(new ConsoleAppender());
        LogManager.setLevel(LogManager.logLevel.debug);
      }
      return this;
    }

    return Promise.all(toLoad);
  });
}

function runningLocally(){
  return window.location.protocol !== 'http' && window.location.protocol !== 'https';
}

function handleApp(appHost){
  var configModuleId = appHost.getAttribute('aurelia-app'),
      aurelia, loader;

  if(configModuleId){
    loader = new window.AureliaLoader();

    return loader.loadModule(configModuleId)
      .then(m => {
        aurelia = new Aurelia(loader);
        aurelia.host = appHost;
        return configureAurelia(aurelia).then(() => { return m.configure(aurelia); });
      });
  }else{
    aurelia = new Aurelia();
    aurelia.host = appHost;

    return configureAurelia(aurelia).then(() => {
      if(runningLocally()){
        aurelia.use.developmentLogging();
      }

      aurelia.use.standardConfiguration();

      return aurelia.start().then(a => a.setRoot());
    });
  }
}

function run() {
  return ready(window).then(doc => {
    var appHost = doc.querySelectorAll("[aurelia-app]");

    return ensureLoader().then(() => {
      return preparePlatform().then(function(){
        var i, ii;

        for (i = 0, ii = appHost.length; i < ii; ++i) {
          handleApp(appHost[i]);
        }

        isReady = true;
        for (i = 0, ii = readyQueue.length; i < ii; ++i) {
          readyQueue[i]();
        }
        readyQueue = [];
      });
    });
  });
}

run();
<commit_msg>fix(index): detect System or require api and load appropriately<commit_after>import core from 'core-js';
import {Aurelia, LogManager} from 'aurelia-framework';
import {ConsoleAppender} from 'aurelia-logging-console';

var logger = LogManager.getLogger('bootstrapper');

var readyQueue = [];
var isReady = false;

function onReady(callback) {
  return new Promise((resolve, reject) => {
    if (!isReady) {
      readyQueue.push(() => {
        try {
          resolve(callback());
        } catch(e) {
          reject(e);
        }
      });
    } else {
      resolve(callback());
    }
  });
}

export function bootstrap(configure) {
  return onReady(() => {
    var loader = new window.AureliaLoader(),
        aurelia = new Aurelia(loader);

    return configureAurelia(aurelia).then(() => { return configure(aurelia); });
  });
}

function ready(global) {
  return new Promise((resolve, reject) =>{
    if (global.document.readyState === "complete" ) {
      resolve(global.document);
    } else {
      global.document.addEventListener("DOMContentLoaded", completed, false);
      global.addEventListener("load", completed, false);
    }

    function completed() {
      global.document.removeEventListener("DOMContentLoaded", completed, false);
      global.removeEventListener("load", completed, false);
      resolve(global.document);
    }
  });
}

function ensureLoader(){
  if(!window.AureliaLoader){
    if(window.System){
      return System.normalize('aurelia-bootstrapper').then(bootstrapperName => {
        return System.normalize('aurelia-loader-default', bootstrapperName).then(loaderName => {
          return System.import(loaderName);
        })
      });
    } else if(window.require){
      return new Promise((resolve, reject) => {
        require(['aurelia-loader-default'], resolve, reject);
      });
    }else{
      throw new Error('No window.AureliaLoader is defined and there is neither a System API (ES6) or a Require API (AMD) available to load your app.')
    }
  }

  return Promise.resolve();
}

function preparePlatform(){
  return System.normalize('aurelia-bootstrapper').then(function(bootstrapperName){
    return System.normalize('aurelia-framework', bootstrapperName).then(function(frameworkName){
      System.map['aurelia-framework'] = frameworkName;

      return System.normalize('aurelia-loader', frameworkName).then(function(loaderName){
        var toLoad = [];

        if(!System.polyfilled){
          logger.debug('loading core-js');
          toLoad.push(System.normalize('core-js', loaderName).then(function(name){
            return System.import(name);
          }));
        }

        toLoad.push(System.normalize('aurelia-dependency-injection', frameworkName).then(function(name){
          System.map['aurelia-dependency-injection'] = name;
        }));

        toLoad.push(System.normalize('aurelia-router', bootstrapperName).then(function(name){
          System.map['aurelia-router'] = name;
        }));

        toLoad.push(System.normalize('aurelia-logging-console', bootstrapperName).then(function(name){
          System.map['aurelia-logging-console'] = name;
        }));

        if(!('import' in document.createElement('link'))){
          logger.debug('loading the HTMLImports polyfill');
          toLoad.push(System.normalize('webcomponentsjs/HTMLImports.min', loaderName).then(function(name){
            return System.import(name);
          }));
        }

        if(!("content" in document.createElement("template"))){
          logger.debug('loading the HTMLTemplateElement polyfill');
          toLoad.push(System.normalize('aurelia-html-template-element', loaderName).then(function(name){
            return System.import(name);
          }));
        }

        return Promise.all(toLoad);
      });
    });
  });
}

var installedDevelopmentLogging = false;

function configureAurelia(aurelia){
  return System.normalize('aurelia-bootstrapper').then(function(bName){
    var toLoad = [];

    toLoad.push(System.normalize('aurelia-templating-binding', bName).then(templatingBinding => {
      aurelia.use.defaultBindingLanguage = function(){
        aurelia.use.plugin(templatingBinding);
        return this;
      };
    }));

    toLoad.push(System.normalize('aurelia-templating-router', bName).then(templatingRouter => {
      aurelia.use.router = function(){
        aurelia.use.plugin(templatingRouter);
        return this;
      };
    }));

    toLoad.push(System.normalize('aurelia-history-browser', bName).then(historyBrowser => {
      aurelia.use.history = function(){
        aurelia.use.plugin(historyBrowser);
        return this;
      };
    }));

    toLoad.push(System.normalize('aurelia-templating-resources', bName).then(name => {
      System.map['aurelia-templating-resources'] = name;
      aurelia.use.defaultResources = function(){
        aurelia.use.plugin(name);
        return this;
      }
    }));

    toLoad.push(System.normalize('aurelia-event-aggregator', bName).then(eventAggregator => {
      System.map['aurelia-event-aggregator'] = eventAggregator;
      aurelia.use.eventAggregator = function(){
        aurelia.use.plugin(eventAggregator);
        return this;
      };
    }));

    aurelia.use.standardConfiguration = function(){
      aurelia.use
        .defaultBindingLanguage()
        .defaultResources()
        .history()
        .router()
        .eventAggregator();
      return this;
    };

    aurelia.use.developmentLogging = function(){
      if(!installedDevelopmentLogging){
        installedDevelopmentLogging = true;
        LogManager.addAppender(new ConsoleAppender());
        LogManager.setLevel(LogManager.logLevel.debug);
      }
      return this;
    }

    return Promise.all(toLoad);
  });
}

function runningLocally(){
  return window.location.protocol !== 'http' && window.location.protocol !== 'https';
}

function handleApp(appHost){
  var configModuleId = appHost.getAttribute('aurelia-app'),
      aurelia, loader;

  if(configModuleId){
    loader = new window.AureliaLoader();

    return loader.loadModule(configModuleId)
      .then(m => {
        aurelia = new Aurelia(loader);
        aurelia.host = appHost;
        return configureAurelia(aurelia).then(() => { return m.configure(aurelia); });
      });
  }else{
    aurelia = new Aurelia();
    aurelia.host = appHost;

    return configureAurelia(aurelia).then(() => {
      if(runningLocally()){
        aurelia.use.developmentLogging();
      }

      aurelia.use.standardConfiguration();

      return aurelia.start().then(a => a.setRoot());
    });
  }
}

function run() {
  return ready(window).then(doc => {
    var appHost = doc.querySelectorAll("[aurelia-app]");

    return ensureLoader().then(() => {
      return preparePlatform().then(function(){
        var i, ii;

        for (i = 0, ii = appHost.length; i < ii; ++i) {
          handleApp(appHost[i]);
        }

        isReady = true;
        for (i = 0, ii = readyQueue.length; i < ii; ++i) {
          readyQueue[i]();
        }
        readyQueue = [];
      });
    });
  });
}

run();
<|endoftext|>


<commit_before>'use strict';

module.exports = function () {
    // returns true
    // comment
    // hello
    return true;
};
<commit_msg>feat: add a name to the function<commit_after>'use strict';

module.exports = function named() {
    // returns true
    // comment
    // hello
    return true;
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import jsQR from 'jsqr'
import raf from 'raf'
import 'md-gum-polyfill'
import 'webrtc-adapter'

raf.polyfill()

export default class Reader extends Component {
  constructor(props){
    super(props)

    this.initiate = this.initiate.bind(this)
    this.initiateLegacyMode = this.initiateLegacyMode.bind(this)
    this.check = this.check.bind(this)
    this.handleVideo = this.handleVideo.bind(this)
    this.handleLoadStart = this.handleLoadStart.bind(this)
    this.handleInputChange = this.handleInputChange.bind(this)
    this.clearComponent = this.clearComponent.bind(this)
    this.handleReaderLoad = this.handleReaderLoad.bind(this)

    this.componentWillUnmount = this.clearComponent
  }
  componentDidMount(){
    if(!this.props.legacyMode){
      this.initiate()
    }else{
      this.initiateLegacyMode()
    }
  }
  componentWillReceiveProps(newProps){
    if(!newProps.legacyMode && this.props.facingMode != newProps.facingMode){
      this.clearComponent()
      this.initiate()
    }
    if(!this.props.legacyMode && newProps.legacyMode){
      this.clearComponent()
      this.componentDidUpdate = this.initiateLegacyMode
    }
    if(this.props.legacyMode && !newProps.legacyMode){
      this.clearComponent()
      this.initiate()
    }
  }
  clearComponent(){
    if (this._interval)
      clearInterval(this._interval)

    if (typeof this.stopCamera === 'function')
      this.stopCamera()

    if(this.requestFrameId){
      window.cancelAnimationFrame(this.requestFrameId)
      delete this.requestFrameId
    }

    if(this.reader){
      this.reader.removeEventListener('load', this.handleReaderLoad)
      this.reader = undefined
    }

    if(this.refs.img){
      this.refs.img.removeEventListener('load', this.check)
    }
  }
  initiate(){
    const { handleError, facingMode } = this.props

    const constrains = {
      video: {
        facingMode: facingMode ? {
          exact: facingMode == 'rear' ? 'environment' : 'user',
        } : undefined,
        width: { min: 360, ideal: 1280, max: 1920 },
        height: { min: 240, ideal: 720, max: 1080 },
      },
    }

    try {
      navigator.mediaDevices.getUserMedia(constrains)
      .then(this.handleVideo)
      .catch(e => handleError(e.name))
    } catch (e) {
      handleError('Not compatible with getUserMedia.')
    }
  }
  handleVideo(stream) {
    const { preview } = this.refs

    if(window.URL.createObjectURL){
      preview.src = window.URL.createObjectURL(stream)
    }else if (window.webkitURL) {
      preview.src = window.webkitURL.createObjectURL(stream)
    } else if (preview.mozSrcObject !== undefined) {
      preview.mozSrcObject = stream
    } else {
      preview.src = stream
    }

    const streamTrack = stream.getTracks()[0]
    this.stopCamera = streamTrack.stop.bind(streamTrack)

    preview.addEventListener('loadstart', this.handleLoadStart)
  }
  handleLoadStart(){
    const preview = this.refs.preview
    preview.play()
    if(this.props.interval){
      this._interval = setInterval(this.check, this.props.interval)
    }else if(!this.requestFrameId){
      this.check()
    }

    preview.removeEventListener('loadstart', this.handleLoadStart)
  }
  check() {
    const { interval, handleScan, legacyMode } = this.props
    const { preview, canvas, img } = this.refs
    let width = Math.floor(legacyMode ? img.naturalWidth : preview.videoWidth)
    let height = Math.floor(legacyMode ? img.naturalHeight : preview.videoHeight)

    if(legacyMode){
      while ((width > height ? width : height) > 1000) {
        width = Math.floor(width / 1.5)
        height = Math.floor(width / 1.5)
      }
    }

    canvas.width = width
    canvas.height = height

    if(!interval && !legacyMode)
      this.requestFrameId = window.requestAnimationFrame(this.check)

    if (legacyMode || (preview && preview.readyState === preview.HAVE_ENOUGH_DATA)){
      const ctx = canvas.getContext('2d')
      ctx.drawImage(legacyMode ? img : preview, 0, 0, width, height)

      const imageData = ctx.getImageData(0, 0, width, height)
      const decoded = jsQR.decodeQRFromImage(imageData.data, width, height)

      if(decoded)
        handleScan(decoded)
    }
  }
  initiateLegacyMode(){
    this.reader = new FileReader()

    this.reader.addEventListener('load', this.handleReaderLoad)

    this.refs.img.addEventListener('load', this.check, false)

    this.componentDidUpdate = undefined
  }
  handleInputChange(e){
    this.reader.readAsDataURL(e.target.files[0])
  }
  handleReaderLoad(e){
    this.refs.img.src = e.target.result
  }
  render(){
    const previewStyle = {
      display: 'block',
      objectFit: 'contain',
      ...this.props.previewStyle,
    }
    const canvasStyle = {
      display: 'none',
    }

    return (

        {this.props.legacyMode ? (

            <input style={this.props.inputStyle} type="file" accept="image/*" ref="input" onChange={this.handleInputChange}/>

        ) : (
          <video style={previewStyle} ref="preview"/>
        )}
        <canvas style={canvasStyle} ref="canvas"/>

    )
  }
}

Reader.defaultProps = {
  interval: null,
  previewStyle: {},
  inputStyle: {},
}
Reader.propTypes = {
  handleScan: PropTypes.func.isRequired,
  handleError: PropTypes.func.isRequired,
  interval: PropTypes.number,
  previewStyle: PropTypes.object,
  inputStyle: PropTypes.object,
  facingMode: PropTypes.string,
  legacyMode: PropTypes.bool,
}
<commit_msg>Faster scanning<commit_after>import React, { Component, PropTypes } from 'react'
import jsQR from 'jsqr'
import raf from 'raf'
import 'md-gum-polyfill'
import 'webrtc-adapter'

raf.polyfill()

export default class Reader extends Component {
  constructor(props){
    super(props)

    this.initiate = this.initiate.bind(this)
    this.initiateLegacyMode = this.initiateLegacyMode.bind(this)
    this.check = this.check.bind(this)
    this.handleVideo = this.handleVideo.bind(this)
    this.handleLoadStart = this.handleLoadStart.bind(this)
    this.handleInputChange = this.handleInputChange.bind(this)
    this.clearComponent = this.clearComponent.bind(this)
    this.handleReaderLoad = this.handleReaderLoad.bind(this)

    this.componentWillUnmount = this.clearComponent
  }
  componentDidMount(){
    if(!this.props.legacyMode){
      this.initiate()
    }else{
      this.initiateLegacyMode()
    }
  }
  componentWillReceiveProps(newProps){
    if(!newProps.legacyMode && this.props.facingMode != newProps.facingMode){
      this.clearComponent()
      this.initiate()
    }
    if(!this.props.legacyMode && newProps.legacyMode){
      this.clearComponent()
      this.componentDidUpdate = this.initiateLegacyMode
    }
    if(this.props.legacyMode && !newProps.legacyMode){
      this.clearComponent()
      this.initiate()
    }
  }
  clearComponent(){
    if (this._interval)
      clearInterval(this._interval)

    if (typeof this.stopCamera === 'function')
      this.stopCamera()

    if(this.requestFrameId){
      window.cancelAnimationFrame(this.requestFrameId)
      delete this.requestFrameId
    }

    if(this.reader){
      this.reader.removeEventListener('load', this.handleReaderLoad)
      this.reader = undefined
    }

    if(this.refs.img){
      this.refs.img.removeEventListener('load', this.check)
    }
  }
  initiate(){
    const { handleError, facingMode } = this.props

    const constrains = {
      video: {
        facingMode: facingMode ? {
          exact: facingMode == 'rear' ? 'environment' : 'user',
        } : undefined,
        width: { min: 360, ideal: 1280, max: 1920 },
        height: { min: 240, ideal: 720, max: 1080 },
      },
    }

    try {
      navigator.mediaDevices.getUserMedia(constrains)
      .then(this.handleVideo)
      .catch(e => handleError(e.name))
    } catch (e) {
      handleError('Not compatible with getUserMedia.')
    }
  }
  handleVideo(stream) {
    const { preview } = this.refs

    if(window.URL.createObjectURL){
      preview.src = window.URL.createObjectURL(stream)
    }else if (window.webkitURL) {
      preview.src = window.webkitURL.createObjectURL(stream)
    } else if (preview.mozSrcObject !== undefined) {
      preview.mozSrcObject = stream
    } else {
      preview.src = stream
    }

    const streamTrack = stream.getTracks()[0]
    this.stopCamera = streamTrack.stop.bind(streamTrack)

    preview.addEventListener('loadstart', this.handleLoadStart)
  }
  handleLoadStart(){
    const preview = this.refs.preview
    preview.play()
    if(this.props.interval){
      this._interval = setInterval(this.check, this.props.interval)
    }else if(!this.requestFrameId){
      this.check()
    }

    preview.removeEventListener('loadstart', this.handleLoadStart)
  }
  check() {
    const { interval, handleScan, legacyMode } = this.props
    const { preview, canvas, img } = this.refs
    let width = Math.floor(legacyMode ? img.naturalWidth : preview.videoWidth)
    let height = Math.floor(legacyMode ? img.naturalHeight : preview.videoHeight)

    if(legacyMode){
      const ratio = 1.2
      while ((width > height ? width : height) > 1000) {
        width = Math.floor(width / ratio)
        height = Math.floor(height / ratio)
      }
    }

    canvas.width = width
    canvas.height = height

    if(!interval && !legacyMode)
      this.requestFrameId = window.requestAnimationFrame(this.check)

    if (legacyMode || (preview && preview.readyState === preview.HAVE_ENOUGH_DATA)){
      const ctx = canvas.getContext('2d')
      ctx.drawImage(legacyMode ? img : preview, 0, 0, width, height)

      this.props.handleScan('height:' + height + ', width:'+width)

      const imageData = ctx.getImageData(0, 0, width, height)
      const decoded = jsQR.decodeQRFromImage(imageData.data, width, height)

      if(decoded)
        handleScan(decoded)
    }
  }
  initiateLegacyMode(){
    this.reader = new FileReader()

    this.reader.addEventListener('load', this.handleReaderLoad)

    this.refs.img.addEventListener('load', this.check, false)

    this.componentDidUpdate = undefined
  }
  handleInputChange(e){
    this.reader.readAsDataURL(e.target.files[0])
  }
  handleReaderLoad(e){
    this.refs.img.src = e.target.result
  }
  render(){
    const previewStyle = {
      display: 'block',
      objectFit: 'contain',
      ...this.props.previewStyle,
    }
    const canvasStyle = {
      display: 'none',
    }

    return (

        {this.props.legacyMode ? (

            <input style={this.props.inputStyle} type="file" accept="image/*" ref="input" onChange={this.handleInputChange}/>

        ) : (
          <video style={previewStyle} ref="preview"/>
        )}
        <canvas style={canvasStyle} ref="canvas"/>

    )
  }
}

Reader.defaultProps = {
  interval: null,
  previewStyle: {},
  inputStyle: {},
}
Reader.propTypes = {
  handleScan: PropTypes.func.isRequired,
  handleError: PropTypes.func.isRequired,
  interval: PropTypes.number,
  previewStyle: PropTypes.object,
  inputStyle: PropTypes.object,
  facingMode: PropTypes.string,
  legacyMode: PropTypes.bool,
}
<|endoftext|>


<commit_before>view = Backbone.View.extend();

view.prototype.events = {
    'click input[type=submit]': 'save',
    'change select[name=layer]': 'attach',
    'keyup input[name=template_location]': 'preview',
    'keyup textarea[name=template_teaser]': 'preview',
    'keyup textarea[name=template_full]': 'preview',
    'focus input[name=template_location]': 'preview',
    'focus textarea[name=template_teaser]': 'preview',
    'focus textarea[name=template_full]': 'preview'
};

view.prototype.initialize = function(options) {
    _(this).bindAll('render', 'save', 'attach', 'zoom', 'preview');
    this.render().attach();
};

view.prototype.preview = function(ev) {
    var target = $(ev.currentTarget);
    var format = target.attr('name').split('template_').pop();
    var formatter = _(target.val().replace(/\[([\w\d]+)\]/g, "<%=obj.$1%>")).template();
    var feature = this.datasource.get('features')[0];
    try {
        var preview = formatter(feature);
        target.siblings('.preview').html(preview);
    } catch(err) {
        target.siblings('.preview').html(err.toString());
    }
};

view.prototype.render = function() {
    this.$('.content').html(templates.Settings(this.model));
    this.$('.slider').slider({
        range: true,
        min:0,
        max:22,
        values:[this.model.get('minzoom'), this.model.get('maxzoom')],
        step:1,
        slide: this.zoom
    });

    // Focus name field for unnamed projects.
    if (!this.model.get('name')) this.$('input[type=text]:first').focus();
    return this;
};

view.prototype.zoom = function(ev, ui) {
    this.$('.minzoom').text(ui.values[0]);
    this.$('.maxzoom').text(ui.values[1]);
};

view.prototype.save = function() {
    var interactivity = this.$('select[name=layer]').val() ? {
        'layer': this.$('select[name=layer]').val(),
        'template_teaser': this.$('textarea[name=template_teaser]').val(),
        'template_full': this.$('textarea[name=template_full]').val(),
        'template_location': this.$('input[name=template_location]').val(),
    } : false;
    var attr = _({
        'name':          this.$('input[name=name]').val(),
        'description':   this.$('input[name=description]').val(),
        'attribution':   this.$('input[name=attribution]').val(),
        'version':       this.$('input[name=version]').val(),
        'format':        this.$('select[name=format]').val(),
        'minzoom':       parseInt(this.$('.slider').slider('values', 0)),
        'maxzoom':       parseInt(this.$('.slider').slider('values', 1)),
        'interactivity': interactivity,
        'legend':        this.$('textarea[name=legend]').val(),
        'bounds': [
            parseFloat(this.$('input[name=bounds_0]').val()),
            parseFloat(this.$('input[name=bounds_1]').val()),
            parseFloat(this.$('input[name=bounds_2]').val()),
            parseFloat(this.$('input[name=bounds_3]').val())
        ],
        'center': [
            parseFloat(this.$('input[name=center_0]').val()),
            parseFloat(this.$('input[name=center_1]').val()),
            parseInt(this.$('input[name=center_2]').val())
        ]
    }).reduce(function(memo, val, key) {
        if (val !== '') memo[key] = val;
        return memo;
    }, {});

    var error = function(m, e) { new views.Modal(e); };
    if (!this.model.set(attr, {error:error})) return false;

    this.model.save({}, {
        success: _(function(model) {
            this.model.trigger('save');
            this.$('.close').click();
        }).bind(this),
        error:error
    });
    return false;
};

view.prototype.attach = function() {
    var id = this.$('select[name=layer]').val();
    var layer = this.model.get('Layer').get(id);

    // If no layer is selected hide dependents and back out.
    if (!layer) {
        this.$('.dependent').hide();
        return;
    }

    var update = _(function(model) {
        var fields = _(model.get('fields')).keys();

        this.$('.tokens').html(_(fields).map(function(f) {
            return _('[<%=f%>]').template({f:f});
        }).join(' '));

        this.$('.dependent').show();
        $('#popup').removeClass('loading');
    }).bind(this);

    // Cache the datasource model to `this.datasource` so it can
    // be used to live render/preview the formatters.
    if (!this.datasource || this.datasource.id !== layer.get('id')) {
        $('#popup').addClass('loading');
        var attr = _(layer.get('Datasource')).chain()
            .clone()
            .extend({id: layer.get('id'), project: this.model.get('id')})
            .value();
        this.datasource = new models.Datasource(attr);
        this.datasource.fetchFeatures({
            success: update,
            error: function(model, err) { new views.Modal(err); }
        });
    } else {
        update(this.datasource);
    }
    if (!layer) return;
};

<commit_msg>Allow description, attribution, legend to be deleted.<commit_after>view = Backbone.View.extend();

view.prototype.events = {
    'click input[type=submit]': 'save',
    'change select[name=layer]': 'attach',
    'keyup input[name=template_location]': 'preview',
    'keyup textarea[name=template_teaser]': 'preview',
    'keyup textarea[name=template_full]': 'preview',
    'focus input[name=template_location]': 'preview',
    'focus textarea[name=template_teaser]': 'preview',
    'focus textarea[name=template_full]': 'preview'
};

view.prototype.initialize = function(options) {
    _(this).bindAll('render', 'save', 'attach', 'zoom', 'preview');
    this.render().attach();
};

view.prototype.preview = function(ev) {
    var target = $(ev.currentTarget);
    var format = target.attr('name').split('template_').pop();
    var formatter = _(target.val().replace(/\[([\w\d]+)\]/g, "<%=obj.$1%>")).template();
    var feature = this.datasource.get('features')[0];
    try {
        var preview = formatter(feature);
        target.siblings('.preview').html(preview);
    } catch(err) {
        target.siblings('.preview').html(err.toString());
    }
};

view.prototype.render = function() {
    this.$('.content').html(templates.Settings(this.model));
    this.$('.slider').slider({
        range: true,
        min:0,
        max:22,
        values:[this.model.get('minzoom'), this.model.get('maxzoom')],
        step:1,
        slide: this.zoom
    });

    // Focus name field for unnamed projects.
    if (!this.model.get('name')) this.$('input[type=text]:first').focus();
    return this;
};

view.prototype.zoom = function(ev, ui) {
    this.$('.minzoom').text(ui.values[0]);
    this.$('.maxzoom').text(ui.values[1]);
};

view.prototype.save = function() {
    var attr = _({
        'name':          this.$('input[name=name]').val(),
        'description':   this.$('input[name=description]').val(),
        'attribution':   this.$('input[name=attribution]').val(),
        'version':       this.$('input[name=version]').val(),
        'format':        this.$('select[name=format]').val(),
        'minzoom':       parseInt(this.$('.slider').slider('values', 0)),
        'maxzoom':       parseInt(this.$('.slider').slider('values', 1)),
        'interactivity': this.$('select[name=layer]').val() ?
            {
                'layer': this.$('select[name=layer]').val(),
                'template_teaser': this.$('textarea[name=template_teaser]').val(),
                'template_full': this.$('textarea[name=template_full]').val(),
                'template_location': this.$('input[name=template_location]').val(),
            } :
            false,
        'legend':        this.$('textarea[name=legend]').val(),
        'bounds': [
            parseFloat(this.$('input[name=bounds_0]').val()),
            parseFloat(this.$('input[name=bounds_1]').val()),
            parseFloat(this.$('input[name=bounds_2]').val()),
            parseFloat(this.$('input[name=bounds_3]').val())
        ],
        'center': [
            parseFloat(this.$('input[name=center_0]').val()),
            parseFloat(this.$('input[name=center_1]').val()),
            parseInt(this.$('input[name=center_2]').val())
        ]
    }).reduce(function(memo, val, key) {
        var allowEmpty = ['description', 'attribution', 'legend']
        if (val !== '' || _(allowEmpty).include(key)) memo[key] = val;
        return memo;
    }, {});

    var error = function(m, e) { new views.Modal(e); };
    if (!this.model.set(attr, {error:error})) return false;

    this.model.save({}, {
        success: _(function(model) {
            this.model.trigger('save');
            this.$('.close').click();
        }).bind(this),
        error:error
    });
    return false;
};

view.prototype.attach = function() {
    var id = this.$('select[name=layer]').val();
    var layer = this.model.get('Layer').get(id);

    // If no layer is selected hide dependents and back out.
    if (!layer) {
        this.$('.dependent').hide();
        return;
    }

    var update = _(function(model) {
        var fields = _(model.get('fields')).keys();

        this.$('.tokens').html(_(fields).map(function(f) {
            return _('[<%=f%>]').template({f:f});
        }).join(' '));

        this.$('.dependent').show();
        $('#popup').removeClass('loading');
    }).bind(this);

    // Cache the datasource model to `this.datasource` so it can
    // be used to live render/preview the formatters.
    if (!this.datasource || this.datasource.id !== layer.get('id')) {
        $('#popup').addClass('loading');
        var attr = _(layer.get('Datasource')).chain()
            .clone()
            .extend({id: layer.get('id'), project: this.model.get('id')})
            .value();
        this.datasource = new models.Datasource(attr);
        this.datasource.fetchFeatures({
            success: update,
            error: function(model, err) { new views.Modal(err); }
        });
    } else {
        update(this.datasource);
    }
    if (!layer) return;
};

<|endoftext|>


<commit_before>import '../styles/style.css';

// Models

function Driver(attributes) {
  this.ranking = attributes.ranking
  this.points = attributes.points
  this.nationality = attributes.nationality
  this.surname = attributes.surname
  this.name = attributes.name
  this.team = attributes.team
  this.teamPoints = attributes.teamPoints
  this.lastRace = attributes.lastRace
  this.wins = attributes.wins
  this.poles = attributes.poles
  this.bestPosition = attributes.bestPosition
  this.bestPositionTimes = attributes.bestPositionTimes
}

// Controllers

function getJSON(path, callback) {
  const httpRequest = new XMLHttpRequest();
  httpRequest.onload = function () {
    if (httpRequest.status >= 200 && httpRequest.status < 400) {
      const data = JSON.parse(httpRequest.responseText);
      if (callback) { callback(data); }
    }
  };
  httpRequest.open('GET', path, true)
  httpRequest.send()
}

function renderDrivers() {
  const driversListContainer = document.getElementById('drivers-list');

  getJSON('data.json', function (data){
    const drivers = data
      .drivers
      .map(attributes => new Driver(attributes));

    const driversRows = document.createDocumentFragment();
    let view;

    drivers.forEach( (driver, i) => {
      view = document.createElement('div');
      view.className = 'driver-row'
      view.id = `driver-${i}`
      view.innerHTML = DriverView(driver, i+1, matchFlags(driver.nationality))
      driversListContainer.appendChild(view)
    })
  })
}

function matchFlags(nationality) {
  const flags = {
    "Germany": "01",
    "Australia": "02",
    "Brazil": "03",
    "Spain": "04",
    "United Kingdom": "05"
  }
  return flags[nationality];
}

renderDrivers()

// Views

function DriverView(driver, i, flagNumber) {
  if (typeof driver.lastRace === 'undefined') {
    driver.lastRace = '---'
  }
  const view = `

        ${driver.ranking}°

Points${driver.points}

        ${driver.nationality}

${driver.surname} ${driver.name}

${driver.team} (${driver.teamPoints})

Last GP${driver.lastRace}°

Victories${driver.wins}

Poles${driver.poles}

Best Position${driver.bestPosition}°

  `
  return view
}
<commit_msg>Add sorting function by property<commit_after>import '../styles/style.css';

// Models

function Driver(attributes) {
  this.ranking = attributes.ranking
  this.points = attributes.points
  this.nationality = attributes.nationality
  this.surname = attributes.surname
  this.name = attributes.name
  this.team = attributes.team
  this.teamPoints = attributes.teamPoints
  this.lastRace = attributes.lastRace
  this.wins = attributes.wins
  this.poles = attributes.poles
  this.bestPosition = attributes.bestPosition
  this.bestPositionTimes = attributes.bestPositionTimes
}

// Controllers

function getJSON(path, callback) {
  const httpRequest = new XMLHttpRequest();
  httpRequest.onload = function () {
    if (httpRequest.status >= 200 && httpRequest.status < 400) {
      const data = JSON.parse(httpRequest.responseText);
      if (callback) { callback(data); }
    }
  };
  httpRequest.open('GET', path, true)
  httpRequest.send()
}

function renderDrivers() {
  const driversListContainer = document.getElementById('drivers-list');

  getJSON('data.json', function (data){
    const drivers = data
      .drivers
      .map(attributes => new Driver(attributes));

    const driversRows = document.createDocumentFragment();
    const filtersButtons = document.querySelectorAll('a.main-nav__button');
    let view;

    filtersButtons.forEach( (btn, i) => {
      filtersButtons[i].addEventListener('click', (e) => {
        sortDataByKey(drivers, filtersButtons[i].dataset.sort)
      })
    })

    drivers.forEach( (driver, i) => {
      view = document.createElement('div');
      view.className = 'driver-row'
      view.id = `driver-${i}`
      view.innerHTML = DriverView(driver, i+1, matchFlags(driver.nationality))
      driversListContainer.appendChild(view)
    })
  })
}

function matchFlags(nationality) {
  const flags = {
    "Germany": "01",
    "Australia": "02",
    "Brazil": "03",
    "Spain": "04",
    "United Kingdom": "05"
  }
  return flags[nationality];
}

function sortDataByKey (data, prop){
  return data.sort( (a, b) => (a[prop] > b[prop]) )
}

renderDrivers()

// Views

function DriverView(driver, i, flagNumber) {
  if (typeof driver.lastRace === 'undefined') {
    driver.lastRace = '---'
  }
  const view = `

        ${driver.ranking}°

Points${driver.points}

        ${driver.nationality}

${driver.surname} ${driver.name}

${driver.team} (${driver.teamPoints})

Last GP${driver.lastRace}°

Victories${driver.wins}

Poles${driver.poles}

Best Position${driver.bestPosition}°

  `
  return view
}
<|endoftext|>


<commit_before>/* informix cli using nodejs-db-informix */

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

/*
 * Connection configurations
 */
// var settings = JSON.parse(require('fs').readFileSync('./tests/db_conf.json','utf8'));
var settings = {
      "host": ""
    , "user": ""
    , "password": ""
    , "database": "sysmaster"
    , "charset": ""
    // , "port": ""
    // , "compress": ""
    // , "initCommand": ""
    // , "readTimeout": ""
    // , "reconnect": ""
    // , "socket": ""
    // , "sslVerifyServer": ""
    // , "timeout": ""
    // , "writeTimeout": ""
};

/*
 * Create a new Informix database bindings. Setup event callbacks. Connect to
 * the database.
 * c - connection
 */
function connect(settings) {
    if (!settings || typeof(settings) !== 'object') {
        throw new Error("No settings provided");
    }

    /*
     * Create an Informix database nodejs object
     */
    var bindings = require("../nodejs-db-informix");
    console.log(bindings);

    var c = new bindings.Informix(settings);

    c.on('error', function(error) {
        console.log("Error: ");
        console.log(error);
    }).on('ready', function(server) {
        console.log("Connection ready to ");
        console.log(server);
    }).connect(function(err) {
        if (err) {
            throw new Error('Could not connect to DB');
        }
        console.log('Connected to db with ');
        console.log(settings);
        console.log("isConnected() == " + c.isConnected());

        this
        .on('each', function(e, idx, more) {
            console.log('each');
            console.log(arguments);
        })
        .on('success', function() {
            console.log('success');
            console.log(arguments);
        });

        /*
        var rs = this.query("select first 10 * from systables", function(s,r) {
            console.log(s);
            console.log(r);
        }).execute();
        */

        /*
        var rs = this
                .query(
                      "SELECT FIRST 10 * FROM systables"
                    , []
                    , function (status, results) {
                        console.log('CALLBACK:');
                        // console.log(arguments);
                        console.log("status:" + status);
                        console.log(results);
                    }
                    , {
                        start: function(q) {
                            console.log('Query:');
                            console.log(q);
                        }
                        , finish: function(f) {
                            console.log('Finish:');
                            console.log(f);
                        }
                        , async: true
                        , cast: true
                    }
                )
                .execute();
        */

        /*
        var rs = this
                .query(
                      ""
                    , []
                    , function (status, results) {
                        console.log('CALLBACK:');
                        // console.log(arguments);
                        console.log("status:" + status);
                        console.log(results);
                    }
                    , {
                        start: function(q) {
                            console.log('Query:');
                            console.log(q);
                        }
                        , finish: function(f) {
                            console.log('Finish:');
                            console.log(f);
                        }
                        , async: true
                        , cast: true
                    }
                )
                .select("*")
                .first(10)
                .from("systables", false)
                .execute();
        */

    });

    return c;
}

function execQuery(conn,qry) {
    if (!conn || conn == undefined || conn == null) {
        throw Error("_main: connection is not valid");
    }
    var rs = conn
        .query(
              qry
            , []
            , function (status, results) {
                console.log('CALLBACK:');
                // console.log(arguments);
                console.log("status:" + status);
                console.log(results);
            }
            , {
                start: function(q) {
                    console.log('Query:');
                    console.log(q);
                }
                , finish: function(f) {
                    console.log('Finish:');
                    console.log(f);
                }
                , async: true
                , cast: true
            }
        )
        .execute();

    return rs;
}

function _main () {
    var conn = connect(settings);

    if (!conn || conn == undefined || conn == null) {
        throw Error("_main: connection is not valid");
    }

    console.log('connection:');
    console.log(conn);

    rl.setPrompt('inf> ');
    rl.prompt();

    rl.on('line', function(line) {
        var cmd = line.trim();

        if (cmd == '' || cmd == undefined || cmd == null) {
            rl.prompt();
            return;
        }

        var c_reg = /^\s*connect\s+(\w+)/;

        if (c_reg.test(cmd)) {
            var m = cmd.match(c_reg);
            var db = m[1];
            if (db == null || db == undefined || db.trim() == '') {
                console.log("Invalid command: " + cmd);
                rl.prompt();
                return;
            }

            conn.disconnect();
            settings.database = db;
            conn = connect(settings);

        } else {
            execQuery(conn, cmd);
        }

        rl.prompt();

    }).on('close', function() {
        console.log('Exit.');
    });
}

_main();
<commit_msg>use node env<commit_after>#!/usr/bin/env node
/* informix cli using nodejs-db-informix */

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

/*
 * Connection configurations
 */
// var settings = JSON.parse(require('fs').readFileSync('./tests/db_conf.json','utf8'));
var settings = {
      "host": ""
    , "user": ""
    , "password": ""
    , "database": "sysmaster"
    , "charset": ""
    // , "port": ""
    // , "compress": ""
    // , "initCommand": ""
    // , "readTimeout": ""
    // , "reconnect": ""
    // , "socket": ""
    // , "sslVerifyServer": ""
    // , "timeout": ""
    // , "writeTimeout": ""
};

/*
 * Create a new Informix database bindings. Setup event callbacks. Connect to
 * the database.
 * c - connection
 */
function connect(settings) {
    if (!settings || typeof(settings) !== 'object') {
        throw new Error("No settings provided");
    }

    /*
     * Create an Informix database nodejs object
     */
    var bindings = require("../nodejs-db-informix");
    console.log(bindings);

    var c = new bindings.Informix(settings);

    c.on('error', function(error) {
        console.log("Error: ");
        console.log(error);
    }).on('ready', function(server) {
        console.log("Connection ready to ");
        console.log(server);
    }).connect(function(err) {
        if (err) {
            throw new Error('Could not connect to DB');
        }
        console.log('Connected to db with ');
        console.log(settings);
        console.log("isConnected() == " + c.isConnected());

        this
        .on('each', function(e, idx, more) {
            console.log('each');
            console.log(arguments);
        })
        .on('success', function() {
            console.log('success');
            console.log(arguments);
        });

        /*
        var rs = this.query("select first 10 * from systables", function(s,r) {
            console.log(s);
            console.log(r);
        }).execute();
        */

        /*
        var rs = this
                .query(
                      "SELECT FIRST 10 * FROM systables"
                    , []
                    , function (status, results) {
                        console.log('CALLBACK:');
                        // console.log(arguments);
                        console.log("status:" + status);
                        console.log(results);
                    }
                    , {
                        start: function(q) {
                            console.log('Query:');
                            console.log(q);
                        }
                        , finish: function(f) {
                            console.log('Finish:');
                            console.log(f);
                        }
                        , async: true
                        , cast: true
                    }
                )
                .execute();
        */

        /*
        var rs = this
                .query(
                      ""
                    , []
                    , function (status, results) {
                        console.log('CALLBACK:');
                        // console.log(arguments);
                        console.log("status:" + status);
                        console.log(results);
                    }
                    , {
                        start: function(q) {
                            console.log('Query:');
                            console.log(q);
                        }
                        , finish: function(f) {
                            console.log('Finish:');
                            console.log(f);
                        }
                        , async: true
                        , cast: true
                    }
                )
                .select("*")
                .first(10)
                .from("systables", false)
                .execute();
        */

    });

    return c;
}

function execQuery(conn,qry) {
    if (!conn || conn == undefined || conn == null) {
        throw Error("_main: connection is not valid");
    }
    var rs = conn
        .query(
              qry
            , []
            , function (status, results) {
                console.log('CALLBACK:');
                // console.log(arguments);
                console.log("status:" + status);
                console.log(results);
            }
            , {
                start: function(q) {
                    console.log('Query:');
                    console.log(q);
                }
                , finish: function(f) {
                    console.log('Finish:');
                    console.log(f);
                }
                , async: true
                , cast: true
            }
        )
        .execute();

    return rs;
}

function _main () {
    var conn = connect(settings);

    if (!conn || conn == undefined || conn == null) {
        throw Error("_main: connection is not valid");
    }

    console.log('connection:');
    console.log(conn);

    rl.setPrompt('inf> ');
    rl.prompt();

    rl.on('line', function(line) {
        var cmd = line.trim();

        if (cmd == '' || cmd == undefined || cmd == null) {
            rl.prompt();
            return;
        }

        var c_reg = /^\s*connect\s+(\w+)/;

        if (c_reg.test(cmd)) {
            var m = cmd.match(c_reg);
            var db = m[1];
            if (db == null || db == undefined || db.trim() == '') {
                console.log("Invalid command: " + cmd);
                rl.prompt();
                return;
            }

            conn.disconnect();
            settings.database = db;
            conn = connect(settings);

        } else {
            execQuery(conn, cmd);
        }

        rl.prompt();

    }).on('close', function() {
        console.log('Exit.');
    });
}

_main();
<|endoftext|>


<commit_before>require('babel-core/register');
require('babel-polyfill');
import bcrypt from 'bcrypt-nodejs';
export const getSalt = salt_work_factor =>
  new Promise((resolve, reject) => {
    bcrypt.genSalt(salt_work_factor, (err, salt) => {
      if (err) reject(err);
      resolve(salt);
    });
  });

export const encrypt = value =>
  new Promise(async (resolve, reject) => {
    const salt = await getSalt(4);
    bcrypt.hash(value, salt, null, (err, hash) => {
      if (err) reject(err);
      resolve(hash);
    });
  });

export const compare = (value, hash) =>
  new Promise((resolve, reject) => {
    bcrypt.compare(value, hash, (err, isValid) => {
      if (err) reject(err);
      resolve(isValid);
    });
  });
<commit_msg>added readFile: promisify readFile of core fs module<commit_after>require('babel-core/register');
require('babel-polyfill');
const fs = require('fs');

import bcrypt from 'bcrypt-nodejs';
export const getSalt = salt_work_factor =>
  new Promise((resolve, reject) => {
    bcrypt.genSalt(salt_work_factor, (err, salt) => {
      if (err) reject(err);
      resolve(salt);
    });
  });

export const encrypt = value =>
  new Promise(async (resolve, reject) => {
    const salt = await getSalt(4);
    bcrypt.hash(value, salt, null, (err, hash) => {
      if (err) reject(err);
      resolve(hash);
    });
  });

export const compare = (value, hash) =>
  new Promise((resolve, reject) => {
    bcrypt.compare(value, hash, (err, isValid) => {
      if (err) reject(err);
      resolve(isValid);
    });
  });

export const readFile = (path) => new Promise((resolve, reject) =>{
	fs.readFile(path, 'utf-8', (err, data) =>{
		if (err) reject(err);
		resolve(data);
	})
});
<|endoftext|>


<commit_before>"use strict";

const fs = require('fs');
const xml2js = require('xml2js');

function increment(versionString) {
  const regex = /(.*\.)([0-9]+)$/;
  var match = regex.exec(versionString);
  if(!match) return undefined;
  return match[1] + (parseInt(match[2]) + 1);
}

function incrementVersion(manifestString) {
  return new Promise((resolve,reject) => {
    // Got file contents - now parse as XML
    xml2js.parseString(manifestString, {explicitArray:false}, function(err,data) {
      if(err) {
        reject({status:"xmlerror",details:err});
        return;
      }

      // Got XML as JSON object - find version and update
      if(!data) {
        reject({status:"xmlerror",details:"No XML content found"});
      } else if(!data.Package) {
        reject({status:"formaterror",details:"Missing Package node"});
      } else if(!data.Package.Identity) {
        reject({status:"formaterror",details:"Missing Identity node"});
      } else if(!data.Package.Identity['$'] || !data.Package.Identity['$'].Version) {
        reject({status:"formaterror",details:"Missing Version attribute node"});
      } else {
        // Data is valid - now increment version
        var newVer = increment(data.Package.Identity['$'].Version);
        if(!newVer) {
          reject({status:"versionerror",details:"Failed to match version number pattern"});
        } else {
          data.Package.Identity['$'].Version = newVer;

          // Return updated XML
          var builder = new xml2js.Builder();
          var xml = builder.buildObject(data);
          resolve({version:newVer, manifest:xml});
        }
      }
    });
  });
}

function incrementVersionFile(manifestPath,overwriteOriginal) {
  return new Promise((resolve,reject) => {
    fs.readFile(manifestPath,'utf8',function (err,res) {
      if(err) {
        reject({status:"readerror",details:err});
      } else {
        incrementVersion(res)
          .then(r => {
            if(overwriteOriginal) {
              console.log(overwriteOriginal);
              // Need to write out the new manifest over the old one
              fs.writeFile(manifestPath,r.manifest,"utf8",function(err) {
                if(err) {
                  reject({status:"writeerror",details:"Unable to write new manifest"});
                } else {
                  resolve(r);
                }
              });
            } else {
              resolve(r);
            }
          })
          .catch(e => { reject(e); });
      }
    });
  });
}

module.exports = {
  incrementVersion,
  incrementVersionFile
};<commit_msg>Remove debugging log.<commit_after>"use strict";

const fs = require('fs');
const xml2js = require('xml2js');

function increment(versionString) {
  const regex = /(.*\.)([0-9]+)$/;
  var match = regex.exec(versionString);
  if(!match) return undefined;
  return match[1] + (parseInt(match[2]) + 1);
}

function incrementVersion(manifestString) {
  return new Promise((resolve,reject) => {
    // Got file contents - now parse as XML
    xml2js.parseString(manifestString, {explicitArray:false}, function(err,data) {
      if(err) {
        reject({status:"xmlerror",details:err});
        return;
      }

      // Got XML as JSON object - find version and update
      if(!data) {
        reject({status:"xmlerror",details:"No XML content found"});
      } else if(!data.Package) {
        reject({status:"formaterror",details:"Missing Package node"});
      } else if(!data.Package.Identity) {
        reject({status:"formaterror",details:"Missing Identity node"});
      } else if(!data.Package.Identity['$'] || !data.Package.Identity['$'].Version) {
        reject({status:"formaterror",details:"Missing Version attribute node"});
      } else {
        // Data is valid - now increment version
        var newVer = increment(data.Package.Identity['$'].Version);
        if(!newVer) {
          reject({status:"versionerror",details:"Failed to match version number pattern"});
        } else {
          data.Package.Identity['$'].Version = newVer;

          // Return updated XML
          var builder = new xml2js.Builder();
          var xml = builder.buildObject(data);
          resolve({version:newVer, manifest:xml});
        }
      }
    });
  });
}

function incrementVersionFile(manifestPath,overwriteOriginal) {
  return new Promise((resolve,reject) => {
    fs.readFile(manifestPath,'utf8',function (err,res) {
      if(err) {
        reject({status:"readerror",details:err});
      } else {
        incrementVersion(res)
          .then(r => {
            if(overwriteOriginal) {
              // Need to write out the new manifest over the old one
              fs.writeFile(manifestPath,r.manifest,"utf8",function(err) {
                if(err) {
                  reject({status:"writeerror",details:"Unable to write new manifest"});
                } else {
                  resolve(r);
                }
              });
            } else {
              resolve(r);
            }
          })
          .catch(e => { reject(e); });
      }
    });
  });
}

module.exports = {
  incrementVersion,
  incrementVersionFile
};<|endoftext|>