<commit_before>#!/usr/bin/env node
/* MicroFlo - Flow-Based Programming for microcontrollers
 * Copyright (c) 2013 Jon Nordby <jononor@gmail.com>
 * MicroFlo may be freely distributed under the MIT license
 */

var fs = require("fs");
var cmdFormat = require("./microflo/commandformat.json");
var microflo = require("./lib/microflo");
var commander = require("commander");
var pkginfo = require('pkginfo')(module);

var componentLib = null;

var setupRuntimeCommand = function(env) {
    var serialPortToUse = env.serial || "auto";
    var port = env.port || 3569;
    var debugLevel = env.debug || "Error";
    var ip = env.ip || "127.0.0.1"
    var baud = parseInt(env.baudrate) || 9600

    microflo.runtime.setupRuntime(serialPortToUse, baud, port, debugLevel, ip);
}

var uploadGraphCommand = function(graphPath, env) {
    var serialPortName = env.serial || "auto";
    var debugLevel = env.debug
    var baud = parseInt(env.baudrate) || 9600

    microflo.runtime.uploadGraphFromFile(graphPath, serialPortName, baud, debugLevel);
}

var generateFwCommand = function(env) {
    var inputFile = process.argv[3];
    var outputFile = process.argv[4] || inputFile.replace(path.extname(inputFile), "");
    var target = process.argv[5] || 'arduino'

    microflo.generate.generateOutput(componentLib, inputFile, outputFile, target);
}

var registerRuntimeCommand = function(user, env) {
    var ip = env.ip || 'auto';
    var port = parseInt(env.port) || 3569;
    var label = env.label || "MicroFlo"
    var id = env.id || process.env['MICROFLO_RUNTIME_ID'];

    if (!user) {
        user = process.env['FLOWHUB_USER_ID'];
    }

    var rt = microflo.runtime.createFlowhubRuntime(user, ip, port, label);
    if (!id) {
        microflo.runtime.registerFlowhubRuntime(rt, function(err, ok) {
            if (err) {
                console.log("Could not register runtime with Flowhub", err);
                process.exit(1);
            } else {
                console.log("Runtime registered with id:", rt.runtime.id);
            }
        });
    }
}

var updateDefsCommand = function(env) {
    // FIXME: move this code somewhere else, make more general
    // For now, default to all components (like before)
    if (typeof env.library !== 'undefined') {
        var included = JSON.parse(fs.readFileSync(env.library)).components;
        var filtered = {};
        included.forEach(function(name){
            filtered[name] = componentLib.definition.components[name];
        });
        componentLib.definition.components = filtered;
    }

    microflo.generate.updateDefinitions(componentLib, "./microflo");
}

var flashCommand = function(file, env) {
    require('coffee-script/register');
    var upload = require('./lib/flash.coffee');
    var tty = env.serial;
    var baud = parseInt(env.baudrate) || 115200;
    upload.avrUploadHexFile(file, tty, baud, function(err, written) {
        console.log(err, written);
    });
}

var main = function() {

    componentLib = new microflo.componentlib.ComponentLibrary(null, "./microflo");
    componentLib.load();

    commander
        .version(module.exports.version)

    commander
        .command('update-defs')
        .description('(internal use) Update the generated C++ headers from .json definitions.')
        .option('-l, --library <FILE>', 'which component library to use')
        .action(updateDefsCommand);

    commander
        .command('generate')
        .description('Generate MicroFlo firmware code, with embedded graph.')
        .action(generateFwCommand);

    commander
        .command('upload')
        .option('-s, --serial <PORT>', 'which serial port to use')
        .option('-b, --baudrate <RATE>', 'baudrate for serialport')
        .option('-d, --debug <LEVEL>', 'set debug level')
        .description('Upload a new graph to a device running MicroFlo firmware')
        .action(uploadGraphCommand);

    commander
        .command('runtime')
        .description('Run as a server, for use with the NoFlo UI.')
        .option('-s, --serial <PORT>', 'which serial port to use')
        .option('-b, --baudrate <RATE>', 'baudrate for serialport')
        .option('-d, --debug <LEVEL>', 'set debug level')
        .option('-p, --port <PORT>', 'which port to use for WebSocket')
        .option('-i, --ip <IP>', 'which IP to use for WebSocket')
        .action(setupRuntimeCommand)

    commander
        .command('register [USER]')
        .description('Register the runtime with Flowhub registry')
        .option('-p, --port <PORT>', 'WebSocket port')
        .option('-i, --ip <IP>', 'WebSocket IP')
        .option('-l, --label <PORT>', 'Label to show in UI for this runtime')
        .option('-r, --id <RUNTIME-ID>', 'UUID for the runtime')
        .action(registerRuntimeCommand)

    commander
        .command('flash <FILE.hex>')
        .description('Flash runtime onto device')
        .option('-s, --serial <PORT>', 'which serial port to use')
        .option('-b, --baudrate <RATE>', 'baudrate for serialport')
        .action(flashCommand)

    commander.parse(process.argv)
    if (process.argv.length <= 2) {
        commander.help()
    }
}

main();

<commit_msg>microflo.js: Fix missing require<commit_after>#!/usr/bin/env node
/* MicroFlo - Flow-Based Programming for microcontrollers
 * Copyright (c) 2013 Jon Nordby <jononor@gmail.com>
 * MicroFlo may be freely distributed under the MIT license
 */

var fs = require("fs");
var path = require("path");
var cmdFormat = require("./microflo/commandformat.json");
var microflo = require("./lib/microflo");
var commander = require("commander");
var pkginfo = require('pkginfo')(module);

var componentLib = null;

var setupRuntimeCommand = function(env) {
    var serialPortToUse = env.serial || "auto";
    var port = env.port || 3569;
    var debugLevel = env.debug || "Error";
    var ip = env.ip || "127.0.0.1"
    var baud = parseInt(env.baudrate) || 9600

    microflo.runtime.setupRuntime(serialPortToUse, baud, port, debugLevel, ip);
}

var uploadGraphCommand = function(graphPath, env) {
    var serialPortName = env.serial || "auto";
    var debugLevel = env.debug
    var baud = parseInt(env.baudrate) || 9600

    microflo.runtime.uploadGraphFromFile(graphPath, serialPortName, baud, debugLevel);
}

var generateFwCommand = function(env) {
    var inputFile = process.argv[3];
    var outputFile = process.argv[4] || inputFile.replace(path.extname(inputFile), "");
    var target = process.argv[5] || 'arduino'

    microflo.generate.generateOutput(componentLib, inputFile, outputFile, target);
}

var registerRuntimeCommand = function(user, env) {
    var ip = env.ip || 'auto';
    var port = parseInt(env.port) || 3569;
    var label = env.label || "MicroFlo"
    var id = env.id || process.env['MICROFLO_RUNTIME_ID'];

    if (!user) {
        user = process.env['FLOWHUB_USER_ID'];
    }

    var rt = microflo.runtime.createFlowhubRuntime(user, ip, port, label);
    if (!id) {
        microflo.runtime.registerFlowhubRuntime(rt, function(err, ok) {
            if (err) {
                console.log("Could not register runtime with Flowhub", err);
                process.exit(1);
            } else {
                console.log("Runtime registered with id:", rt.runtime.id);
            }
        });
    }
}

var updateDefsCommand = function(env) {
    // FIXME: move this code somewhere else, make more general
    // For now, default to all components (like before)
    if (typeof env.library !== 'undefined') {
        var included = JSON.parse(fs.readFileSync(env.library)).components;
        var filtered = {};
        included.forEach(function(name){
            filtered[name] = componentLib.definition.components[name];
        });
        componentLib.definition.components = filtered;
    }

    microflo.generate.updateDefinitions(componentLib, "./microflo");
}

var flashCommand = function(file, env) {
    require('coffee-script/register');
    var upload = require('./lib/flash.coffee');
    var tty = env.serial;
    var baud = parseInt(env.baudrate) || 115200;
    upload.avrUploadHexFile(file, tty, baud, function(err, written) {
        console.log(err, written);
    });
}

var main = function() {

    componentLib = new microflo.componentlib.ComponentLibrary(null, "./microflo");
    componentLib.load();

    commander
        .version(module.exports.version)

    commander
        .command('update-defs')
        .description('(internal use) Update the generated C++ headers from .json definitions.')
        .option('-l, --library <FILE>', 'which component library to use')
        .action(updateDefsCommand);

    commander
        .command('generate')
        .description('Generate MicroFlo firmware code, with embedded graph.')
        .action(generateFwCommand);

    commander
        .command('upload')
        .option('-s, --serial <PORT>', 'which serial port to use')
        .option('-b, --baudrate <RATE>', 'baudrate for serialport')
        .option('-d, --debug <LEVEL>', 'set debug level')
        .description('Upload a new graph to a device running MicroFlo firmware')
        .action(uploadGraphCommand);

    commander
        .command('runtime')
        .description('Run as a server, for use with the NoFlo UI.')
        .option('-s, --serial <PORT>', 'which serial port to use')
        .option('-b, --baudrate <RATE>', 'baudrate for serialport')
        .option('-d, --debug <LEVEL>', 'set debug level')
        .option('-p, --port <PORT>', 'which port to use for WebSocket')
        .option('-i, --ip <IP>', 'which IP to use for WebSocket')
        .action(setupRuntimeCommand)

    commander
        .command('register [USER]')
        .description('Register the runtime with Flowhub registry')
        .option('-p, --port <PORT>', 'WebSocket port')
        .option('-i, --ip <IP>', 'WebSocket IP')
        .option('-l, --label <PORT>', 'Label to show in UI for this runtime')
        .option('-r, --id <RUNTIME-ID>', 'UUID for the runtime')
        .action(registerRuntimeCommand)

    commander
        .command('flash <FILE.hex>')
        .description('Flash runtime onto device')
        .option('-s, --serial <PORT>', 'which serial port to use')
        .option('-b, --baudrate <RATE>', 'baudrate for serialport')
        .action(flashCommand)

    commander.parse(process.argv)
    if (process.argv.length <= 2) {
        commander.help()
    }
}

main();

<|endoftext|>


<commit_before>import React from 'react';
import {shallow} from 'enzyme';

import * as reporterProxy from '../../lib/reporter-proxy';
import BranchSet from '../../lib/models/branch-set';
import Branch, {nullBranch} from '../../lib/models/branch';
import RemoteSet from '../../lib/models/remote-set';
import Remote from '../../lib/models/remote';
import {GitError} from '../../lib/git-shell-out-strategy';
import {BareIssueishDetailController} from '../../lib/controllers/issueish-detail-controller';
import {issueishDetailControllerProps} from '../fixtures/props/issueish-pane-props';

describe('IssueishDetailController', function() {
  function buildApp(opts, overrideProps = {}) {
    return <BareIssueishDetailController {...issueishDetailControllerProps(opts, overrideProps)} />;
  }

  it('updates the pane title for a pull request on mount', function() {
    const onTitleChange = sinon.stub();
    shallow(buildApp({
      repositoryName: 'reponame',
      ownerLogin: 'ownername',
      issueishNumber: 12,
      pullRequestTitle: 'the title',
    }, {onTitleChange}));

    assert.isTrue(onTitleChange.calledWith('PR: ownername/reponame#12 — the title'));
  });

  it('updates the pane title for an issue on mount', function() {
    const onTitleChange = sinon.stub();
    shallow(buildApp({
      repositoryName: 'reponame',
      ownerLogin: 'ownername',
      issueKind: 'Issue',
      issueishNumber: 34,
      omitPullRequestData: true,
      issueTitle: 'the title',
    }, {onTitleChange}));
    assert.isTrue(onTitleChange.calledWith('Issue: ownername/reponame#34 — the title'));
  });

  it('updates the pane title on update', function() {
    const onTitleChange = sinon.stub();
    const wrapper = shallow(buildApp({
      repositoryName: 'reponame',
      ownerLogin: 'ownername',
      issueishNumber: 12,
      pullRequestTitle: 'the title',
    }, {onTitleChange}));
    assert.isTrue(onTitleChange.calledWith('PR: ownername/reponame#12 — the title'));

    wrapper.setProps(issueishDetailControllerProps({
      repositoryName: 'different',
      ownerLogin: 'new',
      issueishNumber: 34,
      pullRequestTitle: 'the title',
    }, {onTitleChange}));

    assert.isTrue(onTitleChange.calledWith('PR: new/different#34 — the title'));
  });

  it('leaves the title alone and renders a message if no repository was found', function() {
    const onTitleChange = sinon.stub();
    const wrapper = shallow(buildApp({}, {onTitleChange, repository: null, issueishNumber: 123}));
    assert.isFalse(onTitleChange.called);
    assert.match(wrapper.find('div').text(), /#123 not found/);
  });

  it('leaves the title alone and renders a message if no issueish was found', function() {
    const onTitleChange = sinon.stub();
    const wrapper = shallow(buildApp({omitIssueData: true, omitPullRequestData: true}, {onTitleChange, issueishNumber: 123}));
    assert.isFalse(onTitleChange.called);
    assert.match(wrapper.find('div').text(), /#123 not found/);
  });

  describe('checkoutOp', function() {
    it('is disabled if the repository is loading or absent', function() {
      const wrapper = shallow(buildApp({}, {isAbsent: true}));
      const op = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op.isEnabled());
      assert.strictEqual(op.getMessage(), 'No repository found');

      wrapper.setProps({isAbsent: false, isLoading: true});
      const op1 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op1.isEnabled());
      assert.strictEqual(op1.getMessage(), 'Loading');

      wrapper.setProps({isAbsent: false, isLoading: false, isPresent: false});
      const op2 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op2.isEnabled());
      assert.strictEqual(op2.getMessage(), 'No repository found');
    });

    it('is disabled if the local repository is merging or rebasing', function() {
      const wrapper = shallow(buildApp({}, {isMerging: true}));
      const op0 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op0.isEnabled());
      assert.strictEqual(op0.getMessage(), 'Merge in progress');

      wrapper.setProps({isMerging: false, isRebasing: true});
      const op1 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op1.isEnabled());
      assert.strictEqual(op1.getMessage(), 'Rebase in progress');
    });

    it('is disabled if the current branch already corresponds to the pull request', function() {
      const upstream = Branch.createRemoteTracking('remotes/origin/feature', 'origin', 'refs/heads/feature');
      const branches = new BranchSet([
        new Branch('current', upstream, upstream, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
      ]);

      const wrapper = shallow(buildApp({
        pullRequestHeadRef: 'feature',
        pullRequestHeadRepoOwner: 'aaa',
        pullRequestHeadRepoName: 'bbb',
      }, {
        branches,
        remotes,
      }));

      const op = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op.isEnabled());
      assert.strictEqual(op.getMessage(), 'Current');
    });

    it('recognizes a current branch even if it was pulled from the refs/pull/... ref', function() {
      const upstream = Branch.createRemoteTracking('remotes/origin/pull/123/head', 'origin', 'refs/pull/123/head');
      const branches = new BranchSet([
        new Branch('current', upstream, upstream, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
      ]);

      const wrapper = shallow(buildApp({
        repositoryName: 'bbb',
        ownerLogin: 'aaa',
        pullRequestHeadRef: 'feature',
        pullRequestNumber: 123,
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
      }));

      const op = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op.isEnabled());
      assert.strictEqual(op.getMessage(), 'Current');
    });

    it('creates a new remote, fetches a PR branch, and checks it out into a new local branch', async function() {
      const upstream = Branch.createRemoteTracking('remotes/origin/current', 'origin', 'refs/heads/current');
      const branches = new BranchSet([
        new Branch('current', upstream, upstream, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
      ]);

      const addRemote = sinon.stub().resolves(new Remote('ccc', 'git@github.com:ccc/ddd.git'));
      const fetch = sinon.stub().resolves();
      const checkout = sinon.stub().resolves();

      const wrapper = shallow(buildApp({
        issueishNumber: 456,
        pullRequestHeadRef: 'feature',
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
        addRemote,
        fetch,
        checkout,
      }));

      sinon.spy(reporterProxy, 'incrementCounter');
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();

      assert.isTrue(addRemote.calledWith('ccc', 'git@github.com:ccc/ddd.git'));
      assert.isTrue(fetch.calledWith('refs/heads/feature', {remoteName: 'ccc'}));
      assert.isTrue(checkout.calledWith('pr-456/ccc/feature', {
        createNew: true,
        track: true,
        startPoint: 'refs/remotes/ccc/feature',
      }));

      assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));
    });

    it('fetches a PR branch from an existing remote and checks it out into a new local branch', async function() {
      const branches = new BranchSet([
        new Branch('current', nullBranch, nullBranch, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
        new Remote('existing', 'git@github.com:ccc/ddd.git'),
      ]);

      const fetch = sinon.stub().resolves();
      const checkout = sinon.stub().resolves();

      const wrapper = shallow(buildApp({
        issueishNumber: 789,
        pullRequestHeadRef: 'clever-name',
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
        fetch,
        checkout,
      }));

      sinon.spy(reporterProxy, 'incrementCounter');
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();

      assert.isTrue(fetch.calledWith('refs/heads/clever-name', {remoteName: 'existing'}));
      assert.isTrue(checkout.calledWith('pr-789/ccc/clever-name', {
        createNew: true,
        track: true,
        startPoint: 'refs/remotes/existing/clever-name',
      }));

      assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));
    });

    it('checks out an existing local branch that corresponds to the pull request', async function() {
      const currentUpstream = Branch.createRemoteTracking('remotes/origin/current', 'origin', 'refs/heads/current');
      const branches = new BranchSet([
        new Branch('current', currentUpstream, currentUpstream, true),
        new Branch('existing', Branch.createRemoteTracking('remotes/upstream/pull/123', 'upstream', 'refs/heads/yes')),
        new Branch('wrong/remote', Branch.createRemoteTracking('remotes/wrong/pull/123', 'wrong', 'refs/heads/yes')),
        new Branch('wrong/ref', Branch.createRemoteTracking('remotes/upstream/pull/123', 'upstream', 'refs/heads/no')),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
        new Remote('upstream', 'git@github.com:ccc/ddd.git'),
        new Remote('wrong', 'git@github.com:eee/fff.git'),
      ]);

      const pull = sinon.stub().resolves();
      const checkout = sinon.stub().resolves();

      const wrapper = shallow(buildApp({
        issueishNumber: 456,
        pullRequestHeadRef: 'yes',
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
        fetch,
        pull,
        checkout,
      }));

      sinon.spy(reporterProxy, 'incrementCounter');
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();

      assert.isTrue(checkout.calledWith('existing'));
      assert.isTrue(pull.calledWith('refs/heads/yes', {remoteName: 'upstream', ffOnly: true}));
      assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));
    });

    it('squelches git errors', async function() {
      const addRemote = sinon.stub().rejects(new GitError('handled by the pipeline'));
      const wrapper = shallow(buildApp({}, {addRemote}));

      // Should not throw
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();
      assert.isTrue(addRemote.called);
    });

    it('propagates non-git errors', async function() {
      const addRemote = sinon.stub().rejects(new Error('not handled by the pipeline'));
      const wrapper = shallow(buildApp({}, {addRemote}));

      await assert.isRejected(
        wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run(),
        /not handled by the pipeline/,
      );
      assert.isTrue(addRemote.called);
    });
  });
});
<commit_msg>fix fromPullRefSpec test<commit_after>import React from 'react';
import {shallow} from 'enzyme';

import * as reporterProxy from '../../lib/reporter-proxy';
import BranchSet from '../../lib/models/branch-set';
import Branch, {nullBranch} from '../../lib/models/branch';
import RemoteSet from '../../lib/models/remote-set';
import Remote from '../../lib/models/remote';
import {GitError} from '../../lib/git-shell-out-strategy';
import {BareIssueishDetailController} from '../../lib/controllers/issueish-detail-controller';
import {issueishDetailControllerProps} from '../fixtures/props/issueish-pane-props';

describe('IssueishDetailController', function() {
  function buildApp(opts, overrideProps = {}) {
    return <BareIssueishDetailController {...issueishDetailControllerProps(opts, overrideProps)} />;
  }

  it('updates the pane title for a pull request on mount', function() {
    const onTitleChange = sinon.stub();
    shallow(buildApp({
      repositoryName: 'reponame',
      ownerLogin: 'ownername',
      issueishNumber: 12,
      pullRequestTitle: 'the title',
    }, {onTitleChange}));

    assert.isTrue(onTitleChange.calledWith('PR: ownername/reponame#12 — the title'));
  });

  it('updates the pane title for an issue on mount', function() {
    const onTitleChange = sinon.stub();
    shallow(buildApp({
      repositoryName: 'reponame',
      ownerLogin: 'ownername',
      issueKind: 'Issue',
      issueishNumber: 34,
      omitPullRequestData: true,
      issueTitle: 'the title',
    }, {onTitleChange}));
    assert.isTrue(onTitleChange.calledWith('Issue: ownername/reponame#34 — the title'));
  });

  it('updates the pane title on update', function() {
    const onTitleChange = sinon.stub();
    const wrapper = shallow(buildApp({
      repositoryName: 'reponame',
      ownerLogin: 'ownername',
      issueishNumber: 12,
      pullRequestTitle: 'the title',
    }, {onTitleChange}));
    assert.isTrue(onTitleChange.calledWith('PR: ownername/reponame#12 — the title'));

    wrapper.setProps(issueishDetailControllerProps({
      repositoryName: 'different',
      ownerLogin: 'new',
      issueishNumber: 34,
      pullRequestTitle: 'the title',
    }, {onTitleChange}));

    assert.isTrue(onTitleChange.calledWith('PR: new/different#34 — the title'));
  });

  it('leaves the title alone and renders a message if no repository was found', function() {
    const onTitleChange = sinon.stub();
    const wrapper = shallow(buildApp({}, {onTitleChange, repository: null, issueishNumber: 123}));
    assert.isFalse(onTitleChange.called);
    assert.match(wrapper.find('div').text(), /#123 not found/);
  });

  it('leaves the title alone and renders a message if no issueish was found', function() {
    const onTitleChange = sinon.stub();
    const wrapper = shallow(buildApp({omitIssueData: true, omitPullRequestData: true}, {onTitleChange, issueishNumber: 123}));
    assert.isFalse(onTitleChange.called);
    assert.match(wrapper.find('div').text(), /#123 not found/);
  });

  describe('checkoutOp', function() {
    it('is disabled if the repository is loading or absent', function() {
      const wrapper = shallow(buildApp({}, {isAbsent: true}));
      const op = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op.isEnabled());
      assert.strictEqual(op.getMessage(), 'No repository found');

      wrapper.setProps({isAbsent: false, isLoading: true});
      const op1 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op1.isEnabled());
      assert.strictEqual(op1.getMessage(), 'Loading');

      wrapper.setProps({isAbsent: false, isLoading: false, isPresent: false});
      const op2 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op2.isEnabled());
      assert.strictEqual(op2.getMessage(), 'No repository found');
    });

    it('is disabled if the local repository is merging or rebasing', function() {
      const wrapper = shallow(buildApp({}, {isMerging: true}));
      const op0 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op0.isEnabled());
      assert.strictEqual(op0.getMessage(), 'Merge in progress');

      wrapper.setProps({isMerging: false, isRebasing: true});
      const op1 = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op1.isEnabled());
      assert.strictEqual(op1.getMessage(), 'Rebase in progress');
    });

    it('is disabled if the current branch already corresponds to the pull request', function() {
      const upstream = Branch.createRemoteTracking('remotes/origin/feature', 'origin', 'refs/heads/feature');
      const branches = new BranchSet([
        new Branch('current', upstream, upstream, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
      ]);

      const wrapper = shallow(buildApp({
        pullRequestHeadRef: 'feature',
        pullRequestHeadRepoOwner: 'aaa',
        pullRequestHeadRepoName: 'bbb',
      }, {
        branches,
        remotes,
      }));

      const op = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op.isEnabled());
      assert.strictEqual(op.getMessage(), 'Current');
    });

    it('recognizes a current branch even if it was pulled from the refs/pull/... ref', function() {
      const upstream = Branch.createRemoteTracking('remotes/origin/pull/123/head', 'origin', 'refs/pull/123/head');
      const branches = new BranchSet([
        new Branch('current', upstream, upstream, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
      ]);

      const wrapper = shallow(buildApp({
        repositoryName: 'bbb',
        ownerLogin: 'aaa',
        pullRequestHeadRef: 'feature',
        issueishNumber: 123,
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
      }));

      const op = wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp');
      assert.isFalse(op.isEnabled());
      assert.strictEqual(op.getMessage(), 'Current');
    });

    it('creates a new remote, fetches a PR branch, and checks it out into a new local branch', async function() {
      const upstream = Branch.createRemoteTracking('remotes/origin/current', 'origin', 'refs/heads/current');
      const branches = new BranchSet([
        new Branch('current', upstream, upstream, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
      ]);

      const addRemote = sinon.stub().resolves(new Remote('ccc', 'git@github.com:ccc/ddd.git'));
      const fetch = sinon.stub().resolves();
      const checkout = sinon.stub().resolves();

      const wrapper = shallow(buildApp({
        issueishNumber: 456,
        pullRequestHeadRef: 'feature',
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
        addRemote,
        fetch,
        checkout,
      }));

      sinon.spy(reporterProxy, 'incrementCounter');
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();

      assert.isTrue(addRemote.calledWith('ccc', 'git@github.com:ccc/ddd.git'));
      assert.isTrue(fetch.calledWith('refs/heads/feature', {remoteName: 'ccc'}));
      assert.isTrue(checkout.calledWith('pr-456/ccc/feature', {
        createNew: true,
        track: true,
        startPoint: 'refs/remotes/ccc/feature',
      }));

      assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));
    });

    it('fetches a PR branch from an existing remote and checks it out into a new local branch', async function() {
      const branches = new BranchSet([
        new Branch('current', nullBranch, nullBranch, true),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
        new Remote('existing', 'git@github.com:ccc/ddd.git'),
      ]);

      const fetch = sinon.stub().resolves();
      const checkout = sinon.stub().resolves();

      const wrapper = shallow(buildApp({
        issueishNumber: 789,
        pullRequestHeadRef: 'clever-name',
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
        fetch,
        checkout,
      }));

      sinon.spy(reporterProxy, 'incrementCounter');
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();

      assert.isTrue(fetch.calledWith('refs/heads/clever-name', {remoteName: 'existing'}));
      assert.isTrue(checkout.calledWith('pr-789/ccc/clever-name', {
        createNew: true,
        track: true,
        startPoint: 'refs/remotes/existing/clever-name',
      }));

      assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));
    });

    it('checks out an existing local branch that corresponds to the pull request', async function() {
      const currentUpstream = Branch.createRemoteTracking('remotes/origin/current', 'origin', 'refs/heads/current');
      const branches = new BranchSet([
        new Branch('current', currentUpstream, currentUpstream, true),
        new Branch('existing', Branch.createRemoteTracking('remotes/upstream/pull/123', 'upstream', 'refs/heads/yes')),
        new Branch('wrong/remote', Branch.createRemoteTracking('remotes/wrong/pull/123', 'wrong', 'refs/heads/yes')),
        new Branch('wrong/ref', Branch.createRemoteTracking('remotes/upstream/pull/123', 'upstream', 'refs/heads/no')),
      ]);
      const remotes = new RemoteSet([
        new Remote('origin', 'git@github.com:aaa/bbb.git'),
        new Remote('upstream', 'git@github.com:ccc/ddd.git'),
        new Remote('wrong', 'git@github.com:eee/fff.git'),
      ]);

      const pull = sinon.stub().resolves();
      const checkout = sinon.stub().resolves();

      const wrapper = shallow(buildApp({
        issueishNumber: 456,
        pullRequestHeadRef: 'yes',
        pullRequestHeadRepoOwner: 'ccc',
        pullRequestHeadRepoName: 'ddd',
      }, {
        branches,
        remotes,
        fetch,
        pull,
        checkout,
      }));

      sinon.spy(reporterProxy, 'incrementCounter');
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();

      assert.isTrue(checkout.calledWith('existing'));
      assert.isTrue(pull.calledWith('refs/heads/yes', {remoteName: 'upstream', ffOnly: true}));
      assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));
    });

    it('squelches git errors', async function() {
      const addRemote = sinon.stub().rejects(new GitError('handled by the pipeline'));
      const wrapper = shallow(buildApp({}, {addRemote}));

      // Should not throw
      await wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run();
      assert.isTrue(addRemote.called);
    });

    it('propagates non-git errors', async function() {
      const addRemote = sinon.stub().rejects(new Error('not handled by the pipeline'));
      const wrapper = shallow(buildApp({}, {addRemote}));

      await assert.isRejected(
        wrapper.find('Relay(BarePullRequestDetailView)').prop('checkoutOp').run(),
        /not handled by the pipeline/,
      );
      assert.isTrue(addRemote.called);
    });
  });
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';

import RadioButtonGroup from '~/components/RadioButtonGroup';

export default class App extends Component {
	constructor(props) {
    super(props);
    this.state = {
    	selectedValue: undefined,
    	radioOptions: [
	      { value: 'CreditCard', text: 'Credit Card' },
	      { value: 'DebitCard', text: 'Debit Card'},
	      { value: 'DebitCard', text: 'Debit Card'}
	    ]
  	};
  }

  handleSelection(value) {
  	this.setState({selectedValue: value});
  }

	render() {
		return (

 Welcome for the radio button example

						<RadioButtonGroup listOfItems={this.state.radioOptions} selectedItemCallback={(value) => this.handleSelection(value)}/>

Selected radio button: {this.state.selectedValue}

		);
	}
}<commit_msg>Updated AppJs<commit_after>import React, { Component, PropTypes } from 'react';

import RadioButtonGroup from '~/components/RadioButtonGroup';

export default class App extends Component {
	constructor(props) {
    super(props);
    this.state = {
    	selectedValue: undefined,
    	radioOptions: [
	      { value: 'CreditCard', text: 'Credit Card' },
	      { value: 'DebitCard', text: 'Debit Card'}
	    ]
  	};
  }

  handleSelection(value) {
  	this.setState({selectedValue: value});
  }

	render() {
		return (

 Welcome for the radio button example

						<RadioButtonGroup listOfItems={this.state.radioOptions} selectedItemCallback={(value) => this.handleSelection(value)}/>

Selected radio button: {this.state.selectedValue}

		);
	}
}
<|endoftext|>


<commit_before>import React from "react";
import TodoInput from "./TodoInput";

const App = () => {
  return (
    <TodoInput />
  );
}

export default App;
<commit_msg>Add TodoList container to App<commit_after>import React from "react";
import TodoInput from "./TodoInput";
import TodoList from "./TodoList";

const App = () => {
  return (
    <div>
      <TodoInput />
      <TodoList />
    </div>
  );
}

export default App;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';

import { closeAll } from '../actions/OverlayActionCreators';
import { selectPanel } from '../actions/PanelSelectActionCreators';
import { sendChat } from '../actions/ChatActionCreators';
import { set as setSetting } from '../actions/SettingsActionCreators';

import { sizeSelector, positionSelector } from '../selectors/waitlistSelectors';
import { currentUserSelector } from '../selectors/userSelectors';
import { settingsSelector } from '../selectors/settingSelectors';
import MuiTheme from '../MuiTheme';
import App from '../components/App';

const mapStateToProps = createStructuredSelector({
  activeOverlay: state => state.activeOverlay,
  selectedPanel: state => state.selectedPanel,
  settings: settingsSelector,
  user: currentUserSelector,
  waitlistPosition: positionSelector,
  waitlistSize: sizeSelector
});

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    selectPanel,
    sendChatMessage: sendChat,
    onCloseOverlay: closeAll,
    onSettingChange: setSetting
  }, dispatch);
}

@ThemeDecorator(ThemeManager.getMuiTheme(MuiTheme))
@connect(mapStateToProps, mapDispatchToProps)
export default class AppContainer extends Component {
  static propTypes = {
    activeOverlay: PropTypes.string,
    selectedPanel: PropTypes.string,
    settings: PropTypes.object,
    user: PropTypes.object,

    onCloseOverlay: PropTypes.func,
    onSettingChange: setSetting,
    selectPanel: PropTypes.func,
    sendChatMessage: PropTypes.func
  };

  render() {
    return <App {...this.props} />;
  }
}
<commit_msg>app: fix onSettingChange proptype<commit_after>import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';

import { closeAll } from '../actions/OverlayActionCreators';
import { selectPanel } from '../actions/PanelSelectActionCreators';
import { sendChat } from '../actions/ChatActionCreators';
import { set as setSetting } from '../actions/SettingsActionCreators';

import { sizeSelector, positionSelector } from '../selectors/waitlistSelectors';
import { currentUserSelector } from '../selectors/userSelectors';
import { settingsSelector } from '../selectors/settingSelectors';
import MuiTheme from '../MuiTheme';
import App from '../components/App';

const mapStateToProps = createStructuredSelector({
  activeOverlay: state => state.activeOverlay,
  selectedPanel: state => state.selectedPanel,
  settings: settingsSelector,
  user: currentUserSelector,
  waitlistPosition: positionSelector,
  waitlistSize: sizeSelector
});

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    selectPanel,
    sendChatMessage: sendChat,
    onCloseOverlay: closeAll,
    onSettingChange: setSetting
  }, dispatch);
}

@ThemeDecorator(ThemeManager.getMuiTheme(MuiTheme))
@connect(mapStateToProps, mapDispatchToProps)
export default class AppContainer extends Component {
  static propTypes = {
    activeOverlay: PropTypes.string,
    selectedPanel: PropTypes.string,
    settings: PropTypes.object,
    user: PropTypes.object,

    onCloseOverlay: PropTypes.func,
    onSettingChange: PropTypes.func,
    selectPanel: PropTypes.func,
    sendChatMessage: PropTypes.func
  };

  render() {
    return <App {...this.props} />;
  }
}
<|endoftext|>


<commit_before>/* eslint max-len: ["error", 100 ] */
/* global describe, beforeEach, afterEach, it, expect */
'use strict';

describe('Selenium Tutorial', function() {

    var selenium = require('selenium-webdriver');
    var timeoutMilliSec = 10 * 1000;

    // Open the TECH.insight website in the browser before each test is run
    beforeEach(function(done) {
        this.driver = new selenium.Builder().
            withCapabilities(selenium.Capabilities.firefox()).
            build();
        this.driver.manage().timeouts().implicitlyWait(timeoutMilliSec);
        jasmine.DEFAULT_TIMEOUT_INTERVAL = timeoutMilliSec;
        this.driver.get('https://narrative.kbase.us/').then(done);
    });

    // Close the website after each test is run (so that it is opened fresh each time)
    afterEach(function(done) {
        this.driver.quit().then(done);
    });

    // Test to ensure we are on the home page by checking for username input
    it('Should be on the login page', function(done) {
        var element = this.driver.findElement(selenium.By.name('username'));
        element.getAttribute('id').then(function(id) {
            expect(id).toBeDefined();
            done();
        });
    });

});
<commit_msg>Connect to local instance and look for signin button<commit_after>/* eslint max-len: ["error", 100 ] */
/* global describe, beforeEach, afterEach, it, expect */
'use strict';

describe('Selenium Tutorial', function() {

    var selenium = require('selenium-webdriver');
    var timeoutMilliSec = 10 * 1000;

    // Open the TECH.insight website in the browser before each test is run
    beforeEach(function(done) {
        this.driver = new selenium.Builder().
            withCapabilities(selenium.Capabilities.firefox()).
            build();
        this.driver.manage().timeouts().implicitlyWait(timeoutMilliSec);
        jasmine.DEFAULT_TIMEOUT_INTERVAL = timeoutMilliSec;
        this.driver.get('http://localhost:9999/narrative/').then(done);
    });

    // Close the website after each test is run (so that it is opened fresh each time)
    afterEach(function(done) {
        this.driver.quit().then(done);
    });

    // Test to ensure we are on the home page by checking for username input
    it('Should be on the narrative tree page', function(done) {
        var element = this.driver.findElement(selenium.By.id('signin-button'));
        element.getAttribute('id').then(function(id) {
            expect(id).toBeDefined();
            done();
        });
    });

});
<|endoftext|>


<commit_before>function ContentBuilder (servico) {
	this.servico = servico;
	this.docContent = [];
	this.parseHtml = new ParseHtml();
}

ContentBuilder.prototype.addContent = function (content) {
	this.docContent.push(content);
};

ContentBuilder.prototype.addNewLine = function () {
	this.addContent('\n');
};

ContentBuilder.prototype.buildNome = function () {
	this.addContent({ text: this.servico.nome + ' (' + this.servico.sigla + ')', style: 'header' });
	this.addNewLine();
};

ContentBuilder.prototype.buildDescricao = function () {
	this.addContent({ text: 'O que é?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.descricao, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildSolicitantes = function () {
	var self = this;

	this.addContent({ text: 'Quem pode utilizar este serviço?', style: 'subheader' });
	this.addNewLine();

	$(this.servico.solicitantes).each(function(index, solicitante) {
		self.addContent({ text: solicitante.tipo , style: 'thirdheader' });
		self.addContent({ text: solicitante.requisitos , style: 'paragraph' });
		self.addNewLine();
	});

	this.addContent({ text: '', style: 'paragraph', pageBreak: 'after' });
};

ContentBuilder.prototype.buildTempoTotalEstimado = function () {
	this.addContent({ text: 'Quanto tempo leva?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.tempoTotalEstimado.max + ' ' + this.servico.tempoTotalEstimado.unidade, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildLegislacoes = function () {
	var content = [];
	var textoHtml = markdown.toHTML(this.servico.legislacoes[0]);

	this.addContent({ text: 'Legislação', style: 'subheader' });
	this.addNewLine();

	this.parseHtml.parseHtml(content, textoHtml);
	console.log(content);
	this.docContent = this.docContent.concat(content);
	this.addNewLine();
};

ContentBuilder.prototype.buildOutrasInformacoes = function () {
	this.addContent({ text: 'Outras informações', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: 'Você também pode conhecer este serviço como: ' + this.servico.nomesPopulares.join(', ') + '.', style: 'paragraph' });
	this.addNewLine();
	this.addContent({ text: this.servico.gratuito ? 'Este serviço é gratuito para o cidadão.' : '', style: 'paragraph' });
};

ContentBuilder.prototype.buildEtapa = function (index, etapa) {
	this.addContent({ text: 'Etapa ' + (index + 1) + ' - ' + etapa.titulo, style: 'thirdheader' });
	this.addNewLine();
	this.addContent({ text: etapa.descricao, style: 'paragraph' });
	this.addNewLine();

	if(etapa.documentos.items.length > 0) { this.buildDocumentos(etapa.documentos); }
	if(etapa.custos.items.length > 0) { this.buildCustos(etapa.custos); }
	if(etapa.canaisDePrestacao.items.length > 0) { this.buildCanais(etapa.canaisDePrestacao); }
};

ContentBuilder.prototype.buildDocumentos = function (documentos) {
	this.addContent({ text: 'Documentos necessários para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var documentosDoc = [];

	documentosDoc.push({ text: 'Documentação comum para todos', style: 'thirdheader' });
	documentosDoc.push({ ul: documentos.items, style: 'list' });
	documentosDoc.push('\n');

	$(documentos.casos).each(function(index, caso) {
		documentosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		documentosDoc.push({ ul: caso.items, style: 'list' });
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: documentosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCustos = function (custos) {
	this.addContent({ text: 'Custos para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var custosDoc = [];

	custosDoc.push({ text: 'Custos padrão', style: 'thirdheader' });

	$(custos.items).each(function(index, custo) {
		custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
	});

	custosDoc.push('\n');

	$(custos.casos).each(function(index, caso) {
		custosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, custo) {
			custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: custosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCanais = function (canais) {
	this.addContent({ text: 'Canais de comunicação com este serviço:', style: 'thirdheader' });
	this.addNewLine();

	var canaisDoc = [];

	this.addContent({ text: 'Canais de prestação padrão', style: 'thirdheader' });

	$(canais.items).each(function(index, canal) {
		canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
	});

	canaisDoc.push('\n');

	$(canais.casos).each(function(index, caso) {
		canaisDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, canal) {
			canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: canaisDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildEtapas = function () {
	var self = this;

	this.addContent({ text: 'Etapas para a realização desse serviço', style: 'subheader' });
	this.addNewLine();

	$(this.servico.etapas).each(function(index, etapa){
		self.buildEtapa(index, etapa);
	});
};

ContentBuilder.prototype.buildContent = function () {
	this.buildNome();
	this.buildDescricao();
	this.buildSolicitantes();
	this.buildEtapas();
	this.buildTempoTotalEstimado();
	this.buildLegislacoes();
	this.buildOutrasInformacoes();

	return this.docContent;
};
<commit_msg>Removido console.log<commit_after>function ContentBuilder (servico) {
	this.servico = servico;
	this.docContent = [];
	this.parseHtml = new ParseHtml();
}

ContentBuilder.prototype.addContent = function (content) {
	this.docContent.push(content);
};

ContentBuilder.prototype.addNewLine = function () {
	this.addContent('\n');
};

ContentBuilder.prototype.buildNome = function () {
	this.addContent({ text: this.servico.nome + ' (' + this.servico.sigla + ')', style: 'header' });
	this.addNewLine();
};

ContentBuilder.prototype.buildDescricao = function () {
	this.addContent({ text: 'O que é?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.descricao, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildSolicitantes = function () {
	var self = this;

	this.addContent({ text: 'Quem pode utilizar este serviço?', style: 'subheader' });
	this.addNewLine();

	$(this.servico.solicitantes).each(function(index, solicitante) {
		self.addContent({ text: solicitante.tipo , style: 'thirdheader' });
		self.addContent({ text: solicitante.requisitos , style: 'paragraph' });
		self.addNewLine();
	});

	this.addContent({ text: '', style: 'paragraph', pageBreak: 'after' });
};

ContentBuilder.prototype.buildTempoTotalEstimado = function () {
	this.addContent({ text: 'Quanto tempo leva?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.tempoTotalEstimado.max + ' ' + this.servico.tempoTotalEstimado.unidade, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildLegislacoes = function () {
	var content = [];
	var textoHtml = markdown.toHTML(this.servico.legislacoes[0]);

	this.addContent({ text: 'Legislação', style: 'subheader' });
	this.addNewLine();

	this.parseHtml.parseHtml(content, textoHtml);
	this.docContent = this.docContent.concat(content);
	this.addNewLine();
};

ContentBuilder.prototype.buildOutrasInformacoes = function () {
	this.addContent({ text: 'Outras informações', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: 'Você também pode conhecer este serviço como: ' + this.servico.nomesPopulares.join(', ') + '.', style: 'paragraph' });
	this.addNewLine();
	this.addContent({ text: this.servico.gratuito ? 'Este serviço é gratuito para o cidadão.' : '', style: 'paragraph' });
};

ContentBuilder.prototype.buildEtapa = function (index, etapa) {
	this.addContent({ text: 'Etapa ' + (index + 1) + ' - ' + etapa.titulo, style: 'thirdheader' });
	this.addNewLine();
	this.addContent({ text: etapa.descricao, style: 'paragraph' });
	this.addNewLine();

	if(etapa.documentos.items.length > 0) { this.buildDocumentos(etapa.documentos); }
	if(etapa.custos.items.length > 0) { this.buildCustos(etapa.custos); }
	if(etapa.canaisDePrestacao.items.length > 0) { this.buildCanais(etapa.canaisDePrestacao); }
};

ContentBuilder.prototype.buildDocumentos = function (documentos) {
	this.addContent({ text: 'Documentos necessários para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var documentosDoc = [];

	documentosDoc.push({ text: 'Documentação comum para todos', style: 'thirdheader' });
	documentosDoc.push({ ul: documentos.items, style: 'list' });
	documentosDoc.push('\n');

	$(documentos.casos).each(function(index, caso) {
		documentosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		documentosDoc.push({ ul: caso.items, style: 'list' });
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: documentosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCustos = function (custos) {
	this.addContent({ text: 'Custos para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var custosDoc = [];

	custosDoc.push({ text: 'Custos padrão', style: 'thirdheader' });

	$(custos.items).each(function(index, custo) {
		custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
	});

	custosDoc.push('\n');

	$(custos.casos).each(function(index, caso) {
		custosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, custo) {
			custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: custosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCanais = function (canais) {
	this.addContent({ text: 'Canais de comunicação com este serviço:', style: 'thirdheader' });
	this.addNewLine();

	var canaisDoc = [];

	this.addContent({ text: 'Canais de prestação padrão', style: 'thirdheader' });

	$(canais.items).each(function(index, canal) {
		canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
	});

	canaisDoc.push('\n');

	$(canais.casos).each(function(index, caso) {
		canaisDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, canal) {
			canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: canaisDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildEtapas = function () {
	var self = this;

	this.addContent({ text: 'Etapas para a realização desse serviço', style: 'subheader' });
	this.addNewLine();

	$(this.servico.etapas).each(function(index, etapa){
		self.buildEtapa(index, etapa);
	});
};

ContentBuilder.prototype.buildContent = function () {
	this.buildNome();
	this.buildDescricao();
	this.buildSolicitantes();
	this.buildEtapas();
	this.buildTempoTotalEstimado();
	this.buildLegislacoes();
	this.buildOutrasInformacoes();

	return this.docContent;
};
<|endoftext|>


<commit_before>/**
 * RootController.test.js
 */
var request = require('supertest');
var should = require('should');

/**
 * Test API "ping" endpoint.
 */
describe('Requests to the root (/api) path', function() {

  it('GET: Returns a 200 status code', function (done) {
    request(sails.hooks.http.app)
      .get('/api')
      .expect(200, done);
  });

  it('GET: Returns JSON format', function(done) {
    request(app)
      .get('/api')
      .expect("content-type", /json/, done)
  });

});
<commit_msg>Basic tests for /api/v1<commit_after>/**
 * RootController.test.js
 */
var request = require('supertest');
var should = require('should');

/**
 * Test API "ping" endpoint.
 */
describe('Requests to the root (/api) path', function() {

  it('GET: Returns a 200 status code', function (done) {
    request(sails.hooks.http.app)
      .get('/api')
      .expect(200, done);
  });

  it('GET: Returns JSON format', function(done) {
    request(app)
      .get('/api')
      .expect("content-type", /json/, done)
  });

});

/**
 * Test API V1 information / status endpoint.
 */
describe('Requests to v1 root (/api/v1) path', function() {

  it('GET: Returns a 200 status code', function(done) {

    request(sails.hooks.http.app)
      .get('/api/v1')
      .expect(200, done);
  });

  it('GET: Returns JSON format', function(done) {

    request(sails.hooks.http.app)
      .get('/api/v1')
      .expect("content-type", /json/, done)
  });
});
<|endoftext|>


<commit_before>// module.exports = {
//   banner: true,
//   format: ["cjs", "umd-min"],
//   exports: "named",
//   css: true,
//   plugins: ["vue"],
//   vue: { css: true },
//   outDir: "lib-dist"
// };

module.exports = {
  banner: true,

  input: "src/lib.js",

  output: {
    moduleName: "Vue2Editor",
    extractCSS: false,
    format: ["esm", "umd", "cjs"],
    fileName({ format }, defaultFileName) {
      if (format === "esm") return "vue2-editor.esm.js";
      if (format === "umd") return "vue2-editor.js";
      if (format === "cjs") return "vue2-editor.cjs.js";
      return defaultFileName;
    },
    sourceMapExcludeSources: true
  },

  babel: {
    minimal: true
  },

  plugins: {
    vue: true,
    alias: {
      resolve: [".vue", ".js"],
      "@/helpers": "./../helpers/"
    }
  },

  extendConfig(config, { format }) {
    if (format === "umd") {
      config.output.minify = true;
      config.env = Object.assign({}, config.env, {
        NODE_ENV: "production"
      });
    }
    return config;
  }
};
<commit_msg>chore: removes unused code<commit_after>module.exports = {
  banner: true,

  input: "src/lib.js",

  output: {
    moduleName: "Vue2Editor",
    extractCSS: false,
    format: ["esm", "umd", "cjs"],
    fileName({ format }, defaultFileName) {
      if (format === "esm") return "vue2-editor.esm.js";
      if (format === "umd") return "vue2-editor.js";
      if (format === "cjs") return "vue2-editor.cjs.js";
      return defaultFileName;
    },
    sourceMapExcludeSources: true
  },

  babel: {
    minimal: true
  },

  plugins: {
    vue: true,
    alias: {
      resolve: [".vue", ".js"],
      "@/helpers": "./../helpers/"
    }
  },

  extendConfig(config, { format }) {
    if (format === "umd") {
      config.output.minify = true;
      config.env = Object.assign({}, config.env, {
        NODE_ENV: "production"
      });
    }
    return config;
  }
};
<|endoftext|>


<commit_before>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2014 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* A basic linked list data structure.
*
* @class Phaser.ArrayList
* @constructor
*/
Phaser.ArrayList = function () {

    /**
    * @property {number} total - Number of objects in the list.
    * @default
    */
    this.total = 0;

    /**
    * @property {number} position - Current cursor position.
    * @default
    */
    this.position = 0;

    /**
    * @property {array} list - The list.
    */
    this.list = [];

};

Phaser.ArrayList.prototype = {

    /**
    * Adds a new element to this linked list.
    *
    * @method Phaser.ArrayList#add
    * @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
    * @return {object} The child that was added.
    */
    add: function (child) {

        if (!this.exists(child))
        {
            this.list.push(child);
            this.total++;
        }

        return child;

    },

    getIndex: function (child) {

        var i = this.list.length;

        while (i--)
        {
            if (this.list[i] === child)
            {
                return i;
            }
        }

        return -1;

    },

    exists: function (child) {

        var i = this.list.length;

        while (i--)
        {
            if (this.list[i] === child)
            {
                return true;
            }
        }

        return false;

    },

    /**
    * Resets the first, last, next and previous node pointers in this list.
    *
    * @method Phaser.ArrayList#reset
    */
    reset: function () {

        this.list.length = 0;
        this.total = 0;

    },

    /**
    * Removes the given element from this linked list if it exists.
    *
    * @method Phaser.ArrayList#remove
    * @param {object} child - The child to be removed from the list.
    */
    remove: function (child) {

        var idx = this.getIndex(child);

        if (idx > -1)
        {
            this.list.splice(idx, 1);
            this.total--;
            return child;
        }

    },

    /**
    * Calls a function on all members of this list, using the member as the context for the callback.
    * The function must exist on the member.
    *
    * @method Phaser.ArrayList#callAll
    * @param {function} callback - The function to call.
    * @param {...*} parameter - Additional parameters that will be passed to the callback.
    */
    callAll: function (callback) {

        var args = Array.prototype.splice.call(arguments, 1);

        var i = this.list.length;

        while (i--)
        {
            this.list[i][callback].apply(this.list[i], args);
        }

    }

};

/**
*
*
* @name Phaser.ArrayList#first
* @property {object} first - The first item in the list.
*/
Object.defineProperty(Phaser.ArrayList.prototype, "first", {

    get: function () {

        this.position = 0;

        if (this.total > 0)
        {
            return this.list[0];
        }
        else
        {
            return null;
        }

    }

});

/**
*
*
* @name Phaser.ArrayList#next
* @property {object} next - Advanced the cursor and return.
*/
Object.defineProperty(Phaser.ArrayList.prototype, "next", {

    get: function () {

        if (this.position < this.total)
        {
            this.position++;

            return this.list[this.position];
        }
        else
        {
            return null;
        }

    }

});

Phaser.ArrayList.prototype.constructor = Phaser.ArrayList;
<commit_msg>Tidied up the ArrayList. May rename to Stack?<commit_after>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2014 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* A basic stack data structure. Allows items to add themselves to and remove themselves from the stack. Items can only exist once in the stack.
*
* @class Phaser.ArrayList
* @constructor
*/
Phaser.ArrayList = function () {

    /**
    * @property {number} total - Number of objects in the list.
    * @default
    */
    this.total = 0;

    /**
    * @property {number} position - Current cursor position.
    * @default
    */
    this.position = 0;

    /**
    * @property {array} list - The list.
    */
    this.list = [];

};

Phaser.ArrayList.prototype = {

    /**
    * Adds a new element to this list. The item can only exist in the list once.
    *
    * @method Phaser.ArrayList#add
    * @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
    * @return {object} The child that was added.
    */
    add: function (child) {

        if (!this.exists(child))
        {
            this.list.push(child);
            this.total++;
        }

        return child;

    },

    /**
    * Gets the index of the child in the list, or -1 if it isn't in the list.
    *
    * @method Phaser.ArrayList#getIndex
    * @param {object} child - The element to get the list index for.
    * @return {number} The index of the child or -1 if not found.
    */
    getIndex: function (child) {

        return this.list.indexOf(child);

    },

    /**
    * Checks for the child within this list.
    *
    * @method Phaser.ArrayList#exists
    * @param {object} child - The element to get the list index for.
    * @return {boolean} True if the child is found in the list, otherwise false.
    */
    exists: function (child) {

        return (this.list.indexOf(child) > -1);

    },

    /**
    * Resets the list length and drops all items in the list.
    *
    * @method Phaser.ArrayList#reset
    */
    reset: function () {

        this.list.length = 0;
        this.total = 0;

    },

    /**
    * Removes the given element from this list if it exists.
    *
    * @method Phaser.ArrayList#remove
    * @param {object} child - The child to be removed from the list.
    * @return {object} child - The child that was removed.
    */
    remove: function (child) {

        var idx = this.list.indexOf(child);

        if (idx > -1)
        {
            this.list.splice(idx, 1);
            this.total--;
            return child;
        }

    },

    /**
    * Calls a function on all members of this list, using the member as the context for the callback.
    * The function must exist on the member.
    *
    * @method Phaser.ArrayList#callAll
    * @param {function} callback - The function to call.
    * @param {...*} parameter - Additional parameters that will be passed to the callback.
    */
    callAll: function (callback) {

        var args = Array.prototype.splice.call(arguments, 1);

        var i = this.list.length;

        while (i--)
        {
            this.list[i][callback].apply(this.list[i], args);
        }

    }

};

/**
* Resets the cursor to the first item in the list and returns it.
*
* @name Phaser.ArrayList#first
* @property {object} first - The first item in the list.
*/
Object.defineProperty(Phaser.ArrayList.prototype, "first", {

    get: function () {

        this.position = 0;

        if (this.total > 0)
        {
            return this.list[0];
        }
        else
        {
            return null;
        }

    }

});

/**
* Gets the next item in the list and returns it, advancing the cursor.
*
* @name Phaser.ArrayList#next
* @property {object} next - Advanced the cursor and return.
*/
Object.defineProperty(Phaser.ArrayList.prototype, "next", {

    get: function () {

        if (this.position < this.total)
        {
            this.position++;

            return this.list[this.position];
        }
        else
        {
            return null;
        }

    }

});

Phaser.ArrayList.prototype.constructor = Phaser.ArrayList;
<|endoftext|>


<commit_before>var searchInputStyle = {
    width: '400px',
    display: 'block',
    marginBottom: '48px',
    marginLeft: 'auto',
    marginRight: 'auto'
  },
  fetchResultsStyle = {
    color: '#888',
    textAlign: 'center',
    fontSize: '1.2em'
  };

var SearchActive = React.createClass({
  render: function() {
    return (

        Looking up the Dewey Decimals

    );
  }
});

var searchNoResultsStyle = {
  textAlign: 'center'
}, searchNoResultsMessageStyle = {
  fontStyle: 'italic',
  marginRight: '5px'
};

var SearchNoResults = React.createClass({
  render: function() {
    return (

        No one has checked anything in for {this.props.query} yet.
        <Link label="Be the first" href="javascript:alert('aww I do nothing')" />

    );
  }
});

var SearchResults = React.createClass({
  render: function() {
    var rows = [];
    console.log('results');
    console.log('made it here');
    this.props.results.forEach(function(result) {
      rows.push(
        <SearchResultRow name={result.name} title={result.stream_name} imgUrl={result.thumbnail}
                         description={result.description} cost_est={result.cost_est} />
      );
    });
    console.log(this.props.results);
    console.log(rows);
    console.log('done');
    return (

{rows}

    );
  }
});

var searchRowImgStyle = {
    maxHeight: '100px',
    display: 'block',
    marginLeft: 'auto',
    marginRight: 'auto',
    float: 'left'
  },
  searchRowCostStyle = {
    float: 'right',
    marginLeft: '20px',
    marginTop: '5px',
    display: 'inline-block'
  },
  searchRowNameStyle = {
    fontSize: '0.9em',
    color: '#666',
    marginBottom: '24px',
    clear: 'both'
  },
  searchRowDescriptionStyle = {
    color : '#444',
    marginBottom: '24px',
    fontSize: '0.9em'
  };

var SearchResultRow = React.createClass({
  getInitialState: function() {
    return {
      downloading: false
    }
  },
  render: function() {
    return (

            <CreditAmount amount={this.props.cost_est} isEstimate={true}/>

{this.props.title}

lbry://{this.props.name}

{this.props.description}

            <WatchLink streamName={this.props.name} button="primary" />
            <DownloadLink streamName={this.props.name} button="alt" />

    );
  }
});

var featuredContentItemStyle = {
  fontSize: '0.95em',
  marginBottom: '10px',
}, featuredContentItemInfoColumnStyle = {
  position: 'relative',
  left: '26px',
}, featuredContentItemImgStyle = {
  maxHeight: '90px',
  display: 'block',
  marginLeft: 'auto',
  marginRight: 'auto',
  float: 'left',
}, featuredContentItemDescriptionStyle = {
  color: '#444',
  marginBottom: '5px',
  fontSize: '0.9em',
  width: '250px',
}, featuredContentItemCostStyle = {
  display: 'block',
  float: 'right',
  position: 'relative',
  left: '-35px',
  fontSize: '0.95em',
};

var FeaturedContentItem = React.createClass({
  propTypes: {
    name: React.PropTypes.string,
  },
  getInitialState: function() {
    return {
      metadata: null,
      title: null,
    };
  },
  componentWillMount: function() {
    lbry.resolveName(this.props.name, (metadata) => {
      this.setState({
        metadata: metadata,
        title: metadata.name || metadata.stream_name || ('lbry://' + this.props.name),
      })
    });
  },
  render: function() {
    if (this.state.metadata == null) {
      // Still waiting for metadata
      return null;
    }

    var metadata = this.state.metadata;

    return (

{this.state.title}

{metadata.description}

          <WatchLink streamName={this.props.name} />
          { ' ' }
          <DownloadLink streamName={this.props.name} />

<CreditAmount amount={0.0} isEstimate={true}/>

);
  }
});

var featuredContentStyle = {
  width: '100%',
},
featuredContentColsStyle = {
  marginLeft: '0px',
};

var FeaturedContent = React.createClass({
  render: function() {
    return (

Featured content

        <FeaturedContentItem name="wonderfullife" /> {/* When ready, change to one/two/three/four/five/six */}
        <FeaturedContentItem name="wonderfullife" />
        <FeaturedContentItem name="wonderfullife" />

        <FeaturedContentItem name="wonderfullife" />
        <FeaturedContentItem name="wonderfullife" />
        <FeaturedContentItem name="wonderfullife" />

);
  }
});

var discoverMainStyle = {
  color: '#333'
};

var Discover = React.createClass({
  userTypingTimer: null,

  getInitialState: function() {
    return {
      results: [],
      searching: false,
      query: ''
    };
  },

  search: function() {
    if (this.state.query)
    {
      console.log('search');
      lbry.search(this.state.query, this.searchCallback.bind(this, this.state.query));
    }
    else
    {
      this.setState({
        searching: false,
        results: []
      });
    }
  },

  searchCallback: function(originalQuery, results) {
    if (this.state.searching) //could have canceled while results were pending, in which case nothing to do
    {
      this.setState({
        results: results,
        searching: this.state.query != originalQuery, //multiple searches can be out, we're only done if we receive one we actually care about
      });
    }
  },

  onQueryChange: function(event) {
    if (this.userTypingTimer)
    {
      clearTimeout(this.userTypingTimer);
    }

    //@TODO: Switch to React.js timing
    this.userTypingTimer = setTimeout(this.search, 800); // 800ms delay, tweak for faster/slower

    this.setState({
      searching: event.target.value.length > 0,
      query: event.target.value
    });
  },

  render: function() {
    console.log(this.state);
    return (

<input type="search" style={searchInputStyle} onChange={this.onQueryChange}
                        placeholder="Find movies, music, games, and more"/>

        { this.state.searching ? <SearchActive /> : null }
        { !this.state.searching && this.state.query && this.state.results.length ? <SearchResults results={this.state.results} /> : null }
        { !this.state.searching && this.state.query && !this.state.results.length ? <SearchNoResults query={this.state.query} /> : null }
        { !this.state.query && !this.state.searching ? <FeaturedContent /> : null }

    );
  }
});

var logoStyle = {
    padding: '48px 12px',
    textAlign: 'center',
    maxHeight: '80px',
  },
  imgStyle = { //@TODO: remove this, img should be properly scaled once size is settled
    height: '80px'
  };

var Header = React.createClass({
  render: function() {
    return (

        <TopBar />

    );
  }
});

var topBarStyle = {
  'float': 'right'
},
balanceStyle = {
  'marginRight': '5px'
},
closeIconStyle = {
  'color': '#ff5155'
};

var TopBar = React.createClass({
  onClose: function() {
    window.location.href = "?start";
  },
  getInitialState: function() {
    return {
      balance: 0,
      showClose: /linux/i.test(navigator.userAgent) // @TODO: find a way to use getVersionInfo() here without messy state management
    };
  },
  componentDidMount: function() {
    lbry.getBalance(function(balance) {
      this.setState({
        balance: balance
      });
    }.bind(this));
  },

  render: function() {
    return (

          <CreditAmount amount={this.state.balance}/>

        <Link href='/?files' title="My Files" icon='icon-cloud-download' />
        <Link href='/?settings' title="Settings" icon='icon-gear' />
        <Link href='/?help' title="Help" icon='icon-question-circle' />
        <Link href="/?start" title="Start" onClick={this.onClose} icon="icon-close"
              style={closeIconStyle} hidden={!this.state.showClose} />

    );
  }
});

var HomePage = React.createClass({
  componentDidMount: function() {
    lbry.getStartNotice(function(notice) {
      if (notice) {
        alert(notice);
      }
    });
  },
  render: function() {
    return (

        <Discover />

    );
  }
});
<commit_msg>Streamline featured content styles; spacing tweaks<commit_after>var searchInputStyle = {
    width: '400px',
    display: 'block',
    marginBottom: '48px',
    marginLeft: 'auto',
    marginRight: 'auto'
  },
  fetchResultsStyle = {
    color: '#888',
    textAlign: 'center',
    fontSize: '1.2em'
  };

var SearchActive = React.createClass({
  render: function() {
    return (

        Looking up the Dewey Decimals

    );
  }
});

var searchNoResultsStyle = {
  textAlign: 'center'
}, searchNoResultsMessageStyle = {
  fontStyle: 'italic',
  marginRight: '5px'
};

var SearchNoResults = React.createClass({
  render: function() {
    return (

        No one has checked anything in for {this.props.query} yet.
        <Link label="Be the first" href="javascript:alert('aww I do nothing')" />

    );
  }
});

var SearchResults = React.createClass({
  render: function() {
    var rows = [];
    console.log('results');
    console.log('made it here');
    this.props.results.forEach(function(result) {
      rows.push(
        <SearchResultRow name={result.name} title={result.stream_name} imgUrl={result.thumbnail}
                         description={result.description} cost_est={result.cost_est} />
      );
    });
    console.log(this.props.results);
    console.log(rows);
    console.log('done');
    return (

{rows}

    );
  }
});

var searchRowImgStyle = {
    maxHeight: '100px',
    display: 'block',
    marginLeft: 'auto',
    marginRight: 'auto',
    float: 'left'
  },
  searchRowCostStyle = {
    float: 'right',
    marginLeft: '20px',
    marginTop: '5px',
    display: 'inline-block'
  },
  searchRowNameStyle = {
    fontSize: '0.9em',
    color: '#666',
    marginBottom: '24px',
    clear: 'both'
  },
  searchRowDescriptionStyle = {
    color : '#444',
    marginBottom: '24px',
    fontSize: '0.9em'
  };

var SearchResultRow = React.createClass({
  getInitialState: function() {
    return {
      downloading: false
    }
  },
  render: function() {
    return (

            <CreditAmount amount={this.props.cost_est} isEstimate={true}/>

{this.props.title}

lbry://{this.props.name}

{this.props.description}

            <WatchLink streamName={this.props.name} button="primary" />
            <DownloadLink streamName={this.props.name} button="alt" />

    );
  }
});

var featuredContentItemStyle = {
  fontSize: '0.95em',
  marginBottom: '10px',
}, featuredContentItemImgStyle = {
  maxHeight: '90px',
  display: 'block',
  marginLeft: 'auto',
  marginRight: 'auto',
  marginTop: '5px',
  float: 'left',
}, featuredContentItemDescriptionStyle = {
  color: '#444',
  marginBottom: '5px',
  fontSize: '0.9em',
}, featuredContentItemCostStyle = {
  display: 'block',
  float: 'right',
  fontSize: '0.95em',
};

var FeaturedContentItem = React.createClass({
  propTypes: {
    name: React.PropTypes.string,
  },
  getInitialState: function() {
    return {
      metadata: null,
      title: null,
    };
  },
  componentWillMount: function() {
    lbry.resolveName(this.props.name, (metadata) => {
      this.setState({
        metadata: metadata,
        title: metadata.name || metadata.stream_name || ('lbry://' + this.props.name),
      })
    });
  },
  render: function() {
    if (this.state.metadata == null) {
      // Still waiting for metadata
      return null;
    }

    var metadata = this.state.metadata;

    return (

{this.state.title}

{metadata.description}

            <WatchLink streamName={this.props.name} />
            { ' ' }
            <DownloadLink streamName={this.props.name} />

<CreditAmount amount={0.0} isEstimate={true}/>

);
  }
});

var featuredContentStyle = {
  width: '100%',
};

var FeaturedContent = React.createClass({
  render: function() {
    return (

Featured content

        <FeaturedContentItem name="wonderfullife" /> {/* When ready, change to one/two/three/four/five/six */}
        <FeaturedContentItem name="wonderfullife" />
        <FeaturedContentItem name="wonderfullife" />

        <FeaturedContentItem name="wonderfullife" />
        <FeaturedContentItem name="wonderfullife" />
        <FeaturedContentItem name="wonderfullife" />

);
  }
});

var discoverMainStyle = {
  color: '#333'
};

var Discover = React.createClass({
  userTypingTimer: null,

  getInitialState: function() {
    return {
      results: [],
      searching: false,
      query: ''
    };
  },

  search: function() {
    if (this.state.query)
    {
      console.log('search');
      lbry.search(this.state.query, this.searchCallback.bind(this, this.state.query));
    }
    else
    {
      this.setState({
        searching: false,
        results: []
      });
    }
  },

  searchCallback: function(originalQuery, results) {
    if (this.state.searching) //could have canceled while results were pending, in which case nothing to do
    {
      this.setState({
        results: results,
        searching: this.state.query != originalQuery, //multiple searches can be out, we're only done if we receive one we actually care about
      });
    }
  },

  onQueryChange: function(event) {
    if (this.userTypingTimer)
    {
      clearTimeout(this.userTypingTimer);
    }

    //@TODO: Switch to React.js timing
    this.userTypingTimer = setTimeout(this.search, 800); // 800ms delay, tweak for faster/slower

    this.setState({
      searching: event.target.value.length > 0,
      query: event.target.value
    });
  },

  render: function() {
    console.log(this.state);
    return (

<input type="search" style={searchInputStyle} onChange={this.onQueryChange}
                        placeholder="Find movies, music, games, and more"/>

        { this.state.searching ? <SearchActive /> : null }
        { !this.state.searching && this.state.query && this.state.results.length ? <SearchResults results={this.state.results} /> : null }
        { !this.state.searching && this.state.query && !this.state.results.length ? <SearchNoResults query={this.state.query} /> : null }
        { !this.state.query && !this.state.searching ? <FeaturedContent /> : null }

    );
  }
});

var logoStyle = {
    padding: '48px 12px',
    textAlign: 'center',
    maxHeight: '80px',
  },
  imgStyle = { //@TODO: remove this, img should be properly scaled once size is settled
    height: '80px'
  };

var Header = React.createClass({
  render: function() {
    return (

        <TopBar />

    );
  }
});

var topBarStyle = {
  'float': 'right'
},
balanceStyle = {
  'marginRight': '5px'
},
closeIconStyle = {
  'color': '#ff5155'
};

var TopBar = React.createClass({
  onClose: function() {
    window.location.href = "?start";
  },
  getInitialState: function() {
    return {
      balance: 0,
      showClose: /linux/i.test(navigator.userAgent) // @TODO: find a way to use getVersionInfo() here without messy state management
    };
  },
  componentDidMount: function() {
    lbry.getBalance(function(balance) {
      this.setState({
        balance: balance
      });
    }.bind(this));
  },

  render: function() {
    return (

          <CreditAmount amount={this.state.balance}/>

        <Link href='/?files' title="My Files" icon='icon-cloud-download' />
        <Link href='/?settings' title="Settings" icon='icon-gear' />
        <Link href='/?help' title="Help" icon='icon-question-circle' />
        <Link href="/?start" title="Start" onClick={this.onClose} icon="icon-close"
              style={closeIconStyle} hidden={!this.state.showClose} />

    );
  }
});

var HomePage = React.createClass({
  componentDidMount: function() {
    lbry.getStartNotice(function(notice) {
      if (notice) {
        alert(notice);
      }
    });
  },
  render: function() {
    return (

        <Discover />

    );
  }
});
<|endoftext|>


<commit_before>// @flow
import isPromise from 'is-promise'
import type { SubmitFunction } from './types'
import type { Props } from './createReduxForm'
import SubmissionError from './SubmissionError'

const isSubmissionError = error => error && error.name === SubmissionError.name

const mergeErrors = ({ asyncErrors, syncErrors }) =>
  asyncErrors && typeof asyncErrors.merge === 'function'
    ? asyncErrors.merge(syncErrors).toJS()
    : { ...asyncErrors, ...syncErrors }

const executeSubmit = (
  submit: SubmitFunction,
  fields: string[],
  props: Props
) => {
  const {
    dispatch,
    submitAsSideEffect,
    onSubmitFail,
    onSubmitSuccess,
    startSubmit,
    stopSubmit,
    setSubmitFailed,
    setSubmitSucceeded,
    values
  } = props

  let result
  try {
    result = submit(values, dispatch, props)
  } catch (submitError) {
    const error = isSubmissionError(submitError)
      ? submitError.errors
      : undefined
    stopSubmit(error)
    setSubmitFailed(...fields)
    if (onSubmitFail) {
      onSubmitFail(error, dispatch, submitError, props)
    }
    if (error || onSubmitFail) {
      // if you've provided an onSubmitFail callback, don't re-throw the error
      return error
    } else {
      throw submitError
    }
  }
  if (submitAsSideEffect) {
    if (result) {
      dispatch(result)
    }
  } else {
    if (isPromise(result)) {
      startSubmit()
      return result.then(
        submitResult => {
          stopSubmit()
          setSubmitSucceeded()
          if (onSubmitSuccess) {
            onSubmitSuccess(submitResult, dispatch, props)
          }
          return submitResult
        },
        submitError => {
          const error = isSubmissionError(submitError)
            ? submitError.errors
            : undefined
          stopSubmit(error)
          setSubmitFailed(...fields)
          if (onSubmitFail) {
            onSubmitFail(error, dispatch, submitError, props)
          }
          if (error || onSubmitFail) {
            // if you've provided an onSubmitFail callback, don't re-throw the error
            return error
          } else {
            throw submitError
          }
        }
      )
    } else {
      setSubmitSucceeded()
      if (onSubmitSuccess) {
        onSubmitSuccess(result, dispatch, props)
      }
    }
  }

  return result
}

const handleSubmit = (
  submit: SubmitFunction,
  props: Props,
  valid: boolean,
  asyncValidate: Function,
  fields: string[]
) => {
  const {
    dispatch,
    onSubmitFail,
    setSubmitFailed,
    syncErrors,
    asyncErrors,
    touch,
    persistentSubmitErrors
  } = props

  touch(...Array.from(fields)) // mark all fields as touched

  if (valid || persistentSubmitErrors) {
    const asyncValidateResult = asyncValidate && asyncValidate()
    if (asyncValidateResult) {
      return asyncValidateResult
        .then(asyncErrors => {
          if (asyncErrors) {
            throw asyncErrors
          }
          return executeSubmit(submit, fields, props)
        })
        .catch(asyncErrors => {
          setSubmitFailed(...fields)
          if (onSubmitFail) {
            onSubmitFail(asyncErrors, dispatch, null, props)
          }
          return Promise.reject(asyncErrors)
        })
    } else {
      return executeSubmit(submit, fields, props)
    }
  } else {
    setSubmitFailed(...fields)
    const errors = mergeErrors({ asyncErrors, syncErrors })
    if (onSubmitFail) {
      onSubmitFail(errors, dispatch, null, props)
    }
    return errors
  }
}

export default handleSubmit
<commit_msg>fix immutable support in lose mode<commit_after>// @flow
import isPromise from 'is-promise'
import type { SubmitFunction } from './types'
import type { Props } from './createReduxForm'
import SubmissionError from './SubmissionError'
import { List } from 'immutable'

const isSubmissionError = error => error && error.name === SubmissionError.name

const mergeErrors = ({ asyncErrors, syncErrors }) =>
  asyncErrors && typeof asyncErrors.merge === 'function'
    ? asyncErrors.merge(syncErrors).toJS()
    : { ...asyncErrors, ...syncErrors }

// fields may be an Immutable List which cannot be spread
// convert the fields to an array if necessary
const makeFieldsArray = (fields: string[] | List<string>) =>
  List.isList(fields) ? ((fields: any): List<string>).toArray() : fields

const executeSubmit = (
  submit: SubmitFunction,
  fields: string[] | List<string>,
  props: Props
) => {
  const {
    dispatch,
    submitAsSideEffect,
    onSubmitFail,
    onSubmitSuccess,
    startSubmit,
    stopSubmit,
    setSubmitFailed,
    setSubmitSucceeded,
    values
  } = props

  fields = makeFieldsArray(fields)

  let result
  try {
    result = submit(values, dispatch, props)
  } catch (submitError) {
    const error = isSubmissionError(submitError)
      ? submitError.errors
      : undefined
    stopSubmit(error)
    setSubmitFailed(...fields)
    if (onSubmitFail) {
      onSubmitFail(error, dispatch, submitError, props)
    }
    if (error || onSubmitFail) {
      // if you've provided an onSubmitFail callback, don't re-throw the error
      return error
    } else {
      throw submitError
    }
  }
  if (submitAsSideEffect) {
    if (result) {
      dispatch(result)
    }
  } else {
    if (isPromise(result)) {
      startSubmit()
      return result.then(
        submitResult => {
          stopSubmit()
          setSubmitSucceeded()
          if (onSubmitSuccess) {
            onSubmitSuccess(submitResult, dispatch, props)
          }
          return submitResult
        },
        submitError => {
          const error = isSubmissionError(submitError)
            ? submitError.errors
            : undefined
          stopSubmit(error)
          setSubmitFailed(...fields)
          if (onSubmitFail) {
            onSubmitFail(error, dispatch, submitError, props)
          }
          if (error || onSubmitFail) {
            // if you've provided an onSubmitFail callback, don't re-throw the error
            return error
          } else {
            throw submitError
          }
        }
      )
    } else {
      setSubmitSucceeded()
      if (onSubmitSuccess) {
        onSubmitSuccess(result, dispatch, props)
      }
    }
  }

  return result
}

const handleSubmit = (
  submit: SubmitFunction,
  props: Props,
  valid: boolean,
  asyncValidate: Function,
  fields: string[] | List<string>
) => {
  const {
    dispatch,
    onSubmitFail,
    setSubmitFailed,
    syncErrors,
    asyncErrors,
    touch,
    persistentSubmitErrors
  } = props

  fields = makeFieldsArray(fields)

  touch(...fields) // mark all fields as touched

  if (valid || persistentSubmitErrors) {
    const asyncValidateResult = asyncValidate && asyncValidate()
    if (asyncValidateResult) {
      return asyncValidateResult
        .then(asyncErrors => {
          if (asyncErrors) {
            throw asyncErrors
          }
          return executeSubmit(submit, fields, props)
        })
        .catch(asyncErrors => {
          setSubmitFailed(...fields)
          if (onSubmitFail) {
            onSubmitFail(asyncErrors, dispatch, null, props)
          }
          return Promise.reject(asyncErrors)
        })
    } else {
      return executeSubmit(submit, fields, props)
    }
  } else {
    setSubmitFailed(...fields)
    const errors = mergeErrors({ asyncErrors, syncErrors })
    if (onSubmitFail) {
      onSubmitFail(errors, dispatch, null, props)
    }
    return errors
  }
}

export default handleSubmit
<|endoftext|>


<commit_before>(function (window) {
	'use strict';

	var HearingTest = Object.create(null);

	HearingTest.init = function init() {
		this.context = new window.AudioContext();
		this.sound = this.createSound(this.context);

		return this;
	}

	HearingTest.createSound = function createSound(context) {
		return context.createOscillator();
	};

	HearingTest.connect = function connect(context, sound) {
		return sound.connect(context.destination);
	}

	HearingTest.playSound = function playSound(delay) {
		delay = delay || 0;
		this.sound.start(delay);
	};

	HearingTest.stopSound = function stopSound(delay) {
		delay = delay || 0;
		this.sound.stop(delay);
	};

	window.HearingTest = HearingTest;
	return HearingTest;
}(window));
<commit_msg>Change instantiate AudioContext timing, and add a argument frequency in init function<commit_after>(function (window) {
	'use strict';

	var HearingTest = Object.create(null);
	var context = new window.AudioContext();

	HearingTest.init = function init(frequency) {
		frequency = frequency || 440;

		return this;
	}

	HearingTest.createSound = function createSound(context) {
		return context.createOscillator();
	};

	HearingTest.connect = function connect(context, sound) {
		return sound.connect(context.destination);
	}

	HearingTest.playSound = function playSound(delay) {
		delay = delay || 0;
		this.sound.start(delay);
	};

	HearingTest.stopSound = function stopSound(delay) {
		delay = delay || 0;
		this.sound.stop(delay);
	};

	window.HearingTest = HearingTest;
	return HearingTest;
}(window));
<|endoftext|>