<|start_filename|>Chapter11/11.1/node_modules/electron-rebuild/src/rebuild.js<|end_filename|>
import { spawnPromise } from 'spawn-rx';
import debug from 'debug';
import EventEmitter from 'events';
import fs from 'fs-promise';
import nodeAbi from 'node-abi';
import os from 'os';
import path from 'path';
import readPackageJSON from './read-package-json';

const d = debug('electron-rebuild');

const defaultMode = process.platform === 'win32' ? 'sequential' : 'parallel';

const locateNodeGyp = async () => {
  let testPath = __dirname;
  for (let upDir = 0; upDir <= 20; upDir++) {
    const nodeGypTestPath = path.resolve(testPath, `node_modules/.bin/node-gyp${process.platform === 'win32' ? '.cmd' : ''}`);
    if (await fs.exists(nodeGypTestPath)) {
      return nodeGypTestPath;
    }
    testPath = path.resolve(testPath, '..');
  }
  return null;
};

const _rebuild = async (lifecycle, buildPath, electronVersion, arch = process.arch, extraModules = [], forceRebuild = false, headerURL = 'https://atom.io/download/electron', types = ['prod', 'optional'], mode = defaultMode) => {
  if (!path.isAbsolute(buildPath)) {
    throw new Error('Expected buildPath to be an absolute path');
  }
  d('rebuilding with args:', buildPath, electronVersion, arch, extraModules, forceRebuild, headerURL, types);
  const prodDeps = {};
  const rebuilds = [];
  const ABI = nodeAbi.getAbi(electronVersion, 'electron');
  const nodeGypPath = await locateNodeGyp();
  if (!nodeGypPath) {
    throw new Error('Could locate node-gyp');
  }

  (extraModules || []).forEach((moduleName) => {
    if (!moduleName) return;
    prodDeps[moduleName] = true
  });

  lifecycle.emit('start');

  const rebuildModuleAt = async (modulePath) => {
    if (await fs.exists(path.resolve(modulePath, 'binding.gyp'))) {
      const metaPath = path.resolve(modulePath, 'build', 'Release', '.forge-meta');
      lifecycle.emit('module-found', path.basename(modulePath));
      if (!forceRebuild && await fs.exists(metaPath)) {
        const meta = await fs.readFile(metaPath, 'utf8');
        if (meta === arch) {
          d(`skipping: ${path.basename(modulePath)} as it is already built`);
          lifecycle.emit('module-done');
          lifecycle.emit('module-skip');
          return;
        }
      }
      d('rebuilding:', path.basename(modulePath));
      const rebuildArgs = [
        'rebuild',
        `--target=${electronVersion}`,
        `--arch=${arch}`,
        `--dist-url=${headerURL}`,
        '--build-from-source',
      ];

      const modulePackageJSON = await readPackageJSON(modulePath);
      Object.keys(modulePackageJSON.binary || {}).forEach((binaryKey) => {
        let value = modulePackageJSON.binary[binaryKey];
        if (binaryKey === 'module_path') {
          value = path.resolve(modulePath, value);
        }
        value = value.replace('{configuration}', 'Release')
          .replace('{node_abi}', `electron-v${electronVersion.split('.').slice(0, 2).join('.')}`)
          .replace('{platform}', process.platform)
          .replace('{arch}', arch)
          .replace('{version}', modulePackageJSON.version);
        Object.keys(modulePackageJSON.binary).forEach((binaryReplaceKey) => {
          value = value.replace(`{${binaryReplaceKey}}`, modulePackageJSON.binary[binaryReplaceKey]);
        });
        rebuildArgs.push(`--${binaryKey}=${value}`);
      });

      d('rebuilding', path.basename(modulePath), 'with args', rebuildArgs);
      await spawnPromise(nodeGypPath, rebuildArgs, {
        cwd: modulePath,
        env: Object.assign({}, process.env, {
          HOME: path.resolve(os.homedir(), '.electron-gyp'),
          USERPROFILE: path.resolve(os.homedir(), '.electron-gyp'),
          npm_config_disturl: 'https://atom.io/download/electron',
          npm_config_runtime: 'electron',
          npm_config_arch: arch,
          npm_config_target_arch: arch,
          npm_config_build_from_source: true,
        }),
      });

      d('built:', path.basename(modulePath));
      await fs.mkdirs(path.dirname(metaPath));
      await fs.writeFile(metaPath, arch);

      const moduleName = path.basename(modulePath);
      d('searching for .node file', path.resolve(modulePath, 'build/Release'));
      d('testing files', (await fs.readdir(path.resolve(modulePath, 'build/Release'))));
      const nodePath = path.resolve(modulePath, 'build/Release',
        (await fs.readdir(path.resolve(modulePath, 'build/Release')))
          .find((file) => file !== '.node' && file.endsWith('.node'))
        );
      const abiPath = path.resolve(modulePath, `bin/${process.platform}-${arch}-${ABI}`);
      if (await fs.exists(nodePath)) {
        d('found .node file', nodePath);
        d('copying to prebuilt place:', abiPath);
        await fs.mkdirs(abiPath);
        await fs.copy(nodePath, path.resolve(abiPath, `${moduleName}.node`));
      }
      lifecycle.emit('module-done');
    }
  };

  const rebuildAllModulesIn = (nodeModulesPath, prefix = '') => {
    d('scanning:', nodeModulesPath);
    for (const modulePath of fs.readdirSync(nodeModulesPath)) {
      if (prodDeps[`${prefix}${modulePath}`]) {
        rebuilds.push(() => rebuildModuleAt(path.resolve(nodeModulesPath, modulePath)));
      }
      if (modulePath.startsWith('@')) {
        rebuildAllModulesIn(path.resolve(nodeModulesPath, modulePath), `${modulePath}/`);
      }
      if (fs.existsSync(path.resolve(nodeModulesPath, modulePath, 'node_modules'))) {
        rebuildAllModulesIn(path.resolve(nodeModulesPath, modulePath, 'node_modules'));
      }
    }
  };

  const findModule = async (moduleName, fromDir, foundFn) => {
    let targetDir = fromDir;
    const foundFns = [];

    while (targetDir !== path.dirname(buildPath)) {
      const testPath = path.resolve(targetDir, 'node_modules', moduleName);
      if (await fs.exists(testPath)) {
        foundFns.push(foundFn(testPath));
      }
      targetDir = path.dirname(targetDir);
    }
    await Promise.all(foundFns);
  };

  const markChildrenAsProdDeps = async (modulePath) => {
    if (!await fs.exists(modulePath)) return;
    d('exploring', modulePath);
    const childPackageJSON = await readPackageJSON(modulePath);
    const moduleWait = [];

    Object.keys(childPackageJSON.dependencies || {}).concat(Object.keys(childPackageJSON.optionalDependencies || {})).forEach((key) => {
      if (prodDeps[key]) return;
      prodDeps[key] = true;
      moduleWait.push(findModule(key, modulePath, markChildrenAsProdDeps));
    });
    await Promise.all(moduleWait);
  };

  const rootPackageJSON = await readPackageJSON(buildPath);
  const markWaiters = [];
  const depKeys = [];
  if (types.indexOf('prod') !== -1) {
    depKeys.push(...Object.keys(rootPackageJSON.dependencies || {}));
  }
  if (types.indexOf('optional') !== -1) {
    depKeys.push(...Object.keys(rootPackageJSON.optionalDependencies || {}));
  }
  if (types.indexOf('dev') !== -1) {
    depKeys.push(...Object.keys(rootPackageJSON.devDependencies || {}));
  }
  depKeys.forEach((key) => {
    prodDeps[key] = true;
    markWaiters.push(markChildrenAsProdDeps(path.resolve(buildPath, 'node_modules', key)));
  });

  await Promise.all(markWaiters);

  d('identified prod deps:', prodDeps);

  rebuildAllModulesIn(path.resolve(buildPath, 'node_modules'));

  if (mode !== 'sequential') {
    await Promise.all(rebuilds.map(fn => fn()));
  } else {
    for (const rebuildFn of rebuilds) {
      await rebuildFn();
    }
  }
};

const rebuild = (...args) => {
  const lifecycle = new EventEmitter();
  d('rebuilding with args:', args);
  const rebuilder = _rebuild(lifecycle, ...args);
  rebuilder.lifecycle = lifecycle;
  return rebuilder;
}

export const rebuildNativeModules = (electronVersion, modulePath, whichModule='', headersDir=null, arch=process.arch, command, ignoreDevDeps=false, ignoreOptDeps=false, verbose=false) => {
  if (path.basename(modulePath) === 'node_modules') {
    modulePath = path.dirname(modulePath);
  }
  d('rebuilding in:', modulePath);
  console.warn('You are using the old API, please read the new docs and update to the new API');
  return rebuild(modulePath, electronVersion, arch, whichModule.split(','));
};

export default rebuild;


<|start_filename|>Chapter07/7.2/test.js<|end_filename|>
describe('my app', () => {
  beforeEach(() => {
    document.body.innerHTML = `
      <div id="app"></div>
    `
    new Vue(myApp)
      .$mount('#app')
  })
  it('should say Hello World', () => {
    expect(document.querySelector('p').innerText)
      .toContain('Hello World')  })
})


<|start_filename|>Chapter11/11.1/node_modules/spawn-rx/src/index.js<|end_filename|>
import path from 'path';
import net from 'net';
import sfs from 'fs';

import 'rxjs/add/observable/of';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/pluck';
import 'rxjs/add/operator/reduce';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { AsyncSubject } from 'rxjs/AsyncSubject';

const spawnOg = require('child_process').spawn;
const isWindows = process.platform === 'win32';

const d = require('debug')('spawn-rx');

/**
 * stat a file but don't throw if it doesn't exist
 *
 * @param  {string} file The path to a file
 * @return {Stats}       The stats structure
 *
 * @private
 */
function statSyncNoException(file) {
  try {
    return sfs.statSync(file);
  } catch (e) {
    return null;
  }
}

/**
 * Search PATH to see if a file exists in any of the path folders.
 *
 * @param  {string} exe The file to search for
 * @return {string}     A fully qualified path, or the original path if nothing
 *                      is found
 *
 * @private
 */
function runDownPath(exe) {
  // NB: Windows won't search PATH looking for executables in spawn like
  // Posix does

  // Files with any directory path don't get this applied
  if (exe.match(/[\\\/]/)) {
    d('Path has slash in directory, bailing');
    return exe;
  }

  let target = path.join('.', exe);
  if (statSyncNoException(target)) {
    d(`Found executable in currect directory: ${target}`);
    return target;
  }

  let haystack = process.env.PATH.split(isWindows ? ';' : ':');
  for (let p of haystack) {
    let needle = path.join(p, exe);
    if (statSyncNoException(needle)) return needle;
  }

  d('Failed to find executable anywhere in path');
  return exe;
}

/**
 * Finds the actual executable and parameters to run on Windows. This method
 * mimics the POSIX behavior of being able to run scripts as executables by
 * replacing the passed-in executable with the script runner, for PowerShell,
 * CMD, and node scripts.
 *
 * This method also does the work of running down PATH, which spawn on Windows
 * also doesn't do, unlike on POSIX.
 *
 * @param  {string} exe           The executable to run
 * @param  {Array<string>} args   The arguments to run
 *
 * @return {Object}               The cmd and args to run
 * @property {string} cmd         The command to pass to spawn
 * @property {Array<string>} args The arguments to pass to spawn
 */
export function findActualExecutable(exe, args) {
  // POSIX can just execute scripts directly, no need for silly goosery
  if (process.platform !== 'win32') return { cmd: runDownPath(exe), args: args };

  if (!sfs.existsSync(exe)) {
    // NB: When you write something like `surf-client ... -- surf-build` on Windows,
    // a shell would normally convert that to surf-build.cmd, but since it's passed
    // in as an argument, it doesn't happen
    const possibleExts = ['.exe', '.bat', '.cmd', '.ps1'];
    for (let ext of possibleExts) {
      let possibleFullPath = runDownPath(`${exe}${ext}`);

      if (sfs.existsSync(possibleFullPath)) {
        return findActualExecutable(possibleFullPath, args);
      }
    }
  }

  if (exe.match(/\.ps1$/i)) {
    let cmd = path.join(process.env.SYSTEMROOT, 'System32', 'WindowsPowerShell', 'v1.0', 'PowerShell.exe');
    let psargs = ['-ExecutionPolicy', 'Unrestricted', '-NoLogo', '-NonInteractive', '-File', exe];

    return { cmd: cmd, args: psargs.concat(args) };
  }

  if (exe.match(/\.(bat|cmd)$/i)) {
    let cmd = path.join(process.env.SYSTEMROOT, 'System32', 'cmd.exe');
    let cmdArgs = ['/C', exe, ...args];

    return { cmd: cmd, args: cmdArgs };
  }

  if (exe.match(/\.(js)$/i)) {
    let cmd = process.execPath;
    let nodeArgs = [exe];

    return { cmd: cmd, args: nodeArgs.concat(args) };
  }

  // Dunno lol
  return { cmd: exe, args: args };
}

/**
 * Spawns a process but detached from the current process. The process is put
 * into its own Process Group that can be killed by unsubscribing from the
 * return Observable.
 *
 * @param  {string} exe               The executable to run
 * @param  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Observable<string>}       Returns an Observable that when subscribed
 *                                    to, will create a detached process. The
 *                                    process output will be streamed to this
 *                                    Observable, and if unsubscribed from, the
 *                                    process will be terminated early. If the
 *                                    process terminates with a non-zero value,
 *                                    the Observable will terminate with onError.
 */
export function spawnDetached(exe, params, opts=null) {
  let { cmd, args } = findActualExecutable(exe, params);

  if (!isWindows) return spawn(cmd, args, Object.assign({}, opts || {}, {detached: true }));
  const newParams = [cmd].concat(args);

  let target = path.join(__dirname, '..', 'vendor', 'jobber', 'jobber.exe');
  let options = Object.assign({}, opts || {}, { detached: true, jobber: true });

  d(`spawnDetached: ${target}, ${newParams}`);
  return spawn(target, newParams, options);
}


/**
 * Spawns a process attached as a child of the current process.
 *
 * @param  {string} exe               The executable to run
 * @param  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Observable<string>}       Returns an Observable that when subscribed
 *                                    to, will create a child process. The
 *                                    process output will be streamed to this
 *                                    Observable, and if unsubscribed from, the
 *                                    process will be terminated early. If the
 *                                    process terminates with a non-zero value,
 *                                    the Observable will terminate with onError.
 */
export function spawn(exe, params=[], opts=null) {
  opts = opts || {};
  let spawnObs = Observable.create((subj) => {
    let proc = null;

    let { cmd, args } = findActualExecutable(exe, params);
    d(`spawning process: ${cmd} ${args.join()}, ${JSON.stringify(opts)}`);
    let origOpts = Object.assign({}, opts);
    if ('jobber' in origOpts) delete origOpts.jobber;
    if ('split' in origOpts) delete origOpts.split;


    proc = spawnOg(cmd, args, origOpts);

    let bufHandler = (source) => (b) => {
      if (b.length < 1) return;
      let chunk = "<< String sent back was too long >>";
      try {
        chunk = b.toString();
      } catch (e) {
        chunk = `<< Lost chunk of process output for ${exe} - length was ${b.length}>>`;
      }

      subj.next({source: source, text: chunk});
    };

    let ret = new Subscription();

    if (opts.stdin) {
      if (proc.stdin) {
        ret.add(opts.stdin.subscribe(
          (x) => proc.stdin.write(x),
          subj.error,
          () => proc.stdin.end()
        ));
      } else {
        subj.error(new Error(`opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required`));
      }
    }

    let stderrCompleted = null;
    let stdoutCompleted = null;
    let noClose = false;

    if (proc.stdout) {
      stdoutCompleted = new AsyncSubject();
      proc.stdout.on('data', bufHandler('stdout'));
      proc.stdout.on('close', () => { stdoutCompleted.next(true); stdoutCompleted.complete(); });
    } else {
      stdoutCompleted = Observable.of(true);
    }

    if (proc.stderr) {
      stderrCompleted = new AsyncSubject();
      proc.stderr.on('data', bufHandler('stderr'));
      proc.stderr.on('close', () => { stderrCompleted.next(true); stderrCompleted.complete(); });
    } else {
      stderrCompleted = Observable.of(true);
    }

    proc.on('error', (e) => {
      noClose = true;
      subj.error(e);
    });

    proc.on('close', (code) => {
      noClose = true;
      let pipesClosed = Observable.merge(stdoutCompleted, stderrCompleted)
        .reduce((acc) => acc, true);

      if (code === 0) {
        pipesClosed.subscribe(() => subj.complete());
      } else {
        pipesClosed.subscribe(() => subj.error(new Error(`Failed with exit code: ${code}`)));
      }
    });

    ret.add(new Subscription(() => {
      if (noClose) return;

      d(`Killing process: ${cmd} ${args.join()}`);
      if (opts.jobber) {
        // NB: Connecting to Jobber's named pipe will kill it
        net.connect(`\\\\.\\pipe\\jobber-${proc.pid}`);
        setTimeout(() => proc.kill(), 5*1000);
      } else {
        proc.kill();
      }
    }));

    return ret;
  });

  return opts.split ? spawnObs : spawnObs.pluck('text');
}

function wrapObservableInPromise(obs) {
  return new Promise((res, rej) => {
    let out = '';

    obs.subscribe(
      (x) => out += x,
      (e) => rej(new Error(`${out}\n${e.message}`)),
      () => res(out));
  });
}

/**
 * Spawns a process but detached from the current process. The process is put
 * into its own Process Group.
 *
 * @param  {string} exe               The executable to run
 * @param  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Promise<string>}       Returns an Promise that represents a detached
 *                                 process. The value returned is the process
 *                                 output. If the process terminates with a
 *                                 non-zero value, the Promise will resolve with
 *                                 an Error.
 */
export function spawnDetachedPromise(exe, params, opts=null) {
  return wrapObservableInPromise(spawnDetached(exe, params, opts));
}


/**
 * Spawns a process as a child process.
 *
 * @param  {string} exe               The executable to run
 * @param  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Promise<string>}       Returns an Promise that represents a child
 *                                 process. The value returned is the process
 *                                 output. If the process terminates with a
 *                                 non-zero value, the Promise will resolve with
 *                                 an Error.
 */
export function spawnPromise(exe, params, opts=null) {
  return wrapObservableInPromise(spawn(exe, params, opts));
}


<|start_filename|>Chapter07/7.2/myApp.js<|end_filename|>
const myApp = {
  template: `
    <div>
        <p>{{greetings}}</p>
    </div>
  `,
  data: {
    greetings: '<NAME>'
  }
}

<|start_filename|>Chapter07/7.7/tests/test.js<|end_filename|>
module.exports = {
  'Demo test Google' : function (client) {
    client
      .url('http://localhost:8080')
      .waitForElementVisible('#app', 1000)
      .assert.containsText('h2', 'Welcome to')
      .assert.hidden('p')
      .moveToElement('tag name', 'button', 0, 0)
      .doubleClick()
      .waitForElementVisible('p', 1000)
      .assert.containsText('p', 'Nightwatch')
      .end();
  }
}
/*
 start selenium-standalone
 start http-server
 nightwatch
*/

<|start_filename|>Chapter11/11.1/node_modules/spawn-rx/test/spawn.js<|end_filename|>
import './support';

import { spawn, spawnPromise, spawnDetachedPromise } from '../src/index';

import { Observable } from 'rxjs';

const uuidRegex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;

describe('The spawnPromise method', function() {
  it('should return a uuid when we call uuid', async function() {
    // NB: Since we get run via npm run test, we know that npm bins are in our
    // PATH.
    let result = await spawnPromise('uuid', []);
    expect(result.match(uuidRegex)).to.be.ok;
  });
});

describe('The spawnDetachedPromise method', function() {
  it('should return a uuid when we call uuid', async function() {
    // NB: Since we get run via npm run test, we know that npm bins are in our
    // PATH.
    let result = await spawnDetachedPromise('uuid', ['--help']);
    expect(result.length > 10).to.be.ok;
  });
});


function wrapSplitObservableInPromise(obs) {
  return new Promise((res) => {
    let out = {stderr: '', stdout: ''};

    obs.subscribe(
      (x) => {
        if (x.source === 'stdout')
          out.stdout += x.text;
        else
          out.stderr += x.text;
      },
      (e) => { out.error = e; res(out); },
      () => res(out));
  });
}

describe('The spawn method', function() {
  it('should return a disposable subscription', async function() {
    // this only check the unsubscribe goes w/o error, not that the spawned process is killed
    // (difficult to do that, maybe iterate through child processes and check ?)
    spawn('sleep', ['2']).subscribe().unsubscribe();
  });

  it('should return split stderr in a inner tag when called with split', async function() {
    // provide an invalid param to uuid so it complains on stderr
    let rxSpawn = spawn('uuid', ['foo'], {split: true});
    let result = await wrapSplitObservableInPromise(rxSpawn);
    expect(result.stderr.length > 10).to.be.ok;
    expect(result.stdout).to.be.empty;
    expect(result.error).to.be.an('error');
  });

  it('should return split stdout in a inner tag when called with split', async function() {
    let rxSpawn = spawn('uuid', [], {split: true});
    let result = await wrapSplitObservableInPromise(rxSpawn);
    expect(result.stdout.match(uuidRegex)).to.be.ok;
    expect(result.stderr).to.be.empty;
    expect(result.error).to.be.undefined;
  });

  it('should ignore stderr if options.stdio = ignore', async function() {
    let rxSpawn = spawn('uuid', ['foo'], {split: true, stdio: [null, null, 'ignore']});
    let result = await wrapSplitObservableInPromise(rxSpawn);
    expect(result.stderr).to.be.empty;
  });

  it('should ignore stdout if options.stdio = inherit', async function() {
    let rxSpawn = spawn('uuid', [], {split: true, stdio: [null, 'inherit', null]});
    let result = await wrapSplitObservableInPromise(rxSpawn);
    expect(result.stdout).to.be.empty;
  });
  
  it('should croak if stdin is provided but stdio.stdin is disabled', async function() {
    let stdin = Observable.of('a');
    let rxSpawn = spawn('marked', [], {split: true, stdin: stdin, stdio: ['ignore', null, null]});
    let result = await wrapSplitObservableInPromise(rxSpawn);
    expect(result.error).to.be.an('error');
  });
  
  it('should subscribe to provided stdin', async function() {
    let stdin = Observable.of('a');
    let rxSpawn = spawn('marked', [], {split: true, stdin: stdin});
    let result = await wrapSplitObservableInPromise(rxSpawn);
    expect(result.stdout.trim()).to.be.equal('<p>a</p>');
  });

});


<|start_filename|>Chapter11/11.4/vue_app/node_modules/clarifai/src/constants.js<|end_filename|>
const MAX_BATCH_SIZE = 128;
const GEO_LIMIT_TYPES = ['withinMiles', 'withinKilometers', 'withinRadians', 'withinDegrees'];
const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/i;
const SYNC_TIMEOUT = 60000;
const MODEL_QUEUED_FOR_TRAINING = '21103';
const MODEL_TRAINING = '21101';
const POLLTIME = 2000;

module.exports = {
  API: {
    TOKEN_PATH: '/v2/token',
    MODELS_PATH: '/v2/models',
    MODEL_PATH: '/v2/models/$0',
    MODEL_VERSIONS_PATH: '/v2/models/$0/versions',
    MODEL_VERSION_PATH: '/v2/models/$0/versions/$1',
    MODEL_PATCH_PATH: '/v2/models/$0/output_info/data/concepts',
    MODEL_OUTPUT_PATH: '/v2/models/$0/output_info',
    MODEL_SEARCH_PATH: '/v2/models/searches',
    PREDICT_PATH: '/v2/models/$0/outputs',
    VERSION_PREDICT_PATH: '/v2/models/$0/versions/$1/outputs',
    CONCEPTS_PATH: '/v2/concepts',
    CONCEPT_PATH: '/v2/concepts/$0',
    CONCEPT_SEARCH_PATH: '/v2/concepts/searches',
    MODEL_INPUTS_PATH: '/v2/models/$0/inputs',
    MODEL_VERSION_INPUTS_PATH: '/v2/models/$0/versions/$1/inputs',
    INPUTS_PATH: '/v2/inputs',
    INPUT_PATH: '/v2/inputs/$0',
    INPUTS_STATUS_PATH: '/v2/inputs/status',
    SEARCH_PATH: '/v2/searches'
  },
  ERRORS: {
    paramsRequired: (param) => {
      let paramList = Array.isArray(param) ? param: [param];
      return new Error(`The following ${paramList.length > 1? 'params are': 'param is'} required: ${paramList.join(', ')}`);
    },
    MAX_INPUTS: new Error(`Number of inputs passed exceeded max of ${MAX_BATCH_SIZE}`),
    INVALID_GEOLIMIT_TYPE: new Error(`Incorrect geo_limit type. Value must be any of the following: ${GEO_LIMIT_TYPES.join(', ')}`),
    INVALID_DELETE_ARGS: new Error(`Wrong arguments passed. You can only delete all models (provide no arguments), delete select models (provide list of ids),
    delete a single model (providing a single id) or delete a model version (provide a single id and version id)`)
  },
  STATUS: {
    MODEL_QUEUED_FOR_TRAINING,
    MODEL_TRAINING
  },
  // var replacement must be given in order
  replaceVars: (path, vars=[])=> {
    let newPath = path;
    vars.forEach((val, index)=> {
      if (index === 0) {
        val = encodeURIComponent(val);
      }
      newPath = newPath.replace(new RegExp(`\\$${index}`, 'g'), val);
    });
    return newPath;
  },
  GEO_LIMIT_TYPES,
  MAX_BATCH_SIZE,
  URL_REGEX,
  SYNC_TIMEOUT,
  POLLTIME
};


<|start_filename|>Chapter11/11.1/node_modules/karma-electron/test/integration-test/karma.conf.js<|end_filename|>
// Karma configuration
// Generated on Thu Mar 03 2016 19:57:50 GMT-0600 (CST)
var Set = require('collections/set');
module.exports = function (config) {
  // Set up default files to test against
  var karmaTest = 'karma-test.js';
  var successTest = 'success-test.js';
  var phantomJsTest = 'phantomjs-test.js';
  var eofCommentTest = 'eof-comment-test.js';
  var failureTest = 'failure-test.js';
  var sourceMapTest = 'source-map-test.js';
  var uncaughtExceptionTest = 'uncaught-exception-test.js';
  var nodeCommonTest = 'node-common-test.js';
  var nodeRequireTest = 'node-require-test.js';
  var nodeScriptSrcTest = 'node-script-src-test.js';
  var customContextFileTest = 'custom-context-file-test.js';
  var filenameOverrideTest = 'filename-override-test.js';
  var testFiles = ['*-test.js'];
  var excludeFiles = new Set([
    customContextFileTest, failureTest, filenameOverrideTest, karmaTest,
    nodeRequireTest, phantomJsTest, sourceMapTest, uncaughtExceptionTest]);

  // If we are testing uncaught exceptions, then update our tests
  if (process.env.TEST_TYPE === 'UNCAUGHT_EXCEPTION') {
    testFiles = [uncaughtExceptionTest];
    excludeFiles.delete(uncaughtExceptionTest);
  } else if (process.env.TEST_TYPE === 'EOF_COMMENT') {
    testFiles = [eofCommentTest];
    excludeFiles.delete(eofCommentTest);
  } else if (process.env.TEST_TYPE === 'FAILURE') {
    testFiles = [failureTest];
    excludeFiles.delete(failureTest);
  } else if (process.env.TEST_TYPE === 'KARMA') {
    testFiles = [karmaTest];
    excludeFiles.delete(karmaTest);
  } else if (process.env.TEST_TYPE === 'PHANTOMJS') {
    testFiles = [successTest, phantomJsTest];
    excludeFiles = new Set();
  } else if (process.env.TEST_TYPE === 'SOURCE_MAP') {
    testFiles = [sourceMapTest];
    excludeFiles.delete(sourceMapTest);
  } else if (process.env.TEST_TYPE === 'CUSTOM_CONTEXT_FILE') {
    testFiles = [customContextFileTest];
    excludeFiles.delete(customContextFileTest);
  } else if (process.env.TEST_TYPE === 'FILENAME_OVERRIDE') {
    testFiles = [filenameOverrideTest];
    excludeFiles.delete(filenameOverrideTest);
  } else if (process.env.TEST_TYPE === 'NODE_REQUIRE') {
    testFiles = [nodeCommonTest, nodeRequireTest];
    excludeFiles.add(nodeScriptSrcTest);
    excludeFiles.delete(nodeRequireTest);
  } else if (process.env.TEST_TYPE) {
    throw new Error('Unrecognized test type "' + process.env.TEST_TYPE + '"');
  }

  // Define our config
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // Custom context and debug files
    customContextFile: process.env.TEST_TYPE === 'CUSTOM_CONTEXT_FILE' ?
      __dirname + '/test-files/custom-context.html' : null,
    customDebugFile: process.env.TEST_TYPE === 'CUSTOM_CONTEXT_FILE' ?
      __dirname + '/test-files/custom-debug.html' : null,

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: testFiles,

    // list of files to exclude
    exclude: excludeFiles.toArray(),

    browserNoActivityTimeout: 2000,
    client: {
      // DEV: We use `client` as these options affect the client side of `karma`
      //   Based on https://github.com/karma-runner/karma-mocha/tree/v1.1.1#configuration
      __filenameOverride: process.env.TEST_TYPE === 'FILENAME_OVERRIDE' ?
        __dirname + '/test-files/filename-override-context.html' : null,
      loadScriptsViaRequire: process.env.TEST_TYPE === 'NODE_REQUIRE',
      useIframe: false
    },

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '*-test.js': ['electron']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Electron'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    // Load in our module as a plugin
    // https://github.com/karma-runner/karma-chrome-launcher/blob/v0.2.2/examples/simple/karma.conf.js
    plugins: [
        require('../../'),
        'karma-mocha',
        'karma-phantomjs-launcher'
    ]
  });
};


<|start_filename|>Chapter11/11.4/vue_app/node_modules/clarifai/dist/Input.js<|end_filename|>
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var axios = require('axios');
var Concepts = require('./Concepts');

var _require = require('./constants'),
    API = _require.API;

var INPUTS_PATH = API.INPUTS_PATH;

/**
* class representing an input
* @class
*/

var Input = function () {
  function Input(_config, data) {
    _classCallCheck(this, Input);

    this.id = data.id;
    this.createdAt = data.created_at || data.createdAt;
    this.imageUrl = data.data.image.url;
    this.concepts = new Concepts(_config, data.data.concepts);
    this.score = data.score;
    this.metadata = data.data.metadata;
    if (data.data.geo && data.data.geo['geo_point']) {
      this.geo = { geoPoint: data.data.geo['geo_point'] };
    }
    this.rawData = data;
    this._config = _config;
  }
  /**
  * Merge concepts to an input
  * @param {object[]}         concepts    Object with keys explained below:
  *   @param {object}           concepts[].concept
  *     @param {string}           concepts[].concept.id        The concept id (required)
  *     @param {boolean}          concepts[].concept.value     Whether or not the input is a positive (true) or negative (false) example of the concept (default: true)
  * @param {object}           metadata                      Object with key values to attach to the input (optional)
  * @return {Promise(Input, error)} A Promise that is fulfilled with an instance of Input or rejected with an error
  */


  _createClass(Input, [{
    key: 'mergeConcepts',
    value: function mergeConcepts(concepts, metadata) {
      return this._update('merge', concepts, metadata);
    }
    /**
    * Delete concept from an input
    * @param {object[]}         concepts    Object with keys explained below:
    *   @param {object}           concepts[].concept
    *     @param {string}           concepts[].concept.id        The concept id (required)
    *     @param {boolean}          concepts[].concept.value     Whether or not the input is a positive (true) or negative (false) example of the concept (default: true)
    * @param {object}           metadata                      Object with key values to attach to the input (optional)
    * @return {Promise(Input, error)} A Promise that is fulfilled with an instance of Input or rejected with an error
    */

  }, {
    key: 'deleteConcepts',
    value: function deleteConcepts(concepts, metadata) {
      return this._update('remove', concepts, metadata);
    }
    /**
    * Overwrite inputs
    * @param {object[]}         concepts                      Array of object with keys explained below:
    *   @param {object}           concepts[].concept
    *     @param {string}           concepts[].concept.id         The concept id (required)
    *     @param {boolean}          concepts[].concept.value      Whether or not the input is a positive (true) or negative (false) example of the concept (default: true)
    * @param {object}           metadata                      Object with key values to attach to the input (optional)
    * @return {Promise(Input, error)} A Promise that is fulfilled with an instance of Input or rejected with an error
    */

  }, {
    key: 'overwriteConcepts',
    value: function overwriteConcepts(concepts, metadata) {
      return this._update('overwrite', concepts, metadata);
    }
  }, {
    key: '_update',
    value: function _update(action) {
      var concepts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var metadata = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      var url = '' + this._config.apiEndpoint + INPUTS_PATH;
      var inputData = {};
      if (concepts.length) {
        inputData.concepts = concepts;
      }
      if (metadata !== null) {
        inputData.metadata = metadata;
      }
      var data = {
        action: action,
        inputs: [{
          id: this.id,
          data: inputData
        }]
      };
      return wrapToken(this._config, function (headers) {
        return new Promise(function (resolve, reject) {
          return axios.patch(url, data, { headers: headers }).then(function (response) {
            if (isSuccess(response)) {
              resolve(new Input(response.data.input));
            } else {
              reject(response);
            }
          }, reject);
        });
      });
    }
  }]);

  return Input;
}();

;

module.exports = Input;

<|start_filename|>Chapter11/11.1/node_modules/electron-rebuild/src/read-package-json.js<|end_filename|>
import fs from 'fs-promise';
import path from 'path';

export default async (dir, safe = false) => {
  let packageData;
  try {
    packageData = await fs.readFile(path.resolve(dir, 'package.json'), 'utf8');
  } catch (err) {
    if (safe) {
      packageData = '{}';
    } else {
      throw err;
    }
  }
  return JSON.parse(packageData);
};


<|start_filename|>Chapter11/11.1/app/src/renderer/main.js<|end_filename|>
import Vue from 'vue'
import Electron from 'vue-electron'

Vue.use(Electron)
Vue.config.debug = true

import App from './App'

/* eslint-disable no-new */
new Vue({
  ...App
}).$mount('#app')


<|start_filename|>Chapter10/10.7/src/store/actions.js<|end_filename|>
import axios from 'axios'

const actions = {
  downloadNew ({ commit }) {
    axios.get('/myNewPosts')
      .then(({ data }) => {
        commit('ADD_ITEMS', data)
      })
  }
}

export default actions


<|start_filename|>Chapter11/11.3/test/services/se/index.test.js<|end_filename|>
'use strict';

const assert = require('assert');
const app = require('../../../src/app');

describe('se service', function() {
  it('registered the ses service', () => {
    assert.ok(app.service('ses'));
  });
});


<|start_filename|>Chapter11/11.4/vue_app/node_modules/clarifai/src/index.js<|end_filename|>
let App = require('./App');
let {version} = require('./../package.json');

module.exports = global.Clarifai = {
  version,
  App,
  GENERAL_MODEL: 'aaa03c23b3724a16a56b629203edc62c',
  FOOD_MODEL: 'bd367be194cf45149e75f01d59f77ba7',
  TRAVEL_MODEL: 'eee28c313d69466f836ab83287a54ed9',
  NSFW_MODEL: 'e9576d86d2004ed1a38ba0cf39ecb4b1',
  WEDDINGS_MODEL: 'c386b7a870114f4a87477c0824499348',
  COLOR_MODEL: 'eeed0b6733a644cea07cf4c60f87ebb7',
  CLUSTER_MODEL: 'cccbe437d6e54e2bb911c6aa292fb072',
  FACE_DETECT_MODEL: 'a403429f2ddf4b49b307e318f00e528b',
  BLUR: 'ddd9d34872ab32be9f0e3b2b98a87be2'
};


<|start_filename|>Chapter07/7.5/test.js<|end_filename|>
describe('my app', () => {
  let vm
  beforeEach(() => {
    vm = new Vue({
      template: `
        <div>
          <input id="name" v-model="name">
          <p>Hello from <span id="output">{{name}}</span></p>
        </div>
      `,
      data: {
        name: undefined
      }
    }).$mount()
  })
  it('should display Hello from Herman after Herman is typed in the text-box', done => {
    const outputEl = vm.$el.querySelector('#output')
    vm.$el.querySelector('#name').value = 'Herman'
    expect(vm.name = 'Herman')
    expect(outputEl.textContent).not.toContain('Herman')
    vm.$nextTick(() => {
      expect(outputEl.textContent).toContain('Herman')
      done()
    })
  })
})

<|start_filename|>Chapter03/3.4/index.html<|end_filename|>

<!DOCTYPE html>
<html>
<head>

  <script type="text/javascript" src="https://vuejs.org/js/vue.js"></script>

  <style type="text/css">
    img {
  float: left;
  padding: 5px
}
.v-enter {
  opacity: 0
}
.v-enter-active {
  transition: opacity 5s
}
  </style>

  <title>3.4.1 (2) by gurghet</title>
</head>

<body>
  <h1>
  The Fill Murray Page
</h1>
<div id="app">
  <transition appear>
    <img src="https://fillmurray.com/50/70" width="50" height="70">
  </transition>
  <p>
    The internet was missing the ability to provide custom-sized placeholder images of <NAME>. Now it can.
  </p>
</div>
  
<script>
new Vue({
	el: '#app',
  data: {
  	msg: 'hello'
  }
})
</script>

</body>

</html>



<|start_filename|>Chapter11/11.3/node_modules/feathers-hooks-common/lib/bundled.js<|end_filename|>
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.lowerCase = lowerCase;
exports.removeQuery = removeQuery;
exports.pluckQuery = pluckQuery;
exports.remove = remove;
exports.pluck = pluck;
exports.disable = disable;
exports.legacyPopulate = legacyPopulate;

var _utils = require('./utils');

/* eslint-env es6, node */
/* eslint brace-style: 0, consistent-return: 0, no-console: 0, no-param-reassign: 0, no-var: 0 */

var errors = require('feathers-errors').errors;


/**
 * Lowercase the given fields either in the data submitted (as a before hook for create,
 * update or patch) or in the result (as an after hook). If the data is an array or
 * a paginated find result the hook will lowercase the field for every item.
 *
 * @param {Array.<string|Function>} fields - Field names to lowercase. Dot notation is supported.
 * @returns {Function} hook function(hook).
 *
 * DEPRECATED: The last param may be a function to determine if the current hook should be updated.
 * Its signature is func(hook) and it returns either a boolean or a promise resolving to a boolean.
 * This boolean determines if the hook is updated.
 *
 * hooks.lowerCase('group', hook => hook.data.status === 1);
 * hooks.lowerCase('group', hook => new Promise(resolve => {
 *   setTimeout(() => { resolve(true); }, 100)
 * }));
 *
 */
function lowerCase() {
  for (var _len = arguments.length, fields = Array(_len), _key = 0; _key < _len; _key++) {
    fields[_key] = arguments[_key];
  }

  var lowerCaseFields = function lowerCaseFields(data) {
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var field = _step.value;

        var value = (0, _utils.getByDot)(data, field);

        if (value !== undefined) {
          if (typeof value !== 'string' && value !== null) {
            throw new errors.BadRequest('Expected string data. (lowercase ' + field + ')');
          }

          (0, _utils.setByDot)(data, field, value ? value.toLowerCase() : value);
        }
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator.return) {
          _iterator.return();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }
  };

  var callback = function callback() {
    return true;
  };
  if (typeof fields[fields.length - 1] === 'function') {
    callback = fields.pop();
    console.error('DEPRECATED Predicate func will be removed next version. (lowerCase)');
  }

  return function (hook) {
    var items = hook.type === 'before' ? hook.data : hook.result;

    var update = function update(condition) {
      if (items && condition) {
        if (hook.method === 'find' || Array.isArray(items)) {
          // data.data if the find method is paginated
          (items.data || items).forEach(lowerCaseFields);
        } else {
          lowerCaseFields(items);
        }
      }
      return hook;
    };

    var check = callback(hook);

    return check && typeof check.then === 'function' ? check.then(update) : update(check);
  };
}

/**
 * Remove the given fields from the query params.
 * Can be used as a before hook for any service method.
 *
 * @param {Array.<string|Function>} fields - Field names to remove. Dot notation is supported.
 * @returns {Function} hook function(hook)
 *
 * DEPRECATED: The last param may be a function to determine if the current hook should be updated.
 * Its signature is func(hook) and it returns either a boolean or a promise resolving to a boolean.
 * This boolean determines if the hook is updated.
 *
 * hooks.lowerCase('group', hook => hook.data.status === 1);
 * hooks.lowerCase('group', hook => new Promise(resolve => {
 *   setTimeout(() => { resolve(true); }, 100)
 * }));
 */
function removeQuery() {
  for (var _len2 = arguments.length, fields = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    fields[_key2] = arguments[_key2];
  }

  var removeQueries = function removeQueries(data) {
    var _iteratorNormalCompletion2 = true;
    var _didIteratorError2 = false;
    var _iteratorError2 = undefined;

    try {
      for (var _iterator2 = fields[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
        var field = _step2.value;

        var value = (0, _utils.getByDot)(data, field); // prevent setByDot creating nested empty objects
        if (value !== undefined) {
          (0, _utils.setByDot)(data, field, undefined, true);
        }
      }
    } catch (err) {
      _didIteratorError2 = true;
      _iteratorError2 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion2 && _iterator2.return) {
          _iterator2.return();
        }
      } finally {
        if (_didIteratorError2) {
          throw _iteratorError2;
        }
      }
    }
  };

  var callback = function callback() {
    return true;
  };
  if (typeof fields[fields.length - 1] === 'function') {
    callback = fields.pop();
    console.error('DEPRECATED Predicate func will be removed next version. (removeQuery)');
  }

  return function (hook) {
    if (hook.type === 'after') {
      var provider = hook.params.provider || 'server';
      throw new errors.GeneralError('Provider \'' + provider + '\' cannot remove query params on after hook. (removeQuery)');
    }
    var result = hook.params.query;
    var update = function update(condition) {
      if (result && condition) {
        removeQueries(result);
      }
      return hook;
    };

    var check = callback(hook);

    return check && typeof check.then === 'function' ? check.then(update) : update(check);
  };
}

/**
 * Discard all other fields except for the given fields from the query params.
 * Can be used as a before hook for any service method.
 *
 * @param {Array.<string|Function>} fields - Field names to retain. Dot notation is supported.
 * @returns {Function} hook function(hook)
 *
 * DEPRECATED: The last param may be a function to determine if the current hook should be updated.
 * Its signature is func(hook) and it returns either a boolean or a promise resolving to a boolean.
 * This boolean determines if the hook is updated.
 *
 * hooks.lowerCase('group', hook => hook.data.status === 1);
 * hooks.lowerCase('group', hook => new Promise(resolve => {
 *   setTimeout(() => { resolve(true); }, 100)
 * }));
 */
function pluckQuery() {
  for (var _len3 = arguments.length, fields = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
    fields[_key3] = arguments[_key3];
  }

  var pluckQueries = function pluckQueries(data) {
    var plucked = {};

    fields.forEach(function (field) {
      var value = (0, _utils.getByDot)(data, field); // prevent setByDot creating nested empty objects
      if (value !== undefined) {
        (0, _utils.setByDot)(plucked, field, value);
      }
    });

    return plucked;
  };

  var callback = function callback() {
    return true;
  };
  if (typeof fields[fields.length - 1] === 'function') {
    callback = fields.pop();
    console.error('DEPRECATED Predicate func will be removed next version. (pluckQuery)');
  }

  return function (hook) {
    if (hook.type === 'after') {
      throw new errors.GeneralError('Provider \'' + hook.params.provider + '\' can not pluck query params on after hook. (pluckQuery)');
    }
    var result = hook.params.query;
    var update = function update(condition) {
      if (result && condition) {
        hook.params.query = pluckQueries(result);
      }
      return hook;
    };

    var check = callback(hook);

    return check && typeof check.then === 'function' ? check.then(update) : update(check);
  };
}

/**
 * Remove the given fields either from the data submitted (as a before hook for create,
 * update or patch) or from the result (as an after hook). If the data is an array or
 * a paginated find result the hook will remove the field for every item.
 *
 * @param {Array.<string|Function>} fields - Field names to remove. Dot notation is supported.
 * @returns {Function} hook function(hook)
 *
 * The last param may be a function to determine if the current hook should be updated.
 * Its signature is func(hook) and it returns either a boolean or a promise resolving to a boolean.
 * This boolean determines if the hook is updated.
 *
 * hooks.lowerCase('group', hook => hook.data.status === 1);
 * hooks.lowerCase('group', hook => new Promise(resolve => {
 *   setTimeout(() => { resolve(true); }, 100)
 * }));
 *
 * The items are only updated for external requests, e.g. hook.params.provider is rest or socketio,
 * or if the decision function mentioned above returns true.
 */
function remove() {
  for (var _len4 = arguments.length, fields = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
    fields[_key4] = arguments[_key4];
  }

  var removeFields = function removeFields(data) {
    var _iteratorNormalCompletion3 = true;
    var _didIteratorError3 = false;
    var _iteratorError3 = undefined;

    try {
      for (var _iterator3 = fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
        var field = _step3.value;

        var value = (0, _utils.getByDot)(data, field);
        if (value !== undefined) {
          // prevent setByDot creating nested empty objects
          (0, _utils.setByDot)(data, field, undefined, true);
        }
      }
    } catch (err) {
      _didIteratorError3 = true;
      _iteratorError3 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion3 && _iterator3.return) {
          _iterator3.return();
        }
      } finally {
        if (_didIteratorError3) {
          throw _iteratorError3;
        }
      }
    }
  };

  // when deprecating, remember hook should not run if called from server
  var callback = function callback(hook) {
    return !!hook.params.provider;
  }; // important condition
  if (typeof fields[fields.length - 1] === 'function') {
    callback = fields.pop();
  }

  return function (hook) {
    var result = hook.type === 'before' ? hook.data : hook.result;
    var update = function update(condition) {
      if (result && condition) {
        if (Array.isArray(result)) {
          result.forEach(removeFields);
        } else {
          removeFields(result);

          if (result.data) {
            if (Array.isArray(result.data)) {
              result.data.forEach(removeFields);
            } else {
              removeFields(result.data);
            }
          }
        }
      }
      return hook;
    };

    var check = callback(hook);

    return check && typeof check.then === 'function' ? check.then(update) : update(check);
  };
}

/**
 * Discard all other fields except for the provided fields either from the data submitted
 * (as a before hook for create, update or patch) or from the result (as an after hook).
 * If the data is an array or a paginated find result the hook will remove the field for every item.
 *
 * @param {Array.<string|Function>} fields - Field names to remove. Dot notation is supported.
 * @returns {Function} hook function(hook)
 *
 * DEPRECATED: The last param may be a function to determine if the current hook should be updated.
 * Its signature is func(hook) and it returns either a boolean or a promise resolving to a boolean.
 * This boolean determines if the hook is updated.
 *
 * hooks.lowerCase('group', hook => hook.data.status === 1);
 * hooks.lowerCase('group', hook => new Promise(resolve => {
 *   setTimeout(() => { resolve(true); }, 100)
 * }));
 *
 * The items are only updated for external requests, e.g. hook.params.provider is rest or socketio,
 * or if the decision function mentioned above returns true.
 */
function pluck() {
  for (var _len5 = arguments.length, fields = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
    fields[_key5] = arguments[_key5];
  }

  var pluckFields = function pluckFields(data) {
    var plucked = {};

    fields.forEach(function (field) {
      var value = (0, _utils.getByDot)(data, field);
      if (value !== undefined) {
        // prevent setByDot creating nested empty objects
        (0, _utils.setByDot)(plucked, field, value);
      }
    });

    return plucked;
  };

  // when deprecating, remember hook should not run if called from server
  var callback = function callback(hook) {
    return !!hook.params.provider;
  };
  if (typeof fields[fields.length - 1] === 'function') {
    callback = fields.pop();
    console.error('DEPRECATED Predicate func will be removed next version. (pluck)');
  }

  return function (hook) {
    var update = function update(condition) {
      if (condition) {
        var items = (0, _utils.getItems)(hook);

        if (items) {
          if (Array.isArray(items)) {
            (0, _utils.replaceItems)(hook, items.map(pluckFields));
          } else {
            (0, _utils.replaceItems)(hook, pluckFields(items));
          }
        }
      }

      return hook;
    };

    var check = callback(hook);

    return check && typeof check.then === 'function' ? check.then(update) : update(check);
  };
}

/**
 * Disable access to a service method completely, for a specific provider,
 * or for a custom condition.
 *
 * @param {string|function} [realm] - Provider, or function(hook):boolean|Promise
 *    The first provider or the custom condition.
 *    null = disable completely,
 *    'external' = disable external access,
 *    string = disable that provider e.g. 'rest',
 *    func(hook) = returns boolean or promise resolving to a boolean. false = disable access.
 * @param {string|string[]} [args] - Additional provider names.
 * @returns {Function} hook function(hook)
 *
 * The function may be invoked with
 * - no param, or with undefined or null. All providers are disallowed, even the server.
 * - multiple params of provider names, e.g. rest, socketio. They are all disabled.
 * - 'external'. All client interfaces are disabled.
 * - a function whose signature is func(hook). It returns either a boolean or a promise which
 * resolves to a boolean. If false, the operation is disabled. This is the only way to disable
 * calls from the server.
 */
function disable(realm) {
  if (!realm) {
    return function (hook) {
      throw new errors.MethodNotAllowed('Calling \'' + hook.method + '\' not allowed. (disable)');
    };
  }

  if (typeof realm === 'function') {
    return function (hook) {
      var result = realm(hook);
      var update = function update(check) {
        if (!check) {
          throw new errors.MethodNotAllowed('Calling \'' + hook.method + '\' not allowed. (disable)');
        }
      };

      if (result && typeof result.then === 'function') {
        return result.then(update);
      }

      update(result);
    };
  }

  for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
    args[_key6 - 1] = arguments[_key6];
  }

  var providers = [realm].concat(args);

  return function (hook) {
    var provider = hook.params.provider;

    if (realm === 'external' && provider || providers.indexOf(provider) !== -1) {
      throw new errors.MethodNotAllowed('Provider \'' + hook.params.provider + '\' can not call \'' + hook.method + '\'. (disable)\'');
    }
  };
}

/**
 * The populate hook uses a property from the result (or every item if it is a list)
 * to retrieve a single related object from a service and add it to the original object.
 * It is meant to be used as an after hook on any service method.
 *
 * @param {string} target - The prop name to contain the populated item or array of populated items.
 *    This is also the default for options.field if that is not specified.
 * @param {Object} options - options
 *    For a mongoose model, these are the options for item.toObject().
 *    For a Sequelize model, these are the options for item.toJSON().
 * @param {string} options.service - The service for the related object, e.g. '/messages'.
 * @param {string|Array.<string>} options.field - The field containing the key(s)
 *    for the item(s) in options.service.
 * @returns {Function} hook function(hook):Promise resolving to the hook.
 *
 * 'options.field' is the foreign key for one related item in options.service, i.e. item[options.field] === foreignItem[idField].
 * 'target' is set to this related item once it is read successfully.
 *
 * If 'options.field' is not present in the hook result item, the hook is ignored.
 *
 * So if the hook result has the message item
 *    { _id: '1...1', senderId: 'a...a', text: 'Jane, are you there?' }
 * and the /users service has the item
 *    { _id: 'a...a', name: '<NAME>'}
 * and then the hook is run
 *    hooks.populate('sender', { field: 'userId', service: '/users' })
 * the hook result will contain
 *    { _id: '1...1', senderId : 'a...a', text: 'Jane, are you there?',
 *      sender: { _id: 'a...a', name: '<NAME>'} }
 *
 * If 'senderId' is an array of keys, then 'sender' will be an array of populated items.
 */
function legacyPopulate(target, options) {
  options = Object.assign({}, options);

  console.error('Calling populate(target, options) is now DEPRECATED and will be removed in the future. ' + 'Refer to docs.feathersjs.com for more information. (legacyPopulate)');

  if (!options.service) {
    throw new Error('You need to provide a service. (populate)');
  }

  var field = options.field || target;

  return function (hook) {
    function populate1(item) {
      if (!item[field]) {
        return Promise.resolve(item);
      }

      // Find by the field value by default or a custom query
      var id = item[field];

      // If it's a mongoose model then
      if (typeof item.toObject === 'function') {
        item = item.toObject(options);
      }
      // If it's a Sequelize model
      else if (typeof item.toJSON === 'function') {
          item = item.toJSON(options);
        }
      // Remove any query from params as it's not related
      var params = Object.assign({}, hook.params, { query: undefined });
      // If the relationship is an array of ids, fetch and resolve an object for each,
      // otherwise just fetch the object.
      var promise = Array.isArray(id) ? Promise.all(id.map(function (objectID) {
        return hook.app.service(options.service).get(objectID, params);
      })) : hook.app.service(options.service).get(id, params);
      return promise.then(function (relatedItem) {
        if (relatedItem) {
          item[target] = relatedItem;
        }
        return item;
      });
    }

    if (hook.type !== 'after') {
      throw new errors.GeneralError('Can not populate on before hook. (populate)');
    }

    var isPaginated = hook.method === 'find' && hook.result.data;
    var data = isPaginated ? hook.result.data : hook.result;

    if (Array.isArray(data)) {
      return Promise.all(data.map(populate1)).then(function (results) {
        if (isPaginated) {
          hook.result.data = results;
        } else {
          hook.result = results;
        }

        return hook;
      });
    }

    // Handle single objects.
    return populate1(hook.result).then(function (item) {
      hook.result = item;
      return hook;
    });
  };
}

<|start_filename|>Chapter11/11.3/src/services/index.js<|end_filename|>
'use strict';
const cats = require('./cats');
const authentication = require('./authentication');
const user = require('./user');

module.exports = function() {
  const app = this;


  app.configure(authentication);
  app.configure(user);
  app.configure(cats);
};


<|start_filename|>Chapter07/7.3/test.js<|end_filename|>
describe('my app', () => {
  let vm
  beforeEach(() => {
    vm = new Vue({
      template: `
        <div>
          <p>{{greetings}}</p>
          <button @click="toItalian">
            Translate to Italian
          </button>
        </div>
      `,
      data: {
        greetings: 'Hello World!'
      },
      methods: {
        toItalian () {
          this.greetings = 'Ciao Mondo!'
        }
      }
    }).$mount()
  })
  it('should greet in Italian after toItalian is called', () => {
    vm.toItalian()
    expect(vm.greetings).toContain('Ciao Mondo')
  })
  it('should greet in English', () => {
    expect(vm.greetings).toContain('Hello World')
  })
})

<|start_filename|>Chapter11/11.3/node_modules/feathers-hooks-common/lib/new.js<|end_filename|>
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.traverse = exports.isNot = exports.isProvider = exports.unless = exports.every = exports.some = exports.when = exports.iff = exports.iffElse = exports.combine = exports.softDelete = undefined;

var _commons = require('feathers-hooks/lib/commons');

var _utils = require('./utils');

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

/* eslint-env es6, node */
/* eslint no-param-reassign: 0, no-var: 0 */

var traverser = require('traverse');
var errors = require('feathers-errors').errors;


/**
 * Mark an item as deleted rather than removing it from the database.
 *
 * @param {string} field - Field for delete status. Supports dot notation. Default is 'deleted'.
 *
 * export.before = {
 *   all: softDelete()
 * };
 */
var softDelete = exports.softDelete = function softDelete(field) {
  var deleteField = field || 'deleted';

  return function (hook) {
    var service = this;
    hook.data = hook.data || {};
    hook.params.query = hook.params.query || {};
    (0, _utils.checkContext)(hook, 'before', null, 'softDelete');

    if (hook.params.query.$disableSoftDelete) {
      delete hook.params.query.$disableSoftDelete;
      return hook;
    }

    switch (hook.method) {
      case 'find':
        hook.params.query[deleteField] = { $ne: true };
        return hook;
      case 'get':
        return throwIfItemDeleted(hook.id).then(function () {
          return hook;
        });
      case 'create':
        return hook;
      case 'update': // fall through
      case 'patch':
        if (hook.id) {
          return throwIfItemDeleted(hook.id).then(function () {
            return hook;
          });
        }
        hook.params.query[deleteField] = { $ne: true };
        return hook;
      case 'remove':
        return Promise.resolve().then(function () {
          return hook.id ? throwIfItemDeleted(hook.id) : null;
        }).then(function () {
          hook.data[deleteField] = true;
          hook.params.query[deleteField] = { $ne: true };
          hook.params.query.$disableSoftDelete = true;

          return service.patch(hook.id, hook.data, hook.params).then(function (result) {
            hook.result = result;
            return hook;
          });
        });
    }

    function throwIfItemDeleted(id) {
      return service.get(id, { query: { $disableSoftDelete: true } }).then(function (data) {
        if (data[deleteField]) {
          throw new errors.NotFound('Item has been soft deleted.');
        }
      }).catch(function () {
        throw new errors.NotFound('Item not found.');
      });
    }
  };
};

/**
 * Hook to execute multiple hooks
 *
 * @param {Array.function} rest - Hook functions to execute.
 * @returns {Object} resulting hook
 *
 * Example 1
 * service.before({
 *   create: hooks.combine(hook1, hook2, ...) // same as [hook1, hook2, ...]
 * });
 *
 * Example 2 - called within a custom hook function
 * function (hook) {
 *   ...
 *   return hooks.combine(hook1, hook2, ...).call(this, currentHook)
 *     .then(hook => { ... });
 * }
 */
var combine = exports.combine = function combine() {
  for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
    rest[_key] = arguments[_key];
  }

  return function (hook) {
    return _commons.processHooks.call(this, rest, hook);
  };
};

/**
 * Hook to conditionally execute one or another set of hooks.
 *
 * @param {Function|Promise|boolean} ifFcn - Predicate function(hook).
 * @param {Array.function|Function} trueHooks - Hook functions to execute when ifFcn is truthy.
 * @param {Array.function|Function} falseHooks - Hook functions to execute when ifFcn is falsey.
 * @returns {Object} resulting hook
 *
 * The predicate is called with hook as a param.
 *   const isServer = hook => !hook.params.provider;
 *   iff(isServer, hook.remove( ... ));
 * You can use a high order predicate to access other values.
 *   const isProvider = provider => hook => hook.params.provider === provider;
 *   iff(isProvider('socketio'), hook.remove( ... ));
 *
 * The hook functions may be sync, return a Promise, or use a callback.
 * feathers-hooks will catch any errors from the predicate or hook Promises.
 *
 * Examples
 * iffElse(isServer, [hookA, hookB], hookC)
 *
 * iffElse(isServer,
 *   [ hookA, iffElse(hook => hook.method === 'create', hook1, [hook2, hook3]), hookB ],
 *   iffElse(isProvider('rest'), [hook4, hook5], hook6])
 * )
 */
var iffElse = exports.iffElse = function iffElse(ifFcn, trueHooks, falseHooks) {
  return function (hook) {
    if (typeof trueHooks === 'function') {
      trueHooks = [trueHooks];
    }
    if (typeof falseHooks === 'function') {
      falseHooks = [falseHooks];
    }

    var runHooks = function runHooks(hooks) {
      return hooks ? combine.apply(undefined, _toConsumableArray(hooks)).call(undefined, hook) : hook;
    };

    var check = typeof ifFcn === 'function' ? ifFcn(hook) : !!ifFcn;

    if (!check) {
      return runHooks(falseHooks);
    }

    if (typeof check.then !== 'function') {
      return runHooks(trueHooks);
    }

    return check.then(function (check1) {
      return runHooks(check1 ? trueHooks : falseHooks);
    });
  };
};

/**
 * Hook to conditionally execute one or another set of hooks using function chaining.
 *
 * @param {Function|Promise|boolean} ifFcn - Predicate function(hook).
 * @param {Array.function} rest - Hook functions to execute when ifFcn is truthy.
 * @returns {Function} iffWithoutElse
 *
 * Examples:
 * iff(isServer, hookA, hookB)
 *   .else(hookC)
 *
 * iff(isServer,
 *   hookA,
 *   iff(isProvider('rest'), hook1, hook2, hook3)
 *     .else(hook4, hook5),
 *   hookB
 * )
 *   .else(
 *     iff(hook => hook.method === 'create', hook6, hook7)
 *   )
 */

var iff = exports.iff = function iff(ifFcn) {
  for (var _len2 = arguments.length, rest = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
    rest[_key2 - 1] = arguments[_key2];
  }

  var trueHooks = [].concat(rest);

  var iffWithoutElse = function iffWithoutElse(hook) {
    return iffElse(ifFcn, trueHooks, null).call(this, hook);
  };
  iffWithoutElse.else = function () {
    for (var _len3 = arguments.length, falseHooks = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
      falseHooks[_key3] = arguments[_key3];
    }

    return iffElse(ifFcn, trueHooks, falseHooks);
  };

  return iffWithoutElse;
};

/**
 * Alias for iff
 */

var when = exports.when = iff;

/**
 * Hook that executes a set of hooks and returns true if at least one of
 * the hooks returns a truthy value and false if none of them do.
 *
 * @param {Array.function} rest - Hook functions to execute.
 * @returns {Boolean}
 *
 * Example 1
 * service.before({
 *   create: hooks.iff(hooks.some(hook1, hook2, ...), hookA, hookB, ...)
 * });
 *
 * Example 2 - called within a custom hook function
 * function (hook) {
 *   ...
 *   hooks.some(hook1, hook2, ...).call(this, currentHook)
 *     .then(bool => { ... });
 * }
 */

var some = exports.some = function some() {
  for (var _len4 = arguments.length, rest = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
    rest[_key4] = arguments[_key4];
  }

  return function (hook) {
    var _this = this;

    var hooks = rest.map(function (fn) {
      return fn.call(_this, hook);
    });

    return Promise.all(hooks).then(function (results) {
      return Promise.resolve(results.some(function (result) {
        return !!result;
      }));
    });
  };
};

/**
 * Hook that executes a set of hooks and returns true if all of
 * the hooks returns a truthy value and false if one of them does not.
 *
 * @param {Array.function} rest - Hook functions to execute.
 * @returns {Boolean}
 *
 * Example 1
 * service.before({
 *    create: hooks.iff(hooks.every(hook1, hook2, ...), hookA, hookB, ...)
 * });
 *
 * Example 2 - called within a custom hook function
 * function (hook) {
 *   ...
 *   hooks.every(hook1, hook2, ...).call(this, currentHook)
 *     .then(bool => { ... })
 * }
 */

var every = exports.every = function every() {
  for (var _len5 = arguments.length, rest = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
    rest[_key5] = arguments[_key5];
  }

  return function (hook) {
    var _this2 = this;

    var hooks = rest.map(function (fn) {
      return fn.call(_this2, hook);
    });

    return Promise.all(hooks).then(function (results) {
      return Promise.resolve(results.every(function (result) {
        return !!result;
      }));
    });
  };
};

/**
 * Hook to conditionally execute one or another set of hooks using function chaining.
 * if the predicate hook function returns a falsey value.
 * Equivalent to iff(isNot(isProvider), hook1, hook2, hook3).
 *
 * @param {Function|Promise|boolean} unlessFcn - Predicate function(hook).
 * @param {Array.function} rest - Hook functions to execute when unlessFcn is falsey.
 * @returns {Function} iffWithoutElse
 *
 * Examples:
 * unless(isServer, hookA, hookB)
 *
 * unless(isServer,
 *   hookA,
 *   unless(isProvider('rest'), hook1, hook2, hook3),
 *   hookB
 * )
 */
var unless = exports.unless = function unless(unlessFcn) {
  for (var _len6 = arguments.length, rest = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
    rest[_key6 - 1] = arguments[_key6];
  }

  if (typeof unlessFcn === 'function') {
    return iff.apply(undefined, [isNot(unlessFcn)].concat(rest));
  }

  return iff.apply(undefined, [!unlessFcn].concat(rest));
};

/**
 * Predicate to check what called the service method.
 *
 * @param {string} [providers] - Providers permitted
 *    'server' = service method called from server,
 *    'external' = any external access,
 *    string = that provider e.g. 'rest',
 * @returns {boolean} whether the service method was called by one of the [providers].
 */
var isProvider = exports.isProvider = function isProvider() {
  for (var _len7 = arguments.length, providers = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
    providers[_key7] = arguments[_key7];
  }

  if (!providers.length) {
    throw new errors.MethodNotAllowed('Calling iff() predicate incorrectly. (isProvider)');
  }

  return function (hook) {
    // allow bind
    var hookProvider = (hook.params || {}).provider;

    return providers.some(function (provider) {
      return provider === hookProvider || provider === 'server' && !hookProvider || provider === 'external' && hookProvider;
    });
  };
};

/**
 * Negate a predicate.
 *
 * @param {Function} predicate - returns a boolean or a promise resolving to a boolean.
 * @returns {boolean} the not of the predicate result.
 *
 * const hooks, { iff, isNot, isProvider } from 'feathers-hooks-common';
 * iff(isNot(isProvider('rest')), hooks.remove( ... ));
 */
var isNot = exports.isNot = function isNot(predicate) {
  if (typeof predicate !== 'function') {
    throw new errors.MethodNotAllowed('Expected function as param. (isNot)');
  }

  return function (hook) {
    var result = predicate(hook); // Should we pass a clone? (safety vs performance)

    if (!result || typeof result.then !== 'function') {
      return !result;
    }

    return result.then(function (result1) {
      return !result1;
    });
  };
};

/**
 * Traverse objects and modifies values in place
 *
 * @param {function} converter - conversion function(node).
 *    See details at https://github.com/substack/js-traverse
 * @param {function|object?} getObj - object or function(hook) to get object. Optional.
 *    Default is items in hook.data or hook.result.
 *
 * Example - trim strings
 * const trimmer = function (node) {
 *   if (typeof node === 'string') { this.update(node.trim()); }
 * };
 * service.before({ create: traverse(trimmer) });
 *
 * Example - REST HTTP request uses string 'null' in query. Replace them with value null.
 * const nuller = function (node) {
 *   if (node === 'null') { this.update(null); }
 * };
 * service.before({ find: traverse(nuller, hook => hook.params.query) });
 *
 */
var traverse = exports.traverse = function traverse(converter, getObj) {
  return function (hook) {
    if (typeof getObj === 'function') {
      var items = getObj(hook);
    } else {
      items = getObj || (0, _utils.getItems)(hook);
    }

    (Array.isArray(items) ? items : [items]).forEach(function (item) {
      traverser(item).forEach(converter); // replacement is in place
    });

    return hook;
  };
};

<|start_filename|>Chapter10/10.5/src/store/index.js<|end_filename|>
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const heart = {
  state: { loves: undefined },
  mutations: {
    love (state, target) {
      state.loves = target // state is local
    },
    unlove (state) {
      state.loves = undefined
    }
  }
}

const leftLobe = {
  namespaced: true,
  state: { reason: true },
  mutations: {
    toggle (state) { state.reason = !state.reason }
  },
  actions: {
    beNerd ({ rootState }) {
      rootState.heart.loves = 'Math & Physics'
    }
  }
}

const rightLobe = {
  namespaced: true,
  state: { fantasy: true },
  mutations: {
    toggle (state) { state.fantasy = !state.fantasy }
  }
}

const brain = {
  modules: {
    left: leftLobe,
    right: rightLobe
  }
}

const store = new Vuex.Store({
  modules: {
    brain,
    heart
  }
})

export default store


<|start_filename|>Chapter07/7.5/greeter.js<|end_filename|>
// const greeter = 

<|start_filename|>Chapter10/10.6/src/store/index.js<|end_filename|>
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    bitcoin: 600,
    rate: 1000
  },
  getters: {
    euro: state => state.bitcoin * state.rate
  }
})

export default store


<|start_filename|>Chapter11/11.1/node_modules/electron-packager/test/util.js<|end_filename|>
'use strict'

const bufferEqual = require('buffer-equal')
const common = require('../common')
const config = require('./config.json')
const fs = require('fs-extra')
const path = require('path')
const series = require('run-series')
const slice = Array.prototype.slice
const test = require('tape')

const ORIGINAL_CWD = process.cwd()
const WORK_CWD = path.join(__dirname, 'work')

exports.areFilesEqual = function areFilesEqual (file1, file2, callback) {
  series([
    function (cb) {
      fs.readFile(file1, cb)
    },
    function (cb) {
      fs.readFile(file2, cb)
    }
  ], function (err, buffers) {
    callback(err, bufferEqual(buffers[0], buffers[1]))
  })
}

exports.downloadAll = function downloadAll (version, callback) {
  let combinations = common.createDownloadCombos({electronVersion: config.version}, common.platforms, common.archs, (platform, arch) => {
    // Skip testing darwin/mas target on Windows since electron-packager itself skips it
    // (see https://github.com/electron-userland/electron-packager/issues/71)
    return common.isPlatformMac(platform) && process.platform === 'win32'
  })

  series(combinations.map(combination => {
    return (cb) => {
      var downloadOpts = Object.assign({}, combination)
      downloadOpts.version = version
      downloadOpts.quiet = !!process.env.CI
      common.downloadElectronZip(downloadOpts, cb)
    }
  }), callback)
}

exports.fixtureSubdir = function fixtureSubdir (subdir) {
  return path.join(__dirname, 'fixtures', subdir)
}

exports.generateResourcesPath = function generateResourcesPath (opts) {
  return common.isPlatformMac(opts.platform)
    ? path.join(opts.name + '.app', 'Contents', 'Resources')
    : 'resources'
}

exports.getWorkCwd = function getWorkCwd () {
  return WORK_CWD
}

// tape doesn't seem to have a provision for before/beforeEach/afterEach/after,
// so run setup/teardown and cleanup tasks as additional "tests" to put them in sequence
// and run them irrespective of test failures

exports.setup = function setup () {
  test('setup', function (t) {
    fs.mkdirp(WORK_CWD, function (err) {
      if (err) t.end(err)
      process.chdir(WORK_CWD)
      t.end()
    })
  })
}

exports.teardown = function teardown () {
  test('teardown', function (t) {
    process.chdir(ORIGINAL_CWD)
    fs.remove(WORK_CWD, function (err) {
      t.end(err)
    })
  })
}

exports.packagerTest = function packagerTest (name, testFunction) {
  exports.setup()
  test(name, testFunction)
  exports.teardown()
}

exports.testSinglePlatform = function testSinglePlatform (name, createTest /*, ...createTestArgs */) {
  var args = slice.call(arguments, 2)
  exports.packagerTest(name, createTest.apply(null, [{platform: 'linux', arch: 'x64', electronVersion: config.version}].concat(args)))
}

exports.verifyPackageExistence = function verifyPackageExistence (finalPaths, callback) {
  series(finalPaths.map((finalPath) => {
    return (cb) => {
      fs.stat(finalPath, cb)
    }
  }), (err, statsResults) => {
    if (err) return callback(null, false)

    callback(null, statsResults.every((stats) => {
      return stats.isDirectory()
    }))
  })
}


<|start_filename|>Chapter11/11.3/node_modules/feathers-hooks-common/lib/populate.js<|end_filename|>
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.populate = undefined;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _feathersErrors = require('feathers-errors');

var _feathersErrors2 = _interopRequireDefault(_feathersErrors);

var _utils = require('./utils');

var _bundled = require('./bundled');

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var populate = exports.populate = function populate(options) {
  for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    rest[_key - 1] = arguments[_key];
  }

  if (typeof options === 'string') {
    return _bundled.legacyPopulate.apply(undefined, [options].concat(rest));
  }

  return function (hook) {
    var optionsDefault = {
      schema: {},
      checkPermissions: function checkPermissions() {
        return true;
      },
      profile: false
    };

    if (hook.params._populate === 'skip') {
      // this service call made from another populate
      return hook;
    }

    return Promise.resolve().then(function () {
      // 'options.schema' resolves to { permissions: '...', include: [ ... ] }

      var items = (0, _utils.getItems)(hook);
      var options1 = Object.assign({}, optionsDefault, options);
      var schema = options1.schema,
          checkPermissions = options1.checkPermissions;

      var schema1 = typeof schema === 'function' ? schema(hook, options1) : schema;
      var permissions = schema1.permissions || null;

      if (typeof checkPermissions !== 'function') {
        throw new _feathersErrors2.default.BadRequest('Permissions param is not a function. (populate)');
      }

      if (permissions && !checkPermissions(hook, hook.path, permissions, 0)) {
        throw new _feathersErrors2.default.BadRequest('Permissions do not allow this populate. (populate)');
      }

      if ((typeof schema1 === 'undefined' ? 'undefined' : _typeof(schema1)) !== 'object') {
        throw new _feathersErrors2.default.BadRequest('Schema does not resolve to an object. (populate)');
      }

      return !schema1.include || !Object.keys(schema1.include).length ? items : populateItemArray(options1, hook, items, schema1.include, 0);
    }).then(function (items) {
      (0, _utils.replaceItems)(hook, items);
      return hook;
    });
  };
};

function populateItemArray(options, hook, items, includeSchema, depth) {
  // 'items' is an item or an array of items
  // 'includeSchema' is like [ { nameAs: 'author', ... }, { nameAs: 'readers', ... } ]

  if (!Array.isArray(items)) {
    return populateItem(options, hook, items, includeSchema, depth + 1);
  }

  return Promise.all(items.map(function (item) {
    return populateItem(options, hook, item, includeSchema, depth + 1);
  }));
}

function populateItem(options, hook, item, includeSchema, depth) {
  // 'item' is one item
  // 'includeSchema' is like [ { nameAs: 'author', ... }, { nameAs: 'readers', ... } ]

  var elapsed = {};
  var startAtAllIncludes = process.hrtime();
  item._include = [];

  return Promise.all(includeSchema.map(function (childSchema) {
    var startAtThisInclude = process.hrtime();
    return populateAddChild(options, hook, item, childSchema, depth).then(function (result) {
      var nameAs = childSchema.nameAs || childSchema.service;
      elapsed[nameAs] = getElapsed(options, startAtThisInclude, depth);

      return result;
    });
  })).then(function (children) {
    // 'children' is like [{ authorInfo: {...}, readersInfo: [{...}, {...}] }]
    if (options.profile !== false) {
      elapsed.total = getElapsed(options, startAtAllIncludes, depth);
      item._elapsed = elapsed;
    }

    return Object.assign.apply(Object, [item].concat(_toConsumableArray(children)));
  });
}

function populateAddChild(options, hook, parentItem, childSchema, depth) {
  /*
  'parentItem' is the item we are adding children to
  'childSchema' is like
    { service: 'comments',
      permissions: '...',
      nameAs: 'comments',
      asArray: true,
      parentField: 'id',
      childField: 'postId',
      query: { $limit: 5, $select: ['title', 'content', 'postId'], $sort: { createdAt: -1 } },
      select: (hook, parent, depth) => ({ something: { $exists: false }}),
      include: [ ... ],
    }
  */

  // note: parentField & childField are req'd, plus parentItem[parentField} !== undefined .
  // childSchema.select may override their relationship but some relationship must be given.
  if (!childSchema.service || !childSchema.parentField || !childSchema.childField) {
    throw new _feathersErrors2.default.BadRequest('Child schema is missing a required property. (populate)');
  }

  if (childSchema.permissions && !options.checkPermissions(hook, childSchema.service, childSchema.permissions, depth)) {
    throw new _feathersErrors2.default.BadRequest('Permissions for ' + childSchema.service + ' do not allow include. (populate)');
  }

  var nameAs = childSchema.nameAs || childSchema.service;
  parentItem._include.push(nameAs);

  var promise = Promise.resolve().then(function () {
    return childSchema.select ? childSchema.select(hook, parentItem, depth) : {};
  }).then(function (selectQuery) {
    var parentVal = (0, _utils.getByDot)(parentItem, childSchema.parentField);

    if (parentVal === undefined) {
      throw new _feathersErrors2.default.BadRequest('ParentField ' + childSchema.parentField + ' for ' + nameAs + ' depth ' + depth + ' is undefined. (populate)');
    }

    var query = Object.assign({}, childSchema.query, _defineProperty({}, childSchema.childField, Array.isArray(parentVal) ? { $in: parentVal } : parentVal), selectQuery // dynamic options override static ones
    );

    var serviceHandle = hook.app.service(childSchema.service);

    if (!serviceHandle) {
      throw new _feathersErrors2.default.BadRequest('Service ' + childSchema.service + ' is not configured. (populate)');
    }

    return serviceHandle.find({ query: query, _populate: 'skip' });
  }).then(function (result) {
    result = result.data || result;

    if (result.length === 1 && !childSchema.asArray) {
      result = result[0];
    }

    return result;
  });

  if (childSchema.include) {
    promise = promise.then(function (items) {
      return populateItemArray(options, hook, items, childSchema.include, depth);
    });
  }

  return promise.then(function (items) {
    return _defineProperty({}, nameAs, items);
  });
}

// Helpers

function getElapsed(options, startHrtime, depth) {
  if (options.profile === true) {
    var elapsed = process.hrtime(startHrtime);
    return elapsed[0] * 1e9 + elapsed[1];
  } else if (options.profile !== false) {
    return depth; // for testing _elapsed
  }
}

<|start_filename|>Chapter10/10.4/src/store/index.js<|end_filename|>
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

const endpoint = '/comic/'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    currentPanel: undefined,
    currentImg: undefined,
    errorStack: []
  },
  actions: {
    goToLastPanel ({ commit }) {
      axios.get(endpoint)
        .then(({ data }) => {
          commit('setPanel', data.num)
          commit('setImg', data.img)
        }).catch(error => {
          commit('pushError', error)
        })
    },
    goToNextPanel ({ commit, state }) {
      const nextPanel = state.currentPanel + 1
      axios.get(`${endpoint}${nextPanel}`)
        .then(({ data }) => {
          commit('nextPanel')
          commit('setImg', data.img)
        }).catch(error => {
          commit('pushError', error)
        })
    },
    goToPrevPanel ({ commit, state }) {
      if (state.currentPanel === 1) {
        commit('pushError', 'First panel')
        return
      }
      const prevPanel = state.currentPanel - 1
      axios.get(`${endpoint}${prevPanel}`)
        .then(({ data }) => {
          commit('prevPanel')
          commit('setImg', data.img)
        }).catch(error => {
          commit('pushError', error)
        })
    }
  },
  mutations: {
    setPanel (state, num) {
      state.currentPanel = num
    },
    setImg (state, img) {
      state.currentImg = img
    },
    nextPanel (state) {
      state.currentPanel += 1
    },
    prevPanel (state) {
      state.currentPanel -= 1
    },
    pushError (state, error) {
      state.errorStack.push(error)
    }
  }
})

export default store


<|start_filename|>Chapter07/7.10/test.js<|end_filename|>
describe('my app', () => {
  let vm
  beforeEach(() => {
    vm = new Vue(myApp).$mount()
    vm.number = 5
  })
  it('should output Lower... if guess is 6', () => {
    vm.guess = 6
    expect(vm.output).toBe('Lower...')
  })
  it('should output Higher... if guess is 4', () => {
    vm.guess = 4
    expect(vm.output).toBe('Higher...')
  })
  it('should output That’s right! if guess is 5', () => {
    vm.guess = 5
    expect(vm.output).toBe('That’s right!')
  })
})

<|start_filename|>Chapter11/11.4/vue_app/node_modules/clarifai/src/App.js<|end_filename|>
let axios = require('axios');
let {Promise}  = require('es6-promise');
let {checkType} = require('./helpers');
let Models = require('./Models');
let Inputs = require('./Inputs');
let Concepts = require('./Concepts');
let {API, ERRORS}  = require('./constants');
let {TOKEN_PATH} = API;


/**
* top-level class that allows access to models, inputs and concepts
* @class
*/
class App {
  constructor(clientId, clientSecret, options) {
    this._validate(clientId, clientSecret, options);
    this._init(clientId, clientSecret, options);
  }
  /**
  * Gets a token from the API using client credentials
  * @return {Promise(token, error)} A Promise that is fulfilled with the token string or rejected with an error
  */
  getToken() {
    return this._config.token();
  }
  /**
  * Sets the token to use for the API
  * @param {String}         _token    The token you are setting
  * @return {Boolean}                 true if token has valid fields, false if not
  */
  setToken(_token) {
    let token = _token;
    let now = new Date().getTime();
    if (typeof _token === 'string') {
      token = {
        accessToken: _token,
        expiresIn: 176400
      };
    } else {
      token = {
        accessToken: _token.access_token || _token.accessToken,
        expiresIn: _token.expires_in || _token.expiresIn
      };
    }
    if ((token.accessToken && token.expiresIn) ||
        (token.access_token && token.expires_in)) {
      if (!token.expireTime) {
        token.expireTime = now + (token.expiresIn * 1000);
      }
      this._config._token = token;
      return true;
    }
    return false;
  }
  _validate(clientId, clientSecret, options) {
    if ((!clientId || !clientSecret) && !options.token) {
      throw ERRORS.paramsRequired(['Client ID', 'Client Secret']);
    }
  }
  _init(clientId, clientSecret, options={}) {
    this._config = {
      apiEndpoint: options.apiEndpoint ||
        (process && process.env && process.env.API_ENDPOINT) ||
        'https://api.clarifai.com',
      clientId,
      clientSecret,
      token: ()=> {
        return new Promise((resolve, reject)=> {
          let now = new Date().getTime();
          if (checkType(/Object/, this._config._token) && this._config._token.expireTime > now) {
            resolve(this._config._token);
          } else {
            this._getToken(resolve, reject);
          }
        });
      }
    };
    if (options.token) {
      this.setToken(options.token);
    }
    this.models = new Models(this._config);
    this.inputs = new Inputs(this._config);
    this.concepts = new Concepts(this._config);
  }
  _getToken(resolve, reject) {
    this._requestToken().then(
      (response)=> {
        if (response.status === 200) {
          this.setToken(response.data);
          resolve(this._config._token);
        } else {
          reject(response);
        }
      },
      reject
    );
  }
  _requestToken() {
    let url = `${this._config.apiEndpoint}${TOKEN_PATH}`;
    let clientId = this._config.clientId;
    let clientSecret = this._config.clientSecret;
    return axios({
      'url': url,
      'method': 'POST',
      'auth': {
        'username': clientId,
        'password': <PASSWORD>Secret
      }
    });
  }
};

module.exports = App;


<|start_filename|>Chapter07/7.4/test.js<|end_filename|>
describe('my app', () => {
  let vm
  beforeEach(() => {
    vm = new Vue({
      template: '<div>{{greetings}}</div>',
      data: {
        greetings: 'Hello World'
      }
    }).$mount()
  })
  it('should say Hello World', () => {
    expect(vm.$el.innerText).toContain('Hello World')
  })
})

<|start_filename|>Chapter11/11.1/node_modules/electron-rebuild/test/electron-locater.js<|end_filename|>
import fs from 'fs';
import path from 'path';
import { expect } from 'chai';
import { spawnPromise } from 'spawn-rx';

import { locateElectronPrebuilt } from '../lib/electron-locater';

const packageCommand = (command, packageName) =>
  spawnPromise('npm', [command, packageName], {
    cwd: path.resolve(__dirname, '..'),
    stdio: 'ignore',
  });

const install = packageCommand.bind(this, 'install');
const uninstall = packageCommand.bind(this, 'uninstall');

const testElectronCanBeFound = () => {
  it('should return a valid path', () => {
    const electronPath = locateElectronPrebuilt();
    expect(electronPath).to.be.a('string');
    expect(fs.existsSync(electronPath)).to.be.equal(true);
  });
};

describe('locateElectronPrebuilt', () => {
  before(() => uninstall('electron-prebuilt'));

  it('should return null when electron is not installed', () => {
    expect(locateElectronPrebuilt()).to.be.equal(null);
  });

  describe('with electron-prebuilt installed', () => {
    before(() => install('electron-prebuilt'));

    testElectronCanBeFound();

    after(() => uninstall('electron-prebuilt'));
  });

  describe('with electron installed', () => {
    before(() => install('electron'));

    testElectronCanBeFound();

    after(() => uninstall('electron'));
  });

  after(() => install('electron-prebuilt'));
});


<|start_filename|>Chapter11/11.1/node_modules/electron-rebuild/src/main.js<|end_filename|>
export { default, rebuildNativeModules } from './rebuild';

export const installNodeHeaders = () => Promise.resolve();
export const shouldRebuildNativeModules  = () => Promise.resolve(true);
export const preGypFixRun = () => Promise.resolve();

<|start_filename|>Chapter07/7.10/myApp.js<|end_filename|>
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

const myApp = {
  template: `
    <div>
      <p>
        I am thinking of a number between 1 and 20.
      </p>
      <input v-model="guess">
      <p v-if="guess">{{output}}</p>
    </div>
  `,
  data: {
    number: getRandomInt(1, 20),
    guess: undefined
  },
  computed: {
    output () {
      if (this.guess < this.number) {
        return 'Higher...'
      }
      if (this.guess > this.number) {
        return 'Lower...'
      }
      return 'That’s right!'
    }
  }
}

<|start_filename|>Chapter11/11.1/node_modules/electron-chromedriver/package.json<|end_filename|>
{
  "_args": [
    [
      {
        "raw": "electron-chromedriver@~1.6.0",
        "scope": null,
        "escapedName": "electron-chromedriver",
        "name": "electron-chromedriver",
        "rawSpec": "~1.6.0",
        "spec": ">=1.6.0 <1.7.0",
        "type": "range"
      },
      "/Users/gurghet/Library/Mobile Documents/com~apple~CloudDocs/Vue2Cookbook tools/vue2cookbook/11/11.1/node_modules/spectron"
    ]
  ],
  "_from": "electron-chromedriver@>=1.6.0 <1.7.0",
  "_id": "electron-chromedriver@1.6.0",
  "_inCache": true,
  "_location": "/electron-chromedriver",
  "_nodeVersion": "7.4.0",
  "_npmOperationalInternal": {
    "host": "packages-18-east.internal.npmjs.com",
    "tmp": "tmp/electron-chromedriver-1.6.0.tgz_1486434368343_0.5650207984726876"
  },
  "_npmUser": {
    "name": "kevinsawicki",
    "email": "<EMAIL>"
  },
  "_npmVersion": "4.0.5",
  "_phantomChildren": {},
  "_requested": {
    "raw": "electron-chromedriver@~1.6.0",
    "scope": null,
    "escapedName": "electron-chromedriver",
    "name": "electron-chromedriver",
    "rawSpec": "~1.6.0",
    "spec": ">=1.6.0 <1.7.0",
    "type": "range"
  },
  "_requiredBy": [
    "/spectron"
  ],
  "_resolved": "https://registry.npmjs.org/electron-chromedriver/-/electron-chromedriver-1.6.0.tgz",
  "_shasum": "6eabdaa5cf9c75e43501e2593b528e8cfd97d7c7",
  "_shrinkwrap": null,
  "_spec": "electron-chromedriver@~1.6.0",
  "_where": "/Users/gurghet/Library/Mobile Documents/com~apple~CloudDocs/Vue2Cookbook tools/vue2cookbook/11/11.1/node_modules/spectron",
  "author": {
    "name": "<NAME>"
  },
  "bin": {
    "chromedriver": "./chromedriver.js"
  },
  "bugs": {
    "url": "https://github.com/electron/chromedriver/issues"
  },
  "dependencies": {
    "electron-download": "^3.1.0",
    "extract-zip": "^1.6.0"
  },
  "description": "Electron ChromeDriver",
  "devDependencies": {
    "mocha": "^2.3.3",
    "standard": "^5.3.1"
  },
  "directories": {},
  "dist": {
    "shasum": "6eabdaa5cf9c75e43501e2593b528e8cfd97d7c7",
    "tarball": "https://registry.npmjs.org/electron-chromedriver/-/electron-chromedriver-1.6.0.tgz"
  },
  "gitHead": "d7166be863ded7f351df773869359289b179444e",
  "homepage": "https://github.com/electron/chromedriver#readme",
  "license": "MIT",
  "maintainers": [
    {
      "name": "jlord",
      "email": "<EMAIL>"
    },
    {
      "name": "kevinsawicki",
      "email": "<EMAIL>"
    },
    {
      "name": "zcbenz",
      "email": "<EMAIL>"
    },
    {
      "name": "zeke",
      "email": "<EMAIL>"
    }
  ],
  "name": "electron-chromedriver",
  "optionalDependencies": {},
  "readme": "ERROR: No README data found!",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/electron/chromedriver.git"
  },
  "scripts": {
    "install": "node ./download-chromedriver.js",
    "test": "standard && mocha"
  },
  "version": "1.6.0"
}


<|start_filename|>Chapter11/11.1/node_modules/electron-rebuild/src/cli.js<|end_filename|>
#!/usr/bin/env node

import 'colors';
import fs from 'fs-promise';
import path from 'path';
import ora from 'ora';

import rebuild from './rebuild.js';
import { locateElectronPrebuilt } from './electron-locater';

const yargs = require('yargs')
  .usage('Usage: electron-rebuild --version [version] --module-dir [path]')
  .help('h')
  .alias('h', 'help')
  .describe('v', 'The version of Electron to build against')
  .alias('v', 'version')
  .describe('f', 'Force rebuilding modules, even if we would skip it otherwise')
  .alias('f', 'force')
  .describe('a', "Override the target architecture to something other than your system's")
  .alias('a', 'arch')
  .describe('m', 'The path to the node_modules directory to rebuild')
  .alias('m', 'module-dir')
  .describe('w', 'A specific module to build, or comma separated list of modules')
  .alias('w', 'which-module')
  .describe('e', 'The path to electron-prebuilt')
  .alias('e', 'electron-prebuilt-dir')
  .describe('d', 'Custom header tarball URL')
  .alias('d', 'dist-url')
  .describe('t', 'The types of dependencies to rebuild.  Comma seperated list of "prod", "dev" and "optional".  Default is "prod,optional"')
  .alias('t', 'types')
  .describe('p', 'Rebuild in parallel, this is enabled by default on macOS and Linux')
  .alias('p', 'parallel')
  .describe('s', 'Rebuild modules sequentially, this is enabled by default on Windows')
  .alias('s', 'sequential')
  .epilog('Copyright 2016');

const argv = yargs.argv;

if (argv.h) {
  yargs.showHelp();
  process.exit(0);
}

const handler = (err) => {
  console.error('An unhandled error occurred inside electron-rebuild'.red);
  console.error(`${err.message}\n\n${err.stack}`.red);
  process.exit(-1);
};
process.on('uncaughtException', handler);
process.on('unhandledRejection', handler);


(async () => {
  const electronPrebuiltPath = argv.e ? path.resolve(process.cwd(), argv.e) : locateElectronPrebuilt();
  let electronPrebuiltVersion = argv.v; 

  if (!electronPrebuiltVersion) {
    try {
      const pkgJson = require(path.join(electronPrebuiltPath, 'package.json'));

      electronPrebuiltVersion = pkgJson.version;
    } catch (e) {
      throw new Error('Unable to find electron-prebuilt\'s version number, either install it or specify an explicit version');
    }
  }

  let rootDirectory = argv.m;

  if (!rootDirectory) {
    // NB: We assume here that we're going to rebuild the immediate parent's
    // node modules, which might not always be the case but it's at least a
    // good guess
    rootDirectory = path.resolve(__dirname, '../../..');
    if (!await fs.exists(rootDirectory) || !await fs.exists(path.resolve(rootDirectory, 'package.json'))) {
      // Then we try the CWD
      rootDirectory = process.cwd();
      if (!await fs.exists(rootDirectory) || !await fs.exists(path.resolve(rootDirectory, 'package.json'))) {
        throw new Error('Unable to find parent node_modules directory, specify it via --module-dir, E.g. "--module-dir ." for the current directory');
      }
    }
  } else {
    rootDirectory = path.resolve(process.cwd(), rootDirectory);
  }
  
  let modulesDone = 0;
  let moduleTotal = 0;
  const rebuildSpinner = ora('Searching dependency tree').start();
  let lastModuleName;
  const redraw = (moduleName) => {
    if (moduleName) lastModuleName = moduleName;
    if (argv.p) {
      rebuildSpinner.text = `Building modules: ${modulesDone}/${moduleTotal}`;
    } else {
      rebuildSpinner.text = `Building module: ${lastModuleName}, Completed: ${modulesDone}`;
    }
  }
  const rebuilder = rebuild(rootDirectory, electronPrebuiltVersion, argv.a || process.arch, argv.w ? argv.w.split(',') : [], argv.f, argv.d, argv.t ? argv.t.split(',') : ['prod', 'dev'], argv.p ? 'parallel' : (argv.s ? 'sequential' : undefined));
  const lifecycle = rebuilder.lifecycle;
  lifecycle.on('module-found', (moduleName) => {
    moduleTotal += 1;
    redraw(moduleName);
  });
  lifecycle.on('module-done', () => {
    modulesDone += 1;
    redraw();
  });
  try {
    await rebuilder;
  } catch (err) {
    rebuildSpinner.text = 'Rebuild Failed';
    rebuildSpinner.fail();
    throw err;
  }
  rebuildSpinner.text = 'Rebuild Complete';
  rebuildSpinner.succeed();
})();

<|start_filename|>Chapter07/7.6/tests/test.js<|end_filename|>
module.exports = {
  'Happy scenario': client => {
    client
      .url('http://localhost:8080')
      .waitForElementVisible('#app', 1000)
      .assert.containsText('h2', 'Welcome to')
      .assert.hidden('p')
      .click('button')
      .waitForElementVisible('p', 1000)
      .assert.containsText('p', 'Nightwatch')
      .end();
  }
}
/*
 start selenium-standalone
 start http-server
 nightwatch
*/

<|start_filename|>Chapter10/10.2/src/router/index.js<|end_filename|>
import Vue from 'vue'
import Router from 'vue-router'
import Market from 'components/Market'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/STAR/LAMP'
    },
    {
      path: '/:symbol1/:symbol2',
      component: Market,
      props: true
    }
  ]
})


<|start_filename|>Chapter10/10.2/src/store/index.js<|end_filename|>
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    STAR: 100,
    LAMP: 100,
    DIAM: 100,
    rate: {
      STAR: {
        LAMP: 2
      },
      LAMP: {
        DIAM: 0.5
      }
    }
  }
})
export default store


<|start_filename|>Chapter10/10.1/src/router/index.js<|end_filename|>
import Vue from 'vue'
import Router from 'vue-router'
import Hello from 'components/Hello'
// import Massive from 'components/Massive'

Vue.use(Router)

const Massive = resolve =>
  require(['../components/Massive.vue'], resolve)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    },
    {
      path: '/massive',
      name: 'Massive',
      component: Massive
    }
  ]
})


<|start_filename|>Chapter11/11.1/app/package.json<|end_filename|>
{
  "name": "pomodoro",
  "version": "0.0.0",
  "description": "A pomodoro app",
  "main": "./dist/main.js",
  "dependencies": {
    "vue": "^2.1.10",
    "vue-electron": "^1.0.6"
  },
  "devDependencies": {},
  "author": "<NAME> <<EMAIL>>"
}


<|start_filename|>Chapter11/11.3/node_modules/feathers-hooks/lib/hooks.js<|end_filename|>
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _uberproto = require('uberproto');

var _uberproto2 = _interopRequireDefault(_uberproto);

var _feathersCommons = require('feathers-commons');

var _populate = require('feathers-hooks-common/lib/populate');

var _bundled = require('feathers-hooks-common/lib/bundled');

var _commons = require('./commons');

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function isPromise(result) {
  return typeof result !== 'undefined' && typeof result.then === 'function';
}

function hookMixin(service) {
  var app = this;
  var methods = app.methods;
  var old = {
    before: service.before,
    after: service.after
  };
  var mixin = (0, _commons.baseMixin)(methods, {
    before: function before(_before) {
      return this.hooks({ before: _before });
    },
    after: function after(_after) {
      return this.hooks({ after: _after });
    }
  });

  (0, _commons.addHookTypes)(service);

  methods.forEach(function (method) {
    if (typeof service[method] !== 'function') {
      return;
    }

    mixin[method] = function () {
      var _this = this;

      var service = this;
      // A reference to the original method
      var _super = this._super.bind(this);
      // Additional data to add to the hook object
      var hookData = {
        app: app,
        service: service,
        get path() {
          return Object.keys(app.services).find(function (path) {
            return app.services[path] === service;
          });
        }
      };
      // Create the hook object that gets passed through
      var hookObject = _feathersCommons.hooks.hookObject(method, 'before', arguments, hookData);
      // Get all hooks
      var hooks = {
        // For before hooks the app hooks will run first
        before: (0, _commons.getHooks)(app, this, 'before', method),
        // For after and error hooks the app hooks will run last
        after: (0, _commons.getHooks)(app, this, 'after', method, true),
        error: (0, _commons.getHooks)(app, this, 'error', method, true)
      };

      // Process all before hooks
      return _commons.processHooks.call(this, hooks.before, hookObject)
      // Use the hook object to call the original method
      .then(function (hookObject) {
        if (typeof hookObject.result !== 'undefined') {
          return Promise.resolve(hookObject);
        }

        return new Promise(function (resolve, reject) {
          var args = _feathersCommons.hooks.makeArguments(hookObject);
          // The method may not be normalized yet so we have to handle both
          // ways, either by callback or by Promise
          var callback = function callback(error, result) {
            if (error) {
              reject(error);
            } else {
              hookObject.result = result;
              resolve(hookObject);
            }
          };

          // We replace the callback with resolving the promise
          args.splice(args.length - 1, 1, callback);

          var result = _super.apply(undefined, _toConsumableArray(args));

          if (isPromise(result)) {
            result.then(function (data) {
              return callback(null, data);
            }, callback);
          }
        });
      })
      // Make a copy of hookObject from `before` hooks and update type
      .then(function (hookObject) {
        return Object.assign({}, hookObject, { type: 'after' });
      })
      // Run through all `after` hooks
      .then(_commons.processHooks.bind(this, hooks.after))
      // Finally, return the result
      .then(function (hookObject) {
        return hookObject.result;
      })
      // Handle errors
      .catch(function (error) {
        var errorHook = Object.assign({}, error.hook || hookObject, {
          type: 'error',
          original: error.hook,
          error: error
        });

        return _commons.processHooks.call(_this, hooks.error, errorHook).then(function (hook) {
          return Promise.reject(hook.error);
        });
      });
    };
  });

  service.mixin(mixin);

  // Before hooks that were registered in the service
  if (old.before) {
    service.before(old.before);
  }

  // After hooks that were registered in the service
  if (old.after) {
    service.after(old.after);
  }
}

function configure() {
  return function () {
    var app = this;

    (0, _commons.addHookTypes)(app);

    _uberproto2.default.mixin((0, _commons.baseMixin)(app.methods), app);

    this.mixins.unshift(hookMixin);
  };
}

configure.removeQuery = _bundled.removeQuery;
configure.pluckQuery = _bundled.pluckQuery;
configure.lowerCase = _bundled.lowerCase;
configure.remove = _bundled.remove;
configure.pluck = _bundled.pluck;
configure.disable = _bundled.disable;
configure.populate = _populate.populate;
configure.removeField = _bundled.removeField;

exports.default = configure;
module.exports = exports['default'];

<|start_filename|>Chapter11/11.3/node_modules/feathers-hooks-common/lib/serialize.js<|end_filename|>
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.serialize = undefined;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _utils = require('./utils');

var serialize = exports.serialize = function serialize(schema) {
  return function (hook) {
    schema = typeof schema === 'function' ? schema(hook) : schema;
    var schemaDirectives = ['computed', 'exclude', 'only'];

    (0, _utils.replaceItems)(hook, serializeItems((0, _utils.getItems)(hook), schema));
    return hook;

    function serializeItems(items, schema) {
      if (!Array.isArray(items)) {
        return serializeItem(items, schema);
      }

      return items.map(function (item) {
        return serializeItem(item, schema);
      });
    }

    function serializeItem(item, schema) {
      var computed = {};
      Object.keys(schema.computed || {}).forEach(function (name) {
        computed[name] = schema.computed[name](item, hook); // needs closure
      });

      var only = schema.only;
      only = typeof only === 'string' ? [only] : only;
      if (only) {
        (function () {
          var newItem = {};
          only.concat('_include', '_elapsed', item._include || []).forEach(function (key) {
            (0, _utils.setByDot)(newItem, key, (0, _utils.getByDot)(item, key), true);
          });
          item = newItem;
        })();
      }

      var exclude = schema.exclude;
      exclude = typeof exclude === 'string' ? [exclude] : exclude;
      if (exclude) {
        exclude.forEach(function (key) {
          (0, _utils.setByDot)(item, key, undefined, true);
        });
      }

      var _computed = Object.keys(computed);
      item = Object.assign({}, item, computed, _computed.length ? { _computed: _computed } : {});

      Object.keys(schema).forEach(function (key) {
        if (!schemaDirectives.includes(key) && _typeof(item[key]) === 'object') {
          // needs closure
          item[key] = serializeItems(item[key], schema[key]);
        }
      });

      return item;
    }
  };
};

<|start_filename|>Chapter10/10.7/src/store/index.js<|end_filename|>
import Vuex from 'vuex'
import Vue from 'vue'
import actions from './actions'

Vue.use(Vuex)

export const mutations = {
  MARK_ITEM_AS_DONE (state, itemId) {
    state.todo.filter(item => {
      return item.id === itemId
    }).forEach(item => {
      item.done = true
    })
    state.archived.filter(item => {
      return item.id === itemId
    }).forEach(item => {
      item.done = true
    })
  }
}

const store = new Vuex.Store({
  state: {
    state: {
      todo: [{
        id: 43,
        text: 'Buy iPhone',
        done: false
      } ],
      archived: [{
        id: 2,
        text: 'Buy gramophone',
        done: true
      } ]
    }
  },
  mutations,
  actions
})

export default store


<|start_filename|>Chapter11/11.3/node_modules/feathers-hooks-common/lib/dePopulate.js<|end_filename|>
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.dePopulate = undefined;

var _utils = require('./utils');

var dePopulate = exports.dePopulate = function dePopulate() {
  return function (hook) {
    var items = (0, _utils.getItems)(hook);

    (Array.isArray(items) ? items : [items]).forEach(function (item) {
      removeProps('_computed', item);
      removeProps('_include', item);
      delete item._elapsed;
    });

    (0, _utils.replaceItems)(hook, items);
    return hook;
  };
};

function removeProps(name, item) {
  if (name in item) {
    item[name].forEach(function (key) {
      delete item[key];
    });
    delete item[name];
  }
}

<|start_filename|>Chapter11/11.4/vue_app/node_modules/clarifai/dist/Concept.js<|end_filename|>
"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
* class representing a concept and its info
* @class
*/
var Concept = function Concept(_config, data) {
  _classCallCheck(this, Concept);

  this.id = data.id;
  this.name = data.name;
  this.createdAt = data.created_at || data.createdAt;
  this.appId = data.app_id || data.appId;
  this.value = data.value || null;
  this._config = _config;
  this.rawData = data;
};

;

module.exports = Concept;

<|start_filename|>Chapter10/10.7/test/unit/specs/Hello.spec.js<|end_filename|>
import { mutations } from 'src/store'

describe('mutations', () => {
  it(`MARK_ITEM_AS_DONE mutation must change the
        done field from false to true for a todo`, () => {
    const state = {
      todo: [
        { id: 43, text: 'Buy iPhone', done: false }
      ],
      archived: [
        { id: 40, text: 'Buy cat', done: false }
      ]
    }
    mutations.MARK_ITEM_AS_DONE(state, 43)
    expect(state.todo[0].done).to.be.true
  })
})

describe('actions', () => {
  const actionsInjector = require('inject-loader!src/store/actions')
  const buyHouseTodo = { id: 84, text: 'Buy house', done: true }
  const actions = actionsInjector({
    'axios': {
      get () {
        return new Promise(resolve => {
          resolve({
            data: [buyHouseTodo]
          })
        })
      }
    }
  }).default
  it(`downloadNew should commit ADD_ITEMS
    with the 'Buy house' todo when successful`, done => {
    const commit = (type, payload) => {
      try {
        expect(type).to.equal('ADD_ITEMS')
        expect(payload).to.deep.equal([buyHouseTodo])
        done()
      } catch (error) {
        done(error)
      }
    }
    actions.downloadNew({ commit })
  })
})


<|start_filename|>Chapter11/11.1/app/node_modules/vue-electron/index.js<|end_filename|>
module.exports = {
  install: function (Vue) {
    Vue.prototype.$electron = require('electron')
  }
}
