<commit_before>/** public/js/views/form/edit.js
 *
 * @author Victor Petrov <victor.petrov@gmail.com>
 * @copyright (c) 2012, The Neuroinformatics Research Group at Harvard University.
 * @copyright (c) 2012, The President and Fellows of Harvard College.
 * @license New BSD License (see LICENSE file for details).
 */

define([
    'jquery',
    'underscore',
    'backbone',
    'models/form',
    'views/alert',
    'errors',
    'views/form/editor'
],
    function ($, _, Backbone, Form, Alert, Errors, Editor) {
        "use strict";

        return Backbone.View.extend({
            template: _.template($('#tpl-form-edit').html()),
            statusTemplate: _.template($('#tpl-code-editor-message').html()),
            editor: null,
            saving: false,

            initialize: function (options) {
                console.log('Initializing Edit Form View', options);

                _.bindAll(this, 'submit', 'onCancelClick', 'onSaveClick', 'onSubmitError', 'onValidationError',
                                'onShortcut', 'setSaveStatus');

                $(window).keydown($.proxy(this.onShortcut, this));
            },

            events: {
                'click  #btn-form-edit-save': 'onSaveClick',
                'click  #btn-form-edit-cancel': 'onCancelClick',
                'submit #edit-form': 'submit'
            },

            render: function () {
                $(this.el).html(this.template(this.model.toJSON()));

                if (!this.editor) {
                    this.editor = new Editor({
                        text: JSON.stringify(this.model.get('data'), null, 4)
                    });

                    this.editor.render();
                    this.$el.find('#code-editor-container').html(this.editor.el);
                }

                return this;
            },

            preview: function () {
                var form = this.$el.find('form.preview');

                form.find('input').val(JSON.stringify(this.model.toJSON()));

                //register the submit handler
                form.submit(function () {
                    window.open('', 'formpreview');
                    this.target = 'formpreview';
                });

                //submit the form
                form.submit();
            },

            setSaveStatus: function (status, message) {
                var icon = "";

                //bootstrap icon-* value
                if (status === null) {
                    icon = 'retweet';
                } else if (status === false) {
                    icon = 'warning-sign';
                } else if (status === true) {
                    icon = 'ok-sign';
                }

                this.$el.find('.code-editor-message').html(this.statusTemplate({
                    'icon': icon,
                    'message': message
                }));
            },

            onShortcut: function (event) {

                var found = false,
                    context = this;

                if (((event.which === 115) || (event.which === 83)) && (event.ctrlKey || event.metaKey)) {  //Save
                    if (!context.saving) {
                        context.saving = true;

                        context.setSaveStatus(null, 'Saving ...');

                        this.submit(function (result) {
                            context.saving = false;
                            if (result) {
                                context.setSaveStatus(true, "Saved at " + (new Date()).toLocaleTimeString());
                            } else {
                                context.setSaveStatus(false, "Save failed");
                            }
                        });
                    }
                    found = true;

                } else if ((event.which === 80) && (event.ctrlKey || event.metaKey)) {                      //Preview
                    this.preview();
                    found = true;
                }

                if (found) {
                    event.preventDefault();
                    return false;
                }

                return true;
            },

            onSaveClick: function (e) {
                this.submit();

                e.preventDefault();
                return false;
            },

            onCancelClick: function (e) {

                window.history.back();
                e.preventDefault();
                return false;
            },

            submit: function (callback) {

                var data = {},
                    router = this.router,
                    form = this.$el.find('form.edit'),
                    context = this;

                //copy all form values into the study object

                _.each(form.serializeArray(), function (item) {
                    data[item.name] = item.value;
                });

                //try to validate the JSON object
                try {
                    //copy the document text
                    data.data = JSON.parse(this.editor.getText());
                } catch (e1) {
                    this.onValidationError({
                        'data': 'Invalid JSON object'
                    }, [e1]);
                    return false;
                }

                try {
                    this.model.save(data, {
                        'wait': true,
                        'success': function (model, updates) {
                            model.set(updates);

                            if (callback) {
                                callback(true, model);
                            } else {
                                router.navigate('form/' + model.get('id'), {'trigger': true});
                            }
                        },

                        'error': function () {
                            if (callback) {
                                callback.apply(context, [false]);
                            } else {
                                this.onSubmitError.apply(context, [false]);
                            }
                        }
                    });
                } catch (e2) {
                    Alert.show(e2.message);
                }

                return false;
            },

            onSubmitError: function (model, result, caller) {
                Errors.onSubmit(this, model, result, caller);
            },

            onValidationError: function (model, errors) {
                var msg = "",
                    e;

                for (e in errors) {
                    if (errors.hasOwnProperty(e)) {
                        msg += errors[e] + "\n";
                    }
                }

                if (!msg.length) {
                    msg = "We were unable to validate your input data. Please try again.";
                }

                Alert.show(msg);
            }
        });

    }); //define
<commit_msg>views/form/edit: Fix bug preventing users from saving code if  a JSON error had been previously detected<commit_after>/** public/js/views/form/edit.js
 *
 * @author Victor Petrov <victor.petrov@gmail.com>
 * @copyright (c) 2012, The Neuroinformatics Research Group at Harvard University.
 * @copyright (c) 2012, The President and Fellows of Harvard College.
 * @license New BSD License (see LICENSE file for details).
 */

define([
    'jquery',
    'underscore',
    'backbone',
    'models/form',
    'views/alert',
    'errors',
    'views/form/editor'
],
    function ($, _, Backbone, Form, Alert, Errors, Editor) {
        "use strict";

        return Backbone.View.extend({
            template: _.template($('#tpl-form-edit').html()),
            statusTemplate: _.template($('#tpl-code-editor-message').html()),
            editor: null,
            saving: false,

            initialize: function (options) {
                console.log('Initializing Edit Form View', options);

                _.bindAll(this, 'submit', 'onCancelClick', 'onSaveClick', 'onSubmitError', 'onValidationError',
                                'onShortcut', 'setSaveStatus');

                $(window).keydown($.proxy(this.onShortcut, this));
            },

            events: {
                'click  #btn-form-edit-save': 'onSaveClick',
                'click  #btn-form-edit-cancel': 'onCancelClick',
                'submit #edit-form': 'submit'
            },

            render: function () {
                $(this.el).html(this.template(this.model.toJSON()));

                if (!this.editor) {
                    this.editor = new Editor({
                        text: JSON.stringify(this.model.get('data'), null, 4)
                    });

                    this.editor.render();
                    this.$el.find('#code-editor-container').html(this.editor.el);
                }

                return this;
            },

            preview: function () {
                var form = this.$el.find('form.preview');

                form.find('input').val(JSON.stringify(this.model.toJSON()));

                //register the submit handler
                form.submit(function () {
                    window.open('', 'formpreview');
                    this.target = 'formpreview';
                });

                //submit the form
                form.submit();
            },

            setSaveStatus: function (status, message) {
                var icon = "";

                //bootstrap icon-* value
                if (status === null) {
                    icon = 'retweet';
                } else if (status === false) {
                    icon = 'warning-sign';
                } else if (status === true) {
                    icon = 'ok-sign';
                }

                this.$el.find('.code-editor-message').html(this.statusTemplate({
                    'icon': icon,
                    'message': message
                }));
            },

            onShortcut: function (event) {

                var found = false,
                    context = this;

                if (((event.which === 115) || (event.which === 83)) && (event.ctrlKey || event.metaKey)) {  //Save
                    if (!context.saving) {
                        context.saving = true;

                        context.setSaveStatus(null, 'Saving ...');

                        this.submit(function (result) {
                            context.saving = false;
                            if (result) {
                                context.setSaveStatus(true, "Saved at " + (new Date()).toLocaleTimeString());
                            } else {
                                context.setSaveStatus(false, "Save failed");
                            }
                        });
                    }
                    found = true;

                } else if ((event.which === 80) && (event.ctrlKey || event.metaKey)) {                      //Preview
                    this.preview();
                    found = true;
                }

                if (found) {
                    event.preventDefault();
                    return false;
                }

                return true;
            },

            onSaveClick: function (e) {
                this.submit();

                e.preventDefault();
                return false;
            },

            onCancelClick: function (e) {

                window.history.back();
                e.preventDefault();
                return false;
            },

            submit: function (callback) {

                var data = {},
                    router = this.router,
                    form = this.$el.find('form.edit'),
                    context = this;

                //copy all form values into the study object

                _.each(form.serializeArray(), function (item) {
                    data[item.name] = item.value;
                });

                //try to validate the JSON object
                try {
                    //copy the document text
                    data.data = JSON.parse(this.editor.getText());
                } catch (e1) {
                    this.onValidationError({
                        'data': 'Invalid JSON object'
                    }, [e1]);

                    return false;
                }

                try {
                    this.model.save(data, {
                        'wait': true,
                        'success': function (model, updates) {
                            model.set(updates);

                            if (callback) {
                                callback(true, model);
                            } else {
                                router.navigate('form/' + model.get('id'), {'trigger': true});
                            }
                        },

                        'error': function () {
                            if (callback) {
                                callback.apply(context, [false]);
                            } else {
                                this.onSubmitError.apply(context, [false]);
                            }
                        }
                    });
                } catch (e2) {
                    Alert.show(e2.message);
                }

                return false;
            },

            onSubmitError: function (model, result, caller) {
                this.saving = false;
                Errors.onSubmit(this, model, result, caller);
            },

            onValidationError: function (model, errors) {
                this.saving = false;
                var msg = "",
                    e;

                for (e in errors) {
                    if (errors.hasOwnProperty(e)) {
                        msg += errors[e] + "\n";
                    }
                }

                if (!msg.length) {
                    msg = "We were unable to validate your input data. Please try again.";
                }

                Alert.show(msg);
            }
        });

    }); //define
<|endoftext|>


<commit_before>var pump = require('pump')
var fs = require('fs')
var debug = require('debug')('bin/write')
var openDat = require('../lib/util/open-dat.js')
var abort = require('../lib/util/abort.js')
var usage = require('../lib/util/usage.js')('write.txt')
var progress = require('../lib/util/progress.js')

module.exports = {
  name: 'write',
  command: handleWrite,
  options: [
    {
      name: 'dataset',
      boolean: false,
      abbr: 'd'
    },
    {
      name: 'name',
      boolean: false,
      abbr: 'n'
    },
    {
      name: 'message',
      boolean: false,
      abbr: 'm'
    }
  ]
}

function handleWrite (args) {
  debug('handleWrite', args)

  if (args.help || args._.length === 0) {
    return usage()
  }

  if (!args.dataset) abort(new Error('Error: Must specify dataset (-d)'), args)

  openDat(args, function (err, db) {
    if (err) abort(err, args)
    var path = args._[0]
    var stream = args._[1]
    var key = args.n || path

    var inputStream
    if (stream === '-') {
      inputStream = process.stdin
    } else {
      if (!fs.existsSync(path)) {
        abort(new Error('Error: File at ' + path + ' does not exist'), args)
      }
      inputStream = fs.createReadStream(path)
    }

    var opts = {
      dataset: args.dataset,
      message: args.message
    }

    var writer = db.createFileWriteStream(key, opts)
    progress(writer, {bytes: true, verb: 'Storing ' + key})
    pump(inputStream, writer, function done (err) {
      if (err) abort(err, args, 'Error: Write failed')

      if (args.json) {
        var output = {
          version: db.head
        }
        console.log(JSON.stringify(output))
      } else console.error('Stored ' + key + ' successfully. \nCurrent version is now: ' + db.head)

    })
  })
}
<commit_msg>use key instead of name for writing files<commit_after>var pump = require('pump')
var fs = require('fs')
var basename = require('path').basename
var debug = require('debug')('bin/write')
var openDat = require('../lib/util/open-dat.js')
var abort = require('../lib/util/abort.js')
var usage = require('../lib/util/usage.js')('write.txt')
var progress = require('../lib/util/progress.js')

module.exports = {
  name: 'write',
  command: handleWrite,
  options: [
    {
      name: 'dataset',
      boolean: false,
      abbr: 'd'
    },
    {
      name: 'key',
      boolean: false,
      abbr: 'k'
    },
    {
      name: 'message',
      boolean: false,
      abbr: 'm'
    }
  ]
}

function handleWrite (args) {
  debug('handleWrite', args)

  if (args.help || args._.length === 0) {
    return usage()
  }

  if (!args.dataset) abort(new Error('Error: Must specify dataset (-d)'), args)

  openDat(args, function (err, db) {
    if (err) abort(err, args)
    var path = args._[0]
    var stream = args._[1]
    var key = args.key || basename(path)

    var inputStream
    if (stream === '-') {
      inputStream = process.stdin
    } else {
      if (!fs.existsSync(path)) {
        abort(new Error('Error: File at ' + path + ' does not exist'), args)
      }
      inputStream = fs.createReadStream(path)
    }

    var opts = {
      dataset: args.dataset,
      message: args.message
    }

    var writer = db.createFileWriteStream(key, opts)
    progress(writer, {bytes: true, verb: 'Storing ' + key})
    pump(inputStream, writer, function done (err) {
      if (err) abort(err, args, 'Error: Write failed')

      if (args.json) {
        var output = {
          version: db.head
        }
        console.log(JSON.stringify(output))
      } else console.error('Stored ' + key + ' successfully. \nCurrent version is now: ' + db.head)

    })
  })
}
<|endoftext|>


<commit_before>var assert = require("assert");
var {defer, promises} = require("ringo/promise");

exports.testPromiseList = function() {
    var d1 = defer(), d2 = defer(), d3 = defer(), done = defer();
    var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
    l.then(function(result) {
        done.resolve(result);
    }, function(error) {
        done.resolve("promises called error callback", true);
    });
    d2.resolve(1);
    d3.resolve("error", true);
    d1.resolve("ok");
    // make sure promises resolve via wait()
    var result = l.wait();
    assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
    // make sure promises resolve via callback
    result = done.promise.wait();
    assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
};

// start the test runner if we're called directly from command line
if (require.main == module.id) {
    system.exit(require('test').run(exports));
}
<commit_msg>Fix promise test using a worker/semaphore hack<commit_after>var assert = require("assert");
var {defer, promises} = require("ringo/promise");
var {Worker} = require("ringo/worker");
var semaphore = new java.util.concurrent.Semaphore(0);

exports.testPromiseList = function() {
    var d1 = defer(), d2 = defer(), d3 = defer(), done = defer();
    var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
    var result;
    l.then(function(value) {
        done.resolve(value);
    }, function(error) {
        done.resolve("promises called error callback", true);
    });
    done.promise.then(function(value) {
        result = value;
        semaphore.release();
    });
    // Resolve promise in worker so async promise callbacks get called
    var worker = new Worker({
        onmessage: function() {
            d2.resolve(1);
            d3.resolve("error", true);
            d1.resolve("ok");
        }
    }).postMessage();
    // wait for last promise to resolve
    semaphore.acquire();
    // make sure promises have resolved via chained callback
    assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
};

// start the test runner if we're called directly from command line
if (require.main == module.id) {
    system.exit(require('test').run(exports));
}
<|endoftext|>


<commit_before>import Component from '@ember/component';
import { computed } from 'ember-decorators/object';
import { alias, equal } from 'ember-decorators/object/computed';

import moment from 'moment';

const NOVEMBER_2017_RETIREMENT = '2017-11-28T12:00:00-08:00';
const LATEST_TRUSTY_RELEASE = '2017-12-10T00:00:00-00:00';

export default Component.extend({
  @alias('job.queue') queue: null,
  @alias('job.config') jobConfig: null,

  @computed('job.isFinished')
  conjugatedRun(isFinished) {
    return isFinished ? 'ran' : 'is running';
  },

  @equal('queue', 'builds.linux') isLegacyInfrastructure: null,
  @equal('queue', 'builds.ec2') isTrustySudoFalse: null,

  @computed('job.startedAt', 'queue', 'job.config')
  isTrustySudoRequired(startedAt, queue, config) {
    console.log(queue);
    console.log(config);
    console.log(config.dist);
    if (queue === 'builds.gce' && config.dist === 'trusty') {
      console.log('!!!! Before date condition.');
      const jobRanAfterReleaseDate = Date.parse(startedAt) > Date.parse(LATEST_TRUSTY_RELEASE);
      if (jobRanAfterReleaseDate) {
        console.log('!!!!! Ran after release date!');
        return true;
      }
    }

    console.log('!!!!! Ran before release date!');
    return false;
  },

  @equal('queue', 'builds.macstadium6') isMacStadium6: null,

  @computed('queue', 'job.config')
  isPreciseEOL(queue, config = {}) {
    if (queue === 'builds.gce' && config.dist === 'precise') {
      if (config.language !== 'android') {
        return true;
      }
    }
  },

  @alias('jobConfig.osx_image') macOSImage: null,

  deprecatedXcodeImages: ['xcode8', 'xcode8.1', 'xcode8.2'],

  imageToRetirementDate: {
    'xcode8': NOVEMBER_2017_RETIREMENT,
    'xcode8.1': NOVEMBER_2017_RETIREMENT,
    'xcode8.2': NOVEMBER_2017_RETIREMENT
  },

  imageToNewImage: {
    'xcode8': 'xcode8.3',
    'xcode8.1': 'xcode8.3',
    'xcode8.2': 'xcode8.3'
  },

  newImageStrings: {
    'xcode8.3': 'Xcode 8.3',
    'xcode7.3': 'Xcode 7.3.1',
    'xcode6.4': 'Xcode 6.4'
  },

  @computed('isMacStadium6', 'macOSImage')
  isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) {
    return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage);
  },

  // eslint-disable-next-line
  @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage')
  deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) {
    const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]);

    const newImage = this.get('imageToNewImage')[image];
    const newImageString = this.get('newImageStrings')[newImage];
    const newImageAnchor = newImageString.replace(' ', '-');
    const newImageURLString = `<a href='https://docs.travis-ci.com/user/reference/osx/#${newImageAnchor}'>${newImageString}</a>`;
    const imageRetirementAnnouncementURL = 'https://blog.travis-ci.com/2017-11-21-xcode8-3-default-image-announce';

    const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate;
    const retirementDateIsInTheFuture = retirementDate > new Date();

    const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY');

    const retirementLink =
      `
      ${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'}
      on ${formattedRetirementDate}`;

    let retirementSentence, routingSentence;

    if (retirementDateIsInTheFuture) {
      retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`;
    } else {
      retirementSentence = `
        This job ${isFinished ? 'was configured to run on' : 'is configured to run on'}
        an OS X image that ${retirementLink}.`;
    }

    if (retirementDateIsInTheFuture) {
      routingSentence =
        `After that, it will route to our ${newImageURLString} image.`;
    } else if (jobRanBeforeRetirementDate) {
      routingSentence = `New jobs will route to our ${newImageURLString} image.`;
    } else {
      routingSentence = `It was routed to our ${newImageURLString} image.`;
    }

    return `${retirementSentence} ${routingSentence}`;
  }
});
<commit_msg>Fingers crossed.<commit_after>import Component from '@ember/component';
import { computed } from 'ember-decorators/object';
import { alias, equal } from 'ember-decorators/object/computed';

import moment from 'moment';

const NOVEMBER_2017_RETIREMENT = '2017-11-28T12:00:00-08:00';
const LATEST_TRUSTY_RELEASE = '2017-12-10T00:00:00-00:00';

export default Component.extend({
  @alias('job.queue') queue: null,
  @alias('job.config') jobConfig: null,

  @computed('job.isFinished')
  conjugatedRun(isFinished) {
    return isFinished ? 'ran' : 'is running';
  },

  @equal('queue', 'builds.linux') isLegacyInfrastructure: null,
  @equal('queue', 'builds.ec2') isTrustySudoFalse: null,

  @computed('job.startedAt', 'queue', 'job.config.dist')
  isTrustySudoRequired(startedAt, queue, dist) {
    if (queue === 'builds.gce' && config.dist === 'trusty') {
      console.log('!!!! Before date condition.');
      const jobRanAfterReleaseDate = Date.parse(startedAt) > Date.parse(LATEST_TRUSTY_RELEASE);
      if (jobRanAfterReleaseDate) {
        console.log('!!!!! Ran after release date!');
        return true;
      }
    }

    console.log('!!!!! Ran before release date!');
    return false;
  },

  @equal('queue', 'builds.macstadium6') isMacStadium6: null,

  @computed('queue', 'job.config')
  isPreciseEOL(queue, config = {}) {
    if (queue === 'builds.gce' && config.dist === 'precise') {
      if (config.language !== 'android') {
        return true;
      }
    }
  },

  @alias('jobConfig.osx_image') macOSImage: null,

  deprecatedXcodeImages: ['xcode8', 'xcode8.1', 'xcode8.2'],

  imageToRetirementDate: {
    'xcode8': NOVEMBER_2017_RETIREMENT,
    'xcode8.1': NOVEMBER_2017_RETIREMENT,
    'xcode8.2': NOVEMBER_2017_RETIREMENT
  },

  imageToNewImage: {
    'xcode8': 'xcode8.3',
    'xcode8.1': 'xcode8.3',
    'xcode8.2': 'xcode8.3'
  },

  newImageStrings: {
    'xcode8.3': 'Xcode 8.3',
    'xcode7.3': 'Xcode 7.3.1',
    'xcode6.4': 'Xcode 6.4'
  },

  @computed('isMacStadium6', 'macOSImage')
  isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) {
    return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage);
  },

  // eslint-disable-next-line
  @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage')
  deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) {
    const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]);

    const newImage = this.get('imageToNewImage')[image];
    const newImageString = this.get('newImageStrings')[newImage];
    const newImageAnchor = newImageString.replace(' ', '-');
    const newImageURLString = `<a href='https://docs.travis-ci.com/user/reference/osx/#${newImageAnchor}'>${newImageString}</a>`;
    const imageRetirementAnnouncementURL = 'https://blog.travis-ci.com/2017-11-21-xcode8-3-default-image-announce';

    const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate;
    const retirementDateIsInTheFuture = retirementDate > new Date();

    const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY');

    const retirementLink =
      `
      ${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'}
      on ${formattedRetirementDate}`;

    let retirementSentence, routingSentence;

    if (retirementDateIsInTheFuture) {
      retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`;
    } else {
      retirementSentence = `
        This job ${isFinished ? 'was configured to run on' : 'is configured to run on'}
        an OS X image that ${retirementLink}.`;
    }

    if (retirementDateIsInTheFuture) {
      routingSentence =
        `After that, it will route to our ${newImageURLString} image.`;
    } else if (jobRanBeforeRetirementDate) {
      routingSentence = `New jobs will route to our ${newImageURLString} image.`;
    } else {
      routingSentence = `It was routed to our ${newImageURLString} image.`;
    }

    return `${retirementSentence} ${routingSentence}`;
  }
});
<|endoftext|>


<commit_before>/** @jsx hJSX */
import {run, Rx} from '@cycle/core';
import {makeDOMDriver, hJSX} from '@cycle/dom';

function main(drivers) {
  let secondsElapsed$ = Rx.Observable.interval(1000)
    .map(i => i + 1)
    .startWith(0);
  let vtree$ = secondsElapsed$.map(secondsElapsed =>

{`Seconds elapsed ${secondsElapsed}`}

  );
  return {DOM: vtree$};
}

let drivers = {
 DOM: makeDOMDriver('#main-container')
};

run(main, drivers);
<commit_msg>Improve code style in jsx-seconds-elapsed example<commit_after>/** @jsx hJSX */
import {run, Rx} from '@cycle/core';
import {makeDOMDriver, hJSX} from '@cycle/dom';

function main(drivers) {
  let secondsElapsed$ = Rx.Observable.interval(1000)
    .map(i => i + 1)
    .startWith(0);
  let vtree$ = secondsElapsed$.map(secondsElapsed =>

Seconds elapsed {secondsElapsed}

  );
  return {DOM: vtree$};
}

let drivers = {
 DOM: makeDOMDriver('#main-container')
};

run(main, drivers);
<|endoftext|>


<commit_before>var bing = require('../lib/bing-api');
var client = new bing.SearchClient({appId: process.env.BING_APP_ID});
client.search("variolabs", function(error, response, data) {

  if (!error && response.statusCode == 200)
  {
    if (data === null || data.SearchResponse === null || (data.SearchResponse.Errors && data.SearchResponse.Errors.length > 0))
    {
      if (error === null)
        error = ""

      for (var i = data.SearchResponse.Errors.length - 1; i >= 0; i--){
        error += data.SearchResponse.Errors[i].Message;
        if (data.SearchResponse.Errors[i].Parameter)
        {
          error += " ("+data.SearchResponse.Errors[i].Parameter+")";
        }
      };

      console.log("ERROR executing search: "+error);
    } else {
      console.log("SUCCESS: Found " + data.SearchResponse.Web.Results.length + " results");
    }

  } else {
    console.log("ERROR! " + error + "/" + response.statusCode);
  }

});<commit_msg>eliminate test code that shouldn't get hit<commit_after>var bing = require('../lib/bing-api');
var client = new bing.SearchClient({appId: process.env.BING_APP_ID});
client.search("variolabs", function(error, response, data) {

  if (!error && response.statusCode == 200)
  {
    console.log("SUCCESS: Found " + data.SearchResponse.Web.Results.length + " results");
  } else {
    console.log("ERROR! " + error + "/" + response.statusCode);
  }

});<|endoftext|>


<commit_before>(function() {
  "use strict";

  var setup = require("../test/setup");
  var assert = require("assert");
  var express = require("express");
  var http = require('http');
  var Q = require("q");
  var nconf = require("../server/config.js");

  var app = express();
  var server;

  var port = nconf.get("testServer_port");

  exports.setUp = function(callback) {

    app.get("/empty", function(req, res) {
      res.send("<title>lol hmm</title>This page has no links.");
    });

    app.get("/multiple", function(req, res) {
      res.send("");
    });

    app.get("/links-to-empty", function(req, res) {
      res.send("click me");
    });

    server = http.createServer(app);
    server.listen(port, callback);
  };

  exports.tearDown = function(callback) {
    console.log("running tearDown");
    if (server) {
      server.close(callback);
      server = null;
    }
  };

/*
  require("nodeunit").on('complete', function() {
    console.log("complete event");
    setup.clearPhantomCache();
  });
*/
  exports.clickElement = {};

  setup.qtest(exports, "should pass arguments to evaluate correctly", setup.usingPhantom(function(page) {

    return page.promise.evaluate(function(a,b,c) {
      return a + b + c;
    },1,2,3)
    .then(function(result) {
      assert.equal(result, 6);
    });
  }));

  setup.qtest(exports, "should be able to load page content as a string", setup.usingPhantom(function(page) {
    return page.promise.open("http://localhost:" + port + "/empty")
      .then(function(status) {
        assert.equal(status, "success");
      })
      .then(function() {
        return page.promise.get("content");
      })
      .then(function(content) {
        assert.ok(content.indexOf("This page has no links") > -1, "Expected page content");
      });
  }));

  setup.qtest(exports.clickElement, "should give useful error when not found", setup.usingPhantom(function(page) {
    return setup.shouldFail(function() {
      return page.promise.open("http://localhost:" + port + "/empty")
      .then(function(status) {
        assert.equal(status, "success");
      })
      .then(function() {
        return page.promise.clickElement("a.target");
      });
    }, "An element matching 'a.target' not found");
  }));

  setup.qtest(exports.clickElement, "should give useful error when multiple found", setup.usingPhantom(function(page) {
    return setup.shouldFail(function() {
      return page.promise.open("http://localhost:" + port + "/multiple")
      .then(function(status) {
        assert.equal(status, "success");
      })
      .then(function() {
        return page.promise.clickElement("a.target");
      });
    }, "More than one elements matching 'a.target' were found");
  }));

  setup.qtest(exports.clickElement, "should click element when found", setup.usingPhantom(function(page) {
    return page.promise.open("http://localhost:" + port + "/links-to-empty")
    .then(function(status) {
      assert.equal(status, "success");
    })
    .then(function() {
      return page.promise.clickElement("a.target");
    })
    .then(function() {
      return page.promise.get("url");
    })
    .then(function(url) {
      assert.equal(url, "http://localhost:" + port + "/empty");
    });
  }));
})();

<commit_msg>add wait to tests<commit_after>(function() {
  "use strict";

  var setup = require("../test/setup");
  var assert = require("assert");
  var express = require("express");
  var http = require('http');
  var Q = require("q");
  var nconf = require("../server/config.js");
  var waitUntil = require("./waitUntil.js");

  var app = express();
  var server;

  var port = nconf.get("testServer_port");

  exports.setUp = function(callback) {

    app.get("/empty", function(req, res) {
      res.send("<title>lol hmm</title>This page has no links.");
    });

    app.get("/multiple", function(req, res) {
      res.send("");
    });

    app.get("/links-to-empty", function(req, res) {
      res.send("click me");
    });

    server = http.createServer(app);
    server.listen(port, callback);
  };

  exports.tearDown = function(callback) {
    console.log("running tearDown");
    if (server) {
      server.close(callback);
      server = null;
    }
  };

/*
  require("nodeunit").on('complete', function() {
    console.log("complete event");
    setup.clearPhantomCache();
  });
*/
  exports.clickElement = {};

  setup.qtest(exports, "should pass arguments to evaluate correctly", setup.usingPhantom(function(page) {

    return page.promise.evaluate(function(a,b,c) {
      return a + b + c;
    },1,2,3)
    .then(function(result) {
      assert.equal(result, 6);
    });
  }));

  setup.qtest(exports, "should be able to load page content as a string", setup.usingPhantom(function(page) {
    return page.promise.open("http://localhost:" + port + "/empty")
      .then(function(status) {
        assert.equal(status, "success");
      })
      .then(function() {
        return page.promise.get("content");
      })
      .then(function(content) {
        assert.ok(content.indexOf("This page has no links") > -1, "Expected page content");
      });
  }));

  setup.qtest(exports.clickElement, "should give useful error when not found", setup.usingPhantom(function(page) {
    return setup.shouldFail(function() {
      return page.promise.open("http://localhost:" + port + "/empty")
      .then(function(status) {
        assert.equal(status, "success");
      })
      .then(function() {
        return page.promise.clickElement("a.target");
      });
    }, "An element matching 'a.target' not found");
  }));

  setup.qtest(exports.clickElement, "should give useful error when multiple found", setup.usingPhantom(function(page) {
    return setup.shouldFail(function() {
      return page.promise.open("http://localhost:" + port + "/multiple")
      .then(function(status) {
        assert.equal(status, "success");
      })
      .then(function() {
        return page.promise.clickElement("a.target");
      });
    }, "More than one elements matching 'a.target' were found");
  }));

  setup.qtest(exports.clickElement, "should click element when found", setup.usingPhantom(function(page) {
    return page.promise.open("http://localhost:" + port + "/links-to-empty")
    .then(function(status) {
      assert.equal(status, "success");
    })
    .then(function() {
      return page.promise.clickElement("a.target");
    })
    .then(function() {
      var start = new Date();
      return waitUntil(function() {
          return page.promise.get("url").then(function(url) {
              console.log("url was", url);
              return url == "http://localhost:" + port + "/empty";
          });
      }, 1000);
    });
  }));
})();

<|endoftext|>


<commit_before>/**
 * Created by cfraser on 2014-04-27.
 */

( function () {
/*
 Problem 1
 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

 Find the sum of all the multiples of 3 or 5 below 1000.

 Resources:
 1) http://www.algebra.com/algebra/homework/Sequences-and-series.faq.question.427328.html

 Sn = (n/2) * (a1 + an)

 Sn = the sum of the n terms in the sequence.
 a1 = the first term in the sequence.
 an = the nth term in the sequence.

*/
    var problemOne = function (multiples, limit) {
        var terms = [],
            an = 0,
            a1 = 0,
            answer = 0;

        var largestMultiple = function (multiple, limit) {
            var largestMultiple;
            // quickly find the largest multiple under the limit
            for (largestMultiple = limit - 1; largestMultiple > 0; largestMultiple--) {
                if (largestMultiple % multiple == 0) {
                        break;
                }
            }

            return largestMultiple;
        }

        var sumMultiples = function (number, limit) {
            var sumMultiples = 0,
                largest = largestMultiple(number, limit);

            for (var x = 1; x <= largest / number; x++) {
                sumMultiples += number * x;
            }

            return sumMultiples;
        }

        for (var x = 0; x < multiples.length; x++) {
            answer += sumMultiples(multiples[x], limit);

        }

        // TODO: We know that we're only getting two items in the array. This could
        // TODO: be refactored later to support an unknown array size.
        var commonMultiple = multiples[0] * multiples[1];

        // remove one set of common multiples, since we added the common multiples twice.
        answer -= sumMultiples(commonMultiple, limit);

        return answer;
    }

/*
 Problem 2.

 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

 Resources:

 1) My brain. ;) - this seemed pretty straight forward when I read the problem.

 */
    var problemTwo = function (limit) {
        var values = [0, 1],
            sum = 0,
            answer = 0;

        // I'd probably break this out into a utility library if this problem wasn't so
        // self contained.
        var isEven = function( value ) {
            if (value % 2 == 0) {
                return true;
            }
            else {
                return false;
            }
        }

        while (sum < limit) {
            sum = values[0] + values [1];

            // This seems like the cleanest way to sum the elements of the sequence.
            // Add the latest sum to the right most side of the array, and drop the left most.
            values.push(sum);
            values.shift();

            // Only accumulate the even sums.
            if (isEven(sum)) {
                answer += sum;
            }
        }

        return answer;
    }

    /*

     Problem 3
     The prime factors of 13195 are 5, 7, 13 and 29.

     What is the largest prime factor of the number 600851475143 ?

     Resources:

     1) http://www.mathsisfun.com/prime-factorization.html

     */

    var problemThree = function ( upperBound ) {
        // The largest prime starts at 2 as it's the prime number we start with.
        var largestPrime = 2,
            lowerBound = 2;

        var isPrime = function (number) {
            // Prime numbers are only divisble by 1 and themselves.
            // So we'll test the range of numbers outside that set.
            for (var x = 2; x < number; x++) {
                if ( number % x == 0) {
                    return false;
                }
            }
            return true;
        }

        for (var x = lowerBound; x <= upperBound; x++) {
            if (upperBound % x == 0) {
                // When we find a factor of the current upper bound adjust the upper bound and test for prime.
                upperBound = upperBound / x;
                if (isPrime(x)) {
                    largestPrime = x;
                }
                else if (isPrime(upperBound)) {
                    largestPrime = upperBound;
                }

                // reset the counter.
                x = 1;
            }
        }

        return largestPrime;
    }

    var main = function() {
        var startTime;
        var now = function() {
            return new Date().getTime();
        }
        console.log("\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");
        console.log("Problem 1\n" +
            "If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n\n" +
            "Find the sum of all the multiples of 3 or 5 below 1000.\n\n" +
            "Resources:\n" +
            "1) http://www.algebra.com/algebra/homework/Sequences-and-series.faq.question.427328.html\n\n" +
            "Sn = (n/2) * (a1 + an)\n" +
            "Sn = the sum of the n terms in the sequence.\n" +
            "a1 = the first term in the sequence." +
            "an = the nth term in the sequence.\n\n");
        startTime = now();
        console.log("Answer: " + problemOne([3, 5], 1000));
        console.log("Compute time: " + (now() - startTime)  + "ms");
        console.log("\n\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");

        console.log("Problem 2\n" +
            "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n\n" +
            "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n" +
            "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n\n");
        startTime = now();
        console.log("Answer: " + problemTwo(4000000));
        console.log("Compute time: " + (now() - startTime)  + "ms");
        console.log("\n\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");

        console.log("Problem 3\n" +
            "The prime factors of 13195 are 5, 7, 13 and 29.\n\n" +
            "What is the largest prime factor of the number 600851475143 ?\n\n");
        startTime = now();
        console.log("Answer: " + problemThree(600851475143));
        console.log("Compute time: " + (now() - startTime) + "ms");
        console.log("\n\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");
    }

    main();
})();
<commit_msg>remove unused variables<commit_after>/**
 * Created by cfraser on 2014-04-27.
 */

( function () {
/*
 Problem 1
 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

 Find the sum of all the multiples of 3 or 5 below 1000.

 Resources:
 1) http://www.algebra.com/algebra/homework/Sequences-and-series.faq.question.427328.html
 2) http://www.factmonster.com/ipka/A0933353.html

 Sn = (n/2) * (a1 + an)

 Sn = the sum of the n terms in the sequence.
 a1 = the first term in the sequence.
 an = the nth term in the sequence.

*/
    var problemOne = function (multiples, limit) {
        var answer = 0;

        var largestMultiple = function (multiple, limit) {
            var largestMultiple;
            // quickly find the largest multiple under the limit
            for (largestMultiple = limit - 1; largestMultiple > 0; largestMultiple--) {
                if (largestMultiple % multiple == 0) {
                        break;
                }
            }

            return largestMultiple;
        }

        var sumMultiples = function (number, limit) {
            var sumMultiples = 0,
                largest = largestMultiple(number, limit);

            for (var x = 1; x <= largest / number; x++) {
                sumMultiples += number * x;
            }

            return sumMultiples;
        }

        for (var x = 0; x < multiples.length; x++) {
            answer += sumMultiples(multiples[x], limit);

        }

        // TODO: We know that we're only getting two items in the array. This could
        // TODO: be refactored later to support an unknown array size.
        var commonMultiple = multiples[0] * multiples[1];

        // remove one set of common multiples, since we added the common multiples twice.
        answer -= sumMultiples(commonMultiple, limit);

        return answer;
    }

/*
 Problem 2.

 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

 Resources:

 1) My brain. ;) - this seemed pretty straight forward when I read the problem.

 */
    var problemTwo = function (limit) {
        var values = [0, 1],
            sum = 0,
            answer = 0;

        // I'd probably break this out into a utility library if this problem wasn't so
        // self contained.
        var isEven = function( value ) {
            if (value % 2 == 0) {
                return true;
            }
            else {
                return false;
            }
        }

        while (sum < limit) {
            sum = values[0] + values [1];

            // This seems like the cleanest way to sum the elements of the sequence.
            // Add the latest sum to the right most side of the array, and drop the left most.
            values.push(sum);
            values.shift();

            // Only accumulate the even sums.
            if (isEven(sum)) {
                answer += sum;
            }
        }

        return answer;
    }

    /*

     Problem 3
     The prime factors of 13195 are 5, 7, 13 and 29.

     What is the largest prime factor of the number 600851475143 ?

     Resources:

     1) http://www.mathsisfun.com/prime-factorization.html
     2) http://www.mathsisfun.com/numbers/factors-all-tool.html

     */

    var problemThree = function ( upperBound ) {
        // The largest prime starts at 2 as it's the prime number we start with.
        var largestPrime = 2,
            lowerBound = 2;

        var isPrime = function (number) {
            // Prime numbers are only divisble by 1 and themselves.
            // So we'll test the range of numbers outside that set.
            for (var x = 2; x < number; x++) {
                if ( number % x == 0) {
                    return false;
                }
            }
            return true;
        }

        for (var x = lowerBound; x <= upperBound; x++) {
            if (upperBound % x == 0) {
                // When we find a factor of the current upper bound adjust the upper bound and test for prime.
                upperBound = upperBound / x;
                if (isPrime(x)) {
                    largestPrime = x;
                }
                else if (isPrime(upperBound)) {
                    largestPrime = upperBound;
                }

                // reset the counter.
                x = 1;
            }
        }

        return largestPrime;
    }

    var main = function() {
        var startTime;
        var now = function() {
            return new Date().getTime();
        }
        console.log("\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");
        console.log("Problem 1\n" +
            "If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n\n" +
            "Find the sum of all the multiples of 3 or 5 below 1000.\n\n" +
            "Resources:\n" +
            "1) http://www.algebra.com/algebra/homework/Sequences-and-series.faq.question.427328.html\n\n" +
            "Sn = (n/2) * (a1 + an)\n" +
            "Sn = the sum of the n terms in the sequence.\n" +
            "a1 = the first term in the sequence." +
            "an = the nth term in the sequence.\n\n");
        startTime = now();
        console.log("Answer: " + problemOne([3, 5], 1000));
        console.log("Compute time: " + (now() - startTime)  + "ms");
        console.log("\n\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");

        console.log("Problem 2\n" +
            "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n\n" +
            "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n" +
            "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n\n");
        startTime = now();
        console.log("Answer: " + problemTwo(4000000));
        console.log("Compute time: " + (now() - startTime)  + "ms");
        console.log("\n\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");

        console.log("Problem 3\n" +
            "The prime factors of 13195 are 5, 7, 13 and 29.\n\n" +
            "What is the largest prime factor of the number 600851475143 ?\n\n");
        startTime = now();
        console.log("Answer: " + problemThree(600851475143));
        console.log("Compute time: " + (now() - startTime) + "ms");
        console.log("\n\n-------------------------------------------------------------------------------------------------------------------------------------\n\n");
    }

    main();
})();
<|endoftext|>


<commit_before>import Component from '@ember/component';
import { computed } from 'ember-decorators/object';
import { alias, equal } from 'ember-decorators/object/computed';

import moment from 'moment';

const NOVEMBER_2017_RETIREMENT = '2017-11-28T12:00:00-08:00';
const LATEST_TRUSTY_RELEASE = '2017-07-12T18:00:00-00:00';

export default Component.extend({
  @alias('job.queue') queue: null,
  @alias('job.config') jobConfig: null,

  @computed('job.isFinished')
  conjugatedRun(isFinished) {
    return isFinished ? 'ran' : 'is running';
  },

  @equal('queue', 'builds.linux') isLegacyInfrastructure: null,
  @equal('queue', 'builds.ec2') isTrustySudoFalse: null,

  @computed('job.startedAt', 'job.config')
  isTrustyStable(startedAt, config = {}) {
    if (config.dist === 'trusty' && config.group === 'stable') {
      const jobRanAfterReleaseDate = Date.parse(startedAt) > Date.parse(LATEST_TRUSTY_RELEASE);
      if (jobRanAfterReleaseDate) {
        return true;
      }
    }

    return false;
  },

  @equal('queue', 'builds.macstadium6') isMacStadium6: null,

  @computed('queue', 'job.config')
  isPreciseEOL(queue, config = {}) {
    if (queue === 'builds.gce' && config.dist === 'precise') {
      if (config.language !== 'android') {
        return true;
      }
    }
  },

  @alias('jobConfig.osx_image') macOSImage: null,

  deprecatedXcodeImages: ['xcode8', 'xcode8.1', 'xcode8.2'],

  imageToRetirementDate: {
    'xcode8': NOVEMBER_2017_RETIREMENT,
    'xcode8.1': NOVEMBER_2017_RETIREMENT,
    'xcode8.2': NOVEMBER_2017_RETIREMENT
  },

  imageToNewImage: {
    'xcode8': 'xcode8.3',
    'xcode8.1': 'xcode8.3',
    'xcode8.2': 'xcode8.3'
  },

  newImageStrings: {
    'xcode8.3': 'Xcode 8.3.3',
    'xcode7.3': 'Xcode 7.3.1',
    'xcode6.4': 'Xcode 6.4'
  },

  @computed('isMacStadium6', 'macOSImage')
  isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) {
    return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage);
  },

  // eslint-disable-next-line
  @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage')
  deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) {
    const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]);

    const newImage = this.get('imageToNewImage')[image];
    const newImageString = this.get('newImageStrings')[newImage];
    const newImageAnchor = newImageString.replace(' ', '-');
    const newImageURLString = `<a href='https://docs.travis-ci.com/user/reference/osx/#${newImageAnchor}'>${newImageString}</a>`;
    const imageRetirementAnnouncementURL = 'https://blog.travis-ci.com/2017-11-21-xcode8-3-default-image-announce';

    const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate;
    const retirementDateIsInTheFuture = retirementDate > new Date();

    const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY');

    const retirementLink =
      `
      ${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'}
      on ${formattedRetirementDate}`;

    let retirementSentence, routingSentence;

    if (retirementDateIsInTheFuture) {
      retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`;
    } else {
      retirementSentence = `
        This job ${isFinished ? 'was configured to run on' : 'is configured to run on'}
        an OS X image that ${retirementLink}.`;
    }

    if (retirementDateIsInTheFuture) {
      routingSentence =
        `After that, it will route to our ${newImageURLString} image.`;
    } else if (jobRanBeforeRetirementDate) {
      routingSentence = `New jobs will route to our ${newImageURLString} image.`;
    } else {
      routingSentence = `It was routed to our ${newImageURLString} image.`;
    }

    return `${retirementSentence} ${routingSentence}`;
  }
});
<commit_msg>Fixed xcode8.3 doc link.<commit_after>import Component from '@ember/component';
import { computed } from 'ember-decorators/object';
import { alias, equal } from 'ember-decorators/object/computed';

import moment from 'moment';

const NOVEMBER_2017_RETIREMENT = '2017-11-28T12:00:00-08:00';
const LATEST_TRUSTY_RELEASE = '2017-07-12T18:00:00-00:00';

export default Component.extend({
  @alias('job.queue') queue: null,
  @alias('job.config') jobConfig: null,

  @computed('job.isFinished')
  conjugatedRun(isFinished) {
    return isFinished ? 'ran' : 'is running';
  },

  @equal('queue', 'builds.linux') isLegacyInfrastructure: null,
  @equal('queue', 'builds.ec2') isTrustySudoFalse: null,

  @computed('job.startedAt', 'job.config')
  isTrustyStable(startedAt, config = {}) {
    if (config.dist === 'trusty' && config.group === 'stable') {
      const jobRanAfterReleaseDate = Date.parse(startedAt) > Date.parse(LATEST_TRUSTY_RELEASE);
      if (jobRanAfterReleaseDate) {
        return true;
      }
    }

    return false;
  },

  @equal('queue', 'builds.macstadium6') isMacStadium6: null,

  @computed('queue', 'job.config')
  isPreciseEOL(queue, config = {}) {
    if (queue === 'builds.gce' && config.dist === 'precise') {
      if (config.language !== 'android') {
        return true;
      }
    }
  },

  @alias('jobConfig.osx_image') macOSImage: null,

  deprecatedXcodeImages: ['xcode8', 'xcode8.1', 'xcode8.2'],

  imageToRetirementDate: {
    'xcode8': NOVEMBER_2017_RETIREMENT,
    'xcode8.1': NOVEMBER_2017_RETIREMENT,
    'xcode8.2': NOVEMBER_2017_RETIREMENT
  },

  imageToNewImage: {
    'xcode8': 'xcode8.3',
    'xcode8.1': 'xcode8.3',
    'xcode8.2': 'xcode8.3'
  },

  newImageStrings: {
    'xcode8.3': 'Xcode 8.3',
    'xcode7.3': 'Xcode 7.3.1',
    'xcode6.4': 'Xcode 6.4'
  },

  @computed('isMacStadium6', 'macOSImage')
  isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) {
    return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage);
  },

  // eslint-disable-next-line
  @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage')
  deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) {
    const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]);

    const newImage = this.get('imageToNewImage')[image];
    const newImageString = this.get('newImageStrings')[newImage];
    const newImageAnchor = newImageString.replace(' ', '-');
    const newImageURLString = `<a href='https://docs.travis-ci.com/user/reference/osx/#${newImageAnchor}'>${newImageString}</a>`;
    const imageRetirementAnnouncementURL = 'https://blog.travis-ci.com/2017-11-21-xcode8-3-default-image-announce';

    const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate;
    const retirementDateIsInTheFuture = retirementDate > new Date();

    const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY');

    const retirementLink =
      `
      ${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'}
      on ${formattedRetirementDate}`;

    let retirementSentence, routingSentence;

    if (retirementDateIsInTheFuture) {
      retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`;
    } else {
      retirementSentence = `
        This job ${isFinished ? 'was configured to run on' : 'is configured to run on'}
        an OS X image that ${retirementLink}.`;
    }

    if (retirementDateIsInTheFuture) {
      routingSentence =
        `After that, it will route to our ${newImageURLString} image.`;
    } else if (jobRanBeforeRetirementDate) {
      routingSentence = `New jobs will route to our ${newImageURLString} image.`;
    } else {
      routingSentence = `It was routed to our ${newImageURLString} image.`;
    }

    return `${retirementSentence} ${routingSentence}`;
  }
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Tabs, { Tab } from 'material-ui/Tabs';
import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';
import Hidden from 'material-ui/Hidden';
import Grid from 'material-ui/Grid';

import SingleStructureView from 'components/SingleStructureView';

import BarrierChart from 'components/BarrierChart';

const styles = (theme) => ({
  tab: {
    backgroundColor: theme.palette.primary[50],
    textTransform: 'none',
  },

});

const prettyPrintReaction = (reactants, products) => (`${Object.keys(JSON.parse(reactants)).join(' + ')}  ⇄  ${Object.keys(JSON.parse(products)).join(' + ')}`
).replace(/star/g, '*').replace(/gas/g, '(ℊ)');

function TabContainer(props) {
  return (<Typography component="div" style={{ padding: 8 * 3 }}>
    {props.children}
  </Typography>);
}

TabContainer.propTypes = {
  children: PropTypes.node.isRequired,
};

const initialState = {
  tabValue: 0,
};

class ReactionStructures extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = initialState;
  }
  handleChange = (event, value) => {
    this.setState({
      tabValue: value,
    });
  }
  render() {
    let { tabValue } = this.state;
    tabValue = Math.min(tabValue, this.props.reactionSystems.length);

    return (
 {/* div necessary before wrapping ternary expression */}
      {this.props.reactionSystems.length === 0 ? null :
      <Grid container direction="column" width="100%">

{prettyPrintReaction(this.props.selectedReaction.reactants, this.props.selectedReaction.products)} - Reaction Geometries

        <Hidden smUp>
          <BarrierChart {...this.props} thumbnailSize={50} />
        </Hidden>
        <Hidden smDown>
          <BarrierChart {...this.props} />
        </Hidden>
        <Tabs
          value={tabValue}
          onChange={this.handleChange}
          centered
          indicatorColor="primary"
          textColor="primary"
          fullWidth
          scrollButtons="auto"
        >
          {this.props.reactionSystems.map((system, i) =>
            <Tab
              label={system.key} key={`reaction_tab_${i}`}
              className={this.props.classes.tab}
            />
              )}
        </Tabs>
        <TabContainer>
          {tabValue === 0 && typeof this.props.reactionSystems[0] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[0]} selectedUUID={this.props.reactionSystems[0].uniqueId} /> }
          {tabValue === 1 && typeof this.props.reactionSystems[1] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[1]} selectedUUID={this.props.reactionSystems[1].uniqueId} /> }
          {tabValue === 2 && typeof this.props.reactionSystems[2] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[2]} selectedUUID={this.props.reactionSystems[2].uniqueId} /> }
          {tabValue === 3 && typeof this.props.reactionSystems[3] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[3]} selectedUUID={this.props.reactionSystems[3].uniqueId} /> }
          {tabValue === 4 && typeof this.props.reactionSystems[4] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[4]} selectedUUID={this.props.reactionSystems[4].uniqueId} /> }
        </TabContainer>
      </Grid>
      }

    );
  }
}

ReactionStructures.propTypes = {
  reactionSystems: PropTypes.array.isRequired,
  selectedReaction: PropTypes.object,
  classes: PropTypes.object,
};

const mapStateToProps = (state) => ({
  reactionSystems: state.get('energiesPageReducer').reactionSystems,
});

const mapDispatchToProps = () => ({
});

exports.ReactionStructures = withStyles(styles, { withTheme: true })(
connect(mapStateToProps, mapDispatchToProps)(ReactionStructures)

);
<commit_msg>Fixed reaction arrow<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Tabs, { Tab } from 'material-ui/Tabs';
import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';
import Hidden from 'material-ui/Hidden';
import Grid from 'material-ui/Grid';

import SingleStructureView from 'components/SingleStructureView';

import BarrierChart from 'components/BarrierChart';

const styles = (theme) => ({
  tab: {
    backgroundColor: theme.palette.primary[50],
    textTransform: 'none',
  },

});

const prettyPrintReaction = (reactants, products) => (`${Object.keys(JSON.parse(reactants)).join(' + ')} → ${Object.keys(JSON.parse(products)).join(' + ')}`
).replace(/star/g, '*').replace(/gas/g, '(ℊ)');

function TabContainer(props) {
  return (<Typography component="div" style={{ padding: 8 * 3 }}>
    {props.children}
  </Typography>);
}

TabContainer.propTypes = {
  children: PropTypes.node.isRequired,
};

const initialState = {
  tabValue: 0,
};

class ReactionStructures extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = initialState;
  }
  handleChange = (event, value) => {
    this.setState({
      tabValue: value,
    });
  }
  render() {
    let { tabValue } = this.state;
    tabValue = Math.min(tabValue, this.props.reactionSystems.length);

    return (
 {/* div necessary before wrapping ternary expression */}
      {this.props.reactionSystems.length === 0 ? null :
      <Grid container direction="column" width="100%">

{prettyPrintReaction(this.props.selectedReaction.reactants, this.props.selectedReaction.products)} - Reaction Geometries

        <Hidden smUp>
          <BarrierChart {...this.props} thumbnailSize={50} />
        </Hidden>
        <Hidden smDown>
          <BarrierChart {...this.props} />
        </Hidden>
        <Tabs
          value={tabValue}
          onChange={this.handleChange}
          centered
          indicatorColor="primary"
          textColor="primary"
          fullWidth
          scrollButtons="auto"
        >
          {this.props.reactionSystems.map((system, i) =>
            <Tab
              label={system.key} key={`reaction_tab_${i}`}
              className={this.props.classes.tab}
            />
              )}
        </Tabs>
        <TabContainer>
          {tabValue === 0 && typeof this.props.reactionSystems[0] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[0]} selectedUUID={this.props.reactionSystems[0].uniqueId} /> }
          {tabValue === 1 && typeof this.props.reactionSystems[1] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[1]} selectedUUID={this.props.reactionSystems[1].uniqueId} /> }
          {tabValue === 2 && typeof this.props.reactionSystems[2] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[2]} selectedUUID={this.props.reactionSystems[2].uniqueId} /> }
          {tabValue === 3 && typeof this.props.reactionSystems[3] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[3]} selectedUUID={this.props.reactionSystems[3].uniqueId} /> }
          {tabValue === 4 && typeof this.props.reactionSystems[4] !== 'undefined' && <SingleStructureView selectedSystem={this.props.reactionSystems[4]} selectedUUID={this.props.reactionSystems[4].uniqueId} /> }
        </TabContainer>
      </Grid>
      }

    );
  }
}

ReactionStructures.propTypes = {
  reactionSystems: PropTypes.array.isRequired,
  selectedReaction: PropTypes.object,
  classes: PropTypes.object,
};

const mapStateToProps = (state) => ({
  reactionSystems: state.get('energiesPageReducer').reactionSystems,
});

const mapDispatchToProps = () => ({
});

exports.ReactionStructures = withStyles(styles, { withTheme: true })(
connect(mapStateToProps, mapDispatchToProps)(ReactionStructures)

);
<|endoftext|>


<commit_before>var Houses = require('../spiders/soufun/houses');
var HotZone = require('../spiders/soufun/hotZone');
var co = require('co');
var expect = require('expect.js');
require('should');

describe('soufun testing', function () {
    it('houses testing', function (done) {
        co(function*() {
            var h = new Houses('http://zu.fang.com/house/list/');
            var listPage = yield h.getHouses();
            expect(listPage).not.to.be(null);
            expect(listPage.houses).not.to.be(null);
            Object.prototype.toString.call(listPage.houses).should.equal('[object Array]');
            listPage.houses.length.should.greaterThan(10);
            done();
        });
    });

    it('hot zone testing', function(done){
        co(function*() {
            var zone = new HotZone('http://zu.fang.com/house/list/');
            var hotZones = yield zone.getHotZones();
            expect(hotZones).not.to.be(null);
            Object.prototype.toString.call(hotZones).should.equal('[object Array]');
            hotZones.length.should.greaterThan(10);
            done();
        });
    });
});
<commit_msg>change soufun testing entrypoint.<commit_after>var Houses = require('../spiders/soufun/houses');
var HotZone = require('../spiders/soufun/hotZone');
var co = require('co');
var expect = require('expect.js');
require('should');

describe('soufun testing', function () {
    it('houses testing', function (done) {
        co(function*() {
            var h = new Houses('http://zu.sh.fang.com/house/list/a21/');
            var listPage = yield h.getHouses();
            expect(listPage).not.to.be(null);
            expect(listPage.houses).not.to.be(null);
            Object.prototype.toString.call(listPage.houses).should.equal('[object Array]');
            listPage.houses.length.should.greaterThan(10);
            done();
        });
    });

    it('hot zone testing', function(done){
        co(function*() {
            var zone = new HotZone('http://zu.sh.fang.com/house/list/a21/');
            var hotZones = yield zone.getHotZones();
            expect(hotZones).not.to.be(null);
            Object.prototype.toString.call(hotZones).should.equal('[object Array]');
            hotZones.length.should.greaterThan(10);
            done();
        });
    });
});
<|endoftext|>


<commit_before>
;(function (window) {

    function Spaceview (canvasId) {

    	Spaceview.nbStars = 30
    	Spaceview.starSpeed = 8
    	Spaceview.starSize = 1

    	var ctx_
    	, width_
    	, height_
    	, center_ = []
    	, stars_ = []

    	function __construct (canvasId) {
            var canvas = document.getElementById(canvasId)
            if (canvas) {
                ctx_    = canvas.getContext('2d')
                width_  = canvas.width
                height_ = canvas.height
                center_['x'] = canvas.width/2
                center_['y'] = canvas.height/2

                while (stars_.length < Spaceview.nbStars) {
                	popStar()
                }

                setInterval(onTick, 25) // start animations

                stars_[0].drawInContext(ctx_)
            } else {
                console.log('No canvas with id: %s', canvasId)
            }
        }  __construct(canvasId);

        function popStar () {
        	var x = center_.x
        	var y = center_.y
        	var speed = Spaceview.starSpeed
        	var star = new Star(x, y, speed)
        	stars_.push(star)
        }

        function onTick () {
        	// TODO
        }

        /**
        * Star class
        *
        */
        function Star (x, y, velocity) {
        	this.x = x
        	this.y = y
        	this.velocity = velocity

        	this.drawInContext = function (ctx) {
        		// Temp draw black BG here
        		ctx.fillStyle = 'black'
        		ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)

        		ctx.fillStyle = 'white'
            	ctx.beginPath()
            	ctx.arc(this.x, this.y, Spaceview.starSize, 0, Math.PI * 2, true)
            	ctx.closePath()
            	ctx.fill()
        	}
        }

	}

window.Spaceview = Spaceview

}(window));<commit_msg>Removed width and height, useless variables.<commit_after>
;(function (window) {

    function Spaceview (canvasId) {

    	Spaceview.nbStars = 30
    	Spaceview.starSpeed = 8
    	Spaceview.starSize = 1

    	var ctx_
    	, center_ = []
    	, stars_ = []

    	function __construct (canvasId) {
            var canvas = document.getElementById(canvasId)
            if (canvas) {
                ctx_    = canvas.getContext('2d')
                center_['x'] = canvas.width/2
                center_['y'] = canvas.height/2

                while (stars_.length < Spaceview.nbStars) {
                	popStar()
                }

                setInterval(onTick, 25) // start animations

                stars_[0].drawInContext(ctx_)
            } else {
                console.log('No canvas with id: %s', canvasId)
            }
        }  __construct(canvasId);

        function popStar () {
        	var x = center_.x
        	var y = center_.y
        	var speed = Spaceview.starSpeed
        	var star = new Star(x, y, speed)
        	stars_.push(star)
        }

        function onTick () {
        	// TODO
        }

        /**
        * Star class
        *
        */
        function Star (x, y, velocity) {
        	this.x = x
        	this.y = y
        	this.velocity = velocity

        	this.drawInContext = function (ctx) {
        		// Temp draw black BG here
        		ctx.fillStyle = 'black'
        		ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)

        		ctx.fillStyle = 'white'
            	ctx.beginPath()
            	ctx.arc(this.x, this.y, Spaceview.starSize, 0, Math.PI * 2, true)
            	ctx.closePath()
            	ctx.fill()
        	}
        }

	}

window.Spaceview = Spaceview

}(window));<|endoftext|>


<commit_before>var openid = require('openid');
var url = require('url');
var nonLoginPaths = {
    "/login" : true,
    "/favicon.ico" : true
};

var conf = {
    "dev" : {
        "host" : "http://localhost:5000"
    },
    "production" : {
        "host" : "http://business-game.kbsbng.com"
    }
};
var env = "dev";
if (process.env.NODE_ENV == "production") {
    env ="production";
}
var config = conf[env];
var nonLoginPatterns = [ '^/combo~', '^/static' ];
module.exports =
    function(req, res, next) {
        console.log(req.headers);
        console.log("called login handler: " + req.url);
        var parsedUrl = url.parse(req.url, true);
        var i;
        var relyingParty = new openid.RelyingParty(
            config.host + "/verify",
            null,
          false,
            false,
            []);

        console.log(parsedUrl);
        if(parsedUrl.pathname === "/authenticate") {
             relyingParty.authenticate(parsedUrl.query['openid-identifier'],
                 false,
                 function(error, authUrl) {
                     if (error) {
                         res.writeHead(200);
                         res.end('Authentication failed: ' + error.message);
                         return;
                     }
                     if (!authUrl) {
                         res.writeHead(200);
                         res.end('Authentication failed');
                         return;
                     }

                     res.writeHead(302, { Location: authUrl });
                     res.end();
                 });
             return;
        }

        console.log(parsedUrl.pathname);
        if (nonLoginPaths[parsedUrl.pathname] === true) {
            return next();
        }
        for (i = 0; i < nonLoginPatterns.length; i++) {
            if (parsedUrl.pathname.match(nonLoginPatterns[i]) !== null) {
                return next();
            }
        }
        if (parsedUrl.pathname === "/verify") {
            console.log("Verify called");
            var result = openid.verifyAssertion(req, function(error, result) {
                res.writeHead(200);

                if (error || !result.authenticated) {
                    res.end("Auth failed");;
                    return;
                }
                res.end("Success");
                return;
            });
            return;
        }

        res.writeHead(302, { Location: config[env] + "/login" });
        res.end();
};
<commit_msg>Adding realm<commit_after>var openid = require('openid');
var url = require('url');
var nonLoginPaths = {
    "/login" : true,
    "/favicon.ico" : true
};

var conf = {
    "dev" : {
        "host" : "http://localhost:5000"
    },
    "production" : {
        "host" : "http://business-game.kbsbng.com"
    }
};
var env = "dev";
if (process.env.NODE_ENV == "production") {
    env ="production";
}
var config = conf[env];
var nonLoginPatterns = [ '^/combo~', '^/static' ];
module.exports =
    function(req, res, next) {
        console.log(req.headers);
        console.log("called login handler: " + req.url);
        var parsedUrl = url.parse(req.url, true);
        var i;
        var relyingParty = new openid.RelyingParty(
            config.host + "/verify",
            config.host + "/",
          false,
            false,
            []);

        console.log(parsedUrl);
        if(parsedUrl.pathname === "/authenticate") {
             relyingParty.authenticate(parsedUrl.query['openid-identifier'],
                 false,
                 function(error, authUrl) {
                     if (error) {
                         res.writeHead(200);
                         res.end('Authentication failed: ' + error.message);
                         return;
                     }
                     if (!authUrl) {
                         res.writeHead(200);
                         res.end('Authentication failed');
                         return;
                     }

                     res.writeHead(302, { Location: authUrl });
                     res.end();
                 });
             return;
        }

        console.log(parsedUrl.pathname);
        if (nonLoginPaths[parsedUrl.pathname] === true) {
            return next();
        }
        for (i = 0; i < nonLoginPatterns.length; i++) {
            if (parsedUrl.pathname.match(nonLoginPatterns[i]) !== null) {
                return next();
            }
        }
        if (parsedUrl.pathname === "/verify") {
            console.log("Verify called");
            var result = openid.verifyAssertion(req, function(error, result) {
                res.writeHead(200);

                if (error || !result.authenticated) {
                    res.end("Auth failed");;
                    return;
                }
                res.end("Success");
                return;
            });
            return;
        }

        res.writeHead(302, { Location: config[env] + "/login" });
        res.end();
};
<|endoftext|>