<commit_before>// Karma configuration
// Generated on Tue Sep 08 2015 19:27:24 GMT+0900 (JST)

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     frameworks: ['mocha', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
      '../test/specs/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '../test/specs/**/*.js': ['webpack']
    },

    webpack: {
      devtool: 'source-map',
      module: {
        loaders: [{
          test: /\.js$/,
          exclude: /node_modules\/dist/,
          loader: 'babel-loader',
          query: {
            presets: ['es2015'],
            plugins: [
              ['babel-plugin-espower']
            ]
          }
        }],
        postLoaders: [{
          test: /\.json$/,
          loader: 'json'
        }, {
          test: /\.js$/,
          exclude: /test|node_modules\/dist/,
          loader: 'istanbul-instrumenter'
        }]
      }
    },

    webpackMiddleware: {
      noInfo: true
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: [
      'mocha', 'coverage'
    ],

    coverageReporter: {
            // specify a common output directory
            dir: 'build/reports/coverage',
            reporters: [
                // reporters not supporting the `file` property
                {
                    type: 'text',
                    subdir: 'report-text',
					dir: '../coverage'
                }, {
                    type: 'lcov',
                    subdir: 'report-lcov',
					dir: '../coverage'
                },
                // reporters supporting the `file` property, use `subdir` to directly
                // output them in the `dir` directory
                {
                    type: 'cobertura',
                    subdir: '.',
                    file: 'cobertura.txt'
                }, {
                    type: 'lcovonly',
                    subdir: '.',
                    file: 'report-lcovonly.txt'
                }, {
                    type: 'teamcity',
                    subdir: '.',
                    file: 'teamcity.txt'
                }, {
                    type: 'text',
                    subdir: '.',
                    file: 'text.txt'
                }, {
                    type: 'text-summary',
                    subdir: '.',
                    file: 'text-summary.txt'
                },
            ]
        },

      browsers: ['Chrome'],
        // custom launchers
        customLaunchers: {
            Chrome_for_Travis_CI: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },

        browserDisconnectTimeout: 10000,
        browserDisconnectTolerance: 2,
        // concurrency level how many browser should be started simultaneously
        concurrency: 4,
        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 100000,
        browserNoActivityTimeout: 30000,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
  if (process.env.TRAVIS) {

        // Use Chrome as default browser for Travis CI
        config.browsers = ['Chrome_for_Travis_CI'];
        // Karma (with socket.io 1.x) buffers by 50 and 50 tests can take a long time on IEs;-)
        config.browserNoActivityTimeout = 120000;
    }
};<commit_msg>removed espower<commit_after>// Karma configuration
// Generated on Tue Sep 08 2015 19:27:24 GMT+0900 (JST)

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     frameworks: ['mocha', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
      '../test/specs/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '../test/specs/**/*.js': ['webpack']
    },

    webpack: {
      devtool: 'source-map',
      module: {
        loaders: [{
          test: /\.js$/,
          exclude: /node_modules\/dist/,
          loader: 'babel-loader',
          query: {
            presets: ['es2015']
          }
        }],
        postLoaders: [{
          test: /\.json$/,
          loader: 'json'
        }, {
          test: /\.js$/,
          exclude: /test|node_modules\/dist/,
          loader: 'istanbul-instrumenter'
        }]
      }
    },

    webpackMiddleware: {
      noInfo: true
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: [
      'mocha', 'coverage'
    ],

    coverageReporter: {
            // specify a common output directory
            dir: 'build/reports/coverage',
            reporters: [
                // reporters not supporting the `file` property
                {
                    type: 'text',
                    subdir: 'report-text',
					dir: '../coverage'
                }, {
                    type: 'lcov',
                    subdir: 'report-lcov',
					dir: '../coverage'
                },
                // reporters supporting the `file` property, use `subdir` to directly
                // output them in the `dir` directory
                {
                    type: 'cobertura',
                    subdir: '.',
                    file: 'cobertura.txt'
                }, {
                    type: 'lcovonly',
                    subdir: '.',
                    file: 'report-lcovonly.txt'
                }, {
                    type: 'teamcity',
                    subdir: '.',
                    file: 'teamcity.txt'
                }, {
                    type: 'text',
                    subdir: '.',
                    file: 'text.txt'
                }, {
                    type: 'text-summary',
                    subdir: '.',
                    file: 'text-summary.txt'
                },
            ]
        },

      browsers: ['Chrome'],
        // custom launchers
        customLaunchers: {
            Chrome_for_Travis_CI: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },

        browserDisconnectTimeout: 10000,
        browserDisconnectTolerance: 2,
        // concurrency level how many browser should be started simultaneously
        concurrency: 4,
        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 100000,
        browserNoActivityTimeout: 30000,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
  if (process.env.TRAVIS) {

        // Use Chrome as default browser for Travis CI
        config.browsers = ['Chrome_for_Travis_CI'];
        // Karma (with socket.io 1.x) buffers by 50 and 50 tests can take a long time on IEs;-)
        config.browserNoActivityTimeout = 120000;
    }
};<|endoftext|>


<commit_before>import { notesMidi } from '../constants/notes';
import { map } from '../utils';

class SynthOscVoice {
  constructor(ctx, oscIndex, cfg) {

    this.osc = new ctx.Oscillator();
    this.env = new ctx.Env();

    this.osc.amp(this.env);
    // p5 sound bug that starts the osc amp != env amp
    this.osc.output.gain.value = 0;
    this.oscIndex = oscIndex;

    this.update(cfg);
    this.osc.start();

    this.isPlaying = false;
  }

  update(cfg) {

    let oscAmp = parseFloat(cfg.synth[`osc_amplitude${this.oscIndex}`]);

    this.amplitude = map(oscAmp, 0, 1, 0, cfg.global.amplitude);
    this.env.setADSR(
      cfg.synth.env_attackTime,
      cfg.synth.env_decayTime,
      cfg.synth.env_susPercent,
      cfg.synth.env_releaseTime
    );

    this.osc.setType(cfg.synth[`osc_type${this.oscIndex}`]);
    this.octave = cfg.synth[`osc_octave${this.oscIndex}`];
  }

  play(note) {

    if (this.isPlaying) {
      return false;
    }

    if (this.noteNumber !== note.number) {
      this.env.triggerRelease();
      this.noteNumber = note.number;
    }

    this.isPlaying = true;

    // Get the note acording to the osc octave
    let noteNumber = parseInt(note.number) + (12 * this.octave);
    let gain = map(note.velocity, 0, 127, 0, this.amplitude);

    note = Object.assign({}, note, notesMidi[noteNumber]);

    this.osc.freq(note.frequency);
    this.env.mult(gain);
    this.env.triggerAttack();

  }

  stop() {
    this.isPlaying = false;
    this.env.triggerRelease();
  }

}

export default SynthOscVoice;
<commit_msg>Correct keyboard mousemove<commit_after>import { notesMidi } from '../constants/notes';
import { map } from '../utils';

class SynthOscVoice {
  constructor(ctx, oscIndex, cfg) {

    this.osc = new ctx.Oscillator();
    this.env = new ctx.Env();

    this.osc.amp(this.env);
    // p5 sound bug that starts the osc amp != env amp
    this.osc.output.gain.value = 0;
    this.oscIndex = oscIndex;

    this.update(cfg);
    this.osc.start();

    this.isPlaying = false;
  }

  update(cfg) {

    let oscAmp = parseFloat(cfg.synth[`osc_amplitude${this.oscIndex}`]);

    this.amplitude = map(oscAmp, 0, 1, 0, cfg.global.amplitude);
    this.env.setADSR(
      cfg.synth.env_attackTime,
      cfg.synth.env_decayTime,
      cfg.synth.env_susPercent,
      cfg.synth.env_releaseTime
    );

    this.osc.setType(cfg.synth[`osc_type${this.oscIndex}`]);
    this.octave = cfg.synth[`osc_octave${this.oscIndex}`];
  }

  play(note) {

    // console.log('this.noteNumber', this.noteNumber, note.number, this.isPlaying);

    if (this.isPlaying && this.noteNumber === note.number) {
      return false;
    }

    this.isPlaying = true;
    this.noteNumber = note.number;

    // Get the note acording to the osc octave
    let noteNumber = parseInt(note.number) + (12 * this.octave);
    let gain = map(note.velocity, 0, 127, 0, this.amplitude);

    note = Object.assign({}, note, notesMidi[noteNumber]);

    this.osc.freq(note.frequency);
    this.env.mult(gain);
    this.env.triggerAttack();

  }

  stop() {
    this.isPlaying = false;
    this.env.triggerRelease();
  }

}

export default SynthOscVoice;
<|endoftext|>


<commit_before>/*global app, sinon, AppPort */
"use strict";

describe("UserEntryView", function() {
  var sandbox, sidebarApp;

  function createFakeSidebarApp() {
    // exposes a global sidebarApp for view consumption
    // XXX: FIX THAT
    window.sidebarApp = {
      user: new app.models.User(),
      appPort: new AppPort()
    };
    return window.sidebarApp;
  }

  beforeEach(function() {
    sandbox = sinon.sandbox.create();

    // mozSocial "mock"
    navigator.mozSocial = {
      getWorker: function() {
        return {
          port: {postMessage: sinon.spy()}
        };
      }
    };

    sandbox.stub(AppPort.prototype, "post");

    sidebarApp = createFakeSidebarApp();
    sidebarApp.openConversation = sandbox.spy();
  });

  afterEach(function() {
    sandbox.restore();
    window.sidebarApp = undefined;
  });

  describe("#call", function() {
    it("should ask the app to open a new conversation", function () {
      var view = new app.views.UserEntryView();

      var clickEvent = {
        preventDefault: function() {},
        currentTarget: {
          getAttribute: function() {return "william";}
        }
      };

      view.openConversation(clickEvent);

      sinon.assert.calledOnce(sidebarApp.openConversation);
      sinon.assert.calledWith(sidebarApp.openConversation, "william");
    });
  });
});
<commit_msg>added tests for user entry view tpl attributes<commit_after>/*global app, chai, sinon, AppPort */
"use strict";

var expect = chai.expect;

describe("UserEntryView", function() {
  var sandbox, sidebarApp;

  function createFakeSidebarApp() {
    // exposes a global sidebarApp for view consumption
    // XXX: FIX THAT
    window.sidebarApp = {
      user: new app.models.User(),
      appPort: new AppPort()
    };
    return window.sidebarApp;
  }

  beforeEach(function() {
    sandbox = sinon.sandbox.create();

    // mozSocial "mock"
    navigator.mozSocial = {
      getWorker: function() {
        return {
          port: {postMessage: sinon.spy()}
        };
      }
    };

    sandbox.stub(AppPort.prototype, "post");

    sidebarApp = createFakeSidebarApp();
    sidebarApp.openConversation = sandbox.spy();
  });

  afterEach(function() {
    sandbox.restore();
    window.sidebarApp = undefined;
  });

  describe("#call", function() {
    it("should ask the app to open a new conversation", function () {
      var view = new app.views.UserEntryView();

      var clickEvent = {
        preventDefault: function() {},
        currentTarget: {
          getAttribute: function() {return "william";}
        }
      };

      view.openConversation(clickEvent);

      sinon.assert.calledOnce(sidebarApp.openConversation);
      sinon.assert.calledWith(sidebarApp.openConversation, "william");
    });
  });

  describe("#render", function() {
    var user, view;

    beforeEach(function() {
      user = new app.models.User();
      view = new app.views.UserEntryView({
        model: user,
        el: $("#fixtures")
      });
    });

    afterEach(function() {
      $("#fixtures").empty();
    });

    it("should populate template with expected username", function() {
      user.set({username: "chuck"});

      view.render();

      console.log(view.$el.html());

      expect(view.$("a").attr("rel")).eql("chuck");
      expect(view.$("a").attr("title")).eql("chuck");
      expect(view.$(".username").text()).eql("chuck");
    });

    it("should populate template with expected full name", function() {
      user.set({username: "chuck", fullName: "Chuck Norris"});

      view.render();

      console.log(view.$el.html());

      expect(view.$("a").attr("rel")).eql("chuck");
      expect(view.$("a").attr("title")).eql("chuck");
      expect(view.$(".username").text()).eql("Chuck Norris");
    });
  });
});
<|endoftext|>


<commit_before>/******************************************************************************/
/************** Setting Up SlideShow ******************************************/
/******************************************************************************/

var allSlides  = $('.slide');
var currSlide  = 0;
var firstSlide = 0;
var lastSlide  = allSlides.length - 1;

/* nextSlide :: (Int) => Int */
function nextSlide(cur){
  return (cur < allSlides.length - 1) ? cur + 1 : cur ;
}

/* prevSlide :: (Int) => Int */
function prevSlide(cur){
  return cur ? cur - 1 : cur;
}

/* gotoSlide :: (Int) => void */
function gotoSlide(nextSlide){
  if (nextSlide !== currSlide) {
    $(allSlides[currSlide])
          .removeClass('active')
          .addClass('inactive');
    $(allSlides[nextSlide])
          .removeClass('inactive')
          .addClass('active');

    currSlide = nextSlide;
  }
}

$(function () {

  // Initialize: Hide all
  $('.slide').removeClass('active').addClass('inactive');
  $(allSlides[currSlide]).removeClass('inactive').addClass('active');

  // Update
  $('.prevbutton').click(function (event) {
    console.log('prev slide click');
    gotoSlide(prevSlide(currSlide));
    event.preventDefault();
   });

  $('.nextbutton').click(function (event) {
    console.log('next slide click');
    gotoSlide(nextSlide(currSlide));
    event.preventDefault();
   });

  $('.firstbutton').click(function (event) {
    console.log('first slide click');
    gotoSlide(firstSlide);
    event.preventDefault();
   });

  $('.lastbutton').click(function (event) {
    console.log('last slide click');
    gotoSlide(lastSlide);
    event.preventDefault();
   });

});

/* progPaneSlide :: (Int) => Int */
function progPaneSlide(paneId){
  var paneId = "#program-pane-" + paneId;
  var elem   = $(paneId).closest(".slide");
  return allSlides.index(elem);

/*
var paneId = "#program-pane-1";
var elem   = $(paneId).closest(".slide");
var pos    = allSlides.index(elem);
 */
}

<commit_msg>add swipe<commit_after>/******************************************************************************/
/************** Setting Up SlideShow ******************************************/
/******************************************************************************/

var allSlides  = $('.slide');
var currSlide  = 0;
var firstSlide = 0;
var lastSlide  = allSlides.length - 1;

/* nextSlide :: (Int) => Int */
function nextSlide(cur){
  return (cur < allSlides.length - 1) ? cur + 1 : cur ;
}

/* prevSlide :: (Int) => Int */
function prevSlide(cur){
  return cur ? cur - 1 : cur;
}

/* gotoSlide :: (Int) => void */
function gotoSlide(nextSlide){
  if (nextSlide !== currSlide) {
    $(allSlides[currSlide])
          .removeClass('active')
          .addClass('inactive');
    $(allSlides[nextSlide])
          .removeClass('inactive')
          .addClass('active');

    currSlide = nextSlide;
  }
}

$(function () {

  // Initialize: Hide all
  $('.slide').removeClass('active').addClass('inactive');
  $(allSlides[currSlide]).removeClass('inactive').addClass('active');

  // Update
  $('.prevbutton').click(function (event) {
    console.log('prev slide click');
    gotoSlide(prevSlide(currSlide));
    event.preventDefault();
   });

  $('.nextbutton').click(function (event) {
    console.log('next slide click');
    gotoSlide(nextSlide(currSlide));
    event.preventDefault();
   });

  $('*').on("swipe",function(event){
    console.log('next slide click');
    gotoSlide(nextSlide(currSlide));
    event.preventDefault();
  });

  $('.firstbutton').click(function (event) {
    console.log('first slide click');
    gotoSlide(firstSlide);
    event.preventDefault();
   });

  $('.lastbutton').click(function (event) {
    console.log('last slide click');
    gotoSlide(lastSlide);
    event.preventDefault();
   });

});

/* progPaneSlide :: (Int) => Int */
function progPaneSlide(paneId){
  var paneId = "#program-pane-" + paneId;
  var elem   = $(paneId).closest(".slide");
  return allSlides.index(elem);

/*
var paneId = "#program-pane-1";
var elem   = $(paneId).closest(".slide");
var pos    = allSlides.index(elem);
 */
}

<|endoftext|>


<commit_before>var ColorList = Array("#FF0000", "#FF7700", "#FFFF00", "#00FF00", "#00FFFF", "#0077FF", "#9900FF");
var LastStr = "";

function IsWhiteSpace(my_c) {
	if (my_c == ' ') return true;
	if (my_c == '\t') return true;
	if (my_c == '\n') return true;
	if (my_c == '\r') return true;
	return false;
}

function ConvertInText(InStr) {
	//var InText = document.getElementById("InText");
	//var OutText = "";
	//if (InText && OutText) {
		//var InStr = InText;
		var OutStr = "";
		var InBBCode = false;
		var CurrCol = 0;

		if (InStr != LastStr) {

			//OutText.value = "";
			var x;
			for (x=0;x<InStr.length;x++) {
				if ((InStr.charAt(x)=='[') && (!InBBCode)) {
					InBBCode=true;
					OutStr += InStr.charAt(x);
				} else if ((InStr.charAt(x)==']') && (InBBCode)) {
					InBBCode=false;
					OutStr += InStr.charAt(x);
				} else if (IsWhiteSpace(InStr.charAt(x))) {
					OutStr += InStr.charAt(x);
				} else if (InBBCode) {
					OutStr += InStr.charAt(x);
				} else {
						OutStr += "[color="+ColorList[CurrCol]+"]"+InStr.charAt(x)+"[/color]";
					CurrCol = (CurrCol+1)%ColorList.length;
				}
			}

			return OutStr;
			LastStr = InStr;
		}
	//}
}
// randomColor by David Merfield under the MIT license
// https://github.com/davidmerfield/randomColor/
;(function(root,factory){if(typeof define==='function'&&define.amd){define([],factory);}else if(typeof exports==='object'){var randomColor=factory();if(typeof module==='object'&&module&&module.exports){exports=module.exports=randomColor;} exports.randomColor=randomColor;}else{root.randomColor=factory();};}(this,function(){var seed=null;var colorDictionary={};loadColorBounds();var randomColor=function(options){options=options||{};if(options.seed&&!seed)seed=options.seed;var H,S,B;if(options.count!=null){var totalColors=options.count,colors=[];options.count=null;while(totalColors>colors.length){colors.push(randomColor(options));} options.count=totalColors;if(options.seed)seed=options.seed;return colors;} H=pickHue(options);S=pickSaturation(H,options);B=pickBrightness(H,S,options);return setFormat([H,S,B],options);};function pickHue(options){var hueRange=getHueRange(options.hue),hue=randomWithin(hueRange);if(hue<0){hue=360+hue} return hue;} function pickSaturation(hue,options){if(options.luminosity==='random'){return randomWithin([0,100]);} if(options.hue==='monochrome'){return 0;} var saturationRange=getSaturationRange(hue);var sMin=saturationRange[0],sMax=saturationRange[1];switch(options.luminosity){case'bright':sMin=55;break;case'dark':sMin=sMax-10;break;case'light':sMax=55;break;} return randomWithin([sMin,sMax]);} function pickBrightness(H,S,options){var brightness,bMin=getMinimumBrightness(H,S),bMax=100;switch(options.luminosity){case'dark':bMax=bMin+20;break;case'light':bMin=(bMax+bMin)/2;break;case'random':bMin=0;bMax=100;break;} return randomWithin([bMin,bMax]);} function setFormat(hsv,options){switch(options.format){case'hsvArray':return hsv;case'hslArray':return HSVtoHSL(hsv);case'hsl':var hsl=HSVtoHSL(hsv);return'hsl('+hsl[0]+', '+hsl[1]+'%, '+hsl[2]+'%)';case'rgbArray':return HSVtoRGB(hsv);case'rgb':var rgb=HSVtoRGB(hsv);return'rgb('+rgb.join(', ')+')';default:return HSVtoHex(hsv);}} function getMinimumBrightness(H,S){var lowerBounds=getColorInfo(H).lowerBounds;for(var i=0;i<lowerBounds.length-1;i++){var s1=lowerBounds[i][0],v1=lowerBounds[i][1];var s2=lowerBounds[i+1][0],v2=lowerBounds[i+1][1];if(S>=s1&&S<=s2){var m=(v2-v1)/(s2-s1),b=v1-m*s1;return m*S+b;}} return 0;} function getHueRange(colorInput){if(typeof parseInt(colorInput)==='number'){var number=parseInt(colorInput);if(number<360&&number>0){return[number,number];}} if(typeof colorInput==='string'){if(colorDictionary[colorInput]){var color=colorDictionary[colorInput];if(color.hueRange){return color.hueRange}}} return[0,360];} function getSaturationRange(hue){return getColorInfo(hue).saturationRange;} function getColorInfo(hue){if(hue>=334&&hue<=360){hue-=360;} for(var colorName in colorDictionary){var color=colorDictionary[colorName];if(color.hueRange&&hue>=color.hueRange[0]&&hue<=color.hueRange[1]){return colorDictionary[colorName];}}return'Color not found';} function randomWithin(range){if(seed==null){return Math.floor(range[0]+Math.random()*(range[1]+1-range[0]));}else{var max=range[1]||1;var min=range[0]||0;seed=(seed*9301+49297)%233280;var rnd=seed/233280.0;return Math.floor(min+rnd*(max-min));}} function HSVtoHex(hsv){var rgb=HSVtoRGB(hsv);function componentToHex(c){var hex=c.toString(16);return hex.length==1?"0"+hex:hex;} var hex="#"+componentToHex(rgb[0])+componentToHex(rgb[1])+componentToHex(rgb[2]);return hex;} function defineColor(name,hueRange,lowerBounds){var sMin=lowerBounds[0][0],sMax=lowerBounds[lowerBounds.length-1][0],bMin=lowerBounds[lowerBounds.length-1][1],bMax=lowerBounds[0][1];colorDictionary[name]={hueRange:hueRange,lowerBounds:lowerBounds,saturationRange:[sMin,sMax],brightnessRange:[bMin,bMax]};} function loadColorBounds(){defineColor('monochrome',null,[[0,0],[100,0]]);defineColor('red',[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]);defineColor('orange',[19,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]);defineColor('yellow',[47,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]);defineColor('green',[63,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]);defineColor('blue',[179,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]);defineColor('purple',[258,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]);defineColor('pink',[283,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]]);} function HSVtoRGB(hsv){var h=hsv[0];if(h===0){h=1} if(h===360){h=359} h=h/360;var s=hsv[1]/100,v=hsv[2]/100;var h_i=Math.floor(h*6),f=h*6-h_i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s),r=256,g=256,b=256;switch(h_i){case 0:r=v,g=t,b=p;break;case 1:r=q,g=v,b=p;break;case 2:r=p,g=v,b=t;break;case 3:r=p,g=q,b=v;break;case 4:r=t,g=p,b=v;break;case 5:r=v,g=p,b=q;break;} var result=[Math.floor(r*255),Math.floor(g*255),Math.floor(b*255)];return result;} function HSVtoHSL(hsv){var h=hsv[0],s=hsv[1]/100,v=hsv[2]/100,k=(2-s)*v;return[h,Math.round(s*v/(k<1?k:2-k)*10000)/100,k/2*100];} return randomColor;}));

function ConvertRandomColor(InStr) {
	var OutArr = InStr.split("");
	var OutStr = ""
	for (var i = 0; i < OutArr.length; i++) {
		OutStr += '[color=' + randomColor() + ']' + OutArr[i] + '[/color]'
	}
	return OutStr;
}

function Timer() {
	ConvertInText();
	setTimeout("Timer();", 100);
}
<commit_msg>ignore<commit_after>var ColorList = Array('#FF0000', '#FF7700', '#FFFF00', '#00FF00', '#00FFFF', '#0077FF', '#9900FF');
var LastStr = '';
function IsWhiteSpace(my_c) {
  if (my_c == ' ')
    return true;
  if (my_c == '\t')
    return true;
  if (my_c == '\n')
    return true;
  if (my_c == '\r')
    return true;
  return false;
}
function ConvertInText(InStr) {
  //var InText = document.getElementById("InText");
  //var OutText = "";
  //if (InText && OutText) {
  //var InStr = InText;
  var OutStr = '';
  var InBBCode = false;
  var CurrCol = 0;
  if (InStr != LastStr) {
    //OutText.value = "";
    var x;
    for (x = 0; x < InStr.length; x++) {
      if (InStr.charAt(x) == '[' && !InBBCode) {
        InBBCode = true;
        OutStr += InStr.charAt(x);
      } else if (InStr.charAt(x) == ']' && InBBCode) {
        InBBCode = false;
        OutStr += InStr.charAt(x);
      } else if (IsWhiteSpace(InStr.charAt(x))) {
        OutStr += InStr.charAt(x);
      } else if (InBBCode) {
        OutStr += InStr.charAt(x);
      } else {
        OutStr += '[color=' + ColorList[CurrCol] + ']' + InStr.charAt(x) + '[/color]';
        CurrCol = (CurrCol + 1) % ColorList.length;
      }
    }
    return OutStr;
    LastStr = InStr;
  }  //}
}
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    var randomColor = factory();
    if (typeof module === 'object' && module && module.exports) {
      exports = module.exports = randomColor;
    }
    exports.randomColor = randomColor;
  } else {
    root.randomColor = factory();
  }
}(this, function () {
  var seed = null;
  var colorDictionary = {};
  loadColorBounds();
  var randomColor = function (options) {
    options = options || {};
    if (options.seed && !seed)
      seed = options.seed;
    var H, S, B;
    if (options.count != null) {
      var totalColors = options.count, colors = [];
      options.count = null;
      while (totalColors > colors.length) {
        colors.push(randomColor(options));
      }
      options.count = totalColors;
      if (options.seed)
        seed = options.seed;
      return colors;
    }
    H = pickHue(options);
    S = pickSaturation(H, options);
    B = pickBrightness(H, S, options);
    return setFormat([
      H,
      S,
      B
    ], options);
  };
  function pickHue(options) {
    var hueRange = getHueRange(options.hue), hue = randomWithin(hueRange);
    if (hue < 0) {
      hue = 360 + hue;
    }
    return hue;
  }
  function pickSaturation(hue, options) {
    if (options.luminosity === 'random') {
      return randomWithin([
        0,
        100
      ]);
    }
    if (options.hue === 'monochrome') {
      return 0;
    }
    var saturationRange = getSaturationRange(hue);
    var sMin = saturationRange[0], sMax = saturationRange[1];
    switch (options.luminosity) {
    case 'bright':
      sMin = 55;
      break;
    case 'dark':
      sMin = sMax - 10;
      break;
    case 'light':
      sMax = 55;
      break;
    }
    return randomWithin([
      sMin,
      sMax
    ]);
  }
  function pickBrightness(H, S, options) {
    var brightness, bMin = getMinimumBrightness(H, S), bMax = 100;
    switch (options.luminosity) {
    case 'dark':
      bMax = bMin + 20;
      break;
    case 'light':
      bMin = (bMax + bMin) / 2;
      break;
    case 'random':
      bMin = 0;
      bMax = 100;
      break;
    }
    return randomWithin([
      bMin,
      bMax
    ]);
  }
  function setFormat(hsv, options) {
    switch (options.format) {
    case 'hsvArray':
      return hsv;
    case 'hslArray':
      return HSVtoHSL(hsv);
    case 'hsl':
      var hsl = HSVtoHSL(hsv);
      return 'hsl(' + hsl[0] + ', ' + hsl[1] + '%, ' + hsl[2] + '%)';
    case 'rgbArray':
      return HSVtoRGB(hsv);
    case 'rgb':
      var rgb = HSVtoRGB(hsv);
      return 'rgb(' + rgb.join(', ') + ')';
    default:
      return HSVtoHex(hsv);
    }
  }
  function getMinimumBrightness(H, S) {
    var lowerBounds = getColorInfo(H).lowerBounds;
    for (var i = 0; i < lowerBounds.length - 1; i++) {
      var s1 = lowerBounds[i][0], v1 = lowerBounds[i][1];
      var s2 = lowerBounds[i + 1][0], v2 = lowerBounds[i + 1][1];
      if (S >= s1 && S <= s2) {
        var m = (v2 - v1) / (s2 - s1), b = v1 - m * s1;
        return m * S + b;
      }
    }
    return 0;
  }
  function getHueRange(colorInput) {
    if (typeof parseInt(colorInput) === 'number') {
      var number = parseInt(colorInput);
      if (number < 360 && number > 0) {
        return [
          number,
          number
        ];
      }
    }
    if (typeof colorInput === 'string') {
      if (colorDictionary[colorInput]) {
        var color = colorDictionary[colorInput];
        if (color.hueRange) {
          return color.hueRange;
        }
      }
    }
    return [
      0,
      360
    ];
  }
  function getSaturationRange(hue) {
    return getColorInfo(hue).saturationRange;
  }
  function getColorInfo(hue) {
    if (hue >= 334 && hue <= 360) {
      hue -= 360;
    }
    for (var colorName in colorDictionary) {
      var color = colorDictionary[colorName];
      if (color.hueRange && hue >= color.hueRange[0] && hue <= color.hueRange[1]) {
        return colorDictionary[colorName];
      }
    }
    return 'Color not found';
  }
  function randomWithin(range) {
    if (seed == null) {
      return Math.floor(range[0] + Math.random() * (range[1] + 1 - range[0]));
    } else {
      var max = range[1] || 1;
      var min = range[0] || 0;
      seed = (seed * 9301 + 49297) % 233280;
      var rnd = seed / 233280;
      return Math.floor(min + rnd * (max - min));
    }
  }
  function HSVtoHex(hsv) {
    var rgb = HSVtoRGB(hsv);
    function componentToHex(c) {
      var hex = c.toString(16);
      return hex.length == 1 ? '0' + hex : hex;
    }
    var hex = '#' + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);
    return hex;
  }
  function defineColor(name, hueRange, lowerBounds) {
    var sMin = lowerBounds[0][0], sMax = lowerBounds[lowerBounds.length - 1][0], bMin = lowerBounds[lowerBounds.length - 1][1], bMax = lowerBounds[0][1];
    colorDictionary[name] = {
      hueRange: hueRange,
      lowerBounds: lowerBounds,
      saturationRange: [
        sMin,
        sMax
      ],
      brightnessRange: [
        bMin,
        bMax
      ]
    };
  }
  function loadColorBounds() {
    defineColor('monochrome', null, [
      [
        0,
        0
      ],
      [
        100,
        0
      ]
    ]);
    defineColor('red', [
      -26,
      18
    ], [
      [
        20,
        100
      ],
      [
        30,
        92
      ],
      [
        40,
        89
      ],
      [
        50,
        85
      ],
      [
        60,
        78
      ],
      [
        70,
        70
      ],
      [
        80,
        60
      ],
      [
        90,
        55
      ],
      [
        100,
        50
      ]
    ]);
    defineColor('orange', [
      19,
      46
    ], [
      [
        20,
        100
      ],
      [
        30,
        93
      ],
      [
        40,
        88
      ],
      [
        50,
        86
      ],
      [
        60,
        85
      ],
      [
        70,
        70
      ],
      [
        100,
        70
      ]
    ]);
    defineColor('yellow', [
      47,
      62
    ], [
      [
        25,
        100
      ],
      [
        40,
        94
      ],
      [
        50,
        89
      ],
      [
        60,
        86
      ],
      [
        70,
        84
      ],
      [
        80,
        82
      ],
      [
        90,
        80
      ],
      [
        100,
        75
      ]
    ]);
    defineColor('green', [
      63,
      178
    ], [
      [
        30,
        100
      ],
      [
        40,
        90
      ],
      [
        50,
        85
      ],
      [
        60,
        81
      ],
      [
        70,
        74
      ],
      [
        80,
        64
      ],
      [
        90,
        50
      ],
      [
        100,
        40
      ]
    ]);
    defineColor('blue', [
      179,
      257
    ], [
      [
        20,
        100
      ],
      [
        30,
        86
      ],
      [
        40,
        80
      ],
      [
        50,
        74
      ],
      [
        60,
        60
      ],
      [
        70,
        52
      ],
      [
        80,
        44
      ],
      [
        90,
        39
      ],
      [
        100,
        35
      ]
    ]);
    defineColor('purple', [
      258,
      282
    ], [
      [
        20,
        100
      ],
      [
        30,
        87
      ],
      [
        40,
        79
      ],
      [
        50,
        70
      ],
      [
        60,
        65
      ],
      [
        70,
        59
      ],
      [
        80,
        52
      ],
      [
        90,
        45
      ],
      [
        100,
        42
      ]
    ]);
    defineColor('pink', [
      283,
      334
    ], [
      [
        20,
        100
      ],
      [
        30,
        90
      ],
      [
        40,
        86
      ],
      [
        60,
        84
      ],
      [
        80,
        80
      ],
      [
        90,
        75
      ],
      [
        100,
        73
      ]
    ]);
  }
  function HSVtoRGB(hsv) {
    var h = hsv[0];
    if (h === 0) {
      h = 1;
    }
    if (h === 360) {
      h = 359;
    }
    h = h / 360;
    var s = hsv[1] / 100, v = hsv[2] / 100;
    var h_i = Math.floor(h * 6), f = h * 6 - h_i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), r = 256, g = 256, b = 256;
    switch (h_i) {
    case 0:
      r = v, g = t, b = p;
      break;
    case 1:
      r = q, g = v, b = p;
      break;
    case 2:
      r = p, g = v, b = t;
      break;
    case 3:
      r = p, g = q, b = v;
      break;
    case 4:
      r = t, g = p, b = v;
      break;
    case 5:
      r = v, g = p, b = q;
      break;
    }
    var result = [
      Math.floor(r * 255),
      Math.floor(g * 255),
      Math.floor(b * 255)
    ];
    return result;
  }
  function HSVtoHSL(hsv) {
    var h = hsv[0], s = hsv[1] / 100, v = hsv[2] / 100, k = (2 - s) * v;
    return [
      h,
      Math.round(s * v / (k < 1 ? k : 2 - k) * 10000) / 100,
      k / 2 * 100
    ];
  }
  return randomColor;
}));
function ConvertRandomColor(InStr) {
  var OutArr = InStr.split('');
  var OutStr = '';
  for (var i = 0; i < OutArr.length; i++) {
    OutStr += '[color=' + randomColor() + ']' + OutArr[i] + '[/color]';
  }
  return OutStr;
}
function Timer() {
  ConvertInText();
  setTimeout('Timer();', 100);
}<|endoftext|>


<commit_before>/**
 * DO NOT EDIT!!!
 *
 * @NOTE(dli) 12-21-2016
 *   This file is generated. For now, it is a snapshot of the proto services as of
 *   Aug 1, 2018 3:42:41 PM. We will update the generation pipeline to actually
 *   place these generated objects in the correct location shortly.
 */

import $ from 'jquery';
import JsonBigInt from 'json-bigint';
import Utils from "../utils/Utils";

const StrictJsonBigInt = JsonBigInt({ strict: true, storeAsString: true });

export class MlflowService {

  /**
   * @param {CreateExperiment} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static createExperiment({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/experiments/create'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {ListExperiments} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static listExperiments({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/experiments/list'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {GetExperiment} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static getExperiment({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/experiments/get'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {CreateRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static createRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/create'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {DeleteRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static deleteRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/delete'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {RestoreRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static restoreRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/restore'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {UpdateRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static updateRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/update'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {LogMetric} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static logMetric({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/log-metric'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {LogParam} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static logParam({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/log-parameter'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {GetRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static getRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/get'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {SearchRuns} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static searchRuns({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/search'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {ListArtifacts} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static listArtifacts({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/artifacts/list'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {GetMetricHistory} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static getMetricHistory({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/metrics/get-history'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {SetTag} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static setTag({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/set-tag'), {
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }
}
<commit_msg>Fix MLFlow Server MIME-Types in the Frontend (#1679)<commit_after>/**
 * DO NOT EDIT!!!
 *
 * @NOTE(dli) 12-21-2016
 *   This file is generated. For now, it is a snapshot of the proto services as of
 *   Aug 1, 2018 3:42:41 PM. We will update the generation pipeline to actually
 *   place these generated objects in the correct location shortly.
 */

import $ from 'jquery';
import JsonBigInt from 'json-bigint';
import Utils from "../utils/Utils";

const StrictJsonBigInt = JsonBigInt({ strict: true, storeAsString: true });

export class MlflowService {

  /**
   * @param {CreateExperiment} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static createExperiment({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/experiments/create'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {ListExperiments} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static listExperiments({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/experiments/list'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {GetExperiment} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static getExperiment({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/experiments/get'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {CreateRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static createRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/create'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {DeleteRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static deleteRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/delete'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {RestoreRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static restoreRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/restore'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {UpdateRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static updateRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/update'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {LogMetric} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static logMetric({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/log-metric'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {LogParam} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static logParam({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/log-parameter'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {GetRun} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static getRun({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/get'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {SearchRuns} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static searchRuns({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/search'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {ListArtifacts} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static listArtifacts({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/artifacts/list'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {GetMetricHistory} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static getMetricHistory({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/metrics/get-history'), {
      type: 'GET',
      dataType: 'json',
      converters: {
        'text json': StrictJsonBigInt.parse,
      },
      data: data,
      jsonp: false,
      success: success,
      error: error,
    });
  }

  /**
   * @param {SetTag} data: Immutable Record
   * @param {function} success
   * @param {function} error
   * @return {Promise}
   */
  static setTag({ data, success, error }) {
    return $.ajax(Utils.getAjaxUrl('ajax-api/2.0/preview/mlflow/runs/set-tag'), {
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(data),
      jsonp: false,
      success: success,
      error: error,
    });
  }
}
<|endoftext|>


<commit_before>var show_suite,report_modules; // TODO: hang these off QUnit?
(function() {

show_suite = function(test_suite) {
  //TODO: only run specified test if ?test=tname
  var is_json_output = acre.request.params.output && acre.request.params.output.indexOf('json') == 0;

  //jsonp wrapper
  if (acre.request.params.callback && is_json_output) {
    acre.write(acre.request.params.callback + '(');
  }

  // actual output
  if (acre.request.params.output==='jsonsummary') {
    acre.write(JSON.stringify( {failures:test_suite.failures, total:test_suite.total} ));
  } else if (acre.request.params.output==='json') {
    acre.write(JSON.stringify(test_suite,null,2));
  } else {
    // output==='html'
    var templates = acre.require('report');
    acre.response.set_header('Content-Type','text/html');
    acre.write(templates.show_suite(test_suite));
  }

  //jsonp wrapper
  if (acre.request.params.callback && is_json_output) {
    acre.write(');');
  }

};

report_modules = function (modules) {
  // HACK: assume the single-file case, so construct a test-suite object
  var test_suite = {
    app_path: get_app_path(),
    testprops:[],
    testfiles:[{
      file:    acre.request.script.name, //HACK: this is broken for http://routing.site.freebase.dev.acre.z:8115/test_app_routes?output=json&mode=discover&acre.console=1
      run_url: make_dev_url(get_app_path()) + '/' + acre.request.script.name,
      modules: modules
    }
    ]
  };
  show_suite(test_suite);
};

var testfinder = (function() {
  var dependencies, // list of libs from manifest
  testfiles;        // list of test files objects

  // Look for MANIFEST containing var MF = {test:{files:['test_file1','test_file2']}};
  function search_deps_in_manifest(app_path) {
    var manifestid=app_path+'/MANIFEST';
    var mf;
    try {
      mf = acre.require(manifestid).MF;
    } catch(e) { return; }
    for (var label in mf.apps) {
      var dep_app_path = mf.apps[label];
      if (!(dep_app_path in dependencies)) {
        dependencies[dep_app_path] = false; // add to set, mark unvisted
      }
    }
  }

  function search_for_test_files(app_path) {
    var metadata = acre.get_metadata(app_path);
    if (!metadata) { return; }
    for (var filekey in metadata.files) {
      var file = metadata.files[filekey];
      if (file.name.indexOf('test_')===0) {
        var path = app_path + '/' + file.name;
        testfiles[path] = true; // add to set
      }
    }
  }

  function search(app_path,recurse) {
    dependencies[app_path] = true; // mark app as visited
    search_for_test_files(app_path);
    if (recurse) {
      search_deps_in_manifest(app_path);
      for (var dep_app_path in dependencies) {
        if (!dependencies[dep_app_path]) {
          search(dep_app_path,recurse);
        }
      }
    }
  }

  function get(app_path,recurse) {
      dependencies={
        // app_path: has_been_visited
      };
      testfiles={
        // testfilepath: true
      };
      search(app_path,recurse);
      var result = [];
      for (var testfilepath in testfiles) {
        result.push( make_file_obj(testfilepath) );
      }
      return result;
  }
  return {
    get:get
  };
})();

function make_dev_url(app_path) {
    var protocol = acre.request.protocol;
    var port = acre.request.server_port;
    port = ((protocol == 'http' && port != 80) || (protocol == 'https' && port != 443)) ? ":" + port : '';
    return protocol + ":" + app_path + '.' + acre.host.name + port;
}

function make_file_obj(fileid) {
  var s = fileid.split('/');
  var filename = s.pop();
  var app_path = s.join('/');
  return { name:filename, fileid:fileid, run_url:make_dev_url(app_path)+'/'+filename};
}

function get_test_suite(app_path,testscripts) {
  var test_suite = {
    app_path:app_path,
    testprops:[],
    testfiles:[]
  };
  var testprops = {};

  acre.request.params.mode = 'discover'; //HACK: is this clean?

  testscripts.forEach(function(file) {
    var acre_testfile = acre.require(file.fileid); //HACK: version?
    var modules = acre_testfile.acre.test.get_modules();
    var testfile = {
      file:    file.name,
      run_url: file.run_url,
      modules: modules
    };
    test_suite.testfiles.push(testfile);
  });
  //TODO: for (var propname in testprops) { test_suite.testprops.push(propname); }
  //console.warn('test_suite =',test_suite);

  return test_suite;
}

function get_app_path() {
  //TODO: what's the acre way to get the app_path?
  return '//' + (acre.request.server_name).replace('.'+acre.host.name,'');
}

if (acre.current_script === acre.request.script) {
  var app_path = get_app_path();

  var testscripts = testfinder.get(app_path, acre.request.params.recurse);
  if (testscripts.length) {
    console.log('test: tests = '+testscripts.map(function(file){return file.name;}).join(', '));
  } else {
    console.warn('test: no tests found in '+app_path);
  }
  if (acre.request.params.mode==='listfiles') {
    // just output the list of test files (fast), don't discover the individual tests (slow)
    var run_urls = testscripts.map(function(file) {
      return file.run_url;
    });
    acre.write(JSON.stringify(run_urls,null,2));
  } else {
    show_suite(get_test_suite(app_path,testscripts));
  }
}

})();
<commit_msg>output=flatjson. the default shape of the json output was awful<commit_after>var show_suite,report_modules; // TODO: hang these off QUnit?
(function() {

show_suite = function(test_suite) {
  //TODO: only run specified test if ?test=tname
  var is_json_output = acre.request.params.output && acre.request.params.output.indexOf('json') == 0;

  //jsonp wrapper
  if (acre.request.params.callback && is_json_output) {
    acre.write(acre.request.params.callback + '(');
  }

  // actual output
  if (acre.request.params.output==='jsonsummary') {
    acre.write(JSON.stringify( {failures:test_suite.failures, total:test_suite.total} ));
  } else if (acre.request.params.output==='json') {
    acre.write(JSON.stringify(test_suite,null,2));
  } else if (acre.request.params.output==='flatjson') {
    acre.write(JSON.stringify(flatten_test_suite(test_suite),null,2));
  } else {
    // output==='html'
    var templates = acre.require('report');
    acre.response.set_header('Content-Type','text/html');
    acre.write(templates.show_suite(test_suite));
  }

  //jsonp wrapper
  if (acre.request.params.callback && is_json_output) {
    acre.write(');');
  }

};

report_modules = function (modules) {
  // HACK: assume the single-file case, so construct a test-suite object
  var test_suite = {
    app_path: get_app_path(),
    testprops:[],
    testfiles:[{
      file:    acre.request.script.name, //HACK: this is broken for http://routing.site.freebase.dev.acre.z:8115/test_app_routes?output=json&mode=discover&acre.console=1
      run_url: make_dev_url(get_app_path()) + '/' + acre.request.script.name,
      modules: modules
    }
    ]
  };
  show_suite(test_suite);
};

function flatten_test_suite(test_suite) {
  // the default shape of the test output is inscrutable
  var testfile = test_suite.testfiles[0];
  var tests = [];
  for (mi in testfile.modules) {
    var m = testfile.modules[mi];
    var mname = m.name + ".";
    if (mname == "DEFAULT.") {
       mname = "";
    };
    //thing += mname;
    for (ti in m.tests) {
      var t = m.tests[ti];
      var tname = mname + t.name;
      var runtime = t.runtime;
      var skip = false;
      for (li in t.log) {
        if (t.log[li].result == "Skipping test: ") {
          skip = t.log[li].message;
        };
      };
      var tobj = {
        "name":tname,
        "runtime":runtime,
        "testEnvironment": t.testEnvironment,
        "skip": skip,
        "failures": t.failures,
        "total": t.total,
        "log": t.log
      };
      tests.push(tobj);
    };
  };

  var clean_suite = {
    "app_path": test_suite.app_path,
    "tid" : test_suite.tid,
    "testprops" : test_suite.testprops,
    "file" : testfile.file,
    "total" : testfile.total,
    "failures" : testfile.failures,
    "run_url" : testfile.run_url,
    "tests" : tests
  };

  return clean_suite
};

var testfinder = (function() {
  var dependencies, // list of libs from manifest
  testfiles;        // list of test files objects

  // Look for MANIFEST containing var MF = {test:{files:['test_file1','test_file2']}};
  function search_deps_in_manifest(app_path) {
    var manifestid=app_path+'/MANIFEST';
    var mf;
    try {
      mf = acre.require(manifestid).MF;
    } catch(e) { return; }
    for (var label in mf.apps) {
      var dep_app_path = mf.apps[label];
      if (!(dep_app_path in dependencies)) {
        dependencies[dep_app_path] = false; // add to set, mark unvisted
      }
    }
  }

  function search_for_test_files(app_path) {
    var metadata = acre.get_metadata(app_path);
    if (!metadata) { return; }
    for (var filekey in metadata.files) {
      var file = metadata.files[filekey];
      if (file.name.indexOf('test_')===0) {
        var path = app_path + '/' + file.name;
        testfiles[path] = true; // add to set
      }
    }
  }

  function search(app_path,recurse) {
    dependencies[app_path] = true; // mark app as visited
    search_for_test_files(app_path);
    if (recurse) {
      search_deps_in_manifest(app_path);
      for (var dep_app_path in dependencies) {
        if (!dependencies[dep_app_path]) {
          search(dep_app_path,recurse);
        }
      }
    }
  }

  function get(app_path,recurse) {
      dependencies={
        // app_path: has_been_visited
      };
      testfiles={
        // testfilepath: true
      };
      search(app_path,recurse);
      var result = [];
      for (var testfilepath in testfiles) {
        result.push( make_file_obj(testfilepath) );
      }
      return result;
  }
  return {
    get:get
  };
})();

function make_dev_url(app_path) {
    var protocol = acre.request.protocol;
    var port = acre.request.server_port;
    port = ((protocol == 'http' && port != 80) || (protocol == 'https' && port != 443)) ? ":" + port : '';
    return protocol + ":" + app_path + '.' + acre.host.name + port;
}

function make_file_obj(fileid) {
  var s = fileid.split('/');
  var filename = s.pop();
  var app_path = s.join('/');
  return { name:filename, fileid:fileid, run_url:make_dev_url(app_path)+'/'+filename};
}

function get_test_suite(app_path,testscripts) {
  var test_suite = {
    app_path:app_path,
    testprops:[],
    testfiles:[]
  };
  var testprops = {};

  acre.request.params.mode = 'discover'; //HACK: is this clean?

  testscripts.forEach(function(file) {
    var acre_testfile = acre.require(file.fileid); //HACK: version?
    var modules = acre_testfile.acre.test.get_modules();
    var testfile = {
      file:    file.name,
      run_url: file.run_url,
      modules: modules
    };
    test_suite.testfiles.push(testfile);
  });
  //TODO: for (var propname in testprops) { test_suite.testprops.push(propname); }
  //console.warn('test_suite =',test_suite);

  return test_suite;
}

function get_app_path() {
  //TODO: what's the acre way to get the app_path?
  return '//' + (acre.request.server_name).replace('.'+acre.host.name,'');
}

if (acre.current_script === acre.request.script) {
  var app_path = get_app_path();

  var testscripts = testfinder.get(app_path, acre.request.params.recurse);
  if (testscripts.length) {
    console.log('test: tests = '+testscripts.map(function(file){return file.name;}).join(', '));
  } else {
    console.warn('test: no tests found in '+app_path);
  }
  if (acre.request.params.mode==='listfiles') {
    // just output the list of test files (fast), don't discover the individual tests (slow)
    var run_urls = testscripts.map(function(file) {
      return file.run_url;
    });
    acre.write(JSON.stringify(run_urls,null,2));
  } else {
    show_suite(get_test_suite(app_path,testscripts));
  }
}

})();
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/license$s/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

'use strict';

KylinApp.controller('CubeMeasuresCtrl', function ($scope, $modal,MetaModel,cubesManager,CubeDescModel) {

  $scope.addNewMeasure = function (measure) {
    $scope.newMeasure = (!!measure)? measure:CubeDescModel.createMeasure();
  };

  $scope.removeElement = function (arr, element) {
    var index = arr.indexOf(element);
    if (index > -1) {
      arr.splice(index, 1);
    }
  };

  $scope.clearNewMeasure = function () {
    $scope.newMeasure = null;
  };

  $scope.saveNewMeasure = function () {
    if ($scope.cubeMetaFrame.measures.indexOf($scope.newMeasure) === -1) {
      $scope.cubeMetaFrame.measures.push($scope.newMeasure);
    }
    $scope.newMeasure = null;
  };

  //map right return type for param
  $scope.measureReturnTypeUpdate = function(){
    if($scope.newMeasure.function.parameter.type=="constant"&&$scope.newMeasure.function.expression!=="COUNT_DISTINCT"){
      switch($scope.newMeasure.function.expression){
        case "SUM":
        case "COUNT":
          $scope.newMeasure.function.returntype = "bigint";
          break;
        default:
          $scope.newMeasure.function.returntype = "";
          break;
      }
    }
    if($scope.newMeasure.function.parameter.type=="column"&&$scope.newMeasure.function.expression!=="COUNT_DISTINCT"){

      var column = $scope.newMeasure.function.parameter.value;
      var colType = $scope.getColumnType(column, $scope.metaModel.model.fact_table); // $scope.getColumnType defined in cubeEdit.js

      if(colType==""||!colType){
        $scope.newMeasure.function.returntype = "";
        return;
      }

      switch($scope.newMeasure.function.expression){
        case "SUM":
          if(colType==="smallint"||colType==="int"||colType==="bigint"||colType==="integer"){
            $scope.newMeasure.function.returntype= 'bigint';
          }else{
            if(colType.indexOf('decimal')!=-1){
              $scope.newMeasure.function.returntype= colType;
            }else{
              $scope.newMeasure.function.returntype= 'decimal';
            }
          }
          break;
        case "MIN":
        case "MAX":
          $scope.newMeasure.function.returntype = colType;
          break;
        case "COUNT":
          $scope.newMeasure.function.returntype = "bigint";
          break;
        default:
          $scope.newMeasure.function.returntype = "";
          break;
      }
    }
  }

});
<commit_msg>KYLIN-1108 always return BIGINT type for COUNT expression<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/license$s/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

'use strict';

KylinApp.controller('CubeMeasuresCtrl', function ($scope, $modal,MetaModel,cubesManager,CubeDescModel) {

  $scope.addNewMeasure = function (measure) {
    $scope.newMeasure = (!!measure)? measure:CubeDescModel.createMeasure();
  };

  $scope.removeElement = function (arr, element) {
    var index = arr.indexOf(element);
    if (index > -1) {
      arr.splice(index, 1);
    }
  };

  $scope.clearNewMeasure = function () {
    $scope.newMeasure = null;
  };

  $scope.saveNewMeasure = function () {
    if ($scope.cubeMetaFrame.measures.indexOf($scope.newMeasure) === -1) {
      $scope.cubeMetaFrame.measures.push($scope.newMeasure);
    }
    $scope.newMeasure = null;
  };

  //map right return type for param
  $scope.measureReturnTypeUpdate = function(){

    if($scope.newMeasure.function.expression == 'COUNT'){
      $scope.newMeasure.function.parameter.type= 'constant';
    }

    if($scope.newMeasure.function.parameter.type=="constant"&&$scope.newMeasure.function.expression!=="COUNT_DISTINCT"){
      switch($scope.newMeasure.function.expression){
        case "SUM":
        case "COUNT":
          $scope.newMeasure.function.returntype = "bigint";
          break;
        default:
          $scope.newMeasure.function.returntype = "";
          break;
      }
    }
    if($scope.newMeasure.function.parameter.type=="column"&&$scope.newMeasure.function.expression!=="COUNT_DISTINCT"){

      var column = $scope.newMeasure.function.parameter.value;
      var colType = $scope.getColumnType(column, $scope.metaModel.model.fact_table); // $scope.getColumnType defined in cubeEdit.js

      if(colType==""||!colType){
        $scope.newMeasure.function.returntype = "";
        return;
      }

      switch($scope.newMeasure.function.expression){
        case "SUM":
          if(colType==="smallint"||colType==="int"||colType==="bigint"||colType==="integer"){
            $scope.newMeasure.function.returntype= 'bigint';
          }else{
            if(colType.indexOf('decimal')!=-1){
              $scope.newMeasure.function.returntype= colType;
            }else{
              $scope.newMeasure.function.returntype= 'decimal';
            }
          }
          break;
        case "MIN":
        case "MAX":
          $scope.newMeasure.function.returntype = colType;
          break;
        case "COUNT":
          $scope.newMeasure.function.returntype = "bigint";
          break;
        default:
          $scope.newMeasure.function.returntype = "";
          break;
      }
    }
  }

});
<|endoftext|>


<commit_before><commit_msg>DevTools: when script has URL all breakpoints are set using that URL and line number, otherwise breakpoint is set using script id and line number. Breakpoints set using URL will survive page reload.<commit_after><|endoftext|>


<commit_before>var escape = require('escape-html'),
  fs = require('fs'),
  highlight = require('highlight.js'),
  Hogan = require('hogan.js'),
  marked = require('marked'),
  path = require('path');

highlight.registerLanguage('bigfix-relevance', require('./relevance.js'));

function typeAnchor(type) {
  var href = '/reference/types/' + type.replace(/ /g, '-') + '.html';
  return '' + escape(type) + '';
}

function linkType(type) {
  var openParen = type.indexOf('(');

  if (openParen === -1) {
    return typeAnchor(type);
  }

  var links = type
    .substring(openParen + 2, type.length - 2)
    .split(', ')
    .map(typeAnchor)
    .join(', ');

  return type.substr(0, openParen) + '( ' + links + ' )';
}

function escapeKey(key) {
  return key
    .replace(/ < /, ' less ')
    .replace(/ > /, ' greater ')
    .replace(/ <= /, ' lesseq ')
    .replace(/ >= /, ' greatereq ')
    .replace(/ = /, ' equals ')
    .replace(/ \+ /, ' plus ')
    .replace(/ - /, ' minus ')
    .replace(/ \* /, ' times ')
    .replace(/ \/ /, ' divide ')
    .replace(/ & /, ' concat ')
    .replace(/[<>]/g, '')
    .replace(/[()]/g, '')
    .replace(/\s+/g, '-');
}

function makeAvailability(value) {
  var availability = [];

  Object.keys(value.availability).forEach(function(version) {
    availability.push({
      version: version,
      platforms: value.availability[version].join(', ')
    });
  });

  return availability;
}

function parseExample(text) {
  var example = { question: '', answers: [], errors: [] };

  text.trim().split('\n').forEach(function(line) {
    if (line.indexOf('Q:') === 0) {
      example.question =
        highlight.highlight('bigfix-relevance', line.substr(2).trim()).value;
    } else if (line.indexOf('A:') === 0) {
      example.answers.push({text: line.substr(2).trim()});
    } else if (line.indexOf('E:') === 0) {
      example.errors.push({text: line.substr(2).trim()});
    }
  });

  return example;
}

function renderProperty(property, template) {
  var data = {
    singularPhrase: property.singularPhrase,
    resultHtml: linkType(property.resultType)
  };

  if (property.indexType) {
    data.indexHtml = linkType(property.indexType);
  }

  if (property.directObjectType) {
    data.directObjectHtml = linkType(property.directObjectType);
  }

  return template.render(data);
}

function renderCast(property, template) {
  var data = {
    argHtml: linkType(property.argType),
    phrase: property.phrase,
    resultHtml: linkType(property.resultType)
  };

  return template.render(data);
}

function renderBinaryOp(property, template) {
  var data = {
    leftHtml: linkType(property.leftType),
    op: property.op,
    rightHtml: linkType(property.rightType),
    resultHtml: linkType(property.resultType)
  };

  return template.render(data);
}

function renderUnaryOp(property, template) {
  var data = {
    op: property.op,
    argHtml: linkType(property.argType),
    resultHtml: linkType(property.resultType)
  };

  return template.render(data);
}

function renderEntry(heading, body, property, template) {
  var data = {
    id: escapeKey(property.key),
    heading: heading,
    body: body,
    availability: makeAvailability(property)
  };

  if (property.pluralPhrase) {
    data.plural = property.pluralPhrase;
  }

  return template.render(data);
}

function renderText(text, templates) {
  var exampleData = {
    example: function() {
      return function(text) {
        return templates.example.render(parseExample(text));
      }
    }
  };

  return marked(Hogan.compile(text).render(exampleData));
}

function renderProperties(language, docs, templates) {
  var rendered = {};

  Object.keys(docs.properties).forEach(function(key) {
    var property = language.properties[key];

    var heading;
    if (property.type === 'property') {
      heading = renderProperty(property, templates.properties.property);
    } else if (property.type === 'cast') {
      heading = renderCast(property, templates.properties.cast);
    } else if (property.type === 'binaryOp') {
      heading = renderBinaryOp(property, templates.properties.binary);
    } else if (property.type === 'unaryOp') {
      heading = renderUnaryOp(property, templates.properties.unary);
    }

    var body = renderText(docs.properties[key], templates);

    rendered[key] = renderEntry(heading, body, property, templates.entry);
  });

  return rendered;
}

function renderType(type, text, renderedProperties, associations, templates) {
  var creation = associations.creation[type.name];
  var methods = associations.methods[type.name];

  function getDoc(property) {
    return renderedProperties[property];
  }

  var data = {
    name: type.name,
    description: renderText(text, templates),
    availability: makeAvailability(type)
  };

  if (type.parent) {
    data.parentHtml = linkType(type.parent);
  } else {
    data.parentHtml = 'none';
  }

  var creationEntries = creation.properties.sort()
    .concat(creation.casts.sort())
    .concat(creation.operators.sort());

  if (creationEntries.length !== 0) {
    data.creation = creationEntries.map(getDoc).join('\n\n');
  }

  if (methods.properties.length !== 0) {
    data.properties = methods.properties.sort().map(getDoc).join('\n\n');
  }

  if (methods.casts.length !== 0) {
    data.casts = methods.casts.sort().map(getDoc).join('\n\n');
  }

  if (methods.operators.length !== 0) {
    data.operators = methods.operators.sort().map(getDoc).join('\n\n');
  }

  return templates.type.render(data);
}

function render(language, docs, associations, templates) {
  var pages = [];

  var renderedProperties = renderProperties(language, docs, templates);

  Object.keys(language.types).forEach(function(key) {
    var type = language.types[key];
    var text = docs.types[key];

    var content =
      renderType(type, text, renderedProperties, associations, templates);

    var data = {
      title: type.name,
      content: content
    };

    var href =
      path.join('reference', 'types', type.name.replace(/ /g, '-') + '.html');

    var content = templates.page.render(data);

    pages.push({ href: href, content: content });
  });

  return pages;
}

module.exports = render;
<commit_msg>Consider tuple types when generating element ids<commit_after>var escape = require('escape-html'),
  fs = require('fs'),
  highlight = require('highlight.js'),
  Hogan = require('hogan.js'),
  marked = require('marked'),
  path = require('path');

highlight.registerLanguage('bigfix-relevance', require('./relevance.js'));

function typeAnchor(type) {
  var href = '/reference/types/' + type.replace(/ /g, '-') + '.html';
  return '' + escape(type) + '';
}

function linkType(type) {
  var openParen = type.indexOf('(');

  if (openParen === -1) {
    return typeAnchor(type);
  }

  var links = type
    .substring(openParen + 2, type.length - 2)
    .split(', ')
    .map(typeAnchor)
    .join(', ');

  return type.substr(0, openParen) + '( ' + links + ' )';
}

function escapeKey(key) {
  var escaped = key
    .replace(/ < /, ' less ')
    .replace(/ > /, ' greater ')
    .replace(/ <= /, ' lesseq ')
    .replace(/ >= /, ' greatereq ')
    .replace(/ = /, ' equals ')
    .replace(/ \+ /, ' plus ')
    .replace(/ - /, ' minus ')
    .replace(/ \* /, ' times ')
    .replace(/ \/ /, ' divide ')
    .replace(/ & /, ' concat ')
    .replace(/,/g, '')
    .replace(/[<>]/g, '')
    .replace(/[()]/g, '');

  return escaped.trim().replace(/\s+/g, '-');
}

function makeAvailability(value) {
  var availability = [];

  Object.keys(value.availability).forEach(function(version) {
    availability.push({
      version: version,
      platforms: value.availability[version].join(', ')
    });
  });

  return availability;
}

function parseExample(text) {
  var example = { question: '', answers: [], errors: [] };

  text.trim().split('\n').forEach(function(line) {
    if (line.indexOf('Q:') === 0) {
      example.question =
        highlight.highlight('bigfix-relevance', line.substr(2).trim()).value;
    } else if (line.indexOf('A:') === 0) {
      example.answers.push({text: line.substr(2).trim()});
    } else if (line.indexOf('E:') === 0) {
      example.errors.push({text: line.substr(2).trim()});
    }
  });

  return example;
}

function renderProperty(property, template) {
  var data = {
    singularPhrase: property.singularPhrase,
    resultHtml: linkType(property.resultType)
  };

  if (property.indexType) {
    data.indexHtml = linkType(property.indexType);
  }

  if (property.directObjectType) {
    data.directObjectHtml = linkType(property.directObjectType);
  }

  return template.render(data);
}

function renderCast(property, template) {
  var data = {
    argHtml: linkType(property.argType),
    phrase: property.phrase,
    resultHtml: linkType(property.resultType)
  };

  return template.render(data);
}

function renderBinaryOp(property, template) {
  var data = {
    leftHtml: linkType(property.leftType),
    op: property.op,
    rightHtml: linkType(property.rightType),
    resultHtml: linkType(property.resultType)
  };

  return template.render(data);
}

function renderUnaryOp(property, template) {
  var data = {
    op: property.op,
    argHtml: linkType(property.argType),
    resultHtml: linkType(property.resultType)
  };

  return template.render(data);
}

function renderEntry(heading, body, property, template) {
  var data = {
    id: escapeKey(property.key),
    heading: heading,
    body: body,
    availability: makeAvailability(property)
  };

  if (property.pluralPhrase) {
    data.plural = property.pluralPhrase;
  }

  return template.render(data);
}

function renderText(text, templates) {
  var exampleData = {
    example: function() {
      return function(text) {
        return templates.example.render(parseExample(text));
      }
    }
  };

  return marked(Hogan.compile(text).render(exampleData));
}

function renderProperties(language, docs, templates) {
  var rendered = {};

  Object.keys(docs.properties).forEach(function(key) {
    var property = language.properties[key];

    var heading;
    if (property.type === 'property') {
      heading = renderProperty(property, templates.properties.property);
    } else if (property.type === 'cast') {
      heading = renderCast(property, templates.properties.cast);
    } else if (property.type === 'binaryOp') {
      heading = renderBinaryOp(property, templates.properties.binary);
    } else if (property.type === 'unaryOp') {
      heading = renderUnaryOp(property, templates.properties.unary);
    }

    var body = renderText(docs.properties[key], templates);

    rendered[key] = renderEntry(heading, body, property, templates.entry);
  });

  return rendered;
}

function renderType(type, text, renderedProperties, associations, templates) {
  var creation = associations.creation[type.name];
  var methods = associations.methods[type.name];

  function getDoc(property) {
    return renderedProperties[property];
  }

  var data = {
    name: type.name,
    description: renderText(text, templates),
    availability: makeAvailability(type)
  };

  if (type.parent) {
    data.parentHtml = linkType(type.parent);
  } else {
    data.parentHtml = 'none';
  }

  var creationEntries = creation.properties.sort()
    .concat(creation.casts.sort())
    .concat(creation.operators.sort());

  if (creationEntries.length !== 0) {
    data.creation = creationEntries.map(getDoc).join('\n\n');
  }

  if (methods.properties.length !== 0) {
    data.properties = methods.properties.sort().map(getDoc).join('\n\n');
  }

  if (methods.casts.length !== 0) {
    data.casts = methods.casts.sort().map(getDoc).join('\n\n');
  }

  if (methods.operators.length !== 0) {
    data.operators = methods.operators.sort().map(getDoc).join('\n\n');
  }

  return templates.type.render(data);
}

function render(language, docs, associations, templates) {
  var pages = [];

  var renderedProperties = renderProperties(language, docs, templates);

  Object.keys(language.types).forEach(function(key) {
    var type = language.types[key];
    var text = docs.types[key];

    var content =
      renderType(type, text, renderedProperties, associations, templates);

    var data = {
      title: type.name,
      content: content
    };

    var href =
      path.join('reference', 'types', type.name.replace(/ /g, '-') + '.html');

    var content = templates.page.render(data);

    pages.push({ href: href, content: content });
  });

  return pages;
}

module.exports = render;
<|endoftext|>


<commit_before>/**
 * Takes a movetree and returns the optimal BoardRegion-Quad for cropping purposes.
 *
 * Note: This isn't a minimal cropping: we split the board into 4 quadrants.
 * Then, we use the quad as part of the final quad-output. Note that we only
 * allow convex shapes.  Thus, these aren't allowed (where the X's are
 * quad-regions)
 * .X     X.
 * X. and XX
 */
glift.bridge.getQuadCropFromMovetree = function(movetree) {
  var bbox = glift.displays.bbox.fromPts;
  var pt = glift.util.point;
  var boardRegions = glift.enums.boardRegions;
  // Intersections need to be 0 rather than 1 indexed for this method.
  var ints = movetree.getIntersections() - 1;
  var middle = Math.ceil(ints / 2);

  // Tracker is a map from quad-key to array of points.
  var tracker = {};
  var numstones = 0;

  // It's not clear to me if we should be cropping boards smaller than 19.  It
  // usually looks pretty weird, so hence this override.
  if (movetree.getIntersections() !== 19) {
    return boardRegions.ALL;
  }

  var quads = {};
  quads[boardRegions.TOP_LEFT] = bbox(pt(0, 0), pt(middle, middle));
  quads[boardRegions.TOP_RIGHT] = bbox(pt(middle, 0), pt(ints, middle));
  quads[boardRegions.BOTTOM_LEFT] = bbox(pt(0, middle), pt(middle, ints));
  quads[boardRegions.BOTTOM_RIGHT] = bbox(pt(middle, middle), pt(ints, ints));

  movetree.recurseFromRoot(function(mt) {
    var stones = mt.properties().getAllStones();
    for (var color in stones) {
      var points = stones[color];
      for (var i = 0; i < points.length; i++) {
        var pt = points[i];
        numstones += 1
        for (var quadkey in quads) {
          var box = quads[quadkey];
          if (middle === pt.x() || middle === pt.y()) {
            // Ignore points right on the middle.  It shouldn't make a different
            // for cropping, anyway.
          } else if (box.contains(pt)) {
            if (tracker[quadkey] === undefined) tracker[quadkey] = [];
            tracker[quadkey].push(pt);
          }
        }
      }
    }
  });
  return glift.bridge._getRegionFromTracker(tracker, numstones);
};

glift.bridge._getRegionFromTracker = function(tracker, numstones) {
  var regions = [], br = glift.enums.boardRegions;
  for (var quadkey in tracker) {
    var quadlist = tracker[quadkey];
    regions.push(quadkey);
  }
  if (regions.length === 1) {
    return regions[0];
  }
  if (regions.length !== 2) {
    return glift.enums.boardRegions.ALL;
  }
  var newset = glift.util.intersection(
    glift.util.regions.getComponents(regions[0]),
    glift.util.regions.getComponents(regions[1]));
  // there should only be one element at this point or nothing
  for (var key in newset) {
    return key;
  }
  return glift.enums.boardRegions.ALL;
};

/**
 * Rotates a movetree so that it's canonical, given some cropbox
 */
glift.bridge.canonicalRotate = function(movetree, regionOrdering) {
  // TODO(kashomon): Fill this in
};
<commit_msg>More work on autorotation.<commit_after>/**
 * Takes a movetree and returns the optimal BoardRegion-Quad for cropping purposes.
 *
 * Note: This isn't a minimal cropping: we split the board into 4 quadrants.
 * Then, we use the quad as part of the final quad-output. Note that we only
 * allow convex shapes.  Thus, these aren't allowed (where the X's are
 * quad-regions)
 * .X     X.
 * X. and XX
 */
glift.bridge.getQuadCropFromMovetree = function(movetree) {
  var bbox = glift.displays.bbox.fromPts;
  var pt = glift.util.point;
  var boardRegions = glift.enums.boardRegions;
  // Intersections need to be 0 rather than 1 indexed for this method.
  var ints = movetree.getIntersections() - 1;
  var middle = Math.ceil(ints / 2);

  // Tracker is a map from quad-key to array of points.
  var tracker = {};
  var numstones = 0;

  // It's not clear to me if we should be cropping boards smaller than 19.  It
  // usually looks pretty weird, so hence this override.
  if (movetree.getIntersections() !== 19) {
    return boardRegions.ALL;
  }

  var quads = {};
  quads[boardRegions.TOP_LEFT] = bbox(pt(0, 0), pt(middle, middle));
  quads[boardRegions.TOP_RIGHT] = bbox(pt(middle, 0), pt(ints, middle));
  quads[boardRegions.BOTTOM_LEFT] = bbox(pt(0, middle), pt(middle, ints));
  quads[boardRegions.BOTTOM_RIGHT] = bbox(pt(middle, middle), pt(ints, ints));

  movetree.recurseFromRoot(function(mt) {
    var stones = mt.properties().getAllStones();
    for (var color in stones) {
      var points = stones[color];
      for (var i = 0; i < points.length; i++) {
        var pt = points[i];
        numstones += 1
        for (var quadkey in quads) {
          var box = quads[quadkey];
          if (middle === pt.x() || middle === pt.y()) {
            // Ignore points right on the middle.  It shouldn't make a different
            // for cropping, anyway.
          } else if (box.contains(pt)) {
            if (tracker[quadkey] === undefined) tracker[quadkey] = [];
            tracker[quadkey].push(pt);
          }
        }
      }
    }
  });
  return glift.bridge._getRegionFromTracker(tracker, numstones);
};

glift.bridge._getRegionFromTracker = function(tracker, numstones) {
  var regions = [], br = glift.enums.boardRegions;
  for (var quadkey in tracker) {
    var quadlist = tracker[quadkey];
    regions.push(quadkey);
  }
  if (regions.length === 1) {
    return regions[0];
  }
  if (regions.length !== 2) {
    return glift.enums.boardRegions.ALL;
  }
  var newset = glift.util.intersection(
    glift.util.regions.getComponents(regions[0]),
    glift.util.regions.getComponents(regions[1]));
  // there should only be one element at this point or nothing
  for (var key in newset) {
    return key;
  }
  return glift.enums.boardRegions.ALL;
};

/**
 * Rotates a movetree so that it's canonical, given some cropbox
 */
glift.bridge.canonicalRotate = function(movetree, regionOrdering) {
  var boardRegions = glift.enums.boardRegions;
  var cornerRegions = {
    TOP_LEFT: true,
    TOP_RIGHT: true,
    BOTTOM_RIGHT: true,
    BOTTOM_LEFT: true
  };
  var sideRegions = {
    TOP: true,
    BOTTOM: true,
    LEFT: true,
    RIGHT: true
  };

  if (!regionOrdering) {
    regionOrdering = {
      corner: boardRegions.TOP_RIGHT,
      side: boardRegions.TOP
    };
  }
  var region = glift.bridge.getQuadCropFromMovetree(movetree);
  if (cornerRegions[region]) {
  }

  if (sideRegions[region]) {
  }
};
<|endoftext|>


<commit_before>describe('certificates', function () {
    var fs = require('fs'),
        path = require('path'),
        CertificateList = require('postman-collection').CertificateList,
        https = require('https'),

        certificateId = 'test-certificate',

        server,
        testrun;

    before(function (done) {
        var port = 9090,
            certDataPath = path.join(__dirname, '..', '..', 'integration-legacy', 'data'),
            clientKeyPath = path.join(certDataPath, 'client1-key.pem'),
            clientCertPath = path.join(certDataPath, 'client1-crt.pem'),

            serverKeyPath = path.join(certDataPath, 'server-key.pem'),
            serverCertPath = path.join(certDataPath, 'server-crt.pem'),
            serverCaPath = path.join(certDataPath, 'ca-crt.pem'),

            certificateList = new CertificateList({}, [{
                id: certificateId,
                matches: ['https://localhost:' + port + '/*'],
                key: {src: clientKeyPath},
                cert: {src: clientCertPath}
            }]);

        server = https.createServer({
            key: fs.readFileSync(serverKeyPath),
            cert: fs.readFileSync(serverCertPath),
            ca: fs.readFileSync(serverCaPath),
            requestCert: true
        });

        server.on('request', function (req, res) {
            if (req.client.authorized) {
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end('authorized\n');
            }
            else {
                res.writeHead(401, {'Content-Type': 'text/plain'});
                res.end('unauthorized\n');
            }
        });

        server.listen(port, 'localhost');

        this.run({
            collection: {
                item: {
                    request: 'https://localhost:' + port + '/'
                }
            },
            requester: {
                strictSSL: false
            },
            fileResolver: fs,
            certificates: certificateList
        }, function (err, results) {
            testrun = results;
            done(err);
        });
    });

    it('must have started and completed the test run', function () {
        expect(testrun).be.ok();
        expect(testrun.done.calledOnce).be.ok();
        expect(testrun.start.calledOnce).be.ok();
    });

    it('must receive response from https server', function () {
        var response = testrun.request.getCall(0).args[2];

        expect(response.text()).to.eql('authorized\n');
    });

    it('must have certificate attached to request', function () {
        var request = testrun.request.getCall(0).args[3].toJSON();

        expect(request.certificate.id).to.eql(certificateId);
    });

    after(function () {
        server.close();
    });
});
<commit_msg>added a test for invalid cert paths<commit_after>describe('certificates', function () {
    var fs = require('fs'),
        path = require('path'),
        CertificateList = require('postman-collection').CertificateList,
        https = require('https'),

        certificateId = 'test-certificate',

        server,
        testrun;

    describe('valid', function () {
        before(function (done) {
            var port = 9090,
                certDataPath = path.join(__dirname, '..', '..', 'integration-legacy', 'data'),
                clientKeyPath = path.join(certDataPath, 'client1-key.pem'),
                clientCertPath = path.join(certDataPath, 'client1-crt.pem'),

                serverKeyPath = path.join(certDataPath, 'server-key.pem'),
                serverCertPath = path.join(certDataPath, 'server-crt.pem'),
                serverCaPath = path.join(certDataPath, 'ca-crt.pem'),

                certificateList = new CertificateList({}, [{
                    id: certificateId,
                    matches: ['https://localhost:' + port + '/*'],
                    key: { src: clientKeyPath },
                    cert: { src: clientCertPath }
                }]);

            server = https.createServer({
                key: fs.readFileSync(serverKeyPath),
                cert: fs.readFileSync(serverCertPath),
                ca: fs.readFileSync(serverCaPath),
                requestCert: true
            });

            server.on('request', function (req, res) {
                if (req.client.authorized) {
                    res.writeHead(200, { 'Content-Type': 'text/plain' });
                    res.end('authorized\n');
                }
                else {
                    res.writeHead(401, { 'Content-Type': 'text/plain' });
                    res.end('unauthorized\n');
                }
            });

            server.listen(port, 'localhost');

            this.run({
                collection: {
                    item: {
                        request: 'https://localhost:' + port + '/'
                    }
                },
                requester: {
                    strictSSL: false
                },
                fileResolver: fs,
                certificates: certificateList
            }, function (err, results) {
                testrun = results;
                done(err);
            });
        });

        it('must have started and completed the test run', function () {
            expect(testrun).be.ok();
            expect(testrun.done.calledOnce).be.ok();
            expect(testrun.start.calledOnce).be.ok();
        });

        it('must receive response from https server', function () {
            var response = testrun.request.getCall(0).args[2];

            expect(response.text()).to.eql('authorized\n');
        });

        it('must have certificate attached to request', function () {
            var request = testrun.request.getCall(0).args[3].toJSON();

            expect(request.certificate.id).to.eql(certificateId);
        });

        after(function () {
            server.close();
        });
    });

    describe.skip('invalid', function () {
        before(function (done) {
            var port = 9090,
                certDataPath = path.join(__dirname, '..', '..', 'integration-legacy', 'data'),
                clientKeyPath = path.join('/tmp/non-existent/', 'client1-key.pem'),
                clientCertPath = path.join('/tmp/non-existent/', 'client1-crt.pem'),

                serverKeyPath = path.join(certDataPath, 'server-key.pem'),
                serverCertPath = path.join(certDataPath, 'server-crt.pem'),
                serverCaPath = path.join(certDataPath, 'ca-crt.pem'),

                certificateList = new CertificateList({}, [{
                    id: certificateId,
                    matches: ['https://localhost:' + port + '/*'],
                    key: { src: clientKeyPath },
                    cert: { src: clientCertPath }
                }]);

            server = https.createServer({
                key: fs.readFileSync(serverKeyPath),
                cert: fs.readFileSync(serverCertPath),
                ca: fs.readFileSync(serverCaPath),
                requestCert: true
            });

            server.on('request', function (req, res) {
                if (req.client.authorized) {
                    res.writeHead(200, { 'Content-Type': 'text/plain' });
                    res.end('authorized\n');
                }
                else {
                    res.writeHead(401, { 'Content-Type': 'text/plain' });
                    res.end('unauthorized\n');
                }
            });

            server.listen(port, 'localhost');

            this.run({
                collection: {
                    item: {
                        request: 'https://localhost:' + port + '/'
                    }
                },
                requester: {
                    strictSSL: false
                },
                fileResolver: fs,
                certificates: certificateList
            }, function (err, results) {
                testrun = results;
                done(err);
            });
        });

        it('must have started and completed the test run', function () {
            expect(testrun).be.ok();
            expect(testrun.done.calledOnce).be.ok();
            expect(testrun.start.calledOnce).be.ok();
        });

        it('must not throw an error', function () {
            var response = testrun.request.getCall(0).args[2];

            expect(response.text()).to.eql('authorized\n');
        });

        it('must have certificate attached to request', function () {
            var request = testrun.request.getCall(0).args[3].toJSON();

            expect(request.certificate.id).to.eql(certificateId);
        });

        after(function () {
            server.close();
        });
    });
});
<|endoftext|>