<commit_before>(function($){
  var config = {
    selectors: { // according to query selector standards
      project: '.project',
      project_id: 'data-id',
      environment: '.environment',
      story_column: '.story',
      github_link: '.GitHubDiffURL',
    },
    pivotal: {
      label: 'status',
      ticket_id_regexp: /\[#(\d+)+\]/g  // we want all matches, not just the first ticket
    },
    github: {
      url_compare_regexp: /.*\/(.*)\/compare/
    },
    urls: {
      pivotal: {
        base: "https://www.pivotaltracker.com",
        story: '/story/show',
        api: '/services/v5',
      }
    }
  };

  function mapStatusLabelClass(status) {
    // returns label class type (as of Twitter Bootstrap 3)
    switch(status) {
      case 'rejected':
        return 'danger';
      case 'accepted':
        return 'success';
      case 'delivered':
        return 'warning';
      case 'finished':
        return 'primary';
      case 'started':
        return 'info';
      default:
        return 'default';
    }
  }

  function getProjectDiffs(){

      var projectDiffs = [];

      $(config.selectors.project).each(function() {
          var project = $(this).attr(config.selectors.project_id);
          var url = $(this).find(config.selectors.github_link).attr('href');
          if (url && url != "undefined"){
              projectDiffs[project] = url;
          }
      });
      return projectDiffs;
  }

  function getLinkDiv(pt_info) {
    var links = '',
        info,
        statusLabel;
    for(f in pt_info)
    {
      info = pt_info[f];
      statusLabel = config.pivotal.label.replace('unknown' , mapStatusLabelClass(info['status'])).replace('status', info['status']);
      links += '#' + info['id'] + ' ' + statusLabel +'
';
    }
    return links;
  }

  function injectPivotalStatus(project_id, pt_info) {
      var project_selector = config.selectors.project + '[' + config.selectors.project_id + '="' + project_id + '"]';
      $(project_selector).find(config.selectors.story_column).append(getLinkDiv(pt_info));
  }

  function getGithubPivotalIDs(github_token, repo, sha1, sha2, callback){
    var compare_uri = 'https://api.github.com/repos/gengo/'+ repo + '/compare/' + sha1 + '...' + sha2;
    $.ajax({
      url: compare_uri,
      type: 'GET',
      beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "token " + github_token);
      },
      success: function (data) {
        callback(data.commits);
      },
      error: function (data) {
        console.log(data);
      }
    });
  }

  function stripBrackets(ticket_id_str){
    return parseInt(ticket_id_str.match(/\[#(\d+)\]/)[1], 10); // base 10
  }

  function getCommitIDs(msgs){
    // create an object with no prior properties; therefore, all keys in set are the values we want
    pivotal_ids = Object.create(null);
    for(msg in msgs)
    {
      var message = msgs[msg];
      var matches = message.match(config.pivotal.ticket_id_regexp);
      if(!matches) continue;
      matches.forEach(function(ticket, i, arr){
        var id = stripBrackets(ticket);
        if(id && !(id in pivotal_ids)) pivotal_ids[id] = true;
      });
    }
    return Object.keys(pivotal_ids); // returning just the keys gives us all unique pivotal IDs
  }

  function getPivotalInfo(pt_token, story_id, callback){
    var story_uri = config.urls.pivotal.base + config.urls.pivotal.api + '/stories/' + story_id;
    $.ajax({
      type:"GET",
      beforeSend: function (request)
      {
        request.setRequestHeader("X-TrackerToken", pt_token);
      },
      url: story_uri,
      success: function (data) {
        var info = {
          'id': story_id
        };
        info['status'] = data['current_state'];
        info['url'] = data['url'];
        callback(info);
      }
    });
  }

  var diffs = getProjectDiffs();
  setTimeout(function(){ diffs = getProjectDiffs(); }, 1000);  // fetch diffs again after 1 sec
  $(document).ready(function(){

    // add button to story columns
    var button = '<button class="btn btn-default getStories">get stories</button>';
    $(config.selectors.story_column).each(function(){
      $(this).html(button);
    });

    // "get stories" button onClick handler
    $('.getStories').click(function(e){
      var $this_button = $(this);
      e.preventDefault();
      diffs = getProjectDiffs();
      var project = $this_button.parents(config.selectors.project).data('id');
      if(project in diffs) {
        // great! we found diffs for this project; load the pivotal stories
        $this_button.hide(); // do not show button
        (function(project) {
        var url = diffs[project];
        // hashes: currentCommit...latestCommit
        var hashes = (url.substr(url.lastIndexOf('/') + 1)).split('...');
        var proj_name = url.match(config.github.url_compare_regexp)[1];

        getGithubPivotalIDs(GITHUB_TOKEN, proj_name, hashes[0], hashes[1], function(commits){
          var messages = [];
          for(commit in commits) {
            messages.push(commits[commit]['commit']['message']); // get all github commit messages
          }

          var pivotal_ids = getCommitIDs(messages); // extract pivotal ticket IDs
          if(!pivotal_ids) {
            alert('No associated Pivotal stories found in commit messages.');
            $this_button.show();
            return
          };

          var display_message = [];
          for(pt_id in pivotal_ids)
          {
            var id = pivotal_ids[pt_id];
            getPivotalInfo(PIVOTAL_TOKEN, id, function(info){
              display_message[id] = info;
              injectPivotalStatus(project, display_message);
            });
          }
        });
      })(project);
      }
      else {
        alert('There seems to be no diffs for ' + project + '. Goship may still be loading the diff, if any. Please try again later.');
      }
    });
  });
}(jQuery));
<commit_msg>rm unnecessary expression in regexp<commit_after>(function($){
  var config = {
    selectors: { // according to query selector standards
      project: '.project',
      project_id: 'data-id',
      environment: '.environment',
      story_column: '.story',
      github_link: '.GitHubDiffURL',
    },
    pivotal: {
      label: 'status',
      ticket_id_regexp: /\[#(\d+)\]/g  // we want all matches, not just the first ticket
    },
    github: {
      url_compare_regexp: /.*\/(.*)\/compare/
    },
    urls: {
      pivotal: {
        base: "https://www.pivotaltracker.com",
        story: '/story/show',
        api: '/services/v5',
      }
    }
  };

  function mapStatusLabelClass(status) {
    // returns label class type (as of Twitter Bootstrap 3)
    switch(status) {
      case 'rejected':
        return 'danger';
      case 'accepted':
        return 'success';
      case 'delivered':
        return 'warning';
      case 'finished':
        return 'primary';
      case 'started':
        return 'info';
      default:
        return 'default';
    }
  }

  function getProjectDiffs(){

      var projectDiffs = [];

      $(config.selectors.project).each(function() {
          var project = $(this).attr(config.selectors.project_id);
          var url = $(this).find(config.selectors.github_link).attr('href');
          if (url && url != "undefined"){
              projectDiffs[project] = url;
          }
      });
      return projectDiffs;
  }

  function getLinkDiv(pt_info) {
    var links = '',
        info,
        statusLabel;
    for(f in pt_info)
    {
      info = pt_info[f];
      statusLabel = config.pivotal.label.replace('unknown' , mapStatusLabelClass(info['status'])).replace('status', info['status']);
      links += '#' + info['id'] + ' ' + statusLabel +'
';
    }
    return links;
  }

  function injectPivotalStatus(project_id, pt_info) {
      var project_selector = config.selectors.project + '[' + config.selectors.project_id + '="' + project_id + '"]';
      $(project_selector).find(config.selectors.story_column).append(getLinkDiv(pt_info));
  }

  function getGithubPivotalIDs(github_token, repo, sha1, sha2, callback){
    var compare_uri = 'https://api.github.com/repos/gengo/'+ repo + '/compare/' + sha1 + '...' + sha2;
    $.ajax({
      url: compare_uri,
      type: 'GET',
      beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "token " + github_token);
      },
      success: function (data) {
        callback(data.commits);
      },
      error: function (data) {
        console.log(data);
      }
    });
  }

  function stripBrackets(ticket_id_str){
    return parseInt(ticket_id_str.match(/\[#(\d+)\]/)[1], 10); // base 10
  }

  function getCommitIDs(msgs){
    // create an object with no prior properties; therefore, all keys in set are the values we want
    pivotal_ids = Object.create(null);
    for(msg in msgs)
    {
      var message = msgs[msg];
      var matches = message.match(config.pivotal.ticket_id_regexp);
      if(!matches) continue;
      matches.forEach(function(ticket, i, arr){
        var id = stripBrackets(ticket);
        if(id && !(id in pivotal_ids)) pivotal_ids[id] = true;
      });
    }
    return Object.keys(pivotal_ids); // returning just the keys gives us all unique pivotal IDs
  }

  function getPivotalInfo(pt_token, story_id, callback){
    var story_uri = config.urls.pivotal.base + config.urls.pivotal.api + '/stories/' + story_id;
    $.ajax({
      type:"GET",
      beforeSend: function (request)
      {
        request.setRequestHeader("X-TrackerToken", pt_token);
      },
      url: story_uri,
      success: function (data) {
        var info = {
          'id': story_id
        };
        info['status'] = data['current_state'];
        info['url'] = data['url'];
        callback(info);
      }
    });
  }

  var diffs = getProjectDiffs();
  setTimeout(function(){ diffs = getProjectDiffs(); }, 1000);  // fetch diffs again after 1 sec
  $(document).ready(function(){

    // add button to story columns
    var button = '<button class="btn btn-default getStories">get stories</button>';
    $(config.selectors.story_column).each(function(){
      $(this).html(button);
    });

    // "get stories" button onClick handler
    $('.getStories').click(function(e){
      var $this_button = $(this);
      e.preventDefault();
      diffs = getProjectDiffs();
      var project = $this_button.parents(config.selectors.project).data('id');
      if(project in diffs) {
        // great! we found diffs for this project; load the pivotal stories
        $this_button.hide(); // do not show button
        (function(project) {
        var url = diffs[project];
        // hashes: currentCommit...latestCommit
        var hashes = (url.substr(url.lastIndexOf('/') + 1)).split('...');
        var proj_name = url.match(config.github.url_compare_regexp)[1];

        getGithubPivotalIDs(GITHUB_TOKEN, proj_name, hashes[0], hashes[1], function(commits){
          var messages = [];
          for(commit in commits) {
            messages.push(commits[commit]['commit']['message']); // get all github commit messages
          }

          var pivotal_ids = getCommitIDs(messages); // extract pivotal ticket IDs
          if(!pivotal_ids) {
            alert('No associated Pivotal stories found in commit messages.');
            $this_button.show();
            return
          };

          var display_message = [];
          for(pt_id in pivotal_ids)
          {
            var id = pivotal_ids[pt_id];
            getPivotalInfo(PIVOTAL_TOKEN, id, function(info){
              display_message[id] = info;
              injectPivotalStatus(project, display_message);
            });
          }
        });
      })(project);
      }
      else {
        alert('There seems to be no diffs for ' + project + '. Goship may still be loading the diff, if any. Please try again later.');
      }
    });
  });
}(jQuery));
<|endoftext|>


<commit_before>/*
    Copyright 2014 UW Information Technology, University of Washington

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    Changes:

    =================================================================

*/

function setupRatingsAndReviews() {

    var REVIEW_CHAR_LIMIT = 300,
        enable_submit = function () {
            $('button#space-review-submit').removeAttr('disabled');
        },
        disable_submit = function () {
            $('button#space-review-submit').attr('disabled', 'disabled');
        };

    // wire up events for markup in reviews.html
    $('.space-reviews .write-a-review').on('click', function (e) {
        $('.space-reviews button.write-a-review').hide();
        $('.space-review-compose').show(400);
        $('.space-reviews-none').hide(400);
        $('.space-review-rating div b span').html(REVIEW_CHAR_LIMIT);
    });

    disable_submit();

    $('.space-review-compose textarea').keyup(function (e) {
        var l = $(this).val().length,
            remaining = REVIEW_CHAR_LIMIT - l;

        if (remaining > 0) {
            $('.space-review-rating div b span').html(remaining);
        } else {
            $('.space-review-rating div b span').html(0);
        }

        if (l > 0 && $('.space-review-compose .space-review-stars i.fa-star').length) {
            enable_submit();
        } else {
            disable_submit();
        }
    });

    $('button#space-review-cancel').click(function (e) {
        var node = $('.space-review-compose');

        node.hide(400);
        $('.space-reviews-none').show();
        $('.space-reviews button.write-a-review').show();

        disable_submit();
        $('textarea', node).val('');
        $('.space-review-stars span', node).html('');
        $('.space-review-rating div b span', node).html(REVIEW_CHAR_LIMIT);
        $('.space-review-rating i', node).switchClass('fa-star', 'fa-star-o');
    });

    $('button#space-review-submit').click(function (e) {
        var id = $(e.target).closest('div[id^=detail_container_]').attr('id').match(/_(\d+)$/)[1];

        submitRatingAndReview(id);
    });

    $('.space-review-submitted a').click(function (e) {
        $('.space-review-submitted').hide(400);
        $('.space-reviews-none').show();
        $('.space-reviews button.write-a-review').show();
    });

    $(document).on('click', '.space-review-stars i', function (e) {
        var target = $(e.target),
            stars = target.prevAll('i'),
            rating = stars.length + 1,
            ratings = ['', gettext('terrible'), gettext('poor'),
                       gettext('average'), gettext('good'), gettext('excellent')];

        stars.switchClass('fa-star-o', 'fa-star');
        target.switchClass('fa-star-o', 'fa-star');
        target.nextAll('i').switchClass('fa-star', 'fa-star-o');
        $('.space-review-stars span:last-child').html(ratings[rating]);
        if ($('.space-review-compose textarea').val().length) {
            enable_submit();
        }
    });

    $('.space-review-compose a').on('click', function (e) {
        var target = $(e.target),
            ul = target.next('ul');

        if (ul.is(':visible')) {
            target.find('i').switchClass('fa-angle-double-up', 'fa-angle-double-down');
        } else {
            target.find('i').switchClass('fa-angle-double-down', 'fa-angle-double-up');
        }

        ul.toggle(400);
    });
}

function loadRatingsAndReviews(id) {
    $.ajax({
        url: 'web_api/v1/space/' + id + '/reviews',
        success: function (data) {
            var template = Handlebars.compile($('#space_reviews').html()),
                content = $('.space-reviews-content'),
                rating_sum = 0;

            content.html('');

            if (data && data.length > 0) {
                $.each(data, function() {
                    var review = this,
                        rating = this.rating,
                        date = new Date(this.date_submitted),
                        node = $(template({
                            reviewer: this.reviewer,
                            review: (this.review && this.review.length) ? this.review : 'No review provided',
                            date: date ? monthname_from_month(date.getMonth()) + ' ' + date.getDate() + ', ' + date.getFullYear() : ''
                        }));

                    rating_sum += parseInt(this.rating);

                    $('.space-review-header i', node).each(function(i) {
                        if (i < rating) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        }
                    });

                    content.append(node);
                });

                if (rating_sum) {
                    var avg = Math.floor((rating_sum) / data.length);

                    $('.space-actions i').each(function(i) {
                        if (i == 0 || i <= avg) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        }
                    });

                    $('.space-actions span#review_count').html(data.length);
                }

            } else {
                template = Handlebars.compile($('#no_space_reviews').html());
                content.html(template());
            }

        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Unable to load reviews: ' + xhr.responseText);
        }
    });
}

function submitRatingAndReview(id) {
    var node = $('.space-review-compose'),
        review = {
            rating: $('.space-review-rating i.fa-star', node).length,
            review: $('textarea', node).val().trim()
        };

    //validate
    if (review.rating < 1 || review.rating > 5 || review.review.length <= 0) {
        return;
    }

    $.ajax({
        url: 'web_api/v1/space/' + id + '/reviews',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(review),
        type: "POST",
        success: function (data) {
            $('.space-reviews button.write-a-review').hide();
            $('.space-review-compose').hide(400);
            $('.space-review-submitted').show();
        },
        error: function (xhr, textStatus, errorThrown) {
            debugger
            console.log('Unable to post reviews: ' + xhr.responseText);
        }
    });
}

<commit_msg>adds color feedback to review character counter<commit_after>/*
    Copyright 2014 UW Information Technology, University of Washington

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    Changes:

    =================================================================

*/

function setupRatingsAndReviews() {

    var REVIEW_CHAR_LIMIT = 300,
        enable_submit = function () {
            $('button#space-review-submit').removeAttr('disabled');
        },
        disable_submit = function () {
            $('button#space-review-submit').attr('disabled', 'disabled');
        };

    // wire up events for markup in reviews.html
    $('.space-reviews .write-a-review').on('click', function (e) {
        $('.space-reviews button.write-a-review').hide();
        $('.space-review-compose').show(400);
        $('.space-reviews-none').hide(400);
        $('.space-review-rating div b span').html(REVIEW_CHAR_LIMIT);
    });

    disable_submit();

    $('.space-review-compose textarea').keyup(function (e) {
        var l = $(this).val().length,
            remaining = REVIEW_CHAR_LIMIT - l,
            span = $('.space-review-rating div b span');

        if (remaining > 0) {
            span.html(remaining);
            span.removeClass('required');
        } else {
            span.html(0);
            span.addClass('required');
        }

        if (l > 0 && $('.space-review-compose .space-review-stars i.fa-star').length) {
            enable_submit();
        } else {
            disable_submit();
        }
    });

    $('button#space-review-cancel').click(function (e) {
        var node = $('.space-review-compose');

        node.hide(400);
        $('.space-reviews-none').show();
        $('.space-reviews button.write-a-review').show();

        disable_submit();
        $('textarea', node).val('');
        $('.space-review-stars span', node).html('');
        $('.space-review-rating div b span', node).html(REVIEW_CHAR_LIMIT);
        $('.space-review-rating i', node).switchClass('fa-star', 'fa-star-o');
    });

    $('button#space-review-submit').click(function (e) {
        var id = $(e.target).closest('div[id^=detail_container_]').attr('id').match(/_(\d+)$/)[1];

        submitRatingAndReview(id);
    });

    $('.space-review-submitted a').click(function (e) {
        $('.space-review-submitted').hide(400);
        $('.space-reviews-none').show();
        $('.space-reviews button.write-a-review').show();
    });

    $(document).on('click', '.space-review-stars i', function (e) {
        var target = $(e.target),
            stars = target.prevAll('i'),
            rating = stars.length + 1,
            ratings = ['', gettext('terrible'), gettext('poor'),
                       gettext('average'), gettext('good'), gettext('excellent')];

        stars.switchClass('fa-star-o', 'fa-star');
        target.switchClass('fa-star-o', 'fa-star');
        target.nextAll('i').switchClass('fa-star', 'fa-star-o');
        $('.space-review-stars span:last-child').html(ratings[rating]);
        if ($('.space-review-compose textarea').val().length) {
            enable_submit();
        }
    });

    $('.space-review-compose a').on('click', function (e) {
        var target = $(e.target),
            ul = target.next('ul');

        if (ul.is(':visible')) {
            target.find('i').switchClass('fa-angle-double-up', 'fa-angle-double-down');
        } else {
            target.find('i').switchClass('fa-angle-double-down', 'fa-angle-double-up');
        }

        ul.toggle(400);
    });
}

function loadRatingsAndReviews(id) {
    $.ajax({
        url: 'web_api/v1/space/' + id + '/reviews',
        success: function (data) {
            var template = Handlebars.compile($('#space_reviews').html()),
                content = $('.space-reviews-content'),
                rating_sum = 0;

            content.html('');

            if (data && data.length > 0) {
                $.each(data, function() {
                    var review = this,
                        rating = this.rating,
                        date = new Date(this.date_submitted),
                        node = $(template({
                            reviewer: this.reviewer,
                            review: (this.review && this.review.length) ? this.review : 'No review provided',
                            date: date ? monthname_from_month(date.getMonth()) + ' ' + date.getDate() + ', ' + date.getFullYear() : ''
                        }));

                    rating_sum += parseInt(this.rating);

                    $('.space-review-header i', node).each(function(i) {
                        if (i < rating) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        }
                    });

                    content.append(node);
                });

                if (rating_sum) {
                    var avg = Math.ceil((rating_sum) / data.length);

                    $('.space-actions i').each(function(i) {
                        if (i < avg) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        }
                    });

                    $('.space-actions span#review_count').html(data.length);
                }

            } else {
                template = Handlebars.compile($('#no_space_reviews').html());
                content.html(template());
            }

        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Unable to load reviews: ' + xhr.responseText);
        }
    });
}

function submitRatingAndReview(id) {
    var node = $('.space-review-compose'),
        review = {
            rating: $('.space-review-rating i.fa-star', node).length,
            review: $('textarea', node).val().trim()
        };

    //validate
    if (review.rating < 1 || review.rating > 5 || review.review.length <= 0) {
        return;
    }

    $.ajax({
        url: 'web_api/v1/space/' + id + '/reviews',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(review),
        type: "POST",
        success: function (data) {
            $('.space-reviews button.write-a-review').hide();
            $('.space-review-compose').hide(400);
            $('.space-review-submitted').show();
        },
        error: function (xhr, textStatus, errorThrown) {
            debugger
            console.log('Unable to post reviews: ' + xhr.responseText);
        }
    });
}

<|endoftext|>


<commit_before>// create a gith server on port 7500
var gith = require('gith').create( 7500 );

gith({
  repo: 'ericstiles/wheat-blog'
}).on( 'all', function( payload ) {
    console.log( 'Post-receive form Github');
    //console.log("Payload = " + JSON.stringify(payload));
    var gitRepoPath = "/home/node/wheat-blog.git";
    var gitCommand = "git --git-dir " + gitRepoPath + " fetch origin master:master";
    var gitLogUpdate = "git --git-dir " + gitRepoPath + " log -1 --pretty=oneline";
    var sys = require('sys')
    var exec = require('child_process').exec;
    var fetchOutput = exec(gitCommand, function puts(error, stdout, stderr) {
            if (error) {
                console.log('Error occurred \n[' + error+']');
            } else{
                var updateOutput = exec(gitLogUpdate, function puts(error, stdout, stderr) {
                    if (error) {
                        console.log('Error occurred getting git update \n[' + error+']');
                    } else {
                        console.log("Update:" + stdout);
                    }
                });
            }
	}
	);

	fetchOutput.on('exit', function (code) {
		console.log('Child process exited with exit code '+code);
	});

});<commit_msg>adding second repo for the wheat code I extended<commit_after>// create a gith server on port 7500
var gith = require('gith').create( 7500 );

gith({
  repo: 'ericstiles/wheat-blog'
}).on( 'all', function( payload ) {
    console.log( 'Post-receive form Github');
    //console.log("Payload = " + JSON.stringify(payload));
    var gitRepoPath = "/home/node/wheat-blog.git";
    var gitCommand = "git --git-dir " + gitRepoPath + " fetch origin master:master";
    var gitLogUpdate = "git --git-dir " + gitRepoPath + " log -1 --pretty=oneline";
    var sys = require('sys')
    var exec = require('child_process').exec;
    var fetchOutput = exec(gitCommand, function puts(error, stdout, stderr) {
        if (error) {
          console.log('Error occurred \n[' + error+']');
        } else{
          var updateOutput = exec(gitLogUpdate, function puts(error, stdout, stderr) {
            if (error) {
              console.log('Error occurred getting git update \n[' + error+']');
            } else {
              console.log("Update:" + stdout);
            }
          });
        }
      }
    );

    fetchOutput.on('exit', function (code) {
      console.log('Child process exited with exit code '+code);
    });

  });

// create a gith server on port 7500
var gith = require('gith').create( 7600 );

gith({
  repo: 'ericstiles/wheat'
}).on( 'all', function( payload ) {
    console.log( 'Post-receive form Github');
    //console.log("Payload = " + JSON.stringify(payload));
    var gitRepoPath = "/home/node/wheat-blog.git/wheat.git";
    var gitCommand = "git --git-dir " + gitRepoPath + " fetch origin master:master";
    var gitLogUpdate = "git --git-dir " + gitRepoPath + " log -1 --pretty=oneline";
    var sys = require('sys')
    var exec = require('child_process').exec;
    var fetchOutput = exec(gitCommand, function puts(error, stdout, stderr) {
        if (error) {
          console.log('Error occurred \n[' + error+']');
        } else{
          var updateOutput = exec(gitLogUpdate, function puts(error, stdout, stderr) {
            if (error) {
              console.log('Error occurred getting git update \n[' + error+']');
            } else {
              console.log("Update:" + stdout);
            }
          });
        }
      }
    );

    fetchOutput.on('exit', function (code) {
      console.log('Child process exited with exit code '+code);
    });

  });<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
!function ($) {
    "use strict"; // jshint ;_;

    if( $( '#blat_menu0').length ){
        fillupBlatMenu0()
    }
    if( $( '#blat_menu1').length ){
        fillupBlatMenu1()
    }
    if( $( '#blat_menu2').length ){
        fillupBlatMenu2()
    }
    if( $( '#hmm_menu0').length ){
        fillupHmmerMenu0()
    }

    initNumberAndTypeJobInput()
    setupMappingSteps()
    summarizeForm()

    $('#jobstart').click( function(){
        var xhr = new XMLHttpRequest();

        // Cancel Job if not correct input
        if ( ! checkJobInput()){
            return;
        }

        xhr.onreadystatechange = function( e ){
            if( 4 == this.readyState ){
                var obj = $.parseJSON( this.responseText );
                if( ! obj.ok ){
                    alert( "Job ERROR: " + obj.msg );
                }else{
                    alert( "Job sent: Go to 'Home' to check its status" );
                }
            }
        };

        xhr.open( 'POST', '/ajax/job', true );

        var form = $('#jobform')[0];
        var fd = new FormData( form );
        xhr.send( fd );
    });

}(window.jQuery);

// -----------------------------------------------------------------------------
function fillupBlatMenu0(){
    getFileListWithType( 3, function( files ){
        var items1 = [];

        var count = 0
        $.each(files, function( key, val ) {

            // this currently defines an array but dont get all values in (just one)
            //            items1.push( "
<input type='checkbox' name='my_blat_custom[]' value=" + val['file'] + " href=\"#\"> " + val['file'] + "
" )
            items1.push( "
<input type='checkbox' class='cleaning_steps' name='blat_custom_reads_n'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )
            count = count + 1
        });

        $( '#blat_menu0').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function fillupBlatMenu1(){
    getFileListWithType( 3, function( files ){
        var items1 = [];

        var count = 0
        $.each(files, function( key, val ) {

            items1.push( "
<input type='checkbox' class='identification_steps' name='blat_custom_ass_n'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )

            count = count + 1
        });

        $( '#blat_menu1').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function fillupBlatMenu2(){
    getFileListWithType( 4, function( files ){
        var items1 = [];

    var count = 0
        $.each(files, function( key, val ) {

            items1.push( "
<input type='checkbox' class='identification_steps' name='blat_custom_ass_aa'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )

        count = count + 1
        });

        $( '#blat_menu2').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function fillupHmmerMenu0(){
    getFileListWithType( 7, function( files ){
        var items1 = [];

    var count = 0
        $.each(files, function( key, val ) {

            items1.push( "
<input type='checkbox' class='identification_steps' name='hmm_custom'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )

        count = count + 1
        });

        $( '#hmm_menu0').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function checkJobInput(){
    // if no input type is selected:
    if ( ! $("input[name=input_type]").is(':checked') ){
        alert("You have to select a type of input at the top of the page before submitting the job")
        return false
    }

    var in_type = $("input[name=input_type]:checked").val()
    // check input type: single
    if ( in_type == "single" ){
        if ( $('#jobfile').val() == null ) {
            alert("You did not specify any reads file")
            return false
        }
    }
    // check input type: paired
    // if both reads files are the same:
    if ( in_type == "paired" ){
        if ( $('#jobfile').val() == null || $('#jobfile2').val() == null ){
            alert("You did not specify two reads files")
            return false
        }
    }
    // check input type: contigs
    if ( in_type == "contigs" ){
        if ( $('#jobfile3').val() == null ) {
            alert("You did not specify any assembly file")
            return false
        }
    }
    // check input type: contigs_with_single:
    if ( in_type == "contigs_with_single" ){
        if ( $('#jobfile').val() == null ) {
            alert("You did not specify any reads file")
            return false
        }
        if ( $('#jobfile3').val() == null ) {
            alert("You did not specify any assembly file")
            return false
        }
    }
    // check input type: contigs_with_paired:
    if ( in_type == "contigs_with_paired" ){
        if ( $('#jobfile').val() == null || $('#jobfile2').val() == null ){
            alert("You did not specify two reads files")
            return false
        }
        if ( $('#jobfile3').val() == null ) {
            alert("You did not specify any assembly file")
            return false
        }
    }

    // if both reads files are the same:
    if ( in_type == "paired" || in_type == "contigs_with_paired"){
        if ( $('#jobfile').val() == $('#jobfile2').val()){
            alert("You have to specify two different reads files as input")
            return false
        }
    }

    // if no analysis steps checked
    var steps = $(".cleaning_steps, .assembly_steps, .identification_steps, .mapping_steps, .expression_steps")

    if ( ! steps.is(":checked")){
        alert("You did not specify any analysis steps")
        return false
    }
    // if no adapters but cutadapt activated:
    if ($("#adapters").is(':checked')){
        if ($("#cutadapt_option1").val() == '' || $("#cutadapt_option2").val() == '' ){
            alert("You have selected Cutadapt but did not specify two adapter sequences: please input the sequences in Cutadapt options")
        }
        return false
    }
    return true
}

// -----------------------------------------------------------------------------
function initNumberAndTypeJobInput(){
    // Select the number and type of input:
    var reads_1 = $("div[id=reads_1]")
    var reads_2 = $("div[id=reads_2]")
    var assembly_in = $("div[id=assembly_in]")
    var in_type = $("input[name=input_type]")

    // Setting single or paired reads
    in_type.change(function (){
        // unchecking all boxes
        $('.cleaning_steps').attr('checked', false)
        $('.assembly_steps').attr('checked', false)
        $('.assembly_qc_steps').attr('checked', false)
        $('.mapping_steps').attr('checked', false)
        $('.identification_steps').attr('checked', false)
        $('.expression_steps').attr('checked', false)

        // No defaults for input files:
        document.getElementById("jobfile").selectedIndex = -1;
        document.getElementById("jobfile2").selectedIndex = -1;
        document.getElementById("jobfile3").selectedIndex = -1;

        var in_type = $("input[name=input_type]:checked").val()
        //	$('#demo').append(in_type)
        var warn_read = $('div[id=no_reads_alert]')
        var warn_read2 = $('div[id=no_reads_alert2]')
        var warn_ass = $('div[id=no_assembly_alert]')
	var warn_exp = $('div[id=no_reads_and_ass_alert]')

        switch(in_type){
        case "single":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').attr('disabled','disabled')
            $('#jobfile3').attr('disabled','disabled')
            reads_1.children("label").text("Single reads file:")
            reads_1.show()
            reads_2.hide()
            assembly_in.hide()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', false);
            warn_read.hide()
            warn_read2.hide()
            $('.assembly_qc_steps').attr('disabled', true);
            $('.mapping_steps').attr('disabled', true);
            $('.identification_steps').attr('disabled', true);
            warn_ass.show()
            $('.expression_steps').attr('disabled', true)
	    warn_exp.show()
            break;
        case "paired":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').removeAttr('disabled')
            $('#jobfile3').attr('disabled','disabled')
            reads_1.children("label").text("Left reads file:")
            reads_1.show()
            reads_2.show()
            assembly_in.hide()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', false);
            warn_read.hide()
            warn_read2.hide()
            $('.assembly_qc_steps').attr('disabled', true);
            $('.mapping_steps').attr('disabled', true);
            $('.identification_steps').attr('disabled', true);
            warn_ass.show()
            $('.expression_steps').attr('disabled', true)
	    warn_exp.show()
            break;
        case "contigs":
            $('#jobfile3').removeAttr('disabled')
            $('#jobfile').attr('disabled','disabled')
            $('#jobfile2').attr('disabled','disabled')
            reads_1.hide()
            reads_2.hide()
            assembly_in.show()
            $('.cleaning_steps').attr('disabled', true);
            $('.assembly_steps').attr('disabled', true);
            warn_read.show()
            warn_read2.show()
            $('.assembly_qc_steps').attr('disabled', false);
            $('.mapping_steps').attr('disabled', true);
            $('.identification_steps').attr('disabled', false);
            warn_ass.hide()
            $('.expression_steps').attr('disabled', true)
	    warn_exp.show()
            break;
        case "contigs_with_single":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').attr('disabled','disabled')
            $('#jobfile3').removeAttr('disabled')
            reads_1.children("label").text("Single reads file:")
            reads_1.show()
            assembly_in.show()
            reads_2.hide()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', true);
            warn_read.hide()
            warn_read2.show()
            $('.assembly_qc_steps').attr('disabled', false);
            $('.mapping_steps').attr('disabled', false);
            $('.identification_steps').attr('disabled', false);
            warn_ass.hide()
            $('.expression_steps').attr('disabled', false)
	    warn_exp.hide()
            break;
        case "contigs_with_paired":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').removeAttr('disabled','disabled')
            $('#jobfile3').removeAttr('disabled')
            reads_1.children("label").text("Left reads file:")
            reads_1.show()
            reads_2.show()
            assembly_in.show()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', true);
            warn_read.hide()
            warn_read2.show()
            $('.assembly_qc_steps').attr('disabled', false);
            $('.mapping_steps').attr('disabled', false);
            $('.identification_steps').attr('disabled', false);
            warn_ass.hide()
            $('.expression_steps').attr('disabled', false)
	    warn_exp.hide()
            break;
        }
    });
}

// -----------------------------------------------------------------------------
function setupMappingSteps(){
    // activate/desactivate mapping/identification steps
    var trin_check = $("input[id=trinity]")
    var warn_ass = $('div[id=no_assembly_alert]')
    var warn_exp = $('div[id=no_reads_and_ass_alert]')

    trin_check.change(function(){
        if (trin_check.is(':checked')){
            $('.mapping_steps').attr('disabled', false);
            $('.assembly_qc_steps').attr('disabled', false);
            $('.identification_steps').attr('disabled', false);
            $('.expression_steps').attr('disabled', false);
            warn_ass.hide()
	    warn_exp.hide()
        }else{
            $('.mapping_steps').attr({'disabled': true, 'checked': false});
            $('.assembly_qc_steps').attr({'disabled': true, 'checked': false});
            $('.identification_steps').attr({'disabled': true, 'checked': false});
            $('.expression_steps').attr({'disabled': true, 'checked': false});
            warn_ass.show()
	    warn_exp.show()
        }

    });
}
// -----------------------------------------------------------------------------
function summarizeForm(){

    $('#jobform :input').change(function(){
	$("#formsum").empty()

	$("#formsum").append("
Summary of the selected steps:")
	$("#formsum").append("
Cleaning step:")
	$(".cleaning_steps").each(function(){
 	     if ( $(this).is(':checked')) {
		var val = $(this).val()
		var name = $(this).attr('name')
		$("#formsum").append("
" + name + ":" + val + "
")
	    }
	});

	$("#formsum").append("
Assembly/Mapping step:")
	$(".assembly_steps, .assembly_qc_steps, .mapping_steps").each(function(){
	    if ( $(this).is(':checked')) {
		var val = $(this).val()
		var name = $(this).attr('name')
		$("#formsum").append("
" + name + ":" + val + "
")
	    }
	});
	$("#formsum").append("
Identification step:")
	$(".identification_steps").each(function(){
	    if ( $(this).is(':checked')) {
		var val = $(this).val()
		var name = $(this).attr('name')
		$("#formsum").append("
" + name + ":" + val + "
")
	    }
	});
	$("#formsum").append("
Expression step:")
	$(".expression_steps").each(function(){
	    if ( $(this).is(':checked')) {
		var val = $(this).val()
		var name = $(this).attr('name')
		$("#formsum").append("
" + name + ":" + val + "
")
	    }
	});
    });
}<commit_msg>fixing form summary<commit_after>// -----------------------------------------------------------------------------
!function ($) {
    "use strict"; // jshint ;_;

    if( $( '#blat_menu0').length ){
        fillupBlatMenu0()
    }
    if( $( '#blat_menu1').length ){
        fillupBlatMenu1()
    }
    if( $( '#blat_menu2').length ){
        fillupBlatMenu2()
    }
    if( $( '#hmm_menu0').length ){
        fillupHmmerMenu0()
    }

    initNumberAndTypeJobInput()
    setupMappingSteps()
    summarizeForm()

    $('#jobstart').click( function(){
        var xhr = new XMLHttpRequest();

        // Cancel Job if not correct input
        if ( ! checkJobInput()){
            return;
        }

        xhr.onreadystatechange = function( e ){
            if( 4 == this.readyState ){
                var obj = $.parseJSON( this.responseText );
                if( ! obj.ok ){
                    alert( "Job ERROR: " + obj.msg );
                }else{
                    alert( "Job sent: Go to 'Home' to check its status" );
                }
            }
        };

        xhr.open( 'POST', '/ajax/job', true );

        var form = $('#jobform')[0];
        var fd = new FormData( form );
        xhr.send( fd );
    });

}(window.jQuery);

// -----------------------------------------------------------------------------
function fillupBlatMenu0(){
    getFileListWithType( 3, function( files ){
        var items1 = [];

        var count = 0
        $.each(files, function( key, val ) {

            // this currently defines an array but dont get all values in (just one)
            //            items1.push( "
<input type='checkbox' name='my_blat_custom[]' value=" + val['file'] + " href=\"#\"> " + val['file'] + "
" )
            items1.push( "
<input type='checkbox' class='cleaning_steps' name='blat_custom_reads_n'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )
            count = count + 1
        });

        $( '#blat_menu0').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function fillupBlatMenu1(){
    getFileListWithType( 3, function( files ){
        var items1 = [];

        var count = 0
        $.each(files, function( key, val ) {

            items1.push( "
<input type='checkbox' class='identification_steps' name='blat_custom_ass_n'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )

            count = count + 1
        });

        $( '#blat_menu1').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function fillupBlatMenu2(){
    getFileListWithType( 4, function( files ){
        var items1 = [];

    var count = 0
        $.each(files, function( key, val ) {

            items1.push( "
<input type='checkbox' class='identification_steps' name='blat_custom_ass_aa'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )

        count = count + 1
        });

        $( '#blat_menu2').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function fillupHmmerMenu0(){
    getFileListWithType( 7, function( files ){
        var items1 = [];

    var count = 0
        $.each(files, function( key, val ) {

            items1.push( "
<input type='checkbox' class='identification_steps' name='hmm_custom'" + count + "' value=" + val['file'] + " href=\"#\" disabled> " + val['file'] + "
" )

        count = count + 1
        });

        $( '#hmm_menu0').append( items1 );
    });
}

// -----------------------------------------------------------------------------
function checkJobInput(){
    // if no input type is selected:
    if ( ! $("input[name=input_type]").is(':checked') ){
        alert("You have to select a type of input at the top of the page before submitting the job")
        return false
    }

    var in_type = $("input[name=input_type]:checked").val()
    // check input type: single
    if ( in_type == "single" ){
        if ( $('#jobfile').val() == null ) {
            alert("You did not specify any reads file")
            return false
        }
    }
    // check input type: paired
    // if both reads files are the same:
    if ( in_type == "paired" ){
        if ( $('#jobfile').val() == null || $('#jobfile2').val() == null ){
            alert("You did not specify two reads files")
            return false
        }
    }
    // check input type: contigs
    if ( in_type == "contigs" ){
        if ( $('#jobfile3').val() == null ) {
            alert("You did not specify any assembly file")
            return false
        }
    }
    // check input type: contigs_with_single:
    if ( in_type == "contigs_with_single" ){
        if ( $('#jobfile').val() == null ) {
            alert("You did not specify any reads file")
            return false
        }
        if ( $('#jobfile3').val() == null ) {
            alert("You did not specify any assembly file")
            return false
        }
    }
    // check input type: contigs_with_paired:
    if ( in_type == "contigs_with_paired" ){
        if ( $('#jobfile').val() == null || $('#jobfile2').val() == null ){
            alert("You did not specify two reads files")
            return false
        }
        if ( $('#jobfile3').val() == null ) {
            alert("You did not specify any assembly file")
            return false
        }
    }

    // if both reads files are the same:
    if ( in_type == "paired" || in_type == "contigs_with_paired"){
        if ( $('#jobfile').val() == $('#jobfile2').val()){
            alert("You have to specify two different reads files as input")
            return false
        }
    }

    // if no analysis steps checked
    var steps = $(".cleaning_steps, .assembly_steps, .identification_steps, .mapping_steps, .expression_steps")

    if ( ! steps.is(":checked")){
        alert("You did not specify any analysis steps")
        return false
    }
    // if no adapters but cutadapt activated:
    if ($("#adapters").is(':checked')){
        if ($("#cutadapt_option1").val() == '' || $("#cutadapt_option2").val() == '' ){
            alert("You have selected Cutadapt but did not specify two adapter sequences: please input the sequences in Cutadapt options")
        }
        return false
    }
    return true
}

// -----------------------------------------------------------------------------
function initNumberAndTypeJobInput(){
    // Select the number and type of input:
    var reads_1 = $("div[id=reads_1]")
    var reads_2 = $("div[id=reads_2]")
    var assembly_in = $("div[id=assembly_in]")
    var in_type = $("input[name=input_type]")

    // Setting single or paired reads
    in_type.change(function (){
        // unchecking all boxes
        $('.cleaning_steps').attr('checked', false)
        $('.assembly_steps').attr('checked', false)
        $('.assembly_qc_steps').attr('checked', false)
        $('.mapping_steps').attr('checked', false)
        $('.identification_steps').attr('checked', false)
        $('.expression_steps').attr('checked', false)

        // No defaults for input files:
        document.getElementById("jobfile").selectedIndex = -1;
        document.getElementById("jobfile2").selectedIndex = -1;
        document.getElementById("jobfile3").selectedIndex = -1;

        var in_type = $("input[name=input_type]:checked").val()
        //	$('#demo').append(in_type)
        var warn_read = $('div[id=no_reads_alert]')
        var warn_read2 = $('div[id=no_reads_alert2]')
        var warn_ass = $('div[id=no_assembly_alert]')
	var warn_exp = $('div[id=no_reads_and_ass_alert]')

        switch(in_type){
        case "single":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').attr('disabled','disabled')
            $('#jobfile3').attr('disabled','disabled')
            reads_1.children("label").text("Single reads file:")
            reads_1.show()
            reads_2.hide()
            assembly_in.hide()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', false);
            warn_read.hide()
            warn_read2.hide()
            $('.assembly_qc_steps').attr('disabled', true);
            $('.mapping_steps').attr('disabled', true);
            $('.identification_steps').attr('disabled', true);
            warn_ass.show()
            $('.expression_steps').attr('disabled', true)
	    warn_exp.show()
            break;
        case "paired":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').removeAttr('disabled')
            $('#jobfile3').attr('disabled','disabled')
            reads_1.children("label").text("Left reads file:")
            reads_1.show()
            reads_2.show()
            assembly_in.hide()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', false);
            warn_read.hide()
            warn_read2.hide()
            $('.assembly_qc_steps').attr('disabled', true);
            $('.mapping_steps').attr('disabled', true);
            $('.identification_steps').attr('disabled', true);
            warn_ass.show()
            $('.expression_steps').attr('disabled', true)
	    warn_exp.show()
            break;
        case "contigs":
            $('#jobfile3').removeAttr('disabled')
            $('#jobfile').attr('disabled','disabled')
            $('#jobfile2').attr('disabled','disabled')
            reads_1.hide()
            reads_2.hide()
            assembly_in.show()
            $('.cleaning_steps').attr('disabled', true);
            $('.assembly_steps').attr('disabled', true);
            warn_read.show()
            warn_read2.show()
            $('.assembly_qc_steps').attr('disabled', false);
            $('.mapping_steps').attr('disabled', true);
            $('.identification_steps').attr('disabled', false);
            warn_ass.hide()
            $('.expression_steps').attr('disabled', true)
	    warn_exp.show()
            break;
        case "contigs_with_single":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').attr('disabled','disabled')
            $('#jobfile3').removeAttr('disabled')
            reads_1.children("label").text("Single reads file:")
            reads_1.show()
            assembly_in.show()
            reads_2.hide()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', true);
            warn_read.hide()
            warn_read2.show()
            $('.assembly_qc_steps').attr('disabled', false);
            $('.mapping_steps').attr('disabled', false);
            $('.identification_steps').attr('disabled', false);
            warn_ass.hide()
            $('.expression_steps').attr('disabled', false)
	    warn_exp.hide()
            break;
        case "contigs_with_paired":
            $('#jobfile').removeAttr('disabled')
            $('#jobfile2').removeAttr('disabled','disabled')
            $('#jobfile3').removeAttr('disabled')
            reads_1.children("label").text("Left reads file:")
            reads_1.show()
            reads_2.show()
            assembly_in.show()
            $('.cleaning_steps').attr('disabled', false);
            $('.assembly_steps').attr('disabled', true);
            warn_read.hide()
            warn_read2.show()
            $('.assembly_qc_steps').attr('disabled', false);
            $('.mapping_steps').attr('disabled', false);
            $('.identification_steps').attr('disabled', false);
            warn_ass.hide()
            $('.expression_steps').attr('disabled', false)
	    warn_exp.hide()
            break;
        }
    });
}

// -----------------------------------------------------------------------------
function setupMappingSteps(){
    // activate/desactivate mapping/identification steps
    var trin_check = $("input[id=trinity]")
    var warn_ass = $('div[id=no_assembly_alert]')
    var warn_exp = $('div[id=no_reads_and_ass_alert]')

    trin_check.change(function(){
        if (trin_check.is(':checked')){
            $('.mapping_steps').attr('disabled', false);
            $('.assembly_qc_steps').attr('disabled', false);
            $('.identification_steps').attr('disabled', false);
            $('.expression_steps').attr('disabled', false);
            warn_ass.hide()
	    warn_exp.hide()
        }else{
            $('.mapping_steps').attr({'disabled': true, 'checked': false});
            $('.assembly_qc_steps').attr({'disabled': true, 'checked': false});
            $('.identification_steps').attr({'disabled': true, 'checked': false});
            $('.expression_steps').attr({'disabled': true, 'checked': false});
            warn_ass.show()
	    warn_exp.show()
        }

    });
}
// -----------------------------------------------------------------------------
function summarizeForm(){

    $('#jobform :input').change(function(){
	$("#formsum_clean").empty()
	$("#formsum_ass").empty()
	$("#formsum_identification").empty()
	$("#formsum_expr").empty()

	$("#formsum_clean").append("
Cleaning step:")
	$(".cleaning_steps").each(function(){
 	     if ( $(this).is(':checked')) {
		var name = $(this).attr('name')
		$("#formsum_clean").append("
" + name + "
")
	    }
	});

	$("#formsum_ass").append("
Assembly/Mapping step:")
	$(".assembly_steps, .assembly_qc_steps, .mapping_steps").each(function(){
	    if ( $(this).is(':checked')) {
		var name = $(this).attr('name')
		$("#formsum_ass").append("
" + name + "
")
	    }
	});
	$("#formsum_identification").append("
Identification step:")
	$(".identification_steps").each(function(){
	    if ( $(this).is(':checked')) {
		var name = $(this).attr('name')
		$("#formsum_identification").append("
" + name + "
")
	    }
	});
	$("#formsum_expr").append("
Expression step:")
	$(".expression_steps").each(function(){
	    if ( $(this).is(':checked')) {
		var name = $(this).attr('name')
		$("#formsum_expr").append("
" + name + "
")
	    }
	});
    });
}<|endoftext|>


<commit_before>var players;
var frames;
var currentFrame;

$(document).ready(function() {
  players = new Players();
  players.fetch({success: function(collection, response){
    var playersView = new PlayersView({collection: players, el: '#players'});
    playersView.render();
  }});

  frames = new Frames();
  var framesView = new FramesView({collection: frames, el: '#frames'});
  frames.fetch({success: function(collection, response){
    framesView.render();
    displayFirstFrame();
  }});

  $('.ballButton').click(function() {
    currentFrame.newStrike(this.value, $('#foul').is(':checked'));
  });

  $('#changePlayer').click(function() {
    currentFrame.changePlayer();
  });

  $('#playerForm').submit(function() {
    var player = new Player();
    var name = $(this).find('input[name="name"]').val();
    player.set('name', name);
    players.create(player);
    $(this).trigger('close');
    $(this).find('input[name="name"]').val('');
    return false;
  });

  $('#frameForm').submit(function() {
    var frame = new Frame();
    var p1_id = $(this).find('select[name="player1"]').val();
    var p2_id = $(this).find('select[name="player2"]').val();
    frame.set('player1', players.get(p1_id));
    frame.set('player2', players.get(p2_id));
    frames.create(frame);
    currentFrame = frame;
    var frameView = new FrameView({model: frame, el: 'currentFrame',
      template: frame_template});
    frameView.render();
    $(this).trigger('close');
    $(this).find('select[name="player1"]').val('');
    $(this).find('select[name="player2"]').val('');
    return false;
  });

  $('#newPlayer').click(function() {
    $('#playerForm').lightbox_me();
  });

  $('#newFrame').click(function() {
    $('#frameForm').lightbox_me();
  });
});

function displayFirstFrame() {
  if (frames.models.length>0) {
    currentFrame = frames.models[0];
    currentFrame.fetchStrikes({
      success: function() {
        var frame_template = Handlebars.compile($('#frame-tmpl').html());
        var frameView = new FrameView({model: currentFrame, el: '#currentFrame',
          template: frame_template});
        frameView.render();
      }
    });
  }
}
<commit_msg>setting focuses when higlighting forms<commit_after>var players;
var frames;
var currentFrame;

$(document).ready(function() {
  players = new Players();
  players.fetch({success: function(collection, response){
    var playersView = new PlayersView({collection: players, el: '#players'});
    playersView.render();
  }});

  frames = new Frames();
  var framesView = new FramesView({collection: frames, el: '#frames'});
  frames.fetch({success: function(collection, response){
    framesView.render();
    displayFirstFrame();
  }});

  $('.ballButton').click(function() {
    currentFrame.newStrike(this.value, $('#foul').is(':checked'));
  });

  $('#changePlayer').click(function() {
    currentFrame.changePlayer();
  });

  $('#playerForm').submit(function() {
    var player = new Player();
    var name = $(this).find('input[name="name"]').val();
    player.set('name', name);
    players.create(player);
    $(this).trigger('close');
    $(this).find('input[name="name"]').val('');
    return false;
  });

  $('#frameForm').submit(function() {
    var frame = new Frame();
    var p1_id = $(this).find('select[name="player1"]').val();
    var p2_id = $(this).find('select[name="player2"]').val();
    frame.set('player1', players.get(p1_id));
    frame.set('player2', players.get(p2_id));
    frames.create(frame);
    currentFrame = frame;
    var frameView = new FrameView({model: frame, el: 'currentFrame',
      template: frame_template});
    frameView.render();
    $(this).trigger('close');
    $(this).find('select[name="player1"]').val('');
    $(this).find('select[name="player2"]').val('');
    return false;
  });

  $('#newPlayer').click(function(e) {
    $('#playerForm').lightbox_me({
      centered: true,
        onLoad: function() {
          $('#playerForm').find('input[name="name"]').focus();
        }
    });
    e.preventDefault();
  });

  $('#newFrame').click(function() {
    $('#frameForm').lightbox_me({
      centered: true,
        onLoad: function() {
          $('#frameForm').find('select[name="player1"]').focus();
        }
    });
  });
});

function displayFirstFrame() {
  if (frames.models.length>0) {
    currentFrame = frames.models[0];
    currentFrame.fetchStrikes({
      success: function() {
        var frame_template = Handlebars.compile($('#frame-tmpl').html());
        var frameView = new FrameView({model: currentFrame, el: '#currentFrame',
          template: frame_template});
        frameView.render();
      }
    });
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright 2009-2012 Eucalyptus Systems, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
 * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
 * additional information or have any questions.
 ************************************************************************/
/* Constants */
var DEPRECATE = false;
var RETURN_KEY_CODE = 13;
var RETURN_MAC_KEY_CODE = 10;
var BACKSPACE_KEY_CODE = 8;

/* CONFIGURABLE */
var REFRESH_INTERVAL_SEC = 10;
var TABLE_REFRESH_INTERVAL_SEC = 20;
var GLOW_DURATION_SEC = 10;
var MAX_PENDING_REQ = 12;
var ID_SEPARATOR = ',';

var DOM_BINDING = {header:'.euca-container .euca-header-container .inner-container',
                   main:'.euca-main-outercontainer .inner-container #euca-main-container',
                   notification:'.euca-container .euca-notification-container .inner-container #euca-notification',
                   explorer:'.euca-explorer-container .inner-container',
                   footer:'.euca-container .euca-footer-container .inner-container',
                   hidden:'.euca-hidden-container',
                  };

var KEY_PATTERN = new RegExp('^[A-Za-z0-9_\s-]{1,256}$');
var VOL_ID_PATTERN = new RegExp('^vol-[A-Za-z0-9]{8}$');

var KEEP_VIEW = 'keep_view';

function escapeHTML(input) {
  return $('
').text(input).html();
}

function asHTML(input) {
  return $('
').append(input).html();
}

function isFunction(obj) {
  return obj && {}.toString.call(obj) == '[object Function]';
}

/** Add Array.indexOf to IE **/
if( !Array.prototype.indexOf ) {
  Array.prototype.indexOf = function(needle) {
    for(var i = 0; i < this.length; i++) {
      if(this[i] === needle) {
        return i;
      }
    }
    return -1;
  };
}

function S4() {
  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function notifySuccess(title, message) {
  $('html body').find(DOM_BINDING['notification']).notification('success', title, message);
}

function notifyError(title, message, proxyMessage, code) {
  var desc = message;
  if (proxyMessage)
    desc += "("+proxyMessage+")";

  $('html body').find(DOM_BINDING['notification']).notification('error', title, desc, code);
}

function allInArray(val_arr, larger_arr){
   var ret = true;
   for (i in val_arr){
     if($.inArray(val_arr[i], larger_arr)<0){
       ret = false;
       break;
     }
   }
   return ret;
}

function onlyInArray(val, array){
  for (i in array) {
    if (array[i] !== val )
      return false;
  }
  return true;
}

var _rqueue = {};
function _delayedExec(cbName, callback){
  if(cbName in _rqueue){
     setTimeout(function() { return _delayedExec(cbName, callback);}, _rqueue[cbName]);
     callback.apply(this);
  }
}

function runRepeat(callback, millisec, startNow){
  var cbName = null;
  do{
    cbName = 'q-'+S4()+'-'+S4();
  }while(cbName in _rqueue);
  _rqueue[cbName] = millisec;
  if(startNow)
    callback.apply(this);
  setTimeout(function(){ return _delayedExec(cbName, callback);}, millisec);
  return cbName;
}

function cancelRepeat (cbName){
  delete _rqueue[cbName];
}

function clearRepeat() {
  _rqueue = {};
}

function describe(resource){
  return $('html body').eucadata('get', resource);
}

function getResource(resourceType, resourceId){
  if (!resourceId)
    return null;
  res = $('html body').eucadata('get', resourceType);
  if (res) {
    for (i in res){
      if (res[i].id && res[i].id.toUpperCase() == resourceId.toUpperCase())
        return res[i];
    }
  } else {
    return null;
  }
}

function refresh(resource){
  return $('html body').eucadata('refresh', resource);
}

function addKeypair(callback){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).keypair();
  $('html body').find(DOM_BINDING['hidden']).keypair('dialogAddKeypair',callback);
}

function addGroup(callback){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).sgroup();
  $('html body').find(DOM_BINDING['hidden']).sgroup('dialogAddGroup',callback);
}

function addSnapshot(volume){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).snapshot();
  $('html body').find(DOM_BINDING['hidden']).snapshot('dialogAddSnapshot', volume);
}

function addVolume(snapshot){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).volume();
  $('html body').find(DOM_BINDING['hidden']).volume('dialogAddVolume', snapshot);
}

function attachVolume(volume, instance){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).volume();
  $('html body').find(DOM_BINDING['hidden']).volume('dialogAttachVolume', volume, instance);
}

function associateIp(instance) {
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).eip({'from_instance' : true});
  $('html body').find(DOM_BINDING['hidden']).eip('dialogAssociateIp', null, instance);
}

function disassociateIp(address){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).eip({'from_instance' : true});
  $('html body').find(DOM_BINDING['hidden']).eip('dialogDisassociateIp', [address]);
}

function allocateIP() {
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).eip();
  $('html body').find(DOM_BINDING['hidden']).eip('createAction');
}

function logout(){
  $.when( // this is to synchronize a chain of ajax calls
    $.ajax({
      type:"POST",
      data:"action=logout&_xsrf="+$.cookie('_xsrf'),
      dataType:"json",
      async:"false", // async option deprecated as of jQuery 1.8
    })).always(function(out){
      $.cookie('session-id','');
      var hostname = null;
      if (location.href && location.href.indexOf('hostname=') >= 0){
        hostname = location.href.substring(location.href.indexOf('hostname='));
        hostname = hostname.replace(/#.+?$/,'');
        hostname = hostname.replace('hostname=','');
        hostname = hostname.replace('#','');
        hostname = hostname.replace('/','');
      }
      if(!hostname)
        hostname = location.hostname;
      var href = '';
      if(location.port && location.port > 0)
        href = location.protocol + '//' + hostname + ':' + location.port + '/';
      else
        href = location.protocol + '//' + hostname + '/';
      location.href=href;
    });
}

function formatDateTime(data) {
 var d = new moment(data);
 return d.format(TIME_FORMAT);
}

function startLaunchWizard(filter) {
  var $container = $('html body').find(DOM_BINDING['main']);
  $container.maincontainer("changeSelected", null, { selected:'launcher', filter: filter});
}

function getErrorMessage(jqXHR) {
  if (jqXHR.status == 504) {
    return $.i18n.prop('general_timeout', ""+cloud_admin+"");
  }
  if (jqXHR && jqXHR.responseText) {
    response = jQuery.parseJSON(jqXHR.responseText);
    return response.message ? response.message : undefined_error;
  } else {
    return undefined_error;
  }
}

function isRootVolume(instanceId, volumeId) {
  var instance = getResource('instance', instanceId);
  if ( instance.root_device_type && instance.root_device_type.toLowerCase() == 'ebs' ) {
    var rootVolume = instance.block_device_mapping[instance.root_device_name];
    if ( rootVolume.volume_id == volumeId ) {
      return true;
    }
  }
  return false;
}

var tableRefreshCallback = null; // hacky..but callback name inside the table breaks with flippy help

function isValidIp(s) {
  var arr = s.split('.');
  if(!arr || arr.length!==4)
    return false;
  for(i in arr){
    var n = parseInt(arr[i]);
    if (!(n >=0 && n<=255)){
      return false;
    }
  }
  return true;
}

function inferImageName(manifest, desc, platform) {
  if(!platform)
    platform='linux';
  var name = platform;
 // Regex '$distro[seperator]$version'
  var inferMap =
    {'rhel5':new RegExp('(rhel|redhat).5','ig'),
     'rhel6':new RegExp('(rhel|redhat).6','ig'),
     'rhel':new RegExp('(rhel|redhat)','ig'),
     'centos5':new RegExp('centos.5','ig'),
     'centos6':new RegExp('centos.6','ig'),
     'centos':new RegExp('centos','ig'),
     'lucid': new RegExp('(lucid|ubuntu.10[\\W\\s]04)','ig'),
     'precise':new RegExp('(precise|ubuntu.12[\\W\\s]04)','ig'),
     'ubuntu':new RegExp('ubuntu','ig'),
     'debian' :new RegExp('debian','ig'),
     'fedora' : new RegExp('fedora','ig'),
     'opensuse' : new RegExp('opensuse','ig'),
     'suse' : new RegExp('suse', 'ig'),
     'gentoo' : new RegExp('gentoo', 'ig'),
     'linux' : new RegExp('linux','ig'),
     'windows' :new RegExp('windows','ig'),
    };
  for (key in inferMap){
    var reg = inferMap[key];
    if(reg.test(manifest) || reg.test(desc)){
      name = key;
      break;
    }
  }
  return name;
}

function errorAndLogout(){
  $('html body').find(DOM_BINDING['hidden']).login();
  $('html body').find(DOM_BINDING['hidden']).login('popupError', $.i18n.prop('connection_failure', 'cloud administrator'), function(){
    logout();
  });
}

<commit_msg>Use translated 'cloud admin' on errors'<commit_after>/*************************************************************************
 * Copyright 2009-2012 Eucalyptus Systems, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
 * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
 * additional information or have any questions.
 ************************************************************************/
/* Constants */
var DEPRECATE = false;
var RETURN_KEY_CODE = 13;
var RETURN_MAC_KEY_CODE = 10;
var BACKSPACE_KEY_CODE = 8;

/* CONFIGURABLE */
var REFRESH_INTERVAL_SEC = 10;
var TABLE_REFRESH_INTERVAL_SEC = 20;
var GLOW_DURATION_SEC = 10;
var MAX_PENDING_REQ = 12;
var ID_SEPARATOR = ',';

var DOM_BINDING = {header:'.euca-container .euca-header-container .inner-container',
                   main:'.euca-main-outercontainer .inner-container #euca-main-container',
                   notification:'.euca-container .euca-notification-container .inner-container #euca-notification',
                   explorer:'.euca-explorer-container .inner-container',
                   footer:'.euca-container .euca-footer-container .inner-container',
                   hidden:'.euca-hidden-container',
                  };

var KEY_PATTERN = new RegExp('^[A-Za-z0-9_\s-]{1,256}$');
var VOL_ID_PATTERN = new RegExp('^vol-[A-Za-z0-9]{8}$');

var KEEP_VIEW = 'keep_view';

function escapeHTML(input) {
  return $('
').text(input).html();
}

function asHTML(input) {
  return $('
').append(input).html();
}

function isFunction(obj) {
  return obj && {}.toString.call(obj) == '[object Function]';
}

/** Add Array.indexOf to IE **/
if( !Array.prototype.indexOf ) {
  Array.prototype.indexOf = function(needle) {
    for(var i = 0; i < this.length; i++) {
      if(this[i] === needle) {
        return i;
      }
    }
    return -1;
  };
}

function S4() {
  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function notifySuccess(title, message) {
  $('html body').find(DOM_BINDING['notification']).notification('success', title, message);
}

function notifyError(title, message, proxyMessage, code) {
  var desc = message;
  if (proxyMessage)
    desc += "("+proxyMessage+")";

  $('html body').find(DOM_BINDING['notification']).notification('error', title, desc, code);
}

function allInArray(val_arr, larger_arr){
   var ret = true;
   for (i in val_arr){
     if($.inArray(val_arr[i], larger_arr)<0){
       ret = false;
       break;
     }
   }
   return ret;
}

function onlyInArray(val, array){
  for (i in array) {
    if (array[i] !== val )
      return false;
  }
  return true;
}

var _rqueue = {};
function _delayedExec(cbName, callback){
  if(cbName in _rqueue){
     setTimeout(function() { return _delayedExec(cbName, callback);}, _rqueue[cbName]);
     callback.apply(this);
  }
}

function runRepeat(callback, millisec, startNow){
  var cbName = null;
  do{
    cbName = 'q-'+S4()+'-'+S4();
  }while(cbName in _rqueue);
  _rqueue[cbName] = millisec;
  if(startNow)
    callback.apply(this);
  setTimeout(function(){ return _delayedExec(cbName, callback);}, millisec);
  return cbName;
}

function cancelRepeat (cbName){
  delete _rqueue[cbName];
}

function clearRepeat() {
  _rqueue = {};
}

function describe(resource){
  return $('html body').eucadata('get', resource);
}

function getResource(resourceType, resourceId){
  if (!resourceId)
    return null;
  res = $('html body').eucadata('get', resourceType);
  if (res) {
    for (i in res){
      if (res[i].id && res[i].id.toUpperCase() == resourceId.toUpperCase())
        return res[i];
    }
  } else {
    return null;
  }
}

function refresh(resource){
  return $('html body').eucadata('refresh', resource);
}

function addKeypair(callback){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).keypair();
  $('html body').find(DOM_BINDING['hidden']).keypair('dialogAddKeypair',callback);
}

function addGroup(callback){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).sgroup();
  $('html body').find(DOM_BINDING['hidden']).sgroup('dialogAddGroup',callback);
}

function addSnapshot(volume){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).snapshot();
  $('html body').find(DOM_BINDING['hidden']).snapshot('dialogAddSnapshot', volume);
}

function addVolume(snapshot){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).volume();
  $('html body').find(DOM_BINDING['hidden']).volume('dialogAddVolume', snapshot);
}

function attachVolume(volume, instance){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).volume();
  $('html body').find(DOM_BINDING['hidden']).volume('dialogAttachVolume', volume, instance);
}

function associateIp(instance) {
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).eip({'from_instance' : true});
  $('html body').find(DOM_BINDING['hidden']).eip('dialogAssociateIp', null, instance);
}

function disassociateIp(address){
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).eip({'from_instance' : true});
  $('html body').find(DOM_BINDING['hidden']).eip('dialogDisassociateIp', [address]);
}

function allocateIP() {
  $('html body').find(DOM_BINDING['hidden']).children().detach();
  $('html body').find(DOM_BINDING['hidden']).eip();
  $('html body').find(DOM_BINDING['hidden']).eip('createAction');
}

function logout(){
  $.when( // this is to synchronize a chain of ajax calls
    $.ajax({
      type:"POST",
      data:"action=logout&_xsrf="+$.cookie('_xsrf'),
      dataType:"json",
      async:"false", // async option deprecated as of jQuery 1.8
    })).always(function(out){
      $.cookie('session-id','');
      var hostname = null;
      if (location.href && location.href.indexOf('hostname=') >= 0){
        hostname = location.href.substring(location.href.indexOf('hostname='));
        hostname = hostname.replace(/#.+?$/,'');
        hostname = hostname.replace('hostname=','');
        hostname = hostname.replace('#','');
        hostname = hostname.replace('/','');
      }
      if(!hostname)
        hostname = location.hostname;
      var href = '';
      if(location.port && location.port > 0)
        href = location.protocol + '//' + hostname + ':' + location.port + '/';
      else
        href = location.protocol + '//' + hostname + '/';
      location.href=href;
    });
}

function formatDateTime(data) {
 var d = new moment(data);
 return d.format(TIME_FORMAT);
}

function startLaunchWizard(filter) {
  var $container = $('html body').find(DOM_BINDING['main']);
  $container.maincontainer("changeSelected", null, { selected:'launcher', filter: filter});
}

function getErrorMessage(jqXHR) {
  if (jqXHR.status == 504) {
    return $.i18n.prop('general_timeout', ""+cloud_admin+"");
  }
  if (jqXHR && jqXHR.responseText) {
    response = jQuery.parseJSON(jqXHR.responseText);
    return response.message ? response.message : undefined_error;
  } else {
    return undefined_error;
  }
}

function isRootVolume(instanceId, volumeId) {
  var instance = getResource('instance', instanceId);
  if ( instance.root_device_type && instance.root_device_type.toLowerCase() == 'ebs' ) {
    var rootVolume = instance.block_device_mapping[instance.root_device_name];
    if ( rootVolume.volume_id == volumeId ) {
      return true;
    }
  }
  return false;
}

var tableRefreshCallback = null; // hacky..but callback name inside the table breaks with flippy help

function isValidIp(s) {
  var arr = s.split('.');
  if(!arr || arr.length!==4)
    return false;
  for(i in arr){
    var n = parseInt(arr[i]);
    if (!(n >=0 && n<=255)){
      return false;
    }
  }
  return true;
}

function inferImageName(manifest, desc, platform) {
  if(!platform)
    platform='linux';
  var name = platform;
 // Regex '$distro[seperator]$version'
  var inferMap =
    {'rhel5':new RegExp('(rhel|redhat).5','ig'),
     'rhel6':new RegExp('(rhel|redhat).6','ig'),
     'rhel':new RegExp('(rhel|redhat)','ig'),
     'centos5':new RegExp('centos.5','ig'),
     'centos6':new RegExp('centos.6','ig'),
     'centos':new RegExp('centos','ig'),
     'lucid': new RegExp('(lucid|ubuntu.10[\\W\\s]04)','ig'),
     'precise':new RegExp('(precise|ubuntu.12[\\W\\s]04)','ig'),
     'ubuntu':new RegExp('ubuntu','ig'),
     'debian' :new RegExp('debian','ig'),
     'fedora' : new RegExp('fedora','ig'),
     'opensuse' : new RegExp('opensuse','ig'),
     'suse' : new RegExp('suse', 'ig'),
     'gentoo' : new RegExp('gentoo', 'ig'),
     'linux' : new RegExp('linux','ig'),
     'windows' :new RegExp('windows','ig'),
    };
  for (key in inferMap){
    var reg = inferMap[key];
    if(reg.test(manifest) || reg.test(desc)){
      name = key;
      break;
    }
  }
  return name;
}

function errorAndLogout(){
  $('html body').find(DOM_BINDING['hidden']).login();
  $('html body').find(DOM_BINDING['hidden']).login('popupError', $.i18n.prop('connection_failure', cloud_admin), function(){
    logout();
  });
}

<|endoftext|>


<commit_before>const Clutter = imports.gi.Clutter;
const Lang = imports.lang;
const Shell = imports.gi.Shell;
const St = imports.gi.St;
const ModalDialog = imports.ui.modalDialog;
const ShellEntry = imports.ui.shellEntry;

const InputDialog = new Lang.Class({
  Name : 'InputDialog',
  Extends : ModalDialog.ModalDialog,

  _callback : null,

  _init: function() {
    this.parent({ styleClass: 'prompt-dialog' });

    /* IMPORTANT
      Gnome 3.18 no longer supports st.table
      see https://github.com/The-Panacea-Projects/Gnomenu/commit/b7dec53593f43dc7686adf78ebc4065dd85a4d27
      for workaround
     */

    // Main box with all widgets
    let mainContentBox = new St.BoxLayout({ style_class: 'prompt-dialog-main-layout', vertical: true });
    this.contentLayout.add(mainContentBox, { x_fill: true, y_fill: false });

    // Message box
    let messageBox = new St.BoxLayout({ style_class: 'prompt-dialog-message-layout', vertical: true });
    mainContentBox.add(messageBox, { y_align: St.Align.START });

    // Subject label
    let subjectLabel = new St.Label({ style_class: 'prompt-dialog-headline', text: "Enter receipient and amount to send:"});

    // Address label and input field
    messageBox.add(subjectLabel, { y_fill:  false, y_align: St.Align.START });

    this._addressEntry = new St.Entry({ style_class: 'prompt-dialog-address-entry', hint_text: "Receipient address", text: "", can_focus: true, reactive: true });
    this._addressEntry.clutter_text.connect('activate', Lang.bind(this, this._onOk)); // call onOk after key press
    this._addressEntry.clutter_text.connect('text-changed', Lang.bind(this, this._updateOkButton)); // enable Send on key press

    // Creates a table and fill box
    let table = new St.Table({ style_class: 'network-dialog-secret-table' });
    table.add(this._addressEntry, { row: 0, col: 0, x_expand: true, x_fill: true, y_align: St.Align.END });
    messageBox.add(table);

    // Amount input field
    this._amountEntry = new St.Entry({ style_class: 'prompt-dialog-address-entry', hint_text: "Amount", text: "", can_focus: true, reactive: true });
    this._amountEntry.clutter_text.connect('activate', Lang.bind(this, this._onOk)); // call onOk after key press
    this._amountEntry.clutter_text.connect('text-changed', Lang.bind(this, this._updateOkButton)); // enable Send on key press

    // Creates a table and fill box
    let table = new St.Table({ style_class: 'network-dialog-secret-table' });
    table.add(this._amountEntry, { row: 0, col: 0, x_expand: true, x_fill: true, y_align: St.Align.END });
    messageBox.add(table);

    // Connect and Unlock buttons
    this._okButton = { label:  _("Send Siacoins"),
                       action: Lang.bind(this, this._onOk),
                       key:    Clutter.KEY_Return,
                     };

    this.setButtons([{ label: _("Cancel"),
                       action: Lang.bind(this, this.cancel),
                       key:    Clutter.KEY_Escape,
                     }, this._okButton]);
  },

  set_callback: function(callback) {
    // Check that callback is a function
    if (callback === undefined || callback === null || typeof callback !== "function"){
      throw TypeError("'callback' needs to be a function.");
    }
    this._callback = callback;
  },

  get_address_entry: function() {
    return this._addressEntry.get_text();
  },

  get_amount_entry: function() {
    return this._amountEntry.get_text();
  },

  _updateOkButton: function() {
    let address = this.get_address_entry();
    let amount  = this.get_amount_entry();

    this._okButton.button.reactive = true; // changes from valid to true
    this._okButton.button.can_focus = true;

    if (address.length != 0 || amount.length != 0)
        this._okButton.button.remove_style_pseudo_class('disabled');
    else
        this._okButton.button.add_style_pseudo_class('disabled');
  },

  _onOk: function() {
    let address = this.get_address_entry();
    let amount  = this.get_amount_entry();

    /* Require one more click to confirm transaction */
    if ( this._okButton.button.label.localeCompare(_("Send Siacoins")) === 0 ) {
      this._okButton.button.label = _("Confirm?");
      return;
    }

    this.close(global.get_current_time());
    this._callback(address, amount);
  },

  cancel: function() {
    this.close(global.get_current_time());
    this._callback(null);
  },
});
<commit_msg>Style fix<commit_after>const Clutter = imports.gi.Clutter;
const Lang = imports.lang;
const Shell = imports.gi.Shell;
const St = imports.gi.St;
const ModalDialog = imports.ui.modalDialog;
const ShellEntry = imports.ui.shellEntry;

const InputDialog = new Lang.Class({
  Name : 'InputDialog',
  Extends : ModalDialog.ModalDialog,

  _callback : null,

  _init: function() {
    this.parent({ styleClass: 'sia-prompt-dialog' });

    /* IMPORTANT
      Gnome 3.18 no longer supports st.table
      see https://github.com/The-Panacea-Projects/Gnomenu/commit/b7dec53593f43dc7686adf78ebc4065dd85a4d27
      for workaround
     */

    // Main box with all widgets
    let mainContentBox = new St.BoxLayout({ style_class: 'prompt-dialog-main-layout', vertical: true });
    this.contentLayout.add(mainContentBox, { x_fill: true, y_fill: false });

    // Message box
    let messageBox = new St.BoxLayout({ style_class: 'prompt-dialog-message-layout', vertical: true });
    mainContentBox.add(messageBox, { y_align: St.Align.START });

    // Subject label
    let subjectLabel = new St.Label({ style_class: 'prompt-dialog-headline', text: "Enter receipient and amount to send:"});

    // Address label and input field
    messageBox.add(subjectLabel, { y_fill:  false, y_align: St.Align.START });

    this._addressEntry = new St.Entry({ style_class: 'prompt-dialog-address-entry', hint_text: "Receipient address", text: "", can_focus: true, reactive: true });
    this._addressEntry.clutter_text.connect('activate', Lang.bind(this, this._onOk)); // call onOk after key press
    this._addressEntry.clutter_text.connect('text-changed', Lang.bind(this, this._updateOkButton)); // enable Send on key press

    // Creates a table and fill box
    let table = new St.Table({ style_class: 'network-dialog-secret-table' });
    table.add(this._addressEntry, { row: 0, col: 0, x_expand: true, x_fill: true, y_align: St.Align.END });
    messageBox.add(table);

    // Amount input field
    this._amountEntry = new St.Entry({ style_class: 'prompt-dialog-address-entry', hint_text: "Amount", text: "", can_focus: true, reactive: true });
    this._amountEntry.clutter_text.connect('activate', Lang.bind(this, this._onOk)); // call onOk after key press
    this._amountEntry.clutter_text.connect('text-changed', Lang.bind(this, this._updateOkButton)); // enable Send on key press

    // Creates a table and fill box
    let table = new St.Table({ style_class: 'network-dialog-secret-table' });
    table.add(this._amountEntry, { row: 0, col: 0, x_expand: true, x_fill: true, y_align: St.Align.END });
    messageBox.add(table);

    // Connect and Unlock buttons
    this._okButton = { label:  _("Send Siacoins"),
                       action: Lang.bind(this, this._onOk),
                       key:    Clutter.KEY_Return,
                     };

    this.setButtons([{ label: _("Cancel"),
                       action: Lang.bind(this, this.cancel),
                       key:    Clutter.KEY_Escape,
                     }, this._okButton]);
  },

  set_callback: function(callback) {
    // Check that callback is a function
    if (callback === undefined || callback === null || typeof callback !== "function"){
      throw TypeError("'callback' needs to be a function.");
    }
    this._callback = callback;
  },

  get_address_entry: function() {
    return this._addressEntry.get_text();
  },

  get_amount_entry: function() {
    return this._amountEntry.get_text();
  },

  _updateOkButton: function() {
    let address = this.get_address_entry();
    let amount  = this.get_amount_entry();

    this._okButton.button.reactive = true; // changes from valid to true
    this._okButton.button.can_focus = true;

    if (address.length != 0 || amount.length != 0)
        this._okButton.button.remove_style_pseudo_class('disabled');
    else
        this._okButton.button.add_style_pseudo_class('disabled');
  },

  _onOk: function() {
    let address = this.get_address_entry();
    let amount  = this.get_amount_entry();

    /* Require one more click to confirm transaction */
    if ( this._okButton.button.label.localeCompare(_("Send Siacoins")) === 0 ) {
      this._okButton.button.label = _("Confirm?");
      return;
    }

    this.close(global.get_current_time());
    this._callback(address, amount);
  },

  cancel: function() {
    this.close(global.get_current_time());
    this._callback(null);
  },
});<|endoftext|>