<commit_before>'use babel';

/* @flow */
import Promise from 'bluebird';
import { existsSync, readFile, unlink } from 'fs';
import { basename, dirname, join, resolve as pathResolve } from 'path';
import { EOL, tmpdir } from 'os';
import { BufferedProcess } from 'atom';
import { parse as babylonParse } from 'jest-editor-support';
import { parse as typescriptParse } from 'jest-test-typescript-parser';
import type { TextEditor } from 'atom';

const ERROR_TEXT = 'Error: ';
let shouldUpdateSnapshot = false;
let isSnapshotNotificationActive = false;

type assertionResult = {
  status: 'passed'|'failed'|'skipped'|'unknown',
  title: string,
  name: string,
  failureMessages: Array<string>
};

type itBlock = {
  file: string,
  name: string,
  start:{
    line: number,
    column: number
  },
  end:{
    line: number,
    column: number
  }
};

type TestState = 'passed'|'failed'|'skipped'|'unknown';

type message = {
  state: TestState,
  title: string,
  error: { name: string, message: string },
  duration?: number,
  lineNumber: number,
  filePath: string,
};

const readFileAsync = Promise.promisify(readFile);
const unlinkAsync = Promise.promisify(unlink);

export function convertPathToPattern(path :string) :string {
  if (process.platform.match(/^win/)) {
    path = path.replace(/\\/g, '\\\\');
  }
  return path;
}

export function removeBadArgs(args :?Array<string>) {
  if (!args) {
    return [];
  }

  const prohibitedArgs = ['--json', '--outputFile', '--watch', '--watchAll', '--watchman'];
  const clearArgs = [];
  args.forEach((arg) => {
    const index = prohibitedArgs.indexOf(arg);
    if (index === -1) {
      clearArgs.push(arg);
    }
  });
  return clearArgs;
}

export function getJestError(result :assertionResult) :string {
  let errorMessage = '';
  if (result && result.failureMessages && result.failureMessages.length > 0) {
    const content = result.failureMessages[0];
    const messageMatch = content.match(/(^(.|\n)*?(?=\n\s*at\s.*\:\d*\:\d*))/);
    errorMessage = messageMatch ? messageMatch[0] : 'Error';
    if (errorMessage.startsWith(ERROR_TEXT)) {
      errorMessage = errorMessage.substr(ERROR_TEXT.length);
    }
  }
  return errorMessage;
}

export function getFormattedTesterMessage(state :TestState,
  title :string,
  errorMessage :string,
  duration :number,
  lineNumber :number,
  filePath :string) :message {
  return {
    state,
    title,
    error: {
      name: '',
      message: errorMessage,
    },
    duration,
    lineNumber,
    filePath,
  };
}

export function getMessagesFromAssertionResults(textEditor :TextEditor,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(assertionResults, (messages, testResult) =>
    new Promise((resolve) => {
      textEditor.scan(new RegExp(testResult.title.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')),
      (scanResult) => {
        if (testResult.status === 'pending') {
          testResult.status = 'skipped';
        }
        const errorMessage = getJestError(testResult);
        const state = testResult.status;
        const title = testResult.title;
        const lineNumber = scanResult.row;
        messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
      });
      resolve(messages);
    }), []);
}

export function getMessagesFromTestLocations(textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(testLocations, (messages, testLocation) => {
    const testResult = assertionResults.find(ar => ar.title === testLocation.name);
    if (assertionResults && assertionResults.length > 0 && testResult) {
      if (testResult.status === 'pending') {
        testResult.status = 'skipped';
      }
      const errorMessage = getJestError(testResult);
      const state = testResult.status;
      const title = testResult.title || '';
      const lineNumber = testLocation.start.line - 1;
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    } else {
      const state = 'unknown';
      const title = testLocation.name || '';
      const lineNumber = testLocation.start.line - 1;
      const errorMessage = '';
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    }
    return messages;
  }, []);
}

export function getMessagesFromTestResults(testResults :Array<Object>) {
  return Promise.map(testResults, testResult =>
    Promise.map(testResult.assertionResults, (result) => {
      if (result.status === 'pending') {
        result.status = 'skipped';
      }
      const errorMessage = getJestError(result);
      const state = result.status;
      const title = result.title;
      const lineNumber = 0;
      const duration = (testResult.endTime || 0) - (testResult.startTime || 0);
      return getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, testResult.name);
    }))
    .reduce((messages, result) => result.concat(messages), []);
}

export async function parseReporterOutput(data :string,
  filePath :string,
  textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  output : string) :Promise<{messages: Array<message>, output: string}> {
  let messages = [];
  let dataJSON;
  try {
    dataJSON = await JSON.parse(data);
  } catch (error) {
    atom.notifications.addError('Tester Jest: Could not parse data to JSON.');
  }
  let duration = 0;
  if (dataJSON && dataJSON.testResults && dataJSON.testResults.length > 0) {
    duration = (dataJSON.testResults[0].endTime || 0) - (dataJSON.testResults[0].startTime || 0);
    if (filePath && textEditor) {
      const assertionResults = dataJSON.testResults[0].assertionResults;
      if (testLocations && testLocations.length > 0) {
        messages = await getMessagesFromTestLocations(textEditor, testLocations, assertionResults, duration);
      } else if (assertionResults) {
        messages = await getMessagesFromAssertionResults(textEditor, assertionResults, duration);
      }
    } else {
      // Project test
      messages = await getMessagesFromTestResults(dataJSON.testResults);
    }
  }
  if (!messages.length) {
    messages.push(getFormattedTesterMessage('unknown', 'No results', output, duration, 0, filePath));
  }
  return { messages, output };
}

export async function getTestLocations(filePath :string) :Promise<?Array<itBlock>> {
  if (!filePath) {
    return Promise.resolve(null);
  }
  const isTypeScript = filePath.match(/.(ts|tsx)$/);
  const parser = isTypeScript ? typescriptParse : babylonParse;
  try {
    const parseResults :{itBlocks:Array<itBlock>} = await parser(filePath);
    return parseResults.itBlocks;
  } catch (e) {
    console.warn('Tester Jest: Failed to parse with babel.', e);
  }
}

export function run(textEditor :?TextEditor, additionalArgs :?string) {
  return new Promise((resolve) => {
    let processOutput = `\u001b[1mTester Jest\u001b[0m${EOL}`;
    const filePath = textEditor ? textEditor.getPath() : '';
    const projectPath = filePath ? atom.project.relativizePath(filePath)[0] : atom.project.getPaths()[0];

    let cwd = projectPath;
    if (!(cwd)) {
      cwd = dirname(filePath);
    }
    const jsonOutputFilePath = join(tmpdir(),
      `tester-jest_${filePath ? basename(filePath) : basename(projectPath)}.json`);

    const userConfigArgs = removeBadArgs(atom.config.get('tester-jest.args'));
    const additionalArgsArray = (additionalArgs && additionalArgs.trim()) ?
      removeBadArgs(additionalArgs.trim().split(' ')) : [];

    const belowEighteen = atom.config.get('tester-jest.jestMajorVersion') < 18;
    const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile';
    const defaultArgs = ['--json', outputArg, jsonOutputFilePath];
    if (filePath) {
      defaultArgs.push(convertPathToPattern(filePath));
    }
    if (shouldUpdateSnapshot) {
      defaultArgs.push('--updateSnapshot');
    }
    let args = userConfigArgs.concat(additionalArgsArray, defaultArgs);
    const env = Object.create(process.env);
    // Jest NODE_ENV default is 'test'
    // https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L13
    env.NODE_ENV = atom.config.get('tester-jest.nodeEnv');
    // To use our own commands in create-react, we need to tell the command that
    // we're in a CI environment, or it will always append --watch
    env.CI = atom.config.get('tester-jest.ciEnv');
    // set NODE_PATH otherwise will set atom own path
    // https://github.com/atom/atom/blob/master/src/initialize-application-window.coffee#L71
    env.NODE_PATH = cwd;
    const options = { cwd, env };
    let jestBinary = atom.config.get('tester-jest.binaryPath');
    let command = '';
    if (jestBinary) {
      const runtimeExecutable = jestBinary;
      const parameters = runtimeExecutable.split(' ');
      command = parameters.shift();
      args = parameters.concat(args);
    } else {
      const jestBinaryProject = pathResolve(cwd, './node_modules/.bin/jest');
      jestBinary = existsSync(jestBinaryProject) ? jestBinaryProject : 'jest';
      command = jestBinary;
    }
    processOutput += `\u001b[1mcommand:\u001b[0m ${command} ${args.join(' ')}${EOL}`;
    processOutput += `\u001b[1mcwd:\u001b[0m ${cwd}${EOL}`;
    const stdout = (data) => {
      if (!data.startsWith('Test results written to:')) {
        processOutput += data;
      }
    };
    const stderr = data => processOutput += data;
    const exit = async () => {
      this.bufferedProcess = null;
      shouldUpdateSnapshot = false;
      try {
        const testLocations = await getTestLocations(filePath);
        const jestJsonResults = await readFileAsync(jsonOutputFilePath, 'utf8');
        await unlinkAsync(jsonOutputFilePath);
        resolve(await parseReporterOutput(jestJsonResults, filePath, textEditor, testLocations, processOutput));
        if (!isSnapshotNotificationActive &&
          processOutput.includes('Inspect your code changes or re-run with `-u` to update them.')) {
          isSnapshotNotificationActive = true;
          const notification = atom.notifications.addInfo('Tester Jest', {
            detail: 'Do you want update the snapshot?',
            icon: 'beaker',
            dismissable: true,
            buttons: [
              {
                text: 'Yes',
                onDidClick: () => {
                  shouldUpdateSnapshot = true;
                  atom.commands.dispatch(atom.views.getView(atom.workspace.getActivePaneItem()), 'tester:test-last');
                  isSnapshotNotificationActive = false;
                  notification.dismiss();
                },
              },
              {
                text: 'No',
                onDidClick: () => {
                  shouldUpdateSnapshot = false;
                  isSnapshotNotificationActive = false;
                  notification.dismiss();
                },
              },
            ],
          });
        }
      } catch (error) {
        processOutput += error.toString();
        resolve({
          messages: getFormattedTesterMessage('unknown', 'No results', error, 0, 0, filePath),
          output: processOutput,
        });
      }
    };
    this.bufferedProcess = new BufferedProcess({ command, args, options, stdout, stderr, exit });

    this.bufferedProcess.onWillThrowError(() => {
      const error = 'Tester is unable to locate the jest command. Please ensure process.env.PATH can access jest.';
      atom.notifications.addError(error);
    });
  });
}

export function stop() {
  if (this.bufferedProcess) {
    this.bufferedProcess.kill();
    this.bufferedProcess = null;
  }
}
<commit_msg>fix windows path<commit_after>'use babel';

/* @flow */
import Promise from 'bluebird';
import { existsSync, readFile, unlink } from 'fs';
import { basename, dirname, join, resolve as pathResolve } from 'path';
import { EOL, tmpdir } from 'os';
import { BufferedProcess } from 'atom';
import { parse as babylonParse } from 'jest-editor-support';
import { parse as typescriptParse } from 'jest-test-typescript-parser';
import type { TextEditor } from 'atom';

const ERROR_TEXT = 'Error: ';
let shouldUpdateSnapshot = false;
let isSnapshotNotificationActive = false;

type assertionResult = {
  status: 'passed'|'failed'|'skipped'|'unknown',
  title: string,
  name: string,
  failureMessages: Array<string>
};

type itBlock = {
  file: string,
  name: string,
  start:{
    line: number,
    column: number
  },
  end:{
    line: number,
    column: number
  }
};

type TestState = 'passed'|'failed'|'skipped'|'unknown';

type message = {
  state: TestState,
  title: string,
  error: { name: string, message: string },
  duration?: number,
  lineNumber: number,
  filePath: string,
};

const readFileAsync = Promise.promisify(readFile);
const unlinkAsync = Promise.promisify(unlink);

export function convertPathToPattern(path :string) :string {
  if (process.platform.match(/^win/)) {
    return path.replace(/\\/g, '\\\\');
  }
  return path;
}

export function removeBadArgs(args :?Array<string>) {
  if (!args) {
    return [];
  }

  const prohibitedArgs = ['--json', '--outputFile', '--watch', '--watchAll', '--watchman'];
  const clearArgs = [];
  args.forEach((arg) => {
    const index = prohibitedArgs.indexOf(arg);
    if (index === -1) {
      clearArgs.push(arg);
    }
  });
  return clearArgs;
}

export function getJestError(result :assertionResult) :string {
  let errorMessage = '';
  if (result && result.failureMessages && result.failureMessages.length > 0) {
    const content = result.failureMessages[0];
    const messageMatch = content.match(/(^(.|\n)*?(?=\n\s*at\s.*\:\d*\:\d*))/);
    errorMessage = messageMatch ? messageMatch[0] : 'Error';
    if (errorMessage.startsWith(ERROR_TEXT)) {
      errorMessage = errorMessage.substr(ERROR_TEXT.length);
    }
  }
  return errorMessage;
}

export function getFormattedTesterMessage(state :TestState,
  title :string,
  errorMessage :string,
  duration :number,
  lineNumber :number,
  filePath :string) :message {
  return {
    state,
    title,
    error: {
      name: '',
      message: errorMessage,
    },
    duration,
    lineNumber,
    filePath,
  };
}

export function getMessagesFromAssertionResults(textEditor :TextEditor,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(assertionResults, (messages, testResult) =>
    new Promise((resolve) => {
      textEditor.scan(new RegExp(testResult.title.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')),
      (scanResult) => {
        if (testResult.status === 'pending') {
          testResult.status = 'skipped';
        }
        const errorMessage = getJestError(testResult);
        const state = testResult.status;
        const title = testResult.title;
        const lineNumber = scanResult.row;
        messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
      });
      resolve(messages);
    }), []);
}

export function getMessagesFromTestLocations(textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(testLocations, (messages, testLocation) => {
    const testResult = assertionResults.find(ar => ar.title === testLocation.name);
    if (assertionResults && assertionResults.length > 0 && testResult) {
      if (testResult.status === 'pending') {
        testResult.status = 'skipped';
      }
      const errorMessage = getJestError(testResult);
      const state = testResult.status;
      const title = testResult.title || '';
      const lineNumber = testLocation.start.line - 1;
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    } else {
      const state = 'unknown';
      const title = testLocation.name || '';
      const lineNumber = testLocation.start.line - 1;
      const errorMessage = '';
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    }
    return messages;
  }, []);
}

export function getMessagesFromTestResults(testResults :Array<Object>) {
  return Promise.map(testResults, testResult =>
    Promise.map(testResult.assertionResults, (result) => {
      if (result.status === 'pending') {
        result.status = 'skipped';
      }
      const errorMessage = getJestError(result);
      const state = result.status;
      const title = result.title;
      const lineNumber = 0;
      const duration = (testResult.endTime || 0) - (testResult.startTime || 0);
      return getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, testResult.name);
    }))
    .reduce((messages, result) => result.concat(messages), []);
}

export async function parseReporterOutput(data :string,
  filePath :string,
  textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  output : string) :Promise<{messages: Array<message>, output: string}> {
  let messages = [];
  let dataJSON;
  try {
    dataJSON = await JSON.parse(data);
  } catch (error) {
    atom.notifications.addError('Tester Jest: Could not parse data to JSON.');
  }
  let duration = 0;
  if (dataJSON && dataJSON.testResults && dataJSON.testResults.length > 0) {
    duration = (dataJSON.testResults[0].endTime || 0) - (dataJSON.testResults[0].startTime || 0);
    if (filePath && textEditor) {
      const assertionResults = dataJSON.testResults[0].assertionResults;
      if (testLocations && testLocations.length > 0) {
        messages = await getMessagesFromTestLocations(textEditor, testLocations, assertionResults, duration);
      } else if (assertionResults) {
        messages = await getMessagesFromAssertionResults(textEditor, assertionResults, duration);
      }
    } else {
      // Project test
      messages = await getMessagesFromTestResults(dataJSON.testResults);
    }
  }
  if (!messages.length) {
    messages.push(getFormattedTesterMessage('unknown', 'No results', output, duration, 0, filePath));
  }
  return { messages, output };
}

export async function getTestLocations(filePath :string) :Promise<?Array<itBlock>> {
  if (!filePath) {
    return Promise.resolve(null);
  }
  const isTypeScript = filePath.match(/.(ts|tsx)$/);
  const parser = isTypeScript ? typescriptParse : babylonParse;
  try {
    const parseResults :{itBlocks:Array<itBlock>} = await parser(filePath);
    return parseResults.itBlocks;
  } catch (e) {
    console.warn('Tester Jest: Failed to parse with babel.', e);
  }
}

export function run(textEditor :?TextEditor, additionalArgs :?string) {
  return new Promise((resolve) => {
    let processOutput = `\u001b[1mTester Jest\u001b[0m${EOL}`;
    const filePath = textEditor ? textEditor.getPath() : '';
    const projectPath = filePath ? atom.project.relativizePath(filePath)[0] : atom.project.getPaths()[0];

    let cwd = projectPath;
    if (!(cwd)) {
      cwd = dirname(filePath);
    }
    const jsonOutputFilePath = join(tmpdir(),
      `tester-jest_${filePath ? basename(filePath) : basename(projectPath)}.json`);

    const userConfigArgs = removeBadArgs(atom.config.get('tester-jest.args'));
    const additionalArgsArray = (additionalArgs && additionalArgs.trim()) ?
      removeBadArgs(additionalArgs.trim().split(' ')) : [];

    const belowEighteen = atom.config.get('tester-jest.jestMajorVersion') < 18;
    const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile';
    const defaultArgs = ['--json', outputArg, jsonOutputFilePath];
    if (filePath) {
      defaultArgs.push(convertPathToPattern(filePath));
    }
    if (shouldUpdateSnapshot) {
      defaultArgs.push('--updateSnapshot');
    }
    let args = userConfigArgs.concat(additionalArgsArray, defaultArgs);
    const env = Object.create(process.env);
    // Jest NODE_ENV default is 'test'
    // https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L13
    env.NODE_ENV = atom.config.get('tester-jest.nodeEnv');
    // To use our own commands in create-react, we need to tell the command that
    // we're in a CI environment, or it will always append --watch
    env.CI = atom.config.get('tester-jest.ciEnv');
    // set NODE_PATH otherwise will set atom own path
    // https://github.com/atom/atom/blob/master/src/initialize-application-window.coffee#L71
    env.NODE_PATH = cwd;
    const options = { cwd, env };
    let jestBinary = atom.config.get('tester-jest.binaryPath');
    let command = '';
    if (jestBinary) {
      const runtimeExecutable = jestBinary;
      const parameters = runtimeExecutable.split(' ');
      command = parameters.shift();
      args = parameters.concat(args);
    } else {
      const jestBinaryProject = pathResolve(cwd, './node_modules/.bin/jest');
      jestBinary = existsSync(jestBinaryProject) ? jestBinaryProject : 'jest';
      command = jestBinary;
    }
    processOutput += `\u001b[1mcommand:\u001b[0m ${command} ${args.join(' ')}${EOL}`;
    processOutput += `\u001b[1mcwd:\u001b[0m ${cwd}${EOL}`;
    const stdout = (data) => {
      if (!data.startsWith('Test results written to:')) {
        processOutput += data;
      }
    };
    const stderr = data => processOutput += data;
    const exit = async () => {
      this.bufferedProcess = null;
      shouldUpdateSnapshot = false;
      try {
        const testLocations = await getTestLocations(filePath);
        const jestJsonResults = await readFileAsync(jsonOutputFilePath, 'utf8');
        await unlinkAsync(jsonOutputFilePath);
        resolve(await parseReporterOutput(jestJsonResults, filePath, textEditor, testLocations, processOutput));
        if (!isSnapshotNotificationActive &&
          processOutput.includes('Inspect your code changes or re-run with `-u` to update them.')) {
          isSnapshotNotificationActive = true;
          const notification = atom.notifications.addInfo('Tester Jest', {
            detail: 'Do you want update the snapshot?',
            icon: 'beaker',
            dismissable: true,
            buttons: [
              {
                text: 'Yes',
                onDidClick: () => {
                  shouldUpdateSnapshot = true;
                  atom.commands.dispatch(atom.views.getView(atom.workspace.getActivePaneItem()), 'tester:test-last');
                  isSnapshotNotificationActive = false;
                  notification.dismiss();
                },
              },
              {
                text: 'No',
                onDidClick: () => {
                  shouldUpdateSnapshot = false;
                  isSnapshotNotificationActive = false;
                  notification.dismiss();
                },
              },
            ],
          });
        }
      } catch (error) {
        processOutput += error.toString();
        resolve({
          messages: getFormattedTesterMessage('unknown', 'No results', error, 0, 0, filePath),
          output: processOutput,
        });
      }
    };
    this.bufferedProcess = new BufferedProcess({ command, args, options, stdout, stderr, exit });

    this.bufferedProcess.onWillThrowError(() => {
      const error = 'Tester is unable to locate the jest command. Please ensure process.env.PATH can access jest.';
      atom.notifications.addError(error);
    });
  });
}

export function stop() {
  if (this.bufferedProcess) {
    this.bufferedProcess.kill();
    this.bufferedProcess = null;
  }
}
<|endoftext|>


<commit_before>'use babel';

/* @flow */
import Promise from 'bluebird';
import { existsSync, readFile } from 'fs';
import { basename, dirname, join } from 'path';
import { EOL, tmpdir } from 'os';
import { BufferedProcess } from 'atom';
import { parse as babylonParse } from 'jest-editor-support';
import { parse as typescriptParse } from 'jest-test-typescript-parser';
import type { TextEditor } from 'atom';

const ERROR_TEXT = 'Error: ';

type assertionResult = {
  status: 'passed'|'failed'|'skipped'|'unknown',
  title: string,
  name: string,
  failureMessages: Array<string>
};

type itBlock = {
  file: string,
  name: string,
  start:{
    line: number,
    column: number
  },
  end:{
    line: number,
    column: number
  }
};

type TestState = 'passed'|'failed'|'skipped'|'unknown';

type message = {
  state: TestState,
  title: string,
  error: { name: string, message: string },
  duration?: number,
  lineNumber: number,
  filePath: string,
};

const readFilePromise = Promise.promisify(readFile);

export function removeBadArgs(args :?Array<string>) {
  if (!args) {
    return [];
  }

  const prohibitedArgs = ['--json', '--outputFile', '--watch', '--watchAll', '--watchman'];
  const clearArgs = [];
  args.forEach((arg) => {
    const index = prohibitedArgs.indexOf(arg);
    if (index === -1) {
      clearArgs.push(arg);
    }
  });
  return clearArgs;
}

export function getJestError(result :assertionResult) :string {
  let errorMessage = '';
  if (result && result.failureMessages && result.failureMessages.length > 0) {
    const content = result.failureMessages[0];
    const messageMatch = content.match(/(^(.|\n)*?(?=\n\s*at\s.*\:\d*\:\d*))/);
    errorMessage = messageMatch ? messageMatch[0] : 'Error';
    if (errorMessage.startsWith(ERROR_TEXT)) {
      errorMessage = errorMessage.substr(ERROR_TEXT.length);
    }
  }
  return errorMessage;
}

export function getFormattedTesterMessage(state :TestState,
  title :string,
  errorMessage :string,
  duration :number,
  lineNumber :number,
  filePath :string) :message {
  return {
    state,
    title,
    error: {
      name: '',
      message: errorMessage,
    },
    duration,
    lineNumber,
    filePath,
  };
}

export function getMessagesFromAssertionResults(textEditor :TextEditor,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(assertionResults, (messages, testResult) =>
    new Promise((resolve) => {
      textEditor.scan(new RegExp(testResult.title.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')),
      (scanResult) => {
        if (testResult.status === 'pending') {
          testResult.status = 'skipped';
        }
        const errorMessage = getJestError(testResult);
        const state = testResult.status;
        const title = testResult.title;
        const lineNumber = scanResult.row;
        messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
      });
      resolve(messages);
    }), []);
}

export function getMessagesFromTestLocations(textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(testLocations, (messages, testLocation) => {
    const testResult = assertionResults.find(ar => ar.title === testLocation.name);
    if (assertionResults && assertionResults.length > 0 && testResult) {
      if (testResult.status === 'pending') {
        testResult.status = 'skipped';
      }
      const errorMessage = getJestError(testResult);
      const state = testResult.status;
      const title = testResult.title || '';
      const lineNumber = testLocation.start.line - 1;
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    } else {
      const state = 'unknown';
      const title = testLocation.name || '';
      const lineNumber = testLocation.start.line - 1;
      const errorMessage = '';
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    }
    return messages;
  }, []);
}

export function getMessagesFromTestResults(testResults :Array<Object>) {
  return Promise.map(testResults, testResult =>
    Promise.map(testResult.assertionResults, (result) => {
      if (result.status === 'pending') {
        result.status = 'skipped';
      }
      const errorMessage = getJestError(result);
      const state = result.status;
      const title = result.title;
      const lineNumber = 0;
      const duration = (testResult.endTime || 0) - (testResult.startTime || 0);
      return getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, testResult.name);
    }))
    .reduce((messages, result) => result.concat(messages), []);
}

export async function parseReporterOutput(data :string,
  filePath :string,
  textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  output : string) :Promise<{messages: Array<message>, output: string}> {
  let messages = [];
  let dataJSON;
  try {
    dataJSON = await JSON.parse(data);
  } catch (error) {
    atom.notifications.addError('Tester Jest: Could not parse data to JSON.');
  }
  let duration = 0;
  let processError = '';
  if (dataJSON && dataJSON.testResults && dataJSON.testResults.length > 0) {
    duration = (dataJSON.testResults[0].endTime || 0) - (dataJSON.testResults[0].startTime || 0);
    processError = dataJSON.testResults[0].message;
    if (filePath && textEditor) {
      const assertionResults = dataJSON.testResults[0].assertionResults;
      if (testLocations && testLocations.length > 0) {
        messages = await getMessagesFromTestLocations(textEditor, testLocations, assertionResults, duration);
      } else if (assertionResults) {
        messages = await getMessagesFromAssertionResults(textEditor, assertionResults, duration);
      }
    } else {
      // Project test
      messages = await getMessagesFromTestResults(dataJSON.testResults);
    }
  }
  if (!messages.length) {
    messages.push(getFormattedTesterMessage('unknown', 'No results', processError, duration, 0, filePath));
  }
  return { messages, output };
}

export async function getTestLocations(filePath :string) :Promise<?Array<itBlock>> {
  if (!filePath) {
    return Promise.resolve(null);
  }
  const isTypeScript = filePath.match(/.(ts|tsx)$/);
  const parser = isTypeScript ? typescriptParse : babylonParse;
  try {
    const parseResults :{itBlocks:Array<itBlock>} = await parser(filePath);
    return parseResults.itBlocks;
  } catch (e) {
    console.warn('Tester Jest: Failed to parse with babel.', e);
  }
}

export function run(textEditor :?TextEditor, additionalArgs :?string) {
  return new Promise((resolve) => {
    let processOutput = `\u001b[1mTester Jest\u001b[0m${EOL}`;
    const filePath = textEditor ? textEditor.getPath() : '';
    const projectPath = filePath ? atom.project.relativizePath(filePath)[0] : atom.project.getPaths()[0];

    let cwd = projectPath;
    if (!(cwd)) {
      cwd = dirname(filePath);
    }
    const jsonOutputFilePath = join(tmpdir(),
      `tester-jest_${filePath ? basename(filePath) : basename(projectPath)}.json`);

    const userConfigArgs = removeBadArgs(atom.config.get('tester-jest.args'));
    const additionalArgsArray = (additionalArgs && additionalArgs.trim()) ?
      removeBadArgs(additionalArgs.trim().split(' ')) : [];

    const belowEighteen = atom.config.get('tester-jest.jestMajorVersion') < 18;
    const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile';
    const defaultArgs = ['--json', outputArg, jsonOutputFilePath];
    if (filePath) {
      defaultArgs.push(filePath);
    }
    let args = userConfigArgs.concat(additionalArgsArray, defaultArgs);
    const env = Object.create(process.env);
    // Jest NODE_ENV default is 'test'
    // https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L13
    env.NODE_ENV = atom.config.get('tester-jest.nodeEnv');
    // To use our own commands in create-react, we need to tell the command that
    // we're in a CI environment, or it will always append --watch
    env.CI = 'true';
    // set NODE_PATH otherwise will set atom own path
    // https://github.com/atom/atom/blob/master/src/initialize-application-window.coffee#L71
    env.NODE_PATH = cwd;
    const options = { cwd, env };
    let jestBinary = atom.config.get('tester-jest.binaryPath');
    const jestBinaryProject = `${cwd}/node_modules/.bin/jest`;
    let command = '';
    if (jestBinary) {
      const runtimeExecutable = jestBinary;
      const parameters = runtimeExecutable.split(' ');
      command = parameters.shift();
      args = args.concat(parameters);
    } else {
      jestBinary = existsSync(jestBinaryProject) ? jestBinaryProject : 'jest';
      command = jestBinary;
    }
    processOutput += `\u001b[1mcommand:\u001b[0m ${command} ${args.join(' ')}${EOL}`;
    processOutput += `\u001b[1mcwd:\u001b[0m ${cwd}${EOL}`;
    const stdout = (data) => {
      if (!data.startsWith('Test results written to:')) {
        processOutput += data;
      }
    };
    const stderr = data => processOutput += data;
    const exit = async () => {
      this.bufferedProcess = null;
      try {
        const testLocations = await getTestLocations(filePath);
        const jestJsonResults = await readFilePromise(jsonOutputFilePath, 'utf8');
        resolve(await parseReporterOutput(jestJsonResults, filePath, textEditor, testLocations, processOutput));
      } catch (error) {
        resolve({ messages: getFormattedTesterMessage('unknown', 'No results', error, 0, 0, filePath), output: error });
      }
    };
    this.bufferedProcess = new BufferedProcess({ command, args, options, stdout, stderr, exit });

    this.bufferedProcess.onWillThrowError(() => {
      const error = 'Tester is unable to locate the jest command. Please ensure process.env.PATH can access jest.';
      atom.notifications.addError(error);
    });
  });
}

export function stop() {
  if (this.bufferedProcess) {
    this.bufferedProcess.kill();
    this.bufferedProcess = null;
  }
}
<commit_msg>remove json file after test ran<commit_after>'use babel';

/* @flow */
import Promise from 'bluebird';
import { existsSync, readFile, unlink } from 'fs';
import { basename, dirname, join } from 'path';
import { EOL, tmpdir } from 'os';
import { BufferedProcess } from 'atom';
import { parse as babylonParse } from 'jest-editor-support';
import { parse as typescriptParse } from 'jest-test-typescript-parser';
import type { TextEditor } from 'atom';

const ERROR_TEXT = 'Error: ';

type assertionResult = {
  status: 'passed'|'failed'|'skipped'|'unknown',
  title: string,
  name: string,
  failureMessages: Array<string>
};

type itBlock = {
  file: string,
  name: string,
  start:{
    line: number,
    column: number
  },
  end:{
    line: number,
    column: number
  }
};

type TestState = 'passed'|'failed'|'skipped'|'unknown';

type message = {
  state: TestState,
  title: string,
  error: { name: string, message: string },
  duration?: number,
  lineNumber: number,
  filePath: string,
};

const readFileAsync = Promise.promisify(readFile);
const unlinkAsync = Promise.promisify(unlink);

export function removeBadArgs(args :?Array<string>) {
  if (!args) {
    return [];
  }

  const prohibitedArgs = ['--json', '--outputFile', '--watch', '--watchAll', '--watchman'];
  const clearArgs = [];
  args.forEach((arg) => {
    const index = prohibitedArgs.indexOf(arg);
    if (index === -1) {
      clearArgs.push(arg);
    }
  });
  return clearArgs;
}

export function getJestError(result :assertionResult) :string {
  let errorMessage = '';
  if (result && result.failureMessages && result.failureMessages.length > 0) {
    const content = result.failureMessages[0];
    const messageMatch = content.match(/(^(.|\n)*?(?=\n\s*at\s.*\:\d*\:\d*))/);
    errorMessage = messageMatch ? messageMatch[0] : 'Error';
    if (errorMessage.startsWith(ERROR_TEXT)) {
      errorMessage = errorMessage.substr(ERROR_TEXT.length);
    }
  }
  return errorMessage;
}

export function getFormattedTesterMessage(state :TestState,
  title :string,
  errorMessage :string,
  duration :number,
  lineNumber :number,
  filePath :string) :message {
  return {
    state,
    title,
    error: {
      name: '',
      message: errorMessage,
    },
    duration,
    lineNumber,
    filePath,
  };
}

export function getMessagesFromAssertionResults(textEditor :TextEditor,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(assertionResults, (messages, testResult) =>
    new Promise((resolve) => {
      textEditor.scan(new RegExp(testResult.title.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')),
      (scanResult) => {
        if (testResult.status === 'pending') {
          testResult.status = 'skipped';
        }
        const errorMessage = getJestError(testResult);
        const state = testResult.status;
        const title = testResult.title;
        const lineNumber = scanResult.row;
        messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
      });
      resolve(messages);
    }), []);
}

export function getMessagesFromTestLocations(textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  assertionResults :Array<assertionResult>,
  duration :number) :Promise<Array<message>> {
  const filePath = textEditor.getPath();
  return Promise.reduce(testLocations, (messages, testLocation) => {
    const testResult = assertionResults.find(ar => ar.title === testLocation.name);
    if (assertionResults && assertionResults.length > 0 && testResult) {
      if (testResult.status === 'pending') {
        testResult.status = 'skipped';
      }
      const errorMessage = getJestError(testResult);
      const state = testResult.status;
      const title = testResult.title || '';
      const lineNumber = testLocation.start.line - 1;
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    } else {
      const state = 'unknown';
      const title = testLocation.name || '';
      const lineNumber = testLocation.start.line - 1;
      const errorMessage = '';
      messages.push(getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, filePath));
    }
    return messages;
  }, []);
}

export function getMessagesFromTestResults(testResults :Array<Object>) {
  return Promise.map(testResults, testResult =>
    Promise.map(testResult.assertionResults, (result) => {
      if (result.status === 'pending') {
        result.status = 'skipped';
      }
      const errorMessage = getJestError(result);
      const state = result.status;
      const title = result.title;
      const lineNumber = 0;
      const duration = (testResult.endTime || 0) - (testResult.startTime || 0);
      return getFormattedTesterMessage(state, title, errorMessage, duration, lineNumber, testResult.name);
    }))
    .reduce((messages, result) => result.concat(messages), []);
}

export async function parseReporterOutput(data :string,
  filePath :string,
  textEditor :TextEditor,
  testLocations :?Array<itBlock>,
  output : string) :Promise<{messages: Array<message>, output: string}> {
  let messages = [];
  let dataJSON;
  try {
    dataJSON = await JSON.parse(data);
  } catch (error) {
    atom.notifications.addError('Tester Jest: Could not parse data to JSON.');
  }
  let duration = 0;
  let processError = '';
  if (dataJSON && dataJSON.testResults && dataJSON.testResults.length > 0) {
    duration = (dataJSON.testResults[0].endTime || 0) - (dataJSON.testResults[0].startTime || 0);
    processError = dataJSON.testResults[0].message;
    if (filePath && textEditor) {
      const assertionResults = dataJSON.testResults[0].assertionResults;
      if (testLocations && testLocations.length > 0) {
        messages = await getMessagesFromTestLocations(textEditor, testLocations, assertionResults, duration);
      } else if (assertionResults) {
        messages = await getMessagesFromAssertionResults(textEditor, assertionResults, duration);
      }
    } else {
      // Project test
      messages = await getMessagesFromTestResults(dataJSON.testResults);
    }
  }
  if (!messages.length) {
    messages.push(getFormattedTesterMessage('unknown', 'No results', processError, duration, 0, filePath));
  }
  return { messages, output };
}

export async function getTestLocations(filePath :string) :Promise<?Array<itBlock>> {
  if (!filePath) {
    return Promise.resolve(null);
  }
  const isTypeScript = filePath.match(/.(ts|tsx)$/);
  const parser = isTypeScript ? typescriptParse : babylonParse;
  try {
    const parseResults :{itBlocks:Array<itBlock>} = await parser(filePath);
    return parseResults.itBlocks;
  } catch (e) {
    console.warn('Tester Jest: Failed to parse with babel.', e);
  }
}

export function run(textEditor :?TextEditor, additionalArgs :?string) {
  return new Promise((resolve) => {
    let processOutput = `\u001b[1mTester Jest\u001b[0m${EOL}`;
    const filePath = textEditor ? textEditor.getPath() : '';
    const projectPath = filePath ? atom.project.relativizePath(filePath)[0] : atom.project.getPaths()[0];

    let cwd = projectPath;
    if (!(cwd)) {
      cwd = dirname(filePath);
    }
    const jsonOutputFilePath = join(tmpdir(),
      `tester-jest_${filePath ? basename(filePath) : basename(projectPath)}.json`);

    const userConfigArgs = removeBadArgs(atom.config.get('tester-jest.args'));
    const additionalArgsArray = (additionalArgs && additionalArgs.trim()) ?
      removeBadArgs(additionalArgs.trim().split(' ')) : [];

    const belowEighteen = atom.config.get('tester-jest.jestMajorVersion') < 18;
    const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile';
    const defaultArgs = ['--json', outputArg, jsonOutputFilePath];
    if (filePath) {
      defaultArgs.push(filePath);
    }
    let args = userConfigArgs.concat(additionalArgsArray, defaultArgs);
    const env = Object.create(process.env);
    // Jest NODE_ENV default is 'test'
    // https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L13
    env.NODE_ENV = atom.config.get('tester-jest.nodeEnv');
    // To use our own commands in create-react, we need to tell the command that
    // we're in a CI environment, or it will always append --watch
    env.CI = 'true';
    // set NODE_PATH otherwise will set atom own path
    // https://github.com/atom/atom/blob/master/src/initialize-application-window.coffee#L71
    env.NODE_PATH = cwd;
    const options = { cwd, env };
    let jestBinary = atom.config.get('tester-jest.binaryPath');
    const jestBinaryProject = `${cwd}/node_modules/.bin/jest`;
    let command = '';
    if (jestBinary) {
      const runtimeExecutable = jestBinary;
      const parameters = runtimeExecutable.split(' ');
      command = parameters.shift();
      args = args.concat(parameters);
    } else {
      jestBinary = existsSync(jestBinaryProject) ? jestBinaryProject : 'jest';
      command = jestBinary;
    }
    processOutput += `\u001b[1mcommand:\u001b[0m ${command} ${args.join(' ')}${EOL}`;
    processOutput += `\u001b[1mcwd:\u001b[0m ${cwd}${EOL}`;
    const stdout = (data) => {
      if (!data.startsWith('Test results written to:')) {
        processOutput += data;
      }
    };
    const stderr = data => processOutput += data;
    const exit = async () => {
      this.bufferedProcess = null;
      try {
        const testLocations = await getTestLocations(filePath);
        const jestJsonResults = await readFileAsync(jsonOutputFilePath, 'utf8');
        await unlinkAsync(jsonOutputFilePath);
        resolve(await parseReporterOutput(jestJsonResults, filePath, textEditor, testLocations, processOutput));
      } catch (error) {
        resolve({ messages: getFormattedTesterMessage('unknown', 'No results', error, 0, 0, filePath), output: error });
      }
    };
    this.bufferedProcess = new BufferedProcess({ command, args, options, stdout, stderr, exit });

    this.bufferedProcess.onWillThrowError(() => {
      const error = 'Tester is unable to locate the jest command. Please ensure process.env.PATH can access jest.';
      atom.notifications.addError(error);
    });
  });
}

export function stop() {
  if (this.bufferedProcess) {
    this.bufferedProcess.kill();
    this.bufferedProcess = null;
  }
}
<|endoftext|>


<commit_before>const uuid  = require("uuid/v4");
const empty = require("is-empty");
const Ajv   = require("ajv");

const RESERVED_ATTRIBUTES = {
  type: "type",
  specversion: "specversion",
  source: "source",
  id: "id",
  time: "time",
  dataschema: "schemaurl",
  datacontenttype: "datacontenttype",
  subject : "subject",
  data: "data",
  data_base64: "data_base64"
};

const schema = require("../../ext/spec_1.json");

const ajv = new Ajv({
  extendRefs: true
});

const isValidAgainstSchema = ajv.compile(schema);

function Spec1(_caller) {
  this.payload = {
    specversion: "1.0",
    id: uuid()
  };

  if(!_caller){
    _caller = require("../cloudevent.js");
  }

  /*
   * Used to inject compatibility methods or attributes
   */
  this.caller = _caller;

  // dataschema attribute
  this.caller.prototype.dataschema = function(dataschema){
    this.spec.dataschema(dataschema);
    return this;
  }
  this.caller.prototype.getDataschema = function() {
    return this.spec.getDataschema();
  }

  // datacontenttype attribute
  this.caller.prototype.dataContentType = function(contentType){
    this.spec.dataContentType(contentType);
    return this;
  };
  this.caller.prototype.getDataContentType = function(){
   return this.spec.getDataContentType();
  };

  // subject attribute
  this.caller.prototype.subject = function(_subject){
    this.spec.subject(_subject);
    return this;
  };
  this.caller.prototype.getSubject = function(){
   return this.spec.getSubject();
  };
}

Spec1.prototype.id = function(_id){
  this.payload["id"] = _id;
  return this;
};

Spec1.prototype.getId = function() {
  return this.payload["id"];
};

Spec1.prototype.source = function(_source){
  this.payload["source"] = _source;
  return this;
};

Spec1.prototype.getSource = function() {
  return this.payload["source"];
};

Spec1.prototype.specversion = function(_specversion){
  // does not set! This is right
  return this;
};

Spec1.prototype.getSpecversion = function() {
  return this.payload["specversion"];
};

Spec1.prototype.type = function(_type){
  this.payload["type"] = _type;
  return this;
};

Spec1.prototype.getType = function(){
  return this.payload["type"];
};

Spec1.prototype.dataContentType = function(_contenttype){
  this.payload["datacontenttype"] = _contenttype;
  return this;
};
Spec1.prototype.getDataContentType = function() {
  return this.payload["datacontenttype"];
};

Spec1.prototype.dataschema = function(_schema){
  this.payload["dataschema"] = _schema;
  return this;
};
Spec1.prototype.getDataschema = function() {
  return this.payload["dataschema"];
};

Spec1.prototype.subject = function(_subject){
  this.payload["subject"] = _subject;
  return this;
};
Spec1.prototype.getSubject = function() {
  return this.payload["subject"];
};

Spec1.prototype.time = function(_time){
  this.payload["time"] = _time.toISOString();
  return this;
};
Spec1.prototype.getTime = function() {
  return this.payload["time"];
};

Spec1.prototype.data = function(_data){
  this.payload["data"] = _data;
  return this;
};
Spec1.prototype.getData = function() {
  return this.payload["data"];
};

module.exports = Spec1;
<commit_msg>Method to check against the json schema<commit_after>const uuid  = require("uuid/v4");
const empty = require("is-empty");
const Ajv   = require("ajv");

const RESERVED_ATTRIBUTES = {
  type: "type",
  specversion: "specversion",
  source: "source",
  id: "id",
  time: "time",
  dataschema: "schemaurl",
  datacontenttype: "datacontenttype",
  subject : "subject",
  data: "data",
  data_base64: "data_base64"
};

const schema = require("../../ext/spec_1.json");

const ajv = new Ajv({
  extendRefs: true
});

const isValidAgainstSchema = ajv.compile(schema);

function Spec1(_caller) {
  this.payload = {
    specversion: "1.0",
    id: uuid()
  };

  if(!_caller){
    _caller = require("../cloudevent.js");
  }

  /*
   * Used to inject compatibility methods or attributes
   */
  this.caller = _caller;

  // dataschema attribute
  this.caller.prototype.dataschema = function(dataschema){
    this.spec.dataschema(dataschema);
    return this;
  }
  this.caller.prototype.getDataschema = function() {
    return this.spec.getDataschema();
  }

  // datacontenttype attribute
  this.caller.prototype.dataContentType = function(contentType){
    this.spec.dataContentType(contentType);
    return this;
  };
  this.caller.prototype.getDataContentType = function(){
   return this.spec.getDataContentType();
  };

  // subject attribute
  this.caller.prototype.subject = function(_subject){
    this.spec.subject(_subject);
    return this;
  };
  this.caller.prototype.getSubject = function(){
   return this.spec.getSubject();
  };
}

/*
 * Check the spec constraints
 */
Spec1.prototype.check = function(ce){
  var toCheck = (!ce ? this.payload : ce);

  if(!isValidAgainstSchema(toCheck)) {
    throw {message: "invalid payload", errors: isValidAgainstSchema.errors};
  }
};

Spec1.prototype.id = function(_id){
  this.payload["id"] = _id;
  return this;
};

Spec1.prototype.getId = function() {
  return this.payload["id"];
};

Spec1.prototype.source = function(_source){
  this.payload["source"] = _source;
  return this;
};

Spec1.prototype.getSource = function() {
  return this.payload["source"];
};

Spec1.prototype.specversion = function(_specversion){
  // does not set! This is right
  return this;
};

Spec1.prototype.getSpecversion = function() {
  return this.payload["specversion"];
};

Spec1.prototype.type = function(_type){
  this.payload["type"] = _type;
  return this;
};

Spec1.prototype.getType = function(){
  return this.payload["type"];
};

Spec1.prototype.dataContentType = function(_contenttype){
  this.payload["datacontenttype"] = _contenttype;
  return this;
};
Spec1.prototype.getDataContentType = function() {
  return this.payload["datacontenttype"];
};

Spec1.prototype.dataschema = function(_schema){
  this.payload["dataschema"] = _schema;
  return this;
};
Spec1.prototype.getDataschema = function() {
  return this.payload["dataschema"];
};

Spec1.prototype.subject = function(_subject){
  this.payload["subject"] = _subject;
  return this;
};
Spec1.prototype.getSubject = function() {
  return this.payload["subject"];
};

Spec1.prototype.time = function(_time){
  this.payload["time"] = _time.toISOString();
  return this;
};
Spec1.prototype.getTime = function() {
  return this.payload["time"];
};

Spec1.prototype.data = function(_data){
  this.payload["data"] = _data;
  return this;
};
Spec1.prototype.getData = function() {
  return this.payload["data"];
};

module.exports = Spec1;
<|endoftext|>


<commit_before>var path = require('path');
var bindings = require('../build/Release/spellchecker.node');

var Spellchecker = bindings.Spellchecker;

var defaultSpellcheck = null;

var setDictionary = function(lang, dictPath) {
  defaultSpellcheck = new Spellchecker();
  // NB: Windows 8 uses *dashes* to set the language (i.e. en-US), so if we fail
  // to set the language, try the Windows 8 way
  lang = lang.replace('_', '-');
  if (!defaultSpellcheck.setDictionary(lang, dictPath)) {
    lang = lang.replace('-', '_');
    defaultSpellcheck.setDictionary(lang, dictPath);
  }
};

var ensureDefaultSpellCheck = function() {
  if (defaultSpellcheck) {
    return;
  }

  var lang = process.env.LANG;
  lang = lang ? lang.split('.')[0] : 'en_US';
  setDictionary(lang, getDictionaryPath());
};

var isMisspelled = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.isMisspelled.apply(defaultSpellcheck, arguments);
};

var checkSpelling = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.checkSpelling.apply(defaultSpellcheck, arguments);
};

var add = function() {
  ensureDefaultSpellCheck();

  defaultSpellcheck.add.apply(defaultSpellcheck, arguments);
};

var remove = function() {
  ensureDefaultSpellCheck();

  defaultSpellcheck.remove.apply(defaultSpellcheck, arguments);
};

var getCorrectionsForMisspelling = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.getCorrectionsForMisspelling.apply(defaultSpellcheck, arguments);
};

var getAvailableDictionaries = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.getAvailableDictionaries.apply(defaultSpellcheck, arguments);
};

var getDictionaryPath = function() {
  var dict = path.join(__dirname, '..', 'vendor', 'hunspell_dictionaries');
  try {
    // HACK: Special case being in an asar archive
    var unpacked = dict.replace('.asar' + path.sep, '.asar.unpacked' + path.sep);
    if (require('fs').statSyncNoException(unpacked)) {
      dict = unpacked;
    }
  } catch (error) {
  }
  return dict;
}

module.exports = {
  setDictionary: setDictionary,
  add: add,
  remove: remove,
  isMisspelled: isMisspelled,
  checkSpelling: checkSpelling,
  getAvailableDictionaries: getAvailableDictionaries,
  getCorrectionsForMisspelling: getCorrectionsForMisspelling,
  Spellchecker: Spellchecker
};
<commit_msg>Make setDictionary consistent with other methods<commit_after>var path = require('path');
var bindings = require('../build/Release/spellchecker.node');

var Spellchecker = bindings.Spellchecker;

var defaultSpellcheck = null;

var ensureDefaultSpellCheck = function() {
  if (defaultSpellcheck) {
    return;
  }

  var lang = process.env.LANG;
  lang = lang ? lang.split('.')[0] : 'en_US';
  setDictionary(lang, getDictionaryPath());
};

var setDictionary = function(lang, dictPath) {
  ensureDefaultSpellCheck();
  return defaultSpellcheck.setDictionary(lang, dictPath);
};

var isMisspelled = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.isMisspelled.apply(defaultSpellcheck, arguments);
};

var checkSpelling = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.checkSpelling.apply(defaultSpellcheck, arguments);
};

var add = function() {
  ensureDefaultSpellCheck();

  defaultSpellcheck.add.apply(defaultSpellcheck, arguments);
};

var remove = function() {
  ensureDefaultSpellCheck();

  defaultSpellcheck.remove.apply(defaultSpellcheck, arguments);
};

var getCorrectionsForMisspelling = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.getCorrectionsForMisspelling.apply(defaultSpellcheck, arguments);
};

var getAvailableDictionaries = function() {
  ensureDefaultSpellCheck();

  return defaultSpellcheck.getAvailableDictionaries.apply(defaultSpellcheck, arguments);
};

var getDictionaryPath = function() {
  var dict = path.join(__dirname, '..', 'vendor', 'hunspell_dictionaries');
  try {
    // HACK: Special case being in an asar archive
    var unpacked = dict.replace('.asar' + path.sep, '.asar.unpacked' + path.sep);
    if (require('fs').statSyncNoException(unpacked)) {
      dict = unpacked;
    }
  } catch (error) {
  }
  return dict;
}

module.exports = {
  setDictionary: setDictionary,
  add: add,
  remove: remove,
  isMisspelled: isMisspelled,
  checkSpelling: checkSpelling,
  getAvailableDictionaries: getAvailableDictionaries,
  getCorrectionsForMisspelling: getCorrectionsForMisspelling,
  Spellchecker: Spellchecker
};
<|endoftext|>


<commit_before>// on startup run resizing event
Meteor.startup(function () {
    //    $(window).resize(function () {
    //        $('#map').css('height', window.innerHeight);
    //    });
    //    $(window).resize(); // trigger resize event
});

//create Collections
var trashesCollection = new Meteor.Collection('trashesCollection');
var fotoLocationsCollection = new Meteor.Collection('fotoLocationsCollection');
var fotoLocationsJulyCollection = new Meteor.Collection('fotoLocationsJulyCollection');
var fotoLocationsAugustCollection = new Meteor.Collection('fotoLocationsAugustCollection');

//if template "map" is renderd
Template.map.rendered = function () {
    var selector = function (selector) {
            return document.querySelector(selector);
        },
        selectors = function (selector) {
            return document.querySelectorAll(selector);
        };

    var toggleFilterImg = selector('.togglefilterimg'),
        toggleFilter = selector('.togglefilter'),
        filter = selector('.filter'),
        informotion = selector('.informotion'),
        crowdedness = selector('.crowdedness'),
        trashes = selector('.trashes'),
        cleaningIntensity = selector('.cleaning-intensity'),
        wijken = selector('.wijken'),
        wijkenP = selector('.wijken p');

    //subscribe to trashesCollection
    Meteor.subscribe('trashesCollection', function () {
        var trashesData = trashesCollection.find().fetch();
        //callback to setTrashes
        setTrashes(trashesData)
    });

    //subscribe to fotoLocationsCollection
    Meteor.subscribe('fotoLocationsCollection', function () {
        var fotosData = fotoLocationsCollection.find().fetch();
        setFotoLocation(fotosData);
    });
    Meteor.subscribe('fotoLocationsJulyCollection', function () {
        var fotosData = fotoLocationsJulyCollection.find().fetch();
        setFotoLocationJuly(fotosData);
    });
    Meteor.subscribe('fotoLocationsAugustCollection', function () {
        var fotosData = fotoLocationsAugustCollection.find().fetch();
        setFotoLocationAugust(fotosData);
    });

    var layerIDs = [];
    HTTP.get(Meteor.absoluteUrl("data/map.json"), function (err, result) {
        geoData = result.data;
        var gData = geoData.features;
        var i = 0;
        for (i; i < gData.length; i++) {
            layerIDs.push(gData[i].properties.id);
        };
        geoDatafunction(geoData);
    });

    HTTP.get(Meteor.absoluteUrl("data/schoonmaakintensiteit.json"), function (err, result) {
        heatmapLayer = result.data;
        createheatmap(heatmapLayer);
    });

    //create leaflet map and start coordiates
    var map = L.map('map', {
        center: [52.376956, 4.902756],
        maxZoom: 10,
        minZoom: 14,
        zoom: 14,
        zoomControl: false,
        attributionControl: false
    });

    //add bounds to map
    map.fitBounds([
    [52.380419542018174, 4.941530227661133],
     [52.359457601988254, 4.864282608032227]
   ]);

    var baseLayer = L.tileLayer(
        'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
            attribution: 'Informotion',
            subdomains: 'abcd',
            maxZoom: 19
        });

    L.tileLayer.provider('CartoDB.PositronNoLabels').addTo(map);

    //create div icon with class trash
    var trashIcon = L.divIcon({
        className: 'trashicon'
    });

    var fotoIconSeptember = L.divIcon({
        className: 'foto-icon-september'
    });
    var fotoIconJuly = L.divIcon({
        className: 'foto-icon-july'
    });
    var fotoIconAugust = L.divIcon({
        className: 'foto-icon-august'
    });

    //    var createheatmap = function (heatmapLayer) {
    //        var heat = L.heatLayer(heatmapLayer, {
    //            radius: 18,
    //            blur: 20,
    //            max: 1.5,
    //            gradient: {
    //                0: '#FFB700',
    //                0.5: '#FFB700',
    //                0.75: '#21B532',
    //                0.80: '#941E64',
    ////                0.50: '#C45D9A',
    ////                0.60: '#B13B80',
    //                1: '#941E64'
    //            }
    //        }).addTo(map);
    //    }

    //disable dragging
    map.dragging.disable();
    map.touchZoom.disable();
    map.doubleClickZoom.disable();
    map.scrollWheelZoom.disable();
    map.boxZoom.disable();
    map.keyboard.disable();

    //set foto's september on map
    var setFotoLocation = function (fotosData) {
        var Amountfotos = fotosData.length,
            f = 0;
        for (f; f < Amountfotos; f++) {
            var longitude = fotosData[f].log;
            var latitude = fotosData[f].lat;
            L.marker([latitude, longitude], {
                icon: fotoIconSeptember,
            }).addTo(map);
        }
    };
    //    set foto's july on map
    var setFotoLocationJuly = function (fotosData) {
        var Amountfotos = fotosData.length,
            f = 0;
        for (f; f < Amountfotos; f++) {
            var longitude = fotosData[f].log;
            var latitude = fotosData[f].lat;
            L.marker([latitude, longitude], {
                icon: fotoIconJuly,
            }).addTo(map);
        }
    };
    //     set foto's August on map
    var setFotoLocationAugust = function (fotosData) {
        var Amountfotos = fotosData.length,
            f = 0;
        for (f; f < Amountfotos; f++) {
            var longitude = fotosData[f].log;
            var latitude = fotosData[f].lat;
            L.marker([latitude, longitude], {
                icon: fotoIconAugust,
            }).addTo(map);
        }
    };

    //set trashes on map
    var setTrashes = function (trashesData) {
        var amountTrashes = trashesData.length,
            i = 0;
        for (i; i < amountTrashes; i++) {
            var longitude = trashesData[i].log;
            var latitude = trashesData[i].lat;
            var street = trashesData[i].street;
            var number = trashesData[i].houseNumber;
            L.marker([latitude, longitude], {
                icon: trashIcon,
                riseOnHover: true,
            }).addTo(map).bindPopup(street + number);
        }
    };

    //Create the map of Amsterdam Centrum and add render it.
    var myStyle = {
        "fillColor": "#fff",
        "fillOpacity": 0.0,
        "color": "RGBA(255, 255, 255, 0)"
    }

    var geojson;

    //What happens on mouseover
    function highlightFeature(e) {
        var layer = e.target;
        var layerName = layer.feature.properties.name,
            SvgMapPart = selector('.mappopup'),
            popup = selector('.popup'),
            overlayList = document.querySelectorAll(".overlay");

        var xPosition = event.clientX;
        var yPosition = event.clientY;

        //If there are elements with the "overlay" class, then hover will work and shows popup. Otherwise not.
        if (overlayList.length === 0) {
            SvgMapPart.classList.remove("none");
            if (layerName !== "rightgone" && layerName !== "leftgone") {
                popup.innerHTML = layerName;
                SvgMapPart.style.position = "absolute";
                SvgMapPart.style.left = xPosition + -30 + 'px';
                SvgMapPart.style.top = yPosition + -130 + 'px';

                layer.setStyle({
                    //                weight: 5,
                    fillColor: '#D83E41',
                    dashArray: '',
                    fillOpacity: 1
                });
                if (!L.Browser.ie && !L.Browser.opera) {
                    layer.bringToFront();
                }
            } else {
                console.log("out of order")
                    //adds class that hides the popup
                SvgMapPart.classList.add("none");
            }
        };
    };
    //reset on mouseout
    function resetHighlight(e) {
        geojson.resetStyle(e.target);
    };

    function clickFeature(e, gData) {
        var layertje = e.target,
            layerName = layertje.feature.properties.name,
            layerID = layertje.feature.properties.id,
            SvgMapPart = selector('.mappopup'),
            overlayList = document.querySelectorAll(".overlay");

        SvgMapPart.classList.add("none");

        //If there are elements with the "overlay" class, then classes will be added to paths. Otherwise not.
        if (overlayList.length === 0) {
            //gives classes to paths, with which they can be styled
            if (layerName !== "rightgone" && layerName !== "leftgone") {
                var i = 0;
                for (i; i < layerIDs.length; i++) {
                    var checkingz = document.getElementById(layerIDs[i]).className;
                    //                console.log(document.getElementById(layerIDs[i]));

                    if (layerIDs[i] !== layerID) {
                        document.getElementById(layerIDs[i]).setAttribute('class', 'overlay');
                    } else {
                        document.getElementById(layerIDs[i]).setAttribute('class', 'transparent');
                    };
                };
            };
        };
    };

    function onEachFeature(feature, layer) {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight,
            click: clickFeature
        });
    };

    var geoDatafunction = function (geoData) {
        geojson = L.geoJson(geoData, {
            style: myStyle,
            onEachFeature: onEachFeature
        }).addTo(map)

        geojson.eachLayer(function (layer) {
            layer._path.id = layer.feature.properties.id;
        });
    };

    //filters
    var closed = false;
    var myMap = document.getElementById("map");
    var windowWidth = window.innerWidth;
    var informotionWidth = windowWidth - 243 + "px";

    toggleFilter.addEventListener('click', function () {
        if (closed === false) {
            var windowWidth = window.innerHeight;
            closed = true;
            TweenMax.to(filter, 2, {
                x: -243
            });
            TweenMax.to(toggleFilterImg, 2, {
                rotation: -45
            });
            TweenMax.to(informotion, 2, {
                width: windowWidth,
                css: {
                    marginLeft: -243
                }
            });
            TweenMax.to(myMap, 2, {left: "100px"});
        } else {
            var informotionWidth = informotion.offsetWidth;
            closed = false;
            TweenMax.to(filter, 2, {
                x: 0
            });
            TweenMax.to(toggleFilterImg, 2, {
                rotation: 0
            });
            TweenMax.to(informotion, 2, {
                width: informotionWidth,
                css: {
                    marginLeft: -0
                }
            });
            TweenMax.to(myMap, 2, {left: 0});
        }
    });
    //crowdedness
    crowdedness.addEventListener('mouseover', function () {
        TweenMax.to(crowdedness, 0.2, {
            opacity: 0.60
        });
    });
    crowdedness.addEventListener('mouseout', function () {
        TweenMax.to(crowdedness, 0.2, {
            opacity: 1
        });
    });
    crowdedness.addEventListener('click', function () {
        crowdedness.classList.toggle('disabled');
        var fotoAugust = selectors('.foto-icon-august'),
            fotoJuly = selectors('.foto-icon-july'),
            fotoSeptember = selectors('.foto-icon-september'),
            a = 0,
            j = 0,
            s = 0;
        for (a; a < fotoAugust.length; a++) {
            fotoAugust[a].classList.toggle("none");
        };
        for (j; j < fotoJuly.length; j++) {
            fotoJuly[j].classList.toggle("none");
        }
        for (s; s < fotoSeptember.length; s++) {
            fotoSeptember[s].classList.toggle("none");
        }
    });

    //trashes
    trashes.addEventListener('mouseover', function () {
        TweenMax.to(trashes, 0.2, {
            opacity: 0.60
        });
    });
    trashes.addEventListener('mouseout', function () {
        TweenMax.to(trashes, 0.2, {
            opacity: 1
        });
    });
    var trashesfilter = false;
    trashes.addEventListener('click', function () {
        var trashIcons = selectors('.trashicon'),
            t = 0;
        trashes.classList.toggle('disabled');
        for (t; t < trashIcons.length; t++) {
            trashIcons[t].classList.toggle("none");
        }
    });

    //cleaningIntensity
    cleaningIntensity.addEventListener('mouseover', function () {
        TweenMax.to(trashes, 0.2, {
            opacity: 0.60
        });
    });
    cleaningIntensity.addEventListener('mouseout', function () {
        TweenMax.to(cleaningIntensity, 0.2, {
            opacity: 1
        });
    });
    cleaningIntensity.addEventListener('click', function () {
        cleaningIntensity.classList.toggle('disabled')
    });

    //wijken
    wijken.addEventListener('mouseover', function () {
        TweenMax.to(wijken, 0.2, {
            opacity: 0.60
        });
    });
    wijken.addEventListener('mouseout', function () {
        TweenMax.to(wijken, 0.2, {
            opacity: 1
        });
    });
    wijken.addEventListener('click', function () {
        if (wijkenP.innerHTML === "Verberg wijken") {
            wijkenP.innerHTML = "toon wijken"
            var i = 0;
            for (i; i < layerIDs.length; i++) {
                console.log(layerIDs[i])
                if (layerIDs[i] !== "left-gone" && layerIDs[i] !== "right-gone") {
                    document.getElementById(layerIDs[i]).removeAttribute('class');
                }
            };
        } else {
            wijkenP.innerHTML = "Verberg wijken"
            var i = 0;
            for (i; i < layerIDs.length; i++) {
                if (layerIDs[i] !== "left-gone" && layerIDs[i] !== "right-gone") {
                    document.getElementById(layerIDs[i]).setAttribute('class', 'toonwijk');
                }
            };
        }
    });
};
<commit_msg>Fixed hover bug<commit_after>// on startup run resizing event
Meteor.startup(function () {
    //    $(window).resize(function () {
    //        $('#map').css('height', window.innerHeight);
    //    });
    //    $(window).resize(); // trigger resize event
});

//create Collections
var trashesCollection = new Meteor.Collection('trashesCollection');
var fotoLocationsCollection = new Meteor.Collection('fotoLocationsCollection');
var fotoLocationsJulyCollection = new Meteor.Collection('fotoLocationsJulyCollection');
var fotoLocationsAugustCollection = new Meteor.Collection('fotoLocationsAugustCollection');

//if template "map" is renderd
Template.map.rendered = function () {
    var selector = function (selector) {
            return document.querySelector(selector);
        },
        selectors = function (selector) {
            return document.querySelectorAll(selector);
        };

    var toggleFilterImg = selector('.togglefilterimg'),
        toggleFilter = selector('.togglefilter'),
        filter = selector('.filter'),
        informotion = selector('.informotion'),
        crowdedness = selector('.crowdedness'),
        trashes = selector('.trashes'),
        cleaningIntensity = selector('.cleaning-intensity'),
        wijken = selector('.wijken'),
        wijkenP = selector('.wijken p');

    //subscribe to trashesCollection
    Meteor.subscribe('trashesCollection', function () {
        var trashesData = trashesCollection.find().fetch();
        //callback to setTrashes
        setTrashes(trashesData)
    });

    //subscribe to fotoLocationsCollection
    Meteor.subscribe('fotoLocationsCollection', function () {
        var fotosData = fotoLocationsCollection.find().fetch();
        setFotoLocation(fotosData);
    });
    Meteor.subscribe('fotoLocationsJulyCollection', function () {
        var fotosData = fotoLocationsJulyCollection.find().fetch();
        setFotoLocationJuly(fotosData);
    });
    Meteor.subscribe('fotoLocationsAugustCollection', function () {
        var fotosData = fotoLocationsAugustCollection.find().fetch();
        setFotoLocationAugust(fotosData);
    });

    var layerIDs = [];
    HTTP.get(Meteor.absoluteUrl("data/map.json"), function (err, result) {
        geoData = result.data;
        var gData = geoData.features;
        var i = 0;
        for (i; i < gData.length; i++) {
            layerIDs.push(gData[i].properties.id);
        };
        geoDatafunction(geoData);
    });

    HTTP.get(Meteor.absoluteUrl("data/schoonmaakintensiteit.json"), function (err, result) {
        heatmapLayer = result.data;
        createheatmap(heatmapLayer);
    });

    //create leaflet map and start coordiates
    var map = L.map('map', {
        center: [52.376956, 4.902756],
        maxZoom: 10,
        minZoom: 14,
        zoom: 14,
        zoomControl: false,
        attributionControl: false
    });

    //add bounds to map
    map.fitBounds([
    [52.380419542018174, 4.941530227661133],
     [52.359457601988254, 4.864282608032227]
   ]);

    var baseLayer = L.tileLayer(
        'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
            attribution: 'Informotion',
            subdomains: 'abcd',
            maxZoom: 19
        });

    L.tileLayer.provider('CartoDB.PositronNoLabels').addTo(map);

    //create div icon with class trash
    var trashIcon = L.divIcon({
        className: 'trashicon'
    });

    var fotoIconSeptember = L.divIcon({
        className: 'foto-icon-september'
    });
    var fotoIconJuly = L.divIcon({
        className: 'foto-icon-july'
    });
    var fotoIconAugust = L.divIcon({
        className: 'foto-icon-august'
    });

    //    var createheatmap = function (heatmapLayer) {
    //        var heat = L.heatLayer(heatmapLayer, {
    //            radius: 18,
    //            blur: 20,
    //            max: 1.5,
    //            gradient: {
    //                0: '#FFB700',
    //                0.5: '#FFB700',
    //                0.75: '#21B532',
    //                0.80: '#941E64',
    ////                0.50: '#C45D9A',
    ////                0.60: '#B13B80',
    //                1: '#941E64'
    //            }
    //        }).addTo(map);
    //    }

    //disable dragging
    map.dragging.disable();
    map.touchZoom.disable();
    map.doubleClickZoom.disable();
    map.scrollWheelZoom.disable();
    map.boxZoom.disable();
    map.keyboard.disable();

    //set foto's september on map
    var setFotoLocation = function (fotosData) {
        var Amountfotos = fotosData.length,
            f = 0;
        for (f; f < Amountfotos; f++) {
            var longitude = fotosData[f].log;
            var latitude = fotosData[f].lat;
            L.marker([latitude, longitude], {
                icon: fotoIconSeptember,
            }).addTo(map);
        }
    };
    //    set foto's july on map
    var setFotoLocationJuly = function (fotosData) {
        var Amountfotos = fotosData.length,
            f = 0;
        for (f; f < Amountfotos; f++) {
            var longitude = fotosData[f].log;
            var latitude = fotosData[f].lat;
            L.marker([latitude, longitude], {
                icon: fotoIconJuly,
            }).addTo(map);
        }
    };
    //     set foto's August on map
    var setFotoLocationAugust = function (fotosData) {
        var Amountfotos = fotosData.length,
            f = 0;
        for (f; f < Amountfotos; f++) {
            var longitude = fotosData[f].log;
            var latitude = fotosData[f].lat;
            L.marker([latitude, longitude], {
                icon: fotoIconAugust,
            }).addTo(map);
        }
    };

    //set trashes on map
    var setTrashes = function (trashesData) {
        var amountTrashes = trashesData.length,
            i = 0;
        for (i; i < amountTrashes; i++) {
            var longitude = trashesData[i].log;
            var latitude = trashesData[i].lat;
            var street = trashesData[i].street;
            var number = trashesData[i].houseNumber;
            L.marker([latitude, longitude], {
                icon: trashIcon,
                riseOnHover: true,
            }).addTo(map).bindPopup(street + number);
        }
    };

    //Create the map of Amsterdam Centrum and add render it.
    var myStyle = {
        "fillColor": "#fff",
        "fillOpacity": 0.0,
        "color": "RGBA(255, 255, 255, 0)"
    }

    var geojson;

    //What happens on mouseover
    function highlightFeature(e) {
        var layer = e.target;
        var layerName = layer.feature.properties.name,
            SvgMapPart = selector('.mappopup'),
            popup = selector('.popup'),
            overlayList = document.querySelectorAll(".overlay");

        var xPosition = event.clientX;
        var yPosition = event.clientY;

        //If there are elements with the "overlay" class, then hover will work and shows popup. Otherwise not.
        if (overlayList.length === 0) {
            SvgMapPart.classList.remove("none");
            if (layerName !== "rightgone" && layerName !== "leftgone") {
                popup.innerHTML = layerName;
                SvgMapPart.style.position = "absolute";
                SvgMapPart.style.left = xPosition + -30 + 'px';
                SvgMapPart.style.top = yPosition + -130 + 'px';

                layer.setStyle({
                    //                weight: 5,
                    fillColor: '#D83E41',
                    dashArray: '',
                    fillOpacity: 1
                });
                if (!L.Browser.ie && !L.Browser.opera) {
                    layer.bringToFront();
                }
            } else {
                console.log("out of order")
                    //adds class that hides the popup
                SvgMapPart.classList.add("none");
            }
        };
    };
    //reset on mouseout
    function resetHighlight(e) {
        geojson.resetStyle(e.target);
    };

    function clickFeature(e, gData) {
        var layertje = e.target,
            layerName = layertje.feature.properties.name,
            layerID = layertje.feature.properties.id,
            SvgMapPart = selector('.mappopup'),
            overlayList = document.querySelectorAll(".overlay");

        SvgMapPart.classList.add("none");

        //If there are elements with the "overlay" class, then classes will be added to paths. Otherwise not.
        if (overlayList.length === 0) {
            //gives classes to paths, with which they can be styled
            if (layerName !== "rightgone" && layerName !== "leftgone") {
                var i = 0;
                for (i; i < layerIDs.length; i++) {
                    var checkingz = document.getElementById(layerIDs[i]).className;
                    //                console.log(document.getElementById(layerIDs[i]));

                    if (layerIDs[i] !== layerID) {
                        document.getElementById(layerIDs[i]).setAttribute('class', 'overlay');
                    } else {
                        document.getElementById(layerIDs[i]).setAttribute('class', 'transparent');
                    };
                };
            };
        };
    };

    function onEachFeature(feature, layer) {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight,
            click: clickFeature
        });
    };

    var geoDatafunction = function (geoData) {
        geojson = L.geoJson(geoData, {
            style: myStyle,
            onEachFeature: onEachFeature
        }).addTo(map)

        geojson.eachLayer(function (layer) {
            layer._path.id = layer.feature.properties.id;
        });
    };

    //filters
    var closed = false;
    var myMap = document.getElementById("map");
    var windowWidth = window.innerWidth;
    var informotionWidth = windowWidth - 243 + "px";

    toggleFilter.addEventListener('click', function () {
        if (closed === false) {
            var windowWidth = window.innerHeight;
            closed = true;
            TweenMax.to(filter, 2, {
                x: -243
            });
            TweenMax.to(toggleFilterImg, 2, {
                rotation: -45
            });
            TweenMax.to(informotion, 2, {
                width: windowWidth,
                css: {
                    marginLeft: -243
                }
            });
            TweenMax.to(myMap, 2, {left: "100px"});
        } else {
            var informotionWidth = informotion.offsetWidth;
            closed = false;
            TweenMax.to(filter, 2, {
                x: 0
            });
            TweenMax.to(toggleFilterImg, 2, {
                rotation: 0
            });
            TweenMax.to(informotion, 2, {
                width: informotionWidth,
                css: {
                    marginLeft: -0
                }
            });
            TweenMax.to(myMap, 2, {left: 0});
        }
    });
    //crowdedness
    crowdedness.addEventListener('mouseover', function () {
        TweenMax.to(crowdedness, 0.2, {
            opacity: 0.60
        });
    });
    crowdedness.addEventListener('mouseout', function () {
        TweenMax.to(crowdedness, 0.2, {
            opacity: 1
        });
    });
    crowdedness.addEventListener('click', function () {
        crowdedness.classList.toggle('disabled');
        var fotoAugust = selectors('.foto-icon-august'),
            fotoJuly = selectors('.foto-icon-july'),
            fotoSeptember = selectors('.foto-icon-september'),
            a = 0,
            j = 0,
            s = 0;
        for (a; a < fotoAugust.length; a++) {
            fotoAugust[a].classList.toggle("none");
        };
        for (j; j < fotoJuly.length; j++) {
            fotoJuly[j].classList.toggle("none");
        }
        for (s; s < fotoSeptember.length; s++) {
            fotoSeptember[s].classList.toggle("none");
        }
    });

    //trashes
    trashes.addEventListener('mouseover', function () {
        TweenMax.to(trashes, 0.2, {
            opacity: 0.60
        });
    });
    trashes.addEventListener('mouseout', function () {
        TweenMax.to(trashes, 0.2, {
            opacity: 1
        });
    });
    var trashesfilter = false;
    trashes.addEventListener('click', function () {
        var trashIcons = selectors('.trashicon'),
            t = 0;
        trashes.classList.toggle('disabled');
        for (t; t < trashIcons.length; t++) {
            trashIcons[t].classList.toggle("none");
        }
    });

    //cleaningIntensity
    cleaningIntensity.addEventListener('mouseover', function () {
        TweenMax.to(cleaningIntensity, 0.2, {
            opacity: 0.60
        });
    });
    cleaningIntensity.addEventListener('mouseout', function () {
        TweenMax.to(cleaningIntensity, 0.2, {
            opacity: 1
        });
    });
    cleaningIntensity.addEventListener('click', function () {
        cleaningIntensity.classList.toggle('disabled')
    });

    //wijken
    wijken.addEventListener('mouseover', function () {
        TweenMax.to(wijken, 0.2, {
            opacity: 0.60
        });
    });
    wijken.addEventListener('mouseout', function () {
        TweenMax.to(wijken, 0.2, {
            opacity: 1
        });
    });
    wijken.addEventListener('click', function () {
        if (wijkenP.innerHTML === "Verberg wijken") {
            wijkenP.innerHTML = "toon wijken"
            var i = 0;
            for (i; i < layerIDs.length; i++) {
                console.log(layerIDs[i])
                if (layerIDs[i] !== "left-gone" && layerIDs[i] !== "right-gone") {
                    document.getElementById(layerIDs[i]).removeAttribute('class');
                }
            };
        } else {
            wijkenP.innerHTML = "Verberg wijken"
            var i = 0;
            for (i; i < layerIDs.length; i++) {
                if (layerIDs[i] !== "left-gone" && layerIDs[i] !== "right-gone") {
                    document.getElementById(layerIDs[i]).setAttribute('class', 'toonwijk');
                }
            };
        }
    });
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 by Greg Reimer <gregreimer@gmail.com>
 * MIT License. See mit-license.txt for more info.
 */

var util = require('util');
var Transform = require('stream').Transform;

// ---------------------------

function StreamBrake(amount, period){
  Transform.call(this);
  this._period = period || 1000;
  this._origPeriod = this._period;
  this._amount = amount || 1024;
  this._chunkifier = new Chunkifier(this._amount);
  this._lastPush = Date.now();
  this._transferred = 0;
}

util.inherits(StreamBrake, Transform);

StreamBrake.prototype._transform = function(chunk, encoding, callback){
  var self = this;
  self._chunkifier.add(chunk);
  (function next(now){
    var nextChunk = self._chunkifier.getSome();
    if (!nextChunk){
      callback();
    } else {

      if (self._started){
        /*
         * Schedule the next push at future time such that the actual transfer
         * rate will match the desired transfer rate as closely as possible. To
         * do that we need to calculate the proper amount of elapsed time by
         * solving for that variable.
         *
         * actualRate === targetRate
         * actualRate === amountTransferred / elapsedTime
         * amountTransferred / elapsedTime === targetRate
         * amountTransferred === targetRate * elapsedTime
         * amountTransferred / targetRate === elapsedTime <--
         */
        var targetRate = self._amount / self._period;
        var amountTransferred = self._transferred + nextChunk.length;
        var elapsedTime = amountTransferred / targetRate;
        var elapsed = now - self._started;
        var wait = Math.round(Math.max(0, elapsedTime - elapsed));
      } else {
        self._started = now;
        var wait = self._period;
      }

      setTimeout(function(){
        var now = Date.now()
        self.push(nextChunk);
        self._lastPush = now;
        self._transferred += nextChunk.length;
        next(now);
      }, wait);
    }
  })(Date.now());
};

StreamBrake.prototype._flush = function(callback){
  var self = this;
  var lastChunk = self._chunkifier.getRest();
  if (!lastChunk){
    callback();
  } else {
    var now = Date.now();
    var elapsed = now - self._lastPush;
    var period = Math.round(period * (lastChunk.length / self._amount));
    var remaining = Math.max(0, period - elapsed);
    setTimeout(function(){
      self.push(lastChunk);
      self._lastPush = Date.now();
      callback();
    }, remaining);
  }
};

function Chunkifier(capacity){
  this._buffers = [];
  this._capacity = capacity;
}

function tally(tally, chunk){
  return tally + chunk.length;
}

Chunkifier.prototype = {
  size: function(){
    return this._buffers.reduce(tally, 0);
  },
  hasSome: function(){
    return this.size() >= this._capacity;
  },
  getSome: function(){
    if (this.size() < this._capacity){
      return null;
    }
    var buf = new Buffer(this._capacity);
    var filled = 0;
    while (filled < this._capacity){
      var next = this._buffers[0];
      if (next.length > this._capacity - filled){
        // copy some of it, replace it with slice of itself
        var amount = this._capacity - filled;
        this._buffers[0] = next.slice(amount, next.length);
      } else {
        // copy all of it, remove it
        var amount = next.length;
        this._buffers.shift();
      }
      next.copy(buf, filled, 0, amount);
      filled += amount;
    }
    return buf;
  },
  getRest: function(){
    var size = this.size();
    if (size === 0){
      return null;
    }
    var buf = new Buffer(size);
    var filled = 0;
    for (var i=0; i<this._buffers.length; i++){
      var next = this._buffers[i];
      next.copy(buf, filled);
      filled += next.length;
    }
    return buf;
  },
  add: function(chunk){
    this._buffers.push(chunk);
  }
};

module.exports = StreamBrake;
<commit_msg>move scheduling logic into its own function in stream brake<commit_after>/*
 * Copyright (c) 2013 by Greg Reimer <gregreimer@gmail.com>
 * MIT License. See mit-license.txt for more info.
 */

var util = require('util');
var Transform = require('stream').Transform;

// ---------------------------

function StreamBrake(amount, period){
  Transform.call(this);
  this._period = period || 1000;
  this._amount = amount || 1024;
  this._chunkifier = new Chunkifier(this._amount);
  this._transferred = 0;
}

util.inherits(StreamBrake, Transform);

StreamBrake.prototype.timeUntilNext = function(chunk, now){
  /*
   * Schedule the next push at future time such that the actual transfer
   * rate will match the desired transfer rate as closely as possible. To
   * do that we need to calculate the proper amount of elapsed time by
   * solving for that variable.
   *
   * actualRate === targetRate
   * actualRate === amountTransferred / time
   * amountTransferred / time === targetRate
   * amountTransferred === targetRate * time
   * amountTransferred / targetRate === time <--
   */
  var targetRate = this._amount / this._period;
  var amountTransferred = this._transferred + chunk.length;
  var time = amountTransferred / targetRate;
  var elapsed = now - this._started;
  return Math.round(Math.max(0, time - elapsed));
};

StreamBrake.prototype._transform = function(chunk, encoding, callback){
  var self = this;
  self._chunkifier.add(chunk);
  (function next(now){
    var nextChunk = self._chunkifier.getSome();
    if (!nextChunk){
      callback();
    } else {

      if (self._started){
        wait = self.timeUntilNext(nextChunk, now);
      } else {
        self._started = now;
        var wait = self._period;
      }

      setTimeout(function(){
        var now = Date.now()
        self.push(nextChunk);
        self._transferred += nextChunk.length;
        next(now);
      }, wait);
    }
  })(Date.now());
};

StreamBrake.prototype._flush = function(callback){
  var self = this;
  var lastChunk = self._chunkifier.getRest();
  if (!lastChunk){
    callback();
  } else {

    var now = Date.now();
    if (self._started){
      var wait = self.timeUntilNext(lastChunk, now);
    } else {
      self._started = now;
      var wait = Math.round(self._period * (lastChunk.length / self._amount));
    }

    setTimeout(function(){
      self.push(lastChunk);
      callback();
    }, wait);
  }
};

function Chunkifier(capacity){
  this._buffers = [];
  this._capacity = capacity;
}

function tally(tally, chunk){
  return tally + chunk.length;
}

Chunkifier.prototype = {
  size: function(){
    return this._buffers.reduce(tally, 0);
  },
  getSome: function(){
    if (this.size() < this._capacity){
      return null;
    }
    var buf = new Buffer(this._capacity);
    var filled = 0;
    while (filled < this._capacity){
      var next = this._buffers[0];
      if (next.length > this._capacity - filled){
        // copy some of it, replace it with slice of itself
        var amount = this._capacity - filled;
        this._buffers[0] = next.slice(amount, next.length);
      } else {
        // copy all of it, remove it
        var amount = next.length;
        this._buffers.shift();
      }
      next.copy(buf, filled, 0, amount);
      filled += amount;
    }
    return buf;
  },
  getRest: function(){
    var size = this.size();
    if (size === 0){
      return null;
    }
    var buf = new Buffer(size);
    var filled = 0;
    for (var i=0; i<this._buffers.length; i++){
      var next = this._buffers[i];
      next.copy(buf, filled);
      filled += next.length;
    }
    return buf;
  },
  add: function(chunk){
    this._buffers.push(chunk);
  }
};

module.exports = StreamBrake;
<|endoftext|>


<commit_before>module.exports = function(options){

  if(options.payment.stripe) {
    return function setupRoutes(app) {
      require('./routes')(app, options.payment.stripe);
    };
  } else {
    return function setupRoutes() {
      console.log('no support for stripe');
    };
  }

};
<commit_msg>Adding check for options.payment<commit_after>module.exports = function(options) {

  if (options.payment && options.payment.stripe) {
    return function setupRoutes(app) {
      require('./routes')(app, options.payment.stripe);
    };
  } else {
    return function setupRoutes() {
      console.log('no support for stripe');
    };
  }

};
<|endoftext|>