<commit_before>module.exports = {
    metadata: {
        plugin: "scene",
        label: "Scene",
        role: "actor",
        family: "scene",
        deviceTypes: ["philips-hue/hueBridge"],
        services: [{
            id: "on",
            label: "On"
        }, {
            id: "off",
            label: "Off"
        }, {
            id: "toggle",
            label: "Toggle"
        }],
        state: [{
            label: "Scenes",
            id: "scenes",
            type: {
                id: "any"
            }
        }, {
            label: "Rooms",
            id: "rooms",
            type: {
                id: "any"
            }
        }, {
            label: "Selected Scene",
            id: "selectedScene",
            type: {
                id: "any"
            }
        }, {
            label: "Selected Room",
            id: "selectedRoom",
            type: {
                id: "any"
            }
        }, {
            label: "Scene Active",
            id: "sceneActive",
            type: {
                id: "boolean"
            }
        }],
        configuration: [{
            label: "Scene Name",
            id: "sceneName",
            type: {
                id: "string"
            },
        }, {
            label: "Room Name",
            id: "roomName",
            type:{
                id: "string"
            }
        }]
    },
    create: function () {
        return new Scene();
    }
};

var q = require('q');
var hue = require('node-hue-api');

function Scene(){
    /**
     *
     */
    Scene.prototype.start = function(){
        var deferred = q.defer();

        if (!this.isSimulated()){

            this.newScenes = [];
            this.state.rooms = [];

            this.device.hueApi.scenes()
                .then(function (result) {
                    for (var n in result) {
                        this.newScenes.push({sceneName: result[n].name, sceneId: result[n].id, Lights: result[n].lights});
                    }
                }.bind(this)).done();

            this.device.hueApi.groups()
                .then(function (group) {
                    for (var n in group) {
                        this.state.rooms.push({roomName: group[n].name, roomId: group[n].id, Lights: group[n].lights});
                    }
                    this.publishStateChange();
                    }.bind(this)).done();

            // for(var n in this.state.rooms) {
            //     if (this.state.selectedRoom === this.state.rooms[n].roomId)
            //         for (var x in newScenes) {
            //             if (this.state.rooms[n].Lights === newScenes[x].Lights) {
            //                 this.state.scenes.push({sceneName: newScenes[x].sceneName, sceneId: newScenes[x].sceneId});
            //             }
            //         }
            // }

            this.state.sceneActive = false;
            this.publishStateChange();
        }
        deferred.resolve();

        return deferred.promise;
    };

    /**
     *
     */
    Scene.prototype.stop = function () {

    };

    /**
     *
     */
    Scene.prototype.getState = function () {

        this.newScenes = [];
        this.state.rooms = [];

        this.device.hueApi.scenes()
            .then(function (result) {
                for (var n in result) {
                    this.newScenes.push({sceneName: result[n].name, sceneId: result[n].id, Lights: result[n].lights});
                }
            }.bind(this)).done();

        this.device.hueApi.groups()
            .then(function (group) {
                for (var n in group) {
                    this.state.rooms.push({roomName: group[n].name, roomId: group[n].id, Lights: group[n].lights});
                    this.publishStateChange();
                }
            }.bind(this)).done();
        //
        //  for(var n in this.state.rooms) {
        //     if (this.state.selectedRoom === this.state.rooms[n].roomId) {
        //         for (var x in newScenes) {
        //             if (this.state.rooms[n].Lights === newScenes[x].Lights) {
        //                 this.state.scenes.push({sceneName: newScenes[x].sceneName, sceneId: newScenes[x].sceneId});
        //             }
        //         }
        //     }
        // }

        this.publishStateChange();
        return this.state;
    };

    /**
     *
     */
    Scene.prototype.setState = function (state){
        this.state.scenes = [];

        for(var n in state.rooms){
            if (state.selectedRoom && state.selectedRoom === state.rooms[n].roomId){
                for(var m in this.newScenes){
                    if(this.newScenes[m] && this.newScenes[m].Lights === state.rooms[n].Lights){
                        this.state.scenes.push({sceneName: this.newScenes[m].sceneName, sceneId: this.newScenes[m].sceneId});
                        this.publishStateChange();
                    }
                }
            }
        }
    };

    /**
     *
     */
    Scene.prototype.on = function () {
        this.state.sceneActive = true;
        if (this.isSimulated()) {
            //this.publishStateChange();
        } else {
            this.device.hueApi.activateScene(this.state.selectedScene).then(function(result){
                this.logDebug("Scene Active: ", result);
                this.publishStateChange();
            }.bind(this)).done();
        }
        this.publishStateChange();
    };

    /**
     *
     */
    Scene.prototype.off = function () {
        this.state.sceneActive = false;

        if (this.isSimulated()) {
            //this.publishStateChange();
        } else {
            this.device.hueApi.setGroupLightState(this.state.selectedRoom, hue.lightState.create().off()).then(function (result) {
                this.logDebug("Scene Not Active: ",result);
                this.publishStateChange();
                }.bind(this)).done();
        }
        this.publishStateChange();
    };

    /**
     *
     */
    Scene.prototype.toggle = function () {
        if (this.state.sceneActive) {
            this.off();
        }
        else {
            this.on();
        }
    };
}<commit_msg>Updated setState function<commit_after>module.exports = {
    metadata: {
        plugin: "scene",
        label: "Scene",
        role: "actor",
        family: "scene",
        deviceTypes: ["philips-hue/hueBridge"],
        services: [{
            id: "on",
            label: "On"
        }, {
            id: "off",
            label: "Off"
        }, {
            id: "toggle",
            label: "Toggle"
        }],
        state: [{
            label: "Scenes",
            id: "scenes",
            type: {
                id: "any"
            }
        }, {
            label: "Rooms",
            id: "rooms",
            type: {
                id: "any"
            }
        }, {
            label: "Selected Scene",
            id: "selectedScene",
            type: {
                id: "any"
            }
        }, {
            label: "Selected Room",
            id: "selectedRoom",
            type: {
                id: "any"
            }
        }, {
            label: "Scene Active",
            id: "sceneActive",
            type: {
                id: "boolean"
            }
        }],
        configuration: [{
            label: "Scene Name",
            id: "sceneName",
            type: {
                id: "string"
            },
        }, {
            label: "Room Name",
            id: "roomName",
            type:{
                id: "string"
            }
        }]
    },
    create: function () {
        return new Scene();
    }
};

var q = require('q');
var hue = require('node-hue-api');

function Scene(){
    /**
     *
     */
    Scene.prototype.start = function(){
        var deferred = q.defer();

        if (!this.isSimulated()){

            this.newScenes = [];
            this.state.rooms = [];

            this.device.hueApi.scenes()
                .then(function (result) {
                    for (var n in result) {
                        this.newScenes.push({sceneName: result[n].name, sceneId: result[n].id, Lights: result[n].lights});
                    }
                }.bind(this)).done();

            this.device.hueApi.groups()
                .then(function (group) {
                    for (var n in group) {
                        this.state.rooms.push({roomName: group[n].name, roomId: group[n].id, Lights: group[n].lights});
                    }
                    this.publishStateChange();
                    }.bind(this)).done();

            // for(var n in this.state.rooms) {
            //     if (this.state.selectedRoom === this.state.rooms[n].roomId)
            //         for (var x in newScenes) {
            //             if (this.state.rooms[n].Lights === newScenes[x].Lights) {
            //                 this.state.scenes.push({sceneName: newScenes[x].sceneName, sceneId: newScenes[x].sceneId});
            //             }
            //         }
            // }

            this.state.sceneActive = false;
            this.publishStateChange();
        }
        deferred.resolve();

        return deferred.promise;
    };

    /**
     *
     */
    Scene.prototype.stop = function () {

    };

    /**
     *
     */
    Scene.prototype.getState = function () {

        this.newScenes = [];
        this.state.rooms = [];

        this.device.hueApi.scenes()
            .then(function (result) {
                for (var n in result) {
                    this.newScenes.push({sceneName: result[n].name, sceneId: result[n].id, Lights: result[n].lights});
                }
            }.bind(this)).done();

        this.device.hueApi.groups()
            .then(function (group) {
                for (var n in group) {
                    this.state.rooms.push({roomName: group[n].name, roomId: group[n].id, Lights: group[n].lights});
                    this.publishStateChange();
                }
            }.bind(this)).done();
        //
        //  for(var n in this.state.rooms) {
        //     if (this.state.selectedRoom === this.state.rooms[n].roomId) {
        //         for (var x in newScenes) {
        //             if (this.state.rooms[n].Lights === newScenes[x].Lights) {
        //                 this.state.scenes.push({sceneName: newScenes[x].sceneName, sceneId: newScenes[x].sceneId});
        //             }
        //         }
        //     }
        // }

        return this.state;
    };

    /**
     *
     */
    Scene.prototype.setState = function (state){
        this.state.scenes = [];

        for(var n in state.rooms){
            if (state.selectedRoom && state.selectedRoom === state.rooms[n].roomId){
                for(var m in this.newScenes){
                    if(this.newScenes[m] && this.newScenes[m].Lights === state.rooms[n].Lights){
                        this.state.scenes.push({sceneName: this.newScenes[m].sceneName, sceneId: this.newScenes[m].sceneId});
                        this.publishStateChange();
                    }
                }
            }
        }
    };

    /**
     *
     */
    Scene.prototype.on = function () {
        this.state.sceneActive = true;
        if (this.isSimulated()) {
            //this.publishStateChange();
        } else {
            this.device.hueApi.activateScene(this.state.selectedScene).then(function(result){
                this.logDebug("Scene Active: ", result);
                this.publishStateChange();
            }.bind(this)).done();
        }
        this.publishStateChange();
    };

    /**
     *
     */
    Scene.prototype.off = function () {
        this.state.sceneActive = false;

        if (this.isSimulated()) {
            //this.publishStateChange();
        } else {
            this.device.hueApi.setGroupLightState(this.state.selectedRoom, hue.lightState.create().off()).then(function (result) {
                this.logDebug("Scene Not Active: ",result);
                this.publishStateChange();
                }.bind(this)).done();
        }
        this.publishStateChange();
    };

    /**
     *
     */
    Scene.prototype.toggle = function () {
        if (this.state.sceneActive) {
            this.off();
        }
        else {
            this.on();
        }
    };
}<|endoftext|>


<commit_before>"use strict";
const utils = require("../utils");

var testSizes = [100, 1000, 10000, 100000, 1000000];
var testTimeResults = [];

testSizes.forEach(n => {
  var toBeSorted, sorted, startTime, endTime;
  toBeSorted = utils.createRandomArray(n);
  startTime = +new Date();

  sorted = quickSort(toBeSorted);

  endTime = +new Date();
  console.log(`n=${n} took ${endTime - startTime}ms`);
  testTimeResults.push(endTime - startTime);

  // Check if the array is sorted
  utils.isSorted(sorted);
});

function swap(array, i, j) {
  var temp = array[i];
  array[i] = array[j];
  array[j] = temp;
}

function partition(array, low, high) {
  // array[low] is the pivot
  var lIndex = low;
  var rIndex = high + 1;
  while (true) {
    // From the left, search an element equal or bigger than the pivot
    while (array[++lIndex] <= array[low]) if (lIndex === high) break;
    // From the right, search an element smaller than the pivot
    while (array[--rIndex] > array[low]) if (rIndex === low) break;
    // This signal the end of the search
    if (lIndex >= rIndex) break;
    swap(array, lIndex, rIndex);
  }
  // Swap the pivot to its final position
  swap(array, rIndex, low);
  return rIndex;
}

function sort(array, low, high) {
  if (low >= high) return array;
  var partitionPivot = partition(array, low, high);
  sort(array, low, partitionPivot - 1);
  sort(array, partitionPivot + 1, high);
}

// Wrapper to avoid giving the user the responsability
// of computing the array boundaries
function quickSort(array) {
  sort(array, 0, array.length - 1);
  return array;
}
<commit_msg>A simpler implementation of the partition algorithm<commit_after>"use strict";
const utils = require("../utils");

var testSizes = [100, 1000, 10000, 100000, 1000000, 10000000];
var testTimeResults = [];

testSizes.forEach(n => {
  var toBeSorted, sorted, startTime, endTime;
  toBeSorted = utils.createRandomArray(n);
  startTime = +new Date();

  sorted = quickSort(toBeSorted);

  endTime = +new Date();
  console.log(`n=${n} took ${endTime - startTime}ms`);
  testTimeResults.push(endTime - startTime);

  // Check if the array is sorted
  utils.isSorted(sorted);
});

function swap(array, i, j) {
  var temp = array[i];
  array[i] = array[j];
  array[j] = temp;
}

/*
// This implementation appears on Algorithms Fourth Edition
// by Robert Sedgewick and Kevin Wayne
function partition(array, low, high) {
  // array[low] is the pivot
  var lIndex = low;
  var rIndex = high + 1;
  while (true) {
    // From the left, search an element equal or bigger than the pivot
    while (array[++lIndex] <= array[low]) if (lIndex === high) break;
    // From the right, search an element smaller than the pivot
    while (array[--rIndex] > array[low]) if (rIndex === low) break;
    // This signal the end of the search
    if (lIndex >= rIndex) break;
    swap(array, lIndex, rIndex);
  }
  // Swap the pivot to its final position
  swap(array, rIndex, low);
  return rIndex;
}
*/

function partition(array, low, high) {
  // The pivot is the first element of the array (array[low])
  var searchIndex = low + 1;
  for (var i = searchIndex; i <= high; i++) {
    if (array[i] < array[low]) {
      swap(array, i, searchIndex);
      searchIndex++;
    }
  }
  searchIndex--;
  swap(array, low, searchIndex);
  return searchIndex;
}

function sort(array, low, high) {
  if (low >= high) return array;
  var partitionPivot = partition(array, low, high);
  sort(array, low, partitionPivot - 1);
  sort(array, partitionPivot + 1, high);
}

// Wrapper to avoid giving the user the responsability
// of computing the array boundaries
function quickSort(array) {
  sort(array, 0, array.length - 1);
  return array;
}
<|endoftext|>


<commit_before>enyo.singleton({
	name: "Model",
	kind: "enyo.Component",
	debug: false,
	info: {},
	defaults: {
		properties: {
			owner: {filterLevel: "hidden"},
			container: {filterLevel: "hidden"},
			parent: {filterLevel: "hidden"},
			prepend: {filterLevel: "hidden"},
			events: {filterLevel: "hidden"},
			id: {filterLevel: "hidden"},
			isContainer: {filterLevel: "hidden"},
			controlParentName: {filterLevel: "hidden"},
			layoutKind: {filterLevel: "hidden"},
			canGenerate: {filterLevel: "dangerous", inputKind: "Inspector.Config.Boolean"},
			content: {filterLevel: "useful", inputKind: "Inspector.Config.Text"},
			name: {filterLevel: "useful", inputKind: "Inspector.Config.Text"}
		},
		events: {
			ontap: {filterLevel: "useful"}
		}
	},
	F_HIDDEN: -1,
	F_DANGEROUS: 1,
	F_NORMAL: 2,
	F_USEFUL: 3,

	levelMapping: null,			// Instanciated at create() time
	create: function() {
		this.inherited(arguments);
		//
		this.levelMapping = {
			"hidden": this.F_HIDDEN,
			"dangerous": this.F_DANGEROUS,
			"normal": this.F_NORMAL,
			"useful": this.F_USEFUL
		};
	},
	/**
	 * Reset the Model Information to default
	 * @public
	 */
	resetInformation: function() {
		if (this.debug)  { this.log("resetInformation!"); }
		this.info = {};
		this.addInformation("properties", "__default", this.defaults.properties);
		this.addInformation("events", "__default", this.defaults.events);
	},
	/**
	 * Build all the information needed by the inspector
	 * @public
	 */
	buildInformation: function(projectIndexer) {
		if (this.debug)  { this.log("buildInformation: Indexer: ", projectIndexer); }
		this.resetInformation();
		enyo.forEach(projectIndexer.propertyMetaData, function(item) {
			if (item.type === "kind") {
				if (this.debug) { this.log("Processing: " + item.name, item); }
				this.addInformation("properties", item.name, item.properties);
				this.addInformation("events", item.name, item.events);
			} else {
				enyo.error("Unknown data type='" + item.type + "' -- Ignored");
			}
		}, this);

	},
	addInformation: function(inType, inName, inInfo) {
		if (inInfo) {
			if (this.debug) { this.log("addInformation: Adding " + inType + " information for " + inName); }

			var fn = function(inType, inName, inSubName, inData) {
				if (inData.filterLevel) {
					inData.level = Model.levelMapping[inData.filterLevel];
					if ( ! inData.level) {
						inData.level = Model.F_NORMAL;
						enyo.error("Invalid filter level for " + inType + " " + inName + "." + inSubName);
					}
				} else {
					inData.level = Model.F_NORMAL;
				}
				if (this.debug) { this.log("addInformation: Setting level " + inData.level + " for " + inType + " " + inName + "." + inSubName); }
			};
			var addFilterLevel = enyo.bind(this, fn, inType, inName);

			if ( ! this.info[inName]) {
				this.info[inName] = {};
			}
			this.info[inName][inType] = inInfo;

			var keys = Object.keys(inInfo);
			for (var n = 0; n < keys.length; n++) {
				addFilterLevel(keys[n], inInfo[keys[n]]);
			}
		}
	},
	getInfo: function(inKind, inType, inName) {
		try {
			return this.info[inKind][inType][inName];
		} catch(error) {
			return;		// Return undefined
		}
	},
	getFilterLevel: function(inKind, inType, inName) {
		var info;
		try {
			info = this.getInfo(inKind, inType, inName);
			if (info && info.level) {
				return info.level;
			} else {
				return this.getInfo("__default", inType, inName).level || Model.F_NORMAL;
			}
		} catch(error) {
			info = this.getInfo("__default", inType, inName);
			return (info && info.level) || Model.F_NORMAL;
		}
	}
});
<commit_msg>ENYO-2263: getFlattenedContainerInfo will be revisited later<commit_after>enyo.singleton({
	name: "Model",
	kind: "enyo.Component",
	debug: false,
	info: {},
	defaults: {
		properties: {
			owner: {filterLevel: "hidden"},
			container: {filterLevel: "hidden"},
			parent: {filterLevel: "hidden"},
			prepend: {filterLevel: "hidden"},
			events: {filterLevel: "hidden"},
			id: {filterLevel: "hidden"},
			isContainer: {filterLevel: "hidden"},
			controlParentName: {filterLevel: "hidden"},
			layoutKind: {filterLevel: "hidden"},
			canGenerate: {filterLevel: "dangerous", inputKind: "Inspector.Config.Boolean"},
			content: {filterLevel: "useful", inputKind: "Inspector.Config.Text"},
			name: {filterLevel: "useful", inputKind: "Inspector.Config.Text"}
		},
		events: {
			ontap: {filterLevel: "useful"}
		}
	},
	F_HIDDEN: -1,
	F_DANGEROUS: 1,
	F_NORMAL: 2,
	F_USEFUL: 3,

	levelMapping: null,			// Instanciated at create() time
	create: function() {
		this.inherited(arguments);
		//
		this.levelMapping = {
			"hidden": this.F_HIDDEN,
			"dangerous": this.F_DANGEROUS,
			"normal": this.F_NORMAL,
			"useful": this.F_USEFUL
		};
	},
	/**
	 * Reset the Model Information to default
	 * @public
	 */
	resetInformation: function() {
		if (this.debug)  { this.log("resetInformation!"); }
		this.info = {};
		this.addInformation("properties", "__default", this.defaults.properties);
		this.addInformation("events", "__default", this.defaults.events);
	},
	/**
	 * Build all the information needed by the inspector
	 * @public
	 */
	buildInformation: function(projectIndexer) {
		if (this.debug)  { this.log("buildInformation: Indexer: ", projectIndexer); }
		this.resetInformation();
		enyo.forEach(projectIndexer.propertyMetaData, function(item) {
			if (item.type === "kind") {
				if (this.debug) { this.log("Processing: " + item.name, item); }
				this.addInformation("properties", item.name, item.properties);
				this.addInformation("events", item.name, item.events);
			} else {
				enyo.error("Unknown data type='" + item.type + "' -- Ignored");
			}
		}, this);

	},
	addInformation: function(inType, inName, inInfo) {
		if (inInfo) {
			if (this.debug) { this.log("addInformation: Adding " + inType + " information for " + inName); }

			var fn = function(inType, inName, inSubName, inData) {
				if (inData.filterLevel) {
					inData.level = Model.levelMapping[inData.filterLevel];
					if ( ! inData.level) {
						inData.level = Model.F_NORMAL;
						enyo.error("Invalid filter level for " + inType + " " + inName + "." + inSubName);
					}
				} else {
					inData.level = Model.F_NORMAL;
				}
				if (this.debug) { this.log("addInformation: Setting level " + inData.level + " for " + inType + " " + inName + "." + inSubName); }
			};
			var addFilterLevel = enyo.bind(this, fn, inType, inName);

			if ( ! this.info[inName]) {
				this.info[inName] = {};
			}
			this.info[inName][inType] = inInfo;

			var keys = Object.keys(inInfo);
			for (var n = 0; n < keys.length; n++) {
				addFilterLevel(keys[n], inInfo[keys[n]]);
			}
		}
	},
	getInfo: function(inKind, inType, inName) {
		try {
			return this.info[inKind][inType][inName];
		} catch(error) {
			return;		// Return undefined
		}
	},
	getFilterLevel: function(inKind, inType, inName) {
		var info;
		try {
			info = this.getInfo(inKind, inType, inName);
			if (info && info.level) {
				return info.level;
			} else {
				return this.getInfo("__default", inType, inName).level || Model.F_NORMAL;
			}
		} catch(error) {
			info = this.getInfo("__default", inType, inName);
			return (info && info.level) || Model.F_NORMAL;
		}
	},
	getFlattenedContainerInfo: function() {
		// TODO: item containerData is set to null, revisit this,
		// function called by the IFrameDesigner.sendIframeContainerData()
		return null;
	}
});
<|endoftext|>


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

    window.App.videos = [
        {
            title: 'Big Buck Bunny',
            url: 'http://smartimmo.ru/uploaded/big_buck_bunny_480p_h264.mp4',
            type: 'vod'
        },
        {
            title: 'Elephants Dream',
            url: 'https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4',
            type: 'vod'
        },
        {
            title: 'Europa plus',
            url: 'http://europaplus.cdnvideo.ru/europaplus-live/eptv_main.sdp/playlist.m3u8',
            type: 'hls'
        },
        {
            title: 'PIK TV',
            url: 'http://phone.pik-tv.com/live/mp4:piktv3pik3tv/playlist.m3u8',
            type: 'hls'
        },
        {
            title: 'Redbull',
            url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
            type: 'hls'
        }
    ];
})();<commit_msg>Update videos.js<commit_after>(function () {
    "use strict";

    window.App.videos = [
        {
            title: '1Big Buck Bunny',
            url: 'http://smartimmo.ru/uploaded/big_buck_bunny_480p_h264.mp4',
            type: 'vod'
        },
        {
            title: '2Elephants Dream',
            url: 'https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4',
            type: 'vod'
        },
        {
            title: '3Europa plus',
            url: 'http://europaplus.cdnvideo.ru/europaplus-live/eptv_main.sdp/playlist.m3u8',
            type: 'hls'
        },
        {
            title: '4PIK TV',
            url: 'http://phone.pik-tv.com/live/mp4:piktv3pik3tv/playlist.m3u8',
            type: 'hls'
        },
        {
            title: '5Redbull',
            url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
            type: 'hls'
        }
    ];
})();<|endoftext|>


<commit_before>(function(){

// Shortcut
var util = Crypto.util;

Crypto.HMAC = function (hasher, key, message, options) {

	// Allow arbitrary length keys
	key = key.length > hasher._blocksize * 4 ?
	      hasher(key, { asBytes: true }) :
	      util.stringToBytes(key);

	// XOR pad constants
	var okey = key,
	    ikey = key.slice(0);
	for (var i = 0; i < hasher._blocksize * 4; i++) {
		okey[i] ^= 0x5C;
		ikey[i] ^= 0x36;
	}

	var hmacbytes = hasher(util.bytesToString(okey) +
	                       hasher(util.bytesToString(ikey) + message, { asString: true }),
	                       { asBytes: true });
	return options && options.asBytes ? hmacbytes :
	       options && options.asHex ? util.bytesToHex(hmacbytes) :
	       util.bytesToString(hmacbytes);

};

})();
<commit_msg>Cosmetic.<commit_after>(function(){

// Shortcut
var util = Crypto.util;

Crypto.HMAC = function (hasher, key, message, options) {

	// Allow arbitrary length keys
	key = key.length > hasher._blocksize * 4 ?
	      hasher(key, { asBytes: true }) :
	      util.stringToBytes(key);

	// XOR keys with pad constants
	var okey = key,
	    ikey = key.slice(0);
	for (var i = 0; i < hasher._blocksize * 4; i++) {
		okey[i] ^= 0x5C;
		ikey[i] ^= 0x36;
	}

	var hmacbytes = hasher(util.bytesToString(okey) +
	                       hasher(util.bytesToString(ikey) + message, { asString: true }),
	                       { asBytes: true });
	return options && options.asBytes ? hmacbytes :
	       options && options.asHex ? util.bytesToHex(hmacbytes) :
	       util.bytesToString(hmacbytes);

};

})();
<|endoftext|>


<commit_before>///import editor.js
///import core/dom/dom.js
///import core/utils.js
/**
 * dtd html语义化的体现类
 * @constructor
 * @namespace dtd
 */
var dtd = dom.dtd = (function() {
    function _( s ) {
        for (var k in s) {
            s[k.toUpperCase()] = s[k];
        }
        return s;
    }
    var X = utils.extend2;
    var A = _({isindex:1,fieldset:1}),
        B = _({input:1,button:1,select:1,textarea:1,label:1}),
        C = X( _({a:1}), B ),
        D = X( {iframe:1}, C ),
        E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}),
        F = _({ins:1,del:1,script:1,style:1}),
        G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ),
        H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ),
        I = X( _({p:1}), H ),
        J = X( _({iframe:1}), H, B ),
        K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}),

        L = X( _({a:0}), J ),//a不能被切开，所以把他
        M = _({tr:1}),
        N = _({'#':1}),
        O = X( _({param:1}), K ),
        P = X( _({form:1}), A, D, E, I ),
        Q = _({li:1,ol:1,ul:1}),
        R = _({style:1,script:1}),
        S = _({base:1,link:1,meta:1,title:1}),
        T = X( S, R ),
        U = _({head:1,body:1}),
        V = _({html:1});

    var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}),

        empty =  _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});

    return  _({

        // $ 表示自定的属性

        // body外的元素列表.
        $nonBodyContent: X( V, U, S ),

        //块结构元素列表
        $block : block,

        //内联元素列表
        $inline : L,

        $inlineWithA : X(_({a:1}),L),

        $body : X( _({script:1,style:1}), block ),

        $cdata : _({script:1,style:1}),

        //自闭和元素
        $empty : empty,

        //不是自闭合，但不能让range选中里边
        $nonChild : _({iframe:1,textarea:1}),
        //列表元素列表
        $listItem : _({dd:1,dt:1,li:1}),

        //列表根元素列表
        $list: _({ul:1,ol:1,dl:1}),

        //不能认为是空的元素
        $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),

        //如果没有子节点就可以删除的元素列表，像span,a
        $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}),

        $removeEmptyBlock : _({'p':1,'div':1}),

        //在table元素里的元素列表
        $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
        //不转换的标签
        $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
        html: U,
        head: T,
        style: N,
        script: N,
        body: P,
        base: {},
        link: {},
        meta: {},
        title: N,
        col : {},
        tr : _({td:1,th:1}),
        img : {},
        embed: {},
        colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
        noscript : P,
        td : P,
        br : {},
        th : P,
        center : P,
        kbd : L,
        button : X( I, E ),
        basefont : {},
        h5 : L,
        h4 : L,
        samp : L,
        h6 : L,
        ol : Q,
        h1 : L,
        h3 : L,
        option : N,
        h2 : L,
        form : X( A, D, E, I ),
        select : _({optgroup:1,option:1}),
        font : L,
        ins : L,
        menu : Q,
        abbr : L,
        label : L,
        table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
        code : L,
        tfoot : M,
        cite : L,
        li : P,
        input : {},
        iframe : P,
        strong : L,
        textarea : N,
        noframes : P,
        big : L,
        small : L,
        //trace:
        span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
        hr : L,
        dt : L,
        sub : L,
        optgroup : _({option:1}),
        param : {},
        bdo : L,
        'var' : L,
        div : P,
        object : O,
        sup : L,
        dd : P,
        strike : L,
        area : {},
        dir : Q,
        map : X( _({area:1,form:1,p:1}), A, F, E ),
        applet : O,
        dl : _({dt:1,dd:1}),
        del : L,
        isindex : {},
        fieldset : X( _({legend:1}), K ),
        thead : M,
        ul : Q,
        acronym : L,
        b : L,
        a : X( _({a:1}), J ),
        blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
        caption : L,
        i : L,
        u : L,
        tbody : M,
        s : L,
        address : X( D, I ),
        tt : L,
        legend : L,
        q : L,
        pre : X( G, C ),
        p : X(_({'a':1}),L),
        em :L,
        dfn : L
    });
})();
<commit_msg>添加了mark标签在dtd中<commit_after>///import editor.js
///import core/dom/dom.js
///import core/utils.js
/**
 * dtd html语义化的体现类
 * @constructor
 * @namespace dtd
 */
var dtd = dom.dtd = (function() {
    function _( s ) {
        for (var k in s) {
            s[k.toUpperCase()] = s[k];
        }
        return s;
    }
    var X = utils.extend2;
    var A = _({isindex:1,fieldset:1}),
        B = _({input:1,button:1,select:1,textarea:1,label:1}),
        C = X( _({a:1}), B ),
        D = X( {iframe:1}, C ),
        E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}),
        F = _({ins:1,del:1,script:1,style:1}),
        G = X( _({mark:1,b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ),
        H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ),
        I = X( _({p:1}), H ),
        J = X( _({iframe:1}), H, B ),
        K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}),

        L = X( _({a:0}), J ),//a不能被切开，所以把他
        M = _({tr:1}),
        N = _({'#':1}),
        O = X( _({param:1}), K ),
        P = X( _({form:1}), A, D, E, I ),
        Q = _({li:1,ol:1,ul:1}),
        R = _({style:1,script:1}),
        S = _({base:1,link:1,meta:1,title:1}),
        T = X( S, R ),
        U = _({head:1,body:1}),
        V = _({html:1});

    var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}),

        empty =  _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});

    return  _({

        // $ 表示自定的属性

        // body外的元素列表.
        $nonBodyContent: X( V, U, S ),

        //块结构元素列表
        $block : block,

        //内联元素列表
        $inline : L,

        $inlineWithA : X(_({a:1}),L),

        $body : X( _({script:1,style:1}), block ),

        $cdata : _({script:1,style:1}),

        //自闭和元素
        $empty : empty,

        //不是自闭合，但不能让range选中里边
        $nonChild : _({iframe:1,textarea:1}),
        //列表元素列表
        $listItem : _({dd:1,dt:1,li:1}),

        //列表根元素列表
        $list: _({ul:1,ol:1,dl:1}),

        //不能认为是空的元素
        $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),

        //如果没有子节点就可以删除的元素列表，像span,a
        $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}),

        $removeEmptyBlock : _({'p':1,'div':1}),

        //在table元素里的元素列表
        $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
        //不转换的标签
        $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
        html: U,
        head: T,
        style: N,
        script: N,
        body: P,
        base: {},
        link: {},
        meta: {},
        title: N,
        col : {},
        tr : _({td:1,th:1}),
        img : {},
        embed: {},
        colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
        noscript : P,
        td : P,
        br : {},
        th : P,
        center : P,
        kbd : L,
        button : X( I, E ),
        basefont : {},
        h5 : L,
        h4 : L,
        samp : L,
        h6 : L,
        ol : Q,
        h1 : L,
        h3 : L,
        option : N,
        h2 : L,
        form : X( A, D, E, I ),
        select : _({optgroup:1,option:1}),
        font : L,
        ins : L,
        menu : Q,
        abbr : L,
        label : L,
        table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
        code : L,
        tfoot : M,
        cite : L,
        li : P,
        input : {},
        iframe : P,
        strong : L,
        textarea : N,
        noframes : P,
        big : L,
        small : L,
        //trace:
        span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
        hr : L,
        dt : L,
        sub : L,
        optgroup : _({option:1}),
        param : {},
        bdo : L,
        'var' : L,
        div : P,
        object : O,
        sup : L,
        dd : P,
        strike : L,
        area : {},
        dir : Q,
        map : X( _({area:1,form:1,p:1}), A, F, E ),
        applet : O,
        dl : _({dt:1,dd:1}),
        del : L,
        isindex : {},
        fieldset : X( _({legend:1}), K ),
        thead : M,
        ul : Q,
        acronym : L,
        b : L,
        a : X( _({a:1}), J ),
        blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
        caption : L,
        i : L,
        u : L,
        tbody : M,
        s : L,
        address : X( D, I ),
        tt : L,
        legend : L,
        q : L,
        pre : X( G, C ),
        p : X(_({'a':1}),L),
        em :L,
        dfn : L,
        mark:L
    });
})();
<|endoftext|>


<commit_before>/*******************************************************************
 File:          siebelhub.js
 Author(s):     alex@siebelhub.com
 Date:          Dec 2015
 Description:   Siebel Hub library for Siebel Open UI.
 See individual functions for details.
 For localization options, scroll down.
 Installation:  Copy this file to siebel/custom folder and
 register in the Manifest using Application/Common

 for(i=should,i=understand,i=read)
 {
    FOR EDUCATIONAL PURPOSES ONLY!!!
    DO NOT USE IN PRODUCTION!!!
 }

 History:

 13-DEC-2015    v0.1    ahansal     File created, first draft
 13-DEC-2015    v0.2    ahansal     added MakeAppletCollapsible method
 13-DEC-2015    v0.3    ahansal     added AlignViewToTop method
 14-DEC-2015    v0.4    ahansal     added ValidateContext to support applet, PM or PR as context
 14-DEC-2015    v0.5    ahansal     enhanced ErrorHandler with more cowbell
 *******************************************************************/

siebelhub = function(){
    return true;
};

/*
 Function SetControlValue: Sets the value of an applet control
 Inputs: context (applet object, PM or PR), control object, new value
 */
siebelhub.SetControlValue = function (context,control,value){
    try{
        var pm = siebelhub.ValidateContext(context);
        if (pm){
            //check for valid control object
            if (typeof(control.GetInputName) !== "function"){
                throw(shMsg["NOCTRL_1"]);
            }

            //now call PM events...
            pm.OnControlEvent(consts.get("PHYEVENT_CONTROL_FOCUS"), control);
            pm.OnControlEvent(consts.get("PHYEVENT_CONTROL_BLUR"), control, value.toString());
        }
    }
    catch(e){
        siebelhub.ErrorHandler(e);
    }
};

/*
 Function GetControlValue: Gets the current value of an applet control
 Inputs: context (Applet, PM or PR), control object
 Returns: current value
 */
siebelhub.GetControlValue = function (context,control){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        var value = pm.ExecuteMethod("GetFieldValue", control);
        return value;
    }
};

/*
 Function GetActivePM: Gets the PM of the active applet
 Inputs: nothing
 Returns: PM instance of active applet
 */
siebelhub.GetActivePM = function(){
    var activeApplet = siebelhub.GetActiveApplet();
    var activePM = activeApplet.GetPModel();
    return activePM;
};

/*
 Function GetActiveApplet: Gets the active applet
 Inputs: nothing
 Returns: active applet object instance
 */
siebelhub.GetActiveApplet = function(){
    var activeView = SiebelApp.S_App.GetActiveView();
    var activeApplet = activeView.GetActiveApplet();
    return activeApplet;
};

/*
 Function GetControlElemByLabel: Gets a control DOM element using the label text
 Inputs: applet object, PM or PR, label text
 Returns: control DOM element
 */
siebelhub.GetControlElemByLabel = function(context,label){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        var appletElemId = pm.Get("GetFullId");
        var appletElem = $("#" + appletElemId);
        var controlElem = $(appletElem).find("[aria-label='" + label + "']");
        return controlElem;
    }
    else
    {
        return null;
    }

};

/*
 Function GetControlObjByLabel: Gets a control object using the label text
 Inputs: applet object, PM or PR, label text
 Returns: control object instance
 */
siebelhub.GetControlObjByLabel = function(context,label){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        var controlElem = siebelhub.GetControlElemByLabel(pm,label);
        var labelName = controlElem.attr("aria-labelledby");
        var controlName = labelName.split("_")[0];
        var controlObj = pm.Get("GetControls")[controlName];
        return controlObj;
    }
    else
    {
        return null;
    }
};

/*
 Function MakeAppletCollapsible: overrides the defaultAppletDisplayMode property
 and enables Siebel OOB collapsibility
 Inputs: applet object, PM or PR
 Kudos: Jan Peterson
 */
siebelhub.MakeAppletCollapsible = function(context){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        if (!pm.Get("defaultAppletDisplayMode")) {
            pm.SetProperty("defaultAppletDisplayMode","expanded"); //or "collapsed"
            var pr = pm.GetRenderer();
            if (pr && typeof(pr.ShowCollapseExpand) === 'function'){
                pm.GetRenderer().ShowCollapseExpand();
            }
        }
    }
};

/*
 Function AlignViewToTop: scrolls to top of the view
 Inputs: true = try to activate top applet (emulates click)
 */
siebelhub.AlignViewToTop = function(activateTopApplet){
    $("#_sweview").scrollTop(0);
    if (activateTopApplet){
        $("#_sweview").find(".siebui-applet").first().click();
    }
};

/*
 Function ValidateContext: returns a valid PM instance for Applet, PW or PR
 Inputs: Applet object, PM, PW or PR instance
 Returns: PM instance for valid input, null for invalid input
 */
siebelhub.ValidateContext = function(object){
    try{
        var pm = null;
        //context = applet instance
        if(typeof(object.GetPModel) === "function"){
            pm = object.GetPModel();
        }
        //context = PM
        else if (typeof(object.OnControlEvent) === "function") {
            pm = object;
        }
        //context = PR
        else if (typeof(object.GetPM) === "function"){
            pm = object.GetPM();
        }
        //context is neither an applet, PM nor PR...
        else{
            throw(shMsg["NOPM_1"]);
        }
        return pm;
    }
    catch(e){
        siebelhub.ErrorHandler(e);
    }
};
/*
 Function ErrorHandler: For centralized error display
 Inputs: exception object
 */
siebelhub.ErrorHandler = function(e){
    //alert(e.toString());
    //$("
" + e.toString() + "
").dialog();
    $("
" + e.toString() + "
").dialog({
        buttons: [
            {
                text: shMsg["OK"],
                click: function() {
                    $(this).dialog("close");
                }
            }
        ],
        modal: true,
        dialogClass: "siebelhub_error_dlg",
        title: shMsg["ERROR_DLG_TITLE"]
    });
};

/*
 Just Hello World
 */
siebelhub.HelloWorld = function (msg) {
    if (typeof(msg) === "string" && msg != "") {
        alert(shMsg["HELLO"] + " " + msg);
    }
    else
    {
        alert(shMsg["HELLO_WORLD"]);
    }
};

/*
 Fun-ctions
 */
siebelhub.GoToTheHub = function(){
    window.open("http://www.siebelhub.com");
};

/*
 Localization happens here
 For a localized version, copy this file to a language directory and translate the array values below
 */
var shMsg = [];
shMsg["HELLO"]          = "Hello";
shMsg["HELLO_WORLD"]    = "Hello World";
shMsg["OK"]             = "OK";
shMsg["ERROR_DLG_TITLE"]= "whoopsy-daisy..."
shMsg["NOPM_1"]         = "This function requires valid context (Applet, PM or PR).";
shMsg["NOCTRL_1"]       = "This function requires a valid control reference.";
<commit_msg>Added new functions<commit_after>/*******************************************************************
 File:          siebelhub.js
 Author(s):     alex@siebelhub.com
 Date:          Dec 2015
 Description:   Siebel Hub library for Siebel Open UI.
 See individual functions for details.
 For localization options, scroll down.
 Installation:  Copy this file to siebel/custom folder and
 register in the Manifest using Application/Common

 for(i=should,i=understand,i=read)
 {
    FOR EDUCATIONAL PURPOSES ONLY!!!
    DO NOT USE IN PRODUCTION!!!
 }

 History:

 13-DEC-2015    v0.1    ahansal     File created, first draft
 13-DEC-2015    v0.2    ahansal     added MakeAppletCollapsible method
 13-DEC-2015    v0.3    ahansal     added AlignViewToTop method
 14-DEC-2015    v0.4    ahansal     added ValidateContext to support applet, PM or PR as context
 14-DEC-2015    v0.5    ahansal     enhanced ErrorHandler with more cowbell
 15-DEC-2015    v0.5    ahansal     published on GitHub
 17-DEC-2015    v0.6    ahansal     added GetRecordSet method
 18-DEC-2015    v0.7    ahansal     added GetAppletType method
 *******************************************************************/

siebelhub = function(){
    return true;
};

/*
 Function SetControlValue: Sets the value of an applet control
 Inputs: context (applet object, PM or PR), control object, new value
 */
siebelhub.SetControlValue = function (context,control,value){
    try{
        var pm = siebelhub.ValidateContext(context);
        if (pm){
            //check for valid control object
            if (typeof(control.GetInputName) !== "function"){
                throw(shMsg["NOCTRL_1"]);
            }

            //now call PM events...
            pm.OnControlEvent(consts.get("PHYEVENT_CONTROL_FOCUS"), control);
            pm.OnControlEvent(consts.get("PHYEVENT_CONTROL_BLUR"), control, value.toString());
        }
    }
    catch(e){
        siebelhub.ErrorHandler(e);
    }
};

/*
 Function GetControlValue: Gets the current value of an applet control
 Inputs: context (Applet, PM or PR), control object
 Returns: current value
 */
siebelhub.GetControlValue = function (context,control){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        var value = pm.ExecuteMethod("GetFieldValue", control);
        return value;
    }
};

/*
 Function GetActivePM: Gets the PM of the active applet
 Inputs: nothing
 Returns: PM instance of active applet
 */
siebelhub.GetActivePM = function(){
    var activeApplet = siebelhub.GetActiveApplet();
    var activePM = activeApplet.GetPModel();
    return activePM;
};

/*
 Function GetActiveApplet: Gets the active applet
 Inputs: nothing
 Returns: active applet object instance
 */
siebelhub.GetActiveApplet = function(){
    var activeView = SiebelApp.S_App.GetActiveView();
    var activeApplet = activeView.GetActiveApplet();
    return activeApplet;
};

/*
 Function GetControlElemByLabel: Gets a control DOM element using the label text
 Inputs: applet object, PM or PR, label text
 Returns: control DOM element
 */
siebelhub.GetControlElemByLabel = function(context,label){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        var appletElemId = pm.Get("GetFullId");
        var appletElem = $("#" + appletElemId);
        var controlElem = $(appletElem).find("[aria-label='" + label + "']");
        return controlElem;
    }
    else
    {
        return null;
    }

};

/*
 Function GetControlObjByLabel: Gets a control object using the label text
 Inputs: applet object, PM or PR, label text
 Returns: control object instance
 */
siebelhub.GetControlObjByLabel = function(context,label){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        var controlElem = siebelhub.GetControlElemByLabel(pm,label);
        var labelName = controlElem.attr("aria-labelledby");
        var controlName = labelName.split("_")[0];
        var controlObj = pm.Get("GetControls")[controlName];
        return controlObj;
    }
    else
    {
        return null;
    }
};

/*
 Function MakeAppletCollapsible: overrides the defaultAppletDisplayMode property
 and enables Siebel OOB collapsibility
 Inputs: applet object, PM or PR
 Kudos: Jan Peterson
 */
siebelhub.MakeAppletCollapsible = function(context){
    var pm = siebelhub.ValidateContext(context);
    if (pm){
        if (!pm.Get("defaultAppletDisplayMode")) {
            pm.SetProperty("defaultAppletDisplayMode","expanded"); //or "collapsed"
            var pr = pm.GetRenderer();
            if (pr && typeof(pr.ShowCollapseExpand) === 'function'){
                pm.GetRenderer().ShowCollapseExpand();
            }
        }
    }
};

/*
 Function AlignViewToTop: scrolls to top of the view
 Inputs: true = try to activate top applet (emulates click)
 */
siebelhub.AlignViewToTop = function(activateTopApplet){
    $("#_sweview").scrollTop(0);
    if (activateTopApplet){
        $("#_sweview").find(".siebui-applet").first().click();
    }
};

/*ideas, tbc*/
//optimize siebelhub.js for list applets
//get value by BC field name

/*
 Function GetAppletType: Returns the type (list, form, tree, chart) of applet
 Inputs: "context" (applet, PM or PR)
 Returns: type of applet as null or string
 */
siebelhub.GetAppletType = function(context){
    debugger;
    var type = null;
    var pm = null;
    var id = null;
    //if we got an applet instance, it could be a list applet...
    if(typeof(context.GetListOfColumns) === "function"){
        type = shMsg["TYPE_LIST"];
    }
    //if we got a PM, we can try get the list of columns
    else if (typeof(context.Get) === "function"){
        if(context.Get("GetListOfColumns")){
            type = shMsg["TYPE_LIST"];
        }
    }
    //if we got a PR, get the PM and try again
    else if (typeof(context.GetPM) === "function"){
        if(context.GetPM().Get("GetListOfColumns")){
            type = shMsg["TYPE_LIST"];
        }
    }

    pm = siebelhub.ValidateContext(context);
    //could be a tree or chart, let's see...

    if (pm){
        id = pm.Get("GetFullId");
        if ($("#" + id).find(".siebui-tree").length != 0){
            type =  shMsg["TYPE_TREE"];
        }
        else if (!type){
            id = pm.Get("GetFullId").split("_")[1];
            id = id.toLowerCase().charAt(0) + "_" + id.charAt(1);
            if ($("#" + id).find(".siebui-charts-container").length != 0){
                type = shMsg["TYPE_CHART"];
            }
            else{
                type = shMsg["TYPE_FORM"];
            }
        }

    }
    return type;
};

siebelhub.GetRecordSet = function(raw){
    var recordset;
    if(raw){
        recordset = siebelhub.GetActivePM().Get("GetRawRecordSet");
    }
    else{
        recordset = siebelhub.GetActivePM().Get("GetRecordSet");
    }
    return recordset;
};
/*
 Function ValidateContext: returns a valid PM instance for Applet, PW or PR
 Inputs: Applet object, PM, PW or PR instance
 Returns: PM instance for valid input, null for invalid input
 */
siebelhub.ValidateContext = function(object){
    try{
        var pm = null;
        //context = applet instance
        if(typeof(object.GetPModel) === "function"){
            pm = object.GetPModel();
        }
        //context = PM
        else if (typeof(object.OnControlEvent) === "function") {
            pm = object;
        }
        //context = PR
        else if (typeof(object.GetPM) === "function"){
            pm = object.GetPM();
        }
        //context is neither an applet, PM nor PR...
        else{
            throw(shMsg["NOPM_1"]);
        }
        return pm;
    }
    catch(e){
        siebelhub.ErrorHandler(e);
    }
};
/*
 Function ErrorHandler: For centralized error display
 Inputs: exception object
 */
siebelhub.ErrorHandler = function(e){
    //alert(e.toString());
    //$("
" + e.toString() + "
").dialog();
    $("
" + e.toString() + "
").dialog({
        buttons: [
            {
                text: shMsg["OK"],
                click: function() {
                    $(this).dialog("close");
                }
            }
        ],
        modal: true,
        dialogClass: "siebelhub_error_dlg",
        title: shMsg["ERROR_DLG_TITLE"]
    });
};

/*
 Just Hello World
 */
siebelhub.HelloWorld = function (msg) {
    if (typeof(msg) === "string" && msg != "") {
        alert(shMsg["HELLO"] + " " + msg);
    }
    else
    {
        alert(shMsg["HELLO_WORLD"]);
    }
};

/*
 Fun-ctions
 */
siebelhub.GoToTheHub = function(){
    window.open("http://www.siebelhub.com");
};

/*
 Localization happens here
 For a localized version, copy this file to a language directory and translate the array values below
 */
var shMsg = [];
shMsg["HELLO"]          = "Hello";
shMsg["HELLO_WORLD"]    = "Hello World";
shMsg["OK"]             = "OK";
shMsg["ERROR_DLG_TITLE"]= "whoopsy-daisy..."
shMsg["NOPM_1"]         = "This function requires valid context (Applet, PM or PR).";
shMsg["NOCTRL_1"]       = "This function requires a valid control reference.";
shMsg["TYPE_LIST"]      = "list";
shMsg["TYPE_FORM"]      = "form";
shMsg["TYPE_CHART"]     = "chart";
shMsg["TYPE_TREE"]      = "tree";
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';

import { connect } from 'react-redux';

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

import ReactDOM from 'react-dom';

import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {
    indigo400,
    cyan700,
    grey400,
    orangeA700,
    grey100,
    grey500,
    darkBlack,
    white,
    grey300
} from 'material-ui/styles/colors';
import { fade } from 'material-ui/utils/colorManipulator';
import Spacing from 'material-ui/styles/spacing';

import { syncReduxAndRouter } from 'redux-simple-router';

import HomeContainer from 'components/home/home-container';

import WelcomePage from 'components/welcome/welcome';
import LoginForm from 'components/welcome/login-form';
import SignupForm from 'components/welcome/signup-form';
import RecoverForm from 'components/welcome/recover-form';

import PageContainer from 'components/pages/page-container';
import Profile from 'components/profile/profile';
import MessagesContainer from 'components/messages/messages-container';
import ProfilePages from 'components/pages/profile-pages';
import EventPages from 'components/pages/event-pages';
import FriendPages from 'components/pages/friend-pages';

import { Provider } from 'react-redux';

import store from 'store';
import api from 'api';

import actionCreators from 'action-creators';

syncReduxAndRouter(browserHistory, store);

function redirectToHomePage(_nextState, replace) {
    if (store.getState().currentToken) {
        replace('/');
    }
}

function redirectToLoginPage(_nextState, replace) {
    if (!store.getState().currentToken) {
        replace('/welcome/login');
    }
}

function mapStateToProps(state) {
    return ({
        settings: state.settings
    });
}

const Application = React.createClass({
    propTypes: {
        settings: PropTypes.object.isRequired,
        addResource: PropTypes.func.isRequired
    },

    childContextTypes: {
        muiTheme: React.PropTypes.object
    },

    mixins: [PureRenderMixin],

    getChildContext() {
        return {
            muiTheme: getMuiTheme({
                spacing: Spacing,
                fontFamily: 'Roboto, sans-serif',
                palette: {
                    primary1Color: indigo400,
                    primary2Color: cyan700,
                    primary3Color: grey400,
                    accent1Color: orangeA700,
                    accent2Color: grey100,
                    accent3Color: grey500,
                    textColor: darkBlack,
                    alternateTextColor: white,
                    canvasColor: white,
                    borderColor: grey300,
                    disabledColor: fade(darkBlack, 0.3)
                }
            })
        };
    },

    componentDidMount() {
        api.settings.getCurrent()
            .then((settings) => {
                this.props.addResource(settings);
            });
    },

    render() {
        return (
            <Router history={browserHistory}>
                <Route path="/welcome" component={WelcomePage} onEnter={redirectToHomePage}>
                    <Route path="login" component={LoginForm} />
                    <Route path="recover" component={RecoverForm} />
                    <Route path="signup" component={SignupForm} />
                </Route>

                <Route path="/" component={HomeContainer} onEnter={redirectToLoginPage}>
                    <Route component={PageContainer}>
                        <IndexRoute component={MessagesContainer} />
                    </Route>

                    <Route path="members" component={ProfilePages} />
                    <Route path="events" component={EventPages} />

                    <Route path=":pageId/profile" component={PageContainer}>
                        <IndexRoute component={Profile} />
                    </Route>

                    <Route path=":pageId" component={PageContainer}>
                        <IndexRoute component={MessagesContainer} />
                        <Route path="friends" component={FriendPages} />
                    </Route>
                </Route>
            </Router>
        );
    }
});

const ConnectedApplication = connect(mapStateToProps, actionCreators)(Application);

ReactDOM.render(
    <Provider store={store}>
        <ConnectedApplication />
    </Provider>
, document.getElementById('application'));
<commit_msg>don't display anything unless settings are loaded<commit_after>import React, { PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';

import { connect } from 'react-redux';

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

import ReactDOM from 'react-dom';

import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {
    indigo400,
    cyan700,
    grey400,
    orangeA700,
    grey100,
    grey500,
    darkBlack,
    white,
    grey300
} from 'material-ui/styles/colors';
import { fade } from 'material-ui/utils/colorManipulator';
import Spacing from 'material-ui/styles/spacing';

import { syncReduxAndRouter } from 'redux-simple-router';

import HomeContainer from 'components/home/home-container';

import WelcomePage from 'components/welcome/welcome';
import LoginForm from 'components/welcome/login-form';
import SignupForm from 'components/welcome/signup-form';
import RecoverForm from 'components/welcome/recover-form';

import PageContainer from 'components/pages/page-container';
import Profile from 'components/profile/profile';
import MessagesContainer from 'components/messages/messages-container';
import ProfilePages from 'components/pages/profile-pages';
import EventPages from 'components/pages/event-pages';
import FriendPages from 'components/pages/friend-pages';

import { Provider } from 'react-redux';

import store from 'store';
import api from 'api';

import actionCreators from 'action-creators';

syncReduxAndRouter(browserHistory, store);

function redirectToHomePage(_nextState, replace) {
    if (store.getState().currentToken) {
        replace('/');
    }
}

function redirectToLoginPage(_nextState, replace) {
    if (!store.getState().currentToken) {
        replace('/welcome/login');
    }
}

function mapStateToProps(state) {
    return ({
        settings: state.settings
    });
}

const Application = React.createClass({
    propTypes: {
        settings: PropTypes.object.isRequired,
        addResource: PropTypes.func.isRequired
    },

    childContextTypes: {
        muiTheme: React.PropTypes.object
    },

    mixins: [PureRenderMixin],

    getChildContext() {
        return {
            muiTheme: getMuiTheme({
                spacing: Spacing,
                fontFamily: 'Roboto, sans-serif',
                palette: {
                    primary1Color: indigo400,
                    primary2Color: cyan700,
                    primary3Color: grey400,
                    accent1Color: orangeA700,
                    accent2Color: grey100,
                    accent3Color: grey500,
                    textColor: darkBlack,
                    alternateTextColor: white,
                    canvasColor: white,
                    borderColor: grey300,
                    disabledColor: fade(darkBlack, 0.3)
                }
            })
        };
    },

    componentWillMount() {
        api.settings.getCurrent()
            .then((settings) => {
                this.props.addResource(settings);
            });
    },

    render() {
        if (!this.props.settings.data) {
            return (<div />)
        }

        return (
            <Router history={browserHistory}>
                <Route path="/welcome" component={WelcomePage} onEnter={redirectToHomePage}>
                    <Route path="login" component={LoginForm} />
                    <Route path="recover" component={RecoverForm} />
                    <Route path="signup" component={SignupForm} />
                </Route>

                <Route path="/" component={HomeContainer} onEnter={redirectToLoginPage}>
                    <Route component={PageContainer}>
                        <IndexRoute component={MessagesContainer} />
                    </Route>

                    <Route path="members" component={ProfilePages} />
                    <Route path="events" component={EventPages} />

                    <Route path=":pageId/profile" component={PageContainer}>
                        <IndexRoute component={Profile} />
                    </Route>

                    <Route path=":pageId" component={PageContainer}>
                        <IndexRoute component={MessagesContainer} />
                        <Route path="friends" component={FriendPages} />
                    </Route>
                </Route>
            </Router>
        );
    }
});

const ConnectedApplication = connect(mapStateToProps, actionCreators)(Application);

ReactDOM.render(
    <Provider store={store}>
        <ConnectedApplication />
    </Provider>
, document.getElementById('application'));
<|endoftext|>


<commit_before>import React from 'react';
import Doc from './Doc';
import View from '../../package/View';

export default class DataTables extends React.Component {

  render(){

    let data = [
      {
        title: 'Simple table',
        state: { selected: [232], selectAll: false, data: [ { id: 232, dessert: 'Bakewell tart', type: 'pastry' }, { id: 111, dessert: 'Chocolate Sundae', type: 'ice cream' }, { id: 9, dessert: 'Soggy biscuit', type: 'pastry' } ] },
        src: Doc.jsx`
          <DataTable
            columns={[
              {key: 'dessert', label: 'Dessert Name', tip: 'yummy name', type:'text'},
              {key: 'type', label: 'Type', tip: 'wtf is a dessert type??'},
            ]}
            onToggleRow={(rowID) => {
              let selected = this.state.selected.slice(0);
              if ( selected.indexOf(rowID) < 0 ) selected.push(rowID); //add it please
              else selected.splice( selected.indexOf(rowID), 1 ); //remove it, yo!
              this.setState({selected: selected})
            }}
            onSelectAll={(rowIDs) => {
              if ( this.state.selectAll ) { //Off
                this.setState({ selectAll: false, selected: (rowIDs.length == this.state.previouslySelected.length ? [] : this.state.previouslySelected ) });
              }
              else { //On
                this.setState({ selectAll: true, selected: rowIDs, previouslySelected: this.state.selected });
              }
            }}
            onSort={(colKey) => {
              let order = 'asc';
              if ( colKey == this.state.sort ) order = ( this.state.order == 'asc' ? 'desc' : 'asc' );
              this.setState( { sort: colKey, order: order } );

              let data = this.state.data.slice(0);
              data.sort(
                function( sort, order, a, b ) {
                  var sortOrder = 1;
                  if(order == "desc") {
                    sortOrder = -1;
                  }
                  var result = (a[sort] < b[sort]) ? -1 : (a[sort] > b[sort]) ? 1 : 0;
                  return result * sortOrder;

                }.bind(this,colKey,order)
              );

              this.setState( { data: data } );

            }}
            sort={this.state.sort}
            order={this.state.order}
            selectAll={this.state.selectAll}
            data={ this.state.data }
            selected={this.state.selected}
         />
        `,
        info:`

        `
      },
      {
        title: 'Simple table with no columns config and no row ids',
        src: Doc.jsx`
          <DataTable
            data={ [ { dessert: 'Bakewell tart', type: 'pastry' }, { dessert: 'Chocolate Sundae', type: 'ice cream' } ] }
         />
        `,
        info:`
          It still displays but it won't be interactive.
        `
      },
      {
        title: 'No heading row and no checkboxes',
        src: Doc.jsx`
          <DataTable
            columns={[
              {key: 'dessert', label: 'Dessert Name', tip: 'yummy name', type:'text'},
              {key: 'type', label: 'Type', tip: 'wtf is a dessert type??'},
            ]}
            showHeadings={false}
            showCheckboxes={false}
            data={ [ { id: 232, dessert: 'Bakewell tart', type: 'pastry' }, { id: 111, dessert: 'Chocolate Sundae', type: 'ice cream' } ] }
            selected={ [ 232 ] }
         />
        `,
        info:`

        `
      },

    ];
    return (
      <View scroll>
        <View>
          {data.map((props,i) => <Doc key={i} {...props} />)}
        </View>
      </View>
    );
  }

}

<commit_msg>Shortened the sorting code a bit<commit_after>import React from 'react';
import Doc from './Doc';
import View from '../../package/View';

export default class DataTables extends React.Component {

  render(){

    let data = [
      {
        title: 'Simple table',
        state: { selected: [232], selectAll: false, data: [ { id: 232, dessert: 'Bakewell tart', type: 'pastry' }, { id: 111, dessert: 'Chocolate Sundae', type: 'ice cream' }, { id: 9, dessert: 'Soggy biscuit', type: 'pastry' } ] },
        src: Doc.jsx`
          <DataTable
            columns={[
              {key: 'dessert', label: 'Dessert Name', tip: 'yummy name', type:'text'},
              {key: 'type', label: 'Type', tip: 'wtf is a dessert type??'},
            ]}
            onToggleRow={(rowID) => {
              let selected = this.state.selected.slice(0);
              if ( selected.indexOf(rowID) < 0 ) selected.push(rowID); //add it please
              else selected.splice( selected.indexOf(rowID), 1 ); //remove it, yo!
              this.setState({selected: selected})
            }}
            onSelectAll={(rowIDs) => {
              if ( this.state.selectAll ) { //Off
                this.setState({ selectAll: false, selected: (rowIDs.length == this.state.previouslySelected.length ? [] : this.state.previouslySelected ) });
              }
              else { //On
                this.setState({ selectAll: true, selected: rowIDs, previouslySelected: this.state.selected });
              }
            }}
            onSort={(colKey) => {
              let order = 'asc';
              if ( colKey == this.state.sort ) order = ( this.state.order == 'asc' ? 'desc' : 'asc' );
              this.setState( { sort: colKey, order: order, data: this.state.data.slice(0).sort( function( sort, order, a, b ) { return ((a[sort] < b[sort]) ? -1 : (a[sort] > b[sort]) ? 1 : 0) * (order == "desc"?-1:1); }.bind(this,colKey,order) ) } );

            }}
            sort={this.state.sort}
            order={this.state.order}
            selectAll={this.state.selectAll}
            data={ this.state.data }
            selected={this.state.selected}
         />
        `,
        info:`

        `
      },
      {
        title: 'Simple table with no columns config and no row ids',
        src: Doc.jsx`
          <DataTable
            data={ [ { dessert: 'Bakewell tart', type: 'pastry' }, { dessert: 'Chocolate Sundae', type: 'ice cream' } ] }
         />
        `,
        info:`
          It still displays but it won't be interactive.
        `
      },
      {
        title: 'No heading row and no checkboxes',
        src: Doc.jsx`
          <DataTable
            columns={[
              {key: 'dessert', label: 'Dessert Name', tip: 'yummy name', type:'text'},
              {key: 'type', label: 'Type', tip: 'wtf is a dessert type??'},
            ]}
            showHeadings={false}
            showCheckboxes={false}
            data={ [ { id: 232, dessert: 'Bakewell tart', type: 'pastry' }, { id: 111, dessert: 'Chocolate Sundae', type: 'ice cream' } ] }
            selected={ [ 232 ] }
         />
        `,
        info:`

        `
      },

    ];
    return (
      <View scroll>
        <View>
          {data.map((props,i) => <Doc key={i} {...props} />)}
        </View>
      </View>
    );
  }

}

<|endoftext|>


<commit_before>const webpack = require('webpack');
const OpenTok = require('opentok');
const opentok = new OpenTok(process.env.OT_API_KEY, process.env.OT_API_SECRET);

module.exports = {
  entry: {
    index: './src/index.js',
  },
  output: {
    path: './js/',
    filename: '[name].bundle.js',
  },
  devtool: 'source-map',
  plugins: [
    new webpack.DefinePlugin({
      config: {
        OT_API_KEY: JSON.stringify(process.env.OT_API_KEY),
        OT_SESSION_ID: JSON.stringify(process.env.OT_SESSION_ID),
        OT_TOKEN: JSON.stringify(opentok.generateToken(process.env.OT_SESSION_ID, {
          expireTime: (new Date().getTime() / 1000) + (2 * 24 * 60 * 60), // in 2 days
        })),
      },
    }),
  ],
};
<commit_msg>Let the token last a little longer to give some time to fix failing tests<commit_after>const webpack = require('webpack');
const OpenTok = require('opentok');
const opentok = new OpenTok(process.env.OT_API_KEY, process.env.OT_API_SECRET);

module.exports = {
  entry: {
    index: './src/index.js',
  },
  output: {
    path: './js/',
    filename: '[name].bundle.js',
  },
  devtool: 'source-map',
  plugins: [
    new webpack.DefinePlugin({
      config: {
        OT_API_KEY: JSON.stringify(process.env.OT_API_KEY),
        OT_SESSION_ID: JSON.stringify(process.env.OT_SESSION_ID),
        OT_TOKEN: JSON.stringify(opentok.generateToken(process.env.OT_SESSION_ID, {
          expireTime: (new Date().getTime() / 1000) + (10 * 24 * 60 * 60), // in 10 days
        })),
      },
    }),
  ],
};
<|endoftext|>


<commit_before>var previousUrl = "";

function setUsername(username) {
    window.localStorage.setItem('username', username);
}

function getUsername() {
    return window.localStorage.getItem('username');
}

function setToken(token) {
    window.localStorage.setItem('token', token);
}

function getToken() {
    return window.localStorage.getItem('token');
}

$(document).ajaxSend(
           function (event, jqxhr, settings) {
               jqxhr.setRequestHeader("Authorization", "Bearer " + getToken() );
           });

$(document).ajaxError(
    function (event, jqxhr, settings, message) {
        if (jqxhr.status === 401) {
            window.location = "/Users/login.html"; // with redirect
        }
    });

function authenticate() {

    if (getUsername() && getToken()) {
        window.location = "/Commits/commits.html";
    }
    else {
        window.location = "/Users/login.html"; // with redirect
    }
}

function loginReady() {
    previousUrl = document.referrer;
    $('#connectButton').on('click', doLogin);
}

function doLogin(event) {

    var username, password;
    event.stopPropagation();

    username = $('#login-username').val();
    password = $('#login-password').val();

    var alertMsg = "";

    if (!username ) {
        alertMsg = "please provide username";
    }

    if (!password) {
        alertMsg = "please provide a password";
    }

    if (alertMsg) {
        $(".alert").removeClass("hidden");
        $(".alert-text").html(alertMsg);
    }
    else {
        var data = 'username=' + username + '&password=' + password + '&grant_type=password';

        $.post('/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
            .done(
                function (data) {
                    setUsername(username);
                    setToken(data.access_token);
                    if (previousUrl && previousUrl.indexOf('login.html') === -1) {
                        window.location = previousUrl;
                    } else {
                        window.location = "/Commits/commits.html";
                    }
                })
            .fail(
                function (xhr, textStatus, error) {
                    $(".alert").removeClass("hidden");
                    $(".alert-text").html(JSON.parse(xhr.responseText)["error_description"]);
                });
    }
}

function doLogout() {
    setUsername(null);
    setToken(null);
}

function registerReady() {
    $('#connectButton').on('click', doRegister);
}

function doRegister() {

    var username = $('#newuser-username').val();
    var password = $('#newuser-password').val();
    var confirm = $('#newuser-confirm').val();
    var email = $('#newuser-email').val();
    var alertMsg = "";

    if (!username) {
        alertMsg = "Username required";
    }

    if (!password) {
        alertMsg = "Password required";
    }

    if (password.length < 8) {
        alertMsg = "Min 8 characters please";
    }

    if (!confirm) {
        alertMsg = "Password confirmation required";
    }

    if (password !== confirm) {
        alertMsg = "Entered password does not match confirmed";
    }

    if (!email) {
        alertMsg = "Email is required";
    }

    if (alertMsg) {
        $(".alert").removeClass("hidden");
        $(".alert-text").html(alertMsg);
    }
    else {

        var form = $('#register');
        $.post('/api/users/register', form.serialize())
            .done(
                function (data) {
                    setUsername(username);
                    var data = 'username=' + username + '&password=' + password + '&grant_type=password';
                    $.post('/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
                        .done(
                            function (data) {
                                setUsername(username);
                                setToken(data.access_token);
                                window.location = "/Commits/commits.html";
                            })
                        .fail(
                            function (xhr, textStatus, error) {
                                $(".alert").removeClass("hidden");
                                $(".alert-text").html(JSON.parse(xhr.responseText)["error_description"]);
                            });
                })
            .fail(
                function (xhr, textStatus, error) {
                    $(".alert").removeClass("hidden");
                    $(".alert-text").html(xhr.statusText);
                });
    }
}

$(window).keydown(function (e) {
    switch (e.keyCode) {
        case 13:
            $(".btn-submit").click();
            return;
    }
});<commit_msg>fixes #18 - Hidden error text bug<commit_after>var previousUrl = "";

function setUsername(username) {
    window.localStorage.setItem('username', username);
}

function getUsername() {
    return window.localStorage.getItem('username');
}

function setToken(token) {
    window.localStorage.setItem('token', token);
}

function getToken() {
    return window.localStorage.getItem('token');
}

$(document).ajaxSend(
           function (event, jqxhr, settings) {
               jqxhr.setRequestHeader("Authorization", "Bearer " + getToken() );
           });

$(document).ajaxError(
    function (event, jqxhr, settings, message) {
        if (jqxhr.status === 401) {
            window.location = "/Users/login.html"; // with redirect
        }
    });

function authenticate() {

    if (getUsername() && getToken()) {
        window.location = "/Commits/commits.html";
    }
    else {
        window.location = "/Users/login.html"; // with redirect
    }
}

function loginReady() {
    previousUrl = document.referrer;
    $('#connectButton').on('click', doLogin);
}

function doLogin(event) {

    var username, password;
    event.stopPropagation();

    username = $('#login-username').val();
    password = $('#login-password').val();

    var alertMsg = "";

    if (!username ) {
        alertMsg = "please provide username";
    }

    if (!password) {
        alertMsg = "please provide a password";
    }

    if (alertMsg) {
        $(".alert").removeClass("hidden");
        $(".alert-text").html(alertMsg);
    }
    else {
        var data = 'username=' + username + '&password=' + password + '&grant_type=password';

        $.post('/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
            .done(
                function (data) {
                    setUsername(username);
                    setToken(data.access_token);
                    if (previousUrl && previousUrl.indexOf('login.html') === -1) {
                        window.location = previousUrl;
                    } else {
                        window.location = "/Commits/commits.html";
                    }
                })
            .fail(
                function (xhr, textStatus, error) {
                    $(".alert").removeClass("hidden");
                    $(".alert-text").html(JSON.parse(xhr.responseText)["error_description"]);
                });
    }
}

function doLogout() {
    setUsername(null);
    setToken(null);
}

function registerReady() {
    $('#connectButton').on('click', doRegister);
}

function doRegister() {
    event.stopPropagation();

    var username = $('#newuser-username').val();
    var password = $('#newuser-password').val();
    var confirm = $('#newuser-confirm').val();
    var email = $('#newuser-email').val();
    var alertMsg = "";

    if (!username) {
        alertMsg = "Username required";
    }

    if (!password) {
        alertMsg = "Password required";
    }

    if (password.length < 8) {
        alertMsg = "Min 8 characters please";
    }

    if (!confirm) {
        alertMsg = "Password confirmation required";
    }

    if (password !== confirm) {
        alertMsg = "Entered password does not match confirmed";
    }

    if (!email) {
        alertMsg = "Email is required";
    }

    if (alertMsg) {
        $(".alert").removeClass("hidden");
        $(".alert-text").html(alertMsg);
    }
    else {

        var form = $('#register');
        $.post('/api/users/register', form.serialize())
            .done(
                function (data) {
                    setUsername(username);
                    var data = 'username=' + username + '&password=' + password + '&grant_type=password';
                    $.post('/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
                        .done(
                            function (data) {
                                setUsername(username);
                                setToken(data.access_token);
                                window.location = "/Commits/commits.html";
                            })
                        .fail(
                        function (xhr, textStatus, error) {
                                $(".alert").removeClass("hidden");
                                $(".alert-text").html(JSON.parse(xhr.responseText)["error_description"]);
                            });
                })
            .fail(
                function (xhr, textStatus, error) {
                    $(".alert").removeClass("hidden");
                    $(".alert-text").html(JSON.parse(xhr.responseText)["error_description"]);
                });
    }
}

$(window).keydown(function (e) {
    switch (e.keyCode) {
        case 13:
            $(".btn-submit").click();
            return;
    }
});<|endoftext|>


<commit_before>const chartId = `${prefix}-chart`;
const chartLoginRequired = `${prefix}-chart-login-required`;
const chartClass = `${prefix}-chart-btn`;
const chartClassDisabled = `${prefix}-chart-btn-disabled`;
let allowedCampaigns = [];

const charts = [
    { column: 6, label: "Impressions / hour", config: {metric: 'impressions', rate: 'hour', chunk: 'hour', round: true} },
    { column: 7, label: "Clicks / day", config: {metric: 'clicks', rate: 'day', chunk: 'day', round: true} },
    { column: 9, label: "Spend / day", config: {metric: 'spend', rate: 'day', chunk: 'day', round: false} },
    { column: 10, label: "Sales / day", config: {metric: 'salesCount', rate: 'day', chunk: 'day', round: false} },
    { column: 11, label: "ACOS", config: {metric: 'acos', chunk: 'day', round: false} },
];

window.setInterval(() => {
    let tableRows = $('#campaignTable tbody tr');
    addChartButtons(tableRows);
}, 100);

chrome.runtime.sendMessage({
    action: 'getAllowedCampaigns',
    entityId: getEntityId(),
},
(response) => {
    allowedCampaigns = response.data || [];
});

const templateUrl = chrome.runtime.getURL('dashboard/templates.html');
$.ajax(templateUrl, {
    method: 'GET',
    success: (data) => {
        let dashboard = $('#campaignDashboard');
        dashboard.append(data);
    },
});

function addChartButtons(rows) {
    for (let row of rows) {
        for (let chart of charts) {
            let cells = $(row).children();
            let target = cells[chart.column];
            if (!target || $(target).find(`.${chartClass}`).length > 0)
                continue;

            let select = $(cells[0]).find('select')[0];
            let name = cells[1].innerText;
            if (!select)
                continue;

            let selectName = select.name;
            let campaignId = selectName.split('_').pop();
            campaignId = campaignId.substring(0, 22); // first 22 chars are the campaignId; timestamp is appended for some reason

            let btnClasses = chartClass;
            let allowed = allowedCampaigns.includes(campaignId);
            if (!allowed) {
                btnClasses += ` ${chartClassDisabled}`;
            }
            let btn = $(`<a href="#" class="${btnClasses}"><img src="${chartPng}" /></a>`);
            btn.click(function() {
                let newId = chartId+campaignId+chart.config.metric;
                let popup = btn.parent().find('#'+newId);
                if (!popup.length) {
                    if (allowed) {
                        popup = $('#'+chartId).hide().clone();
                        popup.addClass(chartId);
                    }
                    else {
                        popup = $('#'+chartLoginRequired).hide().clone();
                        popup.addClass(chartLoginRequired);
                    }
                    popup.attr('id', newId);

                    // hard-coded element width below b/c popup.width() doesn't
                    // work as required
                    let pos = btn.position();
                    if (pos.left + 420 > $(document).width()) {
                        popup.css({top: pos.top + btn.height() + 6, left: pos.left + btn.width() - 414});
                    }
                    else {
                        popup.css({top: pos.top + btn.height() + 6, left: pos.left});
                    }
                    btn.after(popup);
                }
                popup.slideDown(200, function() {
                    // Clicking anywhere outside the popup dismisses the chart
                    $(document).on('click', function() {
                        if (!$.contains(popup[0], this)) {
                            popup.hide();
                            $(document).off('click');
                        }
                    });
                });

                if (allowed) {
                    getDataHistory(getEntityId(), campaignId, (data) => {
                        renderChart(data, name, Object.assign({id: newId}, chart));
                    });
                }
            });
            $(target).append(btn);
        }
    }
}

function getDataHistory(entityId, campaignId, cb) {
    chrome.runtime.sendMessage({
        action: 'getDataHistory',
        entityId: entityId,
        campaignId: campaignId,
    },
    (response) => cb(response.data));
}

function renderChart(data, name, opt) {
    opt.config.startTimestamp = Date.now() - (8 * span.day);
    data = parallelizeHistoryData(data, opt.config);

    const series = {
      x: data.timestamps,
      y: data[opt.config.metric],
      mode: 'lines+markers',
      name: opt.config.metric,
      connectgaps: true
    };

    let height = 300;
    if (data.timestamps.length < 3) {
        height = 270; // leaving room for the lodata link
    }

    const layout = {
      title: `${opt.label}<br />${name}`,
      width: 400,
      height,
      margin: { l: 40, r: 20, b: 25, t: 60, pad: 4 },
    };

    Plotly.newPlot(opt.id, [series], layout, {displayModeBar: false});

    let container = $('#'+opt.id);
    if (data.timestamps.length < 3) {
        let a = container.find(`a.${prefix}-lodata`)
        a[0].href = chrome.runtime.getURL('common/low-data.html');
        a.show();
    }
}
<commit_msg>don't start inserting charts until after you have the list of allowed campaigns<commit_after>const chartId = `${prefix}-chart`;
const chartLoginRequired = `${prefix}-chart-login-required`;
const chartClass = `${prefix}-chart-btn`;
const chartClassDisabled = `${prefix}-chart-btn-disabled`;

const charts = [
    { column: 6, label: "Impressions / hour", config: {metric: 'impressions', rate: 'hour', chunk: 'hour', round: true} },
    { column: 7, label: "Clicks / day", config: {metric: 'clicks', rate: 'day', chunk: 'day', round: true} },
    { column: 9, label: "Spend / day", config: {metric: 'spend', rate: 'day', chunk: 'day', round: false} },
    { column: 10, label: "Sales / day", config: {metric: 'salesCount', rate: 'day', chunk: 'day', round: false} },
    { column: 11, label: "ACOS", config: {metric: 'acos', chunk: 'day', round: false} },
];

chrome.runtime.sendMessage({
    action: 'getAllowedCampaigns',
    entityId: getEntityId(),
},
(response) => {
    const allowedCampaigns = response.data || [];
    window.setInterval(() => {
        let tableRows = $('#campaignTable tbody tr');
        addChartButtons(tableRows, allowedCampaigns);
    }, 100);
});

const templateUrl = chrome.runtime.getURL('dashboard/templates.html');
$.ajax(templateUrl, {
    method: 'GET',
    success: (data) => {
        let dashboard = $('#campaignDashboard');
        dashboard.append(data);
    },
});

function addChartButtons(rows, allowedCampaigns) {
    for (let row of rows) {
        for (let chart of charts) {
            let cells = $(row).children();
            let target = cells[chart.column];
            if (!target || $(target).find(`.${chartClass}`).length > 0)
                continue;

            let select = $(cells[0]).find('select')[0];
            let name = cells[1].innerText;
            if (!select)
                continue;

            let selectName = select.name;
            let campaignId = selectName.split('_').pop();
            campaignId = campaignId.substring(0, 22); // first 22 chars are the campaignId; timestamp is appended for some reason

            let btnClasses = chartClass;
            let allowed = allowedCampaigns.includes(campaignId);
            if (!allowed) {
                btnClasses += ` ${chartClassDisabled}`;
            }
            let btn = $(`<a href="#" class="${btnClasses}"><img src="${chartPng}" /></a>`);
            btn.click(function() {
                let newId = chartId+campaignId+chart.config.metric;
                let popup = btn.parent().find('#'+newId);
                if (!popup.length) {
                    if (allowed) {
                        popup = $('#'+chartId).hide().clone();
                        popup.addClass(chartId);
                    }
                    else {
                        popup = $('#'+chartLoginRequired).hide().clone();
                        popup.addClass(chartLoginRequired);
                    }
                    popup.attr('id', newId);

                    // hard-coded element width below b/c popup.width() doesn't
                    // work as required
                    let pos = btn.position();
                    if (pos.left + 420 > $(document).width()) {
                        popup.css({top: pos.top + btn.height() + 6, left: pos.left + btn.width() - 414});
                    }
                    else {
                        popup.css({top: pos.top + btn.height() + 6, left: pos.left});
                    }
                    btn.after(popup);
                }
                popup.slideDown(200, function() {
                    // Clicking anywhere outside the popup dismisses the chart
                    $(document).on('click', function() {
                        if (!$.contains(popup[0], this)) {
                            popup.hide();
                            $(document).off('click');
                        }
                    });
                });

                if (allowed) {
                    getDataHistory(getEntityId(), campaignId, (data) => {
                        renderChart(data, name, Object.assign({id: newId}, chart));
                    });
                }
            });
            $(target).append(btn);
        }
    }
}

function getDataHistory(entityId, campaignId, cb) {
    chrome.runtime.sendMessage({
        action: 'getDataHistory',
        entityId: entityId,
        campaignId: campaignId,
    },
    (response) => cb(response.data));
}

function renderChart(data, name, opt) {
    opt.config.startTimestamp = Date.now() - (8 * span.day);
    data = parallelizeHistoryData(data, opt.config);

    const series = {
      x: data.timestamps,
      y: data[opt.config.metric],
      mode: 'lines+markers',
      name: opt.config.metric,
      connectgaps: true
    };

    let height = 300;
    if (data.timestamps.length < 3) {
        height = 270; // leaving room for the lodata link
    }

    const layout = {
      title: `${opt.label}<br />${name}`,
      width: 400,
      height,
      margin: { l: 40, r: 20, b: 25, t: 60, pad: 4 },
    };

    Plotly.newPlot(opt.id, [series], layout, {displayModeBar: false});

    let container = $('#'+opt.id);
    if (data.timestamps.length < 3) {
        let a = container.find(`a.${prefix}-lodata`)
        a[0].href = chrome.runtime.getURL('common/low-data.html');
        a.show();
    }
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    // Configurable paths
  var config = {
    app: 'app',
    dist: 'dist'
  };

  // Project configuration.
  grunt.initConfig({

    // Project settings
    config: config,

    pkg: grunt.file.readJSON('package.json'),

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            '*.*'
          ],
          src: [
            '*.{ico,png,txt}',
            '{,*/}*.html',
            'fonts/{,*/}*.*'
          ]
        }]
      }
    },

    concat: {
      options: {
        separator: ';'
      },
      dist : {},
      generated: {
        files: [
          {
            dest: 'dist/scripts/output.min.js',
            src: [
              '<%= config.app %>/scripts/angular.js',
              '<%= config.app %>/scripts/*.js'
            ]
          }
        ]
      }
    },

    uglify: {
      options: {
        mangle: false
      },
      dist : {},
      generated : {
        files: {
          dest: '<%= config.dist %>/scripts/output.min.js',
          src: ['<%= config.dist %>/scripts/output.min.js']
        }
      }
    },

    cssmin: {
      generated : {
        options: {
          banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
        },
        build: {
          files: {
            '<%= config.dist %>/styles/styles.min.css': '<%= config.app %>/styles/*.css'
          }
        }
      }
    },

    useminPrepare: {
      html: '<%= config.app %>/index.html',
      options: {
        dest: '<%= config.dist %>'
      }
    },

    usemin: {
      html: '<%= config.dist %>/index.html',
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        src: [
          ['<%= config.dist %>*','.tmp']
        ]
      },
      temp: {
        src: [
          ['.tmp']
        ]
      }
    },

    // configure watch to auto update ----------------
    watch: {

      // for stylesheets, watch css and less files
      // only run less and cssmin stylesheets: {
      files: ['styles/*.css'],
      tasks: ['build'],
      options: {
        cwd:'<%= config.app %>',
        livereload: true,
      },
    },

  });

  //load task
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-usemin');

  grunt.registerTask('cleanAll', ['clean']);

  grunt.registerTask('build', [
    'clean',
    'copy:dist',
    'useminPrepare',
    'concat:generated',
    'cssmin:generated',
    'uglify:generated',
    'usemin',
    'clean:temp'
]);

  grunt.registerTask('default', ['build']);

};<commit_msg>-Suppression paramètre MANGLE<commit_after>module.exports = function(grunt) {

    // Configurable paths
  var config = {
    app: 'app',
    dist: 'dist'
  };

  // Project configuration.
  grunt.initConfig({

    // Project settings
    config: config,

    pkg: grunt.file.readJSON('package.json'),

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            '*.*'
          ],
          src: [
            '*.{ico,png,txt}',
            '{,*/}*.html',
            'fonts/{,*/}*.*'
          ]
        }]
      }
    },

    concat: {
      options: {
        separator: ';'
      },
      dist : {},
      generated: {
        files: [
          {
            dest: 'dist/scripts/output.min.js',
            src: [
              '<%= config.app %>/scripts/angular.js',
              '<%= config.app %>/scripts/*.js'
            ]
          }
        ]
      }
    },

    uglify: {
      dist : {},
      generated : {
        files: {
          dest: '<%= config.dist %>/scripts/output.min.js',
          src: ['<%= config.dist %>/scripts/output.min.js']
        }
      }
    },

    cssmin: {
      generated : {
        options: {
          banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
        },
        build: {
          files: {
            '<%= config.dist %>/styles/styles.min.css': '<%= config.app %>/styles/*.css'
          }
        }
      }
    },

    useminPrepare: {
      html: '<%= config.app %>/index.html',
      options: {
        dest: '<%= config.dist %>'
      }
    },

    usemin: {
      html: '<%= config.dist %>/index.html',
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        src: [
          ['<%= config.dist %>*','.tmp']
        ]
      },
      temp: {
        src: [
          ['.tmp']
        ]
      }
    },

    // configure watch to auto update ----------------
    watch: {
      files: ['styles/*.css'],
      tasks: ['useminPrepare','cssmin'],
      options: {
        cwd:'<%= config.app %>',
        livereload: true,
      },
    },

  });

  //load task
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-usemin');

  grunt.registerTask('cleanAll', ['clean']);

  grunt.registerTask('build', [
    'clean',
    'copy:dist',
    'useminPrepare',
    'concat:generated',
    'cssmin:generated',
    'uglify:generated',
    'usemin',
    'clean:temp'
]);

  grunt.registerTask('default', ['build']);

};<|endoftext|>


<commit_before>/**
 * Created by karolisrusenas on 13/04/2016.
 */
<commit_msg>showing stats as pie chart<commit_after>/**
 * Created by karolisrusenas on 13/04/2016.
 */
import React, {PropTypes} from 'react'
import ReactHighcharts from 'react-highcharts'
import {connect} from 'react-redux'

export default class CountersPie extends React.Component<void, Props, void> {
  constructor (props) {
    super(props)
    this.getOptions = this.getOptions.bind(this)
    this._prepareChartData = this._prepareChartData.bind(this)
  }

  _prepareChartData (counters) {
    let data = []
    for (var key in counters) {
      if (counters.hasOwnProperty(key)) {
        data.push({'name': key, 'y': counters[key]})
      }
    }
    return data
  }

  getOptions () {
    let data = this._prepareChartData(this.props.stats.counters)
    return {
      chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
      },
      credits: {
        enabled: false
      },
      title: {
        text: 'Requests statistics'
      },
      tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: false
          },
          showInLegend: true
        }
      },
      series: [{
        name: 'Type',
        colorByPoint: true,
        data: data
      }]
    }
  }

  componentWillMount () {
    this.getOptions()
  }

  render () {
    let options = this.getOptions()
    console.log('drwaing new chart')
    return (
      <ReactHighcharts config={options}/>
    )
  }
}

CountersPie.propTypes = {
  stats: PropTypes.object.isRequired
}

const mapStateToProps = (state) => ({
  stats: state.info.stats
})

export default connect(mapStateToProps, {})(CountersPie)

<|endoftext|>