text:
_GraphRing = function(){
	var _graphRing = {};
	// data
	graphData = {}, arcData = [], arcDataWithPos = [];
	//place
	var divId, isG = false, gId, graphG, arcG;
	//size
	var viewWidth, viewHeight, graphWidth, graphHeight, nodeSize = 5, isNodeSizeNum = true, nodeScaleFunc, innerRadius, outerRadius, arcSize, arcGap = 5, startAngle = 0, endAngle = 2 * Math.PI, piePadAngle = 2/180 * Math.PI;
	// var innerRadiusScale;
	//color for the node and the arc
	var arcColorMap, colorMapArr = [d3.scale.category20c(), d3.scale.category20b(), d3.scale.category20()];
	//basic configuration
	var bindEventFlag = true;
	// force
	var force = d3.layout.force();
	//parameter for force layout
	var charge = -30, linkDistance = 20, gravity = 0.1, linkStrength = 0.1;
	var selectedNodeArr = [], brushSelectedNodeArr = [], clickSelectedArcVal = {}, selectedArcVal = {};

	// Set graph data. The data format is {'nodes':[], 'links':[]}
	_graphRing._setGraphData = function(_data) {
		graphData = _data;
		return _graphRing;
	};

	// Set arc data. The data format is [{'name':, 'data':[{'name':, 'val':}, {}]}, {}]
	_graphRing._setArcData = function(_data){
		arcData = _data;
		return _graphRing;
	};

	// Set the svg place. The data should be an id of a div
	_graphRing._setDivId = function(_divId){
		divId = _divId;
		isG = false;
		return _graphRing;
	};

	// Set the g for drawing graph ring. The data should be an id of a g
	_graphRing._setG = function(_gId){
		gId = _gId;
		isG = true;
		return _graphRing;
	};

	// Set the size of the view. The input data should be a array. The first data is the size of width, another one is the size of height
	_graphRing._setViewSize = function(_sizeArr){
		viewWidth = _sizeArr[0];
		viewHeight = _sizeArr[1];
		return _graphRing;
	};

	//Set linkStrength. The data can be a number or a function
	_graphRing._setLinkStrength = function(_linkStrength){
		linkStrength = _linkStrength;
		return _graphRing;
	};

	//Set charge. The data can be a number or a function
	_graphRing._setCharge = function(_charge){
		charge = _charge;
		return _graphRing;
	};

	//Set linkDistance. The data can be a number or a function
	_graphRing._setLinkDistance = function(_linkDistance){
		linkDistance = _linkDistance;
		return _graphRing;
	};

	//Set gravity. The data can be a number or a function
	_graphRing._setGravity = function(_gravity){
		gravity = _gravity;
		return _graphRing;
	};

	//Get alpha
	_graphRing._getAlpha = function(){
		return force.alpha();
	};

	// Bind the event or not. The input data should be a bool
	_graphRing._bindEvent = function(_flag){

	};

	//Set the node size. The data can be a function or just a number
	_graphRing._setNodeSize = function(_nodeSize){
		if(isFinite(_nodeSize))
		{
			isNodeSizeNum = true;
		}
		else
		{
			isNodeSizeNum = false;
		}
		nodeSize = _nodeSize;
		return _graphRing;
	};

	//Set the innerRadius of arcs. The data should be a number
	_graphRing._setArcInnerRadius = function(_innerRadius){
		innerRadius = _innerRadius;
		return _graphRing;
	};

	//Set the outerRadius of arcs. The data should be a number
	_graphRing._setArcOuterRadius = function(_outerRadius){
		outerRadius = _outerRadius;
		return _graphRing;
	};

	//Set the gap between arc. The data should a number
	_graphRing._setArcGap = function(_arcGap){
		arcGap = _arcGap;
		return _graphRing;
	};

	//Set startAngle. The data should be in radian
	_graphRing._setStartAngle = function(_startAngle){
		startAngle = _startAngle;
		return _graphRing;
	};

	// Set endAngele. The data should be in radian
	_graphRing._setEndAngle = function(_endAngle){
		endAngle = _endAngle;
		return _graphRing;
	};

	//Set pie pad angle. The data should be in radian
	_graphRing._setPiePadAngle = function(_padAngle){
		piePadAngle = _padAngle;
		return _graphRing;
	};

	//Set the data to highlight. The data format is [nodeId, nodeId, ...]
	_graphRing._setNodeToHighlight = function(_data){
		brushSelectedNodeArr = [];
		var obj = {};
		_data.forEach(function(d_nodeId, i_nodeId){
			obj[d_nodeId] = 1;
		});
		graphData.nodes.forEach(function(d_node, i_node){
			if(obj[d_node.id] !== undefined)
			{
				brushSelectedNodeArr.push(d_node);
			}
		});
		dealWithSelectedData();
	};

	//Get the data which is highlight now. The data format is [nodeId, nodeId, ...]
	_graphRing._getNodeInHighlight = function(){
		return selectedNodeArr;
	};

	// Start to calculate the graph layout, draw the view
	_graphRing._start = function(){
		calElementPos();
		setViewPlace();
		drawView();
		addEvent();
		return _graphRing;
	};

	// forceStart used to recalculate the graph layout
	_graphRing._forceStart = function(){
		drawNodeLink();
		return _graphRing;
	};

	// Stop the calculation of graph layout
	_graphRing._stop = function(){
		force.stop();
		return _graphRing;
	};

	// Functions in the package

	function calElementPos(){
		calSize();
		calPie();
		calGraph();
	}

	function drawView(){
		drawNodeLink();
		drawArc();
	}

	//cal size
	function calSize (){
		if(viewWidth === undefined || viewHeight === undefined)
		{
			if(isG === false)
			{
				viewWidth = $('#' + divId).width();
				viewHeight = $('#' + divId).height();
			}
			else
			{
				viewWidth = 600;
				viewHeight = 600;
			}
		}

		viewWidth = d3.min([viewWidth, viewHeight]);
		viewHeight = viewWidth;

		if(innerRadius === undefined || outerRadius === undefined)
		{
			if(arcSize === undefined)
			{
				arcSize = 10;
			}
			outerRadius = viewWidth/2 - arcSize;
			innerRadius = outerRadius - arcSize - (arcData.length - 1) *(arcSize + arcGap);
		}

		window.innerRadiusScale = d3.scale.linear().domain([0, arcData.length - 1]).range([innerRadius, outerRadius - arcSize ]);
		arcData.forEach(function(d_arc, i_arc){
			d_arc.innerRadius = innerRadiusScale(i_arc);
			d_arc.outerRadius = d_arc.innerRadius + arcSize;
			d_arc.startAngle = startAngle;
			d_arc.endAngle = endAngle;
			d_arc.padAngle = piePadAngle;
		});

		graphWidth = innerRadius - 5;
		graphHeight = innerRadius - 5;
	}

	function setViewPlace (){
		if(isG === false)
		{
			//remove existing svg
			d3.select('#' + divId + ' svg').remove();
			d3.select('#' + divId).append('svg').attr('width', viewWidth).attr('height', viewHeight).append('g').attr('id', 'graphRingG').attr('class', 'graphRingG');
			gId = 'graphRingG';
		}

		var graphLeft = viewWidth/2, graphTop = viewHeight/2;

		graphG = d3.select('#' + gId).append('g').attr('id', 'graphG')
				   .attr('transform', 'translate(' + graphLeft + ',' + graphTop + ')');
		arcG = d3.select('#' + gId).append('g').attr('id', 'arcG')
		         .attr('transform', 'translate(' + graphLeft + ',' + graphTop + ')');
	}

	function calPie (){
		arcDataWithPos = [];
		arcData.forEach(function(d_arcData, i_arcData){
			var pie = d3.layout.pie().padAngle(d_arcData.padAngle)
						.startAngle(d_arcData.startAngle).endAngle(d_arcData.endAngle)
						.value(function(d){ return d.val;});
			var dataWithPos = pie(d_arcData.data);
			var obj = {};
			obj.name = d_arcData.name;
			obj.data = dataWithPos;
			obj.innerRadius = d_arcData.innerRadius;
			obj.outerRadius = d_arcData.outerRadius;
			obj.startAngle = d_arcData.startAngle;
			obj.endAngle = d_arcData.endAngle;
			obj.padAngle = d_arcData.padAngle;
			arcDataWithPos.push(obj);
		});
	}

	function calGraph (){
		var innerArcWithPos = arcDataWithPos[0].data;
		addVirtualNodeAndLink(innerArcWithPos, graphData);
	}

	function addVirtualNodeAndLink (innerArcWithPos, graphData){
		var self = this;
		var nodes = graphData.nodes;
		var links = graphData.links;
		var virtualNodeIndexObj = {};
		//set center virtual node
		var obj = {};
		obj.id = 'centerVirtual';
		obj.type = 'virtual';
		nodes.push(obj);
		virtualNodeIndexObj.centerVirtual = nodes.length - 1;
		// set virtual links between nodes and virtual center node
		for(var i = 0; i<nodes.length - 2; i++)
		{
			obj = {};
			obj.source = virtualNodeIndexObj.centerVirtual;
			obj.target = i;
			obj.type = 'virtual';
			links.push(obj);
		}

		// add virtual nodes for innerArc
		innerArcWithPos.forEach(function(d_data, i_data){
			var angle = (d_data.endAngle - d_data.startAngle)/2 + d_data.startAngle;
			var obj = {};
			obj.id = d_data.data.name;
			obj.type = 'virtual';
			obj.x = innerRadius * Math.sin(angle);
			obj.y = -innerRadius * Math.cos(angle);
			obj.cx = obj.x;
			obj.cy = obj.y;
			obj.fixed = true;
			nodes.push(obj);
			virtualNodeIndexObj[d_data.data.name] = nodes.length - 1;
		});
		// add virtual links
		nodes.forEach(function(d_node, i_node){
			var innerArcName = arcData[0].name;
			if(d_node.type === 'virtual' || d_node[innerArcName] === undefined) return;
			var obj = {};
			obj.source = virtualNodeIndexObj[d_node[innerArcName]];
			obj.target = i_node;
			obj.type = 'virtual';
			links.push(obj);
		});
	}

	function drawNodeLink(){
		var graphView = graphG;
		if(graphView.select('#linkG')[0][0] === null) graphView.append('g').attr('id', 'linkG');
		if(graphView.select('#nodeG')[0][0] === null) graphView.append('g').attr('id', 'nodeG');
		var linkView = graphView.select('#linkG'), nodeView = graphView.select('#nodeG');
		var linkData = graphData.links;
		var nodeData = graphData.nodes;

		force.nodes(nodeData).links(linkData).charge(charge).linkDistance(linkDistance).linkStrength(linkStrength).gravity(gravity);
		force.start();

		//draw link
		var link = linkView.selectAll('.graphLinkInGraphRing').data(linkData);
		//enter
		var newLink = link.enter().append('path');
		//update
		link.attr('class', function(d, i){
			if(d.type === undefined || d.type !== 'virtual')
			{
				return 'graphLinkInGraphRing ' + d.source.id + ' ' + d.target.id;
			}
			return 'virtualLinkInGraphRing';
		})
		.attr('d', function(d, i){
			return 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y;
		});
		//exit
		link.exit().remove();

		//draw node
		var node = nodeView.selectAll('.graphNodeInGraphRing').data(nodeData);
		//enter
		var newNode = node.enter().append('circle');
		//update
		node.attr('class', function(d, i){
			if(d.type === undefined || d.type !== 'virtual')
			{
				return 'graphNodeInGraphRing ' + d.id + 'InGraphRing';
			}
			return 'virtualNodeInGraphRing';
		}).attr('index', function(d, i){ return i;})
		.attr('r', nodeSize).attr('cx', function(d, i){ return d.x;}).attr('cy', function(d, i){ return d.y;});
		//exit
		node.exit().remove();

		//graph update
		force.on('tick', function(){
			if(force.alpha() < 0.01)
			{
				force.stop();
			}
			if(force.alpha() < 0.02)
			{
				reCalNodePosFromOut();
			}
			if(force.alpha() < 0.07)
			{
				updateNodeAndLinkPos();
			}
		});

		function updateNodeAndLinkPos (){
			link.attr('d', function(d, i){
				return 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y;
			});
			node.attr('cx', function(d, i){ return d.x;}).attr('cy', function(d, i){ return d.y;});
		}

		function reCalNodePosFromOut(){
			var width = graphWidth, height = graphHeight;
			var nodeData = graphData.nodes;
			var linkData = graphData.links;
			var maxDis = width, radio;
			nodeData.forEach(function(d, i){
				if(d.type !== undefined && d.type === 'virtual') return;
				var dis = Math.sqrt(d.x * d.x + d.y * d.y);
				if(dis > maxDis) maxDis = dis;
			});
			if(maxDis <= width) return;
			radio = (width/maxDis);
			nodeData.forEach(function(d, i){
				if(d.type !== undefined && d.type === 'virtual') return;
				d.x = d.x * radio;
				d.y = d.y * radio;
				d.cx = d.cx * radio;
				d.cy = d.cy * radio;
			});
		}
	}

	function drawArc(){
		var ringData = arcDataWithPos;
		var arcView = arcG;
		//remove all exist arcG
		arcView.selectAll('.ringGInGraphRing').style('opacity', 1).transition().style('opacity', 0).remove();

		ringData.forEach(function(d_ring, i_ring){
			var arc = d3.svg.arc().outerRadius(d_ring.outerRadius).innerRadius(d_ring.innerRadius);
			var arcName = d_ring.name;
			var pieView = arcView.append('g').attr('id', arcName + 'RingGInGraphRing').attr('class', 'ringGInGraphRing').attr('name', arcName);
			var pieG = pieView.selectAll('.pieGInGraphRing').data(d_ring.data);
			//enter
			var newPie = pieG.enter().append('g');
			//update
			pieG.attr('class', function(d, i){ return d.data.name + 'PieGInGraphRing pieGInGraphRing'})
				.attr('value', function(d, i) { return d.data.val;})
				.attr('name', function(d, i){ return d.data.name;})
				.attr('color', function(d, i){ return colorMapArr[Math.floor(i_ring/colorMapArr.length)](d.data.name);})
				.attr('innerRadius', d_ring.innerRadius)
				.attr('outerRadius', d_ring.outerRadius)
				.attr('startAngle', function(d, i){ return d.startAngle;})
				.attr('endAngle', function(d, i){ return d.endAngle;});
			var newPiePath = newPie.append('path').attr('class', function(d, i){ return 'piePathInGraphRing ' + d.data.name + 'PiePathInGraphRing';});
			pieG.selectAll('.piePathInGraphRing').attr('d', arc).attr('id', function(d, i){ return d.data.name + 'PiePathInGraphRing';})
				.style('fill', function(d, i){
					return colorMapArr[Math.floor(i_ring/colorMapArr.length)](d.data.name);})
				.attr('class', function(d, i){ return 'piePathInGraphRing ' + d.data.name + 'PiePathInGraphRing';});

			var newSmallPiePath = newPie.append('path').attr('class', function(d, i){ return 'smallPiePathInGraphRing ' + d.data.name + 'SmallPiePathInGraphRing';});
			pieG.selectAll('.smallPieInGraphRing').attr('d', arc)
				.style('fill', function(d, i){ return colorMapArr[Math.floor(i_ring/colorMapArr.length)](d.data.name); })
				.attr('class', function(d, i){ return 'smallPiePathInGraphRing ' + d.data.name + 'SmallPiePathInGraphRing';});

			// add text
			var textG = newPie.append('text').attr('class', 'pieTextInGraphRing').attr('x', 6).attr('dy', 10);
			textG.append('textPath').attr('xlink:href', function(d, i){return '#' + d.data.name + 'PiePathInGraphRing';})
				 .text(function(d, i){ return d.data.name;});
			pieG.selectAll('textPath').attr('xlink:href', function(d, i){ return '#' + d.data.name + 'PiePathInGraphRing';})
				.text(function(d, i){ return d.data.name;});
			//remove the labels that don`t fit
			var pieText = d3.selectAll('.pieTextInGraphRing');
			var piePath = d3.selectAll('.piePathInGraphRing');
			pieText.filter(function(d, i){
				return piePath[0][i].getTotalLength()/2 - 40 < this.getComputedTextLength();
			})
			.select('textPath')
			.text(function(d, i){
				var name = d.data.name;
				if(name.length < 5) return name;
				else
					return name.substr(0, 5) + "...";
			});
			pieText.filter(function(d, i){ return piePath[0][i].getTotalLength() / 2 - 30 < this.getComputedTextLength();})
				   .remove();
			// move the text in the middle
			pieText.filter(function(d, i){ return piePath[0][i].getTotalLength()/2 - 10 > this.getComputedTextLength();})
			       .attr('x', function(d, i){ return (piePath[0][i].getTotalLength()/2 - 10 - this.getComputedTextLength())/2;});
			//exit
			pieG.exit().remove();
		});
	}

	function addEvent(){
		//init
		if(selectedNodeArr.length === 0) selectedNodeArr = graphData.nodes;

		hoverNodeEvent();
		hoverPieEvent();
		brushNodeEvent();
		clickPieEvent();
	}

	function hoverNodeEvent(){
		var tip = d3.tip().attr("class", "d3-tip-inGraphRing").offset([-10, 0]).html(function(d){return d;});
		var graphView = graphG;
		graphView.selectAll('.graphNodeInGraphRing').call(tip)
				 .on('mouseover', function(d, i) { var textInTip = d.id; tip.show(textInTip);}).on('mouseout', function(){ tip.hide();});
	}

	function hoverPieEvent(){
		var tip = d3.tip().attr('class', 'd3-tip-inGraphRing').offset([0, 0]).html(function(d){ return d;});
		var arcView = arcG;
		arcView.selectAll('.ringGInGraphRing .pieGInGraphRing').call(tip)
		       .on('mouseover', function(d, i){ var textInTip = d.data.name; tip.show(textInTip);}).on('mouseout', function(){ tip.hide();});
	}

	function brushNodeEvent(){
		var graphView = graphG;
		var graphNodeG = graphView.select("#nodeG");
		var node = graphView.selectAll('.graphNodeInGraphRing');
		var shiftKey;
            d3.select('body')
                .on("keydown.brush", keyflip)
                .on("keyup.brush", keyflip)
                .each(function() { this.focus(); });
            node.on("mousedown", function(d) {
                if (shiftKey) d3.select(this).classed("brushSelectedInGraphRing", d.selected = !d.selected);
                else node.classed("brushSelectedInGraphRing", function(p) { return p.selected = d === p; });
              });

        var brush = graphNodeG
                        .datum(function() { return {brushSelectedInGraphRing: false, previouslySelected: false}; })
                        .attr("class", "brushNodeInGraphRing")
                        .call(d3.svg.brush()
                            .x(d3.scale.identity().domain([-(graphWidth - 25), (graphWidth - 25)]))
                            .y(d3.scale.identity().domain([-(graphWidth - 25), (graphWidth - 25)]))
                            .on("brushstart", function(d) {
                              node.each(function(d) { d.previouslySelected = shiftKey && d.selected; });
                            })
                        .on("brush", function() {
                              var extent = d3.event.target.extent();
                              node.classed("brushSelectedInGraphRing", function(d) {
                                return d.selected = d.previouslySelected ^
                                    (extent[0][0] <= d.x && d.x < extent[1][0]
                                    && extent[0][1] <= d.y && d.y < extent[1][1]);
                              });

                              node.classed('unselected', function(d){
                                 return !d3.select(this).classed('brushSelectedInGraphRing');
                              })
                            })
                        .on("brushend", function() {
                                d3.event.target.clear();
                                d3.select(this).call(d3.event.target);
                                dealWithBrush();
                            }));

        function keyflip()
        {
          shiftKey = d3.event.shiftKey || d3.event.metaKey;
        }
	}

	function clickPieEvent(){
		var arcView = arcG;
		arcView.selectAll('.pieGInGraphRing').on('click', function(d, i){
			var parentNode = d3.select(this.parentNode);
			var arcName = parentNode.attr('name');
			var pieName = d3.select(this).attr('name');
			var status = d3.select(this).classed('clickSelectedInGraphRing');
			var index;
			if(clickSelectedArcVal[arcName] === undefined) clickSelectedArcVal[arcName] = [];
			if(status === false)
			{
				d3.select(this).classed('clickSelectedInGraphRing', true);
				clickSelectedArcVal[arcName].push(pieName);
			}
			else
			{
				index = clickSelectedArcVal[arcName].indexOf(pieName);
				if(index !== -1)
				{
					clickSelectedArcVal[arcName].splice(index, 1);
					d3.select(this).classed('clickSelectedInGraphRing', false);
				}
			}
			dealWithSelectedData();
		});
	}

	function dealWithBrush(){
		brushSelectedNodeArr = [];
		brushSelectedNodeArr = getNameWithSpecificClassName('graphNodeInGraphRing', 'brushSelectedInGraphRing');
		dealWithSelectedData();

		function getNameWithSpecificClassName(basicElementName, className)
		{
			var nodeArr = graphData.nodes;
		    var node = d3.selectAll('.' + basicElementName);
		    var selectedNode = node.filter(function(d){
		                                var status = d3.select(this).classed(className);
		                                return status;
		                            });

		    var resultArr = [];
		    selectedNode.each(function(d){
		    	var index = d3.select(this).attr('index');
		    	index = (+index);
		        return resultArr.push(nodeArr[index]);
		    });
		    return resultArr;
		}
	}

	function dealWithSelectedData (){
		console.log('hello~~~and');
		andOperate();
		updateSelectedNode();
		updateSelectedArc();
	}

	function andOperate() {
		var allArcData = arcDataWithPos;
		var basicArc = clickSelectedArcVal;
		if(brushSelectedNodeArr.length === 0) brushSelectedNodeArr = graphData.nodes;
		var basicNode = brushSelectedNodeArr;
		selectedNodeArr = [], selectedArcVal = {};

		var basicArcName = Object.keys(basicArc);
		basicNode.forEach(function(d_node, i_node){
			var isSelectedFlag = true;
			var index;
			for(var i = 0; i< basicArcName.length; i++)
			{
				if(basicArc[basicArcName[i]] === undefined || basicArc[basicArcName[i]].length === 0) continue;
				if(d_node[basicArcName[i]] === undefined)
				{
					isSelectedFlag = false;
					break;
				}
				else
				{
					index = basicArc[basicArcName[i]].indexOf(d_node[basicArcName[i]]);
					if(index === -1)
					{
						isSelectedFlag = false;
						break;
					}
				}
			}
			if(isSelectedFlag === true)
			{
				selectedNodeArr.push(d_node);
			}
		});

		selectedNodeArr.forEach(function(d_node, i_node){
			var name;
			for(var i = 0; i< allArcData.length; i++)
			{
				name = allArcData[i].name;
				if(d_node[name] === undefined) continue;
				if(selectedArcVal[d_node[name]] === undefined) selectedArcVal[d_node[name]] = 0;
				selectedArcVal[d_node[name]] += 1;
			}
		});
		window.testNodeArr = selectedNodeArr;
		window.testArcVal = selectedArcVal;
	}

	function updateSelectedNode(){
		var data = selectedNodeArr;
		var graphView = graphG;
		graphView.selectAll('.graphNodeInGraphRing').classed('selected', false).classed('unselected', true);
		data.forEach(function(d_data, i_data){
			var id = d_data.id;
			graphView.select('.' + id + 'InGraphRing').classed('selected', true).classed('unselected', false);
		});
	}

	function updateSelectedArc() {
		var arcView = arcG;
		var selectedArcNameArr = Object.keys(selectedArcVal);
		window.testArcView = arcView;
		arcView.selectAll('.pieGInGraphRing').classed('selected', false).classed('unselected', true);
		selectedArcNameArr.forEach(function(d_arc, i_arc){
			arcView.select('.' + d_arc + 'PieGInGraphRing').classed('selected', true).classed('unselected', false);
			//add selected arc
			if(selectedArcVal[d_arc] !== undefined)
			{
				addSmallArc(arcView.select('.' + d_arc + 'PieGInGraphRing'), selectedArcVal[d_arc]);
			}
		});
	}

	function addSmallArc(place, val){
		var wholeVal = place.attr('value');
			wholeVal = (+wholeVal);
		var startAngle = place.attr('startAngle'), endAngle = place.attr('endAngle');
		    startAngle = (+startAngle);
		    endAngle = (+endAngle);
		var innerRadius = place.attr('innerRadius'), outerRadius = place.attr('outerRadius');
		var color = place.attr('color');
		var start = startAngle, end = (endAngle - startAngle) * (val/wholeVal) + startAngle;
		var arc = d3.svg.arc().outerRadius(outerRadius).innerRadius(innerRadius).startAngle(start).endAngle(end);
		place.select('.smallPiePathInGraphRing').attr('d', arc).style('fill', color);
	}

	function resetNodeStatus(){
		var graphView = graphG;
		selectedNodeArr = [];
		graphView.selectAll('.graphNodeInGraphRing').classed('selected', false).classed('unselected', false);
	}
	return _graphRing;
};


text:
$(function() {
    $('.date').datepicker({ dateFormat: 'dd-mm-yy' });
    $("a.confirmDialog").click(function(e) {
        e.preventDefault();
        urlDelete = $(this).attr('href')
        bootbox.confirm("Are you sure ?", function(confirmed) {
            if (confirmed == true) {
                window.location = urlDelete;
            }
        });
    });

    $('textarea.wysiwyg').css('height','300px').css('width', '350px');
    $('textarea.wysiwyg').wysiwyg({
        rmUnusedControls: true,
        rmUnwantedBr: true,
        controls: {
            bold: { visible : true },
            italic: { visible : true },
            h1: { visible : true },
            h2: { visible : true },
            h3: { visible : true },
            html: { visible : true },
            insertOrderedList: { visible : true },
            removeFormat: { visible : true }
        }
    });

});

redpajama_set_name: RedPajamaGithub


text:
<?php

prado::using ('System.Web.UI.ActiveControls.*');

class Ticket691 extends TPage
{
	public function list_oncallback ($sender, $param)
	{
		$sender->Rating=$sender->SelectedIndex+1;
		$this->Result->Text="You vote ".$sender->Rating;
	}
}


text:
@protocol NNScrollerViewDelegate <NSObject>

@optional

- (void)NNScrollerViewDidClicked:(NSUInteger)index;

@end

@interface NNScrollerView : UIView <UIScrollViewDelegate> {
    CGRect viewSize;
    UIScrollView *scrollView;
    NSArray *imageArray;
    NSMutableArray *linkArray;
    UIPageControl *pageControl;
    NSInteger currentPageIndex;
    UILabel *noteTitle;
}

@property(nonatomic, weak)    id <NNScrollerViewDelegate> delegate;
@property(nonatomic, strong)  NSArray *showArray;

-(instancetype)initWithFrameRect:(CGRect)rect scrolArray:(NSArray *)array needTitile:(BOOL)isNeedTitle;

@end


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>

  <!-- ResourceManager security configs -->
  <property>
    <name>yarn.resourcemanager.keytab</name>
    <value>/etc/hadoop/conf/yarn.keytab</value> <!-- path to the YARN keytab -->
  </property>
  <property>
    <name>yarn.resourcemanager.principal</name>
    <value>yarn/localhost@EXAMPLE.COM</value>
  </property>

  <!-- NodeManager security configs -->
  <property>
    <name>yarn.nodemanager.keytab</name>
    <value>/etc/hadoop/conf/yarn.keytab</value> <!-- path to the YARN keytab -->
  </property>
  <property>
    <name>yarn.nodemanager.principal</name>
    <value>yarn/localhost@EXAMPLE.COM</value>
  </property>
  <property>
    <name>yarn.nodemanager.container-executor.class</name>
    <value>org.apache.hadoop.yarn.server.nodemanager.LinuxContainerExecutor</value>
  </property>
  <property>
    <name>yarn.nodemanager.linux-container-executor.group</name>
    <value>yarn</value>
  </property>

  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>

  <property>
    <name>yarn.nodemanager.aux-services.mapreduce_shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
  </property>

  <property>
    <name>yarn.log-aggregation-enable</name>
    <value>false</value>
  </property>

  <property>
    <name>yarn.dispatcher.exit-on-error</name>
    <value>true</value>
  </property>

  <property>
    <description>List of directories to store localized files in.</description>
    <name>yarn.nodemanager.local-dirs</name>
    <value>/var/lib/hadoop-yarn/cache/${user.name}/nm-local-dir</value>
  </property>

  <property>
    <description>Where to store container logs.</description>
    <name>yarn.nodemanager.log-dirs</name>
    <value>/var/log/hadoop-yarn/containers</value>
  </property>

  <property>
    <description>Where to aggregate logs to.</description>
    <name>yarn.nodemanager.remote-app-log-dir</name>
    <value>/var/log/hadoop-yarn/apps</value>
  </property>

  <property>
    <description>Classpath for typical applications.</description>
     <name>yarn.application.classpath</name>
     <value>
        $HADOOP_CONF_DIR,
        $HADOOP_COMMON_HOME/*,$HADOOP_COMMON_HOME/lib/*,
        $HADOOP_HDFS_HOME/*,$HADOOP_HDFS_HOME/lib/*,
        $HADOOP_MAPRED_HOME/*,$HADOOP_MAPRED_HOME/lib/*,
        $HADOOP_YARN_HOME/*,$HADOOP_YARN_HOME/lib/*
     </value>
  </property>

  <property>
    <name>yarn.linux-container-executor.path</name>
    <value>/usr/lib/hadoop-yarn/bin/container-executor</value>
  </property>

</configuration>


text:
require 'dm-core'
require 'dm-migrations'
require 'dm-types'
require 'sinatra/base'

class Domain
  include DataMapper::Resource
  property :id, Serial
  property :host, String, :index => true
  property :name, String
end

class OrgStats
  include DataMapper::Resource
  property :id, Serial
  property :organization_id, String
  property :data, Json
  property :updated_at, DateTime

  def self.check(org)
    stats = OrgStats.first_or_new(:organization_id => org && org.id)
    if !stats.updated_at || stats.updated_at < (DateTime.now - 1.0)
      res = {}
      if org
        res['issuers'] = ExternalConfig.all(:organization_id => org.id).count
        res['badge_configs'] = BadgeConfig.all(:configured => true, :organization_id => org.id).count
        res['badge_placement_configs'] = BadgePlacementConfig.all(BadgePlacementConfig.badge_config.organization_id => org.id).count
        res['badges'] = Badge.all(:state => 'awarded', Badge.badge_config.organization_id => org.id).count
        res['domains'] = Domain.count
        res['organizations'] = Organization.count
      else
        res['issuers'] = ExternalConfig.count
        res['badge_configs'] = BadgeConfig.all(:configured => true).count
        res['badge_placement_configs'] = BadgePlacementConfig.count
        res['badges'] = Badge.all(:state => 'awarded').count
        res['domains'] = Domain.count
        res['organizations'] = Organization.count
      end
      stats.data = res
      stats.updated_at = DateTime.now
      stats.save
    end
    stats.data
  end
end

class Organization
  include DataMapper::Resource
  property :id, Serial
  property :host, String, :index => true
  property :settings, Json

  def as_json
    host_with_port = self.host
    image = (settings && settings['image']) || "/organizations/default.png"
    if !image.match(/:\/\//)
      image = "#{BadgeHelper.protocol}://" + host_with_port + image
    end
    settings = self.settings || BadgeHelper.issuer
    {
      'name' => settings['name'],
      'url' => settings['url'],
      'description' => settings['description'],
      'image' => image,
      'email' => settings['email'],
      'revocationList' => "#{BadgeHelper.protocol}://#{host_with_port}/api/v1/organizations/#{self.id || 'default'}/revocations.json"
    }
  end

  def default?
    settings['default'] == true
  end

  def to_json
    as_json.to_json
  end

  def org_id
    "#{self.id}-#{self.settings['name'].downcase.gsub(/[^\w]+/, '-')[0, 30]}"
  end
end

class ExternalConfig
  include DataMapper::Resource
  property :id, Serial
  property :config_type, String
  property :app_name, String
  property :organization_id, Integer
  property :value, String
  property :shared_secret, String, :length => 256

  def self.generate(name)
    conf = ExternalConfig.first_or_new(:config_type => 'lti', :app_name => name)
    conf.value ||= Digest::MD5.hexdigest(Time.now.to_i.to_s + rand.to_s).to_s
    conf.shared_secret ||= Digest::MD5.hexdigest(Time.now.to_i.to_s + rand.to_s + conf.value)
    conf.save
    conf
  end
end

class UserConfig
  # NOTE: Right now the code assumes if a UserConfig exists then there is an access token attached.
  include DataMapper::Resource
  property :id, Serial
  property :user_id, String
  property :access_token, String, :length => 512
  property :domain_id, Integer
  property :name, String, :length => 256
  property :image, String, :length => 512
  property :global_user_id, String, :length => 256
  belongs_to :domain

  def host
    self.domain && self.domain.host
  end

  def profile_url
    if host
      "#{BadgeHelper.protocol}://" + host + "/users/" + self.user_id
    else
      "http://www.instructure.com"
    end
  end

  def check_badge_status(badge_placement_config, params, name, email,context_module_id)
    scores_json = CanvasAPI.api_call("/api/v1/courses/#{badge_placement_config.course_id}?include[]=total_scores", self)
    modules_json = CanvasAPI.api_call("/api/v1/courses/#{badge_placement_config.course_id}/modules", self, true) if badge_placement_config.modules_required?
    modules_json ||= []
    completed_module_ids = modules_json.select{|m| m['completed_at'] }.map{|m| m['id'] }.compact
    unless scores_json
      return "
Error getting data from Canvas
"
    end

    student = scores_json['enrollments'].detect{|e|  e['role'].downcase == 'studentenrollment' }
    student['computed_final_score'] ||= 0 if student

    @module_items = badge_placement_config.settings['module_items'] unless badge_placement_config.settings['module_items'].nil?

    if student

      if (@module_items || []).empty?
         #no module_item is add
         @module_item_completed = true
      end

      (@module_items || []).each do |module_item|
        module_item.each do |module_item_id, score|
          @module_item_id = module_item_id.to_i
          @module_item_score = score
          unless @module_item_id.nil?
            #get module_item
            @module_item_json = CanvasAPI.api_call("/api/v1/courses/#{badge_placement_config.course_id.to_i}/modules/#{context_module_id}/items/#{@module_item_id}", self)
            #for getting the assignment id
            if @module_item_json && @module_item_json['type'] == 'Quiz'
                course_assignments = CanvasAPI.api_call("/api/v1/courses/#{badge_placement_config.course_id.to_i}/assignments", self)
                course_assignments.each do |assignment|
                  quiz_id = assignment['quiz_id']
                  unless quiz_id.nil?
                    if quiz_id == @module_item_json['content_id']
                      @assignment = assignment
                    end
                  end
                end
                unless @assignment.nil?
                  submission = CanvasAPI.api_call("/api/v1/courses/#{badge_placement_config.course_id.to_i}/assignments/#{@assignment['id']}/submissions/#{params['user_id']}", self)
                  @student_score = (submission['score'])
                  unless @student_score.nil?
                    if @student_score.to_i >= @module_item_score.to_i
                      @module_item_completed = true
                    end
                  end
                end
            elsif @module_item_json && @module_item_json['type'] == 'Assignment'
              submission = CanvasAPI.api_call("/api/v1/courses/#{badge_placement_config.course_id.to_i}/assignments/#{@module_item_json['content_id']}/submissions/#{params['user_id']}", self)
              @student_score = (submission['score'])
              unless @student_score.nil?
                if @student_score.to_i  >= @module_item_score.to_i
                  @module_item_completed = true
                end
              end
            end
          end
        end
      end

      if badge_placement_config.requirements_met?(student['computed_final_score'], completed_module_ids) && @module_item_completed
        @earned_for_different_course = @badge && @badge.badge_placement_config_id != @badge_placement_config.id
        if @earned_for_different_course && !email
          user_badge_placement = UserBadgePlacement.first(badge_placement_config_id: @badge_placement_config.id,user_id:@badge.user_id,badge_id:@badge.id)
          if user_badge_placement.nil?
            user_badge_placement = UserBadgePlacement.new(badge_placement_config_id: @badge_placement_config.id,user_id:@badge.user_id,badge_id:@badge.id)
            user_badge_placement.save
          end
        end
        params['credits_earned'] = badge_placement_config.credits_earned(student['computed_final_score'], completed_module_ids)
        if !email
          raise "You need to set an email address in Canvas before you can earn any badges."
        end
        badge = Badge.complete(params, badge_placement_config, name, email)
      elsif !badge &&  @module_item_completed
        badge = Badge.generate_badge({'user_id' => self.user_id}, badge_placement_config, name, email)
        badge.save
      end
    end
    return {
      :completed_module_ids => completed_module_ids,
      :badge_config => badge_placement_config.badge_config,
      :badge_placement_config => badge_placement_config,
      :user_config => self,
      :badge => badge,
      :student => student,
      :module_item_json => @module_item_json,
      :student_score => @student_score,
      :module_item_score => @module_item_score.to_i
    }
  end
end

class BadgeConfigOwner
  include DataMapper::Resource
  property :id, Serial
  property :user_config_id, Integer
  property :badge_config_id, Integer
  property :badge_placement_config_id, Integer
  belongs_to :badge_config
  belongs_to :user_config
  belongs_to :badge_placement_config
end

class BadgeConfig
  include DataMapper::Resource
  property :id, Serial
  property :course_id, String # deprecated
  property :placement_id, String # deprecated
  property :teacher_user_config_id, Integer # deprecated
  property :nonce, String
  property :external_config_id, Integer # TODO: how is this used?
  property :organization_id, Integer
  property :domain_id, Integer # deprecated
  property :settings, Json # partially deprecated
  property :root_id, Integer # deprecated
  property :reference_code, String # deprecated
  property :reuse_code, String, :index => true
  property :public, Boolean
  property :uncool, Boolean
  property :configured, Boolean, :index => true
  property :updated_at, DateTime

  before :save, :generate_nonce
  belongs_to :external_config
  belongs_to :organization
  has n, :badge_placement_configs

  def as_json(host_with_port)
    settings = self.settings || {}
    image = settings['badge_url'] || "/badges/default.png"
    if settings['badge_url'].match(/^data:/)
      image = "/badges/from_config/#{self.id}/#{self.nonce}/badge.png"
    end
    image = "#{BadgeHelper.protocol}://" + host_with_port + image if image.match(/^\//)
    {
      :name => settings['badge_name'],
      :description => settings['badge_description'],
      :image => image,
      :criteria => "#{BadgeHelper.protocol}://#{host_with_port}/badges/criteria/#{self.id}/#{self.nonce}",
      :issuer => "#{BadgeHelper.protocol}://#{host_with_port}/api/v1/organizations/#{self.org_id}.json",
      :alignment => [], # TODO
      :tags => [] # TODO
    }
  end

  def to_json(host_with_port)
    as_json(host_with_port).to_json
  end

  def self.generate_badge_placement_configs
    BadgeConfig.all.each{|bc| bc.generate_badge_placement_config }
  end

  def generate_badge_placement_config
    if self.placement_id
      bc = BadgePlacementConfig.first_or_new(:placement_id => self.placement_id, :domain_id => self.domain_id)
      bc.course_id ||= self.course_id
      bc.teacher_user_config_id ||= self.teacher_user_config_id
      bc.external_config_id ||= self.external_config_id
      bc.organization_id ||= self.organization_id
      bc.domain_id ||= self.domain_id
      bc.updated_at = DateTime.now
      bc.set_badge_config(self)
      bc.save
      bc
    end
  end

  def org_id
    if self.organization && self.organization.settings
      "#{self.organization_id}-#{self.organization.settings['name'].downcase.gsub(/[^\w]+/, '-')[0, 30]}"
    else
      "default"
    end
  end

  def generate_nonce
    self.configured = self.configured?
    self.nonce ||= Digest::MD5.hexdigest(Time.now.to_i.to_s + rand.to_s)
    self.reuse_code ||= Digest::MD5.hexdigest(Time.now.to_i.to_s + rand.to_s)
  end

  def approve_to_pending?
    settings && (settings['manual_approval'] || settings['require_evidence'])
  end

  def update_counts
    self.settings ||= {}
    self.settings['awarded_count'] = Badge.all(:badge_config_id => self.id, :state => 'awarded').count
    self.save
  end

  def configured?
    !!(settings && settings['badge_url'])
  end
end

class BadgePlacementConfig
  include DataMapper::Resource
  property :id, Serial
  property :badge_config_id, Integer, :index => true
  property :course_id, String
  property :placement_id, String
  property :teacher_user_config_id, Integer
  property :author_user_config_id, Integer
  property :nonce, String # deprecated
  property :external_config_id, Integer # deprecated
  property :organization_id, Integer
  property :domain_id, Integer
  property :settings, Json # partially deprecated
  property :root_id, Integer # deprecated
  property :reference_code, String # deprecated
  property :public, Boolean #deprecated
  property :public_course, Boolean, :index => true
  property :updated_at, DateTime

  belongs_to :badge_config
  belongs_to :external_config
  belongs_to :organization
  belongs_to :domain

  def merged_settings
    settings = (self.badge_config && self.badge_config.settings) || {}
    settings.merge(self.settings || {})
  end

  def set_badge_config(badge_config)
    self.badge_config_id = badge_config.id
    badge_settings = badge_config.settings || {}
    placement_settings = self.settings || {}
    if badge_settings['min_percent'] != nil && placement_settings['min_percent'] == nil
      placement_settings['manual_approval'] = badge_settings['manual_approval']
      placement_settings['require_evidence'] = badge_settings['require_evidence']
      placement_settings['credit_based'] = badge_settings['credit_based']
      placement_settings['required_credits'] = badge_settings['requird_credits'].to_f.round(1)
      placement_settings['min_percent'] = badge_settings['min_percent'].to_f
      placement_settings['hours'] = badge_settings['hours'].to_f.round(1)
      placement_settings['hours'] = nil if placement_settings['hours'] == 0
      placement_settings['credits_for_final_score'] = badge_settings['credits_for_final_score'].to_f.round(1)
      placement_settings['modules'] = badge_settings['modules']
      placement_settings['total_credits'] = badge_settings['total_credits']
      placement_settings['module_items'] = badge_settings['module_items']

      self.settings = placement_settings
    end
    first_placement = badge_config.badge_placement_configs.first
    self.settings['prior_resource_link_id'] = first_placement.placement_id if first_placement

    self.save
    Badge.all(:badge_config_id => badge_config.id, :badge_placement_config_id => nil).update(:badge_placement_config_id => self.id)
    Badge.all(:badge_config_id => badge_config.id, :course_id => nil).update(:course_id => self.course_id)
  end

  def check_for_awardees
    teacher_config = self.teacher_user_config_id && UserConfig.first(:id => self.teacher_user_config_id)
    if teacher_config
      # get the paginated list of students
      # for each student, check if they already have a badge awarded
      # if not, check on award status
    end
  end

  def check_for_public_state
    return false unless self.domain
    host = "#{BadgeHelper.protocol}://" + self.domain.host
    api = Canvas::API.new(:host => host, :token => "")
    begin
      json = api.get("/api/v1/courses/#{self.course_id}")
      self.public_course = !!(json && json['id'].to_s == self.course_id)
    rescue Canvas::ApiError => e
      self.public_course = false
    rescue Timeout::Error => e
      false
    end
  end

  def load_from_old_config(user_config, old_config=nil)
    self.settings ||= {}
    return nil if !self.settings['prior_resource_link_id'] || self.settings['already_loaded_from_old_config']
    old_config ||= BadgePlacementConfig.first(:placement_id => self.settings['prior_resource_link_id'], :domain_id => self.domain_id)
    old_config ||= BadgePlacementConfig.first(:placement_id => self.settings['prior_resource_link_id'], :badge_config_id => self.badge_config_id)
    if old_config
      # load config settings from previous badge config
      existing_settings = self.settings
      self.settings = old_config.settings

      # set to pending unless
      # able to get new module ids and map them correctly for module-configured badges
      self.settings['pending'] = true if old_config.modules_required?
      self.settings['course_url'] = existing_settings['course_url'] if existing_settings

      api_user = UserConfig.first(:id => self.teacher_user_config_id) || user_config
      if api_user && old_config.modules_required?
        # make an API call to get the module ids and try to map from old to new
        # map ids for module names and also credits_for values
        new_modules = []
        modules_json = CanvasAPI.api_call("/api/v1/courses/#{self.course_id}/modules", api_user, true) || []
        all_found = true
        old_config.settings['modules'].each do |id, str, credits|
          new_module = modules_json.detect{|m| m['name'] == str}
          if new_module
            new_modules << [new_module['id'].to_s.to_i, str, credits]
          else
            all_found = false
          end
        end
        self.settings['modules'] = new_modules
        self.settings['pending'] = !all_found
      end
      self.settings['already_loaded_from_old_config'] = true
      self.save
    end
  end

  def to_json(host_with_port)
    as_json(host_with_port).to_json
  end

  def approve_to_pending?
    settings && (settings['manual_approval'] || settings['require_evidence'])
  end

  def update_counts
    self.settings ||= {}
    self.settings['awarded_count'] = Badge.all(:badge_placement_config_id => self.id, :state => 'awarded').count
    self.save
    self.badge_config.update_counts
  end

  def pending?
    settings && settings['pending']
  end

  def needs_old_config_load?
    settings && !settings['min_percent'] && settings['prior_resource_link_id']
  end

  def award_only?
    settings && settings['award_only']
  end

  def configured?
    !!(self.settings && self.badge_config && self.badge_config.settings && self.badge_config.settings['badge_url'] && self.settings['min_percent'] && !self.pending? && !self.award_only?)
  end

  def modules_required?
    settings && settings['modules']
  end

  def evidence_required?
    settings && settings['require_evidence']
  end

  def credit_based?
    !!(settings && settings['credit_based'] && settings['required_credits'])
  end

  def required_modules
    (settings && settings['modules']) || []
  end

  def required_module_ids
    required_modules.map(&:first).map(&:to_i)
  end

  def required_modules_completed?(completed_module_ids)
    incomplete_module_ids = self.required_module_ids - completed_module_ids
    incomplete_module_ids.length == 0
  end

  def required_score_met?(percent)
    settings && percent >= settings['min_percent']
  end

  def credits_earned(percent, completed_module_ids)
    credits = required_score_met?(percent) ? settings['credits_for_final_score'].to_f : 0
    (settings['modules'] || []).each do |id, name, credit|
      if completed_module_ids.include?(id.to_i)
        credits += (credit || 0)
      end
    end
    credits
  end

  def requirements_met?(percent, completed_module_ids)
    if credit_based?
      credits = credits_earned(percent, completed_module_ids)
      credits > 0 && credits > settings['required_credits'].to_f
    else
      required_modules_completed?(completed_module_ids) && required_score_met?(percent)
    end
  end
end

class Badge
  include DataMapper::Resource
  property :id, Serial
  property :placement_id, String
  property :user_id, String, :index => [:user_badge, :earned_badge]
  property :domain_id, Integer, :index => :earned_badge
  property :badge_url, Text
  property :nonce, String
  property :badge_config_id, Integer, :index => :user_badge
  property :badge_placement_config_id, Integer
  property :name, String, :length => 256
  property :user_full_name, String, :length => 256
  property :description, Text
  property :credits_earned, Integer
  property :recipient, String, :length => 512
  property :salt, String, :length => 512
  property :issued, DateTime
  property :email, String
  property :evidence_url, String, :length => 4096
  property :manual_approval, Boolean
  property :public, Boolean
  property :state, String, :index => [:earned_badge, :awarded_counter]
  property :course_id, String, :index => :earned_badge
  property :global_user_id, String, :length => 256
  property :issuer_name, String
  property :issuer_image_url, String
  property :issuer_org, String
  property :issuer_url, String
  property :issuer_email, String

  belongs_to :badge_config
  belongs_to :badge_placement_config
  before :save, :generate_defaults
  after :save, :check_for_notify_on_award
  after :save, :create_badge_placement_config

  def as_json
    badges = UserBadgePlacement.all(user_id: self.user_id.to_i,badge_id: self.id)
    { self.id => {:user_id => self.user_id,:badge_url => self.badge_url,:badge_count => badges.size,
                                                                :badge_description => self.description} }
  end

  def open_badge_json(host_with_port)
    image = self.badge_url
    if image && image.match(/^data:/) && self.badge_config
      bc = self.badge_config
      image = "/badges/from_badge/#{self.id}/#{self.nonce}/badge.png"
      image = "#{BadgeHelper.protocol}://" + host_with_port + image
    end

    {
      :uid => self.id.to_s,
      :recipient => {
        :identity => self.recipient,
        :type => "email",
        :hashed => true,
        :salt => self.salt
      },
      :badge => "#{BadgeHelper.protocol}://#{host_with_port}/api/v1/badges/summary/#{self.badge_config_id}/#{self.config_nonce}.json",
      :verify => {
        :type => "hosted",
        :url => "#{BadgeHelper.protocol}://#{host_with_port}/api/v1/badges/data/#{self.badge_config_id}/#{self.user_id}/#{self.nonce}.json"
      },
      :issuedOn => (self.issued && self.issued.strftime("%Y-%m-%d")),
      :image => image,
      :evidence => (self.evidence_url || "#{BadgeHelper.protocol}://#{host_with_port}/badges/criteria/#{self.badge_config_id}/#{self.config_nonce}?user=#{self.nonce}")
    }
  end

  def generate_defaults
    self.salt ||= Time.now.to_i.to_s
    self.nonce ||= Digest::MD5.hexdigest(self.salt + rand.to_s)
    self.issued ||= DateTime.now if self.awarded?

    sha = Digest::SHA256.hexdigest(self.email + self.salt)
    self.recipient = "sha256$#{sha}"

    self.badge_placement_config ||= BadgePlacementConfig.first(:placement_id => self.placement_id, :domain_id => self.domain_id)
    self.badge_config ||= self.badge_placement_config && self.badge_placement_config.badge_config
    user_config = UserConfig.first(:user_id => self.user_id, :domain_id => self.domain_id)
    self.global_user_id = user_config.global_user_id if user_config
    true
  end

  def check_for_notify_on_award
    # check if state just changed to awarded or completed, notify via email if that's the case
  end

  def user_name
    conf = UserConfig.first(:user_id => self.user_id, :domain_id => self.domain_id)
    (conf && conf.name) || self.user_full_name
  end

  def config_nonce
    self.badge_placement_config ||= BadgePlacementConfig.first(:placement_id => self.placement_id, :domain_id => self.domain_id)
    self.badge_config ||= self.badge_placement_config && self.badge_placement_config.badge_config
    self.badge_config && self.badge_config.nonce
  end

  def needing_evaluation?
    !awarded? && !pending?
  end

  def awarded?
    self.state == 'awarded'
  end

  def pending?
    self.state == 'pending'
  end

  def revoke
    self.state = 'revoked'
    save
  end

  def award
    self.state = 'awarded'
    save
  end

  def create_badge_placement_config
    user_badge_placement = UserBadgePlacement.new(badge_placement_config_id: self.badge_placement_config_id,
                                                  user_id: self.user_id,badge_id:self.id)
    user_badge_placement.save
  end

  def self.generate_badge(params, badge_placement_config, name, email)
    settings = badge_placement_config.merged_settings || {}
    badge = self.first_or_new(:user_id => params['user_id'], :badge_config_id => badge_placement_config.badge_config_id)
    badge.badge_placement_config = badge_placement_config
    badge.placement_id = badge_placement_config.placement_id
    badge.domain_id = badge_placement_config.domain_id
    badge.course_id = badge_placement_config.course_id

    if settings && settings['org'] && settings['org'].is_a?(Hash)
      badge.issuer_image_url = settings['org']['image']
      badge.issuer_org = settings['org']['name']
      badge.issuer_url = settings['org']['url']
      badge.issuer_email = settings['org']['email']
    end

    badge.issuer_name = BadgeHelper.issuer['name']
    badge.badge_config = badge_placement_config.badge_config
    badge.name = settings['badge_name']
    badge.email = email
    badge.state ||= 'unissued'
    badge.credits_earned = params['credits_earned'].to_i
    badge.user_full_name = name || params['user_name']
    badge.description = settings['badge_description']
    badge.badge_url = settings['badge_url']
    badge
  end

  def self.manually_award(params, badge_placement_config, name, email)
    badge = generate_badge(params, badge_placement_config, name, email)
    badge.manual_approval = true unless badge.pending?
    badge.state = 'awarded'
    badge.issued = DateTime.now
    badge.save
    badge_placement_config.update_counts
    badge
  end

  def self.complete(params, badge_placement_config, name, email)
    badge = generate_badge(params, badge_placement_config, name, email)
    badge.state = nil if badge.state == 'unissued'
    badge.state ||= badge_placement_config.approve_to_pending? ? 'pending' : 'awarded'
    badge.save
    badge_placement_config.update_counts
    badge
  end
end

class UserBadgePlacement
  include DataMapper::Resource

  property :id, Serial
  property :badge_id, Integer
  property :badge_placement_config_id, Integer
  property :user_id, Integer

  property :created_at, DateTime
  property :updated_at, DateTime

  belongs_to :badge
  belongs_to :badge_placement_config
  before :save, :generate_defaults

  def generate_defaults
    self.created_at ||= DateTime.now
  end

end


text:
package de.mosmann.bootstrap;

import java.util.List;

import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

public class NavLinksPanel extends Panel {

	public NavLinksPanel(String id, IModel<List<? extends ILinkFactory>> linkFactories) {
		super(id);

		add(new ListView<ILinkFactory>("links",linkFactories) {
			@Override
			protected void populateItem(ListItem<ILinkFactory> item) {
				ILinkFactory linkFactory = item.getModelObject();
				AbstractLink link = linkFactory.link("link");
				item.add(link);

				item.add(new AttributeAppender("class", Model.of(linkFactory.isActive() ? "active" : "")));
			}
		});
	}

}


text:
package com.gulj.app.blog.biz.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.gulj.app.blog.api.service.BlogReplyService;
import com.gulj.app.blog.api.vo.BlogReplyVo;
import com.gulj.app.blog.biz.mapper.BlogReplyMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author gulj
 * @create 2017-05-19 下午2:45
 **/
@Service(version = "1.0.0")
public class BlogReplyServiceImpl implements BlogReplyService {

    @Autowired
    private BlogReplyMapper blogReplyMapper;

    /**
     * 查询评论下的所有回复
     *
     * @param commentId
     * @return
     */
    public List<BlogReplyVo> queryReplyListByCommentId(Integer commentId) {
        return blogReplyMapper.queryReplyListByCommentId(commentId);
    }

}


text:
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using Orleans.Transactions.Abstractions;

namespace Orleans.Transactions
{
    public class TransactionalStateAttributeMapper : TransactionalStateAttributeMapper<TransactionalStateAttribute>
    {
        protected override TransactionalStateConfiguration AttributeToConfig(TransactionalStateAttribute attribute)
        {
            return new TransactionalStateConfiguration(attribute);
        }
    }

    public abstract class TransactionalStateAttributeMapper<TAttribute> : IAttributeToFactoryMapper<TAttribute>
        where TAttribute : IFacetMetadata, ITransactionalStateConfiguration
    {
        private static readonly MethodInfo create = typeof(ITransactionalStateFactory).GetMethod("Create");

        public Factory<IGrainActivationContext, object> GetFactory(ParameterInfo parameter, TAttribute attribute)
        {
            TransactionalStateConfiguration config = AttributeToConfig(attribute);
            // use generic type args to define collection type.
            MethodInfo genericCreate = create.MakeGenericMethod(parameter.ParameterType.GetGenericArguments());
            object[] args = new object[] { config };
            return context => Create(context, genericCreate, args);
        }

        private object Create(IGrainActivationContext context, MethodInfo genericCreate, object[] args)
        {
            ITransactionalStateFactory factory = context.ActivationServices.GetRequiredService<ITransactionalStateFactory>();
            return genericCreate.Invoke(factory, args);
        }

        protected abstract TransactionalStateConfiguration AttributeToConfig(TAttribute attribute);
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 项目对象相关操作控制。
 */
class Employee extends My_Controller
{
    public function __construct()
    {
        // 设置是否需要登录
        $this->needLogin = true;
        parent::__construct();
        $this->load->model("employees_model");
    }

    // 查看跟踪项目、商机清单
    public function index()
    {
        $data['title'] = '员工管理';

        $data['employees'] = $this->employees_model->get_employees();

        $this->load->view('templates/header', $data);
        $this->load->view('employee/employees', $data);
        $this->load->view('templates/footer');
    }
}


text:
extern const uint8_t PL_0101right_ECB_xml[];
extern const unsigned int PL_0101right_ECB_xml_len;

extern const uint8_t PL_0101right_CBC_xml[];
extern const unsigned int PL_0101right_CBC_xml_len;
#endif // LICENSEPARSERTESTCONSTANTS_H_


text:
<?php

namespace Models\Viewers;

use Illuminate\Database\Eloquent\Model;
use Models\UserStamped;

class ViewerVersion extends UserStamped {

	/**
	 * database attributes
	 */
	public $primaryKey = 'viewer_version_uuid';

	/**
	 * the database table used by the model
	 */
	protected $connection = 'viewer_store';

	/**
	 * mass assignment policy
	 */
	protected $fillable = array(
		'viewer_uuid',
		'version_no',
		'version_string',
		'invocation_cmd',
		'sign_in_cmd',
		'add_user_cmd',
		'add_result_cmd',
		'viewer_path',
		'viewer_checksum',
		'viewer_db_path',
		'viewer_db_checksum',
		'viewer_sharing_status'
	);

	/**
	 * array / json conversion whitelist
	 */
	protected $visible = array(
		'name',
		'viewer_uuid',
		'version_string'
	);
}


text:
import 'react-native';
import React, {} from 'react';
import renderer from 'react-test-renderer';
import RoadmapDetail from '../../../../src/containers/discover/roadmap-detail/RoadmapDetail';

it('renders correctly', () => {
  const roadmapDetail = renderer.create(
    <RoadmapDetail />,
  );
  const roadmapDetailJson = roadmapDetail.toJSON();
  expect(roadmapDetailJson).toMatchSnapshot();
});


text:
<?php

    /**
     * Created by PhpStorm.
     * User: jkirkby91
     * Date: 10/03/2016
     * Time: 16:39
     */

    namespace UniApi\Common\Exception\Http\UnofficialErrors;

    use UniApi\Common\Exception\HttpException;

    class MethodFailureException extends HttpException {

    }


text:
1. Refactor aws-sdk-for-php (or find what we can pass in during instantiation to circumvent) so the config.inc.php file presence issue isn't an issue

2. Integrate the cloudfusion AmazonPAS functionality

3. Condense/Consolidate the Factory and service instantiation


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findClosestBeforeHook = exports.RULE_NAME = void 0;
const utils_1 = require("@typescript-eslint/utils");
const create_testing_library_rule_1 = require("../create-testing-library-rule");
const node_utils_1 = require("../node-utils");
const utils_2 = require("../utils");
exports.RULE_NAME = 'no-render-in-setup';
function findClosestBeforeHook(node, testingFrameworkSetupHooksToFilter) {
    if (node === null) {
        return null;
    }
    if ((0, node_utils_1.isCallExpression)(node) &&
        utils_1.ASTUtils.isIdentifier(node.callee) &&
        testingFrameworkSetupHooksToFilter.includes(node.callee.name)) {
        return node.callee;
    }
    if (node.parent) {
        return findClosestBeforeHook(node.parent, testingFrameworkSetupHooksToFilter);
    }
    return null;
}
exports.findClosestBeforeHook = findClosestBeforeHook;
exports.default = (0, create_testing_library_rule_1.createTestingLibraryRule)({
    name: exports.RULE_NAME,
    meta: {
        type: 'problem',
        docs: {
            description: 'Disallow the use of `render` in testing frameworks setup functions',
            recommendedConfig: {
                dom: false,
                angular: 'error',
                react: 'error',
                vue: 'error',
            },
        },
        messages: {
            noRenderInSetup: 'Forbidden usage of `render` within testing framework `{{ name }}` setup',
        },
        schema: [
            {
                type: 'object',
                properties: {
                    allowTestingFrameworkSetupHook: {
                        enum: utils_2.TESTING_FRAMEWORK_SETUP_HOOKS,
                    },
                },
            },
        ],
    },
    defaultOptions: [
        {
            allowTestingFrameworkSetupHook: '',
        },
    ],
    create(context, [{ allowTestingFrameworkSetupHook }], helpers) {
        const renderWrapperNames = [];
        function detectRenderWrapper(node) {
            const innerFunction = (0, node_utils_1.getInnermostReturningFunction)(context, node);
            if (innerFunction) {
                renderWrapperNames.push((0, node_utils_1.getFunctionName)(innerFunction));
            }
        }
        return {
            CallExpression(node) {
                const testingFrameworkSetupHooksToFilter = utils_2.TESTING_FRAMEWORK_SETUP_HOOKS.filter((hook) => hook !== allowTestingFrameworkSetupHook);
                const callExpressionIdentifier = (0, node_utils_1.getDeepestIdentifierNode)(node);
                if (!callExpressionIdentifier) {
                    return;
                }
                const isRenderIdentifier = helpers.isRenderUtil(callExpressionIdentifier);
                if (isRenderIdentifier) {
                    detectRenderWrapper(callExpressionIdentifier);
                }
                if (!isRenderIdentifier &&
                    !renderWrapperNames.includes(callExpressionIdentifier.name)) {
                    return;
                }
                const beforeHook = findClosestBeforeHook(node, testingFrameworkSetupHooksToFilter);
                if (!beforeHook) {
                    return;
                }
                context.report({
                    node: callExpressionIdentifier,
                    messageId: 'noRenderInSetup',
                    data: {
                        name: beforeHook.name,
                    },
                });
            },
        };
    },
});


text:
import {Type, FIELD} from 'facade/lang';
import {Directive} from '../annotations/directive'

/**
 * Combination of a type with the Directive annotation
 */
export class AnnotatedType {
  constructor(type:Type, annotation:Directive) {
    this.annotation = annotation;
    this.type = type;
  }
}


text:
#include <common.h>
#include <fdtdec.h>

int board_init(void)
{
	return 0;
}

int dram_init(void)
{
	if (fdtdec_setup_memory_size() != 0)
		return -EINVAL;

	return 0;
}

int dram_init_banksize(void)
{
	fdtdec_setup_memory_banksize();

	return 0;
}

void *board_fdt_blob_setup(void)
{
	/* QEMU loads a generated DTB for us at the start of RAM. */
	return (void *)CONFIG_SYS_SDRAM_BASE;
}