text:
SWEP.VElements = {
	["bow"] = { type = "Model", model = "models/dawnguardd/weapon_dawnguardcrossbow_dawnguardcrossbow_loaded.mdl", bone = "Crossbow_model.Crossbow_base", rel = "", pos = Vector(-0.519, 0.518, 0), angle = Angle(-92.338, -90, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
	["arrow"] = { type = "Model", model = "models/dawnguardd/weapon_dawnguardcrossbow_dawnguardbolt.mdl", bone = "Crossbow_model.Crossbow_base", rel = "", pos = Vector(-0.519, -0, 11), angle = Angle(-87.663, 99.35, 15.194), size = Vector(1.299, 1.299, 1.299), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}

SWEP.WElements = {
	["bow"] = { type = "Model", model = "models/dawnguardd/weapon_dawnguardcrossbow_dawnguardcrossbow_loaded.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(10.909, 0, -2.597), angle = Angle(0, 180, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}

if SERVER then

   AddCSLuaFile()

end

SWEP.ViewModelBoneMods = {
	["Crossbow_model.bowr1"] = { scale = Vector(0, 0, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
	["Crossbow_model.bowl1"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
	["Crossbow_model.bowr2"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
	["Crossbow_model.bowl2"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
	["Crossbow_model.bolt"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
	["Crossbow_model.bowl_wheel"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
	["Crossbow_model.Crossbow_base"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }
}

SWEP.HoldType           = "crossbow"
SWEP.dmgtype = 1
BOLT_MODEL			= "models/dawnguardd/weapon_dwarvencrossbow_dwarvenbolt.mdl"

BOLT_AIR_VELOCITY	= 3500
BOLT_WATER_VELOCITY	= 1500
BOLT_SKIN_NORMAL	= 0
BOLT_SKIN_GLOW		= 1

CROSSBOW_GLOW_SPRITE	= "sprites/light_glow02_noz.vmt"
CROSSBOW_GLOW_SPRITE2	= "sprites/blueflare1.vmt"

if CLIENT then

   SWEP.PrintName          = "Легкий арбалет"
   SWEP.Author             = "Darsenvall"
   SWEP.Slot               = 4
   SWEP.SlotPos            = 0
   SWEP.IconLetter         = "w"
   SWEP.Icon = "VGUI/ttt/icon_crossbow"
   SWEP.DrawCrosshair = false

   SWEP.ViewModelFlip = false
end

if SERVER then
   resource.AddFile("materials/VGUI/ttt/icon_crossbow.vmt")
end

SWEP.Base               = "weapon_base"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Category = "WitcherRP"
SWEP.AutoReload = false
SWEP.Primary.Tracer = 1
SWEP.Primary.Delay          = 2
SWEP.Primary.Recoil         = 50
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "Pistol"
SWEP.ShowWorldModel = false
SWEP.Primary.Damage = 55
SWEP.Primary.NumShots		= 1
SWEP.Primary.NumAmmo		= 1
SWEP.Primary.Force = 10000000
SWEP.Primary.Cone = 0.001
SWEP.Primary.ClipSize = 1
SWEP.Primary.DefaultClip = 0
SWEP.Primary.ClipMax = 0
SWEP.AutoReload          = false
--SWEP.AmmoEnt = ""
SWEP.Primary.AmmoType		= "crossbow_bolt"
SWEP.AutoSpawnable      = false
SWEP.ViewModel = "models/weapons/v_crossbow.mdl"
SWEP.WorldModel = "models/weapons/w_crossbow.mdl"
SWEP.ViewModelFlip = false
SWEP.ViewModelFOV = 65

SWEP.Primary.Reload	= Sound( "weapons/bow/pull.wav" )
SWEP.Primary.Sound = Sound ("weapons/bow/shoot.wav")
SWEP.Primary.Special1		= Sound( "npc_med_weapons/whoosh/sword_whoosh12.wav" )
SWEP.Primary.Special2		= Sound( "npc_med_weapons/whoosh/sword_whoosh08.wav" )

SWEP.SightsPos = Vector(6.43, -6, 2.9)
SWEP.SightsAng = Vector(2, -0.1, 0)
SWEP.RunSightsPos = Vector(-1.841, -3.386, 0.708)
SWEP.RunSightsAng = Vector(-7.441, -41.614, 0)
SWEP.PrimaryAnim = ACT_VM_PRIMARYATTACK_SILENCED
SWEP.ReloadAnim = ACT_VM_RELOAD_SILENCED

function SWEP:Precache()

	util.PrecacheSound( "Weapon_Crossbow.BoltHitBody" );
	util.PrecacheSound( "Weapon_Crossbow.BoltHitWorld" );
	util.PrecacheSound( "Weapon_Crossbow.BoltSkewer" );

	util.PrecacheModel( CROSSBOW_GLOW_SPRITE );
	util.PrecacheModel( CROSSBOW_GLOW_SPRITE2 );

	self.BaseClass:Precache();

end

function SWEP:PrimaryAttack()
	if ( !self:CanPrimaryAttack() ) then return end

	if ( self.m_bInZoom && IsMultiplayer() ) then
//		self:FireSniperBolt();
		self:FireBolt();
	else
		if (SERVER) then
			self:FireBolt();
		end
	end

	// Signal a reload
	timer.Simple(3, function()
		self.m_bMustReload = true;
	end)

end

function SWEP:Deploy()
   self.Weapon:SendWeaponAnim(ACT_VM_DRAW_SILENCED)
   return true
end

function SWEP:SetZoom(state)
    if CLIENT then
       return
    else
       if state then
          self.Owner:SetFOV(20, 0.3)
       else
          self.Owner:SetFOV(0, 0.2)
       end
    end
end

-- Add some zoom to ironsights for this gun
function SWEP:SecondaryAttack()
end

function SWEP:Reload()
	timer.Simple(1, function()
		self.Weapon:DefaultReload( ACT_VM_RELOAD );
	end)
end

function SWEP:Holster()
    return true
end
if (SERVER) then
   function SWEP:FireBolt()

	if ( self.Weapon:Clip1() <= 0 && self.Primary.ClipSize > -1 ) then
	if ( self:Ammo1() > 3 ) then
			self:Reload();
	        self:ShootBullet( 150, 1, 0.01 )
		else
			self.Weapon:SetNextPrimaryFire( 5 );

		end

		return;
	end

	local pOwner = self.Owner;

	if ( pOwner == NULL ) then
		return;
	end

	local vecAiming		= pOwner:GetAimVector();
	local vecSrc		= pOwner:GetShootPos();

	local angAiming;
	angAiming = vecAiming:Angle();
	local skill = pOwner:getChar():getAttrib("bow", 0)

	local pBolt = ents.Create ( self.Primary.AmmoType );
	pBolt:SetPos( vecSrc );
	pBolt:SetAngles( angAiming );
	pBolt.Damage = self.Primary.Damage + skill*0.25
		self:ShootBullet( pBolt.Damage, 1, 0.01 )
    pBolt.AmmoType = self.Primary.Ammo;
	pBolt:SetOwner( pOwner );
	pBolt:SetModel("models/dawnguardd/weapon_dawnguardcrossbow_dawnguardbolt.mdl")
	pBolt:Spawn()

	if ( pOwner:WaterLevel() == 3 ) then
		pBolt:SetVelocity( vecAiming * BOLT_WATER_VELOCITY );
	else
		pBolt:SetVelocity( vecAiming * BOLT_AIR_VELOCITY );
	end

	self:TakePrimaryAmmo( self.Primary.NumAmmo );

	if ( !pOwner:IsNPC() ) then
		pOwner:ViewPunch( Angle( -2, 0, 0 ) );
	end

	self.Weapon:EmitSound( self.Primary.Sound );
	self.Owner:EmitSound( self.Primary.Special2 );

	self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK );

	self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay );

	// self:DoLoadEffect();
	// self:SetChargerState( CHARGER_STATE_DISCHARGE );

	end
end

/********************************************************
	SWEP Construction Kit base code
		Created by Clavus
	Available for public use, thread at:
	   facepunch.com/threads/1032378

	DESCRIPTION:
		This script is meant for experienced scripters
		that KNOW WHAT THEY ARE DOING. Don't come to me
		with basic Lua questions.

		Just copy into your SWEP or SWEP base of choice
		and merge with your own code.

		The SWEP.VElements, SWEP.WElements and
		SWEP.ViewModelBoneMods tables are all optional
		and only have to be visible to the client.
********************************************************/

function SWEP:Initialize()

    self:SetWeaponHoldType("crossbow")

	if CLIENT then

		// Create a new table for every weapon instance
		self.VElements = table.FullCopy( self.VElements )
		self.WElements = table.FullCopy( self.WElements )
		self.ViewModelBoneMods = table.FullCopy( self.ViewModelBoneMods )

		self:CreateModels(self.VElements) // create viewmodels
		self:CreateModels(self.WElements) // create worldmodels

		// init view model bone build function
		if IsValid(self.Owner) then
			local vm = self.Owner:GetViewModel()
			if IsValid(vm) then
				self:ResetBonePositions(vm)

				// Init viewmodel visibility
				if (self.ShowViewModel == nil or self.ShowViewModel) then
					vm:SetColor(Color(255,255,255,255))
				else
					// we set the alpha to 1 instead of 0 because else ViewModelDrawn stops being called
					vm:SetColor(Color(255,255,255,1))
					// ^ stopped working in GMod 13 because you have to do Entity:SetRenderMode(1) for translucency to kick in
					// however for some reason the view model resets to render mode 0 every frame so we just apply a debug material to prevent it from drawing
					vm:SetMaterial("Debug/hsv")
				end
			end
		end

	end

end

function SWEP:Holster()
	return true
end

function SWEP:OnRemove()
	self:Holster()
end

function SWEP:OnDrop()
end

function SWEP:Deploy()
	return true
end

-- SCK CODE

if CLIENT then

	SWEP.vRenderOrder = nil
	function SWEP:ViewModelDrawn()

		local vm = self.Owner:GetViewModel()
		if !IsValid(vm) then return end

		if (!self.VElements) then return end

		self:UpdateBonePositions(vm)

		if (!self.vRenderOrder) then

			// we build a render order because sprites need to be drawn after models
			self.vRenderOrder = {}

			for k, v in pairs( self.VElements ) do
				if (v.type == "Model") then
					table.insert(self.vRenderOrder, 1, k)
				elseif (v.type == "Sprite" or v.type == "Quad") then
					table.insert(self.vRenderOrder, k)
				end
			end

		end

		for k, name in ipairs( self.vRenderOrder ) do

			local v = self.VElements[name]
			if (!v) then self.vRenderOrder = nil break end
			if (v.hide) then continue end

			local model = v.modelEnt
			local sprite = v.spriteMaterial

			if (!v.bone) then continue end

			local pos, ang = self:GetBoneOrientation( self.VElements, v, vm )

			if (!pos) then continue end

			if (v.type == "Model" and IsValid(model)) then

				model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z )
				ang:RotateAroundAxis(ang:Up(), v.angle.y)
				ang:RotateAroundAxis(ang:Right(), v.angle.p)
				ang:RotateAroundAxis(ang:Forward(), v.angle.r)

				model:SetAngles(ang)
				//model:SetModelScale(v.size)
				local matrix = Matrix()
				matrix:Scale(v.size)
				model:EnableMatrix( "RenderMultiply", matrix )

				if (v.material == "") then
					model:SetMaterial("")
				elseif (model:GetMaterial() != v.material) then
					model:SetMaterial( v.material )
				end

				if (v.skin and v.skin != model:GetSkin()) then
					model:SetSkin(v.skin)
				end

				if (v.bodygroup) then
					for k, v in pairs( v.bodygroup ) do
						if (model:GetBodygroup(k) != v) then
							model:SetBodygroup(k, v)
						end
					end
				end

				if (v.surpresslightning) then
					render.SuppressEngineLighting(true)
				end

				render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255)
				render.SetBlend(v.color.a/255)
				model:DrawModel()
				render.SetBlend(1)
				render.SetColorModulation(1, 1, 1)

				if (v.surpresslightning) then
					render.SuppressEngineLighting(false)
				end

			elseif (v.type == "Sprite" and sprite) then

				local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z
				render.SetMaterial(sprite)
				render.DrawSprite(drawpos, v.size.x, v.size.y, v.color)

			elseif (v.type == "Quad" and v.draw_func) then

				local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z
				ang:RotateAroundAxis(ang:Up(), v.angle.y)
				ang:RotateAroundAxis(ang:Right(), v.angle.p)
				ang:RotateAroundAxis(ang:Forward(), v.angle.r)

				cam.Start3D2D(drawpos, ang, v.size)
					v.draw_func( self )
				cam.End3D2D()

			end

		end

	end

	SWEP.wRenderOrder = nil
	function SWEP:DrawWorldModel()

		if (self.ShowWorldModel == nil or self.ShowWorldModel) then
			self:DrawModel()
		end

		if (!self.WElements) then return end

		if (!self.wRenderOrder) then

			self.wRenderOrder = {}

			for k, v in pairs( self.WElements ) do
				if (v.type == "Model") then
					table.insert(self.wRenderOrder, 1, k)
				elseif (v.type == "Sprite" or v.type == "Quad") then
					table.insert(self.wRenderOrder, k)
				end
			end

		end

		if (IsValid(self.Owner)) then
			bone_ent = self.Owner
		else
			// when the weapon is dropped
			bone_ent = self
		end

		for k, name in pairs( self.wRenderOrder ) do

			local v = self.WElements[name]
			if (!v) then self.wRenderOrder = nil break end
			if (v.hide) then continue end

			local pos, ang

			if (v.bone) then
				pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent )
			else
				pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent, "ValveBiped.Bip01_R_Hand" )
			end

			if (!pos) then continue end

			local model = v.modelEnt
			local sprite = v.spriteMaterial

			if (v.type == "Model" and IsValid(model)) then

				model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z )
				ang:RotateAroundAxis(ang:Up(), v.angle.y)
				ang:RotateAroundAxis(ang:Right(), v.angle.p)
				ang:RotateAroundAxis(ang:Forward(), v.angle.r)

				model:SetAngles(ang)
				//model:SetModelScale(v.size)
				local matrix = Matrix()
				matrix:Scale(v.size)
				model:EnableMatrix( "RenderMultiply", matrix )

				if (v.material == "") then
					model:SetMaterial("")
				elseif (model:GetMaterial() != v.material) then
					model:SetMaterial( v.material )
				end

				if (v.skin and v.skin != model:GetSkin()) then
					model:SetSkin(v.skin)
				end

				if (v.bodygroup) then
					for k, v in pairs( v.bodygroup ) do
						if (model:GetBodygroup(k) != v) then
							model:SetBodygroup(k, v)
						end
					end
				end

				if (v.surpresslightning) then
					render.SuppressEngineLighting(true)
				end

				render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255)
				render.SetBlend(v.color.a/255)
				model:DrawModel()
				render.SetBlend(1)
				render.SetColorModulation(1, 1, 1)

				if (v.surpresslightning) then
					render.SuppressEngineLighting(false)
				end

			elseif (v.type == "Sprite" and sprite) then

				local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z
				render.SetMaterial(sprite)
				render.DrawSprite(drawpos, v.size.x, v.size.y, v.color)

			elseif (v.type == "Quad" and v.draw_func) then

				local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z
				ang:RotateAroundAxis(ang:Up(), v.angle.y)
				ang:RotateAroundAxis(ang:Right(), v.angle.p)
				ang:RotateAroundAxis(ang:Forward(), v.angle.r)

				cam.Start3D2D(drawpos, ang, v.size)
					v.draw_func( self )
				cam.End3D2D()

			end

		end

	end

	function SWEP:GetBoneOrientation( basetab, tab, ent, bone_override )

		local bone, pos, ang
		if (tab.rel and tab.rel != "") then

			local v = basetab[tab.rel]

			if (!v) then return end

			// Technically, if there exists an element with the same name as a bone
			// you can get in an infinite loop. Let's just hope nobody's that stupid.
			pos, ang = self:GetBoneOrientation( basetab, v, ent )

			if (!pos) then return end

			pos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z
			ang:RotateAroundAxis(ang:Up(), v.angle.y)
			ang:RotateAroundAxis(ang:Right(), v.angle.p)
			ang:RotateAroundAxis(ang:Forward(), v.angle.r)

		else

			bone = ent:LookupBone(bone_override or tab.bone)

			if (!bone) then return end

			pos, ang = Vector(0,0,0), Angle(0,0,0)
			local m = ent:GetBoneMatrix(bone)
			if (m) then
				pos, ang = m:GetTranslation(), m:GetAngles()
			end

			if (IsValid(self.Owner) and self.Owner:IsPlayer() and
				ent == self.Owner:GetViewModel() and self.ViewModelFlip) then
				ang.r = -ang.r // Fixes mirrored models
			end

		end

		return pos, ang
	end

	function SWEP:CreateModels( tab )

		if (!tab) then return end

		// Create the clientside models here because Garry says we can't do it in the render hook
		for k, v in pairs( tab ) do
			if (v.type == "Model" and v.model and v.model != "" and (!IsValid(v.modelEnt) or v.createdModel != v.model) and
					string.find(v.model, ".mdl") and file.Exists (v.model, "GAME") ) then

				v.modelEnt = ClientsideModel(v.model, RENDER_GROUP_VIEW_MODEL_OPAQUE)
				if (IsValid(v.modelEnt)) then
					v.modelEnt:SetPos(self:GetPos())
					v.modelEnt:SetAngles(self:GetAngles())
					v.modelEnt:SetParent(self)
					v.modelEnt:SetNoDraw(true)
					v.createdModel = v.model
				else
					v.modelEnt = nil
				end

			elseif (v.type == "Sprite" and v.sprite and v.sprite != "" and (!v.spriteMaterial or v.createdSprite != v.sprite)
				and file.Exists ("materials/"..v.sprite..".vmt", "GAME")) then

				local name = v.sprite.."-"
				local params = { ["$basetexture"] = v.sprite }
				// make sure we create a unique name based on the selected options
				local tocheck = { "nocull", "additive", "vertexalpha", "vertexcolor", "ignorez" }
				for i, j in pairs( tocheck ) do
					if (v[j]) then
						params["$"..j] = 1
						name = name.."1"
					else
						name = name.."0"
					end
				end

				v.createdSprite = v.sprite
				v.spriteMaterial = CreateMaterial(name,"UnlitGeneric",params)

			end
		end

	end

	local allbones
	local hasGarryFixedBoneScalingYet = false

	function SWEP:UpdateBonePositions(vm)

		if self.ViewModelBoneMods then

			if (!vm:GetBoneCount()) then return end

			// !! WORKAROUND !! //
			// We need to check all model names :/
			local loopthrough = self.ViewModelBoneMods
			if (!hasGarryFixedBoneScalingYet) then
				allbones = {}
				for i=0, vm:GetBoneCount() do
					local bonename = vm:GetBoneName(i)
					if (self.ViewModelBoneMods[bonename]) then
						allbones[bonename] = self.ViewModelBoneMods[bonename]
					else
						allbones[bonename] = {
							scale = Vector(1,1,1),
							pos = Vector(0,0,0),
							angle = Angle(0,0,0)
						}
					end
				end

				loopthrough = allbones
			end
			// !! ----------- !! //

			for k, v in pairs( loopthrough ) do
				local bone = vm:LookupBone(k)
				if (!bone) then continue end

				// !! WORKAROUND !! //
				local s = Vector(v.scale.x,v.scale.y,v.scale.z)
				local p = Vector(v.pos.x,v.pos.y,v.pos.z)
				local ms = Vector(1,1,1)
				if (!hasGarryFixedBoneScalingYet) then
					local cur = vm:GetBoneParent(bone)
					while(cur >= 0) do
						local pscale = loopthrough[vm:GetBoneName(cur)].scale
						ms = ms * pscale
						cur = vm:GetBoneParent(cur)
					end
				end

				s = s * ms
				// !! ----------- !! //

				if vm:GetManipulateBoneScale(bone) != s then
					vm:ManipulateBoneScale( bone, s )
				end
				if vm:GetManipulateBoneAngles(bone) != v.angle then
					vm:ManipulateBoneAngles( bone, v.angle )
				end
				if vm:GetManipulateBonePosition(bone) != p then
					vm:ManipulateBonePosition( bone, p )
				end
			end
		else
			self:ResetBonePositions(vm)
		end

	end

	function SWEP:ResetBonePositions(vm)

		if (!vm:GetBoneCount()) then return end
		for i=0, vm:GetBoneCount() do
			vm:ManipulateBoneScale( i, Vector(1, 1, 1) )
			vm:ManipulateBoneAngles( i, Angle(0, 0, 0) )
			vm:ManipulateBonePosition( i, Vector(0, 0, 0) )
		end

	end

	/**************************
		Global utility code
	**************************/

	// Fully copies the table, meaning all tables inside this table are copied too and so on (normal table.Copy copies only their reference).
	// Does not copy entities of course, only copies their reference.
	// WARNING: do not use on tables that contain themselves somewhere down the line or you'll get an infinite loop
	function table.FullCopy( tab )

		if (!tab) then return nil end

		local res = {}
		for k, v in pairs( tab ) do
			if (type(v) == "table") then
				res[k] = table.FullCopy(v) // recursion ho!
			elseif (type(v) == "Vector") then
				res[k] = Vector(v.x, v.y, v.z)
			elseif (type(v) == "Angle") then
				res[k] = Angle(v.p, v.y, v.r)
			else
				res[k] = v
			end
		end

		return res

	end

end


text:
from asserts import assert_equal
from dectest import TestCase, test

from rouver.exceptions import ArgumentsError

class ArgumentsErrorTest(TestCase):
    @test
    def message(self) -> None:
        error = ArgumentsError({"foo": "bar"})
        assert_equal("400 Bad Request: invalid arguments", str(error))

    @test
    def arguments(self) -> None:
        error = ArgumentsError({"foo": "bar"})
        assert_equal({"foo": "bar"}, error.arguments)

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function(app, passport, auth) {
    //User Routes
    var users = require('../app/controllers/users');
    app.get('/signin', users.signin);
    app.get('/signup', users.signup);
    app.get('/signout', users.signout);
    app.get('/users/me', users.me);

    //Setting up the users api
    app.post('/users', users.create);

    //Setting the local strategy route
    app.post('/users/session', passport.authenticate('local', {
        failureRedirect: '/signin',
        failureFlash: true
    }), users.session);

    //Setting the facebook oauth routes
    app.get('/auth/facebook', passport.authenticate('facebook', {
        scope: ['email', 'user_about_me'],
        failureRedirect: '/signin'
    }), users.signin);

    app.get('/auth/facebook/callback', passport.authenticate('facebook', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Setting the github oauth routes
    app.get('/auth/github', passport.authenticate('github', {
        failureRedirect: '/signin'
    }), users.signin);

    app.get('/auth/github/callback', passport.authenticate('github', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Setting the twitter oauth routes
    app.get('/auth/twitter', passport.authenticate('twitter', {
        failureRedirect: '/signin'
    }), users.signin);

    app.get('/auth/twitter/callback', passport.authenticate('twitter', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Setting the google oauth routes
    app.get('/auth/google', passport.authenticate('google', {
        failureRedirect: '/signin',
        scope: [
            'https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email'
        ]
    }), users.signin);

    app.get('/auth/google/callback', passport.authenticate('google', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Finish with setting up the userId param
    app.param('userId', users.user);

    //Article Routes
    var articles = require('../app/controllers/articles');
    app.get('/articles', articles.all);
    app.post('/articles', auth.requiresLogin, articles.create);
    app.get('/articles/:articleId', articles.show);
    app.put('/articles/:articleId', auth.requiresLogin, auth.article.hasAuthorization, articles.update);
    app.del('/articles/:articleId', auth.requiresLogin, auth.article.hasAuthorization, articles.destroy);

    //Finish with setting up the articleId param
    app.param('articleId', articles.article);

    //Home route
    var index = require('../app/controllers/index');
    app.get('/', index.render);

};


text:
package com.esri;

import ch.hsr.geohash.BoundingBox;
import ch.hsr.geohash.GeoHash;
import ch.hsr.geohash.WGS84Point;
import ch.hsr.geohash.queries.GeoHashBoundingBoxQuery;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 */
public class BoundingBoxScanTest
{
    protected final static byte[] TABLE_NAME = "test".getBytes();

    private final HBaseTestingUtility m_testUtil = new HBaseTestingUtility();

    @Before
    public void setUp() throws Exception
    {
        m_testUtil.startMiniCluster();
    }

    @Test
    public void testBoundingBoxScan() throws IOException
    {
        m_testUtil.createTable(TABLE_NAME, Const.ATTR);
        try
        {
            final HTableInterface table = new HTable(m_testUtil.getConfiguration(), TABLE_NAME);
            try
            {
                putLatLon(table);
                scanBox(table);
            }
            finally
            {
                table.close();
            }
        }
        finally
        {
            m_testUtil.deleteTable(TABLE_NAME);
        }
    }

    private void scanBox(final HTableInterface table) throws IOException
    {
        final List<WGS84Point> list = new ArrayList<WGS84Point>();
        final BoundingBox boundingBox = new BoundingBox(0.5, 1.5, 0.5, 1.5);
        final GeoHashBoundingBoxQuery geoHashBoundingBoxQuery = new GeoHashBoundingBoxQuery(boundingBox);
        final List<GeoHash> searchHashes = geoHashBoundingBoxQuery.getSearchHashes();
        for (final GeoHash geoHash : searchHashes)
        {
            scanGeoHash(table, geoHash, boundingBox, list);
        }
        Assert.assertEquals(1, list.size());
        final WGS84Point point = list.get(0);
        Assert.assertEquals(1.0, point.getLatitude(), 0.000001);
        Assert.assertEquals(1.0, point.getLongitude(), 0.000001);
    }

    private void scanGeoHash(
            final HTableInterface table,
            final GeoHash geoHash,
            final BoundingBox boundingBox,
            final List<WGS84Point> list) throws IOException
    {
        final Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(geoHash.longValue()));
        scan.setStopRow(Bytes.toBytes(geoHash.next().longValue()));
        scan.setMaxVersions(1);
        scan.setCaching(50);
        scan.setFilter(new BoundingBoxFilter(boundingBox));
        final ResultScanner scanner = table.getScanner(scan);
        try
        {
            for (final Result result : scanner)
            {
                final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(result.getRow());
                final DataInput dataInput = new DataInputStream(byteArrayInputStream);
                final long bits = dataInput.readLong();
                final double lon = dataInput.readDouble();
                final double lat = dataInput.readDouble();
                list.add(new WGS84Point(lat, lon));
            }
        }
        finally
        {
            scanner.close();
        }
    }

    private void putLatLon(final HTableInterface table) throws IOException
    {
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(64);
        final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        int id = 0;
        for (double c = -10; c < 10; c++)
        {
            byteArrayOutputStream.reset();
            dataOutputStream.writeLong(Quad.encode(c, c));
            dataOutputStream.writeDouble(c);
            dataOutputStream.writeDouble(c);
            final Put put = new Put(byteArrayOutputStream.toByteArray());
            put.add(Const.ATTR,
                    Const.ID,
                    Bytes.toBytes(id++));
            table.put(put);
        }
    }

    @After
    public void tearDown() throws Exception
    {
        m_testUtil.shutdownMiniCluster();
    }

}


text:
require 'spec_helper'

describe RuboCop::Cop::Style::UnlessElse do
  subject(:cop) { described_class.new }

  context 'unless with else' do
    let(:source) do
      ['unless x # negative 1',
       '  a = 1 # negative 2',
       'else # positive 1',
       '  a = 0 # positive 2',
       'end']
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
    end

    it 'auto-corrects' do
      corrected = autocorrect_source(cop, source)
      expect(corrected).to eq(['if x # positive 1',
                               '  a = 0 # positive 2',
                               'else # negative 1',
                               '  a = 1 # negative 2',
                               'end'].join("\n"))
    end
  end

  it 'accepts an unless without else' do
    inspect_source(cop, ['unless x',
                         '  a = 1',
                         'end'])
    expect(cop.offenses).to be_empty
  end
end


text:
name "setuptools-py3"
default_version "28.8.0"

dependency "python3"

relative_path "setuptools-#{version}"

source url: "https://github.com/pypa/setuptools/archive/v#{version}.tar.gz",
       sha256: "d3b2c63a5cb6816ace0883bc3f6aca9e7890c61d80ac0d608a183f85825a7cc0"

build do
  python_path = "#{install_dir}/embedded/bin/python"
  if ohai["platform"] == "windows"
    python_path = "#{windows_safe_path(python_3_embedded)}\\python.exe"
  end

  license "Python-2.0"
  command "#{python_path} bootstrap.py"
  command "#{python_path} setup.py install --prefix=#{windows_safe_path(python_3_embedded)}"
end


text:
local Server = require "Server"
local server = Server()

server:start()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Ahmad Musleh's Personal Website">
    <meta name="author" content="Ahmad Musleh amusleh">

    <title>Ahmad Musleh - Personal Website</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="css/grayscale.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                    Ahmad Musleh

                        About

                        Pitch

                        Publications

                        Projects

                        Personal

                        Contact

Ahmad Musleh

A more than one page Curriculum Vitae.

About Me

Hey there kind internet surfer! I'd like to personally welcome you to my personal webpage (Pun intended). Let me be your guide.

I'm a graduate in Computer Science from Carnegie Mellon University with a minor in Business Administration

I've taken it upon my self to put them to work and form my own adaptation of the 4 P's in marketing. You will find them in the top right.
                That is the breakdown of my current website.

 The Elevator Pitch shall provide an overview of me and my work experience.

                    Publications provides a list of published papers in peer reviewed conferences.

                    Projects lists all the fun and interesting projects I have done/contributed to.

                    Personal is the non-corporate side of me where my interests and extra curriculars lie.

                    Enjoy!

Elevator Pitch

Hey there! I'm a computer science graduate from Carnegie Mellon. I've had the opportunity to take a vibrant range of courses ranging from
                      Distributed Systems to Software Construction to Embedded Systems.

                      My next adventure is exploring the computational side of data science and working with large
                      amounts of data. I am currently a Software Engineer working in the Qatar Computing Research Institute (QCRI) helping in productizing the reseach done here.

                      I've worked on a vibrant range of projects in different institutes. These projects range from Cybersecurity to Distributed Systems to Language Technologies.
                      My current interests lie in managing datasets. I plan on being a Data Engineer and think of it as a stepping stone to becoming a Data Scientist.

Contact Me

Feel free to email me for feedback on this website, ideas or even book recommendations!

ahmad.s.musleh@gmail.com

                       Github

                       Linkedin


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest>
  <!-- associated voice handler -->
  <voice id="org.OpenT2T.Voice.Cortana.Vcd.Sample.SuperPopular.ShadeControl" />
  <!-- associated schema -->
  <schema id="org.opent2t.sample.windowshade.superpopular" />
  <!-- associated onboarding module -->
  <onboarding id="org.opent2t.onboarding.manual">
    <arg name="name" value="Test Shade" />
    <arg name="instructionsUrl" value="http://example.com" />
  </onboarding>
</manifest>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <title>DNS client for OpenResty</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />

<big></big>

lua-resty-dns-client

Index

Contents

Functions

Modules

resty.dns.balancer.base

resty.dns.balancer.handle

resty.dns.balancer.least_connections

resty.dns.balancer.ring

resty.dns.client

resty.dns.utils

Topics

README

Module resty.dns.balancer.handle

Handle module.

 Implements handles to be used by the objBalancer:getPeer method. These
 implement a __gc method for tracking statistics and not leaking resources
 in case a connection gets aborted prematurely.

 This module is only relevant when implementing your own balancer
 algorithms.

Info:

Copyright: 2016-2020 Kong Inc. All rights reserved.

License: Apache 2.0

Author: Thijs Schreijer

Functions

	get (__gc)
	Gets a handle from the cache.

	release (handle)
	Returns a handle to the cache.

	setCacheSize (size)
	Sets a new cache size.

Functions

    get (__gc)

    Gets a handle from the cache.
 The handle comes from the cache or it is newly created. A handle is just a
 table. It will have two special fields:

__udata: (read-only) a userdata used to track the lifetime of the handle

__gc: (read/write) this method will be called on GC.

 NOTE: the __gc will only be called when the handle is garbage collected,
 not when it is returned by calling release.

Parameters:

__gc
         (optional, function) the method called when the handle is GC'ed.

Returns:

        handle

Usage:

local handle = _M

local my_gc_handler = function(self)
  print(self.name .. " was deleted")
end

local h1 = handle.get(my_gc_handler)
h1.name = "Obama"
local h2 = handle.get(my_gc_handler)
h2.name = "Trump"

handle.release(h1)   -- explicitly release it
h1 = nil
h2 = nil             -- not released, will be GC'ed
collectgarbage()
collectgarbage()     --> "Trump was deleted"

    release (handle)

    Returns a handle to the cache.
 The handle will be cleared, returned to the cache, and its __gc handle
 will NOT be called.

Parameters:

handle
         the handle to return to the cache

Returns:

        nothing

    setCacheSize (size)

    Sets a new cache size.  The default size is 1000.

Parameters:

size
         the new size.

Returns:

        nothing, or throws an error on bad input

generated by LDoc 1.4.6
Last updated 2020-05-14 12:24:23


text:
package org.hisp.dhis.webapi.controller.sms;

import static org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict;
import static org.hisp.dhis.dxf2.webmessage.WebMessageUtils.error;
import static org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound;
import static org.hisp.dhis.dxf2.webmessage.WebMessageUtils.ok;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hisp.dhis.common.DhisApiVersion;
import org.hisp.dhis.dxf2.webmessage.WebMessage;
import org.hisp.dhis.message.MessageSender;
import org.hisp.dhis.outboundmessage.OutboundMessageResponse;
import org.hisp.dhis.render.RenderService;
import org.hisp.dhis.sms.outbound.OutboundSms;
import org.hisp.dhis.sms.outbound.OutboundSmsService;
import org.hisp.dhis.webapi.controller.AbstractCrudController;
import org.hisp.dhis.webapi.mvc.annotation.ApiVersion;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Zubair Asghar
 */

@RestController
@RequestMapping( value = "/sms/outbound" )
@ApiVersion( { DhisApiVersion.DEFAULT, DhisApiVersion.ALL } )
public class SmsOutboundController extends AbstractCrudController<OutboundSms>
{
    private final MessageSender smsSender;

    private final RenderService renderService;

    private final OutboundSmsService outboundSmsService;

    public SmsOutboundController(
        @Qualifier( "smsMessageSender" ) MessageSender smsSender,
        RenderService renderService,
        OutboundSmsService outboundSmsService )
    {
        this.smsSender = smsSender;
        this.renderService = renderService;
        this.outboundSmsService = outboundSmsService;
    }

    // -------------------------------------------------------------------------
    // POST
    // -------------------------------------------------------------------------

    @PreAuthorize( "hasRole('ALL') or hasRole('F_MOBILE_SENDSMS')" )
    @PostMapping( produces = APPLICATION_JSON_VALUE )
    @ResponseBody
    public WebMessage sendSMSMessage( @RequestParam String recipient, @RequestParam String message )
    {
        if ( recipient == null || recipient.length() <= 0 )
        {
            return conflict( "Recipient must be specified" );
        }

        if ( message == null || message.length() <= 0 )
        {
            return conflict( "Message must be specified" );
        }

        OutboundMessageResponse status = smsSender.sendMessage( null, message, recipient );

        if ( status.isOk() )
        {
            return ok( "SMS sent" );
        }
        return error( status.getDescription() );
    }

    @PreAuthorize( "hasRole('ALL') or hasRole('F_MOBILE_SENDSMS')" )
    @PostMapping( consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE )
    @ResponseBody
    public WebMessage sendSMSMessage( HttpServletRequest request )
        throws IOException
    {
        OutboundSms sms = renderService.fromJson( request.getInputStream(), OutboundSms.class );

        OutboundMessageResponse status = smsSender.sendMessage( null, sms.getMessage(), sms.getRecipients() );

        if ( status.isOk() )
        {
            return ok( "SMS sent" );
        }
        return error( status.getDescription() );
    }

    // -------------------------------------------------------------------------
    // DELETE
    // -------------------------------------------------------------------------

    @DeleteMapping( value = "/{uid}", produces = APPLICATION_JSON_VALUE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_MOBILE_SETTINGS')" )
    @ResponseBody
    public WebMessage deleteOutboundMessage( @PathVariable String uid )
    {
        OutboundSms sms = outboundSmsService.get( uid );

        if ( sms == null )
        {
            return notFound( "No OutboundSms with id '" + uid + "' was found." );
        }

        outboundSmsService.delete( uid );

        return ok( "OutboundSms with " + uid + " deleted" );
    }

    @DeleteMapping( produces = APPLICATION_JSON_VALUE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_MOBILE_SETTINGS')" )
    @ResponseBody
    public WebMessage deleteOutboundMessages( @RequestParam List<String> ids )
    {
        ids.forEach( outboundSmsService::delete );

        return ok( "Objects deleted" );
    }
}


text:
package inet

import (
	"context"
	"fmt"
	"net"
	"strings"
	"time"
)

const DefaultHostname = "localhost.loki"
const DefaultPort = "6888"

type Session struct {
	localIP   net.IP
	localAddr string
	name      string
	port      string
	serv      net.Listener
	packet    net.PacketConn
	resolver  net.Resolver
}

func NewSession(port, dns string) (s *Session, err error) {
	var found []net.IP
	found, err = net.LookupIP(DefaultHostname)
	if err != nil {
		return
	}
	localIP := found[0]
	ss := &Session{
		port:      port,
		localIP:   localIP,
		localAddr: net.JoinHostPort(localIP.String(), port),
		resolver: net.Resolver{
			Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
				var d net.Dialer
				return d.DialContext(ctx, "udp", dns)
			},
		},
	}
	var names []string
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	names, err = ss.resolver.LookupAddr(ctx, ss.localIP.String())
	if err != nil {
		return
	}
	if len(names) == 0 {
		err = fmt.Errorf("we have no rdns record for %s", localIP)
		return
	}
	ss.name = strings.TrimSuffix(names[0], ".")
	s = ss
	return
}

func (s *Session) LocalName() string {
	return s.name
}

func (s *Session) Dial(_, a string) (net.Conn, error) {
	h, p, err := net.SplitHostPort(a)
	if err != nil {
		return nil, err
	}
	raddr, err := s.lookupTCP(h, p)
	if err != nil {
		return nil, err
	}
	localAddr := net.JoinHostPort(s.localIP.String(), "0")
	laddr, err := net.ResolveTCPAddr("tcp4", localAddr)
	if err != nil {
		return nil, err
	}
	c, err := net.DialTCP("tcp4", laddr, raddr)
	if err != nil {
		return nil, err
	}
	return s.wrapConn(c)
}

func (s *Session) wrapConn(c net.Conn) (*Conn, error) {
	raddr := c.RemoteAddr()
	h, port, err := net.SplitHostPort(raddr.String())
	if err != nil {
		c.Close()
		return nil, err
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()
	names, err := s.resolver.LookupAddr(ctx, h)
	if err != nil {
		c.Close()
		return nil, err
	}
	return &Conn{
		c: c,
		laddr: &Addr{
			name: s.name,
			port: s.port,
		},
		raddr: &Addr{
			name: strings.TrimSuffix(names[0], "."),
			port: port,
		},
	}, nil
}

type Listener struct {
	l     net.Listener
	laddr *Addr
}

func (l *Listener) Addr() net.Addr {
	return l.laddr
}

func (l *Listener) Close() error {
	return l.l.Close()
}

func (l *Listener) Accept() (net.Conn, error) {
	return l.l.Accept()
}

func NewAddr(n, p string) *Addr {
	return &Addr{
		name: n,
		port: p,
	}
}

type Addr struct {
	name string
	port string
}

func (a *Addr) Network() string {
	return "tcp"
}

func (a *Addr) String() string {
	return net.JoinHostPort(a.name, a.port)
}

type Conn struct {
	c     net.Conn
	laddr *Addr
	raddr *Addr
}

// implements net.Conn
func (c *Conn) Read(d []byte) (n int, err error) {
	n, err = c.c.Read(d)
	return
}

// implements net.Conn
func (c *Conn) Write(d []byte) (n int, err error) {
	n, err = c.c.Write(d)
	return
}

// implements net.Conn
func (c *Conn) Close() error {
	return c.c.Close()
}

// implements net.Conn
func (c *Conn) LocalAddr() net.Addr {
	return c.laddr
}

// implements net.Conn
func (c *Conn) RemoteAddr() net.Addr {
	return c.raddr
}

// implements net.Conn
func (c *Conn) SetDeadline(t time.Time) error {
	return c.c.SetDeadline(t)
}

// implements net.Conn
func (c *Conn) SetReadDeadline(t time.Time) error {
	return c.c.SetReadDeadline(t)
}

// implements net.Conn
func (c *Conn) SetWriteDeadline(t time.Time) error {
	return c.c.SetWriteDeadline(t)
}

func (s *Session) Accept() (net.Conn, error) {
	c, err := s.serv.Accept()
	if err != nil {
		return nil, err
	}
	return s.wrapConn(c)
}

func (s *Session) Open() error {
	l, err := net.Listen("tcp", s.localAddr)
	if err != nil {
		return err
	}
	_, port, err := net.SplitHostPort(l.Addr().String())
	if err != nil {
		return err
	}
	s.serv = &Listener{
		l: l,
		laddr: &Addr{
			name: s.name,
			port: port,
		},
	}
	return nil
}

func (s *Session) ReadFrom(d []byte) (n int, from net.Addr, err error) {
	return
}

func (s *Session) WriteTo(d []byte, to net.Addr) (n int, err error) {
	return
}

func (s *Session) Close() error {
	return s.serv.Close()
}

func (s *Session) Addr() net.Addr {
	if s.serv == nil {
		return nil
	}
	return s.serv.Addr()
}

func (s *Session) Lookup(name, port string) (addr net.Addr, err error) {
	return s.lookupTCP(name, port)
}

func (s *Session) lookupTCP(name, port string) (addr *net.TCPAddr, err error) {
	var ips []net.IPAddr
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	ips, err = s.resolver.LookupIPAddr(ctx, name)
	if err == nil {
		for _, ip := range ips {
			tcpaddr := &net.TCPAddr{
				IP: ip.IP,
			}
			tcpaddr.Port, err = net.LookupPort(tcpaddr.Network(), port)
			if err == nil {
				addr = tcpaddr
				return
			}
		}
	}
	return
}


text:
package org.apache.flink.runtime.state;

import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.core.testutils.OneShotLatch;
import org.apache.flink.util.Preconditions;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import javax.annotation.Nonnull;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/** Tests for {@link AsyncSnapshotCallable}. */
public class AsyncSnapshotCallableTest {

    private static final String METHOD_CALL = "callInternal";
    private static final String METHOD_LOG = "logAsyncSnapshotComplete";
    private static final String METHOD_CLEANUP = "cleanupProvidedResources";
    private static final String METHOD_CANCEL = "cancel";
    private static final String SUCCESS = "Success!";

    private CloseableRegistry ownerRegistry;
    private TestBlockingCloseable testProvidedResource;
    private TestBlockingCloseable testBlocker;
    private TestAsyncSnapshotCallable testAsyncSnapshotCallable;
    private FutureTask<String> task;

    @Before
    public void setup() throws IOException {
        ownerRegistry = new CloseableRegistry();
        testProvidedResource = new TestBlockingCloseable();
        testBlocker = new TestBlockingCloseable();
        testAsyncSnapshotCallable =
                new TestAsyncSnapshotCallable(testProvidedResource, testBlocker);
        task = testAsyncSnapshotCallable.toAsyncSnapshotFutureTask(ownerRegistry);
        Assert.assertEquals(1, ownerRegistry.getNumberOfRegisteredCloseables());
    }

    @After
    public void finalChecks() {
        Assert.assertTrue(testProvidedResource.isClosed());
        Assert.assertEquals(0, ownerRegistry.getNumberOfRegisteredCloseables());
    }

    @Test
    public void testNormalRun() throws Exception {

        Thread runner = startTask(task);

        while (testBlocker.getWaitersCount() < 1) {
            Thread.sleep(1L);
        }

        testBlocker.unblockSuccessfully();

        runner.join();

        Assert.assertEquals(SUCCESS, task.get());
        Assert.assertEquals(
                Arrays.asList(METHOD_CALL, METHOD_LOG, METHOD_CLEANUP),
                testAsyncSnapshotCallable.getInvocationOrder());

        Assert.assertTrue(testBlocker.isClosed());
    }

    @Test
    public void testExceptionRun() throws Exception {

        testBlocker.introduceException();
        Thread runner = startTask(task);

        while (testBlocker.getWaitersCount() < 1) {
            Thread.sleep(1L);
        }

        testBlocker.unblockSuccessfully();
        try {
            task.get();
            Assert.fail();
        } catch (ExecutionException ee) {
            Assert.assertEquals(IOException.class, ee.getCause().getClass());
        }

        runner.join();

        Assert.assertEquals(
                Arrays.asList(METHOD_CALL, METHOD_CLEANUP),
                testAsyncSnapshotCallable.getInvocationOrder());

        Assert.assertTrue(testBlocker.isClosed());
    }

    @Test
    public void testCancelRun() throws Exception {

        Thread runner = startTask(task);

        while (testBlocker.getWaitersCount() < 1) {
            Thread.sleep(1L);
        }

        task.cancel(true);
        testBlocker.unblockExceptionally();

        try {
            task.get();
            Assert.fail();
        } catch (CancellationException ignored) {
        }

        runner.join();

        Assert.assertEquals(
                Arrays.asList(METHOD_CALL, METHOD_CANCEL, METHOD_CLEANUP),
                testAsyncSnapshotCallable.getInvocationOrder());
        Assert.assertTrue(testProvidedResource.isClosed());
        Assert.assertTrue(testBlocker.isClosed());
    }

    @Test
    public void testCloseRun() throws Exception {

        Thread runner = startTask(task);

        while (testBlocker.getWaitersCount() < 1) {
            Thread.sleep(1L);
        }

        ownerRegistry.close();

        try {
            task.get();
            Assert.fail();
        } catch (CancellationException ignored) {
        }

        runner.join();

        Assert.assertEquals(
                Arrays.asList(METHOD_CALL, METHOD_CANCEL, METHOD_CLEANUP),
                testAsyncSnapshotCallable.getInvocationOrder());
        Assert.assertTrue(testBlocker.isClosed());
    }

    @Test
    public void testCancelBeforeRun() throws Exception {

        task.cancel(true);

        Thread runner = startTask(task);

        try {
            task.get();
            Assert.fail();
        } catch (CancellationException ignored) {
        }

        runner.join();

        Assert.assertEquals(
                Arrays.asList(METHOD_CANCEL, METHOD_CLEANUP),
                testAsyncSnapshotCallable.getInvocationOrder());

        Assert.assertTrue(testProvidedResource.isClosed());
    }

    private Thread startTask(Runnable task) {
        Thread runner = new Thread(task);
        runner.start();
        return runner;
    }

    /** Test implementation of {@link AsyncSnapshotCallable}. */
    private static class TestAsyncSnapshotCallable extends AsyncSnapshotCallable<String> {

        @Nonnull private final TestBlockingCloseable providedResource;
        @Nonnull private final TestBlockingCloseable blockingResource;
        @Nonnull private final List<String> invocationOrder;

        TestAsyncSnapshotCallable(
                @Nonnull TestBlockingCloseable providedResource,
                @Nonnull TestBlockingCloseable blockingResource) {

            this.providedResource = providedResource;
            this.blockingResource = blockingResource;
            this.invocationOrder = new ArrayList<>();
        }

        @Override
        protected String callInternal() throws Exception {

            addInvocation(METHOD_CALL);
            snapshotCloseableRegistry.registerCloseable(blockingResource);
            try {
                blockingResource.simulateBlockingOperation();
            } finally {
                if (snapshotCloseableRegistry.unregisterCloseable(blockingResource)) {
                    blockingResource.close();
                }
            }

            return SUCCESS;
        }

        @Override
        protected void cleanupProvidedResources() {
            addInvocation(METHOD_CLEANUP);
            providedResource.close();
        }

        @Override
        protected void logAsyncSnapshotComplete(long startTime) {
            invocationOrder.add(METHOD_LOG);
        }

        @Override
        protected void cancel() {
            addInvocation(METHOD_CANCEL);
            super.cancel();
        }

        @Nonnull
        public List<String> getInvocationOrder() {
            synchronized (invocationOrder) {
                return new ArrayList<>(invocationOrder);
            }
        }

        private void addInvocation(@Nonnull String invocation) {
            synchronized (invocationOrder) {
                invocationOrder.add(invocation);
            }
        }
    }

    /** Mix of a {@link Closeable} and and some {@link OneShotLatch} functionality for testing. */
    private static class TestBlockingCloseable implements Closeable {

        private final OneShotLatch blockerLatch = new OneShotLatch();
        private boolean closed = false;
        private boolean unblocked = false;
        private boolean exceptionally = false;

        public void simulateBlockingOperation() throws IOException {
            while (!unblocked) {
                try {
                    blockerLatch.await();
                } catch (InterruptedException e) {
                    blockerLatch.reset();
                }
            }
            if (exceptionally) {
                throw new IOException("Closed in block");
            }
        }

        @Override
        public void close() {
            Preconditions.checkState(!closed);
            this.closed = true;
            unblockExceptionally();
        }

        public boolean isClosed() {
            return closed;
        }

        public void unblockExceptionally() {
            introduceException();
            unblock();
        }

        public void unblockSuccessfully() {
            unblock();
        }

        private void unblock() {
            this.unblocked = true;
            blockerLatch.trigger();
        }

        public void introduceException() {
            this.exceptionally = true;
        }

        public int getWaitersCount() {
            return blockerLatch.getWaitersCount();
        }
    }
}


text:
<?php

namespace spec\Nikapps\NikPay\PaymentProviders\Saman;

use Nikapps\NikPay\Exceptions\DuplicateReferenceException;
use Nikapps\NikPay\Exceptions\FailedPaymentException;
use Nikapps\NikPay\Exceptions\NotEqualAmountException;
use Nikapps\NikPay\Exceptions\NotVerifiedException;
use Nikapps\NikPay\InvoiceVerifier;
use Nikapps\NikPay\PaymentProviders\Saman\SamanConfig;
use Nikapps\NikPay\Purchase;
use Nikapps\NikPay\Soap\SoapService;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class SamanSpec extends ObjectBehavior
{
    public function let(SoapService $soap, SamanConfig $samanConfig)
    {
        $this->beConstructedWith($soap, $samanConfig);
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType('Nikapps\NikPay\PaymentProviders\Saman\Saman');
    }

    public function it_should_fetch_token_for_given_purchase_and_return_form_data(
        Purchase $purchase,
        $samanConfig,
        $soap
    ) {
        $config = $this->getDefaultConfig();

        $this->mockConfig($samanConfig);
        $this->mockSoapConnection($soap, $config['token_wsdl'], $config['soap_options']);

        $purchase->getAmountInRial()->willReturn(1000);
        $purchase->getInvoice()->willReturn('inv-123-123-123');
        $purchase->getOptions()->willReturn(['Wage' => 800]);

        $params = [
            'TermID'      => $config['merchant'],
            'ResNUM'      => 'inv-123-123-123',
            'TotalAmount' => 1000,
            'Wage'        => 800
        ];

        $soap->call('RequestToken', $params)->willReturn('token-123456');

        $this->prepare($purchase);
        $this->form()->shouldHaveKeyWithValue('token', 'token-123456');
    }

    public function it_should_generate_custom_html_form($samanConfig)
    {
        $this->mockConfig($samanConfig);
        $config = $this->getDefaultConfig();

        $form = '{token}, {gateway}, {redirect}';
        $output = "token-123-123, {$config['gateway']}, {$config['redirect_url']}";

        $this->generateForm($form, 'token-123-123')->shouldBe($output);
    }

    public function it_should_call_closure_when_a_closure_passed($samanConfig)
    {
        $this->mockConfig($samanConfig);
        $config = $this->getDefaultConfig();

        $form = $this->generateForm(
            function (array $data) {

                return $data;

            },
            'token-123-123'
        );

        $form->shouldHaveKeyWithValue('token', 'token-123-123');
        $form->shouldHaveKeyWithValue('gateway', $config['gateway']);
        $form->shouldHaveKeyWithValue('redirect', $config['redirect_url']);
    }

    public function it_should_generate_default_html_form($samanConfig)
    {
        $this->mockConfig($samanConfig);
        $config = $this->getDefaultConfig();

        $output = '<form action="' . $config['gateway'] . '" method="post" id="payment">
    <input type="hidden" name="Token" value="token-123-123"/>
    <input type="hidden" name="RedirectURL" value="' . $config['redirect_url'] . '"/>
</form>

';

        $this->generateForm(null, 'token-123-123')->shouldBe($output);
    }

    public function it_should_verify_payment_and_return_amount($soap, $samanConfig)
    {
        $config = $this->getDefaultConfig();

        $this->mockConfig($samanConfig);
        $this->mockSoapConnection($soap, $config['wsdl'], $config['soap_options']);

        $params = [
            'ref-123-123',
            $config['merchant']
        ];

        $soap->call('verifyTransaction', $params)->willReturn(1000);

        $this->verify('ref-123-123')->shouldBe(1000);
    }

    public function it_should_throw_an_exception_when_verifying_is_failed($soap, $samanConfig)
    {
        $config = $this->getDefaultConfig();

        $this->mockConfig($samanConfig);
        $this->mockSoapConnection($soap, $config['wsdl'], $config['soap_options']);

        $params = [
            'ref-123-123',
            $config['merchant']
        ];

        $soap->call('verifyTransaction', $params)->willReturn(-3);

        $this->shouldThrow(
            new NotVerifiedException('Payment is not verified by bank', -3)
        )->duringVerify('ref-123-123');
    }

    public function it_should_throw_an_exception_when_creating_soap_client_is_failed($soap, $samanConfig)
    {
        $this->mockConfig($samanConfig, ['wsdl' => 'bad_url', 'soap_options' => null]);

        $soap->wsdl('bad_url')->willReturn($soap);
        $soap->options(null)->willReturn($soap);

        $soap->createClient()->willThrow('\Nikapps\NikPay\Exceptions\SoapException');

        $this->shouldThrow('\Nikapps\NikPay\Exceptions\SoapException')
            ->duringVerify('ref-123-123');
    }

    public function it_should_handle_callback_and_generate_result($soap, $samanConfig, InvoiceVerifier $invoiceVerifier)
    {
        $config = $this->getDefaultConfig();

        $this->mockConfig($samanConfig);
        $this->mockSoapConnection($soap, $config['wsdl'], $config['soap_options']);

        $post = [
            'State'   => 'OK',
            'RefNum'  => 'ref-123-123',
            'ResNum'  => 'inv-123-123',
            'TRACENO' => 'trace-123-123'
        ];

        $params = [
            'ref-123-123',
            $config['merchant']
        ];

        $soap->call('verifyTransaction', $params)->willReturn(1000);

        $invoiceVerifier->verifyReference('ref-123-123')->willReturn(true);
        $invoiceVerifier->verifyAmount('inv-123-123', 1000)->willReturn(true);

        $this->invoiceVerifier($invoiceVerifier);
        $this->handleCallback($post);

        $result = $this->getResult();

        $result->merchant()->shouldBe($config['merchant']);
        $result->invoice()->shouldBe('inv-123-123');
        $result->state()->shouldBe('OK');
        $result->reference()->shouldBe('ref-123-123');
        $result->traceNumber()->shouldBe('trace-123-123');
        $result->amount()->shouldBe(1000);
        $result->amountInToman()->shouldBe(100);
    }

    public function it_should_throw_an_exception_when_post_data_is_invalid()
    {
        $post = [
            'invalid_state_key' => 'OK',
            'RefNum'            => 'ref-123-123',
            'ResNum'            => 'inv-123-123',
            'TRACENO'           => 'trace-123-123'
        ];

        $this->shouldThrow('\Nikapps\NikPay\Exceptions\InvalidPostDataException')
            ->duringHandleCallback($post);
    }

    public function it_should_throw_an_exception_when_state_is_not_ok()
    {
        $post = [
            'State'   => 'Canceled By User',
            'RefNum'  => 'ref-123-123',
            'ResNum'  => 'inv-123-123',
            'TRACENO' => 'trace-123-123'
        ];

        $this->shouldThrow((new FailedPaymentException)->setState('Canceled By User'))
            ->duringHandleCallback($post);
    }

    public function it_should_throw_an_exception_when_amount_is_not_equal(
        $soap,
        $samanConfig,
        InvoiceVerifier $invoiceVerifier
    ) {
        $config = $this->getDefaultConfig();

        $this->mockConfig($samanConfig);
        $this->mockSoapConnection($soap, $config['wsdl'], $config['soap_options']);

        $post = [
            'State'   => 'OK',
            'RefNum'  => 'ref-123-123',
            'ResNum'  => 'inv-123-123',
            'TRACENO' => 'trace-123-123'
        ];

        $params = [
            'ref-123-123',
            $config['merchant']
        ];

        $soap->call('verifyTransaction', $params)->willReturn(1200);

        $invoiceVerifier->verifyReference('ref-123-123')->willReturn(true);
        $invoiceVerifier->verifyAmount('inv-123-123', 1200)->willReturn(false);

        $this->invoiceVerifier($invoiceVerifier);

        $exception = (new NotEqualAmountException)
            ->setBankAmount(1200)
            ->setInvoice('inv-123-123')
            ->setReference('ref-123-123');

        $this->shouldThrow($exception)->duringHandleCallback($post);
    }

    public function it_should_throw_an_exception_when_reference_already_exists(
        $samanConfig,
        InvoiceVerifier $invoiceVerifier
    ) {
        $this->mockConfig($samanConfig);

        $post = [
            'State'   => 'OK',
            'RefNum'  => 'ref-123-123',
            'ResNum'  => 'inv-123-123',
            'TRACENO' => 'trace-123-123'
        ];

        $invoiceVerifier->verifyReference('ref-123-123')->willReturn(false);

        $this->invoiceVerifier($invoiceVerifier);

        $this->shouldThrow((new DuplicateReferenceException)->setReference('ref-123-123'))
            ->duringHandleCallback($post);
    }

    public function it_should_successfully_refund_payment($soap, $samanConfig)
    {
        $config = $this->getDefaultConfig();

        $this->mockConfig($samanConfig);
        $this->mockSoapConnection($soap, $config['wsdl'], $config['soap_options']);

        $params = [
            'ref-123-123',
            $config['merchant'],
            $config['username'],
            $config['password']
        ];

        $soap->call('reverseTransaction', $params)->willReturn(1);

        $this->refund('ref-123-123')->shouldBe(true);
    }

    /**
     * Mock saman config
     *
     * @param SamanConfig $config
     * @param array $override
     */
    protected function mockConfig($config, $override = [])
    {
        $data = $this->getDefaultConfig($override);

        $config->getUsername()->willReturn($data['username']);
        $config->getPassword()->willReturn($data['password']);
        $config->getMerchantId()->willReturn($data['merchant']);
        $config->getWebServiceUrl()->willReturn($data['wsdl']);
        $config->getTokenUrl()->willReturn($data['token_wsdl']);
        $config->getGatewayUrl()->willReturn($data['gateway']);
        $config->getRedirectUrl()->willReturn($data['redirect_url']);
        $config->getSoapOptions()->willReturn($data['soap_options']);
    }

    /**
     * Get default config
     *
     * @param array $override [optional] it overrides default configs
     * @return array
     */
    protected function getDefaultConfig($override = [])
    {
        return array_merge(
            [
                'username'     => 'user',
                'password'     => 'pass',
                'merchant'     => 'mid',
                'wsdl'         => 'https://acquirer.samanepay.com/payments/referencepayment.asmx?WSDL',
                'token_wsdl'   => 'https://sep.shaparak.ir/Payments/InitPayment.asmx',
                'gateway'      => 'https://sep.shaparak.ir/Payment.aspx',
                'redirect_url' => 'http://example.com/callback',
                'soap_options' => null

            ],
            $override
        );
    }

    /**
     * Mock creating soap client
     *
     * @param SoapService $soap
     * @param string $wsdl
     * @param null|array $options
     */
    protected function mockSoapConnection($soap, $wsdl, $options = null)
    {
        $soap->wsdl($wsdl)->willReturn($soap);
        $soap->options($options)->willReturn($soap);
        $soap->createClient()->willReturn($soap);
    }
}


text:
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/crypto/krb/checksum_cbc.c */
/*
 * Copyright (C) 2009 by the Massachusetts Institute of Technology.
 * All rights reserved.
 *
 * Export of this software from the United States of America may
 *   require a specific license from the United States Government.
 *   It is the responsibility of any person or organization contemplating
 *   export to obtain such a license before exporting.
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 */

/* CBC checksum, which computes the ivec resulting from CBC encryption of the
 * input. */

#include "crypto_int.h"

krb5_error_code
krb5int_cbc_checksum(const struct krb5_cksumtypes *ctp,
                     krb5_key key, krb5_keyusage usage,
                     const krb5_crypto_iov *data, size_t num_data,
                     krb5_data *output)
{
    if (ctp->enc->cbc_mac == NULL)
        return KRB5_CRYPTO_INTERNAL;
    return ctp->enc->cbc_mac(key, data, num_data, NULL, output);
}


text:
class Faq < ActiveRecord::Base
  attr_accessible :answer, :question
end


text:
<html class="no-js" lang="en">
  <head>
    <base href="index.html">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Beta Project</title>

    <meta name="MobileOptimized" content="320">

    <meta name="apple-mobile-web-app-capable" content="yes">

    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="description" content="">

    <meta name="keywords" content="">

    <meta itemprop="name" content="">
    <meta itemprop="description" content="" />
    <meta itemprop="image" content="http://www." />
    <meta itemprop="url" content="http://www" />

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@name">
    <meta name="twitter:title" content="">
    <meta name="twitter:description" content="">
    <meta name="twitter:creator" content="@d">
    <meta name="twitter:image:src" content="http://www....//">

    <link rel="author" href=" " title=" " hreflang="en">

    <link rel="apple-touch-icon" sizes="57x57" href="/public/ico/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/public/ico/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/public/ico/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/public/ico/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/public/ico/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/public/ico/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/public/ico/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/public/ico/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/public/ico/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="/public/ico/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/public/ico/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/public/ico/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/public/ico/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/public/ico/manifest.json">
    <link rel="shortcut icon" href="/public/ico/favicon.ico">

    <meta name="msapplication-TileColor" content="#9f00a7">
    <meta name="msapplication-TileImage" content="/public/ico/mstile-144x144.png">
    <meta name="msapplication-config" content="/public/ico/browserconfig.xml">
    <meta name="theme-color" content="#ffffff">
    <link rel="stylesheet" href="../foundation.css" />
    <link rel="stylesheet" href="../style.css" />
    <script src="../js/vendor/modernizr.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>

<!--
	<meta name="application-name" content=""/>
<meta name="msapplication-TileColor" content="#222222"/>
<meta http-equiv="imagetoolbar" content="false" />
<meta name="googlebot" content="index,noarchive,follow,noodp" />
<meta name="robots" content="all,index,follow" />
<meta name="msnbot" content="all,index,follow" />
<meta itemprop="url" content="http://" />
<meta name="pinterest" content="nopin" />
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="apple-mobile-web-app-capable" content="yes">

	<!--

	<link rel="shortcut icon" type="image/vnd.microsoft.icon" href="src/ico/favicon.ico" />
    <link rel="icon" type="image/gif" href="src/ico/animated_favicon1.gif" />
	//-->

  </head>
  <body>


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace HermesSpa.Controllers.RailAPI
{
    using HermesSpa.Services;

    [Authorize]
    [Route("api/rail/[controller]")]
    public class TrainsController : Controller
    {
        private readonly RailKaolinApiClient _rail;

        public TrainsController(RailKaolinApiClient railClient)
        {
            _rail = railClient;
        }

        [HttpGet]
        public async Task<IActionResult> Get(RailKaolinApiClient.TrainsListRequest request)
        {
            if (request == null)
            {
                return BadRequest(nameof(request));
            }

            return Ok(await _rail.QueryTrainsAsync(request));
        }

        [HttpGet("cars")]
        public async Task<IActionResult> Cars(string sessionId, int optionRef)
        {
            if (String.IsNullOrEmpty(sessionId))
            {
                return BadRequest(nameof(sessionId));
            }

            return Ok(await _rail.QueryCarsAsync(sessionId, optionRef));
        }

        [HttpGet("seats")]
        public async Task<IActionResult> Seats(string sessionId, int trainRef, int optionRef)
        {
            if (String.IsNullOrEmpty(sessionId))
            {
                return BadRequest(nameof(sessionId));
            }

            return Ok(await _rail.QuerySeatsAsync(sessionId, trainRef, optionRef));
        }
    }
}


text:
@interface ALSearchResultsViewController ()
@end

@implementation ALSearchResultsViewController

#pragma mark - UIViewController
-(void)viewDidLoad
{
   [super viewDidLoad];

   self.searchResults = @[];
}

- (void)viewWillAppear:(BOOL)animated
{
   CGFloat yOrigin = self.tableView.frame.origin.y;

   if (yOrigin != 44)
   {
      CGRect frame = self.tableView.frame;
      self.tableView.frame = CGRectMake(0, 44, frame.size.width, frame.size.height);
   }
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return (self.searchResults ? [self.searchResults count] : 0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   ALAirportTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[ALAirportTableViewCell reuseIdentifier]
                                                                  forIndexPath:indexPath];

   if (cell)
   {
      cell.airport = self.searchResults[indexPath.row];
   }

   return cell;
}
@end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BirthdayParty_first_version
{
    public partial class Form1 : Form
    {
        DinnerParty dinnerParty;
        BirthdayParty birthdayParty;
        public Form1()
        {
            InitializeComponent();
            dinnerParty = new DinnerParty((int)numericUpDown1.Value,
                                 healthyBox.Checked, fancyBox.Checked);
            DisplayDinnerPartyCost();

            birthdayParty = new BirthdayParty((int)numberBirthday.Value,
                              fancyBirthday.Checked, cakeWriting.Text);
            DisplayBirthdayPartyCost();
        }

        private void fancyBox_CheckedChanged(object sender, EventArgs e)
        {
            dinnerParty.FancyDecorations = fancyBox.Checked;
            DisplayDinnerPartyCost();
        }

        private void healthyBox_CheckedChanged(object sender, EventArgs e)
        {
            dinnerParty.HealthyOption = healthyBox.Checked;
            DisplayDinnerPartyCost();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            dinnerParty.NumberOfPeople = (int)numericUpDown1.Value;
            DisplayDinnerPartyCost();
        }

        private void DisplayDinnerPartyCost()
        {
            decimal Cost = dinnerParty.Cost;
            costLabel.Text = Cost.ToString("c");
        }

        private void numberBirthday_ValueChanged(object sender, EventArgs e)
        {
            birthdayParty.NumberOfPeople = (int)numberBirthday.Value;
            DisplayBirthdayPartyCost();
        }

        private void fancyBirthday_CheckedChanged(object sender, EventArgs e)
        {
            birthdayParty.FancyDecorations = fancyBirthday.Checked;
            DisplayBirthdayPartyCost();
        }

        private void cakeWriting_TextChanged(object sender, EventArgs e)
        {
            birthdayParty.CakeWriting = cakeWriting.Text;
            DisplayBirthdayPartyCost();
        }

        private void DisplayBirthdayPartyCost()
        {
            tooLongLabel.Visible = birthdayParty.CakeWritingTooLong;
            decimal cost = birthdayParty.Cost;
            birthdayCost.Text = cost.ToString("c");
        }
    }
}


text:
var resources = {
  url_with_custom_string_already_exists: "A URL with this custom string already exists.",
  url_invalid: "Make sure your URL and the custom string are valid.",
  url_couldnt_be_shortened: "The URL couldn't be shortened. Maybe the server is down?",
  key_invalid: "The key you've provided is invalid.",
  url_is_shortened: "The URL has been shortened successfully!",
  are_you_sure: "Are you sure?",
  url_deleted: "The URL has been deleted successfully!",
  something_went_wrong: "Something went wrong, please try again later."
}


text: The iOS code for the experimental swift talk


text:
"""Experimental design for a quick eval to establish analysis practice."""

import itertools
import math
import numpy as np
from typing import Iterable
from itertools import cycle, islice

from wfa_planning_evaluation_framework.driver.experiment_parameters import (
    ExperimentParameters,
)
from wfa_planning_evaluation_framework.driver.modeling_strategy_descriptor import (
    ModelingStrategyDescriptor,
)
from wfa_planning_evaluation_framework.simulator.modeling_strategy import (
    ModelingStrategy,
)
from wfa_planning_evaluation_framework.simulator.privacy_tracker import (
    PrivacyBudget,
)
from wfa_planning_evaluation_framework.simulator.system_parameters import (
    LiquidLegionsParameters,
    SystemParameters,
)
from wfa_planning_evaluation_framework.driver.trial_descriptor import (
    TrialDescriptor,
)

MODELING_STRATEGIES = [
    ModelingStrategyDescriptor(
        "m3strategy", {}, "goerg", {}, "restricted_pairwise_union", {}
    ),
    ModelingStrategyDescriptor(
        "m3strategy", {}, "gamma_poisson", {}, "restricted_pairwise_union", {}
    ),
]

CAMPAIGN_SPEND_FRACTIONS_GENERATORS = [
    lambda dataset: [0.6] * dataset.publisher_count,
    lambda dataset: list(islice(cycle([0.4, 0.8]), dataset.publisher_count)),
]

LIQUID_LEGIONS_PARAMS = [
    LiquidLegionsParameters(10, 8000),
]

PRIVACY_BUDGETS = [
    PrivacyBudget(2, 1e-9),
    PrivacyBudget(0.5, 1e-9),
]

REPLICA_IDS = [1, 2, 3]

MAX_FREQUENCIES = [3, 6]

TEST_POINT_STRATEGIES = [
    ("latin_hypercube", {"npublishers": 1, "minimum_points_per_publisher": 10}),
    ("uniformly_random", {"npublishers": 1, "minimum_points_per_publisher": 10}),
]

LEVELS = {
    "modeling_strategies": MODELING_STRATEGIES,
    "campaign_spend_fractions_generators": CAMPAIGN_SPEND_FRACTIONS_GENERATORS,
    "liquid_legions_params": LIQUID_LEGIONS_PARAMS,
    "privacy_budgets": PRIVACY_BUDGETS,
    "replica_ids": REPLICA_IDS,
    "max_frequencies": MAX_FREQUENCIES,
    "test_point_strategies": TEST_POINT_STRATEGIES,
}
# Will evaluate all level combinations

def generate_experimental_design_config(seed: int = 1) -> Iterable[TrialDescriptor]:
    """Generates a list of TrialDescriptors for the 1st round eval of M3."""
    for level_combination in itertools.product(*LEVELS.values()):
        design_parameters = dict(zip(LEVELS.keys(), level_combination))
        mstrategy = design_parameters["modeling_strategies"]
        sparams = SystemParameters(
            liquid_legions=design_parameters["liquid_legions_params"],
            generator=np.random.default_rng(seed=seed),
            campaign_spend_fractions_generator=design_parameters[
                "campaign_spend_fractions_generators"
            ],
        )
        test_point_generator, test_point_params = design_parameters[
            "test_point_strategies"
        ]
        eparams = ExperimentParameters(
            design_parameters["privacy_budgets"],
            design_parameters["replica_ids"],
            design_parameters["max_frequencies"],
            test_point_generator,
            test_point_params,
        )
        yield TrialDescriptor(mstrategy, sparams, eparams)


text:
<?php

header('Content_disposition: attachment;
	filename=deskfive.rar');
header('Content-type: application/x-rar-compressed');
readfile('deskfive.rar');

 ?>


text:
#if !defined(_DISPLAY_H_)
#define _DISPLAY_H_

#include "argon.h"
#include "fsl_dspi.h"

//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------

namespace slab {

/*!
 * @brief Display controller.
 */
class DisplayController
{
public:
    DisplayController();
    ~DisplayController() {}

    static DisplayController & get() { return *s_instance; }

    void init();
    void start();

    void set_char(uint32_t charIndex, char c);
    void blit_char(uint32_t charIndex, const uint8_t *data);

    void timer_handler();
    void spi_handler();

protected:
    static const uint32_t kRowCount = 7;

    static DisplayController * s_instance;
    Ar::Semaphore m_transferDoneSem;
    Ar::Semaphore m_nextRowSem;
    dspi_master_handle_t m_spiHandle;
    uint16_t m_buffer[2][kRowCount];
    uint32_t m_activeBuffer;
    bool m_flipBuffers;
    uint32_t m_row;
    uint8_t m_data[2];

    void transfer_row();
    void latch_and_advance();

    void set_latch(bool enable);
    void set_output_enable(bool enable);
    void set_row_enable(bool enable);
    void select_row(uint32_t row);

    static void dspi_master_transfer_callback(SPI_Type *base,
                                                dspi_master_handle_t *handle,
                                                status_t status,
                                                void *userData);
};

} // namespace slab

#endif // _DISPLAY_H_
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------


text:
#ifndef CLI_FUNCTIONS_H
#define CLI_FUNCTIONS_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * a function type for calling parameters
 */
typedef int (*_orderfunc_t)(char *params);

/**
 * execute an order if the input starts with it
 */
int execute(char const *name, char *input, _orderfunc_t func);
#endif


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator.aggregation;

import com.facebook.presto.block.Block;
import com.facebook.presto.block.BlockBuilder;
import com.facebook.presto.block.BlockCursor;
import com.facebook.presto.operator.GroupByIdBlock;
import com.facebook.presto.util.array.DoubleBigArray;
import com.facebook.presto.util.array.LongBigArray;
import com.google.common.base.Optional;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;

import static com.facebook.presto.operator.aggregation.ApproximateUtils.formatApproximateResult;
import static com.facebook.presto.operator.aggregation.ApproximateUtils.sumError;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_VARBINARY;
import static com.facebook.presto.tuple.TupleInfo.Type.FIXED_INT_64;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.SizeOf.SIZE_OF_DOUBLE;
import static io.airlift.slice.SizeOf.SIZE_OF_LONG;

public class ApproximateLongSumAggregation
        extends SimpleAggregationFunction
{
    public static final ApproximateLongSumAggregation LONG_APPROXIMATE_SUM_AGGREGATION = new ApproximateLongSumAggregation();

    private static final int COUNT_OFFSET = 0;
    private static final int SUM_OFFSET = SIZE_OF_LONG;
    private static final int VARIANCE_OFFSET = SIZE_OF_LONG + SIZE_OF_DOUBLE;

    public ApproximateLongSumAggregation()
    {
        // TODO: Change intermediate to fixed width, once we have a better type system
        super(SINGLE_VARBINARY, SINGLE_VARBINARY, FIXED_INT_64);
    }

    @Override
    public ApproximateSumGroupedAccumulator createGroupedAccumulator(Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence, int valueChannel)
    {
        // valueChannel is -1 for intermediates
        checkArgument(sampleWeightChannel.isPresent() ^ valueChannel == -1, "sampleWeightChannel is missing");
        return new ApproximateSumGroupedAccumulator(valueChannel, maskChannel, sampleWeightChannel, confidence);
    }

    public static class ApproximateSumGroupedAccumulator
            extends SimpleGroupedAccumulator
    {
        // Weighted count of rows
        private final LongBigArray counts;
        // Unweighted count of rows
        private final LongBigArray samples;
        private final LongBigArray sums;
        private final DoubleBigArray m2s;
        private final DoubleBigArray means;
        private final double confidence;

        public ApproximateSumGroupedAccumulator(int valueChannel, Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence)
        {
            super(valueChannel, SINGLE_VARBINARY, SINGLE_VARBINARY, maskChannel, sampleWeightChannel);
            this.counts = new LongBigArray();
            this.samples = new LongBigArray();
            this.sums = new LongBigArray();
            this.m2s = new DoubleBigArray();
            this.means = new DoubleBigArray();
            this.confidence = confidence;
        }

        @Override
        public long getEstimatedSize()
        {
            return counts.sizeOf() + samples.sizeOf() + sums.sizeOf() + m2s.sizeOf() + means.sizeOf();
        }

        @Override
        protected void processInput(GroupByIdBlock groupIdsBlock, Block valuesBlock, Optional<Block> maskBlock, Optional<Block> sampleWeightBlock)
        {
            counts.ensureCapacity(groupIdsBlock.getGroupCount());
            samples.ensureCapacity(groupIdsBlock.getGroupCount());
            sums.ensureCapacity(groupIdsBlock.getGroupCount());
            m2s.ensureCapacity(groupIdsBlock.getGroupCount());
            means.ensureCapacity(groupIdsBlock.getGroupCount());
            BlockCursor values = valuesBlock.cursor();
            BlockCursor sampleWeights = sampleWeightBlock.get().cursor();
            BlockCursor masks = null;
            if (maskBlock.isPresent()) {
                masks = maskBlock.get().cursor();
            }

            OnlineVarianceCalculator calculator = new OnlineVarianceCalculator();
            for (int position = 0; position < groupIdsBlock.getPositionCount(); position++) {
                long groupId = groupIdsBlock.getGroupId(position);
                checkState(masks == null || masks.advanceNextPosition(), "failed to advance mask cursor");
                checkState(sampleWeights.advanceNextPosition(), "failed to advance weight cursor");
                checkState(values.advanceNextPosition(), "failed to advance values cursor");
                long weight = values.isNull() ? 0 : SimpleAggregationFunction.computeSampleWeight(masks, sampleWeights);

                if (!values.isNull() && weight > 0) {
                    long value = values.getLong();
                    counts.add(groupId, weight);
                    sums.add(groupId, value * weight);

                    calculator.reinitialize(samples.get(groupId), means.get(groupId), m2s.get(groupId));
                    calculator.add(value);
                    samples.set(groupId, calculator.getCount());
                    means.set(groupId, calculator.getMean());
                    m2s.set(groupId, calculator.getM2());
                }
            }
        }

        @Override
        public void processIntermediate(GroupByIdBlock groupIdsBlock, Block block)
        {
            counts.ensureCapacity(groupIdsBlock.getGroupCount());
            samples.ensureCapacity(groupIdsBlock.getGroupCount());
            sums.ensureCapacity(groupIdsBlock.getGroupCount());
            m2s.ensureCapacity(groupIdsBlock.getGroupCount());
            means.ensureCapacity(groupIdsBlock.getGroupCount());

            BlockCursor intermediates = block.cursor();

            OnlineVarianceCalculator calculator = new OnlineVarianceCalculator();
            for (int position = 0; position < groupIdsBlock.getPositionCount(); position++) {
                checkState(intermediates.advanceNextPosition(), "failed to advance intermediates cursor");

                long groupId = groupIdsBlock.getGroupId(position);
                Slice slice = intermediates.getSlice();
                sums.add(groupId, slice.getLong(SUM_OFFSET));
                counts.add(groupId, slice.getLong(COUNT_OFFSET));

                calculator.deserializeFrom(slice, VARIANCE_OFFSET);
                calculator.merge(samples.get(groupId), means.get(groupId), m2s.get(groupId));
                samples.set(groupId, calculator.getCount());
                means.set(groupId, calculator.getMean());
                m2s.set(groupId, calculator.getM2());
            }
        }

        @Override
        public void evaluateIntermediate(int groupId, BlockBuilder output)
        {
            OnlineVarianceCalculator calculator = new OnlineVarianceCalculator();
            calculator.merge(samples.get(groupId), means.get(groupId), m2s.get(groupId));
            output.append(createIntermediate(counts.get(groupId), sums.get(groupId), calculator));
        }

        @Override
        public void evaluateFinal(int groupId, BlockBuilder output)
        {
            long count = counts.get(groupId);
            if (count == 0) {
                output.appendNull();
                return;
            }

            output.append(formatApproximateResult(
                    sums.get(groupId),
                    sumError(samples.get(groupId), count, m2s.get(groupId), means.get(groupId)),
                    confidence,
                    true));
        }
    }

    @Override
    public ApproximateSumAccumulator createAccumulator(Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence, int valueChannel)
    {
        // valueChannel is -1 for intermediates
        checkArgument(sampleWeightChannel.isPresent() ^ valueChannel == -1, "sampleWeightChannel is missing");
        return new ApproximateSumAccumulator(valueChannel, maskChannel, sampleWeightChannel, confidence);
    }

    public static class ApproximateSumAccumulator
            extends SimpleAccumulator
    {
        private long sum;
        private long count;
        private final OnlineVarianceCalculator calculator = new OnlineVarianceCalculator();
        private final double confidence;

        public ApproximateSumAccumulator(int valueChannel, Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence)
        {
            super(valueChannel, SINGLE_VARBINARY, SINGLE_VARBINARY, maskChannel, sampleWeightChannel);
            this.confidence = confidence;
        }

        @Override
        protected void processInput(Block block, Optional<Block> maskBlock, Optional<Block> sampleWeightBlock)
        {
            BlockCursor values = block.cursor();
            BlockCursor sampleWeights = sampleWeightBlock.get().cursor();
            BlockCursor masks = null;
            if (maskBlock.isPresent()) {
                masks = maskBlock.get().cursor();
            }

            for (int i = 0; i < block.getPositionCount(); i++) {
                checkState(masks == null || masks.advanceNextPosition(), "failed to advance mask cursor");
                checkState(sampleWeights.advanceNextPosition(), "failed to advance weight cursor");
                checkState(values.advanceNextPosition(), "failed to advance values cursor");
                long weight = values.isNull() ? 0 : SimpleAggregationFunction.computeSampleWeight(masks, sampleWeights);
                if (!values.isNull() && weight > 0) {
                    long value = values.getLong();

                    count += weight;
                    sum += value * weight;
                    calculator.add(value);
                }
            }
        }

        @Override
        public void processIntermediate(Block block)
        {
            BlockCursor intermediates = block.cursor();

            OnlineVarianceCalculator calculator = new OnlineVarianceCalculator();
            for (int position = 0; position < block.getPositionCount(); position++) {
                checkState(intermediates.advanceNextPosition(), "failed to advance intermediates cursor");
                Slice slice = intermediates.getSlice();
                sum += slice.getLong(SUM_OFFSET);
                count += slice.getLong(COUNT_OFFSET);
                calculator.deserializeFrom(slice, VARIANCE_OFFSET);
                this.calculator.merge(calculator);
            }
        }

        @Override
        public void evaluateIntermediate(BlockBuilder out)
        {
            out.append(createIntermediate(count, sum, calculator));
        }

        @Override
        public void evaluateFinal(BlockBuilder out)
        {
            if (count == 0) {
                out.appendNull();
                return;
            }

            out.append(formatApproximateResult(
                    sum,
                    sumError(calculator.getCount(), count, calculator.getM2(), calculator.getMean()),
                    confidence,
                    true));
        }
    }

    public static Slice createIntermediate(long count, long sum, OnlineVarianceCalculator calculator)
    {
        Slice slice = Slices.allocate(2 * SIZE_OF_LONG + calculator.sizeOf());
        slice.setLong(COUNT_OFFSET, count);
        slice.setLong(SUM_OFFSET, sum);
        calculator.serializeTo(slice, VARIANCE_OFFSET);
        return slice;
    }
}


text:
package com.alibaba.jstorm.yarn;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Client {

	private static final Logger LOG = LoggerFactory.getLogger(Client.class);

    public static interface ClientCommand {

        /**
         * @return the options this client will process.
         */
        public Options getOpts();

        /**
         * @return header description for this command
         */
        public String getHeaderDescription();

        /**
         * Do the processing
         * @param cl the arguments to process
         * @param stormConf the storm configuration to use
         * @throws Exception on any error
         */
        public void process(CommandLine cl) throws Exception;
    }

    public static class HelpCommand implements ClientCommand {
        HashMap<String, ClientCommand> _commands;
        public HelpCommand(HashMap<String, ClientCommand> commands) {
            _commands = commands;
        }

        @Override
        public Options getOpts() {
            return new Options();
        }

        @Override
        public String getHeaderDescription() {
          return "jstorm-yarn help";
        }

        @SuppressWarnings("unchecked")
        @Override
        public void process(CommandLine cl) throws Exception {
            printHelpFor(cl.getArgList());
        }

        public void printHelpFor(Collection<String> args) {
            if(args == null || args.size() < 1) {
                args = _commands.keySet();
            }
            HelpFormatter f = new HelpFormatter();
            for(String command: args) {
                ClientCommand c = _commands.get(command);
                if (c != null) {
                    //TODO Show any arguments to the commands.
                    f.printHelp(command,  c.getHeaderDescription(), c.getOpts(), null);
                } else {
                    System.err.println("ERROR: " + c + " is not a supported command.");
                    //TODO make this exit with an error at some point
                }
            }
        }
    }

    /**
     * @param args the command line arguments
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public void execute(String[] args) throws Exception {
        HashMap<String, ClientCommand> commands = new HashMap<String, ClientCommand>();
        HelpCommand help = new HelpCommand(commands);
        commands.put("help", help);
        commands.put("launch", new LaunchCommand());
        commands.put("setStormConfig", new StormMasterCommand(StormMasterCommand.COMMAND.SET_STORM_CONFIG));
        commands.put("getStormConfig", new StormMasterCommand(StormMasterCommand.COMMAND.GET_STORM_CONFIG));
        commands.put("addSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.ADD_SUPERVISORS));
        commands.put("startNimbus", new StormMasterCommand(StormMasterCommand.COMMAND.START_NIMBUS));
        commands.put("stopNimbus", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_NIMBUS));
        commands.put("startUI", new StormMasterCommand(StormMasterCommand.COMMAND.START_UI));
        commands.put("stopUI", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_UI));
        commands.put("startSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.START_SUPERVISORS));
        commands.put("stopSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_SUPERVISORS));
        commands.put("shutdown", new StormMasterCommand(StormMasterCommand.COMMAND.SHUTDOWN));
        commands.put("version", new VersionCommand());

        String commandName = null;
        String[] commandArgs = null;
        if (args.length < 1) {
            commandName = "help";
            commandArgs = new String[0];
        } else {
            commandName = args[0];
            commandArgs = Arrays.copyOfRange(args, 1, args.length);
        }
        ClientCommand command = commands.get(commandName);
        if(command == null) {
            LOG.error("ERROR: " + commandName + " is not a supported command.");
            help.printHelpFor(null);
            System.exit(1);
        }
        Options opts = command.getOpts();
        if(!opts.hasOption("h")) {
            opts.addOption("h", "help", false, "print out a help message");
        }
        CommandLine cl = new GnuParser().parse(command.getOpts(), commandArgs);
        if(cl.hasOption("help")) {
            help.printHelpFor(Arrays.asList(commandName));
        } else {

            command.process(cl);
        }
    }

    public static void main(String[] args) throws Exception {
        Client client = new Client();
        client.execute(args);
    }

}


text:
SASS Component
===========================


text:
// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Directive for a schema-based editor for booleans.
 */

oppia.directive('schemaBasedBoolEditor', [
  'UrlInterpolationService',
  function(UrlInterpolationService) {
    return {
      scope: {
        localValue: '=',
        isDisabled: '&',
        labelForFocusTarget: '&'
      },
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/components/forms/schema_editors/' +
        'schema_based_bool_editor_directive.html'),
      restrict: 'E'
    };
  }]);