text:
E2Lib.RegisterExtension( "holo", true, "Allows E2 to create and manipulate non-solid models." )

-- -----------------------------------------------------------------------------

local function checkOwner(self)
	return IsValid(self.player)
end

-- -----------------------------------------------------------------------------

local wire_holograms_max = CreateConVar( "wire_holograms_max", "250", {FCVAR_ARCHIVE} )
local wire_holograms_spawn_amount = CreateConVar( "wire_holograms_spawn_amount", "15", {FCVAR_ARCHIVE} ) -- This limit resets once a second
local wire_holograms_burst_amount = CreateConVar( "wire_holograms_burst_amount", "80", {FCVAR_ARCHIVE} ) -- This limit goes down first, resets every burst_delay
local wire_holograms_burst_delay = CreateConVar( "wire_holograms_burst_delay", "10", {FCVAR_ARCHIVE} )
local wire_holograms_max_clips = CreateConVar( "wire_holograms_max_clips", "5", {FCVAR_ARCHIVE} ) -- Don't set higher than 16 without editing net.Start("wire_holograms_clip")
local wire_holograms_modelany = CreateConVar( "wire_holograms_modelany", "0", {FCVAR_ARCHIVE},
	"1: Allow holograms to use models besides the official hologram models." ..
	"2: Allow holograms to additionally use models not present on the server." )
local wire_holograms_size_max = CreateConVar( "wire_holograms_size_max", "50", {FCVAR_ARCHIVE} )
util.AddNetworkString("wire_holograms_set_visible")
util.AddNetworkString("wire_holograms_clip")
util.AddNetworkString("wire_holograms_set_scale")
util.AddNetworkString("wire_holograms_set_bone_scale")
util.AddNetworkString("wire_holograms_set_player_color")

-- context = chip.context = self
-- uid = context.uid = self.uid = chip.uid = player:UniqueID()
-- Holo = { ent = prop, scale = scale, e2owner = context }
-- E2HoloRepo[uid][-index] = Holo <-- global holos
-- E2HoloRepo[uid][Holo] = Holo <-- local holos
-- context.data.holos[index] = Holo <-- local holos

local E2HoloRepo = {}
local PlayerAmount = {}
local BlockList = {}

local ModelList = {
	["cone"]              = "cone",
	["cplane"]			  = "cplane",
	["cube"]              = "cube",
	["cylinder"]          = "cylinder",
	["hq_cone"]           = "hq_cone",
	["hq_cylinder"]       = "hq_cylinder",
	["hq_dome"]           = "hq_dome",
	["hq_hdome"]          = "hq_hdome",
	["hq_hdome_thick"]    = "hq_hdome_thick",
	["hq_hdome_thin"]     = "hq_hdome_thin",
	["hq_icosphere"]      = "hq_icosphere",
	["hq_sphere"]         = "hq_sphere",
	["hq_torus"]          = "hq_torus",
	["hq_torus_thick"]    = "hq_torus_thick",
	["hq_torus_thin"]     = "hq_torus_thin",
	["hq_torus_oldsize"]  = "hq_torus_oldsize",
	["hq_tube"]           = "hq_tube",
	["hq_tube_thick"]     = "hq_tube_thick",
	["hq_tube_thin"]      = "hq_tube_thin",
	["hq_stube"]          = "hq_stube",
	["hq_stube_thick"]    = "hq_stube_thick",
	["hq_stube_thin"]     = "hq_stube_thin",
	["icosphere"]         = "icosphere",
	["icosphere2"]        = "icosphere2",
	["icosphere3"]        = "icosphere3",
	["plane"]             = "plane",
	["prism"]             = "prism",
	["pyramid"]           = "pyramid",
	["sphere"]            = "sphere",
	["sphere2"]           = "sphere2",
	["sphere3"]           = "sphere3",
	["tetra"]             = "tetra",
	["torus"]             = "torus",
	["torus2"]            = "torus2",
	["torus3"]            = "torus3",

	["rcube"]             = "rcube",
	["rcube_thick"]       = "rcube_thick",
	["rcube_thin"]     	  = "rcube_thin",
	["hq_rcube"]          = "hq_rcube",
	["hq_rcube_thick"]    = "hq_rcube_thick",
	["hq_rcube_thin"]     = "hq_rcube_thin",
	["rcylinder"]         = "rcylinder",
	["rcylinder_thick"]   = "rcylinder_thick",
	["rcylinder_thin"]    = "rcylinder_thin",
	["hq_rcylinder"]      = "hq_rcylinder",
	["hq_rcylinder_thick"]= "hq_rcylinder_thick",
	["hq_rcylinder_thin"] = "hq_rcylinder_thin",
	["hq_cubinder"]       = "hq_cubinder",
	["hexagon"]           = "hexagon",
	["octagon"]           = "octagon",
	["right_prism"]       = "right_prism",

	-- Removed models with their replacements

	["dome"]             = "hq_dome",
	["dome2"]            = "hq_hdome",
	["hqcone"]           = "hq_cone",
	["hqcylinder"]       = "hq_cylinder",
	["hqcylinder2"]      = "hq_cylinder",
	["hqicosphere"]      = "hq_icosphere",
	["hqicosphere2"]     = "hq_icosphere",
	["hqsphere"]         = "hq_sphere",
	["hqsphere2"]        = "hq_sphere",
	["hqtorus"]          = "hq_torus_oldsize",
	["hqtorus2"]         = "hq_torus_oldsize",

	-- HQ models with their short names

	["hqhdome"]          = "hq_hdome",
	["hqhdome2"]         = "hq_hdome_thin",
	["hqhdome3"]         = "hq_hdome_thick",
	["hqtorus3"]         = "hq_torus_thick",
	["hqtube"]           = "hq_tube",
	["hqtube2"]          = "hq_tube_thin",
	["hqtube3"]          = "hq_tube_thick",
	["hqstube"]          = "hq_stube",
	["hqstube2"]         = "hq_stube_thin",
	["hqstube3"]         = "hq_stube_thick",
	["hqrcube"]          = "hq_rcube",
	["hqrcube2"]         = "hq_rcube_thick",
	["hqrcube3"]         = "hq_rcube_thin",
	["hqrcylinder"]      = "hq_rcylinder",
	["hqrcylinder2"]     = "hq_rcylinder_thin",
	["hqrcylinder3"]     = "hq_rcylinder_thick",
	["hqcubinder"]       = "hq_cubinder"
}

-- Return the absolute model path
local function modelPath(name)
	return "models/holograms/" .. name .. ".mdl"
end

local added = {}
local pathLookup = {}

for _,v in pairs( ModelList ) do
	if not added[v] then
		local path = modelPath(v)

		pathLookup[path] = true
		util.PrecacheModel(path)
		-- resource.AddSingleFile( "models/holograms/" .. v .. ".mdl" )

		added[v] = true
	end
end

local function GetModel(self, model, skin)
	skin = skin or 0

	if ModelList[model] then
		model = modelPath(ModelList[model])

	-- If this model isn't already the absolute path of a default model, and only default models are allowed
	elseif not pathLookup[model] and wire_holograms_modelany:GetInt() == 0 then
 		return false
	end

	if wire_holograms_modelany:GetInt() ~= 2 and not WireLib.CanModel(self.player, model, skin) then
		-- Check if the model is at least valid
		if not WireLib.CanModel(self.player, model, 0) then
			return false
		end

		-- The model was valid however the skin was not. Go to default skin
		skin = 0
	end

	return model, skin
end

-- -----------------------------------------------------------------------------

local scale_queue = {}
local bone_scale_queue = {}
local clip_queue = {}
local vis_queue = {}
local player_color_queue = {}

local function add_queue( queue, ply, data )
	local plyqueue = queue[ply]
	if not plyqueue then
		plyqueue = {}
		queue[ply] = plyqueue
	end
	if #plyqueue==wire_holograms_max:GetInt() then return end
	plyqueue[#plyqueue+1] = data
end

local function flush_scale_queue(queue, recipient)
	if not queue then queue = scale_queue end
	if not next(queue) then return end

	net.Start("wire_holograms_set_scale")
		for _, plyqueue in pairs(queue) do
			for _,Holo,scale in ipairs_map(plyqueue, unpack) do
				net.WriteUInt(Holo.ent:EntIndex(), 16)
				net.WriteFloat(scale.x)
				net.WriteFloat(scale.y)
				net.WriteFloat(scale.z)
			end
		end
		net.WriteUInt(0, 16)
	if recipient then net.Send(recipient) else net.Broadcast() end
end

local function flush_bone_scale_queue(queue, recipient)
	if not queue then queue = bone_scale_queue end
	if not next(queue) then return end

	net.Start("wire_holograms_set_bone_scale")
	for _, plyqueue in pairs(queue) do
		for _,Holo,bone,scale in ipairs_map(plyqueue, unpack) do
			net.WriteUInt(Holo.ent:EntIndex(), 16)
			net.WriteUInt(bone + 1, 16) -- using +1 to be able reset holo bones scale with -1 and not use signed int
			net.WriteFloat(scale.x)
			net.WriteFloat(scale.y)
			net.WriteFloat(scale.z)
		end
	end
	net.WriteUInt(0, 16)
	net.WriteUInt(0, 16)
	if recipient then net.Send(recipient) else net.Broadcast() end
end

local function flush_clip_queue(queue, recipient)
	if not queue then queue = clip_queue end
	if not next(queue) then return end

	net.Start("wire_holograms_clip")
		for _, plyqueue in pairs(queue) do
			for _,Holo,clip in ipairs_map(plyqueue, unpack) do
				if clip and clip.index then
					net.WriteUInt(Holo.ent:EntIndex(), 16)
					net.WriteUInt(clip.index, 4) -- 4: absolute highest wire_holograms_max_clips is thus 16
					if clip.enabled ~= nil then
						net.WriteBit(true)
						net.WriteBit(clip.enabled)
					elseif clip.origin and clip.normal and clip.isglobal then
						net.WriteBit(false)
						net.WriteVector(clip.origin)
						net.WriteFloat(clip.normal.x) net.WriteFloat(clip.normal.y) net.WriteFloat(clip.normal.z)
						net.WriteBit(clip.isglobal ~= 0)
					end
				end
			end
		end
		net.WriteUInt(0, 16)
	if recipient then net.Send(recipient) else net.Broadcast() end
end

local function flush_vis_queue()
	if not next(vis_queue) then return end

	for ply,tbl in pairs( vis_queue ) do
		if IsValid( ply ) and #tbl > 0 then
			net.Start("wire_holograms_set_visible")
				for _,Holo,visible in ipairs_map(tbl, unpack) do
					net.WriteUInt(Holo.ent:EntIndex(), 16)
					net.WriteBit(visible)
				end
				net.WriteUInt(0, 16)
			net.Send(ply)
		end
	end
end

local function flush_player_color_queue()
	if not next(player_color_queue) then return end

	net.Start("wire_holograms_set_player_color")
		for _, plyqueue in pairs(player_color_queue) do
			for _,Holo,color in ipairs_map(plyqueue, unpack) do
				net.WriteUInt(Holo.ent:EntIndex(), 16)
				net.WriteVector(color)
			end
		end
		net.WriteUInt(0, 16)
	net.Broadcast()
end

registerCallback("postexecute", function(self)
	flush_scale_queue()
	flush_bone_scale_queue()
	flush_clip_queue()
	flush_vis_queue()
	flush_player_color_queue()

	scale_queue = {}
	bone_scale_queue = {}
	clip_queue = {}
	vis_queue = {}
	player_color_queue = {}
end)

local function rescale(Holo, scale, bone)
	local maxval = wire_holograms_size_max:GetInt()
	local minval = -maxval

	if scale then
		local x = math.Clamp( scale[1], minval, maxval )
		local y = math.Clamp( scale[2], minval, maxval )
		local z = math.Clamp( scale[3], minval, maxval )
		local scale = Vector(x, y, z)

		if Holo.scale ~= scale then
			add_queue( scale_queue, Holo.e2owner, { Holo, scale } )
			Holo.scale = scale
		end
	end

	if bone then
		Holo.bone_scale = Holo.bone_scale or {}
		if #bone == 2 then
			local bidx, b_scale = bone[1], bone[2]
			local x = math.Clamp( b_scale[1], minval, maxval )
			local y = math.Clamp( b_scale[2], minval, maxval )
			local z = math.Clamp( b_scale[3], minval, maxval )
			local scale = Vector(x, y, z)

			add_queue( bone_scale_queue, Holo.e2owner, { Holo, bidx, scale } )
			Holo.bone_scale[bidx] =  scale
		else  -- reset holo bone scale
			add_queue( bone_scale_queue, Holo.e2owner, { Holo, -1, Vector(0,0,0) } )
			Holo.bone_scale = {}
		end
	end
end

local function check_clip(Holo, idx)
	Holo.clips = Holo.clips or {}

	if idx > 0 and idx <= wire_holograms_max_clips:GetInt() then
		Holo.clips[idx] = Holo.clips[idx] or {}
		local clip = Holo.clips[idx]

		clip.enabled = clip.enabled or false
		clip.origin = clip.origin or Vector(0,0,0)
		clip.normal = clip.normal or Vector(0,0,0)
		clip.isglobal = clip.isglobal or false

		return clip
	end

	return nil
end

local function enable_clip(Holo, idx, enabled)
	local clip = check_clip(Holo, idx)

	if clip and clip.enabled ~= enabled then
		clip.enabled = enabled

		add_queue( clip_queue, Holo.e2owner, { Holo,
			{
				index = idx,
				enabled = enabled
			}}
		)
	end
end

local function set_clip(Holo, idx, origin, normal, isglobal)
	local clip = check_clip(Holo, idx)

	if clip and (clip.origin ~= origin or clip.normal ~= normal or clip.isglobal ~= isglobal) then
		clip.origin = origin
		clip.normal = normal
		clip.isglobal = isglobal

		add_queue( clip_queue, Holo.e2owner, { Holo,
			{
				index = idx,
				origin = origin,
				normal = normal,
				isglobal = isglobal
			}}
		)
	end
end

local function set_visible(Holo, players, visible)
	if not Holo.visible then Holo.visible = {} end
	visible = (visible == 1) or (visible == true)
	for _,ply in pairs( players ) do
		if IsValid( ply ) and ply:IsPlayer() and Holo.visible[ply] ~= visible then
			Holo.visible[ply] = visible
			add_queue( vis_queue, ply, { Holo, visible } )
		end
	end
end

local function reset_clholo(Holo, scale)
	if Holo.clips then
		for cidx, clip in pairs(Holo.clips) do
			if clip.enabled then
				add_queue(clip_queue, Holo.e2owner, { Holo,
					{
						index = cidx,
						enabled = false
					}}
				)
			end
		end
		Holo.clips = {}
	end
	rescale(Holo, scale, {})
	if Holo.visible then
		for ply, state in pairs(Holo.visible) do
			if not state then
				add_queue(vis_queue, ply, { Holo, true })
			end
		end
		Holo.visible = {}
	end
end

local function set_player_color(Holo, color)
	add_queue(player_color_queue, Holo.e2owner, { Holo, color })
end

hook.Add( "PlayerInitialSpawn", "wire_holograms_set_vars", function(ply)
	local s_queue = {}
	local b_s_queue = {}
	local c_queue = {}

	for pl_uid,rep in pairs( E2HoloRepo ) do
		for k,Holo in pairs( rep ) do
			if Holo and IsValid(Holo.ent) then
				local clips = Holo.clips
				local scale = Holo.scale
				local bone_scales = Holo.bone_scale

				table.insert(s_queue, { Holo, scale })

				if bone_scales and table.Count(bone_scales) > 0 then
					for bidx,b_scale in pairs(bone_scales) do
						table.insert(b_s_queue, { Holo, bidx, b_scale })
					end
				end

				if clips and table.Count(clips) > 0 then
					for cidx,clip in pairs(clips) do
						if clip.enabled then
							table.insert(c_queue, {
								Holo,
								{
									index = cidx,
									enabled = clip.enabled
								}
							} )
						end

						if clip.origin and clip.normal and clip.isglobal ~= nil then
							table.insert(c_queue, {
								Holo,
								{
									index = cidx,
									origin = clip.origin,
									normal = clip.normal,
									isglobal = clip.isglobal
								}
							} )
						end
					end
				end
			end
		end
	end

	flush_scale_queue({[ply] = s_queue}, ply)
	flush_bone_scale_queue({[ply] = b_s_queue}, ply)
	flush_clip_queue({[ply] = c_queue}, ply)
end)

-- -----------------------------------------------------------------------------

local function MakeHolo(Player, Pos, Ang, model)
	local prop = ents.Create( "gmod_wire_hologram" )
	E2Lib.setPos(prop, Pos)
	E2Lib.setAng(prop, Ang)
	prop:SetModel(model)
	prop:SetPlayer(Player)
	prop:SetNWInt("ownerid", Player:UserID())

	return prop
end

-- Returns the hologram with the given index or nil if it doesn't exist.
local function CheckIndex(self, index)
	index = index - index % 1
	local Holo
	if index<0 then
		Holo = E2HoloRepo[self.uid][-index]
	else
		Holo = self.data.holos[index]
	end
	if not Holo or not IsValid(Holo.ent) then return nil end
	return Holo
end

-- Sets the given index to the given hologram.
local function SetIndex(self, index, Holo)
	index = index - index % 1
	local rep = E2HoloRepo[self.uid]
	if index<0 then
		rep[-index] = Holo
	else
		local holos = self.data.holos
		if holos[index] then rep[holos[index]] = nil end
		holos[index] = Holo
		if Holo then rep[Holo] = Holo end
	end
end

local function CreateHolo(self, index, pos, scale, ang, color, model)
	if not pos   then pos   = self.entity:GetPos() end
	if not scale then scale = Vector(1,1,1) end
	if not ang   then ang   = self.entity:GetAngles() end

	model = GetModel(self, model or "cube") or "models/holograms/cube.mdl"

	local Holo = CheckIndex(self, index)
	if not Holo then
		Holo = {}
		SetIndex(self, index, Holo)
	end

	local prop

	if IsValid(Holo.ent) then
		prop = Holo.ent
		E2Lib.setPos(prop, pos)
		E2Lib.setAng(prop, ang)
		prop:SetModel( model )
	else
		prop = MakeHolo(self.player, pos, ang, model, {}, {})
		prop:Activate()
		prop:Spawn()
		prop:SetSolid(SOLID_NONE)
		prop:SetMoveType(MOVETYPE_NONE)
		PlayerAmount[self.uid] = PlayerAmount[self.uid]+1
		Holo.ent = prop
		Holo.e2owner = self

		prop:CallOnRemove( "holo_cleanup", function( ent, self, index ) --Give the player more holograms if we get removed
			local Holo = CheckIndex( self, index )
			if not Holo then return end

			PlayerAmount[self.uid] = PlayerAmount[self.uid] - 1
			SetIndex( self, index, nil )
		end, self, index )
	end

	if not IsValid(prop) then return nil end
	if color then prop:SetColor(Color(color[1],color[2],color[3],255)) end

	reset_clholo(Holo, scale) -- Reset scale, clips, and visible status

	return prop
end

-- -----------------------------------------------------------------------------

local function CheckSpawnTimer( self, readonly )
	local holo = self.data.holo
	if CurTime() >= holo.nextSpawn then
		holo.nextSpawn = CurTime()+1
		if CurTime() >= holo.nextBurst then
			holo.remainingSpawns = wire_holograms_burst_amount:GetInt()
		elseif holo.remainingSpawns < wire_holograms_spawn_amount:GetInt() then
			holo.remainingSpawns = wire_holograms_spawn_amount:GetInt()
		end
	end

	if CurTime() >= holo.nextBurst then
		holo.nextBurst = CurTime() + wire_holograms_burst_delay:GetInt()
	end

	if holo.remainingSpawns > 0 then
		if not readonly then
			holo.remainingSpawns = holo.remainingSpawns - 1
		end
		return true
	else
		return false
	end
end

-- Removes all holograms from the given chip.
local function clearholos(self)
	-- delete local holos
	for index,Holo in pairs(self.data.holos) do
		if IsValid(Holo.ent) then Holo.ent:Remove() end
	end

	-- delete global holos owned by this chip
	local rep = E2HoloRepo[self.uid]
	if not rep then return end
	for index,Holo in ipairs(rep) do
		if Holo.e2owner == self then
			if IsValid(Holo.ent) then Holo.ent:Remove() end
		end
	end
end

local function clearholos_all(ply_uid)
	if ply_uid == nil then
		for pl_uid, rep in pairs(E2HoloRepo) do clearholos_all(pl_uid) end
		return
	end

	for k,Holo in pairs(E2HoloRepo[ply_uid]) do
		if Holo and IsValid(Holo.ent) then
			Holo.ent:RemoveCallOnRemove( "holo_cleanup" )
			Holo.ent:Remove()
		end
	end

	PlayerAmount[ply_uid] = 0
end

-- -----------------------------------------------------------------------------

__e2setcost(20) -- temporary

e2function entity holoCreate(index, vector position, vector scale, angle ang, vector color, string model)
	if not checkOwner(self) then return end
	if BlockList[self.player:SteamID()] == true or CheckSpawnTimer( self ) == false then return end
	local Holo = CheckIndex(self, index)
	if not Holo and PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then return end

	position = Vector(position[1], position[2], position[3])
	ang = Angle(ang[1], ang[2], ang[3])
	local ret = CreateHolo(self, index, position, scale, ang, color, model)
	if IsValid(ret) then return ret end
end

e2function entity holoCreate(index, vector position, vector scale, angle ang, vector color)
	if not checkOwner(self) then return end
	if BlockList[self.player:SteamID()] == true or CheckSpawnTimer( self ) == false then return end
	local Holo = CheckIndex(self, index)
	if not Holo and PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then return end

	position = Vector(position[1], position[2], position[3])
	ang = Angle(ang[1], ang[2], ang[3])
	local ret = CreateHolo(self, index, position, scale, ang, color)
	if IsValid(ret) then return ret end
end

e2function entity holoCreate(index, vector position, vector scale, angle ang)
	if not checkOwner(self) then return end
	if BlockList[self.player:SteamID()] == true or CheckSpawnTimer( self ) == false then return end
	local Holo = CheckIndex(self, index)
	if not Holo and PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then return end

	position = Vector(position[1], position[2], position[3])
	ang = Angle(ang[1], ang[2], ang[3])
	local ret = CreateHolo(self, index, position, scale, ang)
	if IsValid(ret) then return ret end
end

e2function entity holoCreate(index, vector position, vector scale)
	if not checkOwner(self) then return end
	if BlockList[self.player:SteamID()] == true or CheckSpawnTimer( self ) == false then return end
	local Holo = CheckIndex(self, index)
	if not Holo and PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then return end

	position = Vector(position[1],position[2],position[3])
	local ret = CreateHolo(self, index, position, scale)
	if IsValid(ret) then return ret end
end

e2function entity holoCreate(index, vector position)
	if not checkOwner(self) then return end
	if BlockList[self.player:SteamID()] == true or CheckSpawnTimer( self ) == false then return end
	local Holo = CheckIndex(self, index)
	if not Holo and PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then return end

	position = Vector(position[1],position[2],position[3])
	local ret = CreateHolo(self, index, position)
	if IsValid(ret) then return ret end
end

e2function entity holoCreate(index)
	if not checkOwner(self) then return end
	if BlockList[self.player:SteamID()] == true or CheckSpawnTimer( self ) == false then return end
	local Holo = CheckIndex(self, index)
	if not Holo and PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then return end

	local ret = CreateHolo(self, index)
	if IsValid(ret) then return ret end
end

e2function void holoDelete(index)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	if IsValid(Holo.ent) then
		Holo.ent:Remove()
	end
end

e2function void holoDeleteAll()
	clearholos(self)
end

e2function void holoDeleteAll( all )
	if all > 0 then
		clearholos_all( self.uid )
	else
		clearholos( self )
	end
end

e2function void holoReset(index, string model, vector scale, vector color, string material)
	model = GetModel(self, model)
	if not model then return end
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetModel(model)
	Holo.ent:SetColor(Color(color[1],color[2],color[3],255))
	E2Lib.setMaterial(Holo.ent, material)

	reset_clholo(Holo, scale) -- Reset scale, clips, and visible status
end

__e2setcost(5)

e2function number holoCanCreate()
	if (not checkOwner(self)) then return 0 end

	if CheckSpawnTimer(self, true) == false or PlayerAmount[self.uid] >= wire_holograms_max:GetInt() then
		return 0
	end

	return 1
end

e2function number holoRemainingSpawns()
	CheckSpawnTimer(self, true)
	return self.data.holo.remainingSpawns
end

e2function number holoAmount()
	return PlayerAmount[self.uid]
end

e2function number holoMaxAmount()
	return wire_holograms_max:GetInt()
end

-- -----------------------------------------------------------------------------

__e2setcost(5) -- temporary

e2function void holoScale(index, vector scale)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	rescale(Holo, scale)
end

e2function vector holoScale(index)
	local Holo = CheckIndex(self, index)
	if not Holo then return {0,0,0} end

	return Holo.scale or {0,0,0} -- TODO: maybe {1,1,1}?
end

e2function void holoScaleUnits(index, vector size)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	local propsize = Holo.ent:OBBMaxs()-Holo.ent:OBBMins()

	local x = size[1] / propsize.x
	local y = size[2] / propsize.y
	local z = size[3] / propsize.z

	rescale(Holo, Vector(x, y, z))
end

e2function vector holoScaleUnits(index)
	local Holo = CheckIndex(self, index)
	if not Holo then return {0,0,0} end

	local scale = Holo.scale or {0,0,0} -- TODO: maybe {1,1,1}?

	local propsize = Holo.ent:OBBMaxs()-Holo.ent:OBBMins()

	return Vector(scale[1] * propsize.x, scale[2] * propsize.y, scale[3] * propsize.z)
end

e2function void holoBoneScale(index, boneindex, vector scale)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	rescale(Holo, nil, {boneindex, scale})
end

e2function void holoBoneScale(index, string bone, vector scale)
	local Holo = CheckIndex(self, index)
	if not Holo then return end
	local boneindex = Holo.ent:LookupBone(bone)
	if boneindex == nil then return end

	rescale(Holo, nil, {boneindex, scale})
end

e2function vector holoBoneScale(index, boneindex)
	local Holo = CheckIndex(self, index)
	if not Holo then return {0,0,0} end
	if table.Count(Holo.bone_scale) <= 0 then return {0,0,0} end

	for bidx,b_scale in pairs(Holo.bone_scale) do
    	if bidx == boneindex then return b_scale end
	end

	return {0,0,0}
end

e2function vector holoBoneScale(index, string bone)
	local Holo = CheckIndex(self, index)
	if not Holo then return {0,0,0} end
	if table.Count(Holo.bone_scale) <= 0 then return {0,0,0} end
	local boneindex = Holo.ent:LookupBone(bone)
	if boneindex == nil then return {0,0,0} end

	for bidx,b_scale in pairs(Holo.bone_scale) do
		if bidx == boneindex then return b_scale end
	end

	return {0,0,0}
end

e2function number holoClipsAvailable()
	return wire_holograms_max_clips:GetInt()
end

e2function void holoClipEnabled(index, enabled) -- Clip at first index
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	if enabled == 1 then
		enable_clip(Holo, 1, true)
	elseif enabled == 0 then
		enable_clip(Holo, 1, false)
	end
end

e2function void holoClipEnabled(index, clipidx, enabled)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	if enabled == 1 then
		enable_clip(Holo, clipidx, true)
	elseif enabled == 0 then
		enable_clip(Holo, clipidx, false)
	end
end

e2function void holoClip(index, vector origin, vector normal, isglobal) -- Clip at first index
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	set_clip(Holo, 1, Vector(origin[1], origin[2], origin[3]), Vector(normal[1], normal[2], normal[3]), isglobal)
end

e2function void holoClip(index, clipidx, vector origin, vector normal, isglobal)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	set_clip(Holo, clipidx, Vector(origin[1], origin[2], origin[3]), Vector(normal[1], normal[2], normal[3]), isglobal)
end

e2function void holoPos(index, vector position)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	E2Lib.setPos(Holo.ent, Vector(position[1],position[2],position[3]))
end

e2function void holoAng(index, angle ang)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	E2Lib.setAng(Holo.ent, Angle(ang[1],ang[2],ang[3]))
end

-- -----------------------------------------------------------------------------

e2function void holoColor(index, vector color)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetColor(Color(color[1],color[2],color[3],Holo.ent:GetColor().a))
end

e2function void holoColor(index, vector4 color)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetColor(Color(color[1],color[2],color[3],color[4]))
	Holo.ent:SetRenderMode(Holo.ent:GetColor().a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA)
end

e2function void holoColor(index, vector color, alpha)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetColor(Color(color[1],color[2],color[3],alpha))
	Holo.ent:SetRenderMode(Holo.ent:GetColor().a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA)
end

e2function void holoAlpha(index, alpha)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	local c = Holo.ent:GetColor()
	c.a = alpha
	Holo.ent:SetColor(c)
	Holo.ent:SetRenderMode(Holo.ent:GetColor().a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA)
end

e2function void holoShadow(index, has_shadow)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:DrawShadow( has_shadow ~= 0 )
end

e2function void holoDisableShading( index, disable )
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetNWBool( "disable_shading", disable == 1 )
end

-- -----------------------------------------------------------------------------

e2function array holoModelList()
	local mlist = {}

	for k,_ in pairs( ModelList ) do
	    mlist[#mlist + 1] = k
	end

	return mlist
end

e2function number holoModelAny()
	return wire_holograms_modelany:GetInt()
end

e2function void holoModel(index, string model)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	model = GetModel(self, model)
	if not model then return end

	Holo.ent:SetModel(model)
end

e2function void holoModel(index, string model, skin)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	skin = skin - skin % 1

	model, skin = GetModel(self, model, skin)
	if not model then return end

	Holo.ent:SetModel(model)
	Holo.ent:SetSkin(skin)
end

e2function void holoSkin(index, skin)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	skin = skin - skin % 1
	local _, skin = GetModel(self, Holo.ent:GetModel(), skin)

	Holo.ent:SetSkin(skin)
end

e2function void holoMaterial(index, string material)
	local Holo = CheckIndex(self, index)
	if not Holo then return end
	E2Lib.setMaterial(Holo.ent, material)
end

e2function void holoPlayerColor(index, vector color)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	local r = color[1]/255
	local g = color[2]/255
	local b = color[3]/255

	set_player_color(Holo, Vector(r, g, b))
end

e2function void holoRenderFX(index, effect)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	effect = effect - effect % 1
	Holo.ent:SetKeyValue("renderfx",effect)
end

e2function void holoBodygroup(index, bgrp_id, bgrp_subid)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetBodygroup(bgrp_id, bgrp_subid)
end

e2function number holoBodygroups(index, bgrp_id)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	return Holo.ent:GetBodygroupCount(bgrp_id)
end

-- -----------------------------------------------------------------------------

e2function void holoVisible(index, entity ply, visible)
	local Holo = CheckIndex(self, index)
	if not Holo or not IsValid( ply ) or not ply:IsPlayer() then return end

	set_visible(Holo, { ply }, visible)
end

e2function void holoVisible(index, array players, visible)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	set_visible(Holo, players, visible)
end

-- -----------------------------------------------------------------------------
local function Parent_Hologram(holo, ent, bone, attachment)
	if ent:GetParent() and ent:GetParent():IsValid() and ent:GetParent() == holo.ent then return end

	holo.ent:SetParent(ent)

	if bone ~= nil then
		holo.ent:SetParentPhysNum(bone)
	end
	if attachment ~= nil then
		holo.ent:Fire("SetParentAttachmentMaintainOffset", attachment, 0.01)
	end
end

-- Check for recursive parenting
local function Check_Parents(child, parent)
	while IsValid(parent:GetParent()) do
		parent = parent:GetParent()
		if parent == child then
			return false
		end
	end

	return true
end

e2function void holoParent(index, otherindex)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	local Holo2 = CheckIndex(self, otherindex)
	if not Holo2 then return end

	if not Check_Parents(Holo.ent, Holo2.ent) then return end

	Parent_Hologram(Holo, Holo2.ent, nil, nil)
end

e2function void holoParent(index, entity ent)
	if not IsValid(ent) then return end
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	if not Check_Parents(Holo.ent, ent) then return end

	Parent_Hologram(Holo, ent, 0, nil)
end

e2function void holoParent(index, bone b)
	local ent, boneindex = E2Lib.isValidBone(b)
	if not ent then return end

	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Parent_Hologram(Holo, ent, boneindex, nil)
end

e2function void holoParentAttachment(index, entity ent, string attachmentName)
	if not IsValid(ent) then return end
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Parent_Hologram(Holo, ent, nil, attachmentName)
end

e2function void holoUnparent(index)
	local Holo = CheckIndex(self, index)
	if not Holo then return end

	Holo.ent:SetParent(nil)
	Holo.ent:SetParentPhysNum(0)
end

-- -----------------------------------------------------------------------------

e2function entity holoEntity(index)
	local Holo = CheckIndex(self, index)
	if Holo and IsValid(Holo.ent) then return Holo.ent end
end

__e2setcost(30)
--- Gets the hologram index of the given entity, if any. Returns 0 on failure.
e2function number holoIndex(entity ent)
	if not IsValid(ent) then return 0 end
	if ent:GetClass() ~= "gmod_wire_hologram" then return 0 end

	-- check local holos
	for k,Holo in pairs(self.data.holos) do
		if(ent == Holo.ent) then return k end
	end

	-- check global holos
	for k,Holo in pairs(E2HoloRepo[self.uid]) do
		if isnumber(k) and ent == Holo.ent then return -k end
	end
	return 0
end

-- -----------------------------------------------------------------------------

registerCallback("construct", function(self)
	if not E2HoloRepo[self.uid] then
		E2HoloRepo[self.uid] = {}
		PlayerAmount[self.uid] = 0
	end
	--self.data.HoloEffect = false
	self.data.holos = {}
	self.data.holo = {
		nextSpawn = CurTime()+1,
		nextBurst = CurTime()+wire_holograms_burst_delay:GetInt(),
		remainingSpawns = wire_holograms_burst_amount:GetInt()
	}
end)

registerCallback("destruct", function(self)
	clearholos(self)
end)

-- -----------------------------------------------------------------------------

local function ConsoleMessage(ply, text)
	if ply:IsValid() then
		ply:PrintMessage( HUD_PRINTCONSOLE, text )
	else
		print(text)
	end
end

concommand.Add( "wire_holograms_remove_all", function( ply, com, args )
	if ply:IsValid() and not ply:IsAdmin() then return end

	clearholos_all()
end )

concommand.Add( "wire_holograms_block", function( ply, com, args )
	if ply:IsValid() and not ply:IsAdmin() then return end

	if not args[1] then
		ConsoleMessage( ply, "Command requires a player's name (or part of their name)" )
		ConsoleMessage( ply, "Usage: wire_holograms_block [name]" )
		return
	end

	local name = args[1]:lower()
	local players = E2Lib.filterList(player.GetAll(), function(ent) return ent:GetName():lower():match(name) end)

	if #players == 1 then
		local v = players[1]
		if BlockList[v:SteamID()] == true then
			ConsoleMessage( ply, v:GetName() .. " is already in the holograms blocklist!" )
		else
			local uid = v:UniqueID()
			if E2HoloRepo[uid] then
				for k2,v2 in pairs( E2HoloRepo[uid] ) do
					if v2 and IsValid(v2.ent) then
						v2.ent:Remove()
						PlayerAmount[uid] = PlayerAmount[uid] - 1
					end
				end
			end
			BlockList[v:SteamID()] = true
			for _,p in ipairs( player.GetAll() ) do
				p:PrintMessage( HUD_PRINTTALK, "(ADMIN) " .. v:GetName() .. " added to holograms blocklist" )
			end
		end
	elseif #players > 1 then
		ConsoleMessage( ply, "More than one player matches that name!" )
	else
		ConsoleMessage( ply, "No player names found with " .. args[1] )
	end
end )

concommand.Add( "wire_holograms_unblock", function( ply, com, args )
	if ply:IsValid() and not ply:IsAdmin() then return end

	if not args[1] then
		ConsoleMessage( ply, "Command requires a player's name (or part of their name)" )
		ConsoleMessage( ply, "Usage: wire_holograms_unblock [name]" )
		return
	end

	local name = args[1]:lower()
	local players = E2Lib.filterList(player.GetAll(), function(ent) return ent:GetName():lower():match(name) end)

	if #players == 1 then
		local v = players[1]
		if BlockList[v:SteamID()] == true then
			BlockList[v:SteamID()] = nil
			for _,player in ipairs( player.GetAll() ) do
				player:PrintMessage( HUD_PRINTTALK, "(ADMIN) " .. v:GetName() .. " removed from holograms blocklist" )
			end
		else
			ConsoleMessage( ply, v:GetName() .. " is not in the holograms blocklist!" )
		end
	elseif #players > 1 then
		ConsoleMessage( ply, "More than one player matches that name!" )
	else
		ConsoleMessage( ply, "No player names found with " .. args[1] )
	end
end )

concommand.Add( "wire_holograms_block_id", function( ply, com, args )
	if ply:IsValid() and not ply:IsAdmin() then return end

	local steamID = table.concat(args)

	if not steamID:match("STEAM_[0-9]:[0-9]:[0-9]+") then
		ConsoleMessage( ply, "Invalid SteamID format" )
		ConsoleMessage( ply, "Usage: wire_holograms_block_id STEAM_X:X:XXXXXX" )
		return
	end

	if BlockList[steamID] == true then
		ConsoleMessage( ply, steamID .. " is already in the holograms blocklist!" )
	else
		BlockList[steamID] = true
		for _,player in ipairs( player.GetAll() ) do
			player:PrintMessage( HUD_PRINTTALK, "(ADMIN) " .. steamID .. " added to holograms blocklist" )
		end
		local uid
		for _,v in pairs( player.GetAll() ) do
			if v:SteamID() == steamID then
				uid = v:UniqueID()
				if (E2HoloRepo[uid]) then
					for k2,v2 in pairs( E2HoloRepo[uid] ) do
						if v2 and IsValid(v2.ent) then
							v2.ent:Remove()
							PlayerAmount[uid] = PlayerAmount[uid] - 1
						end
					end
					return
				end
			end
		end
	end
end )

concommand.Add( "wire_holograms_unblock_id", function( ply, com, args )
	if ply:IsValid() and not ply:IsAdmin() then return end

	local steamID = table.concat(args)

	if not steamID:match("STEAM_[0-9]:[0-9]:[0-9]+") then
		ConsoleMessage( ply, "Invalid SteamID format" )
		ConsoleMessage( ply, "Usage: wire_holograms_unblock_id STEAM_X:X:XXXXXX" )
		return
	end

	if BlockList[steamID] == true then
		BlockList[steamID] = nil
		for _,player in ipairs( player.GetAll() ) do
			player:PrintMessage( HUD_PRINTTALK, "(ADMIN) " .. steamID .. " removed from holograms blocklist" )
		end
	else
		ConsoleMessage( ply, steamID .. " is not in the holograms blocklist!" )
	end
end )

-- -----------------------------------------------------------------------------

wire_holograms = {} -- This global table is used to share certain functions and variables with UWSVN
wire_holograms.CheckIndex = CheckIndex

registerCallback( "postinit", function()
	timer.Simple( 1, function()
		wire_holograms = nil
	end )
end )


text:
Ext.namespace("Kwc.List.Carousel");
Kwc.List.Carousel.Carousel = Ext.extend(Kwf.EyeCandy.List.Plugins.Abstract, {
    numberShown: 5,
    moveElementSelector: false, //if false list.el, else list.child(moveElementSelector)

    _currentListIndex: 0,
    init: function() {
        Ext.applyIf(this, {
            animationConfig: { duration: 0.60, easing: 'easeBothStrong' }
        });
        if (!this.fadeAnimationConfig) {
            this.fadeAnimationConfig = this.animationConfig;
        }
        this.animationConfig.concurrent = true;
        this.fadeAnimationConfig.concurrent = true;

        this.moveElement = this.list.el;
        if (this.moveElementSelector) {
            this.moveElement = this.moveElement.child(this.moveElementSelector);
        }

        if (this.list.items.length > this.numberShown) {
            for(var i=this.numberShown; i<this.list.getItems().length; ++i) {
                this.list.getItem(i).el.hide();
            }
        }
        this.list.setActiveItem(this.list.items[0]);
        if (this.list.items.length > 2) {
            this.list.setActiveItem(this.list.items[1]);
            this._currentListIndex = 1;
        }

        this.list.on('activeChanged', function(item) {
            if (item.listIndex > this._currentListIndex) {
                this.onMoveNext();
            } else {
                this.onMovePrevious();
            }
        }, this);
    },
    onMoveNext: function() {
        // fade out first one
        this.list.setActiveChangeLocked(true);
        this.list.getItem(this.numberShown).el.show();

        Kwf.callOnContentReady(this.moveElement, {newRender: false});

        var firstElWidth = this.list.getItem(0).getWidthIncludingMargin();

        this.list.el.addClass('carouselMoving');

        var cfg = Ext.applyIf({
            callback: function() {
                // push moved left element to back
                this.list.getItem(0).el.insertAfter(this.list.getLastItem().el); //move element
                this.list.items.push(this.list.items.shift()); //adapt array

                //adapt listIndex property
                var idx = 0;
                this.list.items.each(function(i) {
                    i.listIndex = idx++;
                }, this);

                // left von wrapper wieder setzen
                this.moveElement.move('right', firstElWidth, false);

                this._currentListIndex = this.list.getActiveItem().listIndex;
                this.list.setActiveChangeLocked(false);

                this.list.el.removeClass('carouselMoving');
            },
            scope: this
        }, this.animationConfig);
        this.moveElement.move('left', firstElWidth, cfg);
    },
    onMovePrevious: function()
    {
        this.list.setActiveChangeLocked(true);
        // rechts rausgeschobenes element vorn dran
        this.list.getLastItem().el.insertBefore(this.list.getItem(0).el);
        this.list.items.unshift(this.list.items.pop());

        this.list.el.addClass('carouselMoving');

        //adapt listIndex property
        var idx = 0;
        this.list.items.each(function(i) {
            i.listIndex = idx++;
        }, this);

        // left von wrapper setzen
        this.moveElement.move('left', this.list.getItem(0).getWidthIncludingMargin(), false);

        // fade in first
        this.list.getItem(0).el.show();

        Kwf.callOnContentReady(this.moveElement, {newRender: false});

        var cfg = Ext.applyIf({
            callback: function() {
                this._currentListIndex = this.list.getActiveItem().listIndex;
                this.list.setActiveChangeLocked(false);

                this.list.el.removeClass('carouselMoving');
            },
            scope: this
        }, this.animationConfig);
        this.moveElement.move('right', this.list.getItem(0).getWidthIncludingMargin(), cfg);
    }

});

redpajama_set_name: RedPajamaGithub


text:
package org.economicsl.agora.markets

import scala.language.implicitConversions

/** Package contains classes and traits for modeling objects that can be traded via market mechanisms. */
package object tradables {

  /** Value class representing a numeric price. */
  case class Price(value: Double) extends AnyVal

  /** Companion object for the `Price` value class. */
  object Price {

    /** Default ordering for `Price` instances is low to high based on the underlying value. */
    implicit val ordering: Ordering[Price] = PriceOrdering

    /** Implicit conversion used by the compiler to construct boiler plate code for >, <, >=, <=, operators. */
    implicit def mkOrderingOps(lhs: Price) = PriceOrdering.mkOrderingOps(lhs)

    val MaxValue = Price(Double.PositiveInfinity)

    val MinValue = Price(0.0)

  }

  /** Default ordering for `Price` instances is low to high based on the underlying value. */
  object PriceOrdering extends Ordering[Price] {

    /** Instances of `Price` are compared using their underlying values.
      *
      * @param p1 some `Price` instance.
      * @param p2 another `Price` instance.
      * @return -1 if `p1` is less than `p2`, 0 if `p1` equals `p2`, 1 otherwise.
      */
    def compare(p1: Price, p2: Price): Int = p1.value compare p2.value

  }

}


text:
  Ferrère est
       un village
       géographiquement positionné dans le département des Hautes-Pyrénées en Midi-Pyrénées. Elle comptait 50 habitants en 2008.

Si vous envisagez de demenager à Ferrère, vous pourrez aisément trouver une maison à acheter.

Le nombre de logements, à Ferrère, était réparti en 2011 en un appartements et 79 maisons soit
 un marché relativement équilibré.

À coté de Ferrère sont positionnées géographiquement les communes de
Troubat située à 4 km, 53 habitants,
Sacoué localisée à 4 km, 62 habitants,
Gaudent située à 5 km, 47 habitants,
Mauléon-Barousse localisée à 2 km, 121 habitants,
Bramevaque localisée à 4 km, 32 habitants,
Cazarilh située à 3 km, 37 habitants,
 entre autres. De plus, Ferrère est située à seulement 23 km de Saint-Gaudens.


text:
package com.hpit.mobile.login.dataStorage;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

/**
 * Data Storage Implementation with Shared Preferences.
 *
 * @author chun-yang.wang@hp.com
 *
 */
public class SharedPreferencesDataStorage implements IDataStorage {
	private static final String LOG_TAG = "HPMobileLogin." + SharedPreferencesDataStorage.class.getSimpleName();
	private static final String PACKAGE_NAME = "com.hpit.mobile.appcatalog";
	private static final String HP_LOGIN_PREFS_FILE = "HPLoginPrefsFile";

	private SharedPreferences preferences;
	private LoginDataStorageStatus status;

	public SharedPreferencesDataStorage(Context context) {
		init(context);

	}

	private void init(Context context) {
		Context appCatalogContext = null;
		try {
			// If app-catalog app is not installed, NameNotFoundException will be thrown when
			// calling context.createPackageContex() to create app-catalog context.
			appCatalogContext = context.createPackageContext(PACKAGE_NAME, Context.MODE_PRIVATE);
		} catch (NameNotFoundException e) {
			status = LoginDataStorageStatus.APP_CATALOG_NOT_INSTALLED;
			Log.w(LOG_TAG, "AppCatalog (" + PACKAGE_NAME + ") is not installed. " + e.getMessage(), e);
			return;
		}

		int appCatalogUID = appCatalogContext.getApplicationInfo().uid;
		int myUID = context.getApplicationInfo().uid;
		Log.d(LOG_TAG, "appCatalogUID=" + appCatalogUID + ", myUID=" + myUID);
		if (appCatalogUID == myUID) {
			status = LoginDataStorageStatus.OK;
			preferences = appCatalogContext.getSharedPreferences(HP_LOGIN_PREFS_FILE, Context.MODE_PRIVATE);
		} else {
			Log.w(LOG_TAG, "Your application is not using shared user id with AppCatalog");
			status = LoginDataStorageStatus.NOT_SIGNED_BY_HPIT;
		}
	}

	public Boolean put(String key, String value) {
		Editor editor = preferences.edit();
		editor.putString(key, value);
		return editor.commit();
	}

	public String get(String key) {
		return preferences.getString(key, "");
	}

	public LoginDataStorageStatus getStatus() {
		return this.status;
	}
}


text:
import NormalisationRulePicker from '../../lib/normalisation-rule-picker';
import * as assert from 'assert';
import {mock, when} from '../helpers';
import WindowAdaptor from '../../lib/adaptors/window';

suite('NormalisationRulePicker', () => {
    const windowAdaptor = mock(WindowAdaptor);
    when(
        windowAdaptor.showQuickPick(
            [
                {label: 'RULE_NAME_1', picked: true, ruleIndex: 0, description: ''},
                {label: 'RULE_NAME_2', picked: false, ruleIndex: 1, description: ''}
            ]
        )
    )
        .thenResolve([{label: 'RULE_NAME_2', picked: true, ruleIndex: 1}]);
    when(
        windowAdaptor.showQuickPick(
            [
                {label: 'RULE_NAME_3', picked: false, ruleIndex: 0, description: ''},
                {label: 'RULE_NAME_4', picked: true, ruleIndex: 1, description: ''}
            ]
        )
    )
        .thenResolve();
    when(
        windowAdaptor.showQuickPick(
            [
                {label: '(no "name" set for this rule)', picked: true, ruleIndex: 0, description: ''}
            ]
        )
    )
        .thenResolve([]);

    const rulePicker = new NormalisationRulePicker(windowAdaptor);

    test('it returns the index of active rules that user chose', async () => {
        const activeRuleIndices = await rulePicker.show([
            {name: 'RULE_NAME_1', active: true} as any,
            {name: 'RULE_NAME_2', active: false} as any
        ]);

        assert.deepEqual(activeRuleIndices, [1]);
    });

    test('it returns the indices of all active rules if user dismissed the selection popup', async () => {
        const activeRuleIndices = await rulePicker.show([
            {name: 'RULE_NAME_3', active: false} as any,
            {name: 'RULE_NAME_4', active: true}
        ]);

        assert.deepEqual(activeRuleIndices, [1]);
    });

    test('it shows a note to tell the user that no name is given for the rule', async () => {
        const activeRuleIndices = await rulePicker.show([{active: true} as any]);

        assert.deepEqual(activeRuleIndices, []);
    });
});


text:
<?php

namespace BootStrap\DatabaseBundle\Exception;

/**
 * Database Exception
 *
 * @category   BootStrap_Exception
 * @package    Exception
 *
 * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
 */
class DatabaseException extends \Exception
{

    public static function serviceNotSupported()
    {
        return new self("The  database service selected is not yet supported.");
    }

    public static function databasePlatformNotSupported()
    {
        return new self("The database platform selected for this DBAL connection is not yet supported.");
    }

    public static function notSupported($method)
    {
        return new self("Operation '$method' is not supported by platform.");
    }

}


text:
package org.infinispan.eviction;

import net.jcip.annotations.ThreadSafe;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.ImmutableContext;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.loaders.CacheLoaderManager;
import org.infinispan.loaders.CacheStore;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.util.Util;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;

import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@ThreadSafe
public class EvictionManagerImpl implements EvictionManager {
   private static final Log log = LogFactory.getLog(EvictionManagerImpl.class);
   private static final boolean trace = log.isTraceEnabled();
   ScheduledFuture <?> evictionTask;

   // components to be injected
   private ScheduledExecutorService executor;
   private Configuration configuration;
   private CacheLoaderManager cacheLoaderManager;
   private DataContainer dataContainer;
   private CacheStore cacheStore;
   private CacheNotifier cacheNotifier;
   private boolean enabled;
   private String cacheName;

   @Inject
   public void initialize(@ComponentName(KnownComponentNames.EVICTION_SCHEDULED_EXECUTOR)
         ScheduledExecutorService executor, Cache cache, Configuration cfg, DataContainer dataContainer,
         CacheLoaderManager cacheLoaderManager, CacheNotifier cacheNotifier) {
      initialize(executor, cache.getName(), cfg, dataContainer,
            cacheLoaderManager, cacheNotifier);
   }

   void initialize(ScheduledExecutorService executor,
            String cacheName, Configuration cfg, DataContainer dataContainer,
            CacheLoaderManager cacheLoaderManager, CacheNotifier cacheNotifier) {
      this.executor = executor;
      this.configuration = cfg;
      this.cacheName = cacheName;
      this.dataContainer = dataContainer;
      this.cacheLoaderManager = cacheLoaderManager;
      this.cacheNotifier = cacheNotifier;
   }

   @Start(priority = 55)
   // make sure this starts after the CacheLoaderManager
   public void start() {
      // first check if eviction is enabled!
      enabled = configuration.expiration().reaperEnabled();
      if (enabled) {
         if (cacheLoaderManager != null && cacheLoaderManager.isEnabled()) {
            cacheStore = cacheLoaderManager.getCacheStore();
         }
         // Set up the eviction timer task
         long expWakeUpInt = configuration.expiration().wakeUpInterval();
         if (expWakeUpInt <= 0) {
            log.notStartingEvictionThread();
         } else {
            evictionTask = executor.scheduleWithFixedDelay(new ScheduledTask(),
                  expWakeUpInt, expWakeUpInt, TimeUnit.MILLISECONDS);
         }
      }
   }

   @Override
   public void processEviction() {
      long start = 0;
      if (!Thread.currentThread().isInterrupted()) {
         try {
            if (trace) {
               log.trace("Purging data container of expired entries");
               start = System.nanoTime();
            }
            dataContainer.purgeExpired();
            if (trace) {
               log.tracef("Purging data container completed in %s", Util.prettyPrintTime(System.nanoTime() - start, TimeUnit.NANOSECONDS));
            }
         } catch (Exception e) {
            log.exceptionPurgingDataContainer(e);
         }
      }

      if (!Thread.currentThread().isInterrupted()) {
         if (cacheStore != null) {
            try {
               if (trace) {
                  log.trace("Purging cache store of expired entries");
                  start = System.nanoTime();
               }
               cacheStore.purgeExpired();
               if (trace) {
                  log.tracef("Purging cache store completed in %s", Util.prettyPrintTime(System.nanoTime() - start, TimeUnit.NANOSECONDS));
               }
            } catch (Exception e) {
               log.exceptionPurgingDataContainer(e);
            }
         }
      }
   }

   @Override
   public boolean isEnabled() {
      return enabled;
   }

   @Stop(priority = 5)
   public void stop() {
      if (evictionTask != null) {
         evictionTask.cancel(true);
      }
   }

   class ScheduledTask implements Runnable {
      @Override
      public void run() {
         LogFactory.pushNDC(cacheName, trace);
         try {
            processEviction();
         } finally {
            LogFactory.popNDC(trace);
         }
      }
   }

   @Override
   public void onEntryEviction(Map<Object, InternalCacheEntry> evicted) {
      // don't reuse the threadlocal context as we don't want to include eviction
      // operations in any ongoing transaction, nor be affected by flags
      // especially see ISPN-1154: it's illegal to acquire locks in a committing transaction
      InvocationContext ctx = ImmutableContext.INSTANCE;
      // This is important because we make no external guarantees on the thread
      // that will execute this code, so it could be the user thread, or could
      // be the eviction thread.
      // However, when a user calls cache.evict(), you do want to carry over the
      // contextual information, hence it makes sense for the notifyCacheEntriesEvicted()
      // call to carry on taking an InvocationContext object.
      cacheNotifier.notifyCacheEntriesEvicted(evicted.values(), ctx);
   }
}


text:
---
uid: SolidEdgeAssembly.Pipe.GetPipeFittings(System.Int32@,System.Array@,System.Array@)
summary:
remarks:
---


text:
module Cases
  class NotesController < ApplicationController
    include Notable

    before_action :set_case

    def create
      authorize(@case, :can_add_note_to_case?)

      add_message(
        event_name: 'add_note_to_case!',
        on_success: case_path(@case, anchor: 'case-history')
      )
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class ModelRule<T>
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class ModelRule<T>
   ">
    <meta name="generator" content="docfx 2.9.3.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class ModelRule<T>

Represents the rule for a model of any type

Inheritance

System.Object

FluentValidation.Internal.PropertyRule

ModelRule<T>

Inherited Members

                  FluentValidation.Internal.PropertyRule.Create<T, TProperty>(System.Linq.Expressions.Expression<System.Func<T, TProperty>>)

                  FluentValidation.Internal.PropertyRule.Create<T, TProperty>(System.Linq.Expressions.Expression<System.Func<T, TProperty>>, System.Func<FluentValidation.CascadeMode>)

                  FluentValidation.Internal.PropertyRule.AddValidator(FluentValidation.Validators.IPropertyValidator)

                  FluentValidation.Internal.PropertyRule.ReplaceValidator(FluentValidation.Validators.IPropertyValidator, FluentValidation.Validators.IPropertyValidator)

                  FluentValidation.Internal.PropertyRule.RemoveValidator(FluentValidation.Validators.IPropertyValidator)

                  FluentValidation.Internal.PropertyRule.ClearValidators()

                  FluentValidation.Internal.PropertyRule.GetDisplayName()

                  FluentValidation.Internal.PropertyRule.Validate(FluentValidation.ValidationContext)

                  FluentValidation.Internal.PropertyRule.ValidateAsync(FluentValidation.ValidationContext, System.Threading.CancellationToken)

                  FluentValidation.Internal.PropertyRule.InvokePropertyValidatorAsync(FluentValidation.ValidationContext, FluentValidation.Validators.IPropertyValidator, System.String, System.Threading.CancellationToken)

                  FluentValidation.Internal.PropertyRule.InvokePropertyValidator(FluentValidation.ValidationContext, FluentValidation.Validators.IPropertyValidator, System.String)

                  FluentValidation.Internal.PropertyRule.ApplyCondition(System.Func<System.Object, System.Boolean>, FluentValidation.ApplyConditionTo)

                  FluentValidation.Internal.PropertyRule.ApplyAsyncCondition(System.Func<System.Object, System.Threading.Tasks.Task<System.Boolean>>, FluentValidation.ApplyConditionTo)

                  FluentValidation.Internal.PropertyRule.Member

                  FluentValidation.Internal.PropertyRule.PropertyFunc

                  FluentValidation.Internal.PropertyRule.Expression

                  FluentValidation.Internal.PropertyRule.DisplayName

                  FluentValidation.Internal.PropertyRule.RuleSet

                  FluentValidation.Internal.PropertyRule.OnFailure

                  FluentValidation.Internal.PropertyRule.CurrentValidator

                  FluentValidation.Internal.PropertyRule.TypeToValidate

                  FluentValidation.Internal.PropertyRule.CascadeMode

                  FluentValidation.Internal.PropertyRule.Validators

                  FluentValidation.Internal.PropertyRule.PropertyName

                  FluentValidation.Internal.PropertyRule.MessageBuilder

                  FluentValidation.Internal.PropertyRule.DependentRules

                  System.Object.ToString()

                  System.Object.Equals(System.Object)

                  System.Object.Equals(System.Object, System.Object)

                  System.Object.ReferenceEquals(System.Object, System.Object)

                  System.Object.GetHashCode()

                  System.Object.GetType()

                  System.Object.MemberwiseClone()

Namespace:Bifrost.FluentValidation

Assembly:Bifrost.FluentValidation.dll

Syntax

public class ModelRule<T> : PropertyRule, IValidationRule

Type Parameters

                    Name
                    Description

                    T
                    Type the rule represents

Constructors

                |
                Improve this Doc

                View Source

ModelRule()

Initializes an instance of ModelRule<T>

Declaration

public ModelRule()

Fields

                |
                Improve this Doc

                View Source

ModelRulePropertyName

Declaration

public const string ModelRulePropertyName = "ModelRuleProperty"

Field Value

                    Type
                    Description

                    System.String

Properties

                |
                Improve this Doc

                View Source

ModelRuleProperty

Declaration

public static string ModelRuleProperty { get; set; }

Property Value

                    Type
                    Description

                    System.String

Extension Methods

                  ConceptExtensions.IsConcept(Object)

                  ConceptExtensions.GetConceptValue(Object)

                  DynamicExtensions.AsExpandoObject(Object)

                  MethodCalls.CallGenericMethod<TOut, T, T1, T2, T3>(T, Expression<Func<T, Func<T1, T2, T3, TOut>>>, T1, T2, T3, Type[])

                  MethodCalls.CallGenericMethod<TOut, T, T1, T2>(T, Expression<Func<T, Func<T1, T2, TOut>>>, T1, T2, Type[])

                  MethodCalls.CallGenericMethod<TOut, T, T1>(T, Expression<Func<T, Func<T1, TOut>>>, T1, Type[])

                  MethodCalls.CallGenericMethod<TOut, T>(T, Expression<Func<T, Func<TOut>>>, Type[])

                  MethodCalls.Generics<T>(T)

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2008-2017 Dolittle


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('booth', '0006_auto_20161124_2050'),
    ]

    operations = [
        migrations.AddField(
            model_name='recording',
            name='schedule',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='booth.Schedule'),
        ),
    ]


text:
using Plugin.Media;
using Plugin.Media.Abstractions;
using Sensus.Exceptions;
using Sensus.UI.Inputs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Sensus.UI.UiProperties
{
	public class MediaPickerUiProperty : UiProperty
	{
		public MediaPickerUiProperty(string labelText, bool editable, int order) : base(labelText, editable, order, false)
		{

		}

		public const string PREVIEW = "Preview";
		public const string CAPTURE_IMAGE = "Capture Image";
		public const string CHOOSE_IMAGE = "Choose Image";
		public const string CAPTURE_VIDEO = "Capture Video";
		public const string CHOOSE_VIDEO = "Choose Video";
		public const string URL = "Url";
		public const string URL_CACHED = "Url (Cached)";
		public const string URL_EMBEDDED = "Url (Embed)";
		public const string NONE = "None";
		public const string CHOOSE = "Choose...";

		private string GetButtonText(MediaObject media)
		{
			if (media != null && string.IsNullOrWhiteSpace(media.Data) == false)
			{
				if (media.StorageMethod == MediaStorageMethods.Embed)
				{
					// using the byte count of the base64 string since it is what gets serialized to Unicode.
					// The file size is likely smaller by almost half due to the base64 string being encoded in Unicode, but it would not represent the actual amount of data being stored.
					int size = Encoding.Unicode.GetByteCount(media.Data);

					return $"{media.Type} ({size} B)";
				}
				else if (media.StorageMethod == MediaStorageMethods.Cache)
				{
					return URL_CACHED;
				}
				else
				{
					return URL;
				}
			}

			return CHOOSE;
		}

		public override View GetView(PropertyInfo property, object o, out BindableProperty bindingProperty, out IValueConverter converter)
		{
			if (property.PropertyType != typeof(MediaObject))
			{
				throw new ArgumentException($"The property provided must have a type of {nameof(MediaObject)}.", nameof(property));
			}

			bindingProperty = null;
			converter = null;

			List<string> buttons = new List<string>();
			StackLayout urlLayout = new StackLayout();
			MediaObject currentMedia = (MediaObject)property.GetValue(o);
			MediaStorageMethods storageMethod = currentMedia?.StorageMethod ?? MediaStorageMethods.URL;
			MediaInput input = (MediaInput)o;

			Button sourceButton = new Button()
			{
				Text = GetButtonText(currentMedia),
				HorizontalOptions = LayoutOptions.FillAndExpand,
				FontSize = 20
			};

			Label urlLabel = new Label
			{
				Text = "Url:",
				FontSize = 20
			};

			Entry urlEntry = new Entry
			{
				Keyboard = Keyboard.Url,
				HorizontalOptions = LayoutOptions.FillAndExpand
			};

			Label cacheLabel = new Label
			{
				Text = "Cache Mode:",
				FontSize = 20
			};

			Picker cachePicker = new Picker()
			{
				Title = "Select Cache Mode",
				HorizontalOptions = LayoutOptions.FillAndExpand
			};

			foreach (string cacheMode in Enum.GetNames(typeof(MediaCacheModes)))
			{
				cachePicker.Items.Add(cacheMode);
			}

			if (currentMedia != null)
			{
				cachePicker.SelectedItem = currentMedia.CacheMode.ToString();
			}

			cachePicker.SelectedIndexChanged += (s, e) =>
			{
				Enum.TryParse(typeof(MediaCacheModes), (string)cachePicker.SelectedItem, out object result);

				if (currentMedia != null)
				{
					currentMedia.CacheMode = (MediaCacheModes)result;
				}
			};

			StackLayout cacheLayout = new StackLayout()
			{
				IsVisible = false,
				Children = { cacheLabel, cachePicker }
			};

			StackLayout urlStack = new StackLayout
			{
				IsVisible = false,
				Children = { urlLabel, urlEntry, cacheLayout }
			};

			async Task setMediaObjectAsync(MediaFile file)
			{
				if (file != null)
				{
					sourceButton.IsEnabled = false;
					sourceButton.Text = "Processing...";

					try
					{
						MediaObject media = await MediaObject.FromFileAsync(file.Path, file.GetStream(), SensusServiceHelper.Get().GetMimeType(file.Path), input.CachePath);

						setMediaObject(media);
					}
					catch (Exception exception)
					{
						await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to attach media to the {o.GetType().Name}");

						SensusServiceHelper.Get().Logger.Log("Failed to attach media: " + exception.Message, LoggingLevel.Normal, GetType());
					}

					sourceButton.IsEnabled = true;
				}
			}

			void setMediaObject(MediaObject media)
			{
				if (currentMedia != null)
				{
					currentMedia.ClearCache();
				}

				currentMedia = media;
				property.SetValue(o, media);

				if (media.StorageMethod == MediaStorageMethods.Cache)
				{
					cachePicker.SelectedItem = currentMedia.CacheMode.ToString();
				}

				Device.BeginInvokeOnMainThread(() =>
				{
					sourceButton.Text = GetButtonText(media);

					if (buttons.Contains(PREVIEW) == false)
					{
						buttons.Insert(0, PREVIEW);
					}

					if (media.StorageMethod == MediaStorageMethods.Embed)
					{
						urlStack.IsVisible = false;
					}
					else
					{
						urlStack.IsVisible = true;

						if (media.StorageMethod == MediaStorageMethods.Cache)
						{
							cacheLayout.IsVisible = true;
						}
					}
				});
			}

			urlEntry.Unfocused += async (s, e) =>
			{
				try
				{
					string mimeType = SensusServiceHelper.Get().GetMimeType(urlEntry.Text);

					if (mimeType?.StartsWith("video") == true && storageMethod == MediaStorageMethods.Embed)
					{
						storageMethod = MediaStorageMethods.Cache;

						sourceButton.Text = URL_CACHED;

						await SensusServiceHelper.Get().FlashNotificationAsync($"You cannot embed videos. The video will be cached instead.");
					}

					MediaObject media = await MediaObject.FromUrlAsync(urlEntry.Text, mimeType, storageMethod, input.CachePath);

					if (media.Type.StartsWith("video") && storageMethod == MediaStorageMethods.Embed)
					{
						storageMethod = MediaStorageMethods.Cache;

						sourceButton.Text = URL_CACHED;

						await SensusServiceHelper.Get().FlashNotificationAsync($"You cannot embed videos. The video will be cached instead.");
					}
					else
					{
						setMediaObject(media);
					}
				}
				catch (Exception exception)
				{
					await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to attach media to the {o.GetType().Name}");

					SensusServiceHelper.Get().Logger.Log("Failed to attach media: " + exception.Message, LoggingLevel.Normal, GetType());
				}
			};

			if (currentMedia != null && string.IsNullOrWhiteSpace(currentMedia.Data) == false)
			{
				buttons.Add(PREVIEW);

				if (currentMedia.StorageMethod != MediaStorageMethods.Embed)
				{
					urlEntry.Text = currentMedia.Data;
					urlStack.IsVisible = true;

					if (currentMedia.StorageMethod == MediaStorageMethods.Cache)
					{
						cacheLayout.IsVisible = true;
					}
				}
			}

			sourceButton.Clicked += async (s, e) =>
			{
				try
				{
					string source = await Application.Current.MainPage.DisplayActionSheet("Media Source", "Cancel", null, buttons.ToArray());

					if (source == PREVIEW)
					{
						INavigation navigation = (Application.Current as App).DetailPage.Navigation;

						MediaObject media = (MediaObject)property.GetValue(o);

						await media.CacheMediaAsync();

						await navigation.PushAsync(new MediaPreviewPage(media), true);
					}
					else if (source == CAPTURE_IMAGE)
					{
						MediaFile file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
						{
							CustomPhotoSize = 50,
							CompressionQuality = 50,
							SaveMetaData = false,
							SaveToAlbum = true
						});

						await setMediaObjectAsync(file);
					}
					else if (source == CHOOSE_IMAGE)
					{
						MediaFile file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions()
						{
							CustomPhotoSize = 50,
							CompressionQuality = 50,
							SaveMetaData = false
						});

						await setMediaObjectAsync(file);
					}
					else if (source == CAPTURE_VIDEO)
					{
						MediaFile file = await CrossMedia.Current.TakeVideoAsync(new StoreVideoOptions
						{
							CustomPhotoSize = 50,
							CompressionQuality = 50,
							SaveMetaData = false,
							SaveToAlbum = true
						});

						await setMediaObjectAsync(file);
					}
					else if (source == CHOOSE_VIDEO)
					{
						MediaFile file = await CrossMedia.Current.PickVideoAsync();

						await setMediaObjectAsync(file);
					}
					else if (source == URL)
					{
						storageMethod = MediaStorageMethods.URL;

						sourceButton.Text = URL;

						urlStack.IsVisible = true;
						urlEntry.Focus();

						cacheLayout.IsVisible = false;
					}
					else if (source == URL_CACHED)
					{
						storageMethod = MediaStorageMethods.Cache;

						sourceButton.Text = URL_CACHED;

						urlStack.IsVisible = true;
						urlEntry.Focus();

						cacheLayout.IsVisible = true;
					}
					else if (source == URL_EMBEDDED)
					{
						storageMethod = MediaStorageMethods.Embed;

						sourceButton.Text = URL_EMBEDDED;

						urlStack.IsVisible = true;
						urlEntry.Focus();

						cacheLayout.IsVisible = false;
					}
					else if (source == NONE)
					{
						buttons.Remove(PREVIEW);

						if (currentMedia != null)
						{
							currentMedia.ClearCache();
						}

						property.SetValue(o, null);

						urlStack.IsVisible = false;
						sourceButton.Text = CHOOSE;
					}
				}
				catch (Exception exception)
				{
					await SensusServiceHelper.Get().FlashNotificationAsync($"Failed to attach media to the {o.GetType().Name}");

					SensusException.Report(exception);
				}
			};

			if (CrossMedia.Current.IsTakePhotoSupported)
			{
				buttons.Add(CAPTURE_IMAGE);
			}

			if (CrossMedia.Current.IsPickPhotoSupported)
			{
				buttons.Add(CHOOSE_IMAGE);
			}

			if (CrossMedia.Current.IsTakeVideoSupported)
			{
				buttons.Add(CAPTURE_VIDEO);
			}

			if (CrossMedia.Current.IsPickVideoSupported)
			{
				buttons.Add(CHOOSE_VIDEO);
			}

			buttons.Add(URL);
			buttons.Add(URL_CACHED);
			buttons.Add(URL_EMBEDDED);
			buttons.Add(NONE);

			StackLayout layout = new StackLayout()
			{
				Children = { sourceButton, urlStack }
			};

			return layout;
		}
	}
}


text:
use std::env;

use cargo::core::Workspace;
use cargo::ops;
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::find_root_manifest_for_wd;

#[derive(Deserialize)]
pub struct Options {
    flag_manifest_path: Option<String>,
    flag_verbose: u32,
    flag_quiet: Option<bool>,
    flag_color: Option<String>,
    flag_frozen: bool,
    flag_locked: bool,
    #[serde(rename = "flag_Z")]
    flag_z: Vec<String>,
}

pub const USAGE: &'static str = "
Generate the lockfile for a project

Usage:
    cargo generate-lockfile [options]

Options:
    -h, --help               Print this message
    --manifest-path PATH     Path to the manifest to generate a lockfile for
    -v, --verbose ...        Use verbose output (-vv very verbose/build.rs output)
    -q, --quiet              No output printed to stdout
    --color WHEN             Coloring: auto, always, never
    --frozen                 Require Cargo.lock and cache are up to date
    --locked                 Require Cargo.lock is up to date
    -Z FLAG ...              Unstable (nightly-only) flags to Cargo
";

pub fn execute(options: Options, config: &mut Config) -> CliResult {
    debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>());
    config.configure(options.flag_verbose,
                     options.flag_quiet,
                     &options.flag_color,
                     options.flag_frozen,
                     options.flag_locked,
                     &options.flag_z)?;
    let root = find_root_manifest_for_wd(options.flag_manifest_path, config.cwd())?;

    let ws = Workspace::new(&root, config)?;
    ops::generate_lockfile(&ws)?;
    Ok(())
}


text:
exports.run = (bot, member) => {
	let Discord = require('discord.js');
	let config = require('../config/config.json');

	const embed = new Discord.RichEmbed()
		.setTitle(":flushed: Welcome to the server... ")
        .setDescription('May I take your order, <@'+member.id+'>?')
        .setThumbnail(member.user.displayAvatarURL)
		.setFooter(("UserID: "+member.id));
	member.guild.defaultChannel.send({embed});
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<SimulatorProject xmlns="https://github.com/TTExtensions/MouseClickSimulator">
  <Title>Gardening – 6 Jellybean Combinations</Title>
  <Description>
This project contains QuickActions for planting flowers using combinations of 6 jellybeans.

Before you click on one of the buttons, the toon needs to stand in front of an empty flower spot.
  </Description>

  <QuickAction title="Tinted Rose  (Rose)">
    <PlantFlower jellybeanCombination="0, 5, 2, 0, 2, 5" />
  </QuickAction>

  <QuickAction title="Smarty Pansy  (Pansy)">
    <PlantFlower jellybeanCombination="2, 5, 5, 2, 4, 5" />
  </QuickAction>

  <QuickAction title="Twolip  (Tulip)">
    <PlantFlower jellybeanCombination="3, 0, 0, 0, 3, 3" />
  </QuickAction>

  <QuickAction title="Upsy Daisy  (Daisy)">
    <PlantFlower jellybeanCombination="6, 4, 7, 3, 4, 4" />
  </QuickAction>

  <QuickAction title="Silly Lily  (Lily)">
    <PlantFlower jellybeanCombination="7, 0, 3, 3, 3, 3" />
  </QuickAction>

</SimulatorProject>


text:
prueba
======

Pruebas para puppet y python.


text:
namespace YUTPLAT.Migrations
{
    using System.Data.Entity.Migrations;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System.Linq;
    using Models;
    using System.IO;
    using System;
    using Helpers;

    internal sealed class Configuration : DbMigrationsConfiguration<YUTPLAT.Context.YutplatDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "YUTPLAT.Context.YutplatDbContext";
        }

        protected override void Seed(YUTPLAT.Context.YutplatDbContext context)
        {
            //if (!System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Launch();

            CargarRoles(context);
            CargarUsuarios(context);
            CargarFrecuenciasMedicionIndicadores(context);
            EjecutarArchivosSQL(context);

            base.Seed(context);
        }

        private void EjecutarArchivosSQL(YUTPLAT.Context.YutplatDbContext context)
        {
            string dirName = AppDomain.CurrentDomain.BaseDirectory;
            FileInfo fileInfo = new FileInfo(dirName);
            DirectoryInfo parentDir = fileInfo.Directory.Parent;
            string parentDirName = parentDir.FullName;

            var archivosSql = Directory.GetFiles(parentDirName + "\\SQL", "*.sql").OrderBy(x => x);

            foreach (string archivo in archivosSql)
            {
                if (!context.ArchivosSQL.Any(r => r.NombreArchivo == archivo.Replace(parentDirName + "\\SQL\\", "")))
                {
                    context.Database.ExecuteSqlCommand(File.ReadAllText(archivo));
                    context.ArchivosSQL.AddOrUpdate(new YUTPLAT.Models.ArchivoSQL { NombreArchivo = archivo.Replace(parentDirName + "\\SQL\\", "") });
                    context.SaveChanges();
                }
            }
        }

        private void CargarRoles(YUTPLAT.Context.YutplatDbContext context)
        {
            string rolAdmin = EnumHelper<Enums.Enum.Rol>.GetDisplayValue(Enums.Enum.Rol.Admin);
            string rolUsuario = EnumHelper<Enums.Enum.Rol>.GetDisplayValue(Enums.Enum.Rol.Usuario);
            string rolOperador = EnumHelper<Enums.Enum.Rol>.GetDisplayValue(Enums.Enum.Rol.Operador);

            if (!context.Roles.Any(r => r.Name == rolAdmin))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = new IdentityRole { Name = rolAdmin };

                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == rolUsuario))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = new IdentityRole { Name = rolUsuario };

                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == rolOperador))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = new IdentityRole { Name = rolOperador };

                manager.Create(role);
            }
        }

        private void CargarUsuarios(YUTPLAT.Context.YutplatDbContext context)
        {
            string rolAdmin = EnumHelper<Enums.Enum.Rol>.GetDisplayValue(Enums.Enum.Rol.Admin);
            string rolUsuario = EnumHelper<Enums.Enum.Rol>.GetDisplayValue(Enums.Enum.Rol.Usuario);
            string rolOperador = EnumHelper<Enums.Enum.Rol>.GetDisplayValue(Enums.Enum.Rol.Operador);

            string email = "@cys.com.ar";
            email += "TEST";

            if (!context.Users.Any(u => u.UserName == "amolinari"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);

                var user = new Persona { UserName = "amolinari", Email = "amolinari" + email, EmailConfirmed = true, Nombre = "Alejandro", Apellido = "Molinari", Rol = rolAdmin };

                manager.Create(user, "i08oyy");
                manager.AddToRole(user.Id, rolAdmin);
            }

            if (!context.Users.Any(u => u.UserName == "jbarbosa"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "jbarbosa", Email= "jbarbosa" + email, EmailConfirmed = true, Nombre = "Jorge", Apellido = "Barbosa", Rol = rolAdmin };

                manager.Create(user, "pjdjiz");
                manager.AddToRole(user.Id, rolAdmin);
            }

            if (!context.Users.Any(u => u.UserName == "elara"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "elara", Email = "elara" + email, EmailConfirmed = true, Nombre = "Enrique", Apellido = "Lara", Rol = rolAdmin };

                manager.Create(user, "bhz6cw");
                manager.AddToRole(user.Id, rolAdmin);
            }

            if (!context.Users.Any(u => u.UserName == "lbertuzzi"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "lbertuzzi", Email = "lbertuzzi" + email, EmailConfirmed = true, Nombre = "Liliana", Apellido = "Bertuzzi", Rol = rolAdmin };

                manager.Create(user, "6dpqmz");
                manager.AddToRole(user.Id, rolAdmin);
            }

            if (!context.Users.Any(u => u.UserName == "ncaniggia"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "ncaniggia", Email = "norberto" + email, EmailConfirmed = true, Nombre = "Norberto", Apellido = "Caniggia", Rol = rolAdmin };

                manager.Create(user, "widqru");
                manager.AddToRole(user.Id, rolAdmin);
            }

            if (!context.Users.Any(u => u.UserName == "cfontela"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "cfontela", Email = "cfontela" + email, EmailConfirmed = true, Nombre = "Carlos", Apellido = "Fontela", Rol = rolUsuario };

                manager.Create(user, "bh283d");
                manager.AddToRole(user.Id, rolUsuario);
            }

            if (!context.Users.Any(u => u.UserName == "econtreras"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "econtreras", Email = "econtreras" + email, EmailConfirmed = true, Nombre = "Eduardo", Apellido = "Contreras", Rol = rolUsuario };

                manager.Create(user, "kpccjk");
                manager.AddToRole(user.Id, rolUsuario);
            }

            if (!context.Users.Any(u => u.UserName == "aromero"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "aromero", Email = "aromero" + email, EmailConfirmed = true, Nombre = "Alexandra", Apellido = "Romero", Rol = rolUsuario };

                manager.Create(user, "b1kjb9");
                manager.AddToRole(user.Id, rolUsuario);
            }

            if (!context.Users.Any(u => u.UserName == "jdelvalle"))
            {
                var store = new UserStore<Persona>(context);
                var manager = new UserManager<Persona>(store);
                var user = new Persona { UserName = "jdelvalle", Email = "jdv" + email, EmailConfirmed = true, Nombre = "Javier", Apellido = "del Valle", Rol = rolUsuario };

                manager.Create(user, "4kd6tk");
                manager.AddToRole(user.Id, rolUsuario);
            }
        }

        private void CargarFrecuenciasMedicionIndicadores(YUTPLAT.Context.YutplatDbContext context)
        {
            if (!context.FrecuenciasMedicionIndicadores.Any(f => f.Descripcion == "Mensual"))
            {
                context.FrecuenciasMedicionIndicadores.AddOrUpdate(new FrecuenciaMedicionIndicador { Descripcion = "Mensual" });
            }

            /*
            if (!context.FrecuenciasMedicionIndicadores.Any(f => f.Descripcion == "Al final de cada proyecto de capacitación"))
            {
                context.FrecuenciasMedicionIndicadores.AddOrUpdate(new FrecuenciaMedicionIndicador { Descripcion = "Al final de cada proyecto de capacitación" });
            }

            if (!context.FrecuenciasMedicionIndicadores.Any(f => f.Descripcion == "Trimestral"))
            {
                context.FrecuenciasMedicionIndicadores.AddOrUpdate(new FrecuenciaMedicionIndicador { Descripcion = "Trimestral" });
            }

            if (!context.FrecuenciasMedicionIndicadores.Any(f => f.Descripcion == "Cuatrimestral"))
            {
                context.FrecuenciasMedicionIndicadores.AddOrUpdate(new FrecuenciaMedicionIndicador { Descripcion = "Cuatrimestral" });
            }
            */

            context.SaveChanges();
        }
    }
}


text:
package nl.sense_os.service.ambience;

import android.annotation.TargetApi;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.os.Build;
import android.util.Log;

/**
 * Class that is responsible for taking camera preview images and converting them into light values.
 * Only works in Android 2.3 (?).
 *
 * @author Ted Schmidt <ted@sense-os.nl>
 */
public class CameraLightValue {

	/**
	 * Interface for new camera light values.
	 *
	 * @see CameraLightValue#getLightValue(int, CameraLightValueCallback)
	 */
	public interface CameraLightValueCallback {
		public void lightValueCallback(float lightValue, int camera_id);
	}

	/**
	 * Handles camera previews by passing calculating the light value from the preivew and passing
	 * it along to a {@link CameraLightValueCallback}.
	 */
	private class CameraPreviewCallback implements PreviewCallback {
		private int camera_id;
		CameraLightValueCallback camlightCallback;

		public CameraPreviewCallback(int camera_id, CameraLightValueCallback camlightCallback) {
			this.camera_id = camera_id;
			this.camlightCallback = camlightCallback;
		}

		private float calculateLightValue(byte[] data, int width, int height) {
			try {
				float lux = 0;
				// Data is YCrCb NV21 encoding
				// the first height*width are Y: luminance values

				// calculate the average luminance
				for (int i = 0; i < height * width; i++) {
					// conversion to java unsigned byte
					if (data[i] < 0)
						lux += (data[i] + 256);
					else
						lux += data[i];
				}
				return lux /= ((float) width * height);
			} catch (Exception e) {
				Log.e(TAG, "Error calculating the light value", e);
				return -1;
			}
		}

		@Override
		public void onPreviewFrame(byte[] data, Camera camera) {
			try {
				int width = camera.getParameters().getPreviewSize().width;
				int height = camera.getParameters().getPreviewSize().height;
				// important set the callback to null or the android camera thread fails
				cameraDevices[camera_id].setPreviewCallback(null);
				cameraDevices[camera_id].stopPreview();
				cameraDevices[camera_id].release();
				cameraDevices[camera_id] = null;
				float lightValue = calculateLightValue(data.clone(), width, height);
				camlightCallback.lightValueCallback(lightValue, camera_id);
			} catch (Exception e) {
				Log.e(TAG, "Error while processing preview frame:" + e.getMessage());
				cameraDevices[camera_id] = null;
			}
		}
	}

	private String TAG = "Camera Light Value";
	private Camera[] cameraDevices;

	public CameraLightValue() {
		cameraDevices = new Camera[getNumberOfCameras()];
	}

	@TargetApi(9)
	public boolean getLightValue(final int camera_id,
			final CameraLightValueCallback camlightCallback) {

		// this camera code only works for API > 9 and API < 14
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
			try {
				if (camera_id > getNumberOfCameras() - 1)
					return false;
				if (cameraDevices[camera_id] != null)
					return false;
				else {
					cameraDevices[camera_id] = Camera.open(camera_id);
					Camera.Parameters parameters = cameraDevices[camera_id].getParameters();
					parameters.setExposureCompensation(0);
					parameters.setWhiteBalance("daylight");
					cameraDevices[camera_id].setPreviewCallback(new CameraPreviewCallback(
							camera_id, camlightCallback));
					cameraDevices[camera_id].startPreview();
				}
				return true;
			} catch (Exception e) {
				Log.e(TAG, "Error getting camera " + camera_id + " " + e.getMessage());
				cameraDevices[camera_id] = null;
				try {
					cameraDevices[camera_id].release();
				} catch (Exception e2) {
					Log.e(TAG, "Error releasing the camera " + camera_id + " " + e2.getMessage());
				}

				return false;
			}

		} else {
			Log.w(TAG, "Camera is not available in this Android version: " + Build.VERSION.SDK_INT);
			return false;
		}
	};

	@TargetApi(9)
	public int getNumberOfCameras() {
		try {
			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {

				return Camera.getNumberOfCameras();
			} else {
				return 1;
			}
		} catch (Exception e) {
			Log.e(TAG, "Error getting the number of camera's " + e.getMessage());
			return 0;
		}
	}
}


text:
import * as credential from "credential";
let passwordTools = credential();

import Collection from "./Collection";

export interface User
{
    email: string;
    username: string;

    credentials: {
        local?: {
            password: string;
        },
        facebook?: {
            id: string;
        }
    }
}

class UserCollection extends Collection<User>
{
    constructor()
    {
        super("Users", UserCollection.template);
    }

    protected static readonly template : User = {
        email: "",
        username: "",
        credentials: {
            local: {
                password: ""
            },
            facebook: {
                id: ""
            }
        }
    };

    hashPassword(password: string): Promise<string>
    {
        return new Promise((resolve) => {
            passwordTools.hash(password, (err: any, result: string) => {
                if (err) {
                    throw(err);
                }
                else {
                    resolve(result);
                }
            });
        });
    }

    isValidPassword(user: User, userPassword: string) : Promise<boolean>
    {
        return new Promise((resolve) => {
            let storedPassword = user.credentials.local.password;
            passwordTools.verify(storedPassword, userPassword, (err: string, isValid: boolean) => {
                if (err) throw err;
                resolve(isValid);
            });
        });
    }
}

export default new UserCollection();


text:
package auth

import (
	"github.com/dcos/dcos-cli/api"
	"github.com/spf13/cobra"
)

// NewCommand creates the `dcos auth` subcommand.
func NewCommand(ctx api.Context) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "auth",
		Short: "Authenticate to DC/OS cluster",
	}
	cmd.AddCommand(
		newCmdAuthListProviders(ctx),
		newCmdAuthLogin(ctx),
		newCmdAuthLogout(ctx),
	)
	return cmd
}


text:
/**
<udf name="${SCISQL_PREFIX}s2PtInBox" return_type="INTEGER" section="s2">
    <desc>
        Returns 1 if the point (lon, lat) lies inside the given
        longitude/latitude angle box, and 0 otherwise. The UDF handles
        range reduction of longitudes so that one can easily test whether
        a point is inside a box spanning the 0/360 degree longitude angle
        discontinuity. However, performing this test with a UDF call will
        inhibit the optimizer from using indexes, so in some cases it may
        be preferrable to express the test in SQL.
    </desc>
    <args>
        <arg name="lon" type="DOUBLE PRECISION" units="deg">
            Longitude angle of point to test.
        </arg>
        <arg name="lat" type="DOUBLE PRECISION" units="deg">
            Latitude angle of point to test.
        </arg>
        <arg name="lonMin" type="DOUBLE PRECISION" units="deg">
            Minimum longitude angle of points in box.
        </arg>
        <arg name="latMin" type="DOUBLE PRECISION" units="deg">
            Minimum latitude angle points in box.
        </arg>
        <arg name="lonMax" type="DOUBLE PRECISION" units="deg">
            Maximum longitude angle of points in box.
        </arg>
        <arg name="latMax" type="DOUBLE PRECISION" units="deg">
            Maximum latitude angle of points in box.
        </arg>
    </args>
    <notes>
        <note>
            If any parameter is NULL, 0 is returned.
        </note>
        <note>
            If any parameter is NaN or +/-Inf, this is an error and NULL is
            returned (IEEE specials are not currently supported by MySQL).
        </note>
        <note>
            If lat, latMin or latMax lie outside of [-90, 90] degrees,
            this is an error and NULL is returned.
        </note>
        <note>
            If both lonMin and lonMax lie in the range [0, 360], then lonMax
            may be less than lonMin. For example, a box with lonMin = 350
            and lonMax = 10 includes points with longitudes in the ranges
            [350, 360) and [0, 10].
        </note>
        <note>
            If either lonMin or lonMax lies outside of [0, 360], then lonMin
            must be less than or equal to lonMax. Otherwise, NULL is returned.
            However, the two values can be arbitrarily large. If they are
            separated by 360 degrees or more, then the box spans [0, 360) in
            longitude. Otherwise, lonMin and lonMax are range reduced. So for
            example, a spherical box with lonMin = 350 and lonMax = 370
            includes longitudes in the ranges [350, 360) and [0, 10].
        </note>
        <note>
            Input values must be convertible to type DOUBLE PRECISION. If their
            actual types are BIGINT or DECIMAL, then the conversion can result
            in loss of precision and hence an inaccurate result. Loss of
            precision will not occur so long as the inputs are values of type
            DOUBLE PRECISION, FLOAT, REAL, INTEGER, SMALLINT or TINYINT.
        </note>
    </notes>
    <example>
        SELECT objectId, ra_PS, decl_PS
            FROM Object
            WHERE ${SCISQL_PREFIX}s2PtInBox(ra_PS, decl_PS, -10, 10, 10, 20) = 1;
    </example>
</udf>
*/

#include <stdio.h>

#include "mysql.h"

#include "udf.h"
#include "geometry.h"

#ifdef __cplusplus
extern "C" {
#endif

SCISQL_API my_bool SCISQL_VERSIONED_FNAME(s2PtInBox, _init) (
    UDF_INIT *initid,
    UDF_ARGS *args,
    char *message)
{
    int i;
    my_bool const_item = 1;
    if (args->arg_count != 6) {
        snprintf(message, MYSQL_ERRMSG_SIZE, SCISQL_UDF_NAME(s2PtInBox)
                 " expects exactly 6 arguments");
        return 1;
    }
    for (i = 0; i < 6; ++i) {
        args->arg_type[i] = REAL_RESULT;
        if (args->args[i] == 0) {
            const_item = 0;
        }
    }
    initid->maybe_null = 1;
    initid->const_item = const_item;
    return 0;
}

SCISQL_API long long SCISQL_VERSIONED_FNAME(s2PtInBox, SCISQL_NO_SUFFIX) (
    UDF_INIT *initid SCISQL_UNUSED,
    UDF_ARGS *args,
    char *is_null,
    char *error SCISQL_UNUSED)
{
    scisql_sc p, bmin, bmax;
    double **a = (double **) args->args;
    int i;

    /* If any input is null, the result is 0. */
    for (i = 0; i < 6; ++i) {
        if (a[i] == 0) {
            return 0;
        }
    }
    if (scisql_sc_init(&p, *a[0], *a[1]) != 0 ||
        scisql_sc_init(&bmin, *a[2], *a[3]) != 0 ||
        scisql_sc_init(&bmax, *a[4], *a[5]) != 0) {
        *is_null = 1;
        return 0;
    }

    if (bmax.lon < bmin.lon && (bmax.lon < 0.0 || bmin.lon > 360.0)) {
        *is_null = 1;
        return 0;
    }
    /* Check if latitude is in range */
    if (bmin.lat > bmax.lat || p.lat < bmin.lat || p.lat > bmax.lat) {
        return 0;
    }
    if (bmax.lon - bmin.lon >= 360.0) {
        return 1;
    }
    /* Range-reduce all longitude angles */
    p.lon = scisql_angred(p.lon);
    bmin.lon = scisql_angred(bmin.lon);
    bmax.lon = scisql_angred(bmax.lon);
    if (bmin.lon <= bmax.lon) {
        return p.lon >= bmin.lon && p.lon <= bmax.lon;
    } else {
        return p.lon >= bmin.lon || p.lon <= bmax.lon;
    }
}

SCISQL_UDF_INIT(s2PtInBox)
SCISQL_INTEGER_UDF(s2PtInBox)

#ifdef __cplusplus
} /* extern "C" */
#endif


text:
<?php
namespace Album;

use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class Module {

    // the ModuleManager will automatically call this for us
    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    // the ModuleManager will automatically call this for us
    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Album\Model\AlbumTable' =>  function($sm) {
                    $tableGateway = $sm->get('AlbumTableGateway');
                    $table = new AlbumTable($tableGateway);
                    return $table;
                },
                'AlbumTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Album());
                    return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
                },
            ),
        );
    }
}