text:
module.exports = function(grunt){
  var config = {
    test: {
      unit: [],
      integration: [],
      functional: []
    }
  };

  if(grunt.file.isDir('test/karma')) {
    //this needs to go first so composer install doesn't fail
    config.test.unit.push('karma:unit');
  }

  if(grunt.file.isDir('test/phpunit')) {
    // check if phpunit exists before adding it
    config.test.unit.push('shell:phpunit:unit');
    config.test.integration.push('shell:phpunit:integration');
  }

  if(grunt.file.isDir('test/casperjs')) {
    // check if casperjs exists before adding it
    config.test.functional.push('shell:casperjs');
  }

  return config;
};


text:
********************************************************************************
	Project owner:		RageQuit community
	Project name: 		GTW-RPG
	Developers:   		Mr_Moose

	Source code:		https://github.com/GTWCode/GTW-RPG/
	Bugtracker: 		http://forum.404rq.com/bug-reports/
	Suggestions:		http://forum.404rq.com/mta-servers-development/

	Version:    		Open source
	License:    		BSD 2-Clause
	Status:     		Stable release
********************************************************************************
]]--

-- Keep track of spam and vandalism
local last_msg 			= {{ }}
local cooldownTimers 	= { }

-- Global settings
local characteraddition 	= 100
local antiSpamTime 		= 1000
local maxbubbles 		= 4
local chat_range 		= 180
local showtime 			= 7500
local hideown 			= true
local defR,defG,defB		= 240, 235, 255

-- Change only if you have the IRC module and renamed the irc resource
local nameOfIRCResource	= "irc"

-- Define law
local lawTeams = {
	["Government"] = true,
	["Emergency service"] = true,
}
local policeTeams = {
	["Government"] = true,
}

-- This will compeletly block below listed words
local enable_word_censor 			= false
-- This will only replace bad words listed below
local enable_bad_word_replacement 	= true
-- Word censoring, list of words
local patterns = {
	-- Bad word, replacement
	{ "fuck", "feck" },
	{ "mtasa://", "gtw://" },
}

--[[ Compatibility with other servers, deal with export calls here ]]--
function dm(plr, msg, r, g, b, col)
	-- Replaces outputChatBox with identical syntax
	exports.GTWtopbar:dm(plr, msg, r, g, b, col)

	-- If you don't have "GTWtopbar" up and running, uncomment this instead
	--outputChatBox(plr, msg, r, g, b, col)
end

function getGroupChatColor(group)
	-- Call whatever group system you use and ask for a
	-- group as a string to receive it's chat color as RGB
	local r,g,b = exports.GTWgroups:getGroupChatColor(group)
	if not r or not g or not b then
		r,g,b = defR,defG,defB
	end
	return r,g,b
end

--[[ Returns true if no matches was found, otherwise false (block output) ]]--
function censorWords(input)
	local res = true
	for k,v in pairs(patterns) do
		if string.find(input, v[1]) and not enable_bad_word_replacement then
			res = false
		end
	end
	return res
end

--[[ Overriding chat helper function to allow word censoring ]]--
function outputToChat(text, visible_to, red, green, blue, color_coded)
	if enable_bad_word_replacement then
		for k,v in pairs(patterns) do
			string.gsub(text, v[1], v[2])
		end
	end
	outputChatBox(text, visible_to, red, green, blue, color_coded)
end

--[[ Clear anti spam cache on quit ]]--
function cleanUpChat()
	last_msg[source] = nil
	cooldownTimers[source] = nil
end
addEventHandler("onPlayerQuit", root, cleanUpChat)

--[[ Bind local chat on join ]]--
function bindLocalChat()
	bindKey(source, "u", "down", "chatbox", "Local")
	last_msg[source] = { }
end
addEventHandler("onPlayerJoin", root, bindLocalChat)

--[[ Check if a player should hear another player in local ]]--
function isPlayerInRangeOfPoint(player,x,y,z,range)
   local px,py,pz = getElementPosition(player)
   return((x-px)^2+(y-py)^2+(z-pz)^2)^0.5<=range
end

--[[ Initialize chat, bind local chat to all players ]]--
function initChat()
	for i,v in pairs(getElementsByType("player")) do
		bindKey(v, "u", "down", "chatbox", "Local")
		last_msg[v] = { }
	end
end
addEventHandler("onResourceStart", resourceRoot, initChat)

--[[ Securely check if a player is in the staff team ]]--
function isServerStaff(plr)
	-- Check if the player exist and are logged in properly
	if (not plr) or (not getPlayerAccount(plr)) then return false end

	-- Check if the player is in any of the staff ACL groups
	local acc = getAccountName(getPlayerAccount(plr))
	if isObjectInACLGroup("user."..acc, aclGetGroup("Admin")) or
		isObjectInACLGroup("user."..acc, aclGetGroup("Developer")) or
		isObjectInACLGroup("user."..acc, aclGetGroup("Moderator")) or
		isObjectInACLGroup("user."..acc, aclGetGroup("Supporter")) then
		return true
	else
		return false
	end
end

--[[ Handle spam and mutes, returns true if passed, false if failed ]]--
function validateChatInput(plr, chatID, text)
	if isPlayerMuted(plr) then
		dm("You are muted, visit games.albonius.com if you wish to appeal your mute", plr, 255, 100, 0)
		return false
	end
	if isTimer(cooldownTimers[plr]) then
		dm("Do not spam the chat!", plr, 255, 100, 0)
		return false
	end
	if last_msg[plr][chatID] and last_msg[plr][chatID] == text then
		dm("Do not repeat yourself!", plr, 255, 100, 0)
		return false
	end
	if enable_word_censor and not censorWords(text) then
		dm("Your message contains illegal words!", plr, 255, 100, 0)
		return false
	end
	-- Special case for car chat
	if chatID == "car" and not getPedOccupiedVehicle(plr) then
		dm("Car chat can only be used inside vehicles!", plr, 255, 100, 0)
		return false
	end
	-- Special case for law chat
	if chatID == "law" and getPlayerTeam(plr) and not lawTeams[getTeamName(getPlayerTeam(plr))] then
		dm("You are not a law enforcer!", plr, 255, 100, 0)
		return false
	end
	if chatID == "law" and not getPlayerTeam(plr) then
		dm("You are not in a team!", plr, 255, 100, 0)
		return false
	end
	-- Special case for group chat
	if chatID == "group" and not getElementData(plr, "Group") then
		dm("You are not in a group! Hit F6 to create or join a group", plr, 255, 100, 0)
		return false
	end
	return true
end

--[[ Handle incoming IRC messages ]]--
function IRCMessageReceive(channel, message)
	-- Verify that the resource is running, added support for custom names 2014-11-14
	local res = getResourceFromName(nameOfIRCResource)
	if getResourceState(res) ~= "running" then return end
	if string.match(message, '%d%d*') then return end
	if string.sub(message, 1, 1) == "!" then return end
	local nick = exports[nameOfIRCResource]:ircGetUserNick(source)
	outputToChat("#444444[IRC] #CCCCCC"..nick..":#FFFFFF "..message, root, 255, 255, 255, true)
	outputServerLog("[IRC] "..nick..": "..message)
end
addEvent("onIRCMessage")
addEventHandler("onIRCMessage", root, IRCMessageReceive)

--[[ Local chat ]]--
function useLocalChat(plr, n, ...)
	local msg = table.concat({...}, " ")
	if not validateChatInput(plr, "local", msg) then return end
  	local px,py,pz = getElementPosition(plr)
	local nick = getPlayerName(plr)
	local r,g,b = 255,255,0
	if not getElementData(plr, "anon") then
	    displayChatBubble("(LOCAL): "..firstToUpper(msg), 0, plr)
	end
  	if getPlayerTeam(plr) then
		if getTeamColor(getPlayerTeam(plr)) then
		 	r,g,b = getTeamColor(getPlayerTeam(plr))
		end
	end
	-- (2014-11-19) Count local players
	local sumOfLocal = 0
	for n,v in pairs(getElementsByType("player")) do
	   	if isPlayerInRangeOfPoint(v, px,py,pz, chat_range) then
	   		sumOfLocal = sumOfLocal + 1
	  	end
	end
	for n,v in pairs(getElementsByType("player")) do
	   	if isPlayerInRangeOfPoint(v, px,py,pz, chat_range) then
	   		local occupation = ""
	   		local is_police_chief = exports.GTWpolicechief:isPoliceChief(plr)
	   		if is_police_chief and getPlayerTeam(plr) and policeTeams[getTeamName(getPlayerTeam(plr))] then
	   			occupation = RGBToHex(defR, defG, defB).."[PoliceChief]"..RGBToHex(r,g,b)
	   		end
	   		local outText = RGBToHex(r,g,b).."(LOCAL) "..occupation.."["..tostring(sumOfLocal).."] "..RGBToHex(r,g,b)..nick..": "..RGBToHex(defR,defG,defB)
			local length = string.len(outText..firstToUpper(msg))
			if length < 128 then
	   			outputToChat(outText..firstToUpper(msg), v, r,g,b, true)
	   		else
	   			outputToChat(outText, v, r,g,b, true)
	   			outputToChat(RGBToHex(defR, defG, defB)..firstToUpper(msg), v, r,g,b, true)
	   		end
	  	end
	end

	-- Prevent spam and log the chat
	last_msg[plr]["local"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
  	outputServerLog("[LOCAL] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("localchat", useLocalChat, false, false)
addCommandHandler("local", useLocalChat, false, false)
addCommandHandler("lc", useLocalChat, false, false)

--[[ Car and vehicle chat]]--
function useCarChat(plr, n, ...)
	local msg = table.concat({...}, " ")
	if not validateChatInput(plr, "car", msg) then return end
	local r,g,b = defR,defG,defB
	if getPlayerTeam(plr) then
		r,g,b = getTeamColor(getPlayerTeam(plr))
	end
	local veh = getPedOccupiedVehicle(plr)
	local nick = getPlayerName(plr)
	for n, v in pairs(getVehicleOccupants(veh)) do
		local outText = "(CC) ["..tostring(n).."] "..nick..": "..RGBToHex(defR,defG,defB)
		local length = string.len(outText..firstToUpper(msg))
		if length < 128 then
			outputToChat(outText..firstToUpper(msg),v,200,0,200,true)
		else
			outputToChat(outText,v,200,0,200,true)
			outputToChat(firstToUpper(msg),v,200,0,200,true)
		end
	end

	-- Prevent spam and log the chat
	last_msg[plr]["car"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
	outputServerLog("[Car] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("carchat", useCarChat, false, false)
addCommandHandler("car", useCarChat, false, false)
addCommandHandler("cc", useCarChat, false, false)

--[[ Law and emergency chat ]]--
function useEmergencyChat(plr, n, ...)
	local msg = table.concat({...}, " ")
	if not validateChatInput(plr, "law", msg) then return end
	local r,g,b = getTeamColor(getPlayerTeam(plr))
	local nick = getPlayerName(plr)
	local occupation = ""
	local is_police_chief = exports.GTWpolicechief:isPoliceChief(plr)
   	if is_police_chief and policeTeams[getTeamName(getPlayerTeam(plr))] then
   		occupation = RGBToHex(defR,defG,defB).."[PoliceChief]"..RGBToHex(r,g,b)
   	end
	for m, v in pairs(getElementsByType("player")) do
		if lawTeams[getTeamName(getPlayerTeam(v))] then
    		local outText = RGBToHex(r,g,b).."(E)("..getTeamName(getPlayerTeam(plr))..")"..occupation.." "..nick..": "
			local length = string.len(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg))
			if length < 128 then
	   			outputToChat(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	   		else
	   			outputToChat(outText, v, r,g,b,true)
	   			outputToChat(RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	   		end
	   	end
  	end

  	-- Prevent spam and log the chat
	last_msg[plr]["law"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
	outputServerLog("[EMT] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("lawchat", useEmergencyChat, false, false)
addCommandHandler("law", useEmergencyChat, false, false)
addCommandHandler("e", useEmergencyChat, false, false)

--[[ Group chat, (only appliable on servers running a group system) ]]--
function useGroupChat(plr, n, ...)
	local msg = table.concat({...}, " ")
	if not validateChatInput(plr, "group", msg) then return end
	local r, g, b = getGroupChatColor(getElementData(plr, "Group")) or defR,defG,defB
	local nick = getPlayerName(plr)
	for n, v in pairs(getElementsByType("player")) do
		if getElementData(plr, "Group") == getElementData(v, "Group") then
	    		local outText = RGBToHex(r, g, b).."(GROUP) ["..getElementData(plr, "Group").."] "..nick..": "
			local length = string.len(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg))
			if length < 128 then
	   			outputToChat(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	  		else
	   			outputToChat(outText, v, r,g,b, true)
	   			outputToChat(RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	   		end
    		end
  	end

  	-- Prevent spam and log the chat
	last_msg[plr]["group"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
	outputServerLog("[GROUP]["..getElementData(plr, "Group").."] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("group", useGroupChat, false, false)
addCommandHandler("gc", useGroupChat, false, false)

--[[ Staff chat, private chat for members of the staff team ]]--
function useStaffChat(plr, n, ...)
	local msg = table.concat({...}, " ")
	if not validateChatInput(plr, "mod", msg) then return end
	if not isServerStaff(plr) then return end
	local r,g,b = defR,defG,defB
	if getPlayerTeam(plr) then
		r,g,b = getTeamColor(getPlayerTeam(plr))
	end
	local nick = getPlayerName(plr)
	for n, v in pairs(getElementsByType("player")) do
		if isServerStaff(v) then
	    		local outText = RGBToHex(255, 255, 255).."(STAFF) "..RGBToHex(r, g, b)..nick..": "
			local length = string.len(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg))
			if length < 128 then
	   			outputToChat(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	  		else
	   			outputToChat(outText, v, r,g,b, true)
	   			outputToChat(RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	   		end
    		end
  	end

  	-- Prevent spam and log the chat
	last_msg[plr]["mod"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
	outputServerLog("[STAFF] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("staff", useStaffChat, false, false)
addCommandHandler("mod", useStaffChat, false, false)
addCommandHandler("s", useStaffChat, false, false)

--[[ Staff chat, to reply to a certain team ]]--
function useStaffTeamChat(plr, n, team, ...)
	local msg = table.concat({...}, " ")
	if (not validateChatInput(plr, "mod-team", msg)) or (not isServerStaff(plr)) then return end
	local r, g, b = defR, defG, defB
	if team and getTeamFromName(team) then
		r, g, b = getTeamColor(getTeamFromName(team))
	end
	local nick = getPlayerName(plr)
	for n,v in pairs(getElementsByType("player")) do
		if team and getTeamFromName(team) and ((getPlayerTeam(v) and getPlayerTeam(v) == getTeamFromName(team)) or (v == plr)) then
	    	local outText = RGBToHex(255, 255, 255).."(STAFF-T) "..RGBToHex(r, g, b)..nick..": "
			local length = string.len(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg))
			if length < 128 then
	   			outputToChat(outText..RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	  		else
	   			outputToChat(outText, v, r,g,b, true)
	   			outputToChat(RGBToHex(defR,defG,defB)..firstToUpper(msg), v, r,g,b, true)
	   		end
    		end
  	end

  	-- Prevent spam and log the chat
	last_msg[plr]["mod-team"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
	outputServerLog("[STAFF-T] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("cteam", useStaffTeamChat, false, false)

--[[ Roleplay action chat, "/do <action>" ]]--
function useActionChatDo(plr, n, ...)
	local msg = table.concat({...}, " ")
	if not validateChatInput(plr, "do", msg) then return end
	local nick = getPlayerName(plr)
	outputToChat("* "..firstToUpper(msg).." ("..nick..")", root, 255, 0, 255)

	-- Prevent spam and log the chat
	last_msg[plr]["do"] = msg
	cooldownTimers[plr] = setTimer(function() end, antiSpamTime, 1)
	outputServerLog("[*DO*] "..getPlayerName(plr)..": "..msg)
end
addCommandHandler("do", useActionChatDo, false, false)

--[[ Global chat, (Main, Team and Me) ]]--
function useGlobalChat(message, messageType)
	cancelEvent() -- Important, do not call return before cancelling the event!
	if (messageType == 0) then
		if not validateChatInput(source, "main", message) then return end
		local occupation = ""
		local r,g,b = defR,defG,defB
		if getPlayerTeam(source) then
	    		r,g,b = getTeamColor(getPlayerTeam(source))
		end
		local is_police_chief = exports.GTWpolicechief:isPoliceChief(source)
		if is_police_chief and getPlayerTeam(source) and policeTeams[getTeamName(getPlayerTeam(source))] then
		 	occupation = RGBToHex(defR,defG,defB).."[PoliceChief]"..RGBToHex(r,g,b)
		end
		local px,py,pz = getElementPosition(source)
		local loc = getElementData(source, "Location") or getZoneName(px,py,pz)
		local outText = "("..loc..") "..occupation.." "..getPlayerName(source)..": "
		local length = string.len(outText..RGBToHex(defR,defG,defB)..firstToUpper(message))
		if length < 128 then
		   	outputToChat(outText..RGBToHex(defR,defG,defB)..firstToUpper(message), root, r,g,b, true)
		else
		 	outputToChat(outText, root, r,g,b, true)
		  	outputToChat(RGBToHex(defR,defG,defB)..firstToUpper(message), root, r,g,b, true)
		end
		outputServerLog("[CHAT] "..getPlayerName(source)..": "..message)
		--[[if not getElementData(source, "anon") then
		   	--displayChatBubble("(MAIN): "..firstToUpper(message), 2, source)
		end]]--

		-- Prevent spam and log the chat
		last_msg[source]["main"] = message
		cooldownTimers[source] = setTimer(function() end, antiSpamTime, 1)
	elseif (messageType == 1) then
		if not validateChatInput(source, "me", message) then return end
	  	local nick = getPlayerName(source)
		outputToChat("* "..nick..": "..firstToUpper(message), root, 255, 0, 255)
		outputServerLog("[*ME*] "..getPlayerName(source)..": "..message)

		-- Prevent spam and log the chat
		last_msg[source]["me"] = message
		cooldownTimers[source] = setTimer(function() end, antiSpamTime, 1)
	elseif (messageType == 2) then
		if not validateChatInput(source, "team", message) then return end
		local team = getPlayerTeam(source)
		if not team then return end
		local r,g,b = getTeamColor(getPlayerTeam(source))
		local occupation = ""
		local is_police_chief = exports.GTWpolicechief:isPoliceChief(source)
		if is_police_chief and policeTeams[getTeamName(getPlayerTeam(source))] then
			occupation = RGBToHex(defR,defG,defB).."[PoliceChief]"..RGBToHex(r,g,b)
		end
		outputServerLog("[TEAM]["..getTeamName(getPlayerTeam(source)).."] "..getPlayerName(source)..": "..message)
		if not getElementData(source, "anon") then
		  	displayChatBubble("(TEAM): "..firstToUpper(message), 2, source)
		end
		for i, v in pairs(getElementsByType("player")) do
			if getPlayerTeam(v) and (team == getPlayerTeam(v) or isServerStaff(v)) then
		    		-- Team chat is visible to team members and server staff
	     			if isServerStaff(v) and team ~= getPlayerTeam(v) then
	     				occupation = "["..getTeamName(team).."] "..occupation
	     			end
				local outText = "(TEAM) "..occupation.." "..getPlayerName(source)..": "
				local length = string.len(outText..RGBToHex(defR,defG,defB)..firstToUpper(message))
				if length < 128 then
					outputToChat(outText..RGBToHex(defR,defG,defB)..firstToUpper(message), v, r,g,b, true)
				else
				  	outputToChat(outText, v, r,g,b, true)
				    	outputToChat(RGBToHex(defR,defG,defB)..firstToUpper(message), v, r,g,b, true)
				end
			end
		end

		-- Prevent spam and log the chat
		last_msg[source]["team"] = message
		cooldownTimers[source] = setTimer(function() end, antiSpamTime, 1)
	end
end
addEventHandler("onPlayerChat", root, useGlobalChat)

--[[ Send chat message to clients to display a chat bubble ]]--
function displayChatBubble(message, messagetype, plr)
	if isPlayerMuted(plr) then return end
	if source then
		triggerClientEvent("GTWchat.makeChatBubble", source, message, messagetype, plr)
	else
		triggerClientEvent("GTWchat.makeChatBubble", plr, message, messagetype, plr)
	end
end

--[[ Convert RGB color to hex color ]]--
function RGBToHex(red, green, blue, alpha)
	if ((red < 0 or red > 255 or green < 0 or green > 255 or blue < 0 or blue > 255) or(alpha and(alpha < 0 or alpha > 255))) then
		return nil
	end
	if (alpha) then
		return string.format("#%.2X%.2X%.2X%.2X", red,green,blue,alpha)
	else
		return string.format("#%.2X%.2X%.2X", red,green,blue)
	end
end

--[[ Make first char in a string uppercase ]]--
function firstToUpper(str)
	if str and str:sub(1,4) ~= "http" and str:sub(1,4) ~= "www." then
    	return str:sub(1,1):upper()..str:sub(2)
    else
    	return str
    end
end

addCommandHandler("gtwinfo", function(plr, cmd)
	outputChatBox("[GTW-RPG] "..getResourceName(
	getThisResource())..", by: "..getResourceInfo(
        getThisResource(), "author")..", v-"..getResourceInfo(
        getThisResource(), "version")..", is represented", plr)
end)

--[[ Show help and available commands ]]--
function displayHelp(plr)
	outputChatBox("#000000**************************************************", plr, 255, 255, 255, true)
	outputChatBox("#444444"..getResourceInfo(getThisResource(), "name").." #FFFFFF(#00AA00"..
		getResourceInfo(getThisResource(), "version").."#FFFFFF), available commands:", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /local		#FFFFFF Local chat (U key)", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /cc		#FFFFFF Car chat, visible to all in your vehicle", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /gc		#FFFFFF Group chat, visible to group members", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /e			#FFFFFF Emergency chat, visible to law units", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /me /do	#FFFFFF Basic roleplay", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - T and Y	#FFFFFF Main and team chat", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /staff 	#FFFFFF Staff chat", plr, 255, 255, 255, true)
	outputChatBox("#00AA00 - /cteam		#FFFFFF Staff chat to a specific team", plr, 255, 255, 255, true)
	outputChatBox("#000000**************************************************", plr, 255, 255, 255, true)
end
addCommandHandler("chathelp", displayHelp, false, false)

--[[ Get bubble settings from clients ]]--
function receiveSettings()
	local settings =
	{
		showtime,
		characteraddition,
		maxbubbles,
		hideown
	}
	triggerClientEvent(source,"GTWchat.returnSettings", root, settings)
end
addEvent("GTWchat.askForSettings",true)
addEventHandler("GTWchat.askForSettings", root, receiveSettings)

redpajama_set_name: RedPajamaGithub


text:
static std::string string_printf (const char *format, ...) __attribute__ ((__format__ (__printf__, 1, 2)));
#endif

static std::string accu;

static std::string string_printf (const char *format, ...)
{
    std::string result;
    char str[1000];
    va_list args;
    va_start (args, format);
    if (vsnprintf (str, sizeof str, format, args) >= 0)
      result = str;
    va_end (args);
    return result;
}

static char float_callback (float f, int, std::string)
{
    accu += string_printf ("float: %.2f\n", f);
    return 0;
}

int main() {
    Simple::Signal<char (float, int, std::string)> sig1;
    size_t id1 = sig1.connect(float_callback);
    sig1.emit (.3f, 4, "huhu");
    sig1.disconnect(id1);
}


text:
class Role < ActiveRecord::Base

  has_many :assignments, :class_name => 'RoleAssignment'

  # Returns true if a role with +role_name+ exists.
  def self.valid? ( role_name = nil )
    return false if role_name.nil?
    self.exists?( :name => role_name.to_s )
  end

end


text:
<?php

namespace Anax\Questions;

/**
 * A controller for questions.
 *
 */
class QuestionsController implements \Anax\DI\IInjectionAware
{
    use \Anax\DI\TInjectable;

    /**
     * Initialize the controller.
     *
     * @return void
     */
    public function initialize()
    {
        $this->questions = new \Anax\Questions\Question();
        $this->questions->setDI($this->di);

        $this->users = new \Anax\Users\User();
        $this->users->setDI($this->di);

        $this->answers = new \Anax\Answers\Answer();
        $this->answers->setDI($this->di);

        $this->comments = new \Anax\Comments\Comment();
        $this->comments->setDI($this->di);

        $this->tags = new \Anax\Tags\Tag();
        $this->tags->setDI($this->di);
    }

    /**
     * List all questions.
     *
     * @return void
     */
    public function viewAction()
    {
        $all = $this->questions->findAll();
        $this->views->add('question/list-all', [
            'questions' => $all,
        ]);
    }

    /**
     * List all questions non deleted questions.
     *
     * @return void
     */
    public function publicviewAction()
    {
        $all = $this->questions->query()
            ->where('deleted is null')
            ->execute();

        $this->views->add('question/list-all', [
            'questions' => $all,
        ]);
    }

    /**
     * Add new question.
     *
     *
     * @return void
     */
    public function askAction()
    {
        $this->theme->setTitle("Ställ en fråga");

        $user = $this->session->get('user');

        if(isset($user)){

            $form = $this->form->create([], [

                'title' => [
                    'type'        => 'text',
                    'label'       => 'Titel',
                    'required'    => true,
                    'validation'  => ['not_empty'],
                ],

                'question' => [
                    'type'        => 'textarea',
                    'required'    => true,
                    'validation'  => ['not_empty'],
                ],

                'tags' => [
                    'type'        => 'text',
                    'label'       => 'Tagg(ar) använd " , " för att separera flera taggar',
                    'required'    => true,
                    'multiple'    => true,
                    'validation'  => ['not_empty'],
                ],

                'submit' => [
                    'type'      => 'submit',
                    'value'     => 'Ställ frågan',
                    'callback'  => function($form) {

                        $form->saveInSession = true;
                        return true;
                    }
                ],
            ]);

            $status = $form->check();

            if($status === true) {

                $form_data = $this->session->get('form-save');

                $stringtags  = $form_data['tags']['value'];

                $now = date("Y-m-d H:i:s");

                $userId = $this->session->get('user_id');

                $user = $this->session->get('user');

                $this->questions->save([
                    'title' => $form_data['title']['value'],
                    'question' => $this->textFilter->doFilter($form_data['question']['value'], 'shortcode, markdown'),
                    'user_id' => $userId,
                    'created' => $now,
                ]);

                $id = $this->questions->getLastInsertID();

                $tags = $this->di->dispatcher->forward([
                    'controller' => 'tags',
                    'action' => 'handleTags',
                    'params' => [$stringtags, $id]
                ]);

                $this->updateUserAsked($userId);

                unset($_SESSION['form-save']);

                $this->flashmessage->addNotice('Din fråga är nu ställd.');

                $url = $url = $this->url->create('questions');

                $this->response->redirect($url);

            } else if($status === false) {

                $form->AddOutput("
Någonting gick fruktansvärt fel. :(
");
            }

            $questionInfo = $this->fileContent->get('questionInfo.md');
            $questionInfo = $this->textFilter->doFilter($questionInfo, 'shortcode, markdown');

            $this->views->add('question/add-question', [
                'form' => $form->getHTML()
            ])

            ->addString($questionInfo, 'sidebar');

        } else {

            $this->flashmessage->addNotice('Du måste vara inloggad för att ställa frågor.');

            $url = $url = $this->url->create('users/login');

            $this->response->redirect($url);
        }
    }

    /**
     * Delete question.
     *
     * @param integer $id of question to delete and the question page for the redirect.
     *
     * @return void
     */
    public function deleteAction($id = null)
    {
        if (!isset($id)) {
            die("Missing id");
        }

        $this->deleteTag($id);

        $res = $this->questions->delete($id);

        if($res) {

            $this->flashmessage->addNotice('Borttagning lyckades!');

            $url = $this->session->get('url');

            $url = $url = $this->url->create($url);

            $this->response->redirect($url);
        }
    }

    /**
     * Delete (soft) question.
     *
     * @param integer $id of user to delete.
     *
     * @return void
     */
    public function softDeleteAction($id = null)
    {
        if (!isset($id)) {
            die("Missing id");
        }

        $now = date("Y-m-d H:i:s");

        $question = $this->questions->find($id);

        $question->deleted = $now;
        $question->save();

        $url = $this->url->create('questions');
        $this->response->redirect($url);
    }

    /**
     * List all questions for the page the questions was made.
     *
     * @return void
     */
    public function taggedAction($tag = null)
    {
        $this->theme->setTitle("Taggad frågor");

        $tag = urldecode($tag);

        $questions = $this->questions->query()
            ->join('tag', 'project_question.id = project_tag.question_id')
            ->where("project_tag.tag = ?")
            ->execute([$tag]);

        $this->views->add('question/list-all', [
            'questions' => $questions,
        ]);
    }

    /**
     * List question.
     *
     * @return void
     */
    public function idAction($id = null)
    {
        $this->theme->setTitle("Frågan");

        $question = $this->questions->query()
            ->where("id = ?")
            ->andWhere('deleted is null')
            ->execute([$id]);

        $comments = $this->comments->query()
            ->where('question_id = ?')
            ->andWhere('deleted is null')
            ->execute([$id]);

        $answers = $this->answers->query()
            ->where('question_id = ?')
            ->andWhere('deleted is null')
            ->execute([$id]);

        $answerForm = $this->answer($id);

        $this->views->add('project/question-view', [
            'questions' => $question,
            'comments' => $comments,
            'answers' => $answers,
            'answerform' => $answerForm,
        ]);
    }

    /**
     * Update question.
     *
     * @param int $id of question to edit.
     *
     * @return void
     */
    public function updateAction($id = null)
    {
        $this->theme->setTitle("Redigera frågan");

        $question = $this->questions->find($id);
        //Check that user is the op of the question.
        $user_id = $this->session->get('user_id');
        $question_user_id = $question->getProperties()['user_id'];

        if($question_user_id == $user_id){

            $properties = $question->getProperties();

            $tags = $this->tags->query('tag')
                        ->where('question_id = ?')
                        ->execute([$id]);

            $tagstring = "";

            foreach($tags as $tag){
                if($tagstring != "") {
                    $tagstring .= ", ";
                }

                $tagstring .= $tag->getProperties()['tag'];
            }

            $form = $this->form->create([], [

                'title' => [
                    'type'        => 'text',
                    'value'       => $properties['title'],
                    'label'       => 'Titel',
                    'required'    => true,
                    'validation'  => ['not_empty'],
                ],

                'question' => [
                    'type'        => 'textarea',
                    'value'       => strip_tags($properties['question']),
                    'required'    => true,
                    'validation'  => ['not_empty'],
                ],

                'tags' => [
                    'type'        => 'textarea',
                    'label'       => 'Tagg(ar)',
                    'value'       => $tagstring,
                    'required'    => true,
                    'validation'  => ['not_empty'],
                ],

                'submit' => [
                    'type'      => 'submit',
                    'value'     => 'Uppdatera frågan',
                    'callback'  => function($form) {

                        $form->saveInSession = true;
                        return true;
                    }
                ],
            ]);

            $status = $form->check();

            if($status === true) {

                foreach($tags as $tag){
                    if($tagstring != "") {
                        $tagstring .= ", ";
                    }

                    $tag= $tag->getProperties()['tag'];

                    $sql = "delete from project_tag where tag = '$tag' and question_id = '$id'";

                    $this->questions->sql($sql);
                }

                $form_data = $this->session->get('form-save');

                $stringtags  = $form_data['tags']['value'];

                $now = date("Y-m-d H:i:s");

                $userId = $this->session->get('user_id');

                $user = $this->session->get('user');

                $this->questions->update([
                    'id' => $id,
                    'title' => $form_data['title']['value'],
                    'question' => $this->textFilter->doFilter($form_data['question']['value'], 'shortcode, markdown'),
                    'user_id' => $userId,
                    'updated' => $now,
                ]);

                unset($_SESSION['form-save']);

                $tags = $this->di->dispatcher->forward([
                    'controller' => 'tags',
                    'action' => 'handleTags',
                    'params' => [$stringtags, $id]
                ]);

                $url = $this->url->create("questions/id/$id");

                $this->response->redirect($url);

            } else if($status === false) {

                $form->AddOutput("
Någonting gick fruktansvärt fel. :(
");
            }

            $this->views->add('question/add-question', [
                'title' => "Redigera frågan " . $properties['title'],
                'form' => $form->getHTML()
            ]);

        } else {

            $this->flashmessage->addNotice('Du kan inte uppdatera den här frågan.');

            $url = $url = $this->url->create("questions/id/$id");

            $this->response->redirect($url);
        }

    }

    /**
     * Gets questions for specific user by id.
     *
     * @param int $id of user.
     *
     * @return array questions.
     */
    public function getquestionsbyuserAction($id = null) {

        $questions = $this->questions->query()
            ->where('user_id = ?')
            ->execute([$id]);
        return $questions;
    }

    /**
     * Gets the ten latest questions order by the time of creation.
     *
     * @return void
     */
    public function tenlatestAction() {

        $sql = 'select * from project_question where deleted is null order by created desc limit 10;';
        $questions = $this->questions->sql($sql);
        $this->views->add('question/list-all', [
            'questions' => $questions,
        ]);
    }

    /**
     * Answer question.
     *
     * @param int $id of question to answer.
     *
     * @return form html
     */
    private function answer($question_id = null)
    {

        $form = $this->form->create([], [

            'answer' => [
                'type'        => 'textarea',
                'label'       => 'Svar',
                'required'    => true,
                'validation'  => ['not_empty'],
            ],

            'submit' => [
                'type'      => 'submit',
                'value'     => 'Posta ett svar',
                'callback'  => function($form) {

                    $form->saveInSession = true;
                    return true;
                }
            ],
        ]);

        $status = $form->check();

        if($status === true) {

            $user = $this->session->get('user');

            if(isset($user)){

                $form_data = $this->session->get('form-save');

                $now = date("Y-m-d H:i:s");

                $userId = $this->session->get('user_id');

                $user = $this->session->get('user');

                $this->answers->save([
                    'answer' => $this->textFilter->doFilter($form_data['answer']['value'], 'shortcode, markdown'),
                    'user_id' => $userId,
                    'question_id' => $question_id,
                    'created' => $now,
                ]);

                $this->updateQuestionAnswerUp($question_id);

                unset($_SESSION['form-save']);

                $url = $this->session->get('url');

                $url = $url = $this->url->create($url);

                $this->response->redirect($url);

        } else {

            unset($_SESSION['form-save']);

            $this->flashmessage->addNotice('Du måste vara inloggad för att svara på frågan.');

            $url = $url = $this->url->create("questions/id/$question_id");

            $this->response->redirect($url);
        }

        } else if($status === false) {

            $form->AddOutput("
Någonting gick fruktansvärt fel. :(
");
        }

        return $form->getHTML();
    }

    /**
     * Delete tag by question id.
     *
     * @param int $id of question in tag.
     *
     * @return void
     */
    private function deleteTag($id)
    {
        $sql = "delete from project_tag where question_id = $id;";

        $this->db->execute($sql);
    }

    /**
     * Updates user profile number of questions asked.
     *
     * @param int $id of the user to update.
     *
     * @return void
     */
    private function updateUserAsked($id = null)
    {
        $sql = "update project_user set questions = questions +1 where id = $id;";

        $this->db->execute($sql);
    }

    /**
     * Updates number of answers of a question by increasing the number by 1.
     *
     * @param int $id of the question to update.
     *
     * @return void
     */
    private function updateQuestionAnswerUp($id = null)
    {
        $sql = "update project_question set answers = answers +1 where id = $id;";

        $this->db->execute($sql);
    }
}


text:
let key = "key";

indexeddb_test(
  function upgrade(t, db) {
    db.createObjectStore('store');
  },
  function success(t, db) {
    const blobAContent = "Blob A content";
    const blobBContent = "Blob B content";
    const blobA = new Blob([blobAContent], {"type" : "text/plain"});
    const blobB = new Blob([blobBContent], {"type" : "text/plain"});
    value = { a0: blobA, a1: blobA, b0: blobB };

    const tx = db.transaction('store', 'readwrite');
    var store = tx.objectStore('store');

    store.put(value, key);
    value = null;

    const trans = db.transaction('store');
    store = trans.objectStore('store');
    const request = store.get(key);

    request.onsuccess = t.step_func(function() {
      const record = request.result;

      trans.oncomplete = t.step_func(function() {
        const trans = db.transaction('store', 'readwrite');
        store = trans.objectStore('store');
        const request = store.delete(key);

        trans.oncomplete = t.step_func(function() {
          const promise1 = record.a0.text().then(t.step_func(text => { assert_equals(text, blobAContent); },
            t.unreached_func()));

          const promise2 = record.a1.text().then(t.step_func(text => { assert_equals(text, blobAContent); },
            t.unreached_func()));

          const promise3 = record.b0.text().then(t.step_func(text => { assert_equals(text, blobBContent); },
            t.unreached_func()));

          Promise.all([promise1, promise2, promise3]).then(function() {
            // The test passes if it successfully completes.
            t.done();
          });
        });
      });
    });
  },
  "Blobs stay alive after their records are deleted.");


text:
package org.apache.druid.query.aggregation.mean;

import org.apache.druid.java.util.common.Numbers;
import org.apache.druid.query.aggregation.BufferAggregator;
import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import org.apache.druid.segment.ColumnValueSelector;

import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.util.List;

/**
 */
public class DoubleMeanBufferAggregator implements BufferAggregator
{

  private final ColumnValueSelector selector;

  public DoubleMeanBufferAggregator(ColumnValueSelector selector)
  {
    this.selector = selector;
  }

  @Override
  public void init(ByteBuffer buf, int position)
  {
    DoubleMeanHolder.init(buf, position);
  }

  @Override
  public void aggregate(ByteBuffer buf, int position)
  {
    Object update = selector.getObject();

    if (update instanceof DoubleMeanHolder) {
      DoubleMeanHolder.update(buf, position, (DoubleMeanHolder) update);
    } else if (update instanceof List) {
      for (Object o : (List) update) {
        DoubleMeanHolder.update(buf, position, Numbers.tryParseDouble(o, 0));
      }
    } else {
      DoubleMeanHolder.update(buf, position, Numbers.tryParseDouble(update, 0));
    }
  }

  @Nullable
  @Override
  public Object get(ByteBuffer buf, int position)
  {
    return DoubleMeanHolder.get(buf, position);
  }

  @Override
  public float getFloat(ByteBuffer buf, int position)
  {
    throw new UnsupportedOperationException("not supported");
  }

  @Override
  public long getLong(ByteBuffer buf, int position)
  {
    throw new UnsupportedOperationException("not supported");
  }

  @Override
  public double getDouble(ByteBuffer buf, int position)
  {
    throw new UnsupportedOperationException("not supported");
  }

  @Override
  public void close()
  {

  }

  @Override
  public void inspectRuntimeShape(RuntimeShapeInspector inspector)
  {
    inspector.visit("selector", selector);
  }
}


text:
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input.Manipulations;

namespace System.Windows.Input
{
    /// <summary>
    ///     Provides information about the inertia behavior.
    /// </summary>
    public class InertiaExpansionBehavior
    {
        /// <summary>
        ///     Instantiates a new instance of this class.
        /// </summary>
        public InertiaExpansionBehavior()
        {
        }

        /// <summary>
        ///     Instantiates a new instance of this class.
        /// </summary>
        internal InertiaExpansionBehavior(Vector initialVelocity)
        {
            _initialVelocity = initialVelocity;
        }

        /// <summary>
        ///     The initial rate of change of size of the element at the start of the inertia phase.
        /// </summary>
        public Vector InitialVelocity
        {
            get { return _initialVelocity; }
            set
            {
                _isInitialVelocitySet = true;
                _initialVelocity = value;
            }
        }

        /// <summary>
        ///     The desired rate of change of velocity.
        /// </summary>
        public double DesiredDeceleration
        {
            get { return _desiredDeceleration; }
            set
            {
                if (Double.IsInfinity(value) || Double.IsNaN(value))
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                _isDesiredDecelerationSet = true;
                _desiredDeceleration = value;
                _isDesiredExpansionSet = false;
                _desiredExpansion = new Vector(double.NaN, double.NaN);
            }
        }

        /// <summary>
        ///     The desired total change in size.
        /// </summary>
        public Vector DesiredExpansion
        {
            get { return _desiredExpansion; }
            set
            {
                _isDesiredExpansionSet = true;
                _desiredExpansion = value;
                _isDesiredDecelerationSet = false;
                _desiredDeceleration = double.NaN;
            }
        }

        public double InitialRadius
        {
            get { return _initialRadius; }
            set
            {
                _isInitialRadiusSet = true;
                _initialRadius = value;
            }
        }

        internal bool CanUseForInertia()
        {
            return _isInitialVelocitySet || _isInitialRadiusSet || _isDesiredDecelerationSet || _isDesiredExpansionSet;
        }

        internal static void ApplyParameters(InertiaExpansionBehavior behavior, InertiaProcessor2D processor, Vector initialVelocity)
        {
            if (behavior != null && behavior.CanUseForInertia())
            {
                InertiaExpansionBehavior2D behavior2D = new InertiaExpansionBehavior2D();
                if (behavior._isInitialVelocitySet)
                {
                    behavior2D.InitialVelocityX = (float)behavior._initialVelocity.X;
                    behavior2D.InitialVelocityY = (float)behavior._initialVelocity.Y;
                }
                else
                {
                    behavior2D.InitialVelocityX = (float)initialVelocity.X;
                    behavior2D.InitialVelocityY = (float)initialVelocity.Y;
                }
                if (behavior._isDesiredDecelerationSet)
                {
                    behavior2D.DesiredDeceleration = (float)behavior._desiredDeceleration;
                }
                if (behavior._isDesiredExpansionSet)
                {
                    behavior2D.DesiredExpansionX = (float)behavior._desiredExpansion.X;
                    behavior2D.DesiredExpansionY = (float)behavior._desiredExpansion.Y;
                }
                if (behavior._isInitialRadiusSet)
                {
                    behavior2D.InitialRadius = (float)behavior._initialRadius;
                }

                processor.ExpansionBehavior = behavior2D;
            }
        }

        private bool _isInitialVelocitySet;
        private Vector _initialVelocity = new Vector(double.NaN, double.NaN);
        private bool _isDesiredDecelerationSet;
        private double _desiredDeceleration = double.NaN;
        private bool _isDesiredExpansionSet;
        private Vector _desiredExpansion = new Vector(double.NaN, double.NaN);
        private bool _isInitialRadiusSet;
        private double _initialRadius = 1.0;
    }
}


text:
package com.deleidos.rtws.commons.dao.tmsdb;

import static org.junit.Assert.assertTrue;

import java.util.Collection;

import javax.sql.DataSource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.unitils.UnitilsJUnit4TestClassRunner;
import org.unitils.database.annotations.TestDataSource;

import com.deleidos.rtws.commons.dao.tmsdb.SystemSizingDao;
import com.deleidos.rtws.commons.model.tmsdb.SystemSizing;

/**
 * Test for the TMS DB accessor SystemSizeDao.
 *
 * @author LUCECU
 *
 */@RunWith(UnitilsJUnit4TestClassRunner.class)
public class SystemSizeDaoTest  {

	private static Logger logger = LogManager
			.getLogger(SystemSizeDaoTest.class);
	private SystemSizingDao sizeDAO;

	@TestDataSource
	private static DataSource ds;

	@Before
	public void setUp() {

		sizeDAO = new SystemSizingDao();
		sizeDAO.setDataSource(ds);

	}

	@After
	public void cleanUp() {

	}

	@Test
	public void retrieveSystemSizes() {

		Collection<SystemSizing> sizes = sizeDAO.getSystemSizes();
		logger.debug("Number of system sizes retrieved is:  " + sizes.size());

		for (SystemSizing size : sizes) {
			logger.debug(size.toString());
		}
		assertTrue(sizes.size() > 0);
	}

}


text:
<?php

namespace Google\Cloud\Tests\Snippets\BigQuery;

use Google\Cloud\BigQuery\Bytes;
use Google\Cloud\Dev\Snippet\SnippetTestCase;
use Prophecy\Argument;

/**
 * @group bigquery
 */
class BytesTest extends SnippetTestCase
{
    public function testClass()
    {
        $snippet = $this->snippetFromClass(Bytes::class);
        $res = $snippet->invoke('bytes');

        $this->assertInstanceOf(Bytes::class, $res->returnVal());
    }
}


text:
(function() {
  'use strict';

  angular
    .module('guh.components')
    .controller('TileListCtrl', TileListCtrl);

  TileListCtrl.$inject = ['$element'];

  /**
   * @ngdoc controller
   * @name guh.containers.controller:TileListCtrl
   * @description Presentational component for tiles.
   *
   */
  function TileListCtrl($element) {

    var vm = this;

    vm.tiles = {};
    vm.visibleTile = null;

    vm.$onInit = $onInit;
    vm.$postLink = postLink;
    vm.addTile = addTile;
    vm.selectTile = selectTile;

    function $onInit() {
      $element.addClass('TileList');
    }

    function postLink() {}

    function addTile(tile) {
      vm.tiles[tile.id] = tile;

      if(vm.initialVisibleId && vm.initialVisibleId === tile.id) {
        selectTile(vm.initialVisibleId);
      }
    }

    function selectTile(tileId) {
      angular.forEach(vm.tiles, function(tile) {
        if(tile.id === tileId) {
          tile.visible = true;
        } else {
          tile.visible = false;
        }
      });
      vm.visibleTile = vm.tiles[tileId];

      vm.onSelectTile({
        tileId: tileId
      });
    }

  }

}());


text:
* [Description](#description)
* [Function Index](#index)
* [Function Details](#functions)

.
Copyright (c) (C) 2014, HIROE Shin

__Behaviours:__ [`supervisor`](supervisor.md).

__Authors:__ HIROE Shin ([`shin@HIROE-no-MacBook-Pro.local`](mailto:shin@HIROE-no-MacBook-Pro.local)).

## Function Index ##

start_client/1	Create subscribe client process.

start_link/0
Starts the supervisor.

## Function Details ##

### start_client/1 ###

start_client(SubOpts) -> {ok, pid()}

SubOpts = [{atom(), binary() | inet:port_number()}]

Create subscribe client process.

### start_link/0 ###

start_link() -> {ok, Pid} | ignore | {error, Error}

Starts the supervisor


text:
/*global module:false*/
module.exports = function (grunt) {
    'use strict';
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        meta: {
            version: '<%= pkg.version %>',
            srcPath: 'src/',
            deployPath: './',
            banner:
                ' Fly.js \n' +
                '(c) 2013 Oleg Pimenov, \n' +
                'Distributed under MIT license\n' +
                'http://github.com/Forestcamp/Fly.js \n'
        },
        lint_files: [
            'Gruntfile.js',
            'example/collide/entities/*.js',
            'example/collide/*.js',
            'example/invaders/*.js',
            'example/hero/*.js',
            'src/flyjs/core/collision/*.js',
            'src/flyjs/core/command/*.js',
            'src/flyjs/core/loader/*.js',
            'src/flyjs/core/*.js',
            'src/flyjs/render/*.js',
            'src/flyjs/utils/*.js',
            'src/flyjs/collection/*.js',
            'src/flyjs/texture/*.js'
        ],
        lint_globals: {
            flyjs: true,
            window: true,
            createjs: true
        },

        /*** Tasks ***/
        uglify: {
            options: {
                banner: '/* <%= meta.banner %> */'
            },
            compress_flyjs: {
                files: [{
                    src: [
                        'src/vendor/stats.min.js',
                        'src/vendor/domReady.js',
                        'src/vendor/jshashtable-2.1.js',
                        'src/vendor/createjs/events/Event.js',
                        'src/vendor/createjs/events/EventDispatcher.js',
                        'src/vendor/createjs/utils/IndexOf.js',
                        'src/vendor/createjs/utils/Log.js',
                        'src/vendor/createjs/utils/Proxy.js',
                        'src/vendor/easeljs/events/MouseEvent.js',
                        'src/vendor/easeljs/utils/UID.js',
                        'src/vendor/easeljs/utils/Ticker.js',
                        'src/vendor/easeljs/events/MouseEvent.js',
                        'src/vendor/easeljs/geom/Matrix2D.js',
                        'src/vendor/easeljs/geom/Point.js',
                        'src/vendor/easeljs/geom/Rectangle.js',
                        'src/vendor/easeljs/ui/ButtonHelper.js',
                        'src/vendor/easeljs/ui/Touch.js',
                        'src/vendor/easeljs/display/DisplayObject.js',
                        'src/vendor/easeljs/display/DOMElement.js',
                        'src/vendor/easeljs/display/Shadow.js',
                        'src/vendor/easeljs/display/SpriteSheet.js',
                        'src/vendor/easeljs/display/Graphics.js',
                        'src/vendor/easeljs/display/Container.js',
                        'src/vendor/easeljs/display/Stage.js',
                        'src/vendor/easeljs/display/Bitmap.js',
                        'src/vendor/easeljs/display/Shape.js',
                        'src/vendor/easeljs/display/Sprite.js',
                        'src/vendor/easeljs/display/Text.js',
                        'src/vendor/easeljs/utils/SpriteSheetUtils.js',
                        'src/vendor/easeljs/utils/SpriteSheetBuilder.js',
                        'src/vendor/easeljs/filters/Filter.js',
                        'src/vendor/easeljs/filters/AlphaMapFilter.js',
                        'src/vendor/easeljs/filters/AlphaMaskFilter.js',
                        'src/vendor/easeljs/filters/ColorFilter.js',
                        'src/vendor/easeljs/filters/ColorMatrix.js',
                        'src/vendor/easeljs/filters/ColorMatrixFilter.js',
                        'src/vendor/easeljs/version.js',
                        'src/vendor/easeljs/version_movieclip.js',
                        'src/vendor/preloadjs/**/*.js',
                        'src/flyjs/utils/Key.js',
                        'src/flyjs/utils/MathUtil.js',
                        'src/flyjs/utils/VertexLib.js',
                        'src/flyjs/utils/GamePad.js',
                        'src/flyjs/texture/AssetManager.js',
                        'src/flyjs/collection/EntitiesCollection.js',
                        'src/flyjs/core/Entity.js',
                        'src/flyjs/core/command/Command.js',
                        'src/flyjs/core/command/SerialCommand.js',
                        'src/flyjs/core/loader/Loader.js',
                        'src/flyjs/core/loader/ImageLoader.js',
                        'src/flyjs/core/loader/ManifestLoader.js',
                        'src/flyjs/core/loader/SpriteSheetLoader.js',
                        'src/flyjs/core/collision/Node.js',
                        'src/flyjs/core/collision/BoundsNode.js',
                        'src/flyjs/core/collision/QuadTree.js',
                        'src/flyjs/core/ManifestManager.js',
                        'src/flyjs/core/ManifestParser.js',
                        'src/flyjs/render/Render.js',
                        'src/flyjs/render/StageRender.js'
                    ],
                    dest: '<%= meta.deployPath %>flyjs.min.js'
                }],
                options: {
                    report: 'min',
                    beautify: false,
                    mangle: true,
                    toplevel: true
                }
            }
        },
        yuidoc: {
            name: '<%= pkg.name %>',
            description: '<%= pkg.description %>',
            version: '<%= pkg.version %>',
            url: '<%= pkg.homepage %>',
            options: {
                paths: '<%= meta.srcPath %>core',
                outdir: 'docs/'
            }
        },
        jslint: {
            directives: {
                nomen: true,
                vars: true,
                eqeq: true,
                plusplus: true,
                bitwise: true,
                globals: '<%= lint_globals %>'
            },
            files: '<%= lint_files %>'
        },
        jshint: {
            options: {
                eqeqeq: true,
                eqnull: true,
                globals: '<%= lint_globals %>'
            },
            uses_defaults: '<%= lint_files %>'
        }
    });

    // These plugins provide necessary tasks.
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-jshint');

    grunt.registerTask('docs', ['yuidoc']);
    grunt.registerTask('ugli', ['jshint', 'uglify']);
    grunt.registerTask('release', ['jshint']);
};


text:
"""
#
# By: Charles Brandt [code at charlesbrandt dot com]
# On: *2013.06.05 21:46:45
# License: MIT

# Requires:
# moments

# Description:
go through all items in a playlist and determine the size the disk space that the items use

cd medley/scripts
python3 size_of_playlist_items.py /media/path/to.m3u

"""
from __future__ import print_function
import os, sys, codecs
import re

from medley.formats import M3U
from medley.helpers import load_json, get_media_properties
from medley.content import Content

from sortable.path import Path, check_ignore

def usage():
    print(__doc__)

def summarize_items(items, media_root, ignores):
    """
    Takes a list of paths to the media / files that should be summarized

    media_root is used to force a size check for a certain path
    (which allows ignoring everything else?)

    """

    #list of results for each item... can be used for csv later
    details = [ ('dimensions', 'length', 'bitrate', 'data size', 'filename'), ]
    # only include summarized results for the list here
    # (may be more than one)
    summary = [ ]

    total_size = 0
    total_items = 0
    #seconds?
    total_length = 0
    for item in items:
        # make sure it's a path
        try:
            #if it's a content item (loaded from m3u)
            item = os.path.join(item.path, item.filename)
        except:
            # otherwise just a normal path
            item = str(item)
        print("\nsize_of_list for: ", item)
        check_item = False
        #see if it's in the media_root that was passed in
        #force check in that case
        if media_root and re.match(media_root, item):
            check_item = True

        #otherwise, make sure it's not in one of the explicit ignores:
        elif not check_ignore(item, ignores):
            check_item = True

        if check_item:
            p = Path(item)
            f = p.load()

            #try:
            results = get_media_properties(item)
            cur_size = f.check_size()
            total_size += cur_size
            #except:
            #    print("missing: %s" % item)
            #else:
            if results[0] != None:
                print(results)
                results = list(results)
                results.append(cur_size)
                results.append(item)
                total_length += results[1]
                total_items += 1
                #print item
                details.append(results)
            else:
                print("skipping: %s" % item)

    print("found %s matching items" % total_items)
    summary = [ total_size, total_length, total_items ]
    return (summary, details)

def size_of_list(source, media_root=None, ignores=['/c/',]):
    """
    ignores are used to distinguish actual media from markers
    """
    items = []
    if re.search('.m3u', source):
        items = M3U(source)
        (summary, details) = summarize_items(items, media_root, ignores)
        details.insert( 0, (source, ) )
        summary.insert( 0, source )
        return ([summary, ], details)

    elif re.search('.json', source):
        loaded = load_json(source)

        #see if we have a dictionary or a list:
        if isinstance(loaded, list):
            #already have a list
            #clean it up
            for item in loaded:
                #these are usually content .json files
                #load them and then look for the media path
                content = Content(item[0])
                #print content.media
                items.append(content.media[-1][0])
            (summary, details) = summarize_items(items, media_root, ignores)
            details.insert( 0, (source, ) )
            summary.insert( 0, source )
            return ([summary, ], details)

        elif isinstance(loaded, dict):
            #walk the tree to load each item individually
            #call size_of_list() recursively
            print("dictionary found:")
            #print loaded
            summary_total = []
            details_total = []
            for child in loaded['children']:
                (summary, details) = size_of_list(child['source'])
                cur_name = child['name']
                #replace filepath with name:
                summary[0][0] = cur_name
                summary_total.extend(summary)
                details_total.extend(details)
            return (summary_total, details_total)

def main():
    #requires that at least one argument is passed in to the script itself
    #(through sys.argv)
    if len(sys.argv) > 1:
        helps = ['--help', 'help', '-h']
        for i in helps:
            if i in sys.argv:
                usage()
                exit()
        source = sys.argv[1]
        if len(sys.argv) > 2:
            media_root = sys.argv[2]
        else:
            media_root = None

        summaries, details = size_of_list(source, media_root)

        base = os.path.dirname(source)
        dest = os.path.join(base, 'summaries.csv')
        f = codecs.open(dest, 'w', encoding='utf-8')
        for summary in summaries:
            new_summary = []
            for item in summary:
                new_summary.append(str(item))
            f.write(','.join(new_summary))
            f.write('\n')
        f.close()

        dest = os.path.join(base, 'details.csv')
        f = codecs.open(dest, 'w', encoding='utf-8')
        for detail in details:
            new_detail = []
            for item in detail:
                new_detail.append(str(item))
            f.write(','.join(new_detail))
            f.write('\n')
        f.close()

        print()
        print("Details saved to: ", dest)

    else:
        usage()
        exit()

if __name__ == '__main__':
    main()


text:
<?php namespace spec\Rossedman\Splice\Git\Repository;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class GitlabRepositorySpec extends ObjectBehavior {

    function let()
    {
        $repository = json_decode('{"name": "Diaspora","url": "git@example.com:mike/diasporadiaspora.git","description": "", "homepage": "http://example.com/mike/diaspora", "git_http_url":"http://example.com/mike/diaspora.git", "git_ssh_url":"git@example.com:mike/diaspora.git", "visibility_level":0}');

        $this->beConstructedWith($repository, 'gitlab');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Rossedman\Splice\Git\Repository\GitlabRepository');
    }

    function it_returns_name()
    {
        $this->name()->shouldReturn('Diaspora');
    }

    function it_returns_url()
    {
        $this->url()->shouldReturn('git@example.com:mike/diasporadiaspora.git');
    }

    function it_determines_if_repo_is_private()
    {
        $this->isPrivate()->shouldReturn(true);
    }
}


text:
function feature_set = GetFeatureHist(obj, varargin)
% Get histogram features
% feature_set = GetFeatureHist(obj, 'param', value, ...)
%
% PARAMETERS
% b_tighten_roi: tighten ROI for lung CT (default: false)
%
% Similar to histogram-based features from Tixier et al. 2011 (doi:
% 10.2967/jnumed.110.082404)
%
% Basically the same as ImageFeature.GetFeatureHist

% By Daniel Golden (dgolden1 at stanford dot edu) January 2013
% $Id$

%% Parse input arguments
p = inputParser;
p.addParamValue('b_tighten_roi', false);
p.parse(varargin{:});

%% Extract features
hist_struct.patient_id = obj.PatientID;

if isempty(obj.MyROI3D)
  values = nan;
else
  values = GetROIPixels(obj, 'b_tighten_roi', p.Results.b_tighten_roi);
end

hist_struct.mean = nanmean(values);
hist_struct.var = nanvar(values);
hist_struct.skewness = skewness(values);
hist_struct.kurtosis = kurtosis(values);
% hist_struct.std = nanstd(values); % std is sqrt of variance
%hist_struct.q25 = quantile(values, 0.25);
%hist_struct.q75 = quantile(values, 0.75);

feature_pretty_names = {'Mean', 'Variance', 'Skewness', 'Kurtosis'};

% feature_set = FeatureSet(hist_struct, feature_pretty_names, ['hist_' obj.ImageName], ['Histogram ' obj.ImagePrettyName]);
feature_set = FeatureSet(hist_struct, feature_pretty_names, 'hist', 'Histogram');


text:
// -----------------------------------------------
// Configuration file for gulp tasks
'use strict';

var gulp = require("gulp");
var template = require('gulp-template');
var debug = require('gulp-debug');

/**
 * configure for debug environment
 */
gulp.task("configure-debug", ["build-ts-debug"], function () {
    return configure(tasksConfig.environmentVars.debug);
});

/**
 * configure for debug environment
 */
gulp.task("configure-release", ["build-ts-release"], function () {
    return configure(tasksConfig.environmentVars.release);
});

function configure(obj)
{
    var files = [
        tasksConfig.outputAppFolder + "config.js",
        tasksConfig.outputAppFolder + "main.js"
        ]

    gulp.src(files)
		.pipe(template(obj))
		.pipe(gulp.dest(tasksConfig.outputAppFolder));

    files = [
        tasksConfig.outputTestsFolder + "test-main.js"
        ]

	gulp.src(files)
		.pipe(template(obj))
		.pipe(gulp.dest(tasksConfig.outputTestsFolder));
}

var tasksConfig = (function ()
{
    var _sourceFolder = "src/";
    var _sourceContentFolder = _sourceFolder + "content/";
    var _outputFolder = "wwwroot/";
    var _outputContentFolder = _outputFolder + "content/";

    return {

        // source resources
        sourceFolder: _sourceFolder,
        sourceContentFolder: _sourceContentFolder,

        sourceHtmlFiles: _sourceFolder + "**/*.html",
        sourceCssFiles: _sourceContentFolder + "css/**/*.css",
        sourceMocksFiles: _sourceContentFolder + "mocks/*.json",

        sourceScriptFiles: _sourceFolder + "app/**/*.ts",
        sourceTestsScriptFiles: _sourceFolder + "tests/**/*.ts",

        // output resources
        outputFolder: _outputFolder,
        outputContentFolder: _outputContentFolder,

        outputAppFolder: _outputFolder + "app/",
        outputLibFolder: _outputFolder + "lib/",
        outputCssFolder: _outputContentFolder + "css/",
        outputFontsFolder: _outputContentFolder + "fonts/",
        outputMocksFolder: _outputContentFolder + "mocks/",

        outputTestsFolder: _outputFolder + "tests/",

        // environments vars for use with gulp-template
        environmentVars: {

            debug: {
                APP_VERSION: "1.0",
	            BASE_URL: "/",
                API_BASE_URL: "/",
                APP_NAME: "angular.ts.sample",
                DEBUG_MODE: "true",
                MINIFIED_EXT: ".min"
            },
            release: {
                APP_VERSION: "1.0",
	            BASE_URL: "/",
                API_BASE_URL: "/",
                APP_NAME: "angular.ts.sample",
                DEBUG_MODE: "false",
                MINIFIED_EXT: ""
            }

        }

    };

})();

module.exports = tasksConfig;


text:
import { compose } from '@typed/compose';
import { createSelector } from 'reselect';

import { sortByKey } from '~client/modules/data';
import type { State } from '~client/reducers/types';
import type { CashTotalNative, NetWorthEntryNative } from '~client/types';
import type { Monthly, NetWorthCategory, NetWorthSubcategory } from '~client/types/gql';
import type { PageNonStandard } from '~shared/constants';

export const getCashTotal = (state: State): CashTotalNative => state.netWorth.cashTotal;

export const getMonthlyValues = (state: State): Monthly => state.overview.monthly;
export const getFutureIncome = (state: State): number[] => state.overview.futureIncome;
export const getStockValues = (state: State): number[] => state.overview.stocks;

export const getStartDate = (state: Pick<State, PageNonStandard.Overview>): Date =>
  state.overview.startDate;

export const getEndDate = (state: Pick<State, PageNonStandard.Overview>): Date =>
  state.overview.endDate;

export const getAnnualisedFundReturns = (state: State): number =>
  state.overview.annualisedFundReturns;

export const getEntries = (state: State): NetWorthEntryNative[] => state.netWorth.entries;

const getNonFilteredCategories = (state: State): NetWorthCategory[] => state.netWorth.categories;
const getNonFilteredSubcategories = (state: State): NetWorthSubcategory[] =>
  state.netWorth.subcategories;

export const getCategories = createSelector(
  getNonFilteredCategories,
  sortByKey('type', 'category'),
);
export const getSubcategories = createSelector(
  getNonFilteredSubcategories,
  compose<NetWorthSubcategory[], NetWorthSubcategory[], NetWorthSubcategory[]>(
    sortByKey('subcategory'),
    sortByKey('categoryId'),
  ),
);


text:
import { AppPage } from './app.po';

describe('workspace-project App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', async () => {
    await page.navigateTo();
    expect(await page.getParagraphText()).toEqual('Welcome to app!');
  });
});


text:
<?php

// VinllaLandingBundle:Admin:info_list.html.twig
return array (
);


text:
These tests use the AWS Java Client Library.

## Prerequisites
* Java 1.7 or 1.8
* Scala 2.10.4
* Maven 3.2.1
  * on OS X:  `brew install maven`

## Running Things
If your system has all the prerequisites, running things is easy:

* Tests
  * `mvn verify -Pitest`

* Test Console
  * `mvn test-compile scala:console`
  * `scala> :load console/tables.scala`
  * `scala> Table.list()`


text:
export pccsIP=your_pccs_ip_to_use_as # This is an IP to be used as k8s service IP, and it should be an IP address that unused in your subnetwork
export pccsImageName=intelanalytics/pccs:0.3.0-SNAPSHOT
export apiKey=your_intel_pcs_server_subscription_key_obtained_through_web_registeration # Refer to README for obtaining pcs api key
# Please do not use the same real IPs as nodes
export httpsProxyUrl=your_usable_https_proxy_url
export countryName=your_country_name
export cityName=your_city_name
export organizaitonName=your_organizaition_name
export commonName=server_fqdn_or_your_name
export emailAddress=your_email_address
export serverPassword=your_server_password_to_use

## Create k8s namespace and apply BigDL-PCCS
kubectl create namespace bigdl-pccs
envsubst < bigdl-pccs.yaml | kubectl apply -f -


text:
package com.iluwatar.bridge;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * Mjollnir
 *
 */
public class Mjollnir extends FlyingMagicWeaponImpl {

  private static final Logger LOGGER = LoggerFactory.getLogger(Mjollnir.class);

  @Override
  public void wieldImp() {
    LOGGER.info("wielding Mjollnir");
  }

  @Override
  public void swingImp() {
    LOGGER.info("swinging Mjollnir");
  }

  @Override
  public void unwieldImp() {
    LOGGER.info("unwielding Mjollnir");
  }

  @Override
  public void flyImp() {
    LOGGER.info("Mjollnir hits the enemy in the air and returns back to the owner's hand");
  }
}


text:
Easy to integrate User onboarding in app. Just changing 2 lines of code.
Download the project and open viewController.swift on the line after the class declaration read the comments.
The Onboarding supports landscape mode too.

#App Preview:
![simulator screen shot dec 15 2016 6 39 16 pm](https://cloud.githubusercontent.com/assets/7130598/21230607/93c3f6c4-c2f6-11e6-8181-310c64dc6cde.png)
![simulator screen shot dec 15 2016 6 39 43 pm](https://cloud.githubusercontent.com/assets/7130598/21230608/93eaae5e-c2f6-11e6-95ac-59699b2ce960.png)


text:
//
//  HXVideoPresentTransition.m
//  微博照片选择
//
//  Created by 洪欣 on 17/2/22.
//  Copyright © 2017年 洪欣. All rights reserved.
//

#import "HXVideoPresentTransition.h"

@interface HXVideoPresentTransition ()
@property (assign, nonatomic) HXVideoPresentTransitionType type;
@end

@implementation HXVideoPresentTransition

+ (instancetype)transitionWithTransitionType:(HXVideoPresentTransitionType)type
{
    return [[self alloc] initWithTransitionType:type];
}

- (instancetype)initWithTransitionType:(HXVideoPresentTransitionType)type
{
    if (self = [super init]) {
        self.type = type;
    }
    return self;
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.4;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    switch (_type) {
        case HXVideoPresentTransitionPresent:
            [self presentAnimation:transitionContext];
            break;

        case HXVideoPresentTransitionDismiss:
            [self dismissAnimation:transitionContext];
            break;
    }
}

/**
 *  实现present动画
 */
- (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    //通过viewControllerForKey取出转场前后的两个控制器,这里toVC就是vc1、fromVC就是vc2
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    UIView *tempView = [fromVC.view snapshotViewAfterScreenUpdates:NO];
    tempView.frame = fromVC.view.frame;

    fromVC.view.hidden = YES;
    //这里有个重要的概念containerView,如果要对视图做转场动画,视图就必须要加入containerView中才能进行,可以理解containerView管理者所有做转场动画的视图
    UIView *containerView = [transitionContext containerView];

    //将视图和vc2的view都加入ContainerView中
    [containerView addSubview:toVC.view];
    [containerView addSubview:tempView];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    toVC.view.frame = CGRectMake(0, -height, width, height);

    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        tempView.frame = CGRectMake(0, height, width, height);
        toVC.view.frame = CGRectMake(0, 0, width, height);
    } completion:^(BOOL finished) {
        [tempView removeFromSuperview];
        fromVC.view.hidden = NO;
        [transitionContext completeTransition:YES];
    }];
}

/**
 *  实现dimiss动画
 */
- (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    //参照present动画的逻辑,present成功后,containerView的最后一个子视图就是截图视图,我们将其取出准备动画
    UIView *containerView = [transitionContext containerView];
    UIView *tempView = [toVC.view snapshotViewAfterScreenUpdates:NO];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    tempView.frame = CGRectMake(0, height, width, height);
    [containerView addSubview:tempView];
    toVC.view.hidden = YES;
    //动画吧
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVC.view.frame = CGRectMake(0, -height, width, height);
        tempView.frame = CGRectMake(0, 0, width, height);
    } completion:^(BOOL finished) {
        [tempView removeFromSuperview];
        toVC.view.hidden = NO;
        [transitionContext completeTransition:YES];
    }];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>zigbee-gateway-client</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.bubblecloud.zigbee4java</groupId>
        <artifactId>zigbee4java</artifactId>
        <version>3.0.3-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.bubblecloud.zigbee4java</groupId>
            <artifactId>zigbee-common</artifactId>
            <version>3.0.3-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.github.briandilley.jsonrpc4j</groupId>
            <artifactId>jsonrpc4j</artifactId>
            <version>1.2.0</version>
        </dependency>

    </dependencies>

</project>


text:
package ovirtclient

func (m *mockClient) GetDatacenter(id string, _ ...RetryStrategy) (Datacenter, error) {
	m.lock.Lock()
	defer m.lock.Unlock()
	if item, ok := m.dataCenters[id]; ok {
		return item, nil
	}
	return nil, newError(ENotFound, "datacenter with ID %s not found", id)
}


text:
/* Minimal network driver for Mini-OS.
 * Copyright (c) 2006-2007 Jacob Gorm Hansen, University of Copenhagen.
 * Based on netfront.c from Xen Linux.
 *
 * Does not handle fragments or extras.
 *
 * Modified: Grzegorz Milos
             Harald Roeck
 */

#include <guk/os.h>
#include <guk/init.h>
#include <guk/service.h>
#include <guk/xenbus.h>
#include <guk/events.h>
#include <guk/gnttab.h>
#include <guk/xmalloc.h>
#include <guk/time.h>
#include <guk/sched.h>
#include <guk/arch_sched.h>
#include <guk/smp.h>
#include <guk/trace.h>
#include <guk/spinlock.h>

#include <xen/io/netif.h>
#include <errno.h>

static struct net_info {
    struct netif_tx_front_ring tx;
    struct netif_rx_front_ring rx;
    int tx_ring_ref;
    int rx_ring_ref;
    unsigned int evtchn, local_port;
    int rings;
    int device_id;
    int state;
#define ST_UNKNOWN      0
#define ST_READY        1
#define ST_SUSPENDING   2
#define ST_SUSPENDED    3
#define ST_RESUMING     4
} net_info;

static DEFINE_SPINLOCK(net_info_lock);

#define DEVICE_STRING "device/vif"
#define MAX_PATH      128

#define NET_TX_RING_SIZE __RING_SIZE((struct netif_tx_sring *)0, PAGE_SIZE)
#define NET_RX_RING_SIZE __RING_SIZE((struct netif_rx_sring *)0, PAGE_SIZE)
#define GRANT_INVALID_REF 0

#define WATCH_TOKEN "net-front"

static unsigned short rx_freelist[NET_RX_RING_SIZE];
static unsigned short tx_freelist[NET_TX_RING_SIZE];

struct net_buffer {
    void* page;
    int gref;
};

static DEFINE_SPINLOCK(freelist_lock);
static struct net_buffer rx_buffers[NET_RX_RING_SIZE];
static struct net_buffer tx_buffers[NET_TX_RING_SIZE];

static inline void add_id_to_freelist(unsigned int id, unsigned short* freelist)
{
    long flags;
    spin_lock_irqsave(&freelist_lock, flags);
    freelist[id] = freelist[0];
    freelist[0]  = id;
    spin_unlock_irqrestore(&freelist_lock, flags);
}

static inline unsigned short get_id_from_freelist(unsigned short* freelist)
{
    unsigned int id;
    long flags;
    spin_lock_irqsave(&freelist_lock, flags);
    id = freelist[0];
    freelist[0] = freelist[id];
    spin_unlock_irqrestore(&freelist_lock, flags);
    return id;
}

__attribute__((weak)) void guk_netif_rx(unsigned char* data,int len)
{
    struct thread *thread = current;
    printk("%d bytes incoming at %p, thread %s\n",len,data, thread->name);
}

__attribute__((weak)) void guk_net_app_main(unsigned char *mac, char *nic) {
}

static inline int xennet_rxidx(RING_IDX idx)
{
    return idx & (NET_RX_RING_SIZE - 1);
}

static void network_rx(void)
{
    struct net_info *np = &net_info;
    RING_IDX rp,cons;
    struct netif_rx_response *rx;

    if (net_info.state != ST_READY)
	return;

moretodo:
    rp = np->rx.sring->rsp_prod;
    rmb(); /* Ensure we see queued responses up to 'rp'. */
    cons = np->rx.rsp_cons;

    int nr_consumed=0;
    while ((cons != rp))
    {
        struct net_buffer* buf;
        unsigned char* page;

        rx = RING_GET_RESPONSE(&np->rx, cons);

        if (rx->flags & NETRXF_extra_info)
        {
            printk("+++++++++++++++++++++ we have extras!\n");
            continue;
        }

        if (rx->status == NETIF_RSP_NULL) continue;

        int id = rx->id;

        buf = &rx_buffers[id];
        page = (unsigned char*)buf->page;
        gnttab_end_access(buf->gref);

        if(rx->status > 0) {
            guk_netif_rx(page+rx->offset,rx->status);
        }

        add_id_to_freelist(id,rx_freelist);

        nr_consumed++;

        ++cons;
    }
    np->rx.rsp_cons=rp;

    int more;
    RING_FINAL_CHECK_FOR_RESPONSES(&np->rx,more);
    if(more)
	goto moretodo;

    RING_IDX req_prod = np->rx.req_prod_pvt;

    int i;
    netif_rx_request_t *req;

    for(i=0; i<nr_consumed; i++)
    {
        int id = xennet_rxidx(req_prod + i);
        req = RING_GET_REQUEST(&np->rx, req_prod + i);
        struct net_buffer* buf = &rx_buffers[id];
        void* page = buf->page;

        buf->gref = req->gref =
            gnttab_grant_access(0,virt_to_mfn(page),0);

        req->id = id;
    }

    wmb();

    np->rx.req_prod_pvt = req_prod + i;

    int notify;
    RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->rx, notify);
    if (notify)
        notify_remote_via_evtchn(np->evtchn);

}

static void network_tx_buf_gc(void)
{
    RING_IDX cons, prod;
    unsigned short id;
    struct net_info *np = &net_info;

    if (net_info.state != ST_READY)
	return;

    do {
        prod = np->tx.sring->rsp_prod;
        rmb(); /* Ensure we see responses up to 'rp'. */

        for (cons = np->tx.rsp_cons; cons != prod; cons++)
        {
            struct netif_tx_response *txrsp;

            txrsp = RING_GET_RESPONSE(&np->tx, cons);
            if (txrsp->status == NETIF_RSP_NULL)
                continue;

            id  = txrsp->id;
            struct net_buffer* buf = &tx_buffers[id];
            gnttab_end_access(buf->gref);
            buf->gref=GRANT_INVALID_REF;

            add_id_to_freelist(id,tx_freelist);
        }

        np->tx.rsp_cons = prod;

        /*
         * Set a new event, then check for race with update of tx_cons.
         * Note that it is essential to schedule a callback, no matter
         * how few tx_buffers are pending. Even if there is space in the
         * transmit ring, higher layers may be blocked because too much
         * data is outstanding: in such cases notification from Xen is
         * likely to be the only kick that we'll get.
         */
        np->tx.sring->rsp_event =
            prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
        mb();
    } while ((cons == prod) && (prod != np->tx.sring->rsp_prod));
}

static void netfront_handler(evtchn_port_t port, void *data)
{
    spin_lock(&net_info_lock);

    network_tx_buf_gc();
    network_rx();

    spin_unlock(&net_info_lock);
}

static char* backend;

static void alloc_buffers(void)
{
    int i;
    for(i=0;i<NET_TX_RING_SIZE;i++) {
        add_id_to_freelist(i,tx_freelist);
	if (tx_buffers[i].page == NULL)
	    tx_buffers[i].page = (char*)alloc_page();
    }

    for(i=0;i<NET_RX_RING_SIZE;i++) {
        add_id_to_freelist(i,rx_freelist);
	if (rx_buffers[i].page == NULL)
	    rx_buffers[i].page = (char*)alloc_page();
    }

}

static inline void alloc_rings(struct net_info *info)
{
    struct netif_tx_sring *txs;
    struct netif_rx_sring *rxs;

    if (!info->rings) {
	txs = (struct netif_tx_sring*) alloc_page();
	rxs = (struct netif_rx_sring *) alloc_page();
	memset(txs,0,PAGE_SIZE);
	memset(rxs,0,PAGE_SIZE);
    } else {
	BUG();
	return;
    }

    SHARED_RING_INIT(txs);
    SHARED_RING_INIT(rxs);
    FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
    FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);

    info->tx_ring_ref = gnttab_grant_access(0,virt_to_mfn(txs),0);
    info->rx_ring_ref = gnttab_grant_access(0,virt_to_mfn(rxs),0);

}

static inline int alloc_evtchn(struct net_info *info)
{
    int retval;
    evtchn_alloc_unbound_t op;
    op.dom = DOMID_SELF;
    op.remote_dom = 0;

    retval = HYPERVISOR_event_channel_op(EVTCHNOP_alloc_unbound, &op);

    clear_evtchn(op.port);        /* Without, handler gets invoked now! */
    info->local_port = bind_evtchn(op.port, ANY_CPU, netfront_handler, NULL);
    info->evtchn = op.port;

    return retval;
}

USED static void netfront_unmap_rx_buffers(void)
{
    int i, notify;
    struct net_info *np = &net_info;
    for (i = 0; i < NET_RX_RING_SIZE; i++)
    {
        struct net_buffer* buf = &rx_buffers[i];
	gnttab_end_transfer(buf->gref);
	gnttab_end_access(buf->gref);
    }

    np->rx.req_prod_pvt = 0;

    RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->rx, notify);

    if (notify)
        notify_remote_via_evtchn(np->evtchn);

    np->rx.sring->rsp_event = np->rx.rsp_cons + 1;

}

static void init_rx_buffers(void)
{
    struct net_info* np = &net_info;
    int i, requeue_idx;
    netif_rx_request_t *req;
    int notify;

    /* Rebuild the RX buffer freelist and the RX ring itself. */
    if (trace_net())
	tprintk("netfront map %d pages\n", NET_RX_RING_SIZE);
    for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++)
    {
        struct net_buffer* buf = &rx_buffers[requeue_idx];
        req = RING_GET_REQUEST(&np->rx, requeue_idx);

        buf->gref = req->gref =
            gnttab_grant_access(0,virt_to_mfn(buf->page),0);

        req->id = requeue_idx;

        requeue_idx++;
    }

    np->rx.req_prod_pvt = requeue_idx;

    RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->rx, notify);

    if (notify)
        notify_remote_via_evtchn(np->evtchn);

    np->rx.sring->rsp_event = np->rx.rsp_cons + 1;
}

static char *nf_explore(void)
{
    char *first;
    char *msg;
    char **dirs;
    int i;

    msg = xenbus_ls(XBT_NIL, DEVICE_STRING, &dirs);
    if (msg) {
	free(msg);
	return NULL;
    }

    for (i=0; dirs[i]; i++) {
	if(i>0)
	    free(dirs[i]);
    }
    if (i==0)
	return NULL;

    first = dirs[0];
    free(dirs);
    return first;
}

static void init_netfront(void)
{
    xenbus_transaction_t xbt;
    struct net_info* info = &net_info;
    char* err;
    char* message=NULL;
    char nodename[MAX_PATH];
    int retry=0;
    char* mac;
    char* msg;
    char* nic;
    char *device;

    if (trace_net())
	tprintk("Initialising netfront\n");

    device = nf_explore();
    if (!device) {
	if (trace_net())
	    tprintk("%s no devices found\n", __FUNCTION__);
	goto out_err;
    }

    info->device_id = (int)simple_strtol(device, NULL, 10);
    snprintf(nodename, MAX_PATH, "%s/%s", DEVICE_STRING, device);

    alloc_buffers();

    alloc_rings(info);

    BUG_ON(alloc_evtchn(info));

again:
    err = xenbus_transaction_start(&xbt);
    if (err) {
        tprintk("starting transaction\n");
    }

    err = xenbus_printf(xbt, nodename, "tx-ring-ref","%u",
                info->tx_ring_ref);
    if (err) {
	free(err);
        message = "writing tx ring-ref";
        goto abort_transaction;
    }
    err = xenbus_printf(xbt, nodename, "rx-ring-ref","%u",
                info->rx_ring_ref);
    if (err) {
	free(err);
        message = "writing rx ring-ref";
        goto abort_transaction;
    }
    err = xenbus_printf(xbt, nodename,
                "event-channel", "%u", info->evtchn);
    if (err) {
	free(err);
        message = "writing event-channel";
        goto abort_transaction;
    }

    err = xenbus_printf(xbt, nodename, "request-rx-copy", "%u", 1);

    if (err) {
	free(err);
        message = "writing request-rx-copy";
        goto abort_transaction;
    }

    err = xenbus_printf(xbt, nodename, "state", "%u", 4); /* connected */
    if(err) {
	free(err);
    }

    err = xenbus_transaction_end(xbt, 0, &retry);
    if (retry) {
            goto again;
        tprintk("completing transaction\n");
    } else if (err)
	free(err);

    goto done;

abort_transaction:
    err = xenbus_transaction_end(xbt, 1, &retry);
    if (err)
	free(err);
    goto out_err_free;

done:

    snprintf(nodename, MAX_PATH, "%s/%s/backend", DEVICE_STRING, device);
    msg = xenbus_read(XBT_NIL, nodename, &backend);
    if (msg) {
	if (trace_net())
	    tprintk("%s %d ERROR reading xenbus: %s\n", __FILE__, __LINE__, msg);
	free(msg);
	goto out_err_free;
    }

    snprintf(nodename, MAX_PATH, "%s/%s/mac", DEVICE_STRING, device);
    msg = xenbus_read(XBT_NIL, nodename, &mac);
    if (msg) {
	if (trace_net())
	    tprintk("%s %d ERROR reading xenbus: %s\n", __FILE__, __LINE__, msg);
	free(msg);
	goto out_err_free;
    }

    if ((backend == NULL) || (mac == NULL)) {
        struct evtchn_close op = { info->local_port };
        if (trace_net()) tprintk("%s: backend/mac failed\n", __func__);
        unbind_evtchn(info->evtchn);
        HYPERVISOR_event_channel_op(EVTCHNOP_close, &op);
	goto out_err_free;
    }

    if (trace_net()) tprintk("backend at %s\n",backend);
    if (trace_net()) tprintk("mac is %s\n",mac);

    /* This seems to be Solaris xVM specific, so no error if it isn't found.
       It's mainly a debugging aid for snooping the vnic */
    snprintf(nodename, MAX_PATH, "%s/nic", backend);
    msg = xenbus_read(XBT_NIL, nodename, &nic);
    if (msg) {
	// printk("%s %d ERROR reading xenbus: %s\n", __FILE__, __LINE__, msg);
	free(msg);
	nic = "unknown";
    }
    if (trace_net())
	tprintk("nic is %s\n",nic);

    snprintf(nodename, MAX_PATH, "%s/state", backend);

    msg = xenbus_watch_path(XBT_NIL, nodename, WATCH_TOKEN);
    if (msg) {
	free(msg);
    }

    xenbus_wait_for_value(WATCH_TOKEN, nodename,"4");

    if (trace_net()) tprintk("*********** connected to backend ***************\n");

    init_rx_buffers();

    unsigned char rawmac[6];
        /* Special conversion specifier 'hh' needed for __ia64__. Without
           this kernel panics with 'Unaligned reference'. */
    sscanf(mac,"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
            &rawmac[0],
            &rawmac[1],
            &rawmac[2],
            &rawmac[3],
            &rawmac[4],
            &rawmac[5]);

    spin_lock(&net_info_lock);
    info->state = ST_READY;
    spin_unlock(&net_info_lock);

    if (trace_net())
	tprintk("** call guk_net_app_main **\n");
    guk_net_app_main(rawmac, nic);

    free(device);
    return;

out_err_free:
    free(device);
out_err:
    guk_net_app_main(NULL, NULL);
    return;
}

void guk_netfront_xmit(unsigned char* data,int len)
{
    int flags;
    struct net_info* info = &net_info;
    struct netif_tx_request *tx;
    RING_IDX i;
    int notify;
    int id = get_id_from_freelist(tx_freelist);
    struct net_buffer* buf = &tx_buffers[id];
    void* page = buf->page;

    spin_lock_irqsave(&net_info_lock, flags);
    if (net_info.state != ST_READY) {
	spin_unlock_irqrestore(&net_info_lock, flags);
	return;
    }

    i  = info->tx.req_prod_pvt;
    tx = RING_GET_REQUEST(&info->tx, i);

    memcpy(page,data,len);

    buf->gref =
        tx->gref = gnttab_grant_access(0,virt_to_mfn(page),0);

    tx->offset=0;
    tx->size = len;
    tx->flags=0;
    tx->id = id;
    info->tx.req_prod_pvt = i + 1;

    wmb();
    RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->tx, notify);

    if(notify)
	notify_remote_via_evtchn(info->evtchn);

    //network_tx_buf_gc();

    spin_unlock_irqrestore(&net_info_lock, flags);
}

static int netfront_shutdown(void)
{
    long flags;

    spin_lock_irqsave(&net_info_lock, flags);
    if (backend == NULL || net_info.state != ST_READY) {
	spin_unlock_irqrestore(&net_info_lock, flags);
	return 1;
    }

    unbind_evtchn(net_info.local_port); /* no more interrupts from the network */
    net_info.state = ST_SUSPENDING;
    spin_unlock_irqrestore(&net_info_lock, flags);

    if (trace_net())
	tprintk("close network: backend at %s\n",backend);

    char* err;
    char nodename[MAX_PATH];

    snprintf(nodename, MAX_PATH, "%s/%d", DEVICE_STRING, net_info.device_id);
    err = xenbus_printf(XBT_NIL, nodename, "state", "%u", 6); /* closing */
    if(err) {
	free(err);
    }

    snprintf(nodename, MAX_PATH, "%s/state", backend);
    xenbus_wait_for_value(WATCH_TOKEN, nodename,"6");

    snprintf(nodename, MAX_PATH, "%s/%d", DEVICE_STRING, net_info.device_id);
    err = xenbus_printf(XBT_NIL, nodename, "state", "%u", 1);
    if(err) {
	free(err);
    }

    snprintf(nodename, MAX_PATH, "%s/state", backend);
    xenbus_wait_for_value(WATCH_TOKEN, nodename,"2");

    netfront_unmap_rx_buffers();

    xenbus_rm_watch(WATCH_TOKEN);
    spin_lock(&net_info_lock);
    net_info.state = ST_SUSPENDED;
    spin_unlock(&net_info_lock);
    return 0;

}

static void netfront_thread(void *p)
{
    init_netfront();
    if (trace_net())
	tprintk("netfront thread terminating\n");
}

static int start_netfront_thread(void *arg)
{
    create_thread("netfront", netfront_thread, UKERNEL_FLAG, NULL);
    return 0;
}

static int netfront_suspend(void)
{
    return netfront_shutdown();
}

static int netfront_resume(void)
{
    return start_netfront_thread(NULL);
}

static struct service nf_service = {
    .name = "netfront service",
    .init = start_netfront_thread,
    .shutdown = netfront_shutdown,
    .suspend = netfront_suspend,
    .resume = netfront_resume,
    .arg = NULL,
};

USED static int init_func(void)
{
    memset(&net_info, 0, sizeof(net_info));
    memset(rx_buffers, 0, sizeof(rx_buffers));
    memset(tx_buffers, 0, sizeof(tx_buffers));
    register_service(&nf_service);
    return 0;
}
DECLARE_INIT(init_func);


text:
extern crate getopts;
extern crate tempfile;
extern crate rand;

#[macro_use]
extern crate uucore;

use std::env;
use std::io::Write;
use std::path::{PathBuf, is_separator};
use std::mem::forget;
use std::iter;

use rand::Rng;
use tempfile::NamedTempFileOptions;

mod tempdir;

static NAME: &'static str = "mktemp";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static DEFAULT_TEMPLATE: &'static str = "tmp.XXXXXXXXXX";

pub fn uumain(args: Vec<String>) -> i32 {
    let mut opts = getopts::Options::new();
    opts.optflag("d", "directory", "Make a directory instead of a file");
    opts.optflag("u",
                 "dry-run",
                 "do not create anything; merely print a name (unsafe)");
    opts.optflag("q", "quiet", "Fail silently if an error occurs.");
    opts.optopt("", "suffix", "append SUFF to TEMPLATE; SUFF must not contain a path separator. This option is implied if TEMPLATE does not end with X.", "SUFF");
    opts.optopt("p", "tmpdir", "interpret TEMPLATE relative to DIR; if DIR is not specified, use $TMPDIR if set, else /tmp.  With this option, TEMPLATE  must  not  be  an  absolute name; unlike with -t, TEMPLATE may contain slashes, but mktemp creates only the final component", "DIR");
    // deprecated option of GNU coreutils
    //    opts.optflag("t", "", "Generate a template (using the supplied prefix and TMPDIR if set) to create a filename template");
    opts.optflag("", "help", "Print this help and exit");
    opts.optflag("", "version", "print the version and exit");

    // >> early return options
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => crash!(1, "Invalid options\n{}", f),
    };

    if matches.opt_present("help") {
        print_help(&opts);
        return 0;
    }
    if matches.opt_present("version") {
        println!("{} {}", NAME, VERSION);
        return 0;
    }

    if 1 < matches.free.len() {
        crash!(1, "Too many templates");
    }
    // <<

    let make_dir = matches.opt_present("directory");
    let dry_run = matches.opt_present("dry-run");
    let suffix_opt = matches.opt_str("suffix");
    let suppress_file_err = matches.opt_present("quiet");

    let template = if matches.free.is_empty() {
        DEFAULT_TEMPLATE
    } else {
        &matches.free[0][..]
    };

    let (prefix, rand, suffix) = match parse_template(template) {
        Some((p, r, s)) => {
            match suffix_opt {
                Some(suf) => {
                    if s == "" {
                        (p, r, suf)
                    } else {
                        crash!(1,
                               "Template should end with 'X' when you specify suffix option.")
                    }
                }
                None => (p, r, s.to_owned()),
            }
        }
        None => ("", 0, "".to_owned()),
    };

    if rand < 3 {
        crash!(1, "Too few 'X's in template")
    }

    if suffix.chars().any(is_separator) {
        crash!(1, "suffix cannot contain any path separators");
    }

    let tmpdir = match matches.opt_str("tmpdir") {
        Some(s) => {
            if PathBuf::from(prefix).is_absolute() {
                show_info!("invalid template, '{}'; with --tmpdir, it may not be absolute", template);
                return 1;
            }
            PathBuf::from(s)
        }
        None => env::temp_dir(),
    };

    if dry_run {
        dry_exec(tmpdir, prefix, rand, &suffix)
    } else {
        exec(tmpdir, prefix, rand, &suffix, make_dir, suppress_file_err)
    }

}

fn print_help(opts: &getopts::Options) {
    let usage = format!(" Create a temporary file or directory, safely, and print its name.
TEMPLATE must contain at least 3 consecutive 'X's in last component.
If TEMPLATE is not specified, use {}, and --tmpdir is implied",
                        DEFAULT_TEMPLATE);

    println!("{} {}", NAME, VERSION);
    println!("SYNOPSIS");
    println!("  {} [OPTION]... [FILE]", NAME);
    println!("Usage:");
    print!("{}", opts.usage(&usage[..]));
}

fn parse_template(temp: &str) -> Option<(&str, usize, &str)> {
    let right = match temp.rfind('X') {
        Some(r) => r + 1,
        None => return None,
    };
    let left = temp[..right].rfind(|c| c != 'X').map_or(0, |i| i + 1);
    let prefix = &temp[..left];
    let rand = right - left;
    let suffix = &temp[right..];
    Some((prefix, rand, suffix))
}

pub fn dry_exec(mut tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str) -> i32 {
    let len = prefix.len() + suffix.len() + rand;
    let mut buf = String::with_capacity(len);
    buf.push_str(prefix);
    buf.extend(iter::repeat('X').take(rand));
    buf.push_str(suffix);

    // Randomize.
    unsafe {
        // We guarantee utf8.
        let bytes = &mut buf.as_mut_vec()[prefix.len()..prefix.len() + rand];
        rand::thread_rng().fill_bytes(bytes);
        for byte in bytes.iter_mut() {
            *byte = match *byte % 62 {
                v @ 0...9 => (v + '0' as u8),
                v @ 10...35 => (v - 10 + 'a' as u8),
                v @ 36...61 => (v - 36 + 'A' as u8),
                _ => unreachable!(),
            }
        }
    }
    tmpdir.push(String::from(buf));
    println!("{}", tmpdir.display());
    0
}

fn exec(tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str, make_dir: bool, quiet: bool) -> i32 {
    if make_dir {
        match tempdir::new_in(&tmpdir, prefix, rand, suffix) {
            Ok(ref f) => {
                println!("{}", f);
                return 0;
            }
            Err(e) => {
                if !quiet {
                    show_info!("{}", e);
                }
                return 1;
            }
        }
    }

    let tmpfile = NamedTempFileOptions::new()
        .prefix(prefix)
        .rand_bytes(rand)
        .suffix(suffix)
        .create_in(tmpdir);

    let tmpfile = match tmpfile {
        Ok(f) => f,
        Err(e) => {
            if !quiet {
                show_info!("failed to create tempfile: {}", e);
            }
            return 1;
        }
    };

    let tmpname = tmpfile.path()
                         .to_string_lossy()
                         .to_string();

    println!("{}", tmpname);

    // CAUTION: Not to call `drop` of tmpfile, which removes the tempfile,
    // I call a dangerous function `forget`.
    forget(tmpfile);

    0
}