<commit_before>translate = function() {

    if( options.i18nMode )
        document.body.classList.add('i18nMode'+options.i18nMode)
    if( options.i18nShow )
        document.body.classList.add('i18nShow'+options.i18nShow)

    if( options.i18nMode == 'Load') {
        log('Trakttvstats : translate all...');
        [...document.querySelectorAll('.posters [data-type=movie]')].forEach(i18nMovieThumb);
    }
    else document.onmouseover = translateOnMouseOver;

    var show_page = document.body.matches('.movies.show');
    if ( show_page && !isTranslated(document.body) ) {
        i18nShow(document.body);
        return;
    }
}
translateOnMouseOver = function (event) {
    var target = event.target || event.toElement,
        is_movie = target.getAttribute('data-type') == 'movie',
        movie = is_movie ? target : closest(target, '[data-type=movie]', '.row')

    if( movie ) i18nMovieThumb(movie);
}
isTranslated = function( el ) {
    return el.matches('.translate, .translated');
}
tmdbImageUrl = function(endpath, type, width) {
    var sizes = options.tmdbConfig.images[type+'_sizes'];
    if( !width && sizes.length )
        width = sizes[ Math.floor(sizes.length / 2) ];
    return options.tmdbConfig.images.secure_base_url + width + endpath;
}

api_request_uri = function(path, args) {
    var api_uri = 'https://api.themoviedb.org/3',
        args_str = ''
    for (var i in args)
        args_str += '&' + i + '=' + args[i]
    return api_uri + '/' + path + '?api_key=' + options.tmdbApiKey + encodeURI(args_str)
}

getIMDbID = function ( el ) {
    var imdbID = el.querySelector('.external a[href*="imdb.com/title/"]');
    if( !imdbID ) return;
    return imdbID.href.substr(imdbID.href.lastIndexOf('/') + 1);
}
getShowInfos = function ( el ) {
    var metaname = el.querySelector('meta[itemprop=name]');
    if ( !metaname ) return;
    var infos = {
        name: metaname.getAttribute('content')
    };

    var yearinname = /(.+?) \((\d{4})\)/.exec(infos.name);
    if ( yearinname ) {
        infos.name = yearinname[1];
        infos.year = yearinname[2];
    }
    var year = el.querySelector('.year');
    infos.year = year ? year.innerHTML : infos.year;

    return infos;
}
insertI18nContent = function ( parent, sel, replace, find ) {
    var el = parent.querySelector( sel );
    find = find || el.innerHTML;
    if(find == replace) return;
    el.innerHTML = el.innerHTML.replace( find,
        '' + find + '' +
        '' + replace + ''
    );
}
insertI18nImage = function ( parent, sel, showInfo, callback ) {
    var img = parent.querySelector( sel + ' img.real'),
        img_type = img.parentNode.className == 'poster' ? 'poster' : 'backdrop',
        img_path = showInfo[img_type+'_path'];

    if( !img_path ) {
        if( callback ) callback();
        return;
    }

    var img_i18n = new Image();
    img_i18n.className = 'real i18n';
    img_i18n.src = tmdbImageUrl(img_path, img_type);
    img_i18n.onload = function() {
        img.classList.add('i18n_original');
        img.parentNode.insertBefore(img_i18n, img);
        if( callback ) callback();
    };
}
countryCodeEmoji = function ( countryCode ) {
    if (typeof countryCode !== 'string')
        throw new TypeError('argument must be a string');
    const cc = countryCode.toUpperCase();
    return (/^[A-Z]{2}$/.test(cc))
        ? String.fromCodePoint(...[...cc].map(c => c.charCodeAt() + 127397))
        : null;
}
renderReleasesDates = function ( el, releases ) {
    var releasedEl = Array.prototype.filter.call(
        document.querySelectorAll('.additional-stats li label'), function(x) {
        return x.textContent == 'Released';
    });
    if( !releasedEl ) return;
    var parent = releasedEl[0].parentNode;
    var selectList = document.createElement('select');
    selectList.classList.add('releasesDatesList');
    parent.innerHTML = releasedEl[0].outerHTML;
    parent.appendChild(selectList);

    var dateOptions = { year: 'numeric', month: 'long', day: 'numeric' };
    releases.countries.sort((a, b) => a.release_date.localeCompare(b.release_date));
    releases.countries.forEach(function (country) {
        var option = document.createElement('option');
        selectList.appendChild(option);

        var d = new Date(country.release_date);
        option.text = d.toLocaleDateString(options.i18nLang, dateOptions);
        option.text += ' (' + countryCodeEmoji(country.iso_3166_1) + ')';

        if( country.iso_3166_1.toUpperCase() == options.i18nLang.toUpperCase() )
            option.selected = true;
    });
}
function i18nMovieThumb (el) {
    if( isTranslated(el) ) return;
    el.classList.add('translate');
    var infos = getShowInfos( el );
    if( !infos ) return;
    var args = {
        query: infos.name,
        year: infos.year,
        language: options.i18nLang.toLowerCase()
    };

    callTMDb( 'search/movie', args, function(result) {
        var translateContent = function() {
            insertI18nContent(el, '.titles h3', result.title, infos.name );
            el.classList.remove('translate');
            el.classList.add('translated');
        };
        if( !options.i18nBack ) translateContent();
        else insertI18nImage(el, '', result, translateContent);
    });
}
function i18nShow (el) {
    var imdbID = getIMDbID( el );
    if( !imdbID ) return;
    var args  = {
        language: options.i18nLang.toLowerCase(),
        append_to_response: 'releases'
    }

    callTMDb( 'movie/'+imdbID, args, function(result) {
        var translateContent = function() {
            insertI18nContent(el, 'h1', result.title );
            insertI18nContent(el, '.info [itemprop=description]', result.overview);
            renderReleasesDates(el, result.releases);
            el.classList.add('translated');
        };
        if( !options.i18nBack ) translateContent();
        else insertI18nImage(el, '#info-wrapper', result, translateContent);
    });
}
function callTMDb( path, args, callback) {
    var message = {
        action: 'xhttp',
        url: api_request_uri( path, args )
    };
    chrome.runtime.sendMessage( message, function(msg) {

        if ( !msg.response ) return warn('TMDb : no response for', message.url)

        var response = JSON.parse(msg.response)

        if( !response )
            return warn('TMDb : response object error for', message.url)

        if( response.status_message )
            return warn('TMDb :', path, response.status_message, message.url)

        if( response.total_results ) {
            if( response.total_results == 0 )
                return warn('TMDb : no search results for', args.query, message.url)
            response = response.results[0]
        }

        log( 'Trakttvstats : TMDb', path, response.title, message.url )
        callback( response )
    });
}
<commit_msg>fix title i18n<commit_after>translate = function() {

    if( options.i18nMode )
        document.body.classList.add('i18nMode'+options.i18nMode)
    if( options.i18nShow )
        document.body.classList.add('i18nShow'+options.i18nShow)

    if( options.i18nMode == 'Load') {
        log('Trakttvstats : translate all...');
        [...document.querySelectorAll('.posters [data-type=movie]')].forEach(i18nMovieThumb);
    }
    else document.onmouseover = translateOnMouseOver;

    var show_page = document.body.matches('.movies.show');
    if ( show_page && !isTranslated(document.body) ) {
        i18nShow(document.body);
        return;
    }
}
translateOnMouseOver = function (event) {
    var target = event.target || event.toElement,
        is_movie = target.getAttribute('data-type') == 'movie',
        movie = is_movie ? target : closest(target, '[data-type=movie]', '.row')

    if( movie ) i18nMovieThumb(movie);
}
isTranslated = function( el ) {
    return el.matches('.translate, .translated');
}
tmdbImageUrl = function(endpath, type, width) {
    var sizes = options.tmdbConfig.images[type+'_sizes'];
    if( !width && sizes.length )
        width = sizes[ Math.floor(sizes.length / 2) ];
    return options.tmdbConfig.images.secure_base_url + width + endpath;
}

api_request_uri = function(path, args) {
    var api_uri = 'https://api.themoviedb.org/3',
        args_str = ''
    for (var i in args)
        args_str += '&' + i + '=' + args[i]
    return api_uri + '/' + path + '?api_key=' + options.tmdbApiKey + encodeURI(args_str)
}

getIMDbID = function ( el ) {
    var imdbID = el.querySelector('.external a[href*="imdb.com/title/"]');
    if( !imdbID ) return;
    return imdbID.href.substr(imdbID.href.lastIndexOf('/') + 1);
}
getShowInfos = function ( el ) {
    var metaname = el.querySelector('meta[itemprop=name]');
    if ( !metaname ) return;
    var infos = {
        name: metaname.getAttribute('content')
    };

    var yearinname = /(.+?) \((\d{4})\)/.exec(infos.name);
    if ( yearinname ) {
        infos.name = yearinname[1];
        infos.year = yearinname[2];
    }
    var year = el.querySelector('.year');
    infos.year = year ? year.innerHTML : infos.year;

    return infos;
}
insertI18nContent = function ( parent, sel, replace, find ) {
    var el = parent.querySelector( sel );
    find = find || el.innerHTML;
    if(find == replace) return;
    el.innerHTML = el.innerHTML.replace( find,
        '' + find + '' +
        '' + replace + ''
    );
}
insertI18nImage = function ( parent, sel, showInfo, callback ) {
    var img = parent.querySelector( sel + ' img.real'),
        img_type = img.parentNode.className == 'poster' ? 'poster' : 'backdrop',
        img_path = showInfo[img_type+'_path'];

    if( !img_path ) {
        if( callback ) callback();
        return;
    }

    var img_i18n = new Image();
    img_i18n.className = 'real i18n';
    img_i18n.src = tmdbImageUrl(img_path, img_type);
    img_i18n.onload = function() {
        img.classList.add('i18n_original');
        img.parentNode.insertBefore(img_i18n, img);
        if( callback ) callback();
    };
}
countryCodeEmoji = function ( countryCode ) {
    if (typeof countryCode !== 'string')
        throw new TypeError('argument must be a string');
    const cc = countryCode.toUpperCase();
    return (/^[A-Z]{2}$/.test(cc))
        ? String.fromCodePoint(...[...cc].map(c => c.charCodeAt() + 127397))
        : null;
}
renderReleasesDates = function ( el, releases ) {
    var releasedEl = Array.prototype.filter.call(
        document.querySelectorAll('.additional-stats li label'), function(x) {
        return x.textContent == 'Released';
    });
    if( !releasedEl ) return;
    var parent = releasedEl[0].parentNode;
    var selectList = document.createElement('select');
    selectList.classList.add('releasesDatesList');
    parent.innerHTML = releasedEl[0].outerHTML;
    parent.appendChild(selectList);

    var dateOptions = { year: 'numeric', month: 'long', day: 'numeric' };
    releases.countries.sort((a, b) => a.release_date.localeCompare(b.release_date));
    releases.countries.forEach(function (country) {
        var option = document.createElement('option');
        selectList.appendChild(option);

        var d = new Date(country.release_date);
        option.text = d.toLocaleDateString(options.i18nLang, dateOptions);
        option.text += ' (' + countryCodeEmoji(country.iso_3166_1) + ')';

        if( country.iso_3166_1.toUpperCase() == options.i18nLang.toUpperCase() )
            option.selected = true;
    });
}
function i18nMovieThumb (el) {
    if( isTranslated(el) ) return;
    el.classList.add('translate');
    var infos = getShowInfos( el );
    if( !infos ) return;
    var args = {
        query: infos.name,
        year: infos.year,
        language: options.i18nLang.toLowerCase()
    };

    callTMDb( 'search/movie', args, function(result) {
        var translateContent = function() {
            insertI18nContent(el, '.titles h3', result.title, infos.name );
            el.classList.remove('translate');
            el.classList.add('translated');
        };
        if( !options.i18nBack ) translateContent();
        else insertI18nImage(el, '', result, translateContent);
    });
}
function i18nShow (el) {
    var imdbID = getIMDbID( el );
    if( !imdbID ) return;
    var args  = {
        language: options.i18nLang.toLowerCase(),
        append_to_response: 'releases'
    }

    callTMDb( 'movie/'+imdbID, args, function(result) {
        var translateContent = function() {
            insertI18nContent(el, 'h1', result.title, result.original_title );
            insertI18nContent(el, '.info [itemprop=description]', result.overview);
            renderReleasesDates(el, result.releases);
            el.classList.add('translated');
        };
        if( !options.i18nBack ) translateContent();
        else insertI18nImage(el, '#info-wrapper', result, translateContent);
    });
}
function callTMDb( path, args, callback) {
    var message = {
        action: 'xhttp',
        url: api_request_uri( path, args )
    };
    chrome.runtime.sendMessage( message, function(msg) {

        if ( !msg.response ) return warn('TMDb : no response for', message.url)

        var response = JSON.parse(msg.response)

        if( !response )
            return warn('TMDb : response object error for', message.url)

        if( response.status_message )
            return warn('TMDb :', path, response.status_message, message.url)

        if( response.total_results ) {
            if( response.total_results == 0 )
                return warn('TMDb : no search results for', args.query, message.url)
            response = response.results[0]
        }

        log( 'Trakttvstats : TMDb', path, response.title, message.url )
        callback( response )
    });
}
<|endoftext|>


<commit_before>teamwall.configuration = {
    colorOk:"#6b9c28",
    colorWarning:"#de7424",
    colorBackground:"#373636",
    colorFailure:"#F40E2a",
    colorText:"#e1dbd8",
    font:"Doppio One",
    instrumentBackground:"#454545",
    cssClassSelected : "selected",
    cssClassInstrument : "instrument",
    cssClassDraggable : "draggable",
    instrumentUpdateInterval: 1000
};

<commit_msg>changed warning color to something readable for red/green blind<commit_after>teamwall.configuration = {
    colorOk:"#6b9c28",
    colorWarning:"#fdd749",
    colorBackground:"#373636",
    colorFailure:"#F40E2a",
    colorText:"#e1dbd8",
    font:"Doppio One",
    instrumentBackground:"#454545",
    cssClassSelected : "selected",
    cssClassInstrument : "instrument",
    cssClassDraggable : "draggable",
    instrumentUpdateInterval: 1000
};

<|endoftext|>


<commit_before>var BAC =  Backbone.View.extend({
	el: '#load',

	initialize: function(){
		this.user = new You();
		this.you = this.user.retrieveProfile();
		this.calc= '

<button class="btn btn-default" style="display: block;width: 100%">Beer</button>

<button class="btn btn-warning" style="display: block;width: 100%">Warning</button>

<button class="btn btn-info" style="display: block;width: 100%">Wine</button>

<button class="btn btn-default btn-lg" style="display: block;width: 100%">%BAC%</button><buton class="btn btn-danger">Calculate</button>

Manual Input';
	},

	render: function(){
		this.$el.html(this.calc);
	},

	//Use to recalculate funciton when view is loaded

	/*Notes
	Temporary data - Estamated dummy data
		Beer avg = 0.05;
		Wine avg = 0.11;
		HL avg = 0.4;

	*/

	calcBac: function(oz, weight, gender, hour){
		//Alex
		var test = ((oz * 4.5)/100* (5.14) / (weight * gender) - (0.015 * hour));
		console.log(Math.round(test *100)/100);
		return test;
	}
	/*var weight = 160;
	var gender_male = 0.73;
	var gender_female = 0.66
	var hour = 1;

 beer_bac = function (oz){
var test = ((oz * 4.5)/100* (5.14) / (weight * gender_male) - (0.015 * hour))
//return test;
console.log(Math.round(test *100)/100)
};
beer_bac(36); // numeric value for ounces

wine_bac = function (oz){ //additional function for wine
var test = ((oz * 12)/100* (5.14) / (weight * gender_male) - (0.015 * hour))
console.log(Math.round(test * 100)/100)
};
wine_bac(20); //how many ounces

hardLiqour_bac = function (oz){ //additional function for hard liqour
var test = ((oz * 40)/100* (5.14) / (weight * gender_female) - (0.015 * hour))
console.log(Math.round(test * 100)/100)
};
hardLiqour_bac(6); //ounces */

});
<commit_msg>(Need to refine calculator?)Added BAC functionality in the view<commit_after>var BAC =  Backbone.View.extend({
	el: '#load',

	events: {
		'click #beer': 'calcBACBeer',
		'click #wine': 'calcBACWine',
		'click #hl': 'calcBACHl',
	},

	initialize: function(){
		this.user = new You();
		this.you = this.user.retrieveProfile();
		this.calc= '

<button class="btn btn-default" style="display: block;width: 100%" id="beer">Beer</button>

<button class="btn btn-warning" style="display: block;width: 100%" id="wine">Wine</button>

<button class="btn btn-info" style="display: block;width: 100%" id="hl">Hard Liqour</button>

Your BAC level is:

Manual Input';
	},

	render: function(){
		this.$el.html(this.calc);
	},

	//Use to recalculate funciton when view is loaded

	/*Notes
	Temporary data - Estamated dummy data
		Beer avg = 0.05;
		Wine avg = 0.11;
		HL avg = 0.4;

	*/

	calcBACBeer: function(){
		var bac = this.calcBac(0.05, this.you.weight, this.you.genderBac, 1);
	},

	calcBACWine: function(){
		var bac = this.calcBac(0.11, this.you.weight, this.you.genderBac, 1);

	},

	calcBACHl: function(){
		var bac = this.calcBac(0.4, this.you.weight, this.you.genderBac, 1);
	},

	calcBac: function(oz, weight, gender, hour){
		//Alex
		var bac = ((oz * 4.5)/100* (5.14) / (weight * gender) - (0.015 * hour));
		console.log(Math.round(bac *100)/100);
		$('#BACLevel').empty();
		$('#BACLevel').append(bac);
		return bac;
	}
	/*var weight = 160;
	var gender_male = 0.73;
	var gender_female = 0.66
	var hour = 1;

 beer_bac = function (oz){
var test = ((oz * 4.5)/100* (5.14) / (weight * gender_male) - (0.015 * hour))
//return test;
console.log(Math.round(test *100)/100)
};
beer_bac(36); // numeric value for ounces

wine_bac = function (oz){ //additional function for wine
var test = ((oz * 12)/100* (5.14) / (weight * gender_male) - (0.015 * hour))
console.log(Math.round(test * 100)/100)
};
wine_bac(20); //how many ounces

hardLiqour_bac = function (oz){ //additional function for hard liqour
var test = ((oz * 40)/100* (5.14) / (weight * gender_female) - (0.015 * hour))
console.log(Math.round(test * 100)/100)
};
hardLiqour_bac(6); //ounces */

});
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 */
 "use strict";

var CommandLine = React.createClass({
  componentDidMount: function() {
    // Make the cursor blink.
    var cursor = this.refs.cursor.getDOMNode();
    this.blinkInterval = window.setInterval(function() {
      var currentBgColor = cursor.style.backgroundColor;
      cursor.style.backgroundColor = currentBgColor === "rgb(0, 0, 0)"? "rgb(187, 187, 187)" : "rgb(0, 0, 0)";
      cursor.style.color = currentBgColor === "rgb(0, 0, 0)"? "#aaa" : "#000";
    }.bind(this), 500);
  },
  componentWillUnmount: function() {
    window.clearInterval(this.blinkInterval);
  },
  render: function() {
    return (

        {this.props.prompt + " "}
        {this.props.input}

    )
  }
})

var Terminal = React.createClass({
  // API
  echo: function(string) {
    var lines = this.state.lines;
    lines.push(string);
    this.setState({
      lines: lines,
      pendingCommand: false // so that the command prompt shows.
    });
  },
  error: function(error) {
    this.echo(error);
  },
  // Defaults
  getInitialState: function() {
    return {
      history: [],
      lines: [],
      input: ""
    }
  },
  getDefaultProps: function() {
    return {
      history: true,
      prompt: ">", // string or function
      greetings: "JSX Terminal", // string or function,
      interpreter: function(command) {
        return command;
      } // function or string or object
    }
  },
  // Logic
  componentDidMount: function() {
    var props = this.props;
    if (typeof props.greetings === "function") {
      this.setState({pendingCommand: "greetings"});
      props.greetings(this);
    } else if (typeof props.greetings === "string") {
      var lines = this.state.lines;
      lines.push(props.greetings);
      this.setState({lines: lines});
    }
  },
  handleKeyDown: function(e) {
    var state = this.state,
        input = state.input,
        history = state.history;

    switch (e.which) {
      case 8: // backspace
        // Stop the browser from navigating back.
        e.preventDefault();
        // Remove the last character from input.
        var input = state.input;
        input = input.slice(0, -1);
        this.setState({input: input});
        return false;
      case 38: // Up arrow key
        var existingCommandIdx = _.lastIndexOf(history, input);
        if (existingCommandIdx === -1) {
          // Is typing a command, since it is not in the history, so
          // we retrieve the last command and display it.
          input = history[history.length-1];
          this.setState({history: history, input: input});
        } else {
          // In the middle of moving up the history, so we just display
          // the previous one, or the same input if at the begining.
          input = history[existingCommandIdx-1] || input;
          this.setState({input: input});
        }
        break;
      case 40: // Down arrow key
        var existingCommandIdx = _.lastIndexOf(history, input);
        if (existingCommandIdx !== -1) {
          // Is not typing a command.
          input = history[existingCommandIdx+1] || "";
          this.setState({input: input});
        }
        break;
    }
  },
  handleKeyPress: function(e) {
    var state = this.state,
      history = state.history,
      lines = state.lines,
      input = state.input,
      interpreter = this.props.interpreter;

    switch (e.which) {
      case 13: // Enter
        history.push(input);
        lines.push(this.props.prompt + " " + input);
        this.setState({
          lines: lines,
          history: history,
          pendingCommand: input,
          input: "" // Clear the input
        });

        // Delegate to the interpreter to handle the command.
        // The interpreter should call terminal.echo or terminal.error
        // so that the terminal is re-rendered.
        interpreter(input, this);
        break;
      default:
        input += String.fromCharCode(e.which);
        this.setState({input: input});
        break;
    }
  },
  // Render
  renderLine: function(line, idx) {
    return (

        {line}

    )
  },
  render: function() {
    var props = this.props, state = this.state;
    var terminalStyles = {
      height: props.height
    }
    return (

          {state.lines.map(this.renderLine)}

        {
          !state.pendingCommand? // Do not render the command prompt when waiting for output.
            CommandLine({
              prompt: props.prompt,
              history: state.history,
              style: {width: "100%"},
              input: state.input
          }) : false
        }

    );
  }

});<commit_msg>Use `props.history` to decide to serve history navigation<commit_after>/**
 * @jsx React.DOM
 */
 "use strict";

var CommandLine = React.createClass({
  componentDidMount: function() {
    // Make the cursor blink.
    var cursor = this.refs.cursor.getDOMNode();
    this.blinkInterval = window.setInterval(function() {
      var currentBgColor = cursor.style.backgroundColor;
      cursor.style.backgroundColor = currentBgColor === "rgb(0, 0, 0)"? "rgb(187, 187, 187)" : "rgb(0, 0, 0)";
      cursor.style.color = currentBgColor === "rgb(0, 0, 0)"? "#aaa" : "#000";
    }.bind(this), 500);
  },
  componentWillUnmount: function() {
    window.clearInterval(this.blinkInterval);
  },
  render: function() {
    return (

        {this.props.prompt + " "}
        {this.props.input}

    )
  }
})

var Terminal = React.createClass({
  // API
  echo: function(string) {
    var lines = this.state.lines;
    lines.push(string);
    this.setState({
      lines: lines,
      pendingCommand: false // so that the command prompt shows.
    });
  },
  error: function(error) {
    this.echo(error);
  },
  // Defaults
  getInitialState: function() {
    return {
      history: [],
      lines: [],
      input: ""
    }
  },
  getDefaultProps: function() {
    return {
      history: true,
      prompt: ">", // string or function
      greetings: "JSX Terminal", // string or function,
      interpreter: function(command) {
        return command;
      } // function or string or object
    }
  },
  // Logic
  componentDidMount: function() {
    var props = this.props;
    if (typeof props.greetings === "function") {
      this.setState({pendingCommand: "greetings"});
      props.greetings(this);
    } else if (typeof props.greetings === "string") {
      var lines = this.state.lines;
      lines.push(props.greetings);
      this.setState({lines: lines});
    }
  },
  handleKeyDown: function(e) {
    var state = this.state,
        input = state.input,
        history = state.history;

    switch (e.which) {
      case 8: // backspace
        // Stop the browser from navigating back.
        e.preventDefault();
        // Remove the last character from input.
        var input = state.input;
        input = input.slice(0, -1);
        this.setState({input: input});
        return false;
      case 38: // Up arrow key
        if (!this.props.history) break;

        var existingCommandIdx = _.lastIndexOf(history, input);
        if (existingCommandIdx === -1) {
          // Is typing a command, since it is not in the history, so
          // we retrieve the last command and display it.
          input = history[history.length-1];
          this.setState({history: history, input: input});
        } else {
          // In the middle of moving up the history, so we just display
          // the previous one, or the same input if at the begining.
          input = history[existingCommandIdx-1] || input;
          this.setState({input: input});
        }
        break;
      case 40: // Down arrow key
        if (!this.props.history) break;

        var existingCommandIdx = _.lastIndexOf(history, input);
        if (existingCommandIdx !== -1) {
          // Is not typing a command.
          input = history[existingCommandIdx+1] || "";
          this.setState({input: input});
        }
        break;
    }
  },
  handleKeyPress: function(e) {
    var state = this.state,
      history = state.history,
      lines = state.lines,
      input = state.input,
      interpreter = this.props.interpreter;

    switch (e.which) {
      case 13: // Enter
        history.push(input);
        lines.push(this.props.prompt + " " + input);
        this.setState({
          lines: lines,
          history: history,
          pendingCommand: input,
          input: "" // Clear the input
        });

        // Delegate to the interpreter to handle the command.
        // The interpreter should call terminal.echo or terminal.error
        // so that the terminal is re-rendered.
        interpreter(input, this);
        break;
      default:
        input += String.fromCharCode(e.which);
        this.setState({input: input});
        break;
    }
  },
  // Render
  renderLine: function(line, idx) {
    return (

        {line}

    )
  },
  render: function() {
    var props = this.props, state = this.state;
    var terminalStyles = {
      height: props.height
    }
    return (

          {state.lines.map(this.renderLine)}

        {
          !state.pendingCommand? // Do not render the command prompt when waiting for output.
            CommandLine({
              prompt: props.prompt,
              history: state.history,
              style: {width: "100%"},
              input: state.input
          }) : false
        }

    );
  }

});<|endoftext|>


<commit_before>#! /usr/bin/env node

const net = require('net')
const fs = require('fs')
const path = require('path')
const util = require('util')
const assert = require('assert')
const program = require('commander')
const xTime = require('x-time')
const spawn = require('child_process').spawn
const Tail = require('tail').Tail

const z1 = require('./../remote/index')
const pack = require('./../package.json')
const spam = require('./message')
const features = require('./features')
const parser = require('./parser')

const SPACER = '--'

const argv = process.argv.slice()
let args = []
if(argv.includes(SPACER)) {
  args = argv.splice(argv.indexOf(SPACER))
  args.shift()
}

program
  .version(pack.version)
  .action(function (cmd) {
    handle(new Error(`command "${cmd}" not found`))
  })

program
  .command('resurrect')
  .description('start the apps that were started before exit')
  .action(() => {
    spam.start()
    return z1.resurrect().then(data => {
      spam.stop()
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('start [dir]')
  .usage('[options] [dir] [-- [arguments]]')
  .description('start the app in the dir')
  .option('-n, --name <name>', 'name of your app')
  .option('-p, --ports <ports>', 'ports that your app listens to', parser.ports)
  .option('-w, --workers <workers>', 'count of workers (default: number of CPUs)', parseInt)
  .option('-o, --output <output>', 'directory for the log files of this app', parser.path)
  .option('-e, --env <env>', 'environment variables e.g. NODE_ENV=development', parser.env)
  .action((dir, opts) => {

    // prepare opts
    const opt = {
      name: opts.name,
      workers: opts.workers,
      ports: opts.ports,
      output: opts.output
    }

    // parse environment variables
    const env = Object.assign({}, process.env, opts.env)

    spam.start()
    return z1.start(dir, args, opt, env).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('stop [appName]')
  .description('stop the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the workers get killed')
  .option('-s, --signal <signal>', 'kill signal')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    return z1.stop(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart [appName]')
  .description('restart the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    return z1.restart(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart-all')
  .description('restart all apps')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action(opts => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    return z1.restartAll(opt).then(data => {
      spam.stop()
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('logs [appName]')
  .description('show the output of an app')
  .action((appName = getAppName()) => {
    const configPath = path.join(process.env.HOME, '.z1', 'config.json')

    let config = null
    try {
      config = require(configPath)
    } catch(err) {
      handle(new Error('config.json not found'))
    }

    const app = config.apps.find(e => e.name === appName)
    const output = app.opt.output || path.join(process.env.HOME, '.z1', appName)
    fs.readdir(output, (err, files) => {
      files = files.sort().slice(-2)

      const stderr = new Tail(path.join(output, files[0]))
      const stdout = new Tail(path.join(output, files[1]))

      stderr.on('line', line => {
        console.log(line)
      })
      stdout.on('line', line => {
        console.log(line)
      })

      stderr.on('error', handle)
      stdout.on('error', handle)

      stderr.watch()
      stdout.watch()
    })
  })

program
  .command('list')
  .description('overview of all running workers')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action(opt => {
    return z1.list().then(data => {
      const props = Object.keys(data.stats)

      if(opt.minimal) {
        console.log(props.join(' '))
        return
      }

      if(!props.length) {
        console.log('no workers running')
        return
      }

      const max = process.stdout.columns
      const stuff = '                    '

      console.log(' workers name                 directory')
      for(const prop of props) {
        let obj = data.stats[prop]
        let p = (stuff + obj.pending).substr(-2)
        let a = (stuff + obj.available).substr(-2)
        let k = (stuff + obj.killed).substr(-2)
        let name = (prop + stuff).substr(0, 20)
        let dir = obj.dir.substr(0, max - 30)
        console.log(p, a, k, name, dir)
      }
      console.log(' |  |  |')
      console.log(' |  | killed')
      console.log(' | available')
      console.log('pending')

      if(data.isResurrectable) {
        console.log('\nThe listed apps are currently not running.\nType "z1 resurrect" to start them.')
      }
    }).catch(handle)
  })

program
  .command('exit')
  .description('kill the z1 daemon')
  .action(() => {
    return z1.exit().then(data => {
      console.log('daemon stopped')
    }).catch(handle)
  })

program
  .command('install [feature]')
  .description('install additional features')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action((feature, opts) => {
    // features:
    // zsh (completion)
    // bash (completion)
    // cron (resurrect)

    const folder = path.join(__dirname, '..', 'install')

    if(opts.minimal) {
      Object.keys(features).forEach((feature, i, list) => {
        process.stdout.write(feature)
        if(list[i+1]) {
          process.stdout.write(' ')
        }
      })
      process.stdout.write('\n')

    } else if(!feature) {
      console.log('\nFeatures:\n')
      Object.keys(features).forEach(feature => {
        console.log(`${feature} - ${features[feature]}`)
      })
      console.log()
    } else if (features.hasOwnProperty(feature)) {
      const file = path.join(folder, feature)
      const installer = spawn(file, [], {
        cwd: folder,
        stdio: 'inherit',
        shell: true
      })
      installer.on('error', handle)
      installer.on('exit', (code) => {
        process.exit(code)
      })
    } else {
      handle(new Error('feature not found'))
    }
  })

  program
    .command('uninstall <feature>')
    .description('uninstall features')
    .action((feature, opts) => {

      const folder = path.join(__dirname, '..', 'uninstall')

      if (features.hasOwnProperty(feature)) {
        const file = path.join(folder, feature)
        const uninstaller = spawn(file, [], {
          cwd: folder,
          stdio: 'inherit',
          shell: true
        })
        uninstaller.on('error', handle)
        uninstaller.on('exit', (code) => {
          process.exit(code)
        })
      } else {
        handle(new Error('feature not found'))
      }
    })

if(process.argv.length === 2) {
  handle(new Error('no command given'))
}

program.parse(argv)

function getAppName() {
  log('no appName given')
  log('searching directory for package.json')
  try {
    const file = path.join(process.cwd(), 'package.json')
    const pack = require(file)
    assert(pack.name)
    log(`found name "${pack.name}" in package.json`)
    return pack.name
  } catch(err) {
    console.error(`no package.json file found`)
    handle(new Error('missing argument `appName\''))
  }
}

function log(...msg) {
  if(process.env.DEBUG) {
    console.log(...msg)
  }
}

function handle(err) {
  if(process.env.DEBUG) {
    console.error(err)
  } else {
    console.error(`\n  error: ${err.message}\n`)
  }
  process.exit(1)
}
<commit_msg>fix log command error when app not found<commit_after>#! /usr/bin/env node

const net = require('net')
const fs = require('fs')
const path = require('path')
const util = require('util')
const assert = require('assert')
const program = require('commander')
const xTime = require('x-time')
const spawn = require('child_process').spawn
const Tail = require('tail').Tail

const z1 = require('./../remote/index')
const pack = require('./../package.json')
const spam = require('./message')
const features = require('./features')
const parser = require('./parser')

const SPACER = '--'

const argv = process.argv.slice()
let args = []
if(argv.includes(SPACER)) {
  args = argv.splice(argv.indexOf(SPACER))
  args.shift()
}

program
  .version(pack.version)
  .action(function (cmd) {
    handle(new Error(`command "${cmd}" not found`))
  })

program
  .command('resurrect')
  .description('start the apps that were started before exit')
  .action(() => {
    spam.start()
    return z1.resurrect().then(data => {
      spam.stop()
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('start [dir]')
  .usage('[options] [dir] [-- [arguments]]')
  .description('start the app in the dir')
  .option('-n, --name <name>', 'name of your app')
  .option('-p, --ports <ports>', 'ports that your app listens to', parser.ports)
  .option('-w, --workers <workers>', 'count of workers (default: number of CPUs)', parseInt)
  .option('-o, --output <output>', 'directory for the log files of this app', parser.path)
  .option('-e, --env <env>', 'environment variables e.g. NODE_ENV=development', parser.env)
  .action((dir, opts) => {

    // prepare opts
    const opt = {
      name: opts.name,
      workers: opts.workers,
      ports: opts.ports,
      output: opts.output
    }

    // parse environment variables
    const env = Object.assign({}, process.env, opts.env)

    spam.start()
    return z1.start(dir, args, opt, env).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('stop [appName]')
  .description('stop the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the workers get killed')
  .option('-s, --signal <signal>', 'kill signal')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    return z1.stop(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart [appName]')
  .description('restart the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    return z1.restart(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart-all')
  .description('restart all apps')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action(opts => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    return z1.restartAll(opt).then(data => {
      spam.stop()
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('logs [appName]')
  .description('show the output of an app')
  .action((appName = getAppName()) => {
    const configPath = path.join(process.env.HOME, '.z1', 'config.json')

    let config = null
    try {
      config = require(configPath)
    } catch(err) {
      handle(new Error('config.json not found'))
    }

    const app = config.apps.find(e => e.name === appName)
    if(!app) {
      handle(new Error(`app "${appName}" not found.`))
    }
    const output = app.opt.output || path.join(process.env.HOME, '.z1', appName)
    fs.readdir(output, (err, files) => {
      files = files.sort().slice(-2)

      const stderr = new Tail(path.join(output, files[0]))
      const stdout = new Tail(path.join(output, files[1]))

      stderr.on('line', line => {
        console.log(line)
      })
      stdout.on('line', line => {
        console.log(line)
      })

      stderr.on('error', handle)
      stdout.on('error', handle)

      stderr.watch()
      stdout.watch()
    })
  })

program
  .command('list')
  .description('overview of all running workers')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action(opt => {
    return z1.list().then(data => {
      const props = Object.keys(data.stats)

      if(opt.minimal) {
        console.log(props.join(' '))
        return
      }

      if(!props.length) {
        console.log('no workers running')
        return
      }

      const max = process.stdout.columns
      const stuff = '                    '

      console.log(' workers name                 directory')
      for(const prop of props) {
        let obj = data.stats[prop]
        let p = (stuff + obj.pending).substr(-2)
        let a = (stuff + obj.available).substr(-2)
        let k = (stuff + obj.killed).substr(-2)
        let name = (prop + stuff).substr(0, 20)
        let dir = obj.dir.substr(0, max - 30)
        console.log(p, a, k, name, dir)
      }
      console.log(' |  |  |')
      console.log(' |  | killed')
      console.log(' | available')
      console.log('pending')

      if(data.isResurrectable) {
        console.log('\nThe listed apps are currently not running.\nType "z1 resurrect" to start them.')
      }
    }).catch(handle)
  })

program
  .command('exit')
  .description('kill the z1 daemon')
  .action(() => {
    return z1.exit().then(data => {
      console.log('daemon stopped')
    }).catch(handle)
  })

program
  .command('install [feature]')
  .description('install additional features')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action((feature, opts) => {
    // features:
    // zsh (completion)
    // bash (completion)
    // cron (resurrect)

    const folder = path.join(__dirname, '..', 'install')

    if(opts.minimal) {
      Object.keys(features).forEach((feature, i, list) => {
        process.stdout.write(feature)
        if(list[i+1]) {
          process.stdout.write(' ')
        }
      })
      process.stdout.write('\n')

    } else if(!feature) {
      console.log('\nFeatures:\n')
      Object.keys(features).forEach(feature => {
        console.log(`${feature} - ${features[feature]}`)
      })
      console.log()
    } else if (features.hasOwnProperty(feature)) {
      const file = path.join(folder, feature)
      const installer = spawn(file, [], {
        cwd: folder,
        stdio: 'inherit',
        shell: true
      })
      installer.on('error', handle)
      installer.on('exit', (code) => {
        process.exit(code)
      })
    } else {
      handle(new Error('feature not found'))
    }
  })

  program
    .command('uninstall <feature>')
    .description('uninstall features')
    .action((feature, opts) => {

      const folder = path.join(__dirname, '..', 'uninstall')

      if (features.hasOwnProperty(feature)) {
        const file = path.join(folder, feature)
        const uninstaller = spawn(file, [], {
          cwd: folder,
          stdio: 'inherit',
          shell: true
        })
        uninstaller.on('error', handle)
        uninstaller.on('exit', (code) => {
          process.exit(code)
        })
      } else {
        handle(new Error('feature not found'))
      }
    })

if(process.argv.length === 2) {
  handle(new Error('no command given'))
}

program.parse(argv)

function getAppName() {
  log('no appName given')
  log('searching directory for package.json')
  try {
    const file = path.join(process.cwd(), 'package.json')
    const pack = require(file)
    assert(pack.name)
    log(`found name "${pack.name}" in package.json`)
    return pack.name
  } catch(err) {
    console.error(`no package.json file found`)
    handle(new Error('missing argument `appName\''))
  }
}

function log(...msg) {
  if(process.env.DEBUG) {
    console.log(...msg)
  }
}

function handle(err) {
  if(process.env.DEBUG) {
    console.error(err)
  } else {
    console.error(`\n  error: ${err.message}\n`)
  }
  process.exit(1)
}
<|endoftext|>


<commit_before>/* eslint-env node */

const _ = require('lodash');
const request = require('request');

const ZEUS_HOOK_BASE = process.env.ZEUS_HOOK_BASE;
if (!ZEUS_HOOK_BASE) {
  console.error('ERROR: Missing ZEUS_HOOK_BASE environment variable');
  process.exit(1);
}

let CI_SYSTEM = null;
let BUILD_ID = null;
let JOB_ID = null;

if (process.env.TRAVIS === 'true') {
  CI_SYSTEM = 'travis';
  BUILD_ID = process.env.TRAVIS_BUILD_ID;
  JOB_ID = process.env.TRAVIS_JOB_ID;
}

if (process.env.APPVEYOR === 'True') {
  CI_SYSTEM = 'appveyor';
  BUILD_ID = process.env.APPVEYOR_BUILD_ID;
  JOB_ID = process.env.APPVEYOR_JOB_ID;
}

if (!CI_SYSTEM) {
  console.error('ERROR: No supported CI system detected');
  process.exit(1);
}

require('yargs')
  .demandCommand()
  .command(
    'upload <file> [type]',
    'Upload a build artifact',
    yargs =>
      yargs
        .positional('file', {
          describe: 'Path to the artifact',
          type: 'string'
        })
        .positional('type', {
          describe: 'Mime type of the file to upload',
          type: 'string'
        }),
    argv => {
      const form = _.pick(argv, ['file', 'type']);
      const url = `${ZEUS_HOOK_BASE}/builds/${BUILD_ID}/jobs/${JOB_ID}/artifacts`;
      request.post(url).form(form);
    }
  )
  .help().argv;
<commit_msg>fix: Allow execution from bash<commit_after>#!/usr/bin/env node
/* eslint-env node */

const _ = require('lodash');
const request = require('request');

const ZEUS_HOOK_BASE = process.env.ZEUS_HOOK_BASE;
if (!ZEUS_HOOK_BASE) {
  console.error('ERROR: Missing ZEUS_HOOK_BASE environment variable');
  process.exit(1);
}

let CI_SYSTEM = null;
let BUILD_ID = null;
let JOB_ID = null;

if (process.env.TRAVIS === 'true') {
  CI_SYSTEM = 'travis';
  BUILD_ID = process.env.TRAVIS_BUILD_ID;
  JOB_ID = process.env.TRAVIS_JOB_ID;
}

if (process.env.APPVEYOR === 'True') {
  CI_SYSTEM = 'appveyor';
  BUILD_ID = process.env.APPVEYOR_BUILD_ID;
  JOB_ID = process.env.APPVEYOR_JOB_ID;
}

if (!CI_SYSTEM) {
  console.error('ERROR: No supported CI system detected');
  process.exit(1);
}

require('yargs')
  .demandCommand()
  .command(
    'upload <file> [type]',
    'Upload a build artifact',
    yargs =>
      yargs
        .positional('file', {
          describe: 'Path to the artifact',
          type: 'string'
        })
        .positional('type', {
          describe: 'Mime type of the file to upload',
          type: 'string'
        }),
    argv => {
      const form = _.pick(argv, ['file', 'type']);
      const url = `${ZEUS_HOOK_BASE}/builds/${BUILD_ID}/jobs/${JOB_ID}/artifacts`;
      request.post(url).form(form);
    }
  )
  .help().argv;
<|endoftext|>


<commit_before>//  Import support https://stackoverflow.com/questions/13673346/supporting-both-commonjs-and-amd
(function(name, definition) {
    if (typeof module != "undefined") module.exports = definition();
    else if (typeof define == "function" && typeof define.amd == "object") define(definition);
    else this[name] = definition();
}("clipboard", function() {

  var clipboard = {};

  clipboard.copy = (function() {
    var _intercept = false;
    var _data; // Map from data type (e.g. "text/html") to value.

    document.addEventListener("copy", function(e){
      if (_intercept) {
        _intercept = false;
        for (var key in _data) {
          e.clipboardData.setData(key, _data[key]);
        }
        e.preventDefault();
      }
    });

    return function(data) {
      return new Promise(function(resolve, reject) {
        _intercept = true; // Race condition?
        _data = (typeof data === "string" ? {"text/plain": data} : data);
        try {
          if (document.execCommand("copy")) {
            // document.execCommand is synchronous: http://www.w3.org/TR/2015/WD-clipboard-apis-20150421/#integration-with-rich-text-editing-apis
            // So we can call resolve() back here.
            resolve();
          }
          else {
            _intercept = false;
            reject(new Error("Unable to copy. Perhaps it's not available in your browser?"));
          }
        }
        catch (e) {
          _intercept = false;
          reject(e);
        }
      });
    };
  }());

  clipboard.paste = (function() {
    var _intercept = false;
    var _resolve;
    var _dataType;

    document.addEventListener("paste", function(e) {
      if (_intercept) {
        _intercept = false;
        e.preventDefault();
        _resolve(e.clipboardData.getData(_dataType));
      }
    });

    return function(dataType) {
      return new Promise(function(resolve, reject) {
        _intercept = true; // Race condition?
        _resolve = resolve;
        _dataType = dataType || "text/plain";
        try {
          if (!document.execCommand("paste")) {
            _intercept = false;
            reject(new Error("Unable to paste. Perhaps it's not available in your browser?"));
          }
        } catch (e) {
          _intercept = false;
          reject(new Error(e));
        }
      });
    };
  }());

  // Handle IE behaviour.
  if (typeof ClipboardEvent === "undefined" &&
      typeof window.clipboardData !== "undefined" &&
      typeof window.clipboardData.setData !== "undefined") {

    /*! promise-polyfill 2.0.1 */
    !function(a){function b(a,b){return function(){a.apply(b,arguments)}}function c(a){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],i(a,b(e,this),b(f,this))}function d(a){var b=this;return null===this._state?void this._deferreds.push(a):void j(function(){var c=b._state?a.onFulfilled:a.onRejected;if(null===c)return void(b._state?a.resolve:a.reject)(b._value);var d;try{d=c(b._value)}catch(e){return void a.reject(e)}a.resolve(d)})}function e(a){try{if(a===this)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var c=a.then;if("function"==typeof c)return void i(b(c,a),b(e,this),b(f,this))}this._state=!0,this._value=a,g.call(this)}catch(d){f.call(this,d)}}function f(a){this._state=!1,this._value=a,g.call(this)}function g(){for(var a=0,b=this._deferreds.length;b>a;a++)d.call(this,this._deferreds[a]);this._deferreds=null}function h(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function i(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var j=c.immediateFn||"function"==typeof setImmediate&&setImmediate||function(a){setTimeout(a,1)},k=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)};c.prototype["catch"]=function(a){return this.then(null,a)},c.prototype.then=function(a,b){var e=this;return new c(function(c,f){d.call(e,new h(a,b,c,f))})},c.all=function(){var a=Array.prototype.slice.call(1===arguments.length&&k(arguments[0])?arguments[0]:arguments);return new c(function(b,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}a[f]=g,0===--e&&b(a)}catch(i){c(i)}}if(0===a.length)return b([]);for(var e=a.length,f=0;f<a.length;f++)d(f,a[f])})},c.resolve=function(a){return a&&"object"==typeof a&&a.constructor===c?a:new c(function(b){b(a)})},c.reject=function(a){return new c(function(b,c){c(a)})},c.race=function(a){return new c(function(b,c){for(var d=0,e=a.length;e>d;d++)a[d].then(b,c)})},"undefined"!=typeof module&&module.exports?module.exports=c:a.Promise||(a.Promise=c)}(this);

    clipboard.copy = function(data) {
      return new Promise(function(resolve, reject) {
        // IE supports string and URL types: https://msdn.microsoft.com/en-us/library/ms536744(v=vs.85).aspx
        // We only support the string type for now.
        if (typeof data !== "string" && !("text/plain" in data)) {
          throw new Error("You must provide a text/plain type.")
        }

        var strData = (typeof data === "string" ? data : data["text/plain"]);
        var copySucceeded = window.clipboardData.setData("Text", strData);
        copySucceeded ? resolve() : reject(new Error("Copying was rejected."));
      });
    };

    clipboard.paste = function(data) {
      return new Promise(function(resolve, reject) {
        var strData = window.clipboardData.getData("Text");
        if (strData) {
          resolve(strData);
        } else {
          // The user rejected the paste request.
          reject(new Error("Pasting was rejected."));
        }
      });
    };
  }

  return clipboard;
}));<commit_msg>Remove old comments (incorrectly) speculating about race conditions.<commit_after>//  Import support https://stackoverflow.com/questions/13673346/supporting-both-commonjs-and-amd
(function(name, definition) {
    if (typeof module != "undefined") module.exports = definition();
    else if (typeof define == "function" && typeof define.amd == "object") define(definition);
    else this[name] = definition();
}("clipboard", function() {

  var clipboard = {};

  clipboard.copy = (function() {
    var _intercept = false;
    var _data; // Map from data type (e.g. "text/html") to value.

    document.addEventListener("copy", function(e){
      if (_intercept) {
        _intercept = false;
        for (var key in _data) {
          e.clipboardData.setData(key, _data[key]);
        }
        e.preventDefault();
      }
    });

    return function(data) {
      return new Promise(function(resolve, reject) {
        _intercept = true;
        _data = (typeof data === "string" ? {"text/plain": data} : data);
        try {
          if (document.execCommand("copy")) {
            // document.execCommand is synchronous: http://www.w3.org/TR/2015/WD-clipboard-apis-20150421/#integration-with-rich-text-editing-apis
            // So we can call resolve() back here.
            resolve();
          }
          else {
            _intercept = false;
            reject(new Error("Unable to copy. Perhaps it's not available in your browser?"));
          }
        }
        catch (e) {
          _intercept = false;
          reject(e);
        }
      });
    };
  }());

  clipboard.paste = (function() {
    var _intercept = false;
    var _resolve;
    var _dataType;

    document.addEventListener("paste", function(e) {
      if (_intercept) {
        _intercept = false;
        e.preventDefault();
        _resolve(e.clipboardData.getData(_dataType));
      }
    });

    return function(dataType) {
      return new Promise(function(resolve, reject) {
        _intercept = true;
        _resolve = resolve;
        _dataType = dataType || "text/plain";
        try {
          if (!document.execCommand("paste")) {
            _intercept = false;
            reject(new Error("Unable to paste. Perhaps it's not available in your browser?"));
          }
        } catch (e) {
          _intercept = false;
          reject(new Error(e));
        }
      });
    };
  }());

  // Handle IE behaviour.
  if (typeof ClipboardEvent === "undefined" &&
      typeof window.clipboardData !== "undefined" &&
      typeof window.clipboardData.setData !== "undefined") {

    /*! promise-polyfill 2.0.1 */
    !function(a){function b(a,b){return function(){a.apply(b,arguments)}}function c(a){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],i(a,b(e,this),b(f,this))}function d(a){var b=this;return null===this._state?void this._deferreds.push(a):void j(function(){var c=b._state?a.onFulfilled:a.onRejected;if(null===c)return void(b._state?a.resolve:a.reject)(b._value);var d;try{d=c(b._value)}catch(e){return void a.reject(e)}a.resolve(d)})}function e(a){try{if(a===this)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var c=a.then;if("function"==typeof c)return void i(b(c,a),b(e,this),b(f,this))}this._state=!0,this._value=a,g.call(this)}catch(d){f.call(this,d)}}function f(a){this._state=!1,this._value=a,g.call(this)}function g(){for(var a=0,b=this._deferreds.length;b>a;a++)d.call(this,this._deferreds[a]);this._deferreds=null}function h(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function i(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var j=c.immediateFn||"function"==typeof setImmediate&&setImmediate||function(a){setTimeout(a,1)},k=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)};c.prototype["catch"]=function(a){return this.then(null,a)},c.prototype.then=function(a,b){var e=this;return new c(function(c,f){d.call(e,new h(a,b,c,f))})},c.all=function(){var a=Array.prototype.slice.call(1===arguments.length&&k(arguments[0])?arguments[0]:arguments);return new c(function(b,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}a[f]=g,0===--e&&b(a)}catch(i){c(i)}}if(0===a.length)return b([]);for(var e=a.length,f=0;f<a.length;f++)d(f,a[f])})},c.resolve=function(a){return a&&"object"==typeof a&&a.constructor===c?a:new c(function(b){b(a)})},c.reject=function(a){return new c(function(b,c){c(a)})},c.race=function(a){return new c(function(b,c){for(var d=0,e=a.length;e>d;d++)a[d].then(b,c)})},"undefined"!=typeof module&&module.exports?module.exports=c:a.Promise||(a.Promise=c)}(this);

    clipboard.copy = function(data) {
      return new Promise(function(resolve, reject) {
        // IE supports string and URL types: https://msdn.microsoft.com/en-us/library/ms536744(v=vs.85).aspx
        // We only support the string type for now.
        if (typeof data !== "string" && !("text/plain" in data)) {
          throw new Error("You must provide a text/plain type.")
        }

        var strData = (typeof data === "string" ? data : data["text/plain"]);
        var copySucceeded = window.clipboardData.setData("Text", strData);
        copySucceeded ? resolve() : reject(new Error("Copying was rejected."));
      });
    };

    clipboard.paste = function(data) {
      return new Promise(function(resolve, reject) {
        var strData = window.clipboardData.getData("Text");
        if (strData) {
          resolve(strData);
        } else {
          // The user rejected the paste request.
          reject(new Error("Pasting was rejected."));
        }
      });
    };
  }

  return clipboard;
}));<|endoftext|>


<commit_before>import {CUSTOM_LAUNCHERS} from './browsers.config.js';

const karmaConfig = {};
const sauceLabsConfig = {
	testName: 'NG2 Lab - UNIT',
	startConnect: false,
	recordVideo: false,
	recordScreenshots: false,
	options:  {
		'selenium-version': '2.48.2',
		'command-timeout': 600,
		'idle-timeout': 600,
		'max-duration': 5400
	}
};

if (process.env.TRAVIS) {
	sauceLabsConfig.build = `TRAVIS #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`;
	sauceLabsConfig.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
	// If there are timeouts,
	// switch to ['pooling'].
	karmaConfig.transports = ['websocket'];
}

module.exports = function (config) {
	config.set(Object.assign(karmaConfig, {
		frameworks: [
			'jasmine',
			'jspm'
		],
		reporters: [
			'spec'
		],
		jspm: {
			config: 'jspm.config.js',
			serveFiles: ['tsconfig.json', 'app/**/*!(*.spec).ts', 'typings/**/*.d.ts'],
			loadFiles: [
				'test/setup.ts',
				'app/**/*.spec.ts'
			]
		},
		plugins: [
			'karma-chrome-launcher',
			'karma-jasmine',
			'karma-jspm',
			'karma-sauce-launcher',
			'karma-spec-reporter'
		],
		proxies: {
			'/jspm_packages/': '/base/jspm_packages/',
			'/app/': '/base/app/',
			'/tsconfig.json': '/base/tsconfig.json',
			'/typings/': '/base/typings/'
		},
		customLaunchers: CUSTOM_LAUNCHERS,
		sauceLabs: sauceLabsConfig,
		browsers: [
			'Chrome'
		]
	}));
};
<commit_msg>chore: fix import<commit_after>const {CUSTOM_LAUNCHERS} = require('./browsers.config.js');

const karmaConfig = {};
const sauceLabsConfig = {
	testName: 'NG2 Lab - UNIT',
	startConnect: false,
	recordVideo: false,
	recordScreenshots: false,
	options:  {
		'selenium-version': '2.48.2',
		'command-timeout': 600,
		'idle-timeout': 600,
		'max-duration': 5400
	}
};

if (process.env.TRAVIS) {
	sauceLabsConfig.build = `TRAVIS #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`;
	sauceLabsConfig.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
	// If there are timeouts,
	// switch to ['pooling'].
	karmaConfig.transports = ['websocket'];
}

module.exports = function (config) {
	config.set(Object.assign(karmaConfig, {
		frameworks: [
			'jasmine',
			'jspm'
		],
		reporters: [
			'spec'
		],
		jspm: {
			config: 'jspm.config.js',
			serveFiles: ['tsconfig.json', 'app/**/*!(*.spec).ts', 'typings/**/*.d.ts'],
			loadFiles: [
				'test/setup.ts',
				'app/**/*.spec.ts'
			]
		},
		plugins: [
			'karma-chrome-launcher',
			'karma-jasmine',
			'karma-jspm',
			'karma-sauce-launcher',
			'karma-spec-reporter'
		],
		proxies: {
			'/jspm_packages/': '/base/jspm_packages/',
			'/app/': '/base/app/',
			'/tsconfig.json': '/base/tsconfig.json',
			'/typings/': '/base/typings/'
		},
		customLaunchers: CUSTOM_LAUNCHERS,
		sauceLabs: sauceLabsConfig,
		browsers: [
			'Chrome'
		]
	}));
};
<|endoftext|>


<commit_before>module.exports = function(config) {
  config.set({
    browsers: ['PhantomJS'],
    files: [
      {
        pattern: 'test/*.test.js',
        watched: false
      }
    ],
    frameworks: ['jasmine'],
    preprocessors: {
      'test/*.test.js': ['webpack'],
      'src/*.js': ['coverage']
    },
    reporters: [
      'coverage',
      'progress'
    ],
    coverageReporter: {
      reporters: [
        // generates ./coverage/lcov.info
        {type: 'lcovonly', subdir: '.'},
        // generates ./coverage/coverage-final.json
        {type: 'json', subdir: '.'},
        // For a pretty coverage report in the terminal
        {type: 'text'}
      ]
    },
    webpack: {
      module: {
        loaders: [
          {
            test: /\.js/,
            exclude: /node_modules/,
            loader: 'babel-loader?presets[]=es2015'
          },
          {
            test: /\.js/,
            include: /(src)/,
            loader: 'istanbul-instrumenter-loader',
            query: {
              esModules: true
            }
          }
        ]
      },
      watch: true
    },
    webpackServer: {
      noInfo: true
    }
  });
};
<commit_msg>Explicitly add karma plugins<commit_after>module.exports = function(config) {
  config.set({
    browsers: ['PhantomJS'],
    files: [
      {
        pattern: 'test/*.test.js',
        watched: false
      }
    ],
    frameworks: ['jasmine'],
    preprocessors: {
      'test/*.test.js': ['webpack'],
      'src/*.js': ['coverage']
    },
    plugins: [
      require('karma-coverage'),
      require('karma-jasmine'),
      require('karma-phantomjs-launcher'),
      require('karma-webpack')
    ],
    reporters: [
      'coverage',
      'progress'
    ],
    coverageReporter: {
      reporters: [
        // generates ./coverage/lcov.info
        {type: 'lcovonly', subdir: '.'},
        // generates ./coverage/coverage-final.json
        {type: 'json', subdir: '.'},
        // For a pretty coverage report in the terminal
        {type: 'text'}
      ]
    },
    webpack: {
      module: {
        loaders: [
          {
            test: /\.js/,
            exclude: /node_modules/,
            loader: 'babel-loader?presets[]=es2015'
          },
          {
            test: /\.js/,
            include: /(src)/,
            loader: 'istanbul-instrumenter-loader',
            query: {
              esModules: true
            }
          }
        ]
      },
      watch: true
    },
    webpackServer: {
      noInfo: true
    }
  });
};
<|endoftext|>


<commit_before>/*
 * cactl: poke and prod components of a Cloud Analytics instance
 */

var mod_ca = require('../lib/ca/ca-common');
var mod_caamqp = require('../lib/ca/ca-amqp');
var mod_cap = require('../lib/ca/ca-amqp-cap');
var mod_log = require('../lib/ca/ca-log');
var mod_sys = require('sys');

var cc_timeout_msec = 3 * 1000;		/* timeout after 3s */
var cc_verbose = false;
var cc_cmdswitch = {};			/* dispatch cmds */
var cc_amqp;				/* ca-amqp handle */
var cc_cap;				/* cap wrapper */
var cc_toid;				/* timeout handle */
var cc_cmd;				/* command sent */
var cc_start;				/* time cmd was sent */
var cc_arg0 = process.argv[1];
var cc_help = [
    'usage: cactl <hostname> <command>',
    'Poke a cloud analytics instance via AMQP.',
    '    <hostname> is a routing key identifying a single system',
    '    	hint: try "ca.config" for the config server',
    '    <command> is one of:',
    '	     abort		panic remote service (use with caution)',
    '        ping		check connectivity',
    '        status [-v]	get detailed status info',
    '                           with -v, print additional unstructured info',
    '        log <msg>		report log message'
].join('\n');

function printf()
{
	var text = mod_ca.caSprintf.apply(null, arguments);
	process.stdout.write(text);
}

function main()
{
	if (process.argv.length <= 2)
		usage();

	var broker = mod_ca.caBroker();
	var sysinfo = mod_ca.caSysinfo('cactl', '0.1');
	var hostname = sysinfo.ca_hostname+ '.' + process.pid;
	var log = new mod_log.caLog({ out: process.stdout });

	cc_amqp = new mod_caamqp.caAmqp({
		broker: broker,
		exchange: mod_ca.ca_amqp_exchange,
		exchange_opts: mod_ca.ca_amqp_exchange_opts,
		basename: mod_ca.ca_amqp_key_base_tool,
		hostname: hostname,
		bindings: [],
		log: log
	});
	cc_amqp.on('amqp-error', function (err) {
		die('amqp: %s', err.message);
	});
	cc_amqp.on('amqp-fatal', function (err) {
		die('amqp: %s', err.message);
	});

	cc_cap = new mod_cap.capAmqpCap({
	    log: log, amqp: cc_amqp, sysinfo: sysinfo
	});
	cc_cap.on('msg-ack-abort', ccAckAbort);
	cc_cap.on('msg-ack-ping', ccAckPing);
	cc_cap.on('msg-ack-status', ccAckStatus);

	cc_amqp.start(ccRunCmd);
}

function usage(msg)
{
	if (msg)
		printf('%s: %s\n', cc_arg0, msg);
	printf('%s\n', cc_help);
	process.exit(2);
}

function die()
{
	var text = mod_ca.caSprintf.apply(null, arguments);
	printf('%s: fatal error: %s\n', cc_arg0, text);
	process.exit(1);
}

function shutdown()
{
	cc_amqp.stop();
}

function ccTimeout()
{
	printf('Timed out.\n');
	process.exit(3);
}

function ccRunCmd()
{
	var destkey = process.argv[2];
	var msg;

	cc_cmd = process.argv[3];

	cc_verbose = process.argv.length > 4 &&
	    process.argv[4] == '-v';

	if (!(cc_cmd in cc_cmdswitch))
		usage('unrecognized command: ' + cc_cmd);

	msg = cc_cmdswitch[cc_cmd](cc_cmd);
	cc_start = new Date();
	cc_cap.send(destkey, msg);

	if (msg.ca_type == 'cmd')
		cc_toid = setTimeout(ccTimeout, cc_timeout_msec);
	else
		shutdown();
}

function ccRunCmdCmd(cmd)
{
	var msg = {};

	msg.ca_type = 'cmd';
	msg.ca_subtype = cmd;
	msg.ca_id = 1;

	return (msg);
}

cc_cmdswitch['abort'] = ccRunCmdCmd;
cc_cmdswitch['ping'] = ccRunCmdCmd;
cc_cmdswitch['status'] = ccRunCmdCmd;

function ccRunLogCmd()
{
	var msg = {};

	if (process.argv.length < 5)
		usage('missing log message');

	msg.ca_type = 'notify';
	msg.ca_subtype = 'log';
	msg.l_message = process.argv[4];

	return (msg);
}

cc_cmdswitch['log'] = ccRunLogCmd;

function ccCheckMsg(msg)
{
	var end = new Date();
	var millis = end.getTime() - cc_start.getTime();

	if (msg.ca_subtype !== cc_cmd)
		die('response message had wrong subtype: %s', msg.ca_subtype);

	if (msg.ca_id !== 1)
		die('response message had wrong id: %s', msg.ca_id);

	printf('%-12s %d ms\n', 'Latency:', millis);
	clearTimeout(cc_toid);
}

function ccAckAbort(msg)
{
	ccCheckMsg(msg);
	printf('%-12s %s\n', 'Hostname:', msg.ca_hostname);
	printf('%-12s %s\n', 'Route key:', msg.ca_source);
	printf('%-12s %s/%s\n', 'Agent:', msg.ca_agent_name,
	    msg.ca_agent_version);
	printf('%-12s %s %s %s\n', 'OS:', msg.ca_os_name,
	    msg.ca_os_release, msg.ca_os_revision);
	printf('abort request %s\n', msg.a_ok ? 'accepted': 'rejected');
	shutdown();
}

function ccAckPing(msg)
{
	ccCheckMsg(msg);
	printf('%-12s %s\n', 'Hostname:', msg.ca_hostname);
	printf('%-12s %s\n', 'Route key:', msg.ca_source);
	printf('%-12s %s/%s\n', 'Agent:', msg.ca_agent_name,
	    msg.ca_agent_version);
	printf('%-12s %s %s %s\n', 'OS:', msg.ca_os_name,
	    msg.ca_os_release, msg.ca_os_revision);
	shutdown();
}

function ccAckStatus(msg)
{
	var elts, elt, fields, ii, jj;
	var metric, decomp;

	ccCheckMsg(msg);
	printf('%-12s %s\n', 'Hostname:', msg.ca_hostname);
	printf('%-12s %s\n', 'Route key:', msg.ca_source);
	printf('%-12s %s/%s\n', 'Agent:', msg.ca_agent_name,
	    msg.ca_agent_version);
	printf('%-12s %s %s %s\n', 'OS:', msg.ca_os_name,
	    msg.ca_os_release, msg.ca_os_revision);
	printf('%-12s %s\n', 'Component:', msg.s_component);

	switch (msg.s_component) {
	case 'config':
		elts = msg.s_aggregators;
		printf('%-28s    %-7s\n', 'AGGREGATORS', 'ACTIVE');
		for (ii = 0; ii < elts.length; ii++)
			printf('  %3d.  %-20s    %6d\n', ii + 1,
			    elts[ii].sia_hostname, elts[ii].sia_ninsts);

		elts = msg.s_instrumenters;
		printf('%-28s    %-7s    %-6s\n', 'INSTRUMENTERS',
		    'ACTIVE', 'METRICS');
		for (ii = 0; ii < elts.length; ii++)
			printf('  %3d.  %-20s    %6d    %7d\n', ii + 1,
			    elts[ii].sii_hostname, elts[ii].sii_ninsts,
			    elts[ii].sii_nmetrics_avail);
		break;

	case 'instrumenter':
		elts = msg.s_instrumentations;
		if (elts.length > 0)
			printf('%-6s  %-20s  %-5s  %s\n', 'INSTID', 'METRIC',
			    'PRED?', 'DECOMP');
		for (ii = 0; ii < elts.length; ii++) {
			metric = mod_ca.caSprintf('%s.%s',
			    elts[ii].s_module, elts[ii].s_stat);
			decomp = elts[ii].s_decomposition.join(', ');
			if (!decomp)
				decomp = 'None';
			printf('%6s  %-20s  %-5s  %s\n', elts[ii].s_inst_id,
			    metric, elts[ii].s_predicate.length > 0 ?
			    'Yes' : 'No',
			    decomp);
		}

		elts = msg.s_modules;
		if (elts.length > 0)
			printf('  %-45s  %-8s %s\n', 'METRIC', 'TYPE',
			    'FIELDS');

		for (ii = 0; ii < elts.length; ii++) {
			for (jj = 0; jj < elts[ii].cam_stats.length; jj++) {
				elt = elts[ii].cam_stats[jj];
				metric = mod_ca.caSprintf('%s: %s',
				    elts[ii].cam_description,
				    elt.cas_description);
				fields = elt.cas_fields.map(function (field) {
					return (field.caf_name);
				});

				decomp = 'None';
				if (fields.length > 0)
					decomp = fields.join(', ');

				printf('  %-45s  %-8s %s\n', metric,
				    elt.cas_type, decomp);
			}
		}

		break;

	case 'aggregator':
		elts = msg.s_instrumentations;
		if (elts.length > 0) {
			printf('Active instrumentations:   (%d total)\n',
			    elts.length);
			printf('    %-6s  %-8s  %-27s  %-27s\n', 'INSTID',
			    'NSOURCES', 'SINCE', 'LAST');
		}

		for (ii = 0; ii < elts.length; ii++) {
			printf('    %6s  %8d  %27s  %27s\n',
			    elts[ii].s_inst_id, elts[ii].s_nsources,
			    mod_ca.caFormatDate(new Date(
			    Date.parse(elts[ii].s_since))),
			    mod_ca.caFormatDate(
			    new Date(elts[ii].s_last * 1000)));
		}

		break;

	default:
		printf('unknown component type\n');
		break;
	}

	if (msg.s_status && cc_verbose) {
		printf('additional unstructured status information:\n');
		printf('%j\n', msg.s_status);
	}

	shutdown();
}

main();
<commit_msg>INTRO-356 cactl ca.config status prints NaN in METRICS column<commit_after>/*
 * cactl: poke and prod components of a Cloud Analytics instance
 */

var mod_ca = require('../lib/ca/ca-common');
var mod_caamqp = require('../lib/ca/ca-amqp');
var mod_cap = require('../lib/ca/ca-amqp-cap');
var mod_log = require('../lib/ca/ca-log');
var mod_sys = require('sys');

var cc_timeout_msec = 3 * 1000;		/* timeout after 3s */
var cc_verbose = false;
var cc_cmdswitch = {};			/* dispatch cmds */
var cc_amqp;				/* ca-amqp handle */
var cc_cap;				/* cap wrapper */
var cc_toid;				/* timeout handle */
var cc_cmd;				/* command sent */
var cc_start;				/* time cmd was sent */
var cc_arg0 = process.argv[1];
var cc_help = [
    'usage: cactl <hostname> <command>',
    'Poke a cloud analytics instance via AMQP.',
    '    <hostname> is a routing key identifying a single system',
    '    	hint: try "ca.config" for the config server',
    '    <command> is one of:',
    '	     abort		panic remote service (use with caution)',
    '        ping		check connectivity',
    '        status [-v]	get detailed status info',
    '                           with -v, print additional unstructured info',
    '        log <msg>		report log message'
].join('\n');

function printf()
{
	var text = mod_ca.caSprintf.apply(null, arguments);
	process.stdout.write(text);
}

function main()
{
	if (process.argv.length <= 2)
		usage();

	var broker = mod_ca.caBroker();
	var sysinfo = mod_ca.caSysinfo('cactl', '0.1');
	var hostname = sysinfo.ca_hostname+ '.' + process.pid;
	var log = new mod_log.caLog({ out: process.stdout });

	cc_amqp = new mod_caamqp.caAmqp({
		broker: broker,
		exchange: mod_ca.ca_amqp_exchange,
		exchange_opts: mod_ca.ca_amqp_exchange_opts,
		basename: mod_ca.ca_amqp_key_base_tool,
		hostname: hostname,
		bindings: [],
		log: log
	});
	cc_amqp.on('amqp-error', function (err) {
		die('amqp: %s', err.message);
	});
	cc_amqp.on('amqp-fatal', function (err) {
		die('amqp: %s', err.message);
	});

	cc_cap = new mod_cap.capAmqpCap({
	    log: log, amqp: cc_amqp, sysinfo: sysinfo
	});
	cc_cap.on('msg-ack-abort', ccAckAbort);
	cc_cap.on('msg-ack-ping', ccAckPing);
	cc_cap.on('msg-ack-status', ccAckStatus);

	cc_amqp.start(ccRunCmd);
}

function usage(msg)
{
	if (msg)
		printf('%s: %s\n', cc_arg0, msg);
	printf('%s\n', cc_help);
	process.exit(2);
}

function die()
{
	var text = mod_ca.caSprintf.apply(null, arguments);
	printf('%s: fatal error: %s\n', cc_arg0, text);
	process.exit(1);
}

function shutdown()
{
	cc_amqp.stop();
}

function ccTimeout()
{
	printf('Timed out.\n');
	process.exit(3);
}

function ccRunCmd()
{
	var destkey = process.argv[2];
	var msg;

	cc_cmd = process.argv[3];

	cc_verbose = process.argv.length > 4 &&
	    process.argv[4] == '-v';

	if (!(cc_cmd in cc_cmdswitch))
		usage('unrecognized command: ' + cc_cmd);

	msg = cc_cmdswitch[cc_cmd](cc_cmd);
	cc_start = new Date();
	cc_cap.send(destkey, msg);

	if (msg.ca_type == 'cmd')
		cc_toid = setTimeout(ccTimeout, cc_timeout_msec);
	else
		shutdown();
}

function ccRunCmdCmd(cmd)
{
	var msg = {};

	msg.ca_type = 'cmd';
	msg.ca_subtype = cmd;
	msg.ca_id = 1;

	return (msg);
}

cc_cmdswitch['abort'] = ccRunCmdCmd;
cc_cmdswitch['ping'] = ccRunCmdCmd;
cc_cmdswitch['status'] = ccRunCmdCmd;

function ccRunLogCmd()
{
	var msg = {};

	if (process.argv.length < 5)
		usage('missing log message');

	msg.ca_type = 'notify';
	msg.ca_subtype = 'log';
	msg.l_message = process.argv[4];

	return (msg);
}

cc_cmdswitch['log'] = ccRunLogCmd;

function ccCheckMsg(msg)
{
	var end = new Date();
	var millis = end.getTime() - cc_start.getTime();

	if (msg.ca_subtype !== cc_cmd)
		die('response message had wrong subtype: %s', msg.ca_subtype);

	if (msg.ca_id !== 1)
		die('response message had wrong id: %s', msg.ca_id);

	printf('%-12s %d ms\n', 'Latency:', millis);
	clearTimeout(cc_toid);
}

function ccAckAbort(msg)
{
	ccCheckMsg(msg);
	printf('%-12s %s\n', 'Hostname:', msg.ca_hostname);
	printf('%-12s %s\n', 'Route key:', msg.ca_source);
	printf('%-12s %s/%s\n', 'Agent:', msg.ca_agent_name,
	    msg.ca_agent_version);
	printf('%-12s %s %s %s\n', 'OS:', msg.ca_os_name,
	    msg.ca_os_release, msg.ca_os_revision);
	printf('abort request %s\n', msg.a_ok ? 'accepted': 'rejected');
	shutdown();
}

function ccAckPing(msg)
{
	ccCheckMsg(msg);
	printf('%-12s %s\n', 'Hostname:', msg.ca_hostname);
	printf('%-12s %s\n', 'Route key:', msg.ca_source);
	printf('%-12s %s/%s\n', 'Agent:', msg.ca_agent_name,
	    msg.ca_agent_version);
	printf('%-12s %s %s %s\n', 'OS:', msg.ca_os_name,
	    msg.ca_os_release, msg.ca_os_revision);
	shutdown();
}

function ccAckStatus(msg)
{
	var elts, elt, fields, ii, jj;
	var metric, decomp;

	ccCheckMsg(msg);
	printf('%-12s %s\n', 'Hostname:', msg.ca_hostname);
	printf('%-12s %s\n', 'Route key:', msg.ca_source);
	printf('%-12s %s/%s\n', 'Agent:', msg.ca_agent_name,
	    msg.ca_agent_version);
	printf('%-12s %s %s %s\n', 'OS:', msg.ca_os_name,
	    msg.ca_os_release, msg.ca_os_revision);
	printf('%-12s %s\n', 'Component:', msg.s_component);

	switch (msg.s_component) {
	case 'config':
		elts = msg.s_aggregators;
		printf('%-28s    %-7s\n', 'AGGREGATORS', 'ACTIVE');
		for (ii = 0; ii < elts.length; ii++)
			printf('  %3d.  %-20s    %6d\n', ii + 1,
			    elts[ii].sia_hostname, elts[ii].sia_ninsts);

		elts = msg.s_instrumenters;
		printf('%-28s    %-7s\n', 'INSTRUMENTERS', 'ACTIVE');
		for (ii = 0; ii < elts.length; ii++)
			printf('  %3d.  %-20s    %6d\n', ii + 1,
			    elts[ii].sii_hostname, elts[ii].sii_ninsts);
		break;

	case 'instrumenter':
		elts = msg.s_instrumentations;
		if (elts.length > 0)
			printf('%-6s  %-20s  %-5s  %s\n', 'INSTID', 'METRIC',
			    'PRED?', 'DECOMP');
		for (ii = 0; ii < elts.length; ii++) {
			metric = mod_ca.caSprintf('%s.%s',
			    elts[ii].s_module, elts[ii].s_stat);
			decomp = elts[ii].s_decomposition.join(', ');
			if (!decomp)
				decomp = 'None';
			printf('%6s  %-20s  %-5s  %s\n', elts[ii].s_inst_id,
			    metric, elts[ii].s_predicate.length > 0 ?
			    'Yes' : 'No',
			    decomp);
		}

		elts = msg.s_modules;
		if (elts.length > 0)
			printf('  %-45s  %-8s %s\n', 'METRIC', 'TYPE',
			    'FIELDS');

		for (ii = 0; ii < elts.length; ii++) {
			for (jj = 0; jj < elts[ii].cam_stats.length; jj++) {
				elt = elts[ii].cam_stats[jj];
				metric = mod_ca.caSprintf('%s: %s',
				    elts[ii].cam_description,
				    elt.cas_description);
				fields = elt.cas_fields.map(function (field) {
					return (field.caf_name);
				});

				decomp = 'None';
				if (fields.length > 0)
					decomp = fields.join(', ');

				printf('  %-45s  %-8s %s\n', metric,
				    elt.cas_type, decomp);
			}
		}

		break;

	case 'aggregator':
		elts = msg.s_instrumentations;
		if (elts.length > 0) {
			printf('Active instrumentations:   (%d total)\n',
			    elts.length);
			printf('    %-6s  %-8s  %-27s  %-27s\n', 'INSTID',
			    'NSOURCES', 'SINCE', 'LAST');
		}

		for (ii = 0; ii < elts.length; ii++) {
			printf('    %6s  %8d  %27s  %27s\n',
			    elts[ii].s_inst_id, elts[ii].s_nsources,
			    mod_ca.caFormatDate(new Date(
			    Date.parse(elts[ii].s_since))),
			    mod_ca.caFormatDate(
			    new Date(elts[ii].s_last * 1000)));
		}

		break;

	default:
		printf('unknown component type\n');
		break;
	}

	if (msg.s_status && cc_verbose) {
		printf('additional unstructured status information:\n');
		printf('%j\n', msg.s_status);
	}

	shutdown();
}

main();
<|endoftext|>


<commit_before>'use strict'

module.exports = function (directory, read, load) {
  return function (name, callback) {
    make(name, function (err, code) {
      if (err) {
        callback(err)
      } else {
        callback(null, code)
      }
    })
  }

  function make (name, callback) {
    read(name, function (err, template) {
      var lines = template.split(/\s*(@.*)\n/g)
      var code = []
      var _extends = false
      var dependencies = []
      var sections = []
      var partials = []
      var imports = []
      var vars = []
      var ends = []

      if (err) {
        callback(err)
      } else {
        code = code.concat(compile(lines))

        Promise.all(dependencies).then(function () {
          var codePromise = Promise.resolve(code)

          if (_extends) {
            codePromise = new Promise(function (resolve, reject) {
              make(_extends, function (err, code) {
                if (err) {
                  reject(err)
                } else {
                  resolve()
                }
              })
            })
          }

          codePromise.then(function (_code) {
            var code = []

            if (!_extends) {
              sections.push(`render(content) {
                var output = []

                ${ _code.join('\n') }

                return output.join('\\n')
              }`)
            }

            code.unshift('function template(content) { return sections.render(content) }')

            code.unshift('var sections = new Sections()')

            code.unshift('}')

            code = [].concat(sections, code)

            code.unshift('class Sections' + (_extends ? ' extends ParentSections' : '') + ' {')

            if (_extends) {
              code.unshift('var ParentSections = require("' + directory + _extends + '.js").Sections')
            }

            if (vars.length) {
              code.unshift('var ' + vars.join(', '))
            }

            Object.keys(imports).forEach(function (k) {
              code.unshift('var ' + k + ' = require("' + directory + imports[k] + '.js").partials.' + k)
            })

            code.unshift('var escape = require("' + directory + '.core.js").escape')
            code.unshift('var safe = require("' + directory + '.core.js").safe')

            code.unshift('"use strict"')

            code = code.concat(Object.keys(partials).map(function (k) {
              return partials[k]
            }))

            code.push('template.Sections = Sections')

            code.push('template.partials = {}')

            Object.keys(partials).forEach(function (k) {
              code.push('template.partials.' + k + ' = ' + k)
            })

            code.push('module.exports = template')

            callback(null, code)

          }).catch(callback)

        }).catch(callback)
      }

      function compile (lines) {
        var code = []

        while (lines.length) {
          let line = lines.shift()
          let trimmed = line.trim()
          let parts = trimmed.substr(1).split(/\s+/)
          let directive = parts[0]
          let args = parts.slice(1)
          let arg0 = args[0]
          let func = []
          let level

          if (trimmed.startsWith('@')) {
            if (trimmed === '@') {
              code.push(ends.shift())
            } else {
              if (['section', 'partial'].indexOf(directive) > -1) {
                level = 1
                while (level) {
                  let line = lines.shift() || ''
                  let trimmed = line.trim()

                  if (trimmed === '@') {
                    level -= 1
                    if (level) {
                      func.push(line)
                    }
                  } else {
                    if (trimmed.startsWith('@') && ['if', 'each', 'section', 'partial'].indexOf(trimmed.substr(1).split(/\s+/)[0]) > -1) {
                      level += 1
                    }

                    func.push(line)
                  }
                }
              }

              switch (directive) {
                case 'extends':
                  _extends = arg0
                  dependencies.push(new Promise(function (resolve, reject) {
                    load(arg0, function (err) {
                      if (err) {
                        reject(err)
                      } else {
                        resolve()
                      }
                    })
                  }))
                  break

                case 'embed':
                  code.push('output.push(require("' + directory + arg0 + '.js")(content))')
                  dependencies.push(new Promise(function (resolve, reject) {
                    load(arg0, function (err) {
                      if (err) {
                        reject(err)
                      } else {
                        resolve()
                      }
                    })
                  }))
                  break

                case 'set':
                  code.push(arg0 + ' = ' + args.slice(1).join(' '))
                  vars.push(arg0)
                  break

                case 'yield':
                  code.push('output = output.concat(this.' + arg0 + '(content))')
                  break

                case 'parent':
                  code.push('output = output.concat(super(content))')
                  break

                case 'section':
                  code.push('output = output.concat(this.' + arg0 + '(content))')
                  sections.push(`${ arg0 }(content) {
                    var output = []
                    ${ compile(func).join('\n') }
                    return output
                  }`)
                  break

                case 'import':
                  imports[arg0] = args.slice(1).join(' ')
                  dependencies.push(new Promise(function (resolve, reject) {
                    load(args.slice(1).join(' '), function (err) {
                      if (err) {
                        reject(err)
                      } else {
                        resolve()
                      }
                    })
                  }))
                  break

                case 'partial':
                  if (!partials[arg0]) {
                    partials[arg0] = `function ${ arg0 }(${ args.slice(1).join(', ') }) {
                      var output = []
                      ${ compile(func).join('\n') }
                      return safe(output.join('\\n'))
                    }`
                  }
                  break

                case 'each':
                  code.push('if (Array.isArray(' + arg0 + ')) { output = output.concat(' + arg0 + '.map(function(' + args.slice(1).join(', ') + ') { var output = [] ')
                  ends.unshift("return output.join('\\n') })) }")
                  break

                case 'if':
                  code.push('if(' + args.join(' ') + ') {')
                  ends.unshift('}')
                  break

                case 'elseif':
                  if (ends.length) {
                    code.push(ends.shift())
                  } else {
                    code.push('if (false) {')
                  }
                  code.push('else if(' + args.join(' ') + ') {')
                  ends.unshift('}')
                  break

                case 'else':
                  if (ends.length) {
                    code.push(ends.shift())
                  } else {
                    code.push('if (false) {')
                  }
                  code.push('else {')
                  ends.unshift('}')
                  break
              }
            }
          } else if (line.trim().length) {
            code.push('output.push(escape`' + line.replace('`', '\\`') + '`)')
          }
        }

        return code
      }
    })
  }
}
<commit_msg>Unwind some stuff<commit_after>'use strict'

module.exports = function (directory, read, load) {
  return function (name, callback) {
    make(name, function (err, code) {
      if (err) {
        callback(err)
      } else {
        callback(null, code)
      }
    })
  }

  function make (name, callback) {
    read(name, function (err, template) {
      var lines = template.split(/\s*(@.*)\n/g)
      var renderCode = []
      var _extends = false
      var dependencies = []
      var sections = []
      var partials = []
      var imports = []
      var vars = []
      var ends = []

      if (err) {
        callback(err)
      } else {
        renderCode = renderCode.concat(compile(lines))

        Promise.all(dependencies).then(function () {
          var codePromise = Promise.resolve(renderCode)

          if (_extends) {
            codePromise = new Promise(function (resolve, reject) {
              make(_extends, function (err, renderCode) {
                if (err) {
                  reject(err)
                } else {
                  resolve()
                }
              })
            })
          }

          codePromise.then(function (renderCode) {

            if (!_extends) {
              sections.push(`render(content) {
                var output = []

                ${ renderCode.join('\n') }

                return output.join('\\n')
              }`)
            }

            var code = []

            code.push('"use strict"')

            code.push('var escape = require("' + directory + '.core.js").escape')
            code.push('var safe = require("' + directory + '.core.js").safe')

            Object.keys(imports).forEach(function (k) {
              code.push('var ' + k + ' = require("' + directory + imports[k] + '.js").partials.' + k)
            })

            if (vars.length) {
              code.push('var ' + vars.join(', '))
            }

            if (_extends) {
              code.push('var ParentSections = require("' + directory + _extends + '.js").Sections')
            }

            code.push('class Sections' + (_extends ? ' extends ParentSections' : '') + ' {')

            code = code.concat(sections)

            code.push('}')

            code = code.concat(Object.keys(partials).map(function (k) {
              return partials[k]
            }))

            code.push('function render(content) { return (new Sections()).render(content) }')

            code.push('render.Sections = Sections')

            code.push('render.partials = {}')

            Object.keys(partials).forEach(function (k) {
              code.push('render.partials.' + k + ' = ' + k)
            })

            code.push('module.exports = render')

            callback(null, code)

          }).catch(callback)

        }).catch(callback)
      }

      function compile (lines) {
        var code = []

        while (lines.length) {
          let line = lines.shift()
          let trimmed = line.trim()
          let parts = trimmed.substr(1).split(/\s+/)
          let directive = parts[0]
          let args = parts.slice(1)
          let arg0 = args[0]
          let func = []
          let level

          if (trimmed.startsWith('@')) {
            if (trimmed === '@') {
              code.push(ends.shift())
            } else {
              if (['section', 'partial'].indexOf(directive) > -1) {
                level = 1
                while (level) {
                  let line = lines.shift() || ''
                  let trimmed = line.trim()

                  if (trimmed === '@') {
                    level -= 1
                    if (level) {
                      func.push(line)
                    }
                  } else {
                    if (trimmed.startsWith('@') && ['if', 'each', 'section', 'partial'].indexOf(trimmed.substr(1).split(/\s+/)[0]) > -1) {
                      level += 1
                    }

                    func.push(line)
                  }
                }
              }

              switch (directive) {
                case 'extends':
                  _extends = arg0
                  dependencies.push(new Promise(function (resolve, reject) {
                    load(arg0, function (err) {
                      if (err) {
                        reject(err)
                      } else {
                        resolve()
                      }
                    })
                  }))
                  break

                case 'embed':
                  code.push('output.push(require("' + directory + arg0 + '.js")(content))')
                  dependencies.push(new Promise(function (resolve, reject) {
                    load(arg0, function (err) {
                      if (err) {
                        reject(err)
                      } else {
                        resolve()
                      }
                    })
                  }))
                  break

                case 'set':
                  code.push(arg0 + ' = ' + args.slice(1).join(' '))
                  vars.push(arg0)
                  break

                case 'yield':
                  code.push('output = output.concat(this.' + arg0 + '(content))')
                  break

                case 'parent':
                  code.push('output = output.concat(super(content))')
                  break

                case 'section':
                  code.push('output = output.concat(this.' + arg0 + '(content))')
                  sections.push(`${ arg0 }(content) {
                    var output = []
                    ${ compile(func).join('\n') }
                    return output
                  }`)
                  break

                case 'import':
                  imports[arg0] = args.slice(1).join(' ')
                  dependencies.push(new Promise(function (resolve, reject) {
                    load(args.slice(1).join(' '), function (err) {
                      if (err) {
                        reject(err)
                      } else {
                        resolve()
                      }
                    })
                  }))
                  break

                case 'partial':
                  if (!partials[arg0]) {
                    partials[arg0] = `function ${ arg0 }(${ args.slice(1).join(', ') }) {
                      var output = []
                      ${ compile(func).join('\n') }
                      return safe(output.join('\\n'))
                    }`
                  }
                  break

                case 'each':
                  code.push('if (Array.isArray(' + arg0 + ') && ' + arg0 + '.length) { output = output.concat(' + arg0 + '.map(function(' + args.slice(1).join(', ') + ') { var output = [] ')
                  ends.unshift("return output.join('\\n') })) }")
                  break

                case 'if':
                  code.push('if(' + args.join(' ') + ') {')
                  ends.unshift('}')
                  break

                case 'elseif':
                  if (ends.length) {
                    code.push(ends.shift())
                  } else {
                    code.push('if (false) {')
                  }
                  code.push('else if(' + args.join(' ') + ') {')
                  ends.unshift('}')
                  break

                case 'else':
                  if (ends.length) {
                    code.push(ends.shift())
                  } else {
                    code.push('if (false) {')
                  }
                  code.push('else {')
                  ends.unshift('}')
                  break
              }
            }
          } else if (line.trim().length) {
            code.push('output.push(escape`' + line.replace('`', '\\`') + '`)')
          }
        }

        return code
      }
    })
  }
}
<|endoftext|>