<commit_before>var creep_work = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if ((creep.memory.building && creep.carry.energy == 0) || (creep.memory.storing && creep.carry.energy == 0) || (creep.memory.upgrading && creep.carry.energy == 0)) {
            creep.memory.building = false;
            creep.memory.storing = false;
            creep.memory.upgrading = false;
            creep.memory.structureTarget = undefined;
            creep.say('harvesting');
        }
        if (!creep.memory.building && !creep.memory.storing && !creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
            switch (creep.memory.priority) {
                case 'builder':
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
                case 'harvester':
                    creep.memory.storing = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('storing');
                    break;
                case 'upgrader':
                    creep.memory.upgrading = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('upgrading');
                    break;
                default:
                    //fucking what
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
            }

        }

        if (creep.memory.building) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //site ID changes when construction is complete, simply check if valid.
            if (savedTarget) {
                if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(savedTarget);
                }
            } else {
                var targets = creep.room.find(FIND_CONSTRUCTION_SITES);
                if (targets.length) {
                    creep.memory.structureTarget = targets[0].id;
                    if (creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Store in container
                    if (creep.memory.priority == 'harvester') {
                        //Already tried to store, upgrade.
                        creep.memory.building = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    } else {
                        creep.memory.building = false;
                        creep.memory.storing = true;
                        creep.say('storing');
                    }
                }
            }
        } else if (creep.memory.storing) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //If target is destroyed, this will prevent creep from locking up
            if (savedTarget) {
                if (savedTarget.energy < savedTarget.energyCapacity) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                } else {
                    //Target is invalid, clear from memory.
                    creep.memory.structureTarget = undefined;
                }
            } else {
                var targets = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_SPAWN ||
                            structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
                    }
                });
                if (targets.length > 0) {
                    creep.memory.structureTarget = targets[0].id;

                    if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Nowhere to store. Change action.
                    if (creep.memory.priority == 'harvester') {
                        //Try to build first
                        creep.memory.storing = false;
                        creep.memory.building = true;
                        creep.say('building');
                    } else {
                        creep.memory.storing = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    }
                }
            }

        } else if (creep.memory.upgrading) {
            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller);
            }
        } else {
            //Harvest
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
            if (savedTarget) {
                if (savedTarget.structureType == STRUCTURE_CONTAINER || savedTarget.structureType == STRUCTURE_STORAGE) {
                    if (savedTarget.energy > 0) {
                        if (creep.withdraw(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget);
                        }
                    }
                } else {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                var targets = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_STORAGE) && structure.energy > 0;
                    }
                });
                if (targets.length > 0) {
                    //Get from container
                    creep.memory.structureTarget = targets[0];
                    if (creep.withdraw(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Mine it yourself
                    var sources = creep.pos.findClosestByRange(FIND_DROPPED_ENERGY);
                    if (sources.length == 0) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE);
                    }
                    if (sources.length == 0) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES);
                    }
                    creep.memory.structureTarget = sources[0];
                    if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(sources[0]);
                    }
                }
            }
        }
    }
};

module.exports = creep_work;<commit_msg>Changes .find to .findClosestByRange<commit_after>var creep_work = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if ((creep.memory.building && creep.carry.energy == 0) || (creep.memory.storing && creep.carry.energy == 0) || (creep.memory.upgrading && creep.carry.energy == 0)) {
            creep.memory.building = false;
            creep.memory.storing = false;
            creep.memory.upgrading = false;
            creep.memory.structureTarget = undefined;
            creep.say('harvesting');
        }
        if (!creep.memory.building && !creep.memory.storing && !creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
            switch (creep.memory.priority) {
                case 'builder':
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
                case 'harvester':
                    creep.memory.storing = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('storing');
                    break;
                case 'upgrader':
                    creep.memory.upgrading = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('upgrading');
                    break;
                default:
                    //fucking what
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
            }

        }

        if (creep.memory.building) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //site ID changes when construction is complete, simply check if valid.
            if (savedTarget) {
                if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(savedTarget);
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                if (targets.length) {
                    creep.memory.structureTarget = targets[0].id;
                    if (creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Store in container
                    if (creep.memory.priority == 'harvester') {
                        //Already tried to store, upgrade.
                        creep.memory.building = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    } else {
                        creep.memory.building = false;
                        creep.memory.storing = true;
                        creep.say('storing');
                    }
                }
            }
        } else if (creep.memory.storing) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //If target is destroyed, this will prevent creep from locking up
            if (savedTarget) {
                if (savedTarget.energy < savedTarget.energyCapacity) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                } else {
                    //Target is invalid, clear from memory.
                    creep.memory.structureTarget = undefined;
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_SPAWN ||
                            structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
                    }
                });
                if (targets.length > 0) {
                    creep.memory.structureTarget = targets[0].id;

                    if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Nowhere to store. Change action.
                    if (creep.memory.priority == 'harvester') {
                        //Try to build first
                        creep.memory.storing = false;
                        creep.memory.building = true;
                        creep.say('building');
                    } else {
                        creep.memory.storing = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    }
                }
            }

        } else if (creep.memory.upgrading) {
            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller);
            }
        } else {
            //Harvest
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
            if (savedTarget) {
                if (savedTarget.structureType == STRUCTURE_CONTAINER || savedTarget.structureType == STRUCTURE_STORAGE) {
                    if (savedTarget.energy > 0) {
                        if (creep.withdraw(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget);
                        }
                    }
                } else {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_STORAGE) && structure.energy > 0;
                    }
                });
                if (targets.length > 0) {
                    //Get from container
                    creep.memory.structureTarget = targets[0].id;
                    if (creep.withdraw(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Mine it yourself
                    var sources = creep.pos.findClosestByRange(FIND_DROPPED_ENERGY);
                    if (!sources) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE);
                    }
                    if (!sources) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES);
                    }
                    creep.memory.structureTarget = sources.id;
                    if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(sources[0]);
                    }
                }
            }
        }
    }
};

module.exports = creep_work;<|endoftext|>


<commit_before>(function(g,Ai) {
	if (typeof exports!="undefined") {
		//exports.strongEval=strongEval;
		exports=Ai;
	}else{
		g.Ai=Ai;
	}
})(this,(function() {
	function lint(str){
		//find bad output
		var list=[],len,index,word;
		for (len=str.length; len>=1; len--) {
			if (!this.words[len]) this.words[len]={};
			for (index=0; index<(str.length-len); index++) {
				word=str.substr(index,len);
				if(!this.words[len][word]) this.words[len][word]=0;//value indicates how "good" a word is
				for(var index2=0; index2<len; index2++) {
					if (!list[index+index2]) list[index+index2]=0;
					if (word>-1) {
						list[index+index2]++;
					}else{
						list[index+index2]--;
					}
				}
			}
		}
		//change bad output to good output
		for(index=0; index<list.length; index++){
			if (((list[index]+list[index+1]+list[index+2])/3)<=-1) {
				word=str.substr(index,3);
				for(var i in this.context[3][word]) {
					if ()
				}
				if (word===str.substr(index,3)) {
					word=(Math.random()*(1<<8)).toString(36).replace(/[0-9]|\./g,"").slice(-3);
				}
			}
		}
		return str;
	}
	var Ai=function(name,obj) {
		/*
		There are 2 ways two run this function

			var myAi= new Ai("My AI's name");//1st
			var mySecondAi= new Ai("My 2nd AI's name",{
				//values here
			});//2nd
		*/
		if  (arguments.length===0||arguments.length>2) throw "The Ai constructor requires 1-2 values passed";
		obj=obj||{};//prevent bugs
		this.name=name;
		this.defaultResponces={
			"How are you?":"If you got this message, I am at least 25% operational.",
		};
		this.lastResponce="";
		this.words=[];
		this.context=[];
		this.inputTypes={
			string:function(str) {return str;},
		};
		if(typeof obj!="undefined") {
			for (var i in this) {
				if (typeof this[i]!="undefined") {
					for (var ii in obj[i]) {
						this[i][ii]=obj[i][ii];
					}
				}else this[i]=obj[i];//overwrite with obj
			}
		}
		/*if (typeof this.name!=="string") {
			throw "The name for your Ai bot must be a string";
		}*/
		this.respondTo=function(input,type) {
			/*
			How to use this function:

				var myAi= new Ai("My AI's name");
				var aisOutput=myAi.reactTo("input","usersname","type of input(optional but will use the typeof operator to determine this value if not specified)");
			*/
			var output="",len,index,word;//set varubles
			type=type||typeof input;

			//check varubles
			if (typeof this.inputTypes[type]==="undefined") {
				throw "Invalid type";
			}else{
				input=this.inputTypes[type](input);
			}

			//apply default responce
			if (this.defaultResponces.hasOwnProperty(input)) output+=this.defaultResponces[input];
			//lint
			output=lint.call(this,output);
			//add to memory
			this.defaultResponces[input]=output;
			this.lastResponce=output;//For the punish and reward functions
			for (len=1; len<output.length; len++) {
				if (!this.words[len]) {
					this.words[len]={};
					this.context[len]={};
				}
				for (index=0; index<(output.length-len); index++) {
					word=output.substr(index,len);
					if(!this.words[len][word]) {
						this.words[len][word]=0;//value indicates how "good" a word is
						this.context[len][word]={
							before:[output.substr(index-len,len)],
							after:[output.substr(index+len,len)],
						};
					}else{
						this.context[len][word].before.push(output.substr(index-len,len));
						this.context[len][word].after.push(output.substr(index+len,len));
					}
				}
			}
			//act
			return output;
		};
		this.punish=function(str){
			if (typeof str=="undefined") {
				str=this.lastResponce;
			}
			for (var len=1; len<str.length; len++) {
				if (!this.words[len]) this.words[len]={};
				for (var index=0; index<(str.length-len); index++) {
					var word=str.substr(index,len);
					if(!this.words[len][word]) {
						this.words[len][word]=0;//value indicates how "good" a word is
					}else{
						this.words[len][word]--;
					}
				}
			}
		};
		this.reward=function(str){
			if (typeof str=="undefined") {
				str=this.lastResponce;
			}
			for (var len=1; len<str.length; len++) {
				if (!this.words[len]) this.words[len]={};
				for (var index=0; index<(str.length-len); index++) {
					var word=str.substr(index,len);
					if(!this.words[len][word]) {
						this.words[len][word]=0;//value indicates how "good" a word is
					}else{
						this.words[len][word]++;
					}
				}
			}
		};
	};
	return Ai;
})());
<commit_msg>remove lint<commit_after>(function(g,Ai) {
	if (typeof exports!="undefined") {
		//exports.strongEval=strongEval;
		exports=Ai;
	}else{
		g.Ai=Ai;
	}
})(this,(function() {
	function randomString(len, an){//comes from http://stackoverflow.com/a/27872144
		an = an&&an.toLowerCase();
		var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
		for(;i++<len;){
			var r = Math.random()*(max-min)+min <<0;
			str += String.fromCharCode(r+=r>9?r<36?55:61:48);
		}
		return str;
	}
	function lint(str){
		//find bad output
		var list=[],len,index,word;
		for (len=str.length; len>=1; len--) {
			if (!this.words[len]) this.words[len]={};
			for (index=0; index<(str.length-len); index++) {
				word=str.substr(index,len);
				if(!this.words[len][word]) this.words[len][word]=0;//value indicates how "good" a word is
				for(var index2=0; index2<len; index2++) {
					if (!list[index+index2]) list[index+index2]=0;
					if (word>-1) {
						list[index+index2]++;
					}else{
						list[index+index2]--;
					}
				}
			}
		}
		//change bad output to good output
		for(index=0; index<list.length; index++){
			if (((list[index]+list[index+1]+list[index+2])/3)<=-1) {
				word=str.substr(index,3);
				for(var i in this.context[3][word]) {
					//if ()
				}
				if (word===str.substr(index,3)) {
					word=randomString(3);
				}
			}
		}
		return str;
	}
	var Ai=function(name,obj) {
		/*
		There are 2 ways two run this function

			var myAi= new Ai("My AI's name");//1st
			var mySecondAi= new Ai("My 2nd AI's name",{
				//values here
			});//2nd
		*/
		if  (arguments.length===0||arguments.length>2) throw "The Ai constructor requires 1-2 values passed";
		obj=obj||{};//prevent bugs
		this.name=name;
		this.defaultResponces={
			"How are you?":"If you got this message, I am at least 25% operational.",
		};
		this.lastResponce="";
		this.words=[];
		this.context=[];
		this.inputTypes={
			string:function(str) {return str;},
		};
		if(typeof obj!="undefined") {
			for (var i in this) {
				if (typeof this[i]!="undefined") {
					for (var ii in obj[i]) {
						this[i][ii]=obj[i][ii];
					}
				}else this[i]=obj[i];//overwrite with obj
			}
		}
		/*if (typeof this.name!=="string") {
			throw "The name for your Ai bot must be a string";
		}*/
		this.respondTo=function(input,type) {
			/*
			How to use this function:

				var myAi= new Ai("My AI's name");
				var aisOutput=myAi.reactTo("input","usersname","type of input(optional but will use the typeof operator to determine this value if not specified)");
			*/
			var output="",len,index,word;//set varubles
			type=type||typeof input;

			//check varubles
			if (typeof this.inputTypes[type]==="undefined") {
				throw "Invalid type";
			}else{
				input=this.inputTypes[type](input);
			}

			//apply default responce
			if (this.defaultResponces.hasOwnProperty(input)) output+=this.defaultResponces[input];
			//lint
			output=lint.call(this,output);
			//add to memory
			this.defaultResponces[input]=output;
			this.lastResponce=output;//For the punish and reward functions
			for (len=1; len<output.length; len++) {
				if (!this.words[len]) {
					this.words[len]={};
					this.context[len]={};
				}
				for (index=0; index<(output.length-len); index++) {
					word=output.substr(index,len);
					if(!this.words[len][word]) {
						this.words[len][word]=0;//value indicates how "good" a word is
						this.context[len][word]={
							before:[output.substr(index-len,len)],
							after:[output.substr(index+len,len)],
						};
					}else{
						this.context[len][word].before.push(output.substr(index-len,len));
						this.context[len][word].after.push(output.substr(index+len,len));
					}
				}
			}
			//act
			return output;
		};
		this.punish=function(str){
			if (typeof str=="undefined") {
				str=this.lastResponce;
			}
			for (var len=1; len<str.length; len++) {
				if (!this.words[len]) this.words[len]={};
				for (var index=0; index<(str.length-len); index++) {
					var word=str.substr(index,len);
					if(!this.words[len][word]) {
						this.words[len][word]=0;//value indicates how "good" a word is
					}else{
						this.words[len][word]--;
					}
				}
			}
		};
		this.reward=function(str){
			if (typeof str=="undefined") {
				str=this.lastResponce;
			}
			for (var len=1; len<str.length; len++) {
				if (!this.words[len]) this.words[len]={};
				for (var index=0; index<(str.length-len); index++) {
					var word=str.substr(index,len);
					if(!this.words[len][word]) {
						this.words[len][word]=0;//value indicates how "good" a word is
					}else{
						this.words[len][word]++;
					}
				}
			}
		};
	};
	return Ai;
})());
<|endoftext|>


<commit_before>// Copyright (c) 2017 Euan Ong
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA

function GlobalCard(Planet) {
    this.ProjectData = null;
    this.id = null;
    this.PlaceholderMBImage = 'images/mbgraphic.png';
    this.PlaceholderTBImage = 'images/tbgraphic.png';
    this.renderData = '\

 \

 \

 \
             \

 \

 \
             \

 \

 \

 \

 \

 \
                '+_('More Details')+' \
                 \
                 \

 \
                                        share \

 \

 \

'+_('Share')+'
 \
                                                        <input id="shareurlselect" type="text" name="shareurl" class="shareurlinput" data-originalurl="https://musicblocks.sugarlabs.org/index.html?id={ID}"> \
                                                        Copy URL to clipboard\

 \

'+_('Flags')+'
 \

<input type="checkbox" name="run" id="global-checkboxrun-{ID}" checked>'+_('Run project on startup.')+'
 \

<input type="checkbox" name="show" id="global-checkboxshow-{ID}">'+_('Show code blocks on startup.')+'
 \

<input type="checkbox" name="collapse" id="global-checkboxcollapse-{ID}">'+_('Collapse code blocks on startup.')+'
 \

 \

 \

 \
                                                        '+_('Advanced Options')+' \

 \

 \

 \

 \

 \

 \

';

    this.render = function() {
        //TODO: Have a TB placeholder image specific to TB projects
        var html = this.renderData.replace(new RegExp('\{ID\}', 'g'), this.id);
        var frag = document.createRange().createContextualFragment(html);

        // set image
        if (this.ProjectData.ProjectImage !== null && this.ProjectData.ProjectImage !== ''){
            frag.getElementById('global-project-image-' + this.id).src = this.ProjectData.ProjectImage;
        } else if (this.ProjectData.ProjectIsMusicBlocks === 1){
            frag.getElementById('global-project-image-' + this.id).src = this.PlaceholderMBImage;
        } else {
            frag.getElementById('global-project-image-' + this.id).src = this.PlaceholderTBImage;
        }

        // set tags
        var tagcontainer = frag.getElementById('global-project-tags-' + this.id);
        for (var i = 0; i < this.ProjectData.ProjectTags.length; i++){
            var chip = document.createElement('div');
            chip.classList.add('chipselect');
            chip.textContent = Planet.TagsManifest[this.ProjectData.ProjectTags[i]].TagName;
            tagcontainer.appendChild(chip);
        }

        // set title text
        frag.getElementById('global-project-title-' + this.id).textContent = this.ProjectData.ProjectName;

        // set number of likes
        frag.getElementById('global-project-likes-' + this.id).textContent = this.ProjectData.ProjectLikes.toString();

        var that = this;

        // set view button listener
        frag.getElementById('global-project-more-details-' + this.id).addEventListener('click', function (evt) {
            Planet.GlobalPlanet.ProjectViewer.open(that.id);
        });

        // set image listener
        frag.getElementById('global-project-image-' + this.id).addEventListener('click', function (evt) {
            Planet.GlobalPlanet.ProjectViewer.open(that.id);
        });

        // set share button listener
        frag.getElementById('global-project-share-' + this.id).addEventListener('click', function (evt) {
            var s = document.getElementById('global-sharebox-' + that.id);
            if (s.style.display=='none') {
                s.style.display = 'initial';
                hideOnClickOutside([document.getElementById('global-share-' + that.id)], 'global-sharebox-' + that.id);
            } else {
                s.style.display = 'none';
            }
        });

        // set share checkbox listener
        frag.getElementById('global-checkboxrun-' + this.id).addEventListener('click', function (evt) {
            updateCheckboxes('global-sharebox-' + that.id);
        });
        frag.getElementById('global-checkboxshow-' + this.id).addEventListener('click', function (evt) {
            updateCheckboxes('global-sharebox-' + that.id);
        });
        frag.getElementById('global-checkboxcollapse-' + this.id).addEventListener('click', function (evt) {
            updateCheckboxes('global-sharebox-' + that.id);
        });

        // set like icon
        if (Planet.ProjectStorage.isLiked(this.id)){
            frag.getElementById('global-like-icon-' + this.id).textContent = 'favorite';
        } else {
            frag.getElementById('global-like-icon-' + this.id).textContent = 'favorite_border';
        }

        frag.getElementById('global-like-icon-' + this.id).addEventListener('click', function (evt) {
            that.like();
        });

        document.getElementById('global-projects').appendChild(frag);
        updateCheckboxes('global-sharebox-' + that.id);
    };

    this.like = function() {
        var like = true;
        if (Planet.ProjectStorage.isLiked(this.id)) {
            like = false;
        }

        Planet.ServerInterface.likeProject(this.id, like, function(data) {
            this.afterLike(data,like);
        }.bind(this));
    };

    this.afterLike = function(data, like) {
        if (!data.success) {
            if (data.error === 'ERROR_ACTION_NOT_PERMITTED') {
                this.setLike(like);
            }
        } else {
            this.setLike(like);
        }
    };

    this.setLike = function(like) {
        Planet.ProjectStorage.like(this.id,like);
        var incr = 1;
        var text = 'favorite';
        if (!like) {
            incr = -1;
            text = 'favorite_border';
        }

        var l = document.getElementById('global-project-likes-' + this.id);
        l.textContent = (parseInt(l.textContent) + incr).toString();
        document.getElementById('global-like-icon-' + this.id).textContent = text;
    };

    this.init = function(id){
        this.id = id;
        this.ProjectData = Planet.GlobalPlanet.cache[id];
    };
};

function share(id) {
    this.id = id;
    try {
        const toCopy = "https://musicblocks.sugarlabs.org/index.html?id="+id+"&run=True";
        navigator.clipboard.writeText(toCopy);
        alert("Copied!");
        console.log('MB url copied');
      } catch (err) {
        console.error('Failed to copy: ', err);
      }
}
<commit_msg>Fixes #1419<commit_after>// Copyright (c) 2017 Euan Ong
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA

function GlobalCard(Planet) {
    this.ProjectData = null;
    this.id = null;
    this.PlaceholderMBImage = 'images/mbgraphic.png';
    this.PlaceholderTBImage = 'images/tbgraphic.png';
    this.renderData = '\

 \

 \

 \
             \

 \

 \
             \

 \

 \

 \

 \

 \
                '+_('More Details')+' \
                 \
                 \

 \
                                        share \

 \

 \

'+_('Share')+'
 \
                                                        <input id="shareurlselect" type="text" name="shareurl" class="shareurlinput" data-originalurl="https://musicblocks.sugarlabs.org/index.html?id={ID}"> \
                                                        Copy URL to clipboard\

 \

'+_('Flags')+'
 \

<input type="checkbox" name="run" id="global-checkboxrun-{ID}" checked>'+_('Run project on startup.')+'
 \

<input type="checkbox" name="show" id="global-checkboxshow-{ID}">'+_('Show code blocks on startup.')+'
 \

<input type="checkbox" name="collapse" id="global-checkboxcollapse-{ID}">'+_('Collapse code blocks on startup.')+'
 \

 \

 \

 \
                                                        '+_('Advanced Options')+' \

 \

 \

 \

 \

 \

 \

';

    this.render = function() {
        //TODO: Have a TB placeholder image specific to TB projects
        var html = this.renderData.replace(new RegExp('\{ID\}', 'g'), this.id);
        var frag = document.createRange().createContextualFragment(html);

        // set image
        if (this.ProjectData.ProjectImage !== null && this.ProjectData.ProjectImage !== ''){
            frag.getElementById('global-project-image-' + this.id).src = this.ProjectData.ProjectImage;
        } else if (this.ProjectData.ProjectIsMusicBlocks === 1){
            frag.getElementById('global-project-image-' + this.id).src = this.PlaceholderMBImage;
        } else {
            frag.getElementById('global-project-image-' + this.id).src = this.PlaceholderTBImage;
        }

        // set tags
        var tagcontainer = frag.getElementById('global-project-tags-' + this.id);
        for (var i = 0; i < this.ProjectData.ProjectTags.length; i++){
            var chip = document.createElement('div');
            chip.classList.add('chipselect');
            chip.textContent = Planet.TagsManifest[this.ProjectData.ProjectTags[i]].TagName;
            tagcontainer.appendChild(chip);
        }

        // set title text
        frag.getElementById('global-project-title-' + this.id).textContent = this.ProjectData.ProjectName;

        // set number of likes
        frag.getElementById('global-project-likes-' + this.id).textContent = this.ProjectData.ProjectLikes.toString();

        var that = this;

        // set view button listener
        frag.getElementById('global-project-more-details-' + this.id).addEventListener('click', function (evt) {
            Planet.GlobalPlanet.ProjectViewer.open(that.id);
        });

        // set image listener
        frag.getElementById('global-project-image-' + this.id).addEventListener('click', function (evt) {
            Planet.GlobalPlanet.ProjectViewer.open(that.id);
        });

        // set share button listener
        frag.getElementById('global-project-share-' + this.id).addEventListener('click', function (evt) {
            var s = document.getElementById('global-sharebox-' + that.id);
            if (s.style.display=='none') {
                s.style.display = 'initial';
                hideOnClickOutside([document.getElementById('global-share-' + that.id)], 'global-sharebox-' + that.id);
            } else {
                s.style.display = 'none';
            }
        });

        // set share checkbox listener
        frag.getElementById('global-checkboxrun-' + this.id).addEventListener('click', function (evt) {
            updateCheckboxes('global-sharebox-' + that.id);
        });
        frag.getElementById('global-checkboxshow-' + this.id).addEventListener('click', function (evt) {
            updateCheckboxes('global-sharebox-' + that.id);
        });
        frag.getElementById('global-checkboxcollapse-' + this.id).addEventListener('click', function (evt) {
            updateCheckboxes('global-sharebox-' + that.id);
        });

        // set like icon
        if (Planet.ProjectStorage.isLiked(this.id)){
            frag.getElementById('global-like-icon-' + this.id).textContent = 'favorite';
        } else {
            frag.getElementById('global-like-icon-' + this.id).textContent = 'favorite_border';
        }

        frag.getElementById('global-like-icon-' + this.id).addEventListener('click', function (evt) {
            that.like();
        });

        document.getElementById('global-projects').appendChild(frag);
        updateCheckboxes('global-sharebox-' + that.id);
    };

    this.like = function() {
        var like = true;
        if (Planet.ProjectStorage.isLiked(this.id)) {
            like = false;
        }

        Planet.ServerInterface.likeProject(this.id, like, function(data) {
            this.afterLike(data,like);
        }.bind(this));
    };

    this.afterLike = function(data, like) {
        if (!data.success) {
            if (data.error === 'ERROR_ACTION_NOT_PERMITTED') {
                this.setLike(like);
            }
        } else {
            this.setLike(like);
        }
    };

    this.setLike = function(like) {
        Planet.ProjectStorage.like(this.id,like);
        var incr = 1;
        var text = 'favorite';
        if (!like) {
            incr = -1;
            text = 'favorite_border';
        }

        var l = document.getElementById('global-project-likes-' + this.id);
        l.textContent = (parseInt(l.textContent) + incr).toString();
        document.getElementById('global-like-icon-' + this.id).textContent = text;
    };

    this.init = function(id){
        this.id = id;
        this.ProjectData = Planet.GlobalPlanet.cache[id];
    };
};

function share(id) {
    this.id = id;
    try {
        const toCopy = "https://musicblocks.sugarlabs.org/index.html?id="+id+"&run=True";
        navigator.clipboard.writeText(toCopy);
        alert("Copied!");
        console.log('MB url copied');
      } catch (err) {
        console.error('Failed to copy: ', err);
      }
}
<|endoftext|>


<commit_before>import { getBindingIdentifiers } from "./retrievers";
import esutils from "esutils";
import * as t from "./index";

/**
 * Check if the input `node` is a binding identifier.
 */

export function isBinding(node: Object, parent: Object): boolean {
  var keys = getBindingIdentifiers.keys[parent.type];
  if (keys) {
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var val = parent[key];
      if (Array.isArray(val)) {
        if (val.indexOf(node) >= 0) return true;
      } else {
        if (val === node) return true;
      }
    }
  }

  return false;
}

/**
 * Check if the input `node` is a reference to a bound variable.
 */

export function isReferenced(node: Object, parent: Object): boolean {
  switch (parent.type) {
    // yes: PARENT[NODE]
    // yes: NODE.child
    // no: parent.NODE
    case "MemberExpression":
    case "JSXMemberExpression":
      if (parent.property === node && parent.computed) {
        return true;
      } else if (parent.object === node) {
        return true;
      } else {
        return false;
      }

    // no: new.NODE
    // no: NODE.target
    case "MetaProperty":
      return false;

    // yes: { [NODE]: "" }
    // yes: { NODE }
    // no: { NODE: "" }
    case "Property":
      if (parent.key === node) {
        return parent.computed;
      }

    // no: var NODE = init;
    // yes: var id = NODE;
    case "VariableDeclarator":
      return parent.id !== node;

    // no: function NODE() {}
    // no: function foo(NODE) {}
    case "ArrowFunctionExpression":
    case "FunctionDeclaration":
    case "FunctionExpression":
      for (var param of (parent.params: Array)) {
        if (param === node) return false;
      }

      return parent.id !== node;

    // no: export { foo as NODE };
    // yes: export { NODE as foo };
    // no: export { NODE as foo } from "foo";
    case "ExportSpecifier":
      if (parent.source) {
        return false;
      } else {
        return parent.local === node;
      }

    // no:

    case "JSXAttribute":
      return parent.name !== node;

    // no: class { NODE = value; }
    // yes: class { key = NODE; }
    case "ClassProperty":
      return parent.value === node;

    // no: import NODE from "foo";
    // no: import * as NODE from "foo";
    // no: import { NODE as foo } from "foo";
    // no: import { foo as NODE } from "foo";
    // no: import NODE from "bar";
    case "ImportDefaultSpecifier":
    case "ImportNamespaceSpecifier":
    case "ImportSpecifier":
      return false;

    // no: class NODE {}
    case "ClassDeclaration":
    case "ClassExpression":
      return parent.id !== node;

    // yes: class { [NODE](){} }
    case "MethodDefinition":
      return parent.key === node && parent.computed;

    // no: NODE: for (;;) {}
    case "LabeledStatement":
      return false;

    // no: try {} catch (NODE) {}
    case "CatchClause":
      return parent.param !== node;

    // no: function foo(...NODE) {}
    case "RestElement":
      return false;

    // yes: left = NODE;
    // no: NODE = right;
    case "AssignmentExpression":
      return parent.right === node;

    // no: [NODE = foo] = [];
    // no: [foo = NODE] = [];
    case "AssignmentPattern":
      return false;

    // no: [NODE] = [];
    // no: ({ NODE }) = [];
    case "ObjectPattern":
    case "ArrayPattern":
      return false;
  }

  return true;
}

/**
 * Check if the input `name` is a valid identifier name
 * and isn't a reserved word.
 */

export function isValidIdentifier(name: string): boolean {
  if (typeof name !== "string" || esutils.keyword.isReservedWordES6(name, true)) {
    return false;
  } else {
    return esutils.keyword.isIdentifierNameES6(name);
  }
}

/**
 * Check if the input `node` is a `let` variable declaration.
 */

export function isLet(node: Object): boolean {
  return t.isVariableDeclaration(node) && (node.kind !== "var" || node._let);
}

/**
 * Check if the input `node` is block scoped.
 */

export function isBlockScoped(node: Object): boolean {
  return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node);
}

/**
 * Check if the input `node` is a variable declaration.
 */

export function isVar(node: Object): boolean {
  return t.isVariableDeclaration(node, { kind: "var" }) && !node._let;
}

/**
 * Check if the input `specifier` is a `default` import or export.
 */

export function isSpecifierDefault(specifier: Object): boolean {
  return t.isImportDefaultSpecifier(specifier) ||
         t.isIdentifier(specifier.imported || specifier.exported, { name: "default" });
}

/**
 * Check if the input `node` is a scope.
 */

export function isScope(node: Object, parent: Object): boolean {
  if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
    return false;
  }

  return t.isScopable(node);
}

/**
 * Check if the input `node` is definitely immutable.
 */

export function isImmutable(node: Object): boolean {
  if (t.isType(node.type, "Immutable")) return true;

  if (t.isIdentifier(node)) {
    if (node.name === "undefined") {
      // immutable!
      return true;
    } else {
      // no idea...
      return false;
    }
  }

  return false;
}
<commit_msg>add support for bind expression to t.isReferenced<commit_after>import { getBindingIdentifiers } from "./retrievers";
import esutils from "esutils";
import * as t from "./index";

/**
 * Check if the input `node` is a binding identifier.
 */

export function isBinding(node: Object, parent: Object): boolean {
  var keys = getBindingIdentifiers.keys[parent.type];
  if (keys) {
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var val = parent[key];
      if (Array.isArray(val)) {
        if (val.indexOf(node) >= 0) return true;
      } else {
        if (val === node) return true;
      }
    }
  }

  return false;
}

/**
 * Check if the input `node` is a reference to a bound variable.
 */

export function isReferenced(node: Object, parent: Object): boolean {
  switch (parent.type) {
    // yes: PARENT[NODE]
    // yes: NODE.child
    // no: parent.NODE
    case "MemberExpression":
    case "JSXMemberExpression":
    case "BindExpression":
      if (parent.property === node && parent.computed) {
        return true;
      } else if (parent.object === node) {
        return true;
      } else {
        return false;
      }

    // no: new.NODE
    // no: NODE.target
    case "MetaProperty":
      return false;

    // yes: { [NODE]: "" }
    // yes: { NODE }
    // no: { NODE: "" }
    case "Property":
      if (parent.key === node) {
        return parent.computed;
      }

    // no: var NODE = init;
    // yes: var id = NODE;
    case "VariableDeclarator":
      return parent.id !== node;

    // no: function NODE() {}
    // no: function foo(NODE) {}
    case "ArrowFunctionExpression":
    case "FunctionDeclaration":
    case "FunctionExpression":
      for (var param of (parent.params: Array)) {
        if (param === node) return false;
      }

      return parent.id !== node;

    // no: export { foo as NODE };
    // yes: export { NODE as foo };
    // no: export { NODE as foo } from "foo";
    case "ExportSpecifier":
      if (parent.source) {
        return false;
      } else {
        return parent.local === node;
      }

    // no:

    case "JSXAttribute":
      return parent.name !== node;

    // no: class { NODE = value; }
    // yes: class { key = NODE; }
    case "ClassProperty":
      return parent.value === node;

    // no: import NODE from "foo";
    // no: import * as NODE from "foo";
    // no: import { NODE as foo } from "foo";
    // no: import { foo as NODE } from "foo";
    // no: import NODE from "bar";
    case "ImportDefaultSpecifier":
    case "ImportNamespaceSpecifier":
    case "ImportSpecifier":
      return false;

    // no: class NODE {}
    case "ClassDeclaration":
    case "ClassExpression":
      return parent.id !== node;

    // yes: class { [NODE](){} }
    case "MethodDefinition":
      return parent.key === node && parent.computed;

    // no: NODE: for (;;) {}
    case "LabeledStatement":
      return false;

    // no: try {} catch (NODE) {}
    case "CatchClause":
      return parent.param !== node;

    // no: function foo(...NODE) {}
    case "RestElement":
      return false;

    // yes: left = NODE;
    // no: NODE = right;
    case "AssignmentExpression":
      return parent.right === node;

    // no: [NODE = foo] = [];
    // no: [foo = NODE] = [];
    case "AssignmentPattern":
      return false;

    // no: [NODE] = [];
    // no: ({ NODE }) = [];
    case "ObjectPattern":
    case "ArrayPattern":
      return false;
  }

  return true;
}

/**
 * Check if the input `name` is a valid identifier name
 * and isn't a reserved word.
 */

export function isValidIdentifier(name: string): boolean {
  if (typeof name !== "string" || esutils.keyword.isReservedWordES6(name, true)) {
    return false;
  } else {
    return esutils.keyword.isIdentifierNameES6(name);
  }
}

/**
 * Check if the input `node` is a `let` variable declaration.
 */

export function isLet(node: Object): boolean {
  return t.isVariableDeclaration(node) && (node.kind !== "var" || node._let);
}

/**
 * Check if the input `node` is block scoped.
 */

export function isBlockScoped(node: Object): boolean {
  return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node);
}

/**
 * Check if the input `node` is a variable declaration.
 */

export function isVar(node: Object): boolean {
  return t.isVariableDeclaration(node, { kind: "var" }) && !node._let;
}

/**
 * Check if the input `specifier` is a `default` import or export.
 */

export function isSpecifierDefault(specifier: Object): boolean {
  return t.isImportDefaultSpecifier(specifier) ||
         t.isIdentifier(specifier.imported || specifier.exported, { name: "default" });
}

/**
 * Check if the input `node` is a scope.
 */

export function isScope(node: Object, parent: Object): boolean {
  if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
    return false;
  }

  return t.isScopable(node);
}

/**
 * Check if the input `node` is definitely immutable.
 */

export function isImmutable(node: Object): boolean {
  if (t.isType(node.type, "Immutable")) return true;

  if (t.isIdentifier(node)) {
    if (node.name === "undefined") {
      // immutable!
      return true;
    } else {
      // no idea...
      return false;
    }
  }

  return false;
}
<|endoftext|>


<commit_before>import Ember from "ember";
import AjaxPromise from "../utils/ajax-promise";
import config from "../config/environment";

export default Ember.Mixin.create({
  messages: Ember.inject.service(),

  preloadData(includePublicTypes) {
    var promises = [];
    var isDonorApp = this.get("session.isDonorApp");

    var retrieve = types =>
      types.map(type => this.store.findAll(type, { reload: true }));

    if (includePublicTypes && isDonorApp) {
      promises = retrieve(config.APP.PRELOAD_TYPES);
    }

    if (this.get("session.authToken")) {
      promises.push(
        new AjaxPromise(
          "/auth/current_user_profile",
          "GET",
          this.session.get("authToken")
        ).then(data => {
          this.store.pushPayload(data);
          this.store.pushPayload({ user: data.user_profile });
          this.notifyPropertyChange("session.currentUser");
        })
      );

      if (isDonorApp) {
        promises.push(this.store.query("offer", { states: ["for_donor"] }));
        promises = promises.concat(
          retrieve(config.APP.PRELOAD_AUTHORIZED_TYPES)
        );
      }
    }

    return Ember.RSVP.all(promises).then(results => {
      // this.runBackgroundTasks();
      return results;
    });
  },

  runBackgroundTasks() {
    // We don't wait for the following tasks to return
    if (this.session.get("isAdminApp")) {
      this.get("messages").fetchUnreadMessages();
    }
  },

  loadStaticData(includePublicTypes) {
    var promises = [];
    var retrieve = types =>
      types.map(type => this.store.findAll(type, { reload: true }));
    if (includePublicTypes) {
      promises = retrieve(config.APP.PRELOAD_TYPES);
    }
    if (this.get("session.authToken")) {
      promises = promises.concat(retrieve(config.APP.PRELOAD_AUTHORIZED_TYPES));
    }
    return Ember.RSVP.all(promises);
  }
});
<commit_msg>revert  offers preload removal code<commit_after>import Ember from "ember";
import AjaxPromise from "../utils/ajax-promise";
import config from "../config/environment";

export default Ember.Mixin.create({
  messages: Ember.inject.service(),

  preloadData(includePublicTypes) {
    var promises = [];
    var isDonorApp = this.get("session.isDonorApp");

    var retrieve = types =>
      types.map(type => this.store.findAll(type, { reload: true }));

    if (includePublicTypes && isDonorApp) {
      promises = retrieve(config.APP.PRELOAD_TYPES);
    }

    if (this.get("session.authToken")) {
      promises.push(
        new AjaxPromise(
          "/auth/current_user_profile",
          "GET",
          this.session.get("authToken")
        ).then(data => {
          this.store.pushPayload(data);
          this.store.pushPayload({ user: data.user_profile });
          this.notifyPropertyChange("session.currentUser");
        })
      );

      var offer_params = this.session.get("isAdminApp")
        ? { states: ["nondraft"], summarize: true }
        : { states: ["for_donor"] };
      promises.push(this.store.query("offer", offer_params));

      if (isDonorApp) {
        promises = promises.concat(
          retrieve(config.APP.PRELOAD_AUTHORIZED_TYPES)
        );
      }
    }

    return Ember.RSVP.all(promises).then(results => {
      this.runBackgroundTasks();
      return results;
    });
  },

  runBackgroundTasks() {
    // We don't wait for the following tasks to return
    if (this.session.get("isAdminApp")) {
      this.get("messages").fetchUnreadMessages();
    }
  },

  loadStaticData(includePublicTypes) {
    var promises = [];
    var retrieve = types =>
      types.map(type => this.store.findAll(type, { reload: true }));
    if (includePublicTypes) {
      promises = retrieve(config.APP.PRELOAD_TYPES);
    }
    if (this.get("session.authToken")) {
      promises = promises.concat(retrieve(config.APP.PRELOAD_AUTHORIZED_TYPES));
    }
    return Ember.RSVP.all(promises);
  }
});
<|endoftext|>


<commit_before>/*

Copyright (c) 2011, Steven Thurlow
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Steven Thurlow nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

var DataFrame = function(samples, seeds) {
	this.samples = samples;
	this.seeds = seeds || [];
}
DataFrame.prototype = {
	samples: [],
	seeds: [],
	range: 0.0
};
DataFrame.prototype.constructor = DataFrame;

function nthOrderError(i, arr, order, seeds) {
	if (order > 0) {
		return nthOrderError(i, arr, order-1, seeds) - nthOrderError(i-1, arr, order-1, seeds);
	}
	else {
		if (i >= 0) return arr[i];
		else return (seeds[seeds.length + i] || 0);
	}
}

function nthOrderPrediction(i, arr, order, seeds) {
	function val(i) { return (arr[i] || seeds[seeds.length + i] || 0); }
	if (order == 0)
		return 0;
	if (order == 1)
		return val(i-1);
	if (order == 2)
		return 2*val(i-1) - val(i-2);
	if (order == 3)
		return 3*val(i-1) - 3*val(i-2) + val(i-3);
}

function encodeNth(input, order, seeds) {
	seeds = seeds || [];
	return new DataFrame(
		input.map(
			function(curr, i, out) {
				return nthOrderError(i, out, order, seeds);
			}),
		seeds);
};

function decodeNth(dataFrame, order) {
	var output = new Float32Array(dataFrame.samples.length);
	dataFrame.samples.map(
		function(curr,i,input) {
			return (output[i] = nthOrderPrediction(i, output, order, dataFrame.seeds) + curr);
		});
	return output;
};

// linear adaptive quantization
function quantizeLin(dataFrame, bits) {
	bits = bits || 4;
	var err = 0;
	//dataFrame.range = 0.125;
	dataFrame.range = Math.max.apply(Math, Array.prototype.slice.call(dataFrame.samples));
	var steps = Math.pow(bits, 2) / 2;
	var stepSize = dataFrame.range / steps;
	dataFrame.samples = dataFrame.samples.map(function(curr, i, out) {
		var val = (curr + err) / stepSize;
		if (val >= 0) val = Math.round(val >= steps ? steps - 1 : val);
		else val = Math.round(val < -steps ? -steps : val);

		err = curr + err - val * stepSize;
		return val;
	});
}

function unQuantizeLin(dataFrame, bits) {
	var steps = Math.pow(bits, 2) / 2;
	var stepSize = dataFrame.range / steps;
	dataFrame.samples = dataFrame.samples.map(function(curr, i, out) {
		return curr * stepSize;
	});
}

function quantizeLog(input, levels, range) {

}
<commit_msg>fix licence<commit_after>/*

Copyright (c) 2011, Steven Thurlow
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of aud.i-o nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

var DataFrame = function(samples, seeds) {
	this.samples = samples;
	this.seeds = seeds || [];
}
DataFrame.prototype = {
	samples: [],
	seeds: [],
	range: 0.0
};
DataFrame.prototype.constructor = DataFrame;

function nthOrderError(i, arr, order, seeds) {
	if (order > 0) {
		return nthOrderError(i, arr, order-1, seeds) - nthOrderError(i-1, arr, order-1, seeds);
	}
	else {
		if (i >= 0) return arr[i];
		else return (seeds[seeds.length + i] || 0);
	}
}

function nthOrderPrediction(i, arr, order, seeds) {
	function val(i) { return (arr[i] || seeds[seeds.length + i] || 0); }
	if (order == 0)
		return 0;
	if (order == 1)
		return val(i-1);
	if (order == 2)
		return 2*val(i-1) - val(i-2);
	if (order == 3)
		return 3*val(i-1) - 3*val(i-2) + val(i-3);
}

function encodeNth(input, order, seeds) {
	seeds = seeds || [];
	return new DataFrame(
		input.map(
			function(curr, i, out) {
				return nthOrderError(i, out, order, seeds);
			}),
		seeds);
};

function decodeNth(dataFrame, order) {
	var output = new Float32Array(dataFrame.samples.length);
	dataFrame.samples.map(
		function(curr,i,input) {
			return (output[i] = nthOrderPrediction(i, output, order, dataFrame.seeds) + curr);
		});
	return output;
};

// linear adaptive quantization
function quantizeLin(dataFrame, bits) {
	bits = bits || 4;
	var err = 0;
	//dataFrame.range = 0.125;
	dataFrame.range = Math.max.apply(Math, Array.prototype.slice.call(dataFrame.samples));
	var steps = Math.pow(bits, 2) / 2;
	var stepSize = dataFrame.range / steps;
	dataFrame.samples = dataFrame.samples.map(function(curr, i, out) {
		var val = (curr + err) / stepSize;
		if (val >= 0) val = Math.round(val >= steps ? steps - 1 : val);
		else val = Math.round(val < -steps ? -steps : val);

		err = curr + err - val * stepSize;
		return val;
	});
}

function unQuantizeLin(dataFrame, bits) {
	var steps = Math.pow(bits, 2) / 2;
	var stepSize = dataFrame.range / steps;
	dataFrame.samples = dataFrame.samples.map(function(curr, i, out) {
		return curr * stepSize;
	});
}

function quantizeLog(input, levels, range) {

}
<|endoftext|>


<commit_before>import {PureComponent} from 'react';
import {bind} from 'lodash-decorators';
import './CommentInput.css';

export default class CommentInput extends PureComponent {

    state = {
        content: ''
    };

    @bind()
    syncContent(e) {
        this.setState({content: e.target.value});
    }

    @bind()
    save() {
        const {onSave} = this.props;
        const {content} = this.state;

        onSave(content);
    }

    render() {
        return (

                <textarea autoFocus onChange={this.syncContent} />

                    Markdown enabled
                    <button type="button" onClick={this.save}>保存</button>

        );
    }
}
<commit_msg>Translate the comment save button into english<commit_after>import {PureComponent} from 'react';
import {bind} from 'lodash-decorators';
import './CommentInput.css';

export default class CommentInput extends PureComponent {

    state = {
        content: ''
    };

    @bind()
    syncContent(e) {
        this.setState({content: e.target.value});
    }

    @bind()
    save() {
        const {onSave} = this.props;
        const {content} = this.state;

        onSave(content);
    }

    render() {
        return (

                <textarea autoFocus onChange={this.syncContent} />

                    Markdown enabled
                    <button type="button" onClick={this.save}>Save</button>

        );
    }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Web3 from 'web3'
import { Loader } from '../components/Common/Loader'

const ONE_SECOND = 1000

class Web3Provider extends Component {
  constructor(props, context) {
    super(props, context)

    this.state = {
      selectedAccount: null,
      web3: null,
      approvePermissions: null,
      render: null
    }

  }

  render() {
    const { web3UnavailableScreen: Web3UnavailableScreen } = this.props

    if (this.state.render && this.state.web3 && this.state.approvePermissions) {
      return this.props.children
    }

    if (!this.state.render && (!this.state.web3 || !this.state.approvePermissions)) {
      return <Loader show={true} />
    }

    if (this.state.render && (!this.state.web3 || !this.state.approvePermissions)) {
      return <Web3UnavailableScreen />
    }

    return null
  }

  componentDidMount() {
    this.checkWeb3()
      .then(this.initPoll())
      .then(() => {
        this.setState({
          render: true
        })
      })
      .catch(err => {
        console.log(err)
        this.setState({
          render: true
        })
      })
  }

  checkWeb3() {
    const setWeb3 = () => {
      try {
        window.web3 = new Web3(window.web3.currentProvider)
        this.setState({
          approvePermissions: true,
          web3: window.web3
        })
      } catch (err) {
        console.log('There was a problem fetching accounts', err)
      }
    }

    return new Promise((resolve, reject) => {
      const { ethereum } = window

      // Modern dapp browsers...
      if (ethereum) {
        window.web3 = new Web3(ethereum)
          // Request account access if needed
        ethereum.enable().then(() => {
          if (!this.state.web3) {
            setWeb3()
          }
        }).catch(err => {
          this.setState({
            approvePermissions: false
          })
          reject()
        })
        resolve()
      }
        // Legacy dapp browsers...
      else if (window.web3) {
        setWeb3()
        resolve()
      }
        // Non-dapp browsers...
      else {
        this.setState({
          approvePermissions: false
        })
        reject()
      }
    })
  }

  componentWillUnmount() {
    clearInterval(this.interval)
  }

  initPoll = () => {
    if (!this.interval) {
      this.interval = setInterval(this.fetchAccounts, ONE_SECOND)
    }
  }

  fetchAccounts = () => {
    const { web3  } = this.state
    const { onChangeAccount } = this.props

    if (!web3 || !web3.eth) {
      return
    }

    return web3.eth.getAccounts()
      .then(accounts => {
        if (!accounts || !accounts.length) {
          return
        }

        let curr = this.state.selectedAccount
        let next = accounts[0]
        curr = curr && curr.toLowerCase()
        next = next && next.toLowerCase()

        const didChange = curr && next && (curr !== next)

        if (didChange && typeof onChangeAccount === 'function') {
          onChangeAccount(next)
        }

        this.setState({
          selectedAccount: next || null
        })
      })
  }

  getChildContext() {
    return {
      web3: this.state.web3,
      selectedAccount: this.state.selectedAccount
    }
  }
}

Web3Provider.childContextTypes = {
  web3: PropTypes.object,
  selectedAccount: PropTypes.string
}

export default Web3Provider;
<commit_msg>Added catch<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Web3 from 'web3'
import { Loader } from '../components/Common/Loader'

const ONE_SECOND = 1000

class Web3Provider extends Component {
  constructor(props, context) {
    super(props, context)

    this.state = {
      selectedAccount: null,
      web3: null,
      approvePermissions: null,
      render: null
    }

  }

  render() {
    const { web3UnavailableScreen: Web3UnavailableScreen } = this.props

    if (this.state.render && this.state.web3 && this.state.approvePermissions) {
      return this.props.children
    }

    if (!this.state.render && (!this.state.web3 || !this.state.approvePermissions)) {
      return <Loader show={true} />
    }

    if (this.state.render && (!this.state.web3 || !this.state.approvePermissions)) {
      return <Web3UnavailableScreen />
    }

    return null
  }

  componentDidMount() {
    this.checkWeb3()
      .then(this.initPoll())
      .then(() => {
        this.setState({
          render: true
        })
      })
      .catch(err => {
        console.log(err)
        this.setState({
          render: true
        })
      })
  }

  checkWeb3() {
    const setWeb3 = () => {
      try {
        window.web3 = new Web3(window.web3.currentProvider)
        this.setState({
          approvePermissions: true,
          web3: window.web3
        })
      } catch (err) {
        console.log('There was a problem fetching accounts', err)
      }
    }

    return new Promise((resolve, reject) => {
      const { ethereum } = window

      // Modern dapp browsers...
      if (ethereum) {
        window.web3 = new Web3(ethereum)
          // Request account access if needed
        ethereum.enable().then(() => {
          if (!this.state.web3) {
            setWeb3()
          }
        }).catch(err => {
          this.setState({
            approvePermissions: false
          })
          reject()
        })
        resolve()
      }
        // Legacy dapp browsers...
      else if (window.web3) {
        setWeb3()
        resolve()
      }
        // Non-dapp browsers...
      else {
        this.setState({
          approvePermissions: false
        })
        reject()
      }
    })
  }

  componentWillUnmount() {
    clearInterval(this.interval)
  }

  initPoll = () => {
    if (!this.interval) {
      this.interval = setInterval(this.fetchAccounts, ONE_SECOND)
    }
  }

  fetchAccounts = () => {
    const { web3  } = this.state
    const { onChangeAccount } = this.props

    if (!web3 || !web3.eth) {
      return
    }

    return web3.eth.getAccounts()
      .then(accounts => {
        if (!accounts || !accounts.length) {
          return
        }

        let curr = this.state.selectedAccount
        let next = accounts[0]
        curr = curr && curr.toLowerCase()
        next = next && next.toLowerCase()

        const didChange = curr && next && (curr !== next)

        if (didChange && typeof onChangeAccount === 'function') {
          onChangeAccount(next)
        }

        this.setState({
          selectedAccount: next || null
        })
      })
      .catch( err => console.log(err))
  }

  getChildContext() {
    return {
      web3: this.state.web3,
      selectedAccount: this.state.selectedAccount
    }
  }
}

Web3Provider.childContextTypes = {
  web3: PropTypes.object,
  selectedAccount: PropTypes.string
}

export default Web3Provider;
<|endoftext|>


<commit_before>import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
const DockMonitorD = DockMonitor.default // 这里有 bug 不知道为啥非要使用 default

export default createDevTools(
  <DockMonitorD toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q">
    <LogMonitor.default />
  </DockMonitorD>
);
<commit_msg>opti: redux-devtools 默认关闭<commit_after>import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
const DockMonitorD = DockMonitor.default // 这里有 bug 不知道为啥非要使用 default

export default createDevTools(
  <DockMonitorD
    toggleVisibilityKey="ctrl-h"
    changePositionKey="ctrl-q"
    defaultIsVisible={false}
  >
    <LogMonitor.default />
  </DockMonitorD>
);
<|endoftext|>


<commit_before>export default Ember.Mixin.create({
    defaultCapabilities: {
        admin: [
            'User Administrator',
            'System Administrator'
        ],
        appointments: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_appointment: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_diagnosis: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        add_medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        add_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_patient: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_lab: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Lab Technician',
            'System Administrator'
        ],
        add_imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_request: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        add_inventory_item: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_purchase: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_invoice: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_procedure: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        add_user: [
            'User Administrator',
            'System Administrator'
        ],
        add_visit: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        add_vitals: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        adjust_inventory_location: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        complete_imaging: [
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        complete_lab: [
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_appointment: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_diagnosis: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_inventory_item: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_inventory_purchase: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_imaging: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_lab: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_medication: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_patient: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_procedure: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        delete_vitals: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        delete_visit: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        delete_user: [
            'User Administrator',
            'System Administrator'
        ],
        fulfill_inventory: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        fulfill_medication: [
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        labs: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        inventory: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        patients: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        visits: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse Manager',
            'Nurse',
            'Patient Administration',
            'System Administrator'
        ],
        update_config: [
            'System Administrator'
        ],
        users: [
            'User Administrator',
            'System Administrator'
        ]

    },

    _getUserSessionVars: function() {
        var session = this.get('session');
        if (!Ember.isEmpty(session) && session.isAuthenticated) {
            var sessionVars = session.store.restore();
            return sessionVars;
        }
    },

    currentUserCan: function(capability) {
        var sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars) && !Ember.isEmpty(sessionVars.role)) {
            var capabilities = this.get('defaultCapabilities'),
                supportedRoles = capabilities[capability];
            if (!Ember.isEmpty(supportedRoles)) {
                return supportedRoles.contains(sessionVars.role);
            }
        }
        return false;
    },

    /**
     * Returns the display name of the user or the username if
     * the display name is not set or if the username is explictly requested.
     * @param {boolean} returnUserName if true, always return the username instead
     * of the display name even if the display name is set.
     */
    getUserName: function(returnUserName) {
        var returnName,
            sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars)) {
            if (returnUserName) {
                returnName = sessionVars.name;
            } else if (!Ember.isEmpty(sessionVars.displayName)) {
                returnName = sessionVars.displayName;
            } else if (!Ember.isEmpty(sessionVars.name)) {
                returnName = sessionVars.name;
            }
        }
        return returnName;
    }
});<commit_msg>Added social work permissions<commit_after>export default Ember.Mixin.create({
    defaultCapabilities: {
        admin: [
            'User Administrator',
            'System Administrator'
        ],
        appointments: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_appointment: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_diagnosis: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        add_medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        add_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_patient: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_lab: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Lab Technician',
            'System Administrator'
        ],
        add_imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_request: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        add_inventory_item: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_purchase: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_invoice: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_procedure: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        add_socialwork: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_user: [
            'User Administrator',
            'System Administrator'
        ],
        add_visit: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        add_vitals: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        adjust_inventory_location: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        complete_imaging: [
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        complete_lab: [
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_appointment: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_diagnosis: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_inventory_item: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_inventory_purchase: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_imaging: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_lab: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_medication: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_patient: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_procedure: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        delete_socialwork: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_vitals: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        delete_visit: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        delete_user: [
            'User Administrator',
            'System Administrator'
        ],
        fulfill_inventory: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        fulfill_medication: [
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        labs: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        inventory: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        patients: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        visits: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse Manager',
            'Nurse',
            'Patient Administration',
            'System Administrator'
        ],
        update_config: [
            'System Administrator'
        ],
        users: [
            'User Administrator',
            'System Administrator'
        ]

    },

    _getUserSessionVars: function() {
        var session = this.get('session');
        if (!Ember.isEmpty(session) && session.isAuthenticated) {
            var sessionVars = session.store.restore();
            return sessionVars;
        }
    },

    currentUserCan: function(capability) {
        var sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars) && !Ember.isEmpty(sessionVars.role)) {
            var capabilities = this.get('defaultCapabilities'),
                supportedRoles = capabilities[capability];
            if (!Ember.isEmpty(supportedRoles)) {
                return supportedRoles.contains(sessionVars.role);
            }
        }
        return false;
    },

    /**
     * Returns the display name of the user or the username if
     * the display name is not set or if the username is explictly requested.
     * @param {boolean} returnUserName if true, always return the username instead
     * of the display name even if the display name is set.
     */
    getUserName: function(returnUserName) {
        var returnName,
            sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars)) {
            if (returnUserName) {
                returnName = sessionVars.name;
            } else if (!Ember.isEmpty(sessionVars.displayName)) {
                returnName = sessionVars.displayName;
            } else if (!Ember.isEmpty(sessionVars.name)) {
                returnName = sessionVars.name;
            }
        }
        return returnName;
    }
});<|endoftext|>


<commit_before>var
	bookshelf = require('../../config/bookshelf'),
	stringService = require('../services/stringService'),
	modelRegistry = require('../services/modelRegistry');

var ActionTarget = module.exports = bookshelf.Model.extend({
	tableName: 'action_targets',
	hasTimestamps: true,

	validations: {
		name: [ 'required', 'minLength:3', 'unique:action_targets:[name, action_target_template_id, organization_id]:Name is already taken for this action target template and this organization.' ]
	},

	constructor: function() {
		bookshelf.Model.apply(this, arguments);

		this.on('creating', function(model, attrs, options) {
			if (!model.get('generatedIdentifier')) {
				model.set('generatedIdentifier', stringService.generateId());
			}
		});
	},

	generatedId: function() {
		return this.get('generatedIdentifier');
	},

	organization: function() {
		return this.belongsTo(modelRegistry.organization);
	},

	actionTargetTemplate: function() {
		return this.belongsTo(modelRegistry.actionTargetTemplate);
	}
});<commit_msg>Added event listeners to update the reference count of organizations<commit_after>var
	bookshelf = require('../../config/bookshelf'),
	stringService = require('../services/stringService'),
	modelRegistry = require('../services/modelRegistry');

var ActionTarget = module.exports = bookshelf.Model.extend({
	tableName: 'action_targets',
	hasTimestamps: true,

	validations: {
		name: [ 'required', 'minLength:3', 'unique:action_targets:[name, action_target_template_id, organization_id]:Name is already taken for this action target template and this organization.' ]
	},

	constructor: function() {
		bookshelf.Model.apply(this, arguments);

		this.on('creating', function(model, attrs, options) {
			if (!model.get('generatedIdentifier')) {
				model.set('generatedIdentifier', stringService.generateId());
			}
		});

	},

	generatedId: function() {
		return this.get('generatedIdentifier');
	},

	organization: function() {
		return this.belongsTo(modelRegistry.organization);
	},

	actionTargetTemplate: function() {
		return this.belongsTo(modelRegistry.actionTargetTemplate);
	}
});<|endoftext|>