<commit_before>
var request = require('request'),
  app = require('../../server');

app.get('/price/kronan', function(req, res){

  var data = req.query;
  if(!data.barcode) {
    return res.json(400, {error: 'You must supply a barcode parameter!'})
  }

  request.get({
    url: 'http://appservice.kronan.is/KrAppVerdPerVoruJSON.ashx?BarcodeOrItem=' + data.barcode
    }, function(err, response, body) {
      if(err || response.statusCode !== 200)
        return res.json(500,{error:'The Krónan price api is down or refuses to respond'});

      var obj;
      try{
        obj = JSON.parse(body);
      }catch(error){
        return res.json(500,{error:'Something is wrong with the data provided from the data source'});
      }

      return res.json({ results: [obj] });
    }
  );
});
<commit_msg>allowed /price/kronan/:barcode to be sent in without querystring<commit_after>
var request = require('request'),
  app = require('../../server');

app.get('/price/kronan/:barcode?', function(req, res){

  var barcode = req.query.barcode || req.params.barcode;

  if(!barcode) {
    return res.json(400, {error: 'You must supply a barcode parameter!'})
  }

  request.get({
    url: 'http://appservice.kronan.is/KrAppVerdPerVoruJSON.ashx?BarcodeOrItem=' + data.barcode
    }, function(err, response, body) {
      if(err || response.statusCode !== 200)
        return res.json(500,{error:'The Krónan price api is down or refuses to respond'});

      var obj;
      try{
        obj = JSON.parse(body);
      }catch(error){
        return res.json(500,{error:'Something is wrong with the data provided from the data source'});
      }

      return res.json({ results: [obj] });
    }
  );
});
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose');
var db = require('../config/db');
var helper = require('../config/helper');

var queue = db.model('Queue', mongoose.Schema({
	id: { type: String, index: {unique: true, dropDups: true} },
	url: String,
	seen: { type: Boolean, default: false },
	parent: { type: String, default: '' },
	created: { type: Date, default: Date.now }
}));

queue.addUrl = function(url, parent) {
	return new this({
		id: helper.getUrlId(url),
		url: url,
		seen: 0,
		parent: helper.getUrlId(parent)
	}).save();
}

queue.findById = function(urlId) {
	return this.find({id: urlId});
}

queue.findByParent = function(parentUrl) {
	if (!helper.isUrlId(parentUrl)) {
		parentUrl = helper.getUrlId(parentUrl);
	}

	return this.find({parent: parentUrl});
}

queue.findByUrl = function(name, cb) {
	return this.find({ url: new RegExp(name, 'i') }, cb);
}

queue.findId = function(id, cb) {
	return this.find({ id: id }, cb);
}

queue.dequeue = function() {
	return this.findOne({seen: false});
}

queue.queue = function(url, parent) {
	return this.addUrl(url, parent);
}

module.exports = queue;<commit_msg>Add model<commit_after>'use strict';

var mongoose = require('mongoose');
var db = require('../config/db');
var helper = require('../config/helper');

var QueueScheme = mongoose.Schema({
	id: { type: String, index: {unique: true, dropDups: true} },
	url: String,
	seen: { type: Boolean, default: false },
	parent: { type: String, default: '' },
	created: { type: Date, default: Date.now }
});

QueueScheme.statics.addUrl = function(url, parent) {
	return new this({
		id: helper.getUrlId(url),
		url: url,
		seen: 0,
		parent: helper.getUrlId(parent)
	}).save();
}

QueueScheme.statics.findById = function(urlId) {
	return this.find({id: urlId});
}

QueueScheme.statics.findByParent = function(parentUrl) {
	if (!helper.isUrlId(parentUrl)) {
		parentUrl = helper.getUrlId(parentUrl);
	}

	return this.find({parent: parentUrl});
}

QueueScheme.statics.findByUrl = function(name, cb) {
	return this.find({ url: new RegExp(name, 'i') }, cb);
}

QueueScheme.statics.findId = function(id, cb) {
	return this.find({ id: id }, cb);
}

QueueScheme.statics.dequeue = function() {
	var url = '';
	return this.findOne({seen: false}, function(err, link) {
		if (!link) return false;

		link.seen = true;
		link.save();

		url = link.url;
	});

	return url;
}

QueueScheme.statics.queue = function(url, parent) {
	return this.addUrl(url, parent);
}

var queue = db.model('Queue', QueueScheme);

module.exports = queue;<|endoftext|>


<commit_before>//This stores the current date object:
var today = null;
function updateTime() {
    //Update today:
    today = new Date();
    //Insert the local time string into #curTime:
    $("#curTime").text(today.toLocaleTimeString("en-US"));
}

function getData() {
    //When passed into .toLocaleTimeString() with "en-US", this will yield a time with only the hour, minute, and AM/PM:
    var timeOptions = {
        "hour": "numeric",
        "minute": "numeric"
    };
    //Set the sunrise, sunset data for MHS's location:
    $.getJSON("http://api.sunrise-sunset.org/json", {lat: 43.200710, lng: -70.797379, formatted: 0}, function(result) {
        //Parse sunrise datestring and insert the time into #sunrise:
        var sunriseDate = new Date(result.results.sunrise);
        $('#sunrise').text(sunriseDate.toLocaleTimeString("en-US", timeOptions));
        //Do the same thing for the sunset:
        var sunsetDate = new Date(result.results.sunset);
        $('#sunset').text(sunsetDate.toLocaleTimeString("en-US", timeOptions));

        //Now that the sunrise and sunset has been loaded, adjust the iframe:
        adjustFrame();
        //Also, resize the frame whenever the window is resized:
        window.addEventListener("resize", adjustFrame);
    });
    //Set the moon phase data for MHS's location:
    $.getJSON("http://api.usno.navy.mil/rstt/oneday", {date: today.toLocaleDateString("en-US"), coords: "43.2007N,70.7974W"}, function(result) {
        //If curphase is specified, then put it in #moonPhase:
        if (result.hasOwnProperty("curphase")) $("#moonPhase").text(result.curphase);
        //Otherwise, use closestphase.phase:
        else $("#moonPhase").text(result.closestphase.phase);
    });

    //This is old code which we might need to bring back later:
    /*$.get("http://localhost:8080", function(result) {
        //Set the moon phase status to whatever the local server gives us back:
        $('#moonPhase').text(result);
    });*/
}

function adjustFrame() {
    //This stores what will be the top attribute of the iframe:
    var getOffset = 0;
    //Get the elements which we want to above above the iframe:
    var aboveFrameElems = $(".above-frame");
    for (var i = 0; i < aboveFrameElems.length; i++) {
        //Get the current element:
        var curElem = aboveFrameElems.get(i);
        //Get its bottom:
        //Remember to add window.scrollY since getBoundingClientRect() is relative to the window, not the document:
        var curElemBottom = curElem.getBoundingClientRect().bottom+window.scrollY;
        //Make getOffset the maximum of all of the bottoms:
        getOffset = Math.max(getOffset, curElemBottom);
    }
    $("#frame").css("top", getOffset+"px")

    //This is done so that it goes after the sunrise/sunset blocks, but can be next to the moon phase block.
}

//Set the time:
updateTime();
//Keep updating the time two times every second:
setInterval(updateTime, 500);
//Get the API data:
getData();<commit_msg>Revert "Made moon_phase.py useless"<commit_after>function startTime() {
    //Insert the local time string into #curTime:
    var today = new Date();
    $("#curTime").text(today.toLocaleTimeString("en-US"));
}

function getData() {
    //When passed into .toLocaleTimeString() with "en-US", this will yield a time with only the hour, minute, and AM/PM:
    var timeOptions = {
        "hour": "numeric",
        "minute": "numeric"
    };
    //Set the sunrise, sunset data for MHS's location:
    $.getJSON("http://api.sunrise-sunset.org/json", {lat: 43.200710, lng: -70.797379, formatted: 0}, function(result) {
        //Parse sunrise datestring and insert the time into #sunrise:
        var sunriseDate = new Date(result.results.sunrise);
        $('#sunrise').text(sunriseDate.toLocaleTimeString("en-US", timeOptions));
        //Do the same thing for the sunset:
        var sunsetDate = new Date(result.results.sunset);
        $('#sunset').text(sunsetDate.toLocaleTimeString("en-US", timeOptions));

        //Now that the sunrise and sunset has been loaded, adjust the iframe:
        adjustFrame();
        //Also, resize the frame whenever the window is resized:
        window.addEventListener("resize", adjustFrame);
    });
    $.get("http://localhost:8080", function(result) {
        //Set the moon phase status to whatever the local server gives us back:
        $('#moonPhase').text(result);
    });
}

function adjustFrame() {
    //This stores what will be the top attribute of the iframe:
    var getOffset = 0;
    //Get the elements which we want to above above the iframe:
    var aboveFrameElems = $(".above-frame");
    for (var i = 0; i < aboveFrameElems.length; i++) {
        //Get the current element:
        var curElem = aboveFrameElems.get(i);
        //Get its bottom:
        //Remember to add window.scrollY since getBoundingClientRect() is relative to the window, not the document:
        var curElemBottom = curElem.getBoundingClientRect().bottom+window.scrollY;
        //Make getOffset the maximum of all of the bottoms:
        getOffset = Math.max(getOffset, curElemBottom);
    }
    $("#frame").css("top", getOffset+"px")

    //This is done so that it goes after the sunrise/sunset blocks, but can be next to the moon phase block.
}

//Set the time:
startTime();
//Keep updating the time two times every second:
setInterval(startTime, 500);
//Get the API data:
getData();<|endoftext|>


<commit_before>'use strict'
const props = require('../render/static').property
const getParent = require('../render/dom/parent')
const vstamp = require('vigour-stamp')

exports.types = {
  group: {
    type: 'property',
    isGroup: true,
    properties: {
      render (render) {
        this.define({ groupRender: { val: render } })
      }
    },
    define: {
      render: {
        val: {
          static (target, pnode) {
            // static can also have mixed static/state things
            if (!target.isStatic) {
              throw new Error('trying static but is not!')
            }
            // this is problem of course...
            const store = {}

            const parsed = '_' + target.key + 'StaticParsed'
            if (pnode) {
              props(target, pnode, store)
              pnode[parsed] = true
            }

            target.groupRender.static(target, pnode, store)
          },
          state (target, state, type, stamp, subs, tree, id, pid) {
            let storeId = pid + target.key
            const store = tree._[storeId] || (tree._[storeId] = {})
            const pnode = getParent(type, stamp, subs, tree, pid)
            const parsed = '_' + target.key + 'StaticParsed'
            if (pnode) {
              if (!pnode[parsed]) {
                props(target, pnode, store)
                pnode[parsed] = true
              }
              if (!('stamp' in store)) {
                store.stamp = stamp
                vstamp.on(stamp, () => {
                  delete store.stamp
                  target.groupRender.state(target, state, type, stamp, subs, tree, id, pid, store)
                })
              }
            }
          }
        }
      }
    },
    child: {
      define: {
        getStore (tree, id) {
          if (this.$ !== true) {
            tree = tree._p
            while (!tree.$ && tree._p) {
              tree = tree._p
            }
          }
          const _ = tree._ || (tree._ = {})
          const store = _[id] || (_[id] = {})
          return store
        }
      },
      render: {
        static (target, node, store) {
          store[target.key] = target.compute()
        },
        state (target, state, type, stamp, subs, tree, id, pid) {
          target.getStore(
            tree, pid + target.cParent().key
          )[target.key] = target.compute(state)
        }
      }
    }
  }
}
<commit_msg>removed error msg in group/static<commit_after>'use strict'
const props = require('../render/static').property
const getParent = require('../render/dom/parent')
const vstamp = require('vigour-stamp')

exports.types = {
  group: {
    type: 'property',
    isGroup: true,
    properties: {
      render (render) {
        this.define({ groupRender: { val: render } })
      }
    },
    define: {
      render: {
        val: {
          static (target, pnode) {
            const store = {}
            const parsed = '_' + target.key + 'StaticParsed'
            if (pnode) {
              props(target, pnode, store)
              pnode[parsed] = true
            }
            target.groupRender.static(target, pnode, store)
          },
          state (target, state, type, stamp, subs, tree, id, pid) {
            let storeId = pid + target.key
            const store = tree._[storeId] || (tree._[storeId] = {})
            const pnode = getParent(type, stamp, subs, tree, pid)
            const parsed = '_' + target.key + 'StaticParsed'
            if (pnode) {
              if (!pnode[parsed]) {
                props(target, pnode, store)
                pnode[parsed] = true
              }
              if (!('stamp' in store)) {
                store.stamp = stamp
                vstamp.on(stamp, () => {
                  delete store.stamp
                  target.groupRender.state(target, state, type, stamp, subs, tree, id, pid, store)
                })
              }
            }
          }
        }
      }
    },
    child: {
      define: {
        getStore (tree, id) {
          if (this.$ !== true) {
            tree = tree._p
            while (!tree.$ && tree._p) {
              tree = tree._p
            }
          }
          const _ = tree._ || (tree._ = {})
          const store = _[id] || (_[id] = {})
          return store
        }
      },
      render: {
        static (target, node, store) {
          store[target.key] = target.compute()
        },
        state (target, state, type, stamp, subs, tree, id, pid) {
          target.getStore(
            tree, pid + target.cParent().key
          )[target.key] = target.compute(state)
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    var itemview = require('./itemview');
    var view = require('./view');
    var layouts = require('./layoutviews');
    var collectionview = require('./collections-views');
    var collectionlayout = require('./collections-layouts');
    var utils = require('./utils');
    var regions = require('./region');

    var views = {
        View: view.FamousView,

        layouts: {
            LayoutView: layouts.FamousLayoutView
        },

        items: {
            ItemView: itemview.FamousItemView
        },

        collections: {
            CollectionView: collectionview.FamousCollectionView,
            horizontalLayout: collectionlayout.horizontalLayout,
            verticalLayout: collectionlayout.verticalLayout
        }
    };

    // shortcuts
    exports.View = view.FamousView;
    exports.ItemView = itemview.FamousItemView;
    exports.LayoutView = layouts.FamousLayoutView;
    exports.CollectionView = collectionview.FamousCollectionView;
    exports.Region = regions.FamousRegion;

    // fully qualified
    exports.utils = utils;
    exports.views  = views;
});
<commit_msg>bar comment<commit_after>define(function (require, exports, module) {
    var itemview = require('./itemview');
    var view = require('./view');
    var layouts = require('./layoutviews');
    var collectionview = require('./collections-views');
    var collectionlayout = require('./collections-layouts');
    var utils = require('./utils');
    var regions = require('./region');

    var views = {
        View: view.FamousView,

        layouts: {
            LayoutView: layouts.FamousLayoutView
        },

        items: {
            ItemView: itemview.FamousItemView
        },

        collections: {
            CollectionView: collectionview.FamousCollectionView,
            horizontalLayout: collectionlayout.horizontalLayout,
            verticalLayout: collectionlayout.verticalLayout
        }
    };

    // shortcuts
    // BAR
    exports.View = view.FamousView;
    exports.ItemView = itemview.FamousItemView;
    exports.LayoutView = layouts.FamousLayoutView;
    exports.CollectionView = collectionview.FamousCollectionView;
    exports.Region = regions.FamousRegion;

    // fully qualified
    exports.utils = utils;
    exports.views  = views;
});
<|endoftext|>


<commit_before>/**************************************************************************************
 * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere *
 *                                                                                *
 * All rights reserved.                                                               *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without modification,   *
 * are permitted provided that the following conditions are met:                      *
 * 1. Redistributions of source code must retain the above copyright notice, this     *
 *    list of conditions and the following disclaimer.                                *
 * 2. Redistributions in binary form must reproduce the above copyright notice,       *
 *    this list of conditions and the following disclaimer in the documentation       *
 *    and/or other materials provided with the distribution.                          *
 * 3. Neither the name of the copyright holder nor the names of its contributors      *
 *    may be used to endorse or promote products derived from this software           *
 *    without specific prior written permission.                                      *
 *                                                                                *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND    *
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED      *
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE             *
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR   *
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES     *
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;       *
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON     *
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT            *
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS      *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                       *
 **************************************************************************************/

define(function (require) {
    'use strict';

    var resultParser = require('./resultParser');

    return function (options) {
        return function () {
            // A bit of a workaround, getting the correct ids to be shown
            var id = options.data.key.id;
            if (options.data.fields.studyid != null && options.data.fields.studyid.values[options.defaultLang].original.startsWith("FSD")){ id = options.data.fields.studyid.values[options.defaultLang].original };
            if (options.data.fields.binderid != null && options.data.fields.binderid.values[options.defaultLang].original.startsWith("FSD")){ id = options.data.fields.binderid.values[options.defaultLang].original };
            if (options.data.fields.publicationid != null){ id = options.data.fields.publicationid.values[options.defaultLang].original };
            var operationType = options.data.state.uiState === 'DRAFT' ? 'draft' : 'logical';
            require('./modal')($.extend(true, require('./optionsBase')(), {
                title: MetkaJS.L10N.get('confirmation.remove.revision.title'),
                // TODO: simpler/unified way to supplement localization keys/texts
                body: MetkaJS.L10N.get('confirmation.remove.revision.{operationType}.text'.supplant({
                    operationType: operationType
                })).supplant({id: id, no: options.data.key.no}).supplant({
                    target: MetkaJS.L10N.get('confirmation.remove.revision.{operationType}.data.{type}'.supplant({
                        operationType: operationType,
                        type: options.data.configuration.type
                    }))
                }),
                buttons: [{
                    type: 'YES',
                    create: function () {
                        this
                            .click(function () {
                                require('./server')('remove', {
                                    data: JSON.stringify(options.data.key),
                                    success: function (response) {
                                        var success = $.extend({
                                            SUCCESS_LOGICAL: function () {
                                                require('./assignUrl')('view');
                                            },
                                            SUCCESS_DRAFT: function () {
                                                require('./assignUrl')('view', {no: ''});
                                            },
                                            SUCCESS_REVISIONABLE: function () {
                                                require('./assignUrl')('searchPage');
                                            }
                                        }, options.success);

                                        success = success[resultParser(response.result).getResult()] || function (response) {
                                            require('./resultViewer')(response.result, "remove");
                                        };

                                        success(response);
                                    }
                                });
                            });
                    }
                }, {
                    type: 'NO'
                }]
            }));
        };
    };
});
<commit_msg>Korjaus hyväksymättömien revisionien poistoon<commit_after>/**************************************************************************************
 * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere *
 *                                                                                *
 * All rights reserved.                                                               *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without modification,   *
 * are permitted provided that the following conditions are met:                      *
 * 1. Redistributions of source code must retain the above copyright notice, this     *
 *    list of conditions and the following disclaimer.                                *
 * 2. Redistributions in binary form must reproduce the above copyright notice,       *
 *    this list of conditions and the following disclaimer in the documentation       *
 *    and/or other materials provided with the distribution.                          *
 * 3. Neither the name of the copyright holder nor the names of its contributors      *
 *    may be used to endorse or promote products derived from this software           *
 *    without specific prior written permission.                                      *
 *                                                                                *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND    *
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED      *
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE             *
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR   *
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES     *
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;       *
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON     *
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT            *
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS      *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                       *
 **************************************************************************************/

define(function (require) {
    'use strict';

    var resultParser = require('./resultParser');

    return function (options) {
        return function () {
            // A bit of a workaround, getting the correct ids to be shown
            var id = options.data.key.id;
            switch (options.data.configuration.type) {
                case "STUDY":
                    id = options.data.fields.studyid.values[options.defaultLang].original || options.data.fields.studyid.values[options.defaultLang].current
                    break;
                case "BINDER_PAGE":
                    id = options.data.fields.binderid.values[options.defaultLang].original || options.data.fields.binderid.values[options.defaultLang].current
                    break;
                case "PUBLICATION":
                    id = options.data.fields.publicationid.values[options.defaultLang].original || options.data.fields.publicationid.values[options.defaultLang].current;
                    break;
            }
            var operationType = options.data.state.uiState === 'DRAFT' ? 'draft' : 'logical';
            require('./modal')($.extend(true, require('./optionsBase')(), {
                title: MetkaJS.L10N.get('confirmation.remove.revision.title'),
                // TODO: simpler/unified way to supplement localization keys/texts
                body: MetkaJS.L10N.get('confirmation.remove.revision.{operationType}.text'.supplant({
                    operationType: operationType
                })).supplant({id: id, no: options.data.key.no}).supplant({
                    target: MetkaJS.L10N.get('confirmation.remove.revision.{operationType}.data.{type}'.supplant({
                        operationType: operationType,
                        type: options.data.configuration.type
                    }))
                }),
                buttons: [{
                    type: 'YES',
                    create: function () {
                        this
                            .click(function () {
                                require('./server')('remove', {
                                    data: JSON.stringify(options.data.key),
                                    success: function (response) {
                                        var success = $.extend({
                                            SUCCESS_LOGICAL: function () {
                                                require('./assignUrl')('view');
                                            },
                                            SUCCESS_DRAFT: function () {
                                                require('./assignUrl')('view', {no: ''});
                                            },
                                            SUCCESS_REVISIONABLE: function () {
                                                require('./assignUrl')('searchPage');
                                            }
                                        }, options.success);

                                        success = success[resultParser(response.result).getResult()] || function (response) {
                                            require('./resultViewer')(response.result, "remove");
                                        };

                                        success(response);
                                    }
                                });
                            });
                    }
                }, {
                    type: 'NO'
                }]
            }));
        };
    };
});
<|endoftext|>


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

    angular
        .module('shinyDeploy')
        .controller('DeploymentsController', DeploymentsController);

    DeploymentsController.$inject = ['deploymentsService', 'alertsService'];

    function DeploymentsController(deploymentsService, alertsService) {
        /*jshint validthis: true */
        var vm = this;

        vm.deployments = null;

        vm.getDeployments = getDeployments;
        vm.deleteDeployment = deleteDeployment;

        init();

        /**
         * Loads data required for deployments list view.
         */
        function init() {
            var promise = deploymentsService.getDeployments();
            promise.then(function(data) {
                vm.deployments = data;
            }, function(reason) {
                console.log('Error fetching deployments: ' + reason);
            });
        }

        /**
         * Returns list of deployments.
         *
         * @returns {null|Array}
         */
        function getDeployments() {
            return vm.deployments;
        }

        /**
         * Removes a deployment.
         *
         * @param {number} deploymentId
         */
        function deleteDeployment(deploymentId) {
            deploymentsService.deleteDeployment(deploymentId).then(function (data) {
                for (var i = vm.deployments.length - 1; i >= 0; i--) {
                    if (vm.deployments[i].id === deploymentId) {
                        vm.deployments.splice(i, 1);
                        break;
                    }
                }
                alertsService.pushAlert('Deployment successfully deleted.', 'success');
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }
    }
})();

(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsAddController', DeploymentsAddController);

    DeploymentsAddController.$inject = ['$location', 'deploymentsService', 'alertsService'];

    function DeploymentsAddController($location, deploymentsService, alertsService) {
        /*jshint validthis: true */
        var vm = this;

        // Properties
        vm.isAdd = true;
        vm.deployment = {};
        vm.servers = {};
        vm.repositories = {};
        vm.branches = {};
        vm.task = {};
        vm.taskFormMode = 'add';

        // Methods
        vm.addDeployment = addDeployment;
        vm.refreshBranches = refreshBranches;
        vm.showAddTask = showAddTask;
        vm.showEditTask = showEditTask;
        vm.addTask = addTask;
        vm.editTask = editTask;
        vm.deleteTask = deleteTask;

        // Init
        init();

        /**
         * Loads data required for add deployment form.
         */
        function init() {
            // load servers:
            deploymentsService.getServers().then(function (data) {
                vm.servers = data;
            }, function(reason) {
                console.log('Error fetching servers: ' + reason);
            });

            // load repositories:
            deploymentsService.getRepositories().then(function (data) {
                vm.repositories = data;
            }, function(reason) {
                console.log('Error fetching repositories: ' + reason);
            });
        }

        /**
         * Requests add-deployment action on project backend.
         */
        function addDeployment() {
            vm.deployment.server_id = vm.deployment.server.id;
            vm.deployment.repository_id = vm.deployment.repository.id;
            vm.deployment.branch = vm.deployment.branchObj.id;
            deploymentsService.addDeployment(vm.deployment).then(function(data) {
                $location.path('/deployments');
                alertsService.queueAlert('Deployment successfully added.', 'success');
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Refresh branches list if repository is changed.
         */
        function refreshBranches() {
            deploymentsService.getRepositoryBranches(vm.deployment.repository.id).then(function (data) {
                vm.branches = data;
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Shows form to add new task.
         */
        function showAddTask() {
            vm.taskFormMode = 'add';
            vm.task = {};
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Shows form to edit a task.
         *
         * @param {Number} index
         */
        function showEditTask(index) {
            vm.task = vm.deployment.tasks[index];
            vm.taskFormMode = 'edit';
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Adds new task.
         */
        function addTask() {
            if (!vm.deployment.hasOwnProperty('tasks')) {
                vm.deployment.tasks = [];
            }
            vm.deployment.tasks.push(vm.task);
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Updates an existing task.
         */
        function editTask() {
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Deletes a task.
         *
         * @param {Number} index
         */
        function deleteTask(index) {
            vm.deployment.tasks.splice(index, 1);
        }
    }
})();

(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsEditController', DeploymentsEditController);

    DeploymentsEditController.$inject = ['$location', '$routeParams', 'deploymentsService', 'alertsService'];

    function DeploymentsEditController($location, $routeParams, deploymentsService, alertsService) {
        /*jshint validthis: true */
        var vm = this;

        // Properties
        vm.isEdit = true;
        vm.servers = {};
        vm.repositories = {};
        vm.branches = {};
        vm.deployment = {};
        vm.task = {};
        vm.taskFormMode = 'add';

        // Methods
        vm.updateDeployment = updateDeployment;
        vm.refreshBranches = refreshBranches;
        vm.showAddTask = showAddTask;
        vm.showEditTask = showEditTask;
        vm.addTask = addTask;
        vm.editTask = editTask;
        vm.deleteTask = deleteTask;

        // Init
        init();

        /**
         * Loads data required for edit deployment form.
         */
        function init() {
            // load servers:
            deploymentsService.getServers().then(function (data) {
                vm.servers = data;
            }, function(reason) {
                console.log('Error fetching servers: ' + reason);
            });

            // load repositories:
            deploymentsService.getRepositories().then(function (data) {
                vm.repositories = data;
            }, function(reason) {
                console.log('Error fetching repositories: ' + reason);
            });

            // load deployment:
            var deploymentId = ($routeParams.deploymentId) ? parseInt($routeParams.deploymentId) : 0;
            deploymentsService.getDeploymentData(deploymentId).then(function(data) {
                vm.deployment = data;
                vm.refreshBranches();
            }, function(reason) {
                $location.path('/deployments');
            });
        }

        /**
         * Updates deployment data.
         */
        function updateDeployment() {
            vm.deployment.server_id = vm.deployment.server.id;
            vm.deployment.repository_id = vm.deployment.repository.id;
            vm.deployment.branch = vm.deployment.branchObj.id;
            deploymentsService.updateDeployment(vm.deployment).then(function (data) {
                alertsService.pushAlert('Deployment successfully updated.', 'success');
            }, function (reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Refresh branches list if repository is changed.
         */
        function refreshBranches() {
            deploymentsService.getRepositoryBranches(vm.deployment.repository.id).then(function (data) {
                vm.branches = data;
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Shows form to add new task.
         */
        function showAddTask() {
            vm.taskFormMode = 'add';
            vm.task = {};
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Shows form to edit a task.
         *
         * @param {Number} index
         */
        function showEditTask(index) {
            vm.task = vm.deployment.tasks[index];
            vm.taskFormMode = 'edit';
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Adds new task.
         */
        function addTask() {
            if (!vm.deployment.hasOwnProperty('tasks')) {
                vm.deployment.tasks = [];
            }
            vm.deployment.tasks.push(vm.task);
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Updates an existing task.
         */
        function editTask() {
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Deletes a task.
         *
         * @param {Number} index
         */
        function deleteTask(index) {
            vm.deployment.tasks.splice(index, 1);
        }
    }
})();

(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsRunController', DeploymentsRunController);

    DeploymentsRunController.$inject = [
        '$location',
        '$routeParams',
        '$scope',
        '$sce',
        'deploymentsService',
        'serversService',
        'repositoriesService',
        'ws'
    ];

    function DeploymentsRunController(
        $location,
        $routeParams,
        $scope,
        $sce,
        deploymentsService,
        serversService,
        repositoriesService,
        ws
    ) {
        /*jshint validthis: true */
        var vm = this;

        // Properties
        vm.deployment = {};
        vm.changedFiles = {};
        vm.diff = '';
        vm.remoteRevision = '';
        vm.localRevision = '';

        // Methods
        vm.triggerDeploy = triggerDeploy;
        vm.triggerGetChangedFiles = triggerGetChangedFiles;
        vm.displayChangedFiles = displayChangedFiles;
        vm.triggerShowDiff = triggerShowDiff;
        vm.listenShowDiff = listenShowDiff;

        // Init
        init();
        vm.displayChangedFiles();
        vm.listenShowDiff();

        /**
         * Loads data required for run deployment view.
         */
        function init() {
            // load deployment:
            var deploymentId = ($routeParams.deploymentId) ? parseInt($routeParams.deploymentId) : 0;
            deploymentsService.getDeploymentData(deploymentId).then(function (data) {
                vm.deployment = data;
                resolveRelations();
                getLocalRevision();
                getRemoteRevision();

            }, function(reason) {
                $location.path('/deployments');
            });
        }

        /**
         * Start new deployment job.
         */
        function triggerDeploy() {
            vm.changedFiles = {};
            vm.diff = '';
            deploymentsService.triggerDeployAction(vm.deployment.id);
        }

        /**
         * Fetch list of changed files.
         */
        function triggerGetChangedFiles() {
            vm.changedFiles = {};
            vm.diff = '';
            deploymentsService.triggerGetChangedFiles(vm.deployment.id);
        }

        function displayChangedFiles() {
            ws.addListener('updateChangedFiles', function(data) {
                $scope.$apply(function() {
                    vm.changedFiles = data.changedFiles;
                });
            });
        }

        /**
         * Fetches data not directly stored within deployments table and stores it into deployment object.
         */
        function resolveRelations() {
            serversService.getServerData(vm.deployment.server_id).then(function(server) {
                vm.deployment.server = server;
            });
            repositoriesService.getRepositoryData(vm.deployment.repository_id).then(function(repository) {
                vm.deployment.repository = repository;
            });
        }

        /**
         * Triggers request to show file diff.
         *
         * @param {number} fileKey
         */
        function triggerShowDiff(fileKey) {
            var params = {
                repositoryId: vm.deployment.repository_id,
                localRevision: vm.localRevision,
                remoteRevision: vm.remoteRevision,
                file: vm.changedFiles[fileKey].file
            };
            deploymentsService.triggerGetFileDiff(params);
        }

        /**
         * Listens for showDiff events hand handles them.
         */
        function listenShowDiff() {
            ws.addListener('showDiff', function(data) {
                $scope.$apply(function() {
                    vm.diff = $sce.trustAsHtml(Diff2Html.getPrettyHtmlFromDiff(data.diff));
                });
            });
        }

        /**
         * Fetches current revision of remote repository.
         *
         */
        function getRemoteRevision() {
            deploymentsService.getRemoteRevision(vm.deployment.id).then(function(revision) {
                vm.remoteRevision = revision;
            });
        }

        /**
         * Fetches local repository revision.
         */
        function getLocalRevision() {
            deploymentsService.getLocalRevision(vm.deployment.id).then(function(revision) {
                vm.localRevision = revision;
            });
        }
    }
})();<commit_msg>Check diff response before triggering diff2html<commit_after>(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsController', DeploymentsController);

    DeploymentsController.$inject = ['deploymentsService', 'alertsService'];

    function DeploymentsController(deploymentsService, alertsService) {
        /*jshint validthis: true */
        var vm = this;

        vm.deployments = null;

        vm.getDeployments = getDeployments;
        vm.deleteDeployment = deleteDeployment;

        init();

        /**
         * Loads data required for deployments list view.
         */
        function init() {
            var promise = deploymentsService.getDeployments();
            promise.then(function(data) {
                vm.deployments = data;
            }, function(reason) {
                console.log('Error fetching deployments: ' + reason);
            });
        }

        /**
         * Returns list of deployments.
         *
         * @returns {null|Array}
         */
        function getDeployments() {
            return vm.deployments;
        }

        /**
         * Removes a deployment.
         *
         * @param {number} deploymentId
         */
        function deleteDeployment(deploymentId) {
            deploymentsService.deleteDeployment(deploymentId).then(function (data) {
                for (var i = vm.deployments.length - 1; i >= 0; i--) {
                    if (vm.deployments[i].id === deploymentId) {
                        vm.deployments.splice(i, 1);
                        break;
                    }
                }
                alertsService.pushAlert('Deployment successfully deleted.', 'success');
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }
    }
})();

(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsAddController', DeploymentsAddController);

    DeploymentsAddController.$inject = ['$location', 'deploymentsService', 'alertsService'];

    function DeploymentsAddController($location, deploymentsService, alertsService) {
        /*jshint validthis: true */
        var vm = this;

        // Properties
        vm.isAdd = true;
        vm.deployment = {};
        vm.servers = {};
        vm.repositories = {};
        vm.branches = {};
        vm.task = {};
        vm.taskFormMode = 'add';

        // Methods
        vm.addDeployment = addDeployment;
        vm.refreshBranches = refreshBranches;
        vm.showAddTask = showAddTask;
        vm.showEditTask = showEditTask;
        vm.addTask = addTask;
        vm.editTask = editTask;
        vm.deleteTask = deleteTask;

        // Init
        init();

        /**
         * Loads data required for add deployment form.
         */
        function init() {
            // load servers:
            deploymentsService.getServers().then(function (data) {
                vm.servers = data;
            }, function(reason) {
                console.log('Error fetching servers: ' + reason);
            });

            // load repositories:
            deploymentsService.getRepositories().then(function (data) {
                vm.repositories = data;
            }, function(reason) {
                console.log('Error fetching repositories: ' + reason);
            });
        }

        /**
         * Requests add-deployment action on project backend.
         */
        function addDeployment() {
            vm.deployment.server_id = vm.deployment.server.id;
            vm.deployment.repository_id = vm.deployment.repository.id;
            vm.deployment.branch = vm.deployment.branchObj.id;
            deploymentsService.addDeployment(vm.deployment).then(function(data) {
                $location.path('/deployments');
                alertsService.queueAlert('Deployment successfully added.', 'success');
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Refresh branches list if repository is changed.
         */
        function refreshBranches() {
            deploymentsService.getRepositoryBranches(vm.deployment.repository.id).then(function (data) {
                vm.branches = data;
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Shows form to add new task.
         */
        function showAddTask() {
            vm.taskFormMode = 'add';
            vm.task = {};
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Shows form to edit a task.
         *
         * @param {Number} index
         */
        function showEditTask(index) {
            vm.task = vm.deployment.tasks[index];
            vm.taskFormMode = 'edit';
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Adds new task.
         */
        function addTask() {
            if (!vm.deployment.hasOwnProperty('tasks')) {
                vm.deployment.tasks = [];
            }
            vm.deployment.tasks.push(vm.task);
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Updates an existing task.
         */
        function editTask() {
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Deletes a task.
         *
         * @param {Number} index
         */
        function deleteTask(index) {
            vm.deployment.tasks.splice(index, 1);
        }
    }
})();

(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsEditController', DeploymentsEditController);

    DeploymentsEditController.$inject = ['$location', '$routeParams', 'deploymentsService', 'alertsService'];

    function DeploymentsEditController($location, $routeParams, deploymentsService, alertsService) {
        /*jshint validthis: true */
        var vm = this;

        // Properties
        vm.isEdit = true;
        vm.servers = {};
        vm.repositories = {};
        vm.branches = {};
        vm.deployment = {};
        vm.task = {};
        vm.taskFormMode = 'add';

        // Methods
        vm.updateDeployment = updateDeployment;
        vm.refreshBranches = refreshBranches;
        vm.showAddTask = showAddTask;
        vm.showEditTask = showEditTask;
        vm.addTask = addTask;
        vm.editTask = editTask;
        vm.deleteTask = deleteTask;

        // Init
        init();

        /**
         * Loads data required for edit deployment form.
         */
        function init() {
            // load servers:
            deploymentsService.getServers().then(function (data) {
                vm.servers = data;
            }, function(reason) {
                console.log('Error fetching servers: ' + reason);
            });

            // load repositories:
            deploymentsService.getRepositories().then(function (data) {
                vm.repositories = data;
            }, function(reason) {
                console.log('Error fetching repositories: ' + reason);
            });

            // load deployment:
            var deploymentId = ($routeParams.deploymentId) ? parseInt($routeParams.deploymentId) : 0;
            deploymentsService.getDeploymentData(deploymentId).then(function(data) {
                vm.deployment = data;
                vm.refreshBranches();
            }, function(reason) {
                $location.path('/deployments');
            });
        }

        /**
         * Updates deployment data.
         */
        function updateDeployment() {
            vm.deployment.server_id = vm.deployment.server.id;
            vm.deployment.repository_id = vm.deployment.repository.id;
            vm.deployment.branch = vm.deployment.branchObj.id;
            deploymentsService.updateDeployment(vm.deployment).then(function (data) {
                alertsService.pushAlert('Deployment successfully updated.', 'success');
            }, function (reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Refresh branches list if repository is changed.
         */
        function refreshBranches() {
            deploymentsService.getRepositoryBranches(vm.deployment.repository.id).then(function (data) {
                vm.branches = data;
            }, function(reason) {
                alertsService.pushAlert(reason, 'warning');
            });
        }

        /**
         * Shows form to add new task.
         */
        function showAddTask() {
            vm.taskFormMode = 'add';
            vm.task = {};
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Shows form to edit a task.
         *
         * @param {Number} index
         */
        function showEditTask(index) {
            vm.task = vm.deployment.tasks[index];
            vm.taskFormMode = 'edit';
            jQuery('#editTaskModal').modal('show');
        }

        /**
         * Adds new task.
         */
        function addTask() {
            if (!vm.deployment.hasOwnProperty('tasks')) {
                vm.deployment.tasks = [];
            }
            vm.deployment.tasks.push(vm.task);
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Updates an existing task.
         */
        function editTask() {
            vm.task = {};
            jQuery('#editTaskModal').modal('hide');
        }

        /**
         * Deletes a task.
         *
         * @param {Number} index
         */
        function deleteTask(index) {
            vm.deployment.tasks.splice(index, 1);
        }
    }
})();

(function () {
    "use strict";

    angular
        .module('shinyDeploy')
        .controller('DeploymentsRunController', DeploymentsRunController);

    DeploymentsRunController.$inject = [
        '$location',
        '$routeParams',
        '$scope',
        '$sce',
        'deploymentsService',
        'serversService',
        'repositoriesService',
        'ws'
    ];

    function DeploymentsRunController(
        $location,
        $routeParams,
        $scope,
        $sce,
        deploymentsService,
        serversService,
        repositoriesService,
        ws
    ) {
        /*jshint validthis: true */
        var vm = this;

        // Properties
        vm.deployment = {};
        vm.changedFiles = {};
        vm.diff = '';
        vm.remoteRevision = '';
        vm.localRevision = '';

        // Methods
        vm.triggerDeploy = triggerDeploy;
        vm.triggerGetChangedFiles = triggerGetChangedFiles;
        vm.displayChangedFiles = displayChangedFiles;
        vm.triggerShowDiff = triggerShowDiff;
        vm.listenShowDiff = listenShowDiff;

        // Init
        init();
        vm.displayChangedFiles();
        vm.listenShowDiff();

        /**
         * Loads data required for run deployment view.
         */
        function init() {
            // load deployment:
            var deploymentId = ($routeParams.deploymentId) ? parseInt($routeParams.deploymentId) : 0;
            deploymentsService.getDeploymentData(deploymentId).then(function (data) {
                vm.deployment = data;
                resolveRelations();
                getLocalRevision();
                getRemoteRevision();

            }, function(reason) {
                $location.path('/deployments');
            });
        }

        /**
         * Start new deployment job.
         */
        function triggerDeploy() {
            vm.changedFiles = {};
            vm.diff = '';
            deploymentsService.triggerDeployAction(vm.deployment.id);
        }

        /**
         * Fetch list of changed files.
         */
        function triggerGetChangedFiles() {
            vm.changedFiles = {};
            vm.diff = '';
            deploymentsService.triggerGetChangedFiles(vm.deployment.id);
        }

        function displayChangedFiles() {
            ws.addListener('updateChangedFiles', function(data) {
                $scope.$apply(function() {
                    vm.changedFiles = data.changedFiles;
                });
            });
        }

        /**
         * Fetches data not directly stored within deployments table and stores it into deployment object.
         */
        function resolveRelations() {
            serversService.getServerData(vm.deployment.server_id).then(function(server) {
                vm.deployment.server = server;
            });
            repositoriesService.getRepositoryData(vm.deployment.repository_id).then(function(repository) {
                vm.deployment.repository = repository;
            });
        }

        /**
         * Triggers request to show file diff.
         *
         * @param {number} fileKey
         */
        function triggerShowDiff(fileKey) {
            var params = {
                repositoryId: vm.deployment.repository_id,
                localRevision: vm.localRevision,
                remoteRevision: vm.remoteRevision,
                file: vm.changedFiles[fileKey].file
            };
            deploymentsService.triggerGetFileDiff(params);
        }

        /**
         * Listens for showDiff events hand handles them.
         */
        function listenShowDiff() {
            ws.addListener('showDiff', function(data) {
                if (!data.hasOwnProperty('diff')) {
                    return;
                }
                if (data.diff === null) {
                    return;
                }
                $scope.$apply(function() {
                    vm.diff = $sce.trustAsHtml(Diff2Html.getPrettyHtmlFromDiff(data.diff));
                });
            });
        }

        /**
         * Fetches current revision of remote repository.
         *
         */
        function getRemoteRevision() {
            deploymentsService.getRemoteRevision(vm.deployment.id).then(function(revision) {
                vm.remoteRevision = revision;
            });
        }

        /**
         * Fetches local repository revision.
         */
        function getLocalRevision() {
            deploymentsService.getLocalRevision(vm.deployment.id).then(function(revision) {
                vm.localRevision = revision;
            });
        }
    }
})();<|endoftext|>


<commit_before>// @flow weak

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Table, TableRow, TableRowColumn, TableBody } from 'material-ui/table';
import Slider from 'material-ui/Slider';
import Paper from 'material-ui/Paper';
import Surface from 'resonance/Surface';
import NodeGroup from 'resonance/NodeGroup';
import MarkdownElement from 'docs/src/components/MarkdownElement';
import { updateSortOrder, updateTopCount, makeGetSelectedData } from '../module';
import { VIEW, TRBL, AGES } from '../module/constants';
import Circle from './Circle';
import description from '../description.md';

const circleKeyAccessor = (d) => d.name;

export class Example extends Component {

  constructor(props) {
    super(props);

    (this:any).setShowTop = this.setShowTop.bind(this);
    (this:any).setDuration = this.setDuration.bind(this);
  }

  state = {
    duration: 750,
    showTop: this.props.showTop,
  }

  setShowTop(e, value) {
    this.setState({
      showTop: value,
    });
  }

  setDuration(e, value) {
    this.setState({
      duration: Math.floor(value * 10000),
    });
  }

  render() {
    const { sortKey, data, dispatch } = this.props;
    const { duration, showTop } = this.state;

    return (
      <Paper style={{ padding: 20 }}>

                <MarkdownElement text={description} />

Show Top {showTop} States:

                <Slider
                  min={5} max={25} step={1}
                  value={showTop}
                  onChange={this.setShowTop}
                  onDragStop={() => dispatch(updateTopCount(showTop))}
                />

Transition Duration: {(duration / 1000).toFixed(1)} Seconds

                <Slider
                  defaultValue={0.1}
                  onChange={this.setDuration}
                />

 dispatch(updateSortOrder(AGES[d]))}
                >
                  <TableBody deselectOnClickaway={false}>
                    {AGES.map((age) => {
                      return (
                        <TableRow
                          key={age}
                          selected={sortKey === age}
                        >
                          <TableRowColumn>{age}</TableRowColumn>
                        </TableRow>
                      );
                    })}
                  </TableBody>

                <Surface view={VIEW} trbl={TRBL}>
                  <NodeGroup
                    data={data}
                    duration={duration}
                    keyAccessor={circleKeyAccessor}
                    sortKey={sortKey}
                    nodeComponent={Circle}
                  />
                </Surface>

      </Paper>
    );
  }
}

Example.propTypes = {
  data: PropTypes.array.isRequired,
  showTop: PropTypes.number.isRequired,
  sortKey: PropTypes.string.isRequired,
  dispatch: PropTypes.func.isRequired,
};

const makeMapStateToProps = () => {
  const getSelectedData = makeGetSelectedData();
  const mapStateToProps = (state) => {
    return getSelectedData(state);
  };
  return mapStateToProps;
};

export default connect(makeMapStateToProps())(Example);
<commit_msg>side-step mui table update issue<commit_after>// @flow weak

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Table, TableRow, TableRowColumn, TableBody } from 'material-ui/table';
import Slider from 'material-ui/Slider';
import Paper from 'material-ui/Paper';
import Surface from 'resonance/Surface';
import NodeGroup from 'resonance/NodeGroup';
import MarkdownElement from 'docs/src/components/MarkdownElement';
import { updateSortOrder, updateTopCount, makeGetSelectedData } from '../module';
import { VIEW, TRBL, AGES } from '../module/constants';
import Circle from './Circle';
import description from '../description.md';

const circleKeyAccessor = (d) => d.name;

export class Example extends Component {

  constructor(props) {
    super(props);

    (this:any).setShowTop = this.setShowTop.bind(this);
    (this:any).setDuration = this.setDuration.bind(this);
  }

  state = {
    duration: 750,
    showTop: this.props.showTop,
  }

  setShowTop(e, value) {
    this.setState({
      showTop: value,
    });
  }

  setDuration(e, value) {
    this.setState({
      duration: Math.floor(value * 10000),
    });
  }

  render() {
    const { sortKey, data, dispatch } = this.props;
    const { duration, showTop } = this.state;

    return (
      <Paper style={{ padding: 20 }}>

                <MarkdownElement text={description} />

Show Top {showTop} States:

                <Slider
                  min={5} max={25} step={1}
                  value={showTop}
                  onChange={this.setShowTop}
                  onDragStop={() => dispatch(updateTopCount(showTop))}
                />

Transition Duration: {(duration / 1000).toFixed(1)} Seconds

                <Slider
                  defaultValue={0.1}
                  onChange={this.setDuration}
                />

 dispatch(updateSortOrder(AGES[d]))}
                >
                  <TableBody displayRowCheckbox={false}>
                    {AGES.map((age) => {
                      const color = sortKey === age ? 'rgba(51,51,51,0.1)' : 'transparent';

                      return (
                        <TableRow
                          key={age}
                          style={{ backgroundColor: color }}
                        >
                          <TableRowColumn>{age}</TableRowColumn>
                        </TableRow>
                      );
                    })}
                  </TableBody>

                <Surface view={VIEW} trbl={TRBL}>
                  <NodeGroup
                    data={data}
                    duration={duration}
                    keyAccessor={circleKeyAccessor}
                    sortKey={sortKey}
                    nodeComponent={Circle}
                  />
                </Surface>

      </Paper>
    );
  }
}

Example.propTypes = {
  data: PropTypes.array.isRequired,
  showTop: PropTypes.number.isRequired,
  sortKey: PropTypes.string.isRequired,
  dispatch: PropTypes.func.isRequired,
};

const makeMapStateToProps = () => {
  const getSelectedData = makeGetSelectedData();
  const mapStateToProps = (state) => {
    return getSelectedData(state);
  };
  return mapStateToProps;
};

export default connect(makeMapStateToProps())(Example);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';
import { Breadcrumb, BreadcrumbItem, Input, Well, Button, Panel, DropdownButton, ButtonToolbar, MenuItem, Popover, OverlayTrigger, ButtonGroup } from 'react-bootstrap';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import { connect } from 'react-redux';
import { getTaskDefs } from '../../../actions/WorkflowActions';

const TaskMetaList = React.createClass({

  getInitialState() {
    return {
      name: '',
      version: '',
      taskDefs: []
    }
  },

  componentWillMount(){
    this.props.dispatch(getTaskDefs());
  },

  componentWillReceiveProps(nextProps){
    this.state.taskDefs = nextProps.taskDefs;

  },

  render() {
    var wfs = this.state.taskDefs;

    function retries(cell, row){
      if(row.retryLogic == 'FIXED') {
        return row.retryLogic + ' (' + row.retryDelaySeconds + ' seconds)';
      }
    };

    function editor(cell, row){
      return (<OverlayTrigger trigger="click" rootClose placement="right" overlay={
        <Popover title={row.name} style={{ width: '500px'}}>

          <form>
            <Input type="text" ref="retryCount" value={row.retryCount} addonBefore="Retry Count" addonAfter="Times"></Input>

            <Input type="select" ref="retryLogic" value={row.retryLogic} addonBefore="Retry Logic">
                <option value="FIXED">FIXED</option>
                <option value="EXPONENTIAL_BACKOFF">EXPONENTIAL_BACKOFF</option>
            </Input>

            <Input type="text" ref="retryDelaySeconds" value={row.retryDelaySeconds} addonBefore="Retry Delay" addonAfter="Seconds"></Input>

            <Input type="select" ref="timeoutPolicy" value={row.timeoutPolicy} addonBefore="Time Out Action">
              <option value="RETRY_TASK">RETRY TASK</option>
              <option value="TIME_OUT_WF">TIME_OUT_WF</option>
            </Input>

            <Input type="text" ref="timeoutSeconds" value={row.timeoutSeconds} addonBefore="Time Out" addonAfter="Seconds"></Input>

            <Input type="text" ref="restimeoutSeconds" value={row.responseTimeoutSeconds} addonBefore="Response Time Out" addonAfter="timeoutSeconds"></Input>

            <Input type="text" ref="concurrentExecLimit" value={row.concurrentExecLimit} addonBefore="Concurrent Exec Limit"></Input>

            <Input type="textarea" label="Task Description" ref="description" value={row.description} readonly={true}/>

          </form>

</Popover>
      }>{cell}</OverlayTrigger>);
    };

    return (

Task Definitions

        <BootstrapTable data={wfs} striped={true} hover={true} search={true} exportCSV={false} pagination={false}>
          <TableHeaderColumn dataField="name" isKey={true} dataAlign="left" dataSort={true} dataFormat={editor}>Name/Version</TableHeaderColumn>
          <TableHeaderColumn dataField="ownerApp" dataSort={true} >Owner App</TableHeaderColumn>
          <TableHeaderColumn dataField="timeoutPolicy" dataSort={true} >Timeout Policy</TableHeaderColumn>
          <TableHeaderColumn dataField="timeoutSeconds" dataSort={true} >Timeout Seconds</TableHeaderColumn>
          <TableHeaderColumn dataField="responseTimeoutSeconds" dataSort={true} >Response Timeout Seconds</TableHeaderColumn>
          <TableHeaderColumn dataField="retryCount" dataSort={true} >Retry Count</TableHeaderColumn>
          <TableHeaderColumn dataField="concurrentExecLimit" dataSort={true} >Concurrent Exec Limit</TableHeaderColumn>
          <TableHeaderColumn dataField="retryLogic" dataSort={true} dataFormat={retries}>Retry Logic</TableHeaderColumn>
          </BootstrapTable>

    );
  }
});
export default connect(state => state.workflow)(TaskMetaList);
<commit_msg>removing unused imports workflow tasks<commit_after>import React from 'react';
import { Input, Popover, OverlayTrigger } from 'react-bootstrap';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import { connect } from 'react-redux';
import { getTaskDefs } from '../../../actions/WorkflowActions';

const TaskMetaList = React.createClass({
  getInitialState() {
    return {
      name: '',
      version: '',
      taskDefs: []
    }
  },
  componentWillMount(){
    this.props.dispatch(getTaskDefs());
  },
  componentWillReceiveProps(nextProps){
    this.state.taskDefs = nextProps.taskDefs;

  },
  render() {
    var wfs = this.state.taskDefs;

    function retries(cell, row){
      if(row.retryLogic == 'FIXED') {
        return row.retryLogic + ' (' + row.retryDelaySeconds + ' seconds)';
      }
    };

    function editor(cell, row){
      return (<OverlayTrigger trigger="click" rootClose placement="right" overlay={
        <Popover title={row.name} style={{ width: '500px'}}>

          <form>
            <Input type="text" ref="retryCount" value={row.retryCount} addonBefore="Retry Count" addonAfter="Times"></Input>

            <Input type="select" ref="retryLogic" value={row.retryLogic} addonBefore="Retry Logic">
                <option value="FIXED">FIXED</option>
                <option value="EXPONENTIAL_BACKOFF">EXPONENTIAL_BACKOFF</option>
            </Input>

            <Input type="text" ref="retryDelaySeconds" value={row.retryDelaySeconds} addonBefore="Retry Delay" addonAfter="Seconds"></Input>

            <Input type="select" ref="timeoutPolicy" value={row.timeoutPolicy} addonBefore="Time Out Action">
              <option value="RETRY_TASK">RETRY TASK</option>
              <option value="TIME_OUT_WF">TIME_OUT_WF</option>
            </Input>

            <Input type="text" ref="timeoutSeconds" value={row.timeoutSeconds} addonBefore="Time Out" addonAfter="Seconds"></Input>

            <Input type="text" ref="restimeoutSeconds" value={row.responseTimeoutSeconds} addonBefore="Response Time Out" addonAfter="timeoutSeconds"></Input>

            <Input type="text" ref="concurrentExecLimit" value={row.concurrentExecLimit} addonBefore="Concurrent Exec Limit"></Input>

            <Input type="textarea" label="Task Description" ref="description" value={row.description} readonly={true}/>

          </form>

</Popover>
      }>{cell}</OverlayTrigger>);
    };

    return (

Task Definitions

        <BootstrapTable data={wfs} striped={true} hover={true} search={true} exportCSV={false} pagination={false}>
          <TableHeaderColumn dataField="name" isKey={true} dataAlign="left" dataSort={true} dataFormat={editor}>Name/Version</TableHeaderColumn>
          <TableHeaderColumn dataField="ownerApp" dataSort={true} >Owner App</TableHeaderColumn>
          <TableHeaderColumn dataField="timeoutPolicy" dataSort={true} >Timeout Policy</TableHeaderColumn>
          <TableHeaderColumn dataField="timeoutSeconds" dataSort={true} >Timeout Seconds</TableHeaderColumn>
          <TableHeaderColumn dataField="responseTimeoutSeconds" dataSort={true} >Response Timeout Seconds</TableHeaderColumn>
          <TableHeaderColumn dataField="retryCount" dataSort={true} >Retry Count</TableHeaderColumn>
          <TableHeaderColumn dataField="concurrentExecLimit" dataSort={true} >Concurrent Exec Limit</TableHeaderColumn>
          <TableHeaderColumn dataField="retryLogic" dataSort={true} dataFormat={retries}>Retry Logic</TableHeaderColumn>
          </BootstrapTable>

    );
  }
});

export default connect(state => state.workflow)(TaskMetaList);
<|endoftext|>


<commit_before>/**
 * Validators for Mongoose.js utilising node-validate
 *
 */
var validator    = require('validator')
  , defaultError = validator.defaultError
  , Validator    = new validator.Validator()
  , customError  = {};

Validator.error = function() {
    return false;
}

Validator.validate = function(options, method) {
    var hasOptions = 'object' === typeof options
      , _method    = hasOptions ? method : options
      , msg        = options.message ? options.message : (customError[_method] || defaultError[_method])
      , passIfEmpty = options.passIfEmpty ? options.passIfEmpty : false
      , args       = Array.prototype.slice.call(arguments, (hasOptions ? 2 : 1));

    if (Validator[_method]) {
        return {
            validator: function(val, next) {
                if (passIfEmpty && val === "") {
                    return next(true);
                }
                next(Validator.check(val)[_method].apply(Validator, args));
            },
            msg: msg
        }
    }

    throw new Error('Method ' +  _method + ' does not exist on Validators.');
}

Validator.extend = function (name, fn, msg) {
    customError[name] = msg || "Error";
    Object.getPrototypeOf(Validator)[name] = fn;
}

module.exports = Validator;<commit_msg>Fix to passIfEmpty<commit_after>/**
 * Validators for Mongoose.js utilising node-validate
 *
 */
var validator    = require('validator')
  , defaultError = validator.defaultError
  , Validator    = new validator.Validator()
  , customError  = {};

Validator.error = function() {
    return false;
}

Validator.validate = function(options, method) {
    var hasOptions = 'object' === typeof options
      , _method    = hasOptions ? method : options
      , msg        = options.message ? options.message : (customError[_method] || defaultError[_method])
      , passIfEmpty = options.passIfEmpty ? options.passIfEmpty : false
      , args       = Array.prototype.slice.call(arguments, (hasOptions ? 2 : 1));

    if (Validator[_method]) {
        return {
            validator: function(val, next) {
                if (passIfEmpty && (val === "" || 'undefined' === typeof val )) {
                    return next(true);
                }
                next(Validator.check(val)[_method].apply(Validator, args));
            },
            msg: msg
        }
    }

    throw new Error('Method ' +  _method + ' does not exist on Validators.');
}

Validator.extend = function (name, fn, msg) {
    customError[name] = msg || "Error";
    Object.getPrototypeOf(Validator)[name] = fn;
}

module.exports = Validator;<|endoftext|>


<commit_before>var hddComplete = false;
var memComplete = false;
var printed = false;

$(document).ready(function(){
  var timer = window.setInterval(updateStatus,1000);
});

function updateStatus() {
  $.getJSON("/status.json", function(status){
    var hddStatus = status.hddStatus;
    console.log("Set hddStatus");
    var memStatus = status.memoryStatus;
    console.log("Set memStatus");
    if (memComplete == false) {
      if (memStatus == 'PASS') {
        console.log("Made it into if statement");
        $("#memTest").removeClass("load fa-spin");
        $("#memTest").addClass("success");
        memComplete = true;
      } else if (memStatus == 'FAIL') {
        $("#memTest").removeClass("load fa-spin");
        $("#memTest").addClass("failure");
        memComplete = true;
      }
    }

    if (hddComplete == false) {
      if (hddStatus == 'PASS') {
        console.log("Made it into if statement");
        $("#hddTest").removeClass("load fa-spin");
        $("#hddTest").addClass("success");
        hddComplete = true;
      } else if (hddStatus == 'FAIL') {
        $("#hddTest").removeClass("load fa-spin");
        $("#hddTest").addClass("failure");
        hddComplete = true;
      } else if (hddStatus == "ERROR: SMART Not Supported by Drive") {
        $("#hddTest").removeClass("load fa-spin");
        $("#hddTest").addClass("question");
        hddComplete = true;
      }
    }

    if (hddComplete == true && memComplete == true && printed == false) {
      $.ajax({
        url: "/printlabel"
      }).done(function() {
        printed = true;
      });
    }

    if (hddStatus == 'PASS' && memStatus == 'PASS') {
      if (status.hasOwnProperty('modelMatch')) {
        modelStatus = status.modelMatch;
        procStatus = status.procMatch;
        if (modelStatus && procStatus) {
          $("#proceed").removeClass("disabled");
          $("#proceed").removeAttr("disabled");
          $("#proceed").attr("href", "/clone");
          $("#proceed").click(function() {
            $.ajax({
              url: "/logdb"
            });
          });
        }
      } else {
      console.log("hm.");
        $("#proceed").removeClass("disabled");
        $("#proceed").removeAttr("disabled");
        $("#proceed").attr("href", "/clone");
        $("#proceed").click(function() {
          $.ajax({
            url: "/logdb"
          });
        });
      }
    }
  });
}
<commit_msg>Whoops! I think JS works this way<commit_after>var hddComplete = false;
var memComplete = false;
var printed = false;

$(document).ready(function () {
  var timer = window.setInterval(updateStatus, 1000);
});

function updateStatus() {
  $.getJSON("/status.json", function (status) {
    var hddStatus = status.hddStatus;
    console.log("Set hddStatus");
    var memStatus = status.memoryStatus;
    console.log("Set memStatus");
    if (memComplete == false) {
      if (memStatus == 'PASS') {
        console.log("Made it into if statement");
        $("#memTest").removeClass("fa-spin");
        $("#memTest").removeClass("load");
        $("#memTest").addClass("success");
        memComplete = true;
      } else if (memStatus == 'FAIL') {
        $("#memTest").removeClass("fa-spin");
        $("#memTest").removeClass("load");
        $("#memTest").addClass("failure");
        memComplete = true;
      }
    }

    if (hddComplete == false) {
      if (hddStatus == 'PASS') {
        console.log("Made it into if statement");
        $("#hddTest").removeClass("load fa-spin");
        $("#hddTest").removeClass("load");
        $("#hddTest").addClass("success");
        hddComplete = true;
      } else if (hddStatus == 'FAIL') {
        $("#hddTest").removeClass("fa-spin");
        $("#hddTest").removeClass("load");
        $("#hddTest").addClass("failure");
        hddComplete = true;
      } else if (hddStatus == "ERROR: SMART Not Supported by Drive") {
        $("#hddTest").removeClass("load fa-spin");
        $("#hddTest").removeClass("load");
        $("#hddTest").addClass("question");
        hddComplete = true;
      }
    }

    if (hddComplete == true && memComplete == true && printed == false) {
      $.ajax({
        url: "/printlabel"
      }).done(function () {
        printed = true;
      });
    }

    if (hddStatus == 'PASS' && memStatus == 'PASS') {
      if (status.hasOwnProperty('modelMatch')) {
        modelStatus = status.modelMatch;
        procStatus = status.procMatch;
        if (modelStatus && procStatus) {
          $("#proceed").removeClass("disabled");
          $("#proceed").removeAttr("disabled");
          $("#proceed").attr("href", "/clone");
          $("#proceed").click(function () {
            $.ajax({
              url: "/logdb"
            });
          });
        }
      } else {
        console.log("hm.");
        $("#proceed").removeClass("disabled");
        $("#proceed").removeAttr("disabled");
        $("#proceed").attr("href", "/clone");
        $("#proceed").click(function () {
          $.ajax({
            url: "/logdb"
          });
        });
      }
    }
  });
}<|endoftext|>


<commit_before>"use strict";

exports.getConfig = function() {
  var config = {
    port: 31337,
    database: 3,

    saltSecret: 'secret token',
    secret: 'secret',

    origin: 'http://localhost:3333'
  }

  config.host = 'http://localhost:' + config.port

  config.attachments = {
    // Make sure that all directories here have a trailing slash
    urlDir: config.host + '/attachments/original/',
    fsDir: '/tmp/pepyatka-attachments/original/',

    thumbnails: {
      urlDir: config.host + '/attachments/thumbnails/',
      fsDir: '/tmp/pepyatka-attachments/thumbnails/'
    }
  }

  config.mailer: {
    transport: "Stub"
  }

  return config
}
<commit_msg>Fixes typo.<commit_after>"use strict";

exports.getConfig = function() {
  var config = {
    port: 31337,
    database: 3,

    saltSecret: 'secret token',
    secret: 'secret',

    origin: 'http://localhost:3333'
  }

  config.host = 'http://localhost:' + config.port

  config.attachments = {
    // Make sure that all directories here have a trailing slash
    urlDir: config.host + '/attachments/original/',
    fsDir: '/tmp/pepyatka-attachments/original/',

    thumbnails: {
      urlDir: config.host + '/attachments/thumbnails/',
      fsDir: '/tmp/pepyatka-attachments/thumbnails/'
    }
  }

  config.mailer = {
    transport: "Stub"
  }

  return config
}
<|endoftext|>