repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
resistor58/deaths-gmod-server
Nuke Pack 4/lua/entities/sent_nuke/cl_init.lua
2
2282
local sndWaveBlast = Sound("ambient/levels/streetwar/city_battle11.wav") local sndWaveIncoming = Sound("ambient/levels/labs/teleport_preblast_suckin1.wav") local sndSplode = Sound("ambient/explosions/explode_6.wav") local sndRumble = Sound("ambient/explosions/exp1.wav") local sndPop = Sound("weapons/pistol/pistol_fire3.wav") function ENT:Initialize() self.Yield = (GetConVarNumber("nuke_yield") or 100)/100 self.SplodeDist = 1000 self.BlastSpeed = 4000 self.lastThink = CurTime() + 0.2 self.SplodeTime = self.lastThink + 7*self.Yield if self.Yield > 0.13 then self.HasPlayedIncomingSnd = false self.HasPlayedBlastSnd = false self.HasPlayedSlopdeSnd = false surface.PlaySound(sndRumble) else self.HasPlayedIncomingSnd = true self.HasPlayedBlastSnd = true self.HasPlayedSlopdeSnd = true self.SplodeTime = 0 self.lastThink = CurTime() + 999 timer.Simple(0.05,PlayPopSound,self.Entity) end end function ENT:Think() if CurTime() - self.lastThink < 0.1 then return end local FTime = CurTime() - self.lastThink self.lastThink = CurTime() self.SplodeDist = self.SplodeDist + self.BlastSpeed*FTime local EntPos = EntPos or self.Entity:GetPos() local CurDist = (EntPos - LocalPlayer():GetPos()):Length() if CurDist < 900 + self.BlastSpeed then self.HasPlayedIncomingSnd = true end if not self.HasPlayedSlopdeSnd then timer.Simple(CurDist/18e3,PlaySplodeSound,7e5/CurDist) self.HasPlayedSlopdeSnd = true end if self.lastThink < self.SplodeTime then if (not self.HasPlayedIncomingSnd) and self.SplodeDist + self.BlastSpeed*1.6 > CurDist then surface.PlaySound(sndWaveIncoming) self.HasPlayedIncomingSnd = true end if (not self.HasPlayedBlastSnd) and self.SplodeDist + self.BlastSpeed*0.2 > CurDist then surface.PlaySound(sndWaveBlast) self.HasPlayedBlastSnd = true end end end function PlaySplodeSound(volume) if volume > 400 then surface.PlaySound(sndSplode) return end if volume < 60 then volume = 60 end LocalPlayer():EmitSound(sndSplode,volume,100) end function PlayPopSound(ent) ent:EmitSound(sndPop,500,100) end function ENT:Draw() end include('shared.lua')
gpl-3.0
comedinha/New-Poke-Lite
data/npc/scripts/bless.lua
28
2641
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local node1 = keywordHandler:addKeyword({'first bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the first blessing for 10000 gold?'}) node1:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 1, premium = true, cost = 10000}) node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'}) local node2 = keywordHandler:addKeyword({'second bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the second blessing for 10000 gold?'}) node2:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 2, premium = true, cost = 10000}) node2:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'}) local node3 = keywordHandler:addKeyword({'third bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the third blessing for 10000 gold?'}) node3:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 3, premium = true, cost = 10000}) node3:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'}) local node4 = keywordHandler:addKeyword({'fourth bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the fourth blessing for 10000 gold?'}) node4:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 4, premium = true, cost = 10000}) node4:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'}) local node5 = keywordHandler:addKeyword({'fifth bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the fifth blessing for 10000 gold?'}) node5:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 5, premium = true, cost = 10000}) node5:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'}) npcHandler:addModule(FocusModule:new())
gpl-2.0
tkdrob/Battle-Tag
Packages/StarterFrag/Data/Script/ByteCode/UAStarterFrag.ByteCode.lua
1
1836
byteCode = { 0x09, 0x53, 0x43, 0x30, 0x35, 0x00, 0x00, 0x53, 0x43, 0x30, 0x33, 0x00, 0x00, 0x41, 0x53, 0x48, 0x54, 0x00, 0x00, 0x53, 0x57, 0x35, 0x36, 0x00, 0x00, 0x53, 0x57, 0x32, 0x32, 0x00, 0x00, 0x53, 0x43, 0x30, 0x38, 0x00, 0x00, 0x53, 0x57, 0x31, 0x32, 0x00, 0x00, 0x53, 0x57, 0x34, 0x32, 0x00, 0x00, 0x41, 0x52, 0x41, 0x4d, 0x00, 0x00, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x03, 0xcc, 0x03, 0xd0, 0x00, 0x18, 0xcf, 0x01, 0x03, 0x00, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, 0xcd, 0x00, 0x01, 0x00, 0x04, 0xcd, 0x00, 0x01, 0x01, 0xce, 0x00, 0x02, 0x00, 0xd0, 0x01, 0x0c, 0xc0, 0x02, 0x00, 0x06, 0xc1, 0x02, 0xc0, 0x01, 0x00, 0x05, 0xc3, 0x00, 0xd0, 0x02, 0x0a, 0xc2, 0x00, 0xd3, 0x1e, 0xc5, 0x00, 0x00, 0xca, 0x1e, 0x01, 0xd2, 0x01, 0x00, 0x10, 0x0c, 0x0e, 0xc9, 0x64, 0xdd, 0x01, 0xc0, 0x00, 0x01, 0x00, 0x00, 0xc5, 0x00, 0x01, 0xd0, 0x01, 0xc7, 0x00, 0x00, 0x65, 0x01, 0x21, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x14, 0xc4, 0x05, 0x01, 0x00, 0x14, 0x03, 0x02, 0xc1, 0x01, 0x02, 0xcb, 0x02, 0xc5, 0x01, 0x03, 0xd4, 0x01, 0xd5, 0x01, 0xc6, 0x00, 0xd0, 0x00, 0xc5, 0x00, 0x04, 0x02, 0x1b, 0xc8, 0x03, 0xc4, 0x03, 0x01, 0x00, 0x01, 0x02, 0x0e, 0xde, 0x04, 0xc4, 0x04, 0x01, 0x00, 0x04, 0x02, 0x04, 0xd5, 0x01, 0xc3, 0x02, 0x00, 0x00, 0xc5, 0x00, 0x05, 0x0b, 0x02, 0xd0, 0x02, 0x0c, 0x02, 0xd0, 0x00, 0x09, 0x1b, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x02, 0x13, 0xc4, 0x02, 0x01, 0x00, 0x00, 0x00, 0x0b, 0xc1, 0x02, 0xc5, 0x00, 0x06, 0xc0, 0x01, 0x00, 0x05, 0xd0, 0x00, 0x00, 0x00, 0xc7, 0x02, 0x00, 0x11, 0x0c, 0x07, 0xc5, 0x00, 0x07, 0xd5, 0x01, 0xcb, 0x08, 0x0d, 0x02, 0xd0, 0x01, 0x0b, 0x02, 0xd0, 0x02, } return byteCode
mit
resistor58/deaths-gmod-server
counter-strike/lua/autorun/cs_playermodels.lua
1
1896
----Counter terrorists list.Set( "PlayerOptionsModel", "urban", "models/player/urban.mdl" ) player_manager.AddValidModel( "urban", "models/player/urban.mdl" ) list.Set( "PlayerOptionsModel", "swat", "models/player/swat.mdl" ) player_manager.AddValidModel( "swat", "models/player/swat.mdl" ) list.Set( "PlayerOptionsModel", "gasmask", "models/player/gasmask.mdl" ) player_manager.AddValidModel( "gasmask", "models/player/gasmask.mdl" ) list.Set( "PlayerOptionsModel", "riot", "models/player/riot.mdl" ) player_manager.AddValidModel( "riot", "models/player/riot.mdl" ) ----Terrorists list.Set( "PlayerOptionsModel", "leet", "models/player/leet.mdl" ) player_manager.AddValidModel( "leet", "models/player/leet.mdl" ) list.Set( "PlayerOptionsModel", "guerilla", "models/player/guerilla.mdl" ) player_manager.AddValidModel( "guerilla", "models/player/guerilla.mdl" ) list.Set( "PlayerOptionsModel", "phoenix", "models/player/Phoenix.mdl" ) player_manager.AddValidModel( "phoenix", "models/player/Phoenix.mdl" ) list.Set( "PlayerOptionsModel", "arctic", "models/player/arctic.mdl" ) player_manager.AddValidModel( "arctic", "models/player/arctic.mdl" ) ------Hostages list.Set( "PlayerOptionsModel", "hostage_01", "models/player/Hostage/Hostage_01.mdl" ) player_manager.AddValidModel( "hostage_01", "models/player/Hostage/Hostage_01.mdl" ) list.Set( "PlayerOptionsModel", "hostage_02", "models/player/Hostage/Hostage_02.mdl" ) player_manager.AddValidModel( "hostage_02", "models/player/Hostage/Hostage_02.mdl" ) list.Set( "PlayerOptionsModel", "hostage_03", "models/player/Hostage/Hostage_03.mdl" ) player_manager.AddValidModel( "hostage_03", "models/player/Hostage/Hostage_03.mdl" ) list.Set( "PlayerOptionsModel", "hostage_04", "models/player/Hostage/Hostage_04.mdl" ) player_manager.AddValidModel( "hostage_04", "models/player/Hostage/Hostage_04.mdl" )
gpl-3.0
resistor58/deaths-gmod-server
wire/lua/entities/gmod_wire_consolescreen/init.lua
1
7616
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') ENT.WireDebugName = "ConsoleScreen" function ENT:Initialize() self.Entity:PhysicsInit(SOLID_VPHYSICS) self.Entity:SetMoveType(MOVETYPE_VPHYSICS) self.Entity:SetSolid(SOLID_VPHYSICS) self.Inputs = Wire_CreateInputs(self.Entity, { "CharX", "CharY", "Char", "CharParam", "Clk", "Reset" }) self.Outputs = Wire_CreateOutputs(self.Entity, { "Memory" }) self.Memory = {} for i = 0, 2047 do self.Memory[i] = 0 end self.CharX = 0 self.CharY = 0 self.Char = 0 self.CharParam = 0 self.Memory[2022] = 3/4 self.Memory[2023] = 0 self.Memory[2024] = 0 self.Memory[2025] = 1 self.Memory[2026] = 1 self.Memory[2027] = 1 self.Memory[2028] = 1 self.Memory[2029] = 1 self.Memory[2030] = 1 self.Memory[2031] = 0 self.Memory[2032] = 29 self.Memory[2033] = 0 self.Memory[2034] = 17 self.Memory[2035] = 0 self.Memory[2036] = 0 self.Memory[2042] = 000 self.Memory[2043] = 0.5 self.Memory[2044] = 0.25 self.Memory[2045] = 0 self.Memory[2046] = 0 self.Memory[2047] = 1 -- CLK self.IgnoreDataTransfer = false self:ResetCacheSystem() end function ENT:ResetCacheSystem() self.MemoryCache = {} end function ENT:SendToClient(Address, value) value = math.max(-99,value or 0) table.insert(self.MemoryCache, { Address, value }) end local function calcoffset(offset) if offset < 0 then offset = 1048576 + offset end return -100-offset end function ENT:FlushCache() if not next(self.MemoryCache) then return end local bytes = 4+4 umsg.Start("hispeed_datastream") umsg.Short(self:EntIndex()) local last_address = -1 for _,Address,value in ipairs_map(self.MemoryCache,unpack) do local gap = Address - (last_address+1) if gap ~= 0 then bytes = bytes + 8 else bytes = bytes + 4 end if bytes >= 200 then umsg.Float(-100) umsg.End() bytes = 4+4 umsg.Start("hispeed_datastream") umsg.Short(self:EntIndex()) last_address = -1 gap = Address - (last_address+1) end if gap ~= 0 then umsg.Float(calcoffset(gap)) end umsg.Float(value) last_address = Address end umsg.Float(-100) umsg.End() self:ResetCacheSystem() end function ENT:SendPixel() if (self.Memory[2047] ~= 0) && (self.CharX >= 0) && (self.CharX < 30) && (self.CharY >= 0) && (self.CharY < 18) then local pixelno = math.floor(self.CharY)*30+math.floor(self.CharX) self:WriteCell(pixelno*2, self.Char) self:WriteCell(pixelno*2+1, self.CharParam) end end function ENT:ReadCell(Address) if Address < 0 then return nil end if Address >= 2048 then return nil end if Address == 2022 then return WireGPU_Monitors[self.Entity:GetModel()].RatioX end return self.Memory[Address] end function ENT:WriteCell(Address, value) if Address < 0 then return false end if Address >= 2048 then return false end if Address < 2000 then -- text/attribute data if self.Memory[Address] == value then return true end else self:ClientWriteCell(Address, value) end self.Memory[Address] = value self:SendToClient(Address, value) return true end function ENT:Think() if (self.IgnoreDataTransfer == true) then self.IgnoreDataTransfer = false self.Entity:NextThink(CurTime()+0.2) else self:FlushCache() self.Entity:NextThink(CurTime()+0.1) end return true end function ENT:TriggerInput(iname, value) if (iname == "CharX") then self.CharX = value self:SendPixel() elseif (iname == "CharY") then self.CharY = value self:SendPixel() elseif (iname == "Char") then self.Char = value self:SendPixel() elseif (iname == "CharParam") then self.CharParam = value self:SendPixel() elseif (iname == "Clk") then self:WriteCell(2047, value) self:SendPixel() elseif (iname == "Reset") then self:WriteCell(2041,0) self:WriteCell(2046,0) self:WriteCell(2042,0) end end function ENT:ClientWriteCell(Address, value) if (Address == 2019) then -- Hardware Clear Viewport local low = math.floor(math.Clamp(self.Memory[2033],0,17)) local high = math.floor(math.Clamp(self.Memory[2034],0,17)) local lowc = math.floor(math.Clamp(self.Memory[2031],0,29)) local highc = math.floor(math.Clamp(self.Memory[2032],0,29)) for j = low, high do for i = 2*lowc, 2*highc+1 do self.Memory[i*60+value] = 0 end end elseif (Address == 2037) then -- Shift cells (number of cells, >0 right, <0 left) local delta = math.abs(value) local low = math.floor(math.Clamp(self.Memory[2033],0,17)) local high = math.floor(math.Clamp(self.Memory[2034],0,17)) local lowc = math.floor(math.Clamp(self.Memory[2031],0,29)) local highc = math.floor(math.Clamp(self.Memory[2032],0,29)) if (value > 0) then for j = low,high do for i = highc,lowc+delta,-1 do self.Memory[j*60+i*2] = self.Memory[j*60+i*2-delta*2] self.Memory[j*60+i*2+1] = self.Memory[j*60+i*2+1-delta*2] end end for j = low,high do for i = lowc, lowc+delta-1 do self.Memory[j*60+i*2] = 0 self.Memory[j*60+i*2+1] = 0 end end else for j = low,high do for i = lowc,highc-delta do self.Memory[j*60+i*2] = self.Memory[j*60+i*2+delta*2] self.Memory[j*60+i*2+1] = self.Memory[j*60+i*2+1+delta*2] end end for j = low,high do for i = highc-delta+1,highc do self.Memory[j*60+i*2] = 0 self.Memory[j*60+i*2+1] = 0 end end end elseif (Address == 2038) then -- Shift rows (number of rows, >0 shift down, <0 shift up) local delta = math.abs(value) local low = math.floor(math.Clamp(self.Memory[2033],0,17)) local high = math.floor(math.Clamp(self.Memory[2034],0,17)) local lowc = math.floor(math.Clamp(self.Memory[2031],0,29)) local highc = math.floor(math.Clamp(self.Memory[2032],0,29)) if (value > 0) then for j = low, high-delta do for i = 2*lowc, 2*highc+1 do self.Memory[j*60+i] = self.Memory[(j+delta)*60+i] end end for j = high-delta+1,high do for i = 2*lowc, 2*highc+1 do self.Memory[j*60+i] = 0 end end else for j = high,low+delta,-1 do for i = 2*lowc, 2*highc+1 do self.Memory[j*60+i] = self.Memory[(j-delta)*60+i] end end for j = low,low+delta-1 do for i = 2*lowc, 2*highc+1 do self.Memory[j*60+i] = 0 end end end elseif (Address == 2039) then -- Hardware Clear Row (Writing clears row) for i = 0, 59 do self.Memory[value*60+i] = 0 end elseif (Address == 2040) then -- Hardware Clear Column (Writing clears column) for i = 0, 17 do self.Memory[i*60+value] = 0 end elseif (Address == 2041) then -- Hardware Clear Screen for i = 0, 18*30*2-1 do self.Memory[i] = 0 end self:ResetCacheSystem() -- optimization end end function MakeWireconsoleScreen(pl, Pos, Ang, model) if (!pl:CheckLimit("wire_consolescreens")) then return false end local wire_consolescreen = ents.Create("gmod_wire_consolescreen") if (!wire_consolescreen:IsValid()) then return false end wire_consolescreen:SetModel(model) wire_consolescreen:SetAngles(Ang) wire_consolescreen:SetPos(Pos) wire_consolescreen:Spawn() wire_consolescreen:SetPlayer(pl) pl:AddCount("wire_consolescreens", wire_consolescreen) return wire_consolescreen end duplicator.RegisterEntityClass("gmod_wire_consolescreen", MakeWireconsoleScreen, "Pos", "Ang", "Model")
gpl-3.0
resistor58/deaths-gmod-server
Ultimate Vehicle Pack/lua/autorun/VP_Government.lua
1
10593
// Vehicle Pack Governement v1.0 local Category = "GMow+ Government Vehicles" local V = { // Required information Name = "UAZ", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "UAZ", Model = "models/uazjeep.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/uaz.txt" } } list.Set( "Vehicles", "uaz", V ) local V = { // Required information Name = "Cop Car", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Cop Car", Model = "models/copcar.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/copcar.txt" } } list.Set( "Vehicles", "copcar", V ) local V = { // Required information Name = "Police Car", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Unknown", Information = "Police Car", Model = "models/pcar/pcar.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/pcar.txt" } } list.Set( "Vehicles", "police_car", V ) local V = { // Required information Name = "Ambulance", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Ambulance", Model = "models/ambulance.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/ambulance.txt" } } list.Set( "Vehicles", "ambulance", V ) local V = { // Required information Name = "Fire Truck", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Fire Truck", Model = "models/firetruck.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/firetruck.txt" } } list.Set( "Vehicles", "firetruck", V ) local V = { // Required information Name = "Patrol Jeep", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Patrol Jeep", Model = "models/copcarru.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/copcarru.txt" } } list.Set( "Vehicles", "copcarru", V ) local V = { // Required information Name = "Military Tacoma", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Military Tacoma", Model = "models/tacoma2.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/tacoma.txt" } } list.Set( "Vehicles", "tacoma", V ) local V = { // Required information Name = "SdKfz222", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "SdKfz222", Model = "models/tank222.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/tank222.txt" } } list.Set( "Vehicles", "tank222", V ) local V = { // Required information Name = "HL1 Truck", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Unknown", Information = "HL1 truck", Model = "models/hl1truck/hl1truck.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/hl1truck.txt" } } list.Set( "Vehicles", "hl1truck", V ) local V = { // Required information Name = "School Bus", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Solid_Granite", Information = "School Bus", Model = "models/bus.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/bus_test.txt" } } list.Set( "Vehicles", "schoolbus", V ) local V = { // Required information Name = "Street Sweeper", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Street Sweeper", Model = "models/sweeper.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/sweeper.txt" } } list.Set( "Vehicles", "sweeper", V ) local V = { // Required information Name = "Komatsu 330M", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Solid_Granite", Information = "Komatsu 330m", Model = "models/330m.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/330m_test.txt" } } list.Set( "Vehicles", "komatsu_330m", V ) local V = { // Required information Name = "Golf Cart", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Golf Cart", Model = "models/caddy.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/caddy.txt" } } list.Set( "Vehicles", "caddy", V ) local V = { // Required information Name = "Forklift", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Solid_Granite", Information = "A forklift", Model = "models/forklift.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/forklift_test.txt" } } list.Set( "Vehicles", "Forklift", V ) local V = { // Required information Name = "Old Rig", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Solid_Granite", Information = "Old Rig", Model = "models/freight.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/freight_test.txt" } } list.Set( "Vehicles", "old_rig", V ) local V = { // Required information Name = "Komatsu 930E", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Solid_Granite", Information = "Komatsu 930E", Model = "models/komatsu.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/komatsu_test.txt" } } list.Set( "Vehicles", "komatsu_930e", V ) local V = { // Required information Name = "New Rig", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Solid_Granite", Information = "New Rig", Model = "models/rig.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/rig_test.txt" } } list.Set( "Vehicles", "new_rig", V ) local V = { // Required information Name = "Taxi", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Taxi", Model = "models/taxi.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/taxi.txt" } } list.Set( "Vehicles", "taxi", V ) local V = { // Required information Name = "Police Enforcer", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "The huge ass truck you ran like hell from in GTA:SA.", Model = "models/enforcer.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/enforcer.txt" } } list.Set( "Vehicles", "enforcer", V ) local V = { // Required information Name = "M1A1 Tank", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "NPerez", Information = "An M1A1 tank from the military models pack.", Model = "models/m1a1/m1a1.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/m1a1.txt" } } list.Set( "Vehicles", "m1a1", V ) local V = { // Required information Name = "Military Humvee", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "NPerez", Information = "A humvee from the military models pack.", Model = "models/humvee/humvee.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/humvee.txt" } } list.Set( "Vehicles", "humvee", V ) local V = { // Required information Name = "Cabbie", Class = "prop_vehicle_jeep", Category = Category, // Optional information Author = "Kuno86", Information = "Old Taxi Cab", Model = "models/cabbie.mdl", SeatType = "jeep_seat", ModView = { FirstPerson = Vector(0,0,12) }, KeyValues = { vehiclescript = "scripts/vehicles/cabbie.txt" } } list.Set( "Vehicles", "cabbie", V )
gpl-3.0
punisherbot/hh
libs/mimetype.lua
28
2924
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
milos-korenciak/heroku-buildpack-tex
buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/doc.lua
3
3586
-- Copyright 2013 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/doc.lua,v 1.2 2013/03/20 17:16:38 tantau Exp $ --- -- The table doc is used for documentation purposes. It is used to -- provide lazy documentation for keys, that is, to install -- documentation for keys only when this information is requested and -- when the documentation is kept in a separate file. -- -- Using the doc facility is easy: -- -- \begin{enumerate} -- \item In the |declare| statement of the key, you do not provide -- fields like |documentation| or |summary|. Rather, you provide the -- field |documentation_in|, which gets the name of a Lua file the -- will be read whenever one of the fields |documentation|, |summary|, -- or |examples| is requested for the key. -- \item When the key is requested, |require| will be applied to the -- filename given in the |documentation_in| field. -- \item In this file, you start with the following code: --\begin{codeexample}[code only] --local doc = require 'pgf.gd.doc' --local key = doc.key --local documentation = doc.documentation --local summary = doc.summary --local example = doc.example --\end{codeexample} -- This will setup nice shortcuts for the commands you are going to -- use in your file. -- \item Next, for each to-be-lazily-documented key, add a block to -- the file like the following: --\begin{codeexample}[code only] -- --- -- key "my radius" -- summary "This key specifies a radius." -- documentation -- [[ -- This key is used, whenever... -- ]] -- example "\tikz \graph [foo layout, my radius=5] { a--b };" -- example "\tikz \graph [foo layout, my radius=3] { c--d };" --\end{codeexample} -- -- Note that |[[| and |]]| are used in Lua for raw multi-line -- strings. -- -- The effect of the above code will be that for the key |my radius| -- the different field like |summary| or |documentation| get -- updated. The |key| function simple ``selects'' a key and subsequent -- commands like |summary| will update this key until a different key -- is selected through another use of |key|. -- \end{enumerate} local doc = {} local current_key -- Namespace require "pgf.gd".doc = doc -- Imports local keys = require "pgf.gd.interface.InterfaceCore".keys --- -- Selects the key which will be subsequently updated by the other -- functions of this class. -- -- @param key A key. function doc.key (key) current_key = assert(keys[key], "trying to document not-yet-declared key") end --- -- Updates (replaces) the summary field of the last key selected -- through the |key| command. -- -- @param string A (new) summary string. function doc.summary (string) current_key.summary = string end --- -- Updates (replaces) the documentation field of the last key selected -- through the |key| command. -- -- @param string A (new) documentation string. Typically, the |[[| -- syntax will be used to specify this string. function doc.documentation (string) current_key.documentation = string end --- -- Adds an example to the |examples| field of the last key selected -- through the |key| command. -- -- @param string An additional example string. function doc.example (string) local examples = rawget(current_key, "examples") or {} examples[#examples + 1] = string current_key.examples = examples end return doc
mit
chewi/Aquaria
files/scripts/entities/nudinoshell.lua
6
1149
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end -- ================================================================================================ -- NUDI NO SHELL -- ================================================================================================ dofile("scripts/entities/nudicommon.lua") function init(me) -- init without shell v.commonInit(me, false) end
gpl-2.0
zhaoxx063/luci
protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
47
3692
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, username, password local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_failure.write = keepalive_interval.write keepalive_failure.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
apache-2.0
Aico/mudlet
src/old_mudlet-lua/lua/Other.lua
6
16089
---------------------------------------------------------------------------------- --- Mudlet Unsorted Stuff ---------------------------------------------------------------------------------- -- Extending default libraries makes Babelfish happy. setmetatable( _G, { ["__call"] = function(func, ...) if type(func) == "function" then return func(...) else local h = metatable(func).__call if h then return h(func, ...) elseif _G[type(func)][func] then _G[type(func)][func](...) end end end, }) --- Mudlet's support for ATCP. This is primarily available on IRE-based MUDs, but Mudlets impelementation is generic enough --- such that any it should work on others. <br/><br/> --- --- The latest ATCP data is stored in the atcp table. Whenever new data arrives, the previous is overwritten. An event is also --- raised for each ATCP message that arrives. To find out the available messages available in the atcp table and the event names, --- you can use display(atcp). <br/><br/> --- --- Note that while the typical message comes in the format of Module.Submodule, ie Char.Vitals or Room.Exits, in Mudlet the dot is --- removed - so it becomes CharVitals and RoomExits. Here's an example: --- <pre> --- room_number = tonumber(atcp.RoomNum) --- echo(room_number) --- </pre> --- --- Triggering on ATCP events: <br/> --- If you'd like to trigger on ATCP messages, then you need to create scripts to attach handlers to the ATCP messages. --- The ATCP handler names follow the same format as the atcp table - RoomNum, RoomExits, CharVitals and so on. <br/><br/> --- --- While the concept of handlers for events is to be explained elsewhere in the manual, the quick rundown is this - place --- the event name you'd like your script to listen to into the Add User Defined Event Handler: field and press the + button --- to register it. Next, because scripts in Mudlet can have multiple functions, you need to tell Mudlet which function --- should it call for you when your handler receives a message. You do that by setting the Script name: to the function --- name in the script you'd like to be called. <br/><br/> --- --- For example, if you'd like to listen to the RoomExits event and have it call the process_exits() function - --- register RoomExits as the event handler, make the script name be process_exits, and use this in the script: --- <pre> --- function process_exits(event, args) --- echo("Called event: " .. event .. "\nWith args: " .. args) --- end --- </pre> --- --- Feel free to experiment with this to achieve the desired results. A ATCP demo package is also available on the forums --- for using event handlers and parsing its messages into Lua datastructures. <br/> --- --- @release Mudlet 1.0.6 --- --- @see sendATCP --- --- @class function --- @name atcp atcp = {} --- <b><u>TODO</u></b> Table walklist. --- --- @class function --- @name walklist walklist = {} --- <b><u>TODO</u></b> Variable walkdelay. --- --- @class function --- @name walkdelay walkdelay = 0 --- <b><u>TODO</u></b> Table SavedVariables. --- --- @class function --- @name SavedVariables SavedVariables = {} --- Sends a list of commands to the MUD. You can use this to send some things at once instead of having --- to use multiple send() commands one after another. --- --- @param ... list of commands --- @param echoTheValue optional boolean flag (default value is true) which determine if value should --- be echoed back on client. --- --- @usage Use sendAll instead of multiple send commands. --- <pre> --- sendAll("stand", "wield shield", "say ha!") --- </pre> --- Instead of calling: --- <pre> --- send ("stand") --- send ("wield shield") --- send ("say ha!") --- </pre> --- @usage Use sendAll and do not echo sent commnad on the main window. --- <pre> --- sendAll("stand", "wield shield", "say ha!", false) --- </pre> --- --- @see send function sendAll(...) local args = {...} local echo = true if type(args[#args]) == 'boolean' then echo = table.remove(args, #args) end for i, v in ipairs(args) do if type(v) == 'string' then send(v, echo) end end end --- Creates a group of a given type that will persist through sessions. --- --- @param name name of the teim --- @param itemtype type of the item - can be trigger, alias, or timer --- --- @usage --- <pre> --- --create a new trigger group --- permGroup("Combat triggers", "trigger") --- </pre> --- @usage --- <pre> --- --create a new alias group only if one doesn't exist already --- if exists("Defensive aliases", "alias") == 0 then --- permGroup("Defensive aliases", "alias") --- end --- </pre> function permGroup(name, itemtype) assert(type(name) == "string", "permGroup: need a name for the new thing") local t = { timer = function(name) return (permTimer(name, "", 0, "") == -1) and false or true end, trigger = function(name) return (permSubstringTrigger(name, "", {""}, "") == -1) and false or true end, alias = function(name) return (permAlias(name, "", "", "") == -1) and false or true end } assert(t[itemtype], "permGroup: "..tostring(itemtype).." isn't a valid type") return t[itemtype](name) end --- Checks to see if a given file or folder exists. If it exists, it'll return the Lua true boolean value, otherwise false. --- --- @usage --- <pre> --- if io.exists("/home/user/Desktop") then --- echo("This folder exists!") --- else --- echo("This folder doesn't exist.") --- end --- --- if io.exists("/home/user/Desktop/file.txt") then --- echo("This file exists!") --- else --- echo("This file doesn't exist.") --- end --- </pre> --- --- @return true or false function io.exists(fileOfFolderName) local f = io.open(fileOfFolderName) if f then io.close(f) return true end return false end --- Implementation of boolean exclusive or. --- --- @usage All following will return false. --- <pre> --- xor(false, false) --- xor(true, true) --- </pre> --- --- @return true or false function xor(a, b) if (a and (not b)) or (b and (not a)) then return true else return false end end --- Determine operating system. --- --- @usage --- <pre> --- if "linux" == getOS() then --- echo("We are using GNU/Linux!") --- end --- </pre> --- --- @return "linux", "mac" or "windows" string function getOS() if string.char(getMudletHomeDir():byte()) == "/" then if string.find(os.getenv("HOME"), "home") == 2 then return "linux" else return "mac" end else return "windows" end end --- This function flags a variable to be saved by Mudlet's variable persistence system. --- Variables are automatically unpacked into the global namespace when the profile is loaded. --- They are saved to "SavedVariables.lua" when the profile is closed or saved. --- --- @usage remember("varName") --- --- @see loadVars function remember(varName) if not _saveTable then _saveTable = {} end _saveTable[varName] = _G[varName] end --- This function should be primarily used by Mudlet. It loads saved settings in from the Mudlet home directory --- and unpacks them into the global namespace. --- --- @see remember function loadVars() if string.char(getMudletHomeDir():byte()) == "/" then _sep = "/" else _sep = "\\" end local l_SettingsFile = getMudletHomeDir() .. _sep .. "SavedVariables.lua" local lt_VariableHolder = {} if (io.exists(l_SettingsFile)) then table.load(l_SettingsFile, lt_VariableHolder) for k,v in pairs(lt_VariableHolder) do _G[k] = v end end end --- This function should primarily be used by Mudlet. It saves the contents of _saveTable into a file for persistence. --- --- @see loadVars function saveVars() if string.char(getMudletHomeDir():byte()) == "/" then _sep = "/" else _sep = "\\" end local l_SettingsFile = getMudletHomeDir() .. _sep .. "SavedVariables.lua" for k,_ in pairs(_saveTable) do remember(k) end table.save(l_SettingsFile, _saveTable) end --- The below functions (table.save, table.load) can be used to save individual Lua tables to disc and load --- them again at a later time e.g. make a database, collect statistical information etc. --- These functions are also used by Mudlet to load & save the entire Lua session variables. <br/><br/> --- --- Original code written by CHILLCODE™ on https://board.ptokax.ch, distributed under the same terms as Lua itself. <br/><br/> --- --- Notes: <br/> --- Userdata and indices of these are not saved <br/> --- Functions are saved via string.dump, so make sure it has no upvalues <br/> --- References are saved <br/> --- --- @usage Saves the globals table (minus some lua enviroment stuffs) into a file (only Mudlet should use this). --- <pre> --- table.save(file) --- </pre> --- @usage Saves the given table into the given file. --- <pre> --- table.save(file, table) --- </pre> --- --- @see table.load function table.save( sfile, t ) assert(type(sfile) == "string", "table.save requires a file path to save to") local tables = {} table.insert( tables, t ) local lookup = { [t] = 1 } local file = io.open( sfile, "w" ) file:write( "return {" ) for i,v in ipairs( tables ) do table.pickle( v, file, tables, lookup ) end file:write( "}" ) file:close() end --- <b><u>TODO</u></b> table.pickle( t, file, tables, lookup ) function table.pickle( t, file, tables, lookup ) file:write( "{" ) for i,v in pairs( t ) do -- escape functions if type( v ) ~= "function" and type( v ) ~= "userdata" and (i ~= "string" and i ~= "xpcall" and i ~= "package" and i ~= "os" and i ~= "io" and i ~= "math" and i ~= "debug" and i ~= "coroutine" and i ~= "_G" and i ~= "_VERSION" and i ~= "table") then -- handle index if type( i ) == "table" then if not lookup[i] then table.insert( tables, i ) lookup[i] = table.maxn( tables ) end file:write( "[{"..lookup[i].."}] = " ) else local index = ( type( i ) == "string" and "[ "..string.enclose( i, 50 ).." ]" ) or string.format( "[%d]", i ) file:write( index.." = " ) end -- handle value if type( v ) == "table" then if not lookup[v] then table.insert( tables, v ) lookup[v] = table.maxn( tables ) end file:write( "{"..lookup[v].."}," ) else local value = ( type( v ) == "string" and string.enclose( v, 50 ) ) or tostring( v ) file:write( value.."," ) end end end file:write( "},\n" ) end --- Restores a Lua table from a data file that has been saved with table.save(). --- --- @usage Loads a serialized file into the globals table (only Mudlet should use this). --- <pre> --- table.load(file) --- </pre> --- @usage Loads a serialized file into the given table. --- <pre> --- table.load(file, table) --- </pre> --- --- @see table.save function table.load( sfile, loadinto ) assert(type(sfile) == "string", "table.load requires a file path to load") local tables = dofile( sfile ) if tables then if loadinto ~= nil and type(loadinto) == "table" then table.unpickle( tables[1], tables, loadinto ) else table.unpickle( tables[1], tables, _G ) end end end --- <b><u>TODO</u></b> table.unpickle( t, tables, tcopy, pickled ) function table.unpickle( t, tables, tcopy, pickled ) pickled = pickled or {} pickled[t] = tcopy for i,v in pairs( t ) do local i2 = i if type( i ) == "table" then local pointer = tables[ i[1] ] if pickled[pointer] then i2 = pickled[pointer] else i2 = {} table.unpickle( pointer, tables, i2, pickled ) end end local v2 = v if type( v ) == "table" then local pointer = tables[ v[1] ] if pickled[pointer] then v2 = pickled[pointer] else v2 = {} table.unpickle( pointer, tables, v2, pickled ) end end tcopy[i2] = v2 end end --- <b><u>TODO</u></b> speedwalktimer() function speedwalktimer() send(walklist[1]) table.remove(walklist, 1) if #walklist>0 then tempTimer(walkdelay, [[speedwalktimer()]]) end end --- <b><u>TODO</u></b> speedwalk(dirString, backwards, delay) function speedwalk(dirString, backwards, delay) local dirString = dirString:lower() walklist = {} walkdelay = delay local reversedir = { n = "s", en = "sw", e = "w", es = "nw", s = "n", ws = "ne", w = "e", wn = "se", u = "d", d = "u", ni = "out", tuo = "in" } if not backwards then for count, direction in string.gmatch(dirString, "([0-9]*)([neswudio][ewnu]?t?)") do count = (count == "" and 1 or count) for i=1, count do if delay then walklist[#walklist+1] = direction else send(direction) end end end else for direction, count in string.gmatch(dirString:reverse(), "(t?[ewnu]?[neswudio])([0-9]*)") do count = (count == "" and 1 or count) for i=1, count do if delay then walklist[#walklist+1] = reversedir[direction] else send(reversedir[direction]) end end end end if walkdelay then speedwalktimer() end end --- <b><u>TODO</u></b> _comp(a, b) function _comp(a, b) if type(a) ~= type(b) then return false end if type(a) == 'table' then for k, v in pairs(a) do if not b[k] then return false end if not _comp(v, b[k]) then return false end end else if a ~= b then return false end end return true end --- <b><u>TODO</u></b> phpTable(...) - abuse to: http://richard.warburton.it function phpTable(...) local newTable, keys, values = {}, {}, {} newTable.pairs = function(self) -- pairs iterator local count = 0 return function() count = count + 1 return keys[count], values[keys[count]] end end setmetatable(newTable, { __newindex = function(self, key, value) if not self[key] then table.insert(keys, key) elseif value == nil then -- Handle item delete local count = 1 while keys[count] ~= key do count = count + 1 end table.remove(keys, count) end values[key] = value -- replace/create end, __index=function(self, key) return values[key] end, isPhpTable = true, }) local args = {...} for x=1, #args do for k, v in pairs(args[x]) do newTable[k] = v end end return newTable end --- <b><u>TODO</u></b> getColorWildcard(color) function getColorWildcard(color) local color = tonumber(color) local startc local endc local results = {} for i = 1, string.len(line) do selectSection(i, 1) if isAnsiFgColor(color) then if not startc then if i == 1 then startc = 1 else startc = i + 1 end else endc = i + 1 if i == line:len() then results[#results + 1] = line:sub(startc, endc) end end elseif startc then results[#results + 1] = line:sub(startc, endc) startc = nil end end return results[1] and results or false end do local oldsetExit = setExit local exitmap = { n = 1, ne = 2, nw = 3, e = 4, w = 5, s = 6, se = 7, sw = 8, u = 9, d = 10, ["in"] = 11, out = 12 } function setExit(from, to, direction) if type(direction) == "string" and not exitmap[direction] then return false end return oldsetExit(from, to, type(direction) == "string" and exitmap[direction] or direction) end end do local oldlockExit = lockExit local oldhasExitLock = hasExitLock local exitmap = { n = 1, north = 1, ne = 2, northeast = 2, nw = 3, northwest = 3, e = 4, east = 4, w = 5, west = 5, s = 6, south = 6, se = 7, southeast = 7, sw = 8, southwest = 8, u = 9, up = 9, d = 10, down = 10, ["in"] = 11, out = 12 } function lockExit(from, direction, status) if type(direction) == "string" and not exitmap[direction] then return false end return oldlockExit(from, type(direction) == "string" and exitmap[direction] or direction, status) end function hasExitLock(from, direction) if type(direction) == "string" and not exitmap[direction] then return false end return oldhasExitLock(from, type(direction) == "string" and exitmap[direction] or direction) end end function print(...) local t, echo, tostring = {...}, echo, tostring for i = 1, #t do echo((tostring(t[i]) or '?').." ") end echo("\n") end
gpl-2.0
zhaoxx063/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/processes.lua
57
1951
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.processes", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { { title = "%H: Processes", vlabel = "Processes/s", data = { instances = { ps_state = { "sleeping", "running", "paging", "blocked", "stopped", "zombies" } }, options = { ps_state_sleeping = { color = "0000ff" }, ps_state_running = { color = "008000" }, ps_state_paging = { color = "ffff00" }, ps_state_blocked = { color = "ff5000" }, ps_state_stopped = { color = "555555" }, ps_state_zombies = { color = "ff0000" } } } }, { title = "%H: CPU time used by %pi", vlabel = "Jiffies", data = { sources = { ps_cputime = { "syst", "user" } }, options = { ps_cputime__user = { color = "0000ff", overlay = true }, ps_cputime__syst = { color = "ff0000", overlay = true } } } }, { title = "%H: Threads and processes belonging to %pi", vlabel = "Count", detail = true, data = { sources = { ps_count = { "threads", "processes" } }, options = { ps_count__threads = { color = "00ff00" }, ps_count__processes = { color = "0000bb" } } } }, { title = "%H: Page faults in %pi", vlabel = "Pagefaults", detail = true, data = { sources = { ps_pagefaults = { "minflt", "majflt" } }, options = { ps_pagefaults__minflt = { color = "ff0000" }, ps_pagefaults__majflt = { color = "ff5500" } } } }, { title = "%H: Virtual memory size of %pi", vlabel = "Bytes", detail = true, number_format = "%5.1lf%sB", data = { types = { "ps_rss" }, options = { ps_rss = { color = "0000ff" } } } } } end
apache-2.0
javierguerragiraldez/snabbswitch
src/apps/rate_limiter/rate_limiter.lua
2
6425
module(..., package.seeall) local app = require("core.app") local link = require("core.link") local config = require("core.config") local packet = require("core.packet") local timer = require("core.timer") local basic_apps = require("apps.basic.basic_apps") local ffi = require("ffi") local C = ffi.C local floor, min = math.floor, math.min --- # `Rate limiter` app: enforce a byte-per-second limit -- uses http://en.wikipedia.org/wiki/Token_bucket algorithm -- single bucket, drop non-conformant packets -- bucket capacity and content - bytes -- rate - bytes per second RateLimiter = {} -- Source produces synthetic packets of such size local PACKET_SIZE = 60 function RateLimiter:new (arg) local conf = arg and config.parse_app_arg(arg) or {} assert(conf.rate) assert(conf.bucket_capacity) conf.initial_capacity = conf.initial_capacity or conf.bucket_capacity local o = { rate = conf.rate, bucket_capacity = conf.bucket_capacity, bucket_content = conf.initial_capacity } return setmetatable(o, {__index=RateLimiter}) end function RateLimiter:reset(rate, bucket_capacity, initial_capacity) assert(rate) assert(bucket_capacity) self.rate = rate self.bucket_capacity = bucket_capacity self.bucket_content = initial_capacity or bucket_capacity end -- return statistics snapshot function RateLimiter:get_stat_snapshot () return { rx = self.input.input.stats.txpackets, tx = self.output.output.stats.txpackets, time = tonumber(C.get_time_ns()), } end function RateLimiter:push () local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") do local cur_now = tonumber(app.now()) local last_time = self.last_time or cur_now self.bucket_content = min( self.bucket_content + self.rate * (cur_now - last_time), self.bucket_capacity ) self.last_time = cur_now end while not link.empty(i) and not link.full(o) do local p = link.receive(i) local length = p.length if length <= self.bucket_content then self.bucket_content = self.bucket_content - length link.transmit(o, p) else -- discard packet packet.free(p) end end end local function compute_effective_rate (rl, rate, snapshot) local elapsed_time = (tonumber(C.get_time_ns()) - snapshot.time) / 1e9 local tx = tonumber(rl.output.output.stats.txpackets - snapshot.tx) return floor(tx * PACKET_SIZE / elapsed_time) end function selftest () print("Rate limiter selftest") local c = config.new() config.app(c, "source", basic_apps.Source) -- app.apps.source = app.new(basic_apps.Source:new()) local ok = true local rate_non_busy_loop = 200000 local effective_rate_non_busy_loop -- bytes local bucket_size = rate_non_busy_loop / 4 -- should be big enough to process packets generated by Source:pull() -- during 100 ms - internal RateLimiter timer resolution -- small value may limit effective rate local arg = { rate = rate_non_busy_loop, bucket_capacity = rate_non_busy_loop / 4 } config.app(c, "ratelimiter", RateLimiter, arg) config.app(c, "sink", basic_apps.Sink) -- Create a pipeline: -- Source --> RateLimiter --> Sink config.link(c, "source.output -> ratelimiter.input") config.link(c, "ratelimiter.output -> sink.input") app.configure(c) -- XXX do this in new () ? local rl = app.app_table.ratelimiter local seconds_to_run = 5 -- print packets statistics every second timer.activate(timer.new( "report", function () app.report() seconds_to_run = seconds_to_run - 1 end, 1e9, -- every second 'repeating' )) -- bytes per second do print("\ntest effective rate, non-busy loop") local snapshot = rl:get_stat_snapshot() -- push some packets through it while seconds_to_run > 0 do app.breathe() timer.run() C.usleep(10) -- avoid busy loop end -- print final report app.report() effective_rate_non_busy_loop = compute_effective_rate( rl, rate_non_busy_loop, snapshot ) print("configured rate is", rate_non_busy_loop, "bytes per second") print( "effective rate is", effective_rate_non_busy_loop, "bytes per second" ) local accepted_min = floor(rate_non_busy_loop * 0.9) local accepted_max = floor(rate_non_busy_loop * 1.1) if effective_rate_non_busy_loop < accepted_min or effective_rate_non_busy_loop > accepted_max then print("test failed") ok = false end end do print("measure throughput on heavy load...") -- bytes per second local rate_busy_loop = 1200000000 local effective_rate_busy_loop -- bytes local bucket_size = rate_busy_loop / 10 -- should be big enough to process packets generated by Source:pull() -- during 100 ms - internal RateLimiter timer resolution -- small value may limit effective rate -- too big value may produce burst in the beginning rl:reset(rate_busy_loop, bucket_size) local snapshot = rl:get_stat_snapshot() for i = 1, 100000 do app.breathe() timer.run() end local elapsed_time = (tonumber(C.get_time_ns()) - snapshot.time) / 1e9 print("elapsed time ", elapsed_time, "seconds") local rx = tonumber(rl.input.input.stats.txpackets - snapshot.rx) print("packets received", rx, floor(rx / elapsed_time / 1e6), "Mpps") effective_rate_busy_loop = compute_effective_rate( rl, rate_busy_loop, snapshot ) print("configured rate is", rate_busy_loop, "bytes per second") print( "effective rate is", effective_rate_busy_loop, "bytes per second" ) print( "throughput is", floor(effective_rate_busy_loop / PACKET_SIZE / 1e6), "Mpps") -- on poor computer effective rate may be too small -- so no formal checks end if not ok then print("selftest failed") os.exit(1) end print("selftest passed") end
apache-2.0
oratory/wago.io
backend/api/lua/libs/LibBase64-1.0/LibBase64-1.0.lua
1
4957
--[[ Name: LibBase64-1.0 Author(s): ckknight (ckknight@gmail.com) Website: http://www.wowace.com/projects/libbase64-1-0/ Description: A library to encode and decode Base64 strings License: MIT ]] local LibBase64 = LibStub:NewLibrary("LibBase64-1.0", 1) if not LibBase64 then return end local _chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' local byteToNum = {} local numToChar = {} for i = 1, #_chars do numToChar[i - 1] = _chars:sub(i, i) byteToNum[_chars:byte(i)] = i - 1 end _chars = nil local A_byte = ("A"):byte() local Z_byte = ("Z"):byte() local a_byte = ("a"):byte() local z_byte = ("z"):byte() local zero_byte = ("0"):byte() local nine_byte = ("9"):byte() local plus_byte = ("+"):byte() local slash_byte = ("/"):byte() local equals_byte = ("="):byte() local whitespace = { [(" "):byte()] = true, [("\t"):byte()] = true, [("\n"):byte()] = true, [("\r"):byte()] = true, } local t = {} --- Encode a normal bytestring into a Base64-encoded string -- @param text a bytestring, can be binary data -- @param maxLineLength This should be a multiple of 4, greater than 0 or nil. If non-nil, it will break up the output into lines no longer than the given number of characters. 76 is recommended. -- @param lineEnding a string to end each line with. This is "\r\n" by default. -- @usage LibBase64.Encode("Hello, how are you doing today?") == "SGVsbG8sIGhvdyBhcmUgeW91IGRvaW5nIHRvZGF5Pw==" -- @return a Base64-encoded string function LibBase64.Encode(text, maxLineLength, lineEnding) if type(text) ~= "string" then error(("Bad argument #1 to `Encode'. Expected %q, got %q"):format("string", type(text)), 2) end if maxLineLength == nil then -- do nothing elseif type(maxLineLength) ~= "number" then error(("Bad argument #2 to `Encode'. Expected %q or %q, got %q"):format("number", "nil", type(maxLineLength)), 2) elseif (maxLineLength % 4) ~= 0 then error(("Bad argument #2 to `Encode'. Expected a multiple of 4, got %s"):format(maxLineLength), 2) elseif maxLineLength <= 0 then error(("Bad argument #2 to `Encode'. Expected a number > 0, got %s"):format(maxLineLength), 2) end if lineEnding == nil then lineEnding = "\r\n" elseif type(lineEnding) ~= "string" then error(("Bad argument #3 to `Encode'. Expected %q, got %q"):format("string", type(lineEnding)), 2) end local currentLength = 0 for i = 1, #text, 3 do local a, b, c = text:byte(i, i+2) local nilNum = 0 if not b then nilNum = 2 b = 0 c = 0 elseif not c then nilNum = 1 c = 0 end local num = a * 2^16 + b * 2^8 + c local d = num % 2^6 num = (num - d) / 2^6 local c = num % 2^6 num = (num - c) / 2^6 local b = num % 2^6 num = (num - b) / 2^6 local a = num % 2^6 t[#t+1] = numToChar[a] t[#t+1] = numToChar[b] t[#t+1] = (nilNum >= 2) and "=" or numToChar[c] t[#t+1] = (nilNum >= 1) and "=" or numToChar[d] currentLength = currentLength + 4 if maxLineLength and (currentLength % maxLineLength) == 0 then t[#t+1] = lineEnding end end local s = table.concat(t) for i = 1, #t do t[i] = nil end return s end local t2 = {} --- Decode a Base64-encoded string into a bytestring -- this will raise an error if the data passed in is not a Base64-encoded string -- this will ignore whitespace, but not invalid characters -- @param text a Base64-encoded string -- @usage LibBase64.Encode("SGVsbG8sIGhvdyBhcmUgeW91IGRvaW5nIHRvZGF5Pw==") == "Hello, how are you doing today?" -- @return a bytestring function LibBase64.Decode(text) if type(text) ~= "string" then error(("Bad argument #1 to `Decode'. Expected %q, got %q"):format("string", type(text)), 2) end for i = 1, #text do local byte = text:byte(i) if whitespace[byte] or byte == equals_byte then -- do nothing else local num = byteToNum[byte] if not num then for i = 1, #t2 do t2[k] = nil end error(("Bad argument #1 to `Decode'. Received an invalid char: %q"):format(text:sub(i, i)), 2) end t2[#t2+1] = num end end for i = 1, #t2, 4 do local a, b, c, d = t2[i], t2[i+1], t2[i+2], t2[i+3] local nilNum = 0 if not c then nilNum = 2 c = 0 d = 0 elseif not d then nilNum = 1 d = 0 end local num = a * 2^18 + b * 2^12 + c * 2^6 + d local c = num % 2^8 num = (num - c) / 2^8 local b = num % 2^8 num = (num - b) / 2^8 local a = num % 2^8 t[#t+1] = string.char(a) if nilNum < 2 then t[#t+1] = string.char(b) end if nilNum < 1 then t[#t+1] = string.char(c) end end for i = 1, #t2 do t2[i] = nil end local s = table.concat(t) for i = 1, #t do t[i] = nil end return s end
mit
rickyHong/dptorchLib
init.lua
1
6568
require 'torch' require 'nn' require 'nnx' require 'string' _ = require 'moses' require 'xlua' require 'fs' require 'os' require 'sys' require 'image' require 'lfs' ffi = require 'ffi' ------------------------------------------------------------------------ --[[ dp ]]-- -- deep learning library for torch7. ------------------------------------------------------------------------ dp = {} dp.TORCH_DIR = os.getenv('TORCH_DATA_PATH') or os.getenv('HOME') --[[ utils ]]-- torch.include('dp', 'utils/utils.lua') torch.include('dp', 'utils/underscore.lua') torch.include('dp', 'utils/os.lua') torch.include('dp', 'utils/table.lua') torch.include('dp', 'utils/torch.lua') torch.include('dp', 'utils/threads.lua') --[[ directory structure ]]-- dp.DATA_DIR = os.getenv('DEEP_DATA_PATH') or paths.concat(dp.TORCH_DIR, 'data') dp.check_and_mkdir(dp.DATA_DIR) dp.SAVE_DIR = os.getenv('DEEP_SAVE_PATH') or paths.concat(dp.TORCH_DIR, 'save') dp.check_and_mkdir(dp.SAVE_DIR) dp.LOG_DIR = os.getenv('DEEP_LOG_PATH') or paths.concat(dp.TORCH_DIR, 'log') dp.check_and_mkdir(dp.LOG_DIR) dp.UNIT_DIR = os.getenv('DEEP_UNIT_PATH') or paths.concat(dp.TORCH_DIR, 'unit') dp.check_and_mkdir(dp.UNIT_DIR) --[[ misc ]]-- torch.include('dp', 'choose.lua') torch.include('dp', 'xplog.lua') torch.include('dp', 'mediator.lua') torch.include('dp', 'objectid.lua') torch.include('dp', 'node.lua') --[[ view ]]-- torch.include('dp', 'view/view.lua') torch.include('dp', 'view/dataview.lua') torch.include('dp', 'view/imageview.lua') torch.include('dp', 'view/classview.lua') torch.include('dp', 'view/sequenceview.lua') torch.include('dp', 'view/listview.lua') --[[ data ]]-- torch.include('dp', 'data/baseset.lua') torch.include('dp', 'data/dataset.lua') torch.include('dp', 'data/sentenceset.lua') torch.include('dp', 'data/imageclassset.lua') torch.include('dp', 'data/batch.lua') torch.include('dp', 'data/carry.lua') torch.include('dp', 'data/datasource.lua') torch.include('dp', 'data/mnist.lua') torch.include('dp', 'data/cifar10.lua') torch.include('dp', 'data/cifar100.lua') torch.include('dp', 'data/notmnist.lua') torch.include('dp', 'data/facialkeypoints.lua') torch.include('dp', 'data/billionwords.lua') torch.include('dp', 'data/svhn.lua') torch.include('dp', 'data/imagenet.lua') --[[ sampler ]]-- torch.include('dp', 'sampler/sampler.lua') torch.include('dp', 'sampler/shufflesampler.lua') torch.include('dp', 'sampler/sentencesampler.lua') torch.include('dp', 'sampler/randomsampler.lua') --[[ preprocess ]]-- torch.include('dp', 'preprocess/preprocess.lua') torch.include('dp', 'preprocess/pipeline.lua') torch.include('dp', 'preprocess/parallelpreprocess.lua') torch.include('dp', 'preprocess/binarize.lua') torch.include('dp', 'preprocess/standardize.lua') torch.include('dp', 'preprocess/gcn.lua') torch.include('dp', 'preprocess/zca.lua') torch.include('dp', 'preprocess/lecunlcn.lua') --[[ propagator ]]-- torch.include('dp', 'propagator/propagator.lua') torch.include('dp', 'propagator/optimizer.lua') torch.include('dp', 'propagator/evaluator.lua') torch.include('dp', 'propagator/experiment.lua') --[[ feedback ]]-- torch.include('dp', 'feedback/feedback.lua') torch.include('dp', 'feedback/compositefeedback.lua') torch.include('dp', 'feedback/confusion.lua') torch.include('dp', 'feedback/perplexity.lua') torch.include('dp', 'feedback/topcrop.lua') torch.include('dp', 'feedback/fkdkaggle.lua') torch.include('dp', 'feedback/facialkeypointfeedback.lua') --torch.include('dp', 'feedback/criteria.lua') --[[ visitor ]]-- torch.include('dp', 'visitor/visitor.lua') torch.include('dp', 'visitor/visitorchain.lua') torch.include('dp', 'visitor/recurrentvisitorchain.lua') torch.include('dp', 'visitor/maxnorm.lua') torch.include('dp', 'visitor/weightdecay.lua') torch.include('dp', 'visitor/learn.lua') torch.include('dp', 'visitor/momentum.lua') torch.include('dp', 'visitor/gradclip.lua') --[[ observer ]]-- torch.include('dp', 'observer/observer.lua') torch.include('dp', 'observer/compositeobserver.lua') torch.include('dp', 'observer/logger.lua') torch.include('dp', 'observer/errorminima.lua') torch.include('dp', 'observer/earlystopper.lua') torch.include('dp', 'observer/savetofile.lua') --not an observer torch.include('dp', 'observer/learningrateschedule.lua') torch.include('dp', 'observer/adaptivelearningrate.lua') torch.include('dp', 'observer/filelogger.lua') --[[ nn ]]-- torch.include('dp', 'nn/Print.lua') torch.include('dp', 'nn/PrintSize.lua') torch.include('dp', 'nn/FairLookupTable.lua') --[[ model ]]-- torch.include('dp', 'model/model.lua') torch.include('dp', 'model/container.lua') torch.include('dp', 'model/sequential.lua') torch.include('dp', 'model/layer.lua') torch.include('dp', 'model/neural.lua') torch.include('dp', 'model/module.lua') torch.include('dp', 'model/dictionary.lua') torch.include('dp', 'model/narrowdictionary.lua') torch.include('dp', 'model/recurrentdictionary.lua') torch.include('dp', 'model/softmaxtree.lua') torch.include('dp', 'model/softmaxforest.lua') torch.include('dp', 'model/mixtureofexperts.lua') torch.include('dp', 'model/blocksparse.lua') torch.include('dp', 'model/convolution1D.lua') torch.include('dp', 'model/convolution2D.lua') torch.include('dp', 'model/inception.lua') --[[ loss ]]-- torch.include('dp', 'loss/loss.lua') torch.include('dp', 'loss/nll.lua') torch.include('dp', 'loss/kldivergence.lua') torch.include('dp', 'loss/treenll.lua') torch.include('dp', 'loss/null.lua') torch.include('dp', 'loss/criterion.lua') --[[ hyper ]]-- torch.include('dp', 'hyper/hyperoptimizer.lua') torch.include('dp', 'hyper/hyperparamsampler.lua') torch.include('dp', 'hyper/datasourcefactory.lua') torch.include('dp', 'hyper/experimentfactory.lua') torch.include('dp', 'hyper/priorsampler.lua') torch.include('dp', 'hyper/imageclassfactory.lua') torch.include('dp', 'hyper/mlpfactory.lua') torch.include('dp', 'hyper/contextwordfactory.lua') torch.include('dp', 'hyper/lmfactory.lua') --[[ postgres ]]-- torch.include('dp', 'postgres/postgres.lua') torch.include('dp', 'postgres/logger.lua') torch.include('dp', 'postgres/xplog.lua') torch.include('dp', 'postgres/savetofile.lua') torch.include('dp', 'postgres/earlystopper.lua') torch.include('dp', 'postgres/done.lua') torch.include('dp', 'postgres/mlpfactory.lua') torch.include('dp', 'postgres/lmfactory.lua') torch.include('dp', 'postgres/hyperoptimizer.lua') --[[ test ]]-- torch.include('dp', 'test/test.lua') torch.include('dp', 'test/test-cuda.lua') torch.include('dp', 'test/test-datasets.lua') return dp
bsd-3-clause
zhusz/ICCV17-fashionGAN
ih1_p2p/net_graph_ih1.lua
1
2959
require 'nngraph' local function weights_init(m) local name = torch.type(m) if name:find('Convolution') then m.weight:normal(0.0, 0.02) -- zhuzhu m.bias:fill(0) -- zhuzhu -- m:noBias() elseif name:find('BatchNormalization') then if m.weight then m.weight:normal(1.0, 0.02) end if m.bias then m.bias:fill(0) end end end local nc = 3 local ncondition = 3 -- zhuzhu local nz = 100 -- opt.nz local ndf = 64 -- opt.ndf local ngf = 64 -- opt.ngf local inplace = true local bn4 = nn.SpatialBatchNormalization local conv = nn.SpatialConvolution local deconv = nn.SpatialFullConvolution local relu = nn.ReLU local lerelu = nn.LeakyReLU local input_condition = nn.Identity()() local e1 = input_condition - conv(ncondition, ngf, 4, 4, 2, 2, 1, 1) local e2 = e1 - lerelu(0.2, inplace) - conv(ngf, ngf * 2, 4, 4, 2, 2, 1, 1) - bn4(ngf * 2) local e3 = e2 - lerelu(0.2, inplace) - conv(ngf * 2, ngf * 4, 4, 4, 2, 2, 1, 1) - bn4(ngf * 4) local e4 = e3 - lerelu(0.2, inplace) - conv(ngf * 4, ngf * 8, 4, 4, 2, 2, 1, 1) - bn4(ngf * 8) local e5 = e4 - lerelu(0.2, inplace) - conv(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) - bn4(ngf * 8) local e6 = e5 - lerelu(0.2, inplace) - conv(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) - bn4(ngf * 8) local e7 = e6 - lerelu(0.2, inplace) - conv(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) local d1_ = e7 - relu(inplace) - deconv(ngf*8, ngf*8, 4, 4, 2, 2, 1, 1) - bn4(ngf * 8) - nn.Dropout(0.5) local d1 = {d1_, e6} - nn.JoinTable(2) local d2_ = d1 - relu(inplace) - deconv(ngf*8*2, ngf*8, 4, 4, 2, 2, 1, 1) - bn4(ngf*8) - nn.Dropout(0.5) local d2 = {d2_, e5} - nn.JoinTable(2) local d3_ = d2 - relu(inplace) - deconv(ngf*8*2, ngf*8, 4, 4, 2, 2, 1, 1) - bn4(ngf*8) - nn.Dropout(0.5) local d3 = {d3_, e4} - nn.JoinTable(2) local d4_ = d3 - relu(inplace) - deconv(ngf*8*2, ngf*4, 4, 4, 2, 2, 1, 1) - bn4(ngf*4) local d4 = {d4_, e3} - nn.JoinTable(2) local d5_ = d4 - relu(inplace) - deconv(ngf*4*2, ngf*2, 4, 4, 2, 2, 1, 1) - bn4(ngf*2) local d5 = {d5_, e2} - nn.JoinTable(2) local d6_ = d5 - relu(inplace) - deconv(ngf*2*2, ngf, 4, 4, 2, 2, 1, 1) - bn4(ngf) local d6 = {d6_, e1} - nn.JoinTable(2) local d7 = d6 - relu(inplace) - deconv(ngf * 2, nc, 4, 4, 2, 2, 1, 1) local o1 = d7 - nn.Tanh() local netG = nn.gModule({input_condition}, {o1}) netG:apply(weights_init) local output_data = nn.Identity()() local output_condition = nn.Identity()() local output_merge = {output_data, output_condition} - nn.JoinTable(2) local x0 = output_merge - conv(ncondition+nc, ndf, 4, 4, 2, 2, 1, 1) - lerelu(0.2, inplace) local x1 = x0 - conv(ndf*1,ndf*2,4,4,2,2,1,1) - bn4(ndf*2) - lerelu(0.2, inplace) local x2 = x1 - conv(ndf*2,ndf*4,4,4,2,2,1,1) - bn4(ndf*4) - lerelu(0.2, inplace) local x3 = x2 - conv(ndf*4,ndf*8,4,4,1,1,1,1) - bn4(ndf*8) - lerelu(0.2, inplace) local x4 = x3 - conv(ndf*8,1,4,4,1,1,1,1) - nn.Sigmoid() local netD = nn.gModule({output_data,output_condition}, {x4}) netD:apply(weights_init) return netG, netD
bsd-3-clause
tehran980/tele_HSN
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
resistor58/deaths-gmod-server
ulib/lua/ULib/server/hook.lua
1
4783
--[[ Title: Hook This overrides garry's default hook system. We need this better hook system for any serious development. We're implementing hook priorities. hook.Add() now takes an additional parameter of type number between -20 and 20. 0 is default (so we remain backwards compatible). -20 and 20 are read only (ignores returned values). Hooks are called in order from -20 on up. ]] -- Globals that we are going to use local pairs = pairs local ErrorNoHalt = ErrorNoHalt local pcall = pcall local tostring = tostring local concommand = concommand local PrintTable = PrintTable local CLIENT = CLIENT local type = type -- Grab all previous hooks from the pre-existing hook module. local OldHooks = hook.GetTable() ----------------------------------------------------------- -- Name: hook -- Desc: For scripts to hook onto Gamemode events ----------------------------------------------------------- module( "hook" ) -- Local variables local Hooks = {} -- Exposed Functions --[[ Function: hook.GetTable Returns: The table filled with all the hooks ]] function GetTable() return Hooks end --[[ Function: hook.Add Our new and improved hook.Add function. Read the file description for more information on how the hook priorities work. Parameters: event_name - The name of the event (IE "PlayerInitialSpawn"). name - The unique name of your hook. This is only so that if the file is reloaded, it can be unhooked (or you can unhook it yourself). func - The function callback to call priority - *(Optional, defaults to 0)* Priority from -20 to 20. Remember that -20 and 20 are read-only. ]] function Add( event_name, name, func, priority ) if not Hooks[ event_name ] then Hooks[ event_name ] = {} for i=-20, 20 do Hooks[ event_name ][ i ] = {} end end priority = priority or 0 Hooks[ event_name ][ priority ][ name ] = func Hooks[ event_name ][ tostring( name ) ] = func -- Keep the classic style too so we won't break anything end --[[ Function: hook.Remove Parameters: event_name - The name of the event (IE "PlayerInitialSpawn"). name - The unique name of your hook. Use the same name you used in hook.Add() ]] function Remove( event_name, name ) for i=-20, 20 do if Hooks[ event_name ][ i ][ name ] then Hooks[ event_name ][ i ][ name ] = nil end end Hooks[ event_name ][ tostring( name ) ] = nil end --[[ Function: hook.Call Normally, you don't want to call this directly. Use gamemode.Call() instead. Parameters: name - The name of the event gm - The gamemode table ... - Any other params to pass ]] function Call( name, gm, ... ) local b, retval local HookTable = Hooks[ name ] if HookTable then for i=-20, 20 do for k, v in pairs( HookTable[ i ] ) do if not v then ErrorNoHalt( "ERROR: Hook '" .. tostring( k ) .. "' tried to call a nil function!\n" ) ErrorNoHalt( "Removing Hook '" .. tostring( k ) .. "'\n" ) HookTable[ i ][ k ] = nil -- remove this hook break else -- Call hook function b, retval = pcall( v, ... ) if not b then ErrorNoHalt( "ERROR: Hook '" .. tostring( k ) .. "' Failed: " .. tostring( retval ) .. "\n" ) ErrorNoHalt( "Removing Hook '" .. tostring( k ) .. "'\n" ) HookTable[ i ][ k ] = nil -- remove this hook else -- Allow hooks to override return values if it's within the limits (-20 and 20 are read only) if retval ~= nil and i > -20 and i < 20 then return retval end end end end end end if gm then local GamemodeFunction = gm[ name ] if not GamemodeFunction then return nil end if type( GamemodeFunction ) ~= "function" then Msg( "Calling Non Function!? ", GamemodeFunction, "\n" ) end -- This calls the actual gamemode function - after all the hooks have had chance to override b, retval = pcall( GamemodeFunction, gm, ... ) if not b then gm[ name .. "_ERRORCOUNT" ] = gm[ name .. "_ERRORCOUNT" ] or 0 gm[ name .. "_ERRORCOUNT" ] = gm[ name .. "_ERRORCOUNT" ] + 1 ErrorNoHalt( "ERROR: GAMEMODE:'" .. tostring( name ) .. "' Failed: " .. tostring( retval ) .. "\n" ) return nil end end return retval end --************************************** -- DEBUG CONSOLE COMMAND FOR LUA CODERS --************************************** local function DumpHooks() PrintTable( Hooks ) end if ( CLIENT ) then concommand.Add( "dump_hooks_cl", DumpHooks ) else concommand.Add( "dump_hooks", DumpHooks ) end for event_name, t in pairs( OldHooks ) do for name, func in pairs( t ) do Add( event_name, name, func, 0 ) end end
gpl-3.0
ruvolof/telegram-bot
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
fegimanam/telegram-bot-supergroups
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
RobertZenz/minetest-australopithecus-utils
mods/utils/settings.lua
2
7177
--[[ Copyright (c) 2015, Robert 'Bobby' Zenz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --]] --- Encapsulates the settings API of minetest and extends it with further -- functions. settings = {} --- Gets a value from the configuration as is. -- -- @param name The name of the value to get. -- @param default_value Optional. The default_value to return if the value is -- not set in the configuration. Can be nil. -- @param cast_function Optional. The function to apply to the value that is -- read, for example to convert it into a different type. -- If this function returns nil, the default value IS -- returned. Can be nil. -- @return The value from the configuration with the given name. If the read -- value is nil, the default value is returned or nil. function settings.get(name, default_value, cast_function) local value = minetest.setting_get(name) if value ~= nil and cast_function ~= nil then value = cast_function(value) end if value ~= nil then return value else return default_value end end --- Gets a boolean from the configuration. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is nil. -- Can be nil. -- @return The boolean with the given name, or the default value if it is nil, -- or nil. function settings.get_bool(name, default_value) local value = minetest.setting_getbool(name) if value ~= nil then return value else return default_value end end --- Gets a list from the configuration. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is -- nil. Can be nil. -- @return The list with the given name, or the default value if it is nil, -- or nil. function settings.get_list(name, default_value) local value = settings.get(name, nil, tostring) if value ~= nil then return stringutil.split(value, ",") elseif type(default_value) == "string" then return stringutil.split(default_value, ",") else return default_value end end --- Gets a number from the configuration. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is nil. -- Can be nil. -- @return The number with the given name, or the default value if it is nil, -- or nil. function settings.get_number(name, default_value) return settings.get(name, default_value, tonumber) end --- Gets a pos (with x and y values) from the configuration. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is nil. -- Can be nil. -- @return The pos with the given name, or the default value if it is nil, -- or nil. function settings.get_pos2d(name, default_value) local value = minetest.setting_get(name) if value ~= nil then local splitted_value = stringutil.split(value, ",") if splitted_value:size() == 2 then local x = tonumber(splitted_value:get(1)) local y = tonumber(splitted_value:get(2)) if x ~= nil and y ~= nil then return { x = x, y = y } end end end return default_value end --- Gets a pos with (x, y and z values) from the configuration. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is nil. -- Can be nil. -- @return The pos with the given name, or the default value if it is nil, -- or nil. function settings.get_pos3d(name, default_value) local value = minetest.setting_get_pos(name) if value ~= nil then return value else return default_value end end --- Gets a string from the configuration. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is nil. -- Can be nil. -- @return The string with the given name, or the default value if it is nil, -- or nil. function settings.get_string(name, default_value) return settings.get(name, default_value, tostring) end --- Gets a table with the given keys form the configuration. -- -- @param name The name of the value to get. -- @param default_value The default value to return if the value is nil, can be -- nil. -- @param ... The name of the keys, or a table with the name and the conversion -- function. -- @return The table with the given name and the given keys, or the default -- value it is nil. function settings.get_table(name, default_value, ...) local value = settings.get_list(name, nil) if value ~= nil then local table = {} if ... ~= nil then for index, key in ipairs({...}) do if type(key) == "table" then table[key.name] = key.convert(value:get(index)) else table[key] = value:get(index) end end end if ... == nil or #{...} < value:size() then for index = #{...} + 1, value:size(), 1 do table[index] = value:get(index) end end return table else return default_value end end --- Saves all settings to configuration file. function settings.save() minetest.setting_save() end --- Set a value with the given name into the configuration. -- -- @param name The name of the value to set. Is not allowed to contain '="#{}'. -- @param value The value. function settings.set(name, value) minetest.setting_set(name, value) end --- Gets a pos from the configuration, this is an alias for get_pos3d. -- -- @param name The name of the value to get. -- @param default_value Optional. The default value to return if the value is nil. -- Can be nil. -- @return The pos with the given name, or the default value if it is nil, -- or nil. settings.get_pos = settings.get_pos3d
bsd-2-clause
zchengquan/nn
SpatialConvolution.lua
27
4452
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padW = padW or 0 self.padH = padH or self.padW self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() if self.padding then self.padW = self.padding self.padH = self.padding self.padding = nil else self.padW = self.padW or 0 self.padH = self.padH or 0 end if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end function SpatialConvolution:updateOutput(input) backCompatibility(self) viewWeight(self) input = makeContiguous(self, input) local out = input.nn.SpatialConvolutionMM_updateOutput(self, input) unviewWeight(self) return out end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then backCompatibility(self) viewWeight(self) input, gradOutput = makeContiguous(self, input, gradOutput) local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) unviewWeight(self) return out end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) viewWeight(self) local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) unviewWeight(self) return out end function SpatialConvolution:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end function SpatialConvolution:__tostring__() local s = string.format('%s(%d -> %d, %dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.kW, self.kH) if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d', self.dW, self.dH) end if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padW .. ',' .. self.padH end return s .. ')' end
bsd-3-clause
zeta0134/LuaGB
gameboy/z80/arithmetic.lua
1
7065
local bit32 = require("bit") local lshift = bit32.lshift local rshift = bit32.rshift local band = bit32.band local bxor = bit32.bxor local bor = bit32.bor local bnor = bit32.bnor function apply(opcodes, opcode_cycles, z80, memory) local read_at_hl = z80.read_at_hl local set_at_hl = z80.set_at_hl local read_nn = z80.read_nn local reg = z80.registers local flags = reg.flags local read_byte = memory.read_byte local write_byte = memory.write_byte local add_to_a = function(value) -- half-carry flags.h = band(reg.a, 0xF) + band(value, 0xF) > 0xF local sum = reg.a + value -- carry (and overflow correction) flags.c = sum > 0xFF reg.a = band(sum, 0xFF) flags.z = reg.a == 0 flags.n = false end local adc_to_a = function(value) -- half-carry local carry = 0 if flags.c then carry = 1 end flags.h = band(reg.a, 0xF) + band(value, 0xF) + carry > 0xF local sum = reg.a + value + carry -- carry (and overflow correction) flags.c = sum > 0xFF reg.a = band(sum, 0xFF) flags.z = reg.a == 0 flags.n = false end -- add A, r opcodes[0x80] = function() add_to_a(reg.b) end opcodes[0x81] = function() add_to_a(reg.c) end opcodes[0x82] = function() add_to_a(reg.d) end opcodes[0x83] = function() add_to_a(reg.e) end opcodes[0x84] = function() add_to_a(reg.h) end opcodes[0x85] = function() add_to_a(reg.l) end opcode_cycles[0x86] = 8 opcodes[0x86] = function() add_to_a(read_at_hl()) end opcodes[0x87] = function() add_to_a(reg.a) end -- add A, nn opcode_cycles[0xC6] = 8 opcodes[0xC6] = function() add_to_a(read_nn()) end -- adc A, r opcodes[0x88] = function() adc_to_a(reg.b) end opcodes[0x89] = function() adc_to_a(reg.c) end opcodes[0x8A] = function() adc_to_a(reg.d) end opcodes[0x8B] = function() adc_to_a(reg.e) end opcodes[0x8C] = function() adc_to_a(reg.h) end opcodes[0x8D] = function() adc_to_a(reg.l) end opcode_cycles[0x8E] = 8 opcodes[0x8E] = function() adc_to_a(read_at_hl()) end opcodes[0x8F] = function() adc_to_a(reg.a) end -- adc A, nn opcode_cycles[0xCE] = 8 opcodes[0xCE] = function() adc_to_a(read_nn()) end sub_from_a = function(value) -- half-carry flags.h = band(reg.a, 0xF) - band(value, 0xF) < 0 reg.a = reg.a - value -- carry (and overflow correction) flags.c = reg.a < 0 or reg.a > 0xFF reg.a = band(reg.a, 0xFF) flags.z = reg.a == 0 flags.n = true end sbc_from_a = function(value) local carry = 0 if flags.c then carry = 1 end -- half-carry flags.h = band(reg.a, 0xF) - band(value, 0xF) - carry < 0 local difference = reg.a - value - carry -- carry (and overflow correction) flags.c = difference < 0 or difference > 0xFF reg.a = band(difference, 0xFF) flags.z = reg.a == 0 flags.n = true end -- sub A, r opcodes[0x90] = function() sub_from_a(reg.b) end opcodes[0x91] = function() sub_from_a(reg.c) end opcodes[0x92] = function() sub_from_a(reg.d) end opcodes[0x93] = function() sub_from_a(reg.e) end opcodes[0x94] = function() sub_from_a(reg.h) end opcodes[0x95] = function() sub_from_a(reg.l) end opcode_cycles[0x96] = 8 opcodes[0x96] = function() sub_from_a(read_at_hl()) end opcodes[0x97] = function() sub_from_a(reg.a) end -- sub A, nn opcode_cycles[0xD6] = 8 opcodes[0xD6] = function() sub_from_a(read_nn()) end -- sbc A, r opcodes[0x98] = function() sbc_from_a(reg.b) end opcodes[0x99] = function() sbc_from_a(reg.c) end opcodes[0x9A] = function() sbc_from_a(reg.d) end opcodes[0x9B] = function() sbc_from_a(reg.e) end opcodes[0x9C] = function() sbc_from_a(reg.h) end opcodes[0x9D] = function() sbc_from_a(reg.l) end opcode_cycles[0x9E] = 8 opcodes[0x9E] = function() sbc_from_a(read_at_hl()) end opcodes[0x9F] = function() sbc_from_a(reg.a) end -- sbc A, nn opcode_cycles[0xDE] = 8 opcodes[0xDE] = function() sbc_from_a(read_nn()) end -- daa -- BCD adjustment, correct implementation details located here: -- http://www.z80.info/z80syntx.htm#DAA opcodes[0x27] = function() local a = reg.a if not flags.n then -- Addition Mode, adjust BCD for previous addition-like instruction if band(0xF, a) > 0x9 or flags.h then a = a + 0x6 end if a > 0x9F or flags.c then a = a + 0x60 end else -- Subtraction mode! Adjust BCD for previous subtraction-like instruction if flags.h then a = band(a - 0x6, 0xFF) end if flags.c then a = a - 0x60 end end -- Always reset H and Z flags.h = false flags.z = false -- If a is greater than 0xFF, set the carry flag if band(0x100, a) == 0x100 then flags.c = true end -- Note: Do NOT clear the carry flag otherwise. This is how hardware -- behaves, yes it's weird. reg.a = band(a, 0xFF) -- Update zero flag based on A's contents flags.z = reg.a == 0 end add_to_hl = function(value) -- half carry flags.h = band(reg.hl(), 0xFFF) + band(value, 0xFFF) > 0xFFF local sum = reg.hl() + value -- carry flags.c = sum > 0xFFFF or sum < 0x0000 reg.set_hl(band(sum, 0xFFFF)) flags.n = false end -- add HL, rr opcode_cycles[0x09] = 8 opcode_cycles[0x19] = 8 opcode_cycles[0x29] = 8 opcode_cycles[0x39] = 8 opcodes[0x09] = function() add_to_hl(reg.bc()) end opcodes[0x19] = function() add_to_hl(reg.de()) end opcodes[0x29] = function() add_to_hl(reg.hl()) end opcodes[0x39] = function() add_to_hl(reg.sp) end -- inc rr opcode_cycles[0x03] = 8 opcodes[0x03] = function() reg.set_bc(band(reg.bc() + 1, 0xFFFF)) end opcode_cycles[0x13] = 8 opcodes[0x13] = function() reg.set_de(band(reg.de() + 1, 0xFFFF)) end opcode_cycles[0x23] = 8 opcodes[0x23] = function() reg.set_hl(band(reg.hl() + 1, 0xFFFF)) end opcode_cycles[0x33] = 8 opcodes[0x33] = function() reg.sp = band(reg.sp + 1, 0xFFFF) end -- dec rr opcode_cycles[0x0B] = 8 opcodes[0x0B] = function() reg.set_bc(band(reg.bc() - 1, 0xFFFF)) end opcode_cycles[0x1B] = 8 opcodes[0x1B] = function() reg.set_de(band(reg.de() - 1, 0xFFFF)) end opcode_cycles[0x2B] = 8 opcodes[0x2B] = function() reg.set_hl(band(reg.hl() - 1, 0xFFFF)) end opcode_cycles[0x3B] = 8 opcodes[0x3B] = function() reg.sp = band(reg.sp - 1, 0xFFFF) end -- add SP, dd opcode_cycles[0xE8] = 16 opcodes[0xE8] = function() local offset = read_nn() -- offset comes in as unsigned 0-255, so convert it to signed -128 - 127 if band(offset, 0x80) ~= 0 then offset = offset + 0xFF00 end -- half carry --if band(reg.sp, 0xFFF) + offset > 0xFFF or band(reg.sp, 0xFFF) + offset < 0 then flags.h = band(reg.sp, 0xF) + band(offset, 0xF) > 0xF -- carry flags.c = band(reg.sp, 0xFF) + band(offset, 0xFF) > 0xFF reg.sp = reg.sp + offset reg.sp = band(reg.sp, 0xFFFF) flags.z = false flags.n = false end end return apply
bsd-3-clause
nullstyle/docker-stellar-core
heka/stellar_core_metrics_filter.lua
1
2930
local cj = require "cjson" local dt = require "date_time" local l = require "lpeg" local table = require "table" local math = require "math" local environment = read_config("environment") local node = read_config("node") local cluster = read_config("cluster") local latest_stats = {} function process_message() local raw_message = read_message("Payload") local ok, json = pcall(cj.decode, raw_message) if not ok then return -1 end if json["ts"] ~= nil then local ts = lpeg.match(dt.rfc3339, json["ts"]) if not ts then return -1 end local timestamp = dt.time_to_ns(ts) end for name, stats in pairs(json["metrics"]) do if stats.type == "timer" then process_metric(timestamp, name, stats, { "count", "1_min_rate", "min", "mean", "max", "95%", "99%", "99.9%" }) elseif stats.type == "meter" then process_metric(timestamp, name, stats, { "count", "1_min_rate", }) elseif stats.type == "counter" then process_metric(timestamp, name, stats, { "count" }) end end return 0 end function send_to_influx(ns) local message = { Timestamp = ns, Type = "stellar.core.metrics.influx" } local time = math.floor(ns / 1000000) local output = {} for name, stats in pairs(latest_stats) do name = environment .. "." .. node .. "." .. name local point_set = { name = name, columns = {"time"}, points = {{time}} } for stat, value in pairs(stats) do table.insert(point_set.columns, stat) table.insert(point_set.points[1], value) end table.insert(output, point_set) end -- Only inject if we have metrics to send if next(output) then message.Payload = cjson.encode(output) inject_message(message) end end function send_to_atlas(ns) local message = { Timestamp = ns, Type = "stellar.core.metrics.atlas" } local time = math.floor(ns / 1000000) local output = { tags = { environment = environment, cluster = cluster, node = node, app = "stellar-core" }, metrics = { } } for name, stats in pairs(latest_stats) do for stat, value in pairs(stats) do local metric_payload = { tags = { name = name, stat = stat, ["atlas.dstype"] = "gauge" }, timestamp = time, value = value } table.insert(output.metrics, metric_payload) end end -- Only inject if we have metrics to send if next(output.metrics) then message.Payload = cjson.encode(output) inject_message(message) end end function timer_event(ns) send_to_influx(ns) send_to_atlas(ns) end function process_metric(timestamp, name, stats, stat_whitelist) local selected_stats = {} for i, stat in ipairs(stat_whitelist) do selected_stats[stat] = stats[stat] end latest_stats[name] = selected_stats end
apache-2.0
resistor58/deaths-gmod-server
ulx/lua/ulx/modules/slots.lua
1
3462
-- This file handles reserved slots ulx.setCategory( "Reserved Slots" ) ulx.convar( "rslotsMode", "0", " - Sets the slots mode. See server.ini for more information.", ULib.ACCESS_ADMIN ) ulx.convar( "rslots", "2", " - Sets the number of reserved slots, only applicable for modes 1 and 2.", ULib.ACCESS_ADMIN ) ulx.convar( "rslotsVisible", "1", " - Sets whether slots are visible. See server.ini for more information.", ULib.ACCESS_ADMIN ) local access = "ulx reservedslots" -- Access string needed for reserved slots ULib.ucl.registerAccess( access, ULib.ACCESS_ADMIN ) -- Give admins access to reserved slots by default function calcSlots( disconnect ) local mode = GetConVarNumber( "ulx_rslotsMode" ) if mode == 3 then return 1 end -- Only one slot on this mode local slots = GetConVarNumber( "ulx_rslots" ) if mode == 2 then return slots end if mode == 1 then local admins = 0 -- Keep track of how many people with access we have local players = player.GetAll() for _, player in ipairs( players ) do if player:IsConnected() and player:query( access ) then admins = admins + 1 end end if disconnect then admins = admins - 1 end -- Otherwise we're counting the disconnecting admin if admins < 0 then admins = 0 end -- Just to be safe! local rslots = slots - admins if rslots < 0 then rslots = 0 end -- If we have more admins right now then slots for them, we don't want to return a negative number. return rslots end return 0 -- We're actually having an error if we get here, but let's handle it gracefully end local function updateSlots( ply, disconnect ) local visible = util.tobool( GetConVarString( "ulx_rslotsVisible" ) ) if not visible then -- Make sure our visible slots is up to date local slots = calcSlots( disconnect ) local max = MaxPlayers() game.ConsoleCommand( "sv_visiblemaxplayers " .. max - slots .. "\n" ) end end hook.Add( "PlayerDisconnected", "ulxSlotsDisconnect", function( ply ) updateSlots( ply, ply:query( access ) ) end ) ulx.OnDoneLoading( updateSlots ) local function playerAccess( ply ) local mode = GetConVarNumber( "ulx_rslotsMode" ) if mode == 0 then return end -- Off! local visible = util.tobool( GetConVarString( "ulx_rslotsVisible" ) ) local slots = calcSlots() local cur = #player.GetAll() local max = MaxPlayers() if ply:query( access ) then -- If they have access, handle this differently if not visible then -- Make sure our visible slots is up to date updateSlots() end if mode == 3 and cur + slots > max then -- We've got some kicking to do! local shortestply local shortesttime = 0 local players = player.GetAll() for _, player in ipairs( players ) do if not ULib.ucl.query( player, access ) and not ULib.ucl.query( player, ULib.ACCESS_IMMUNITY ) then if player.Created > shortesttime then shortesttime = player.Created shortestply = player end end end if not shortestply then -- We've got a server filled to the brim with admins? Odd but okay return end ULib.kick( shortestply, "[ULX] Freeing slot. Sorry, you had the shortest connection time." ) end return end if cur + slots > max then timer.Simple( FrameTime() * 0.5, ULib.kick, ply, "[ULX] Reserved slot, sorry!" ) -- Wait a frame so all access hooks can be called properly. end end ULib.ucl.addAccessCallback( playerAccess )
gpl-3.0
tkdrob/Battle-Tag
Packages/LastTeamStanding/Data/Script/ByteCode/UALastTeamStanding.ByteCode2.lua
1
4699
byteCode = { 0x11, 0x53, 0x43, 0x30, 0x35, 0x00, 0x00, 0x53, 0x43, 0x30, 0x33, 0x00, 0x00, 0x41, 0x53, 0x48, 0x54, 0x00, 0x00, 0x53, 0x57, 0x35, 0x36, 0x00, 0x00, 0x53, 0x44, 0x30, 0x31, 0x00, 0x00, 0x53, 0x44, 0x31, 0x33, 0x00, 0x00, 0x53, 0x57, 0x32, 0x32, 0x00, 0x00, 0x53, 0x43, 0x30, 0x38, 0x00, 0x00, 0x53, 0x43, 0x30, 0x32, 0x00, 0x00, 0x53, 0x57, 0x31, 0x32, 0x00, 0x00, 0x53, 0x57, 0x34, 0x32, 0x00, 0x00, 0x41, 0x52, 0x41, 0x4d, 0x00, 0x00, 0x53, 0x43, 0x31, 0x30, 0x00, 0x00, 0x53, 0x43, 0x30, 0x39, 0x00, 0x00, 0x41, 0x4d, 0x45, 0x44, 0x00, 0x00, 0x53, 0x44, 0x30, 0x33, 0x00, 0x00, 0x41, 0x4f, 0x55, 0x54, 0x00, 0x00, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x02, 0xcc, 0x00, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xd0, 0x00, 0x45, 0xc4, 0x05, 0x01, 0x00, 0x00, 0x03, 0x10, 0xcf, 0x01, 0x02, 0x00, 0xcf, 0x00, 0x03, 0x00, 0xcd, 0x00, 0x00, 0x00, 0xce, 0x01, 0x00, 0x00, 0x2d, 0xcf, 0x01, 0x03, 0x00, 0xcf, 0x00, 0x02, 0x00, 0xc4, 0x07, 0x01, 0x00, 0x14, 0x03, 0x18, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0xcd, 0x00, 0x01, 0x00, 0xce, 0x00, 0x02, 0x00, 0x08, 0xcd, 0x00, 0x01, 0x01, 0xce, 0x00, 0x02, 0x01, 0x05, 0xd6, 0xce, 0x01, 0x01, 0x01, 0xd0, 0x01, 0x1d, 0xc0, 0x02, 0x00, 0x08, 0xc0, 0x01, 0x00, 0x07, 0xc1, 0x02, 0xc4, 0x09, 0x01, 0x00, 0x02, 0x02, 0x04, 0xc0, 0x0e, 0x00, 0x0d, 0x00, 0xc0, 0x05, 0x01, 0x00, 0x00, 0xc3, 0x00, 0xd0, 0x02, 0x17, 0xc0, 0x00, 0x00, 0x06, 0xc4, 0x09, 0x01, 0x00, 0x00, 0x00, 0x04, 0xc0, 0x0f, 0x00, 0x0d, 0x00, 0xc0, 0x05, 0x01, 0x00, 0x01, 0xc3, 0x00, 0xd0, 0x03, 0x0e, 0xd0, 0x01, 0xd0, 0x02, 0xc0, 0x0e, 0x01, 0x00, 0x32, 0xc0, 0x0f, 0x01, 0x00, 0x32, 0xd0, 0x04, 0x23, 0xc5, 0x00, 0x00, 0xca, 0x1e, 0x01, 0xc4, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0xc1, 0x00, 0xd3, 0x1e, 0xc0, 0x05, 0x01, 0x00, 0x01, 0x00, 0xc4, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0xc3, 0x01, 0x00, 0xd0, 0x00, 0xd2, 0x02, 0x00, 0x33, 0x0c, 0x31, 0xc9, 0x64, 0xc0, 0x03, 0x01, 0x00, 0x00, 0xc0, 0x13, 0x01, 0x00, 0x00, 0xc0, 0x12, 0x01, 0x00, 0x00, 0xc4, 0x0b, 0x01, 0x00, 0x00, 0x02, 0x02, 0xdc, 0x0a, 0x00, 0xc1, 0x0a, 0xc4, 0x06, 0x01, 0x00, 0x00, 0x02, 0x07, 0xc0, 0x00, 0x01, 0x00, 0x00, 0xc3, 0x01, 0x05, 0xc5, 0x00, 0x01, 0xd0, 0x03, 0xc7, 0x00, 0x00, 0xfb, 0x01, 0x5b, 0xc4, 0x04, 0x01, 0x00, 0x07, 0x01, 0x53, 0xc0, 0x05, 0x01, 0x00, 0x00, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x27, 0xc4, 0x07, 0x01, 0x00, 0x14, 0x03, 0x02, 0xc1, 0x01, 0x02, 0xcb, 0x02, 0xc5, 0x01, 0x03, 0xd4, 0x01, 0xd5, 0x01, 0xc6, 0xc4, 0x01, 0x01, 0x00, 0x03, 0x02, 0x0b, 0xc4, 0x02, 0x01, 0x00, 0x00, 0x02, 0x03, 0xc5, 0x01, 0x04, 0x00, 0x00, 0x1a, 0xc4, 0x02, 0x01, 0x00, 0x00, 0x02, 0x12, 0xc2, 0x13, 0xc4, 0x13, 0x01, 0x00, 0x05, 0x00, 0x08, 0xc5, 0x01, 0x05, 0xc0, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x00, 0xc5, 0x00, 0x06, 0x00, 0x02, 0x45, 0xc8, 0x10, 0xc4, 0x10, 0x01, 0x00, 0x01, 0x02, 0x38, 0xde, 0x0d, 0xc4, 0x0d, 0x01, 0x00, 0x04, 0x02, 0x0b, 0xd9, 0x0d, 0xc4, 0x0d, 0x00, 0x0e, 0x03, 0x02, 0xc3, 0x03, 0x00, 0x00, 0xc4, 0x04, 0x01, 0x00, 0x01, 0x01, 0x1b, 0xc4, 0x0c, 0x01, 0x00, 0x01, 0x02, 0x13, 0xc4, 0x0d, 0x01, 0x00, 0x03, 0x02, 0x0b, 0xd9, 0x0d, 0xc4, 0x0d, 0x00, 0x0f, 0x03, 0x02, 0xc3, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x07, 0x0b, 0x02, 0xd0, 0x04, 0x00, 0x1c, 0xc4, 0x04, 0x01, 0x00, 0x06, 0x01, 0x12, 0xc5, 0x00, 0x08, 0xc2, 0x05, 0xc4, 0x05, 0x01, 0x00, 0x01, 0x00, 0x05, 0xc0, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x09, 0x1d, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x02, 0x13, 0xc4, 0x02, 0x01, 0x00, 0x00, 0x00, 0x0b, 0xc1, 0x02, 0xc5, 0x00, 0x09, 0xc0, 0x01, 0x00, 0x07, 0xd0, 0x00, 0x00, 0x00, 0xc2, 0x03, 0x0c, 0x02, 0xd0, 0x00, 0x0d, 0x04, 0xce, 0x01, 0x01, 0x01, 0x0e, 0x0a, 0xc4, 0x04, 0x01, 0x00, 0x00, 0x02, 0x02, 0xdd, 0x01, 0x00, 0xc7, 0x03, 0x00, 0x14, 0x0c, 0x07, 0xc5, 0x00, 0x0a, 0xd5, 0x01, 0xcb, 0x0b, 0x0d, 0x05, 0xd0, 0x01, 0xc5, 0x01, 0x0c, 0x0b, 0x02, 0xd0, 0x04, 0xc7, 0x04, 0x00, 0x17, 0x0c, 0x07, 0xc5, 0x00, 0x0d, 0xd5, 0x01, 0xcb, 0x0e, 0x0d, 0x05, 0xd0, 0x02, 0xc5, 0x01, 0x0c, 0x0b, 0x05, 0xd0, 0x02, 0xdf, 0xd0, 0x04, 0xc7, 0x01, 0x00, 0x0c, 0x0c, 0x0a, 0xc5, 0x01, 0x0f, 0xca, 0x1e, 0x00, 0xd4, 0xff, 0xd8, 0x10, } return byteCode
mit
Aico/mudlet
src/old_mudlet-lua/lua/LuaGlobal.lua
6
2911
---------------------------------------------------------------------------------- --- Mudlet Lua packages loader ---------------------------------------------------------------------------------- if package.loaded["rex_pcre"] then rex = require "rex_pcre" end if package.loaded["lpeg"] then lpeg = require "lpeg" end if package.loaded["zip"] then zip = require "zip" end if package.loaded["lfs"] then lfs = require "lfs" end -- TODO this is required by DB.lua, so we might load it all at one place --if package.loaded["luasql.sqlite3"] then require "luasql.sqlite3" end json_to_value = yajl.to_value gmcp = {} function __gmcp_merge_gmcp_sub_tables( a, key ) local _m = a.__needMerge; for k,v in pairs(_m) do a[key][k] = v; end a.__needMerge = nil end function unzip( what, dest ) cecho("\n<blue>unpacking package:<"..what.."< to <"..dest..">\n") local z, err = zip.open( what ) if not z then cecho("\nerror unpacking: "..err) return end local createdDirs = {} for file in z:files() do local _f, err = z:open( file.filename ) local _data = _f:read("*a") local _path = dest .. file.filename local _dir = string.split( file.filename, '/' ) local created = dest; for k,v in ipairs( _dir ) do if k < # _dir then created = created .. '/'.. v; if not table.contains( createdDirs, created ) then table.insert( createdDirs, created ); lfs.mkdir( created ); cecho("<red>--> creating dir:" .. created .. "\n"); end elseif file.uncompressed_size == 0 then if not table.contains( createdDirs, created ) then cecho("<red>--> creating dir:" .. file.filename .. "\n") table.insert( createdDirs, created ); lfs.mkdir( file.filename ) end end end local _path = dest .. file.filename if file.uncompressed_size > 0 then local out = io.open( _path, "wb" ) if out then cecho("<green>unpacking file:".._path.."\n") out:write( _data ) out:close() else echo("ERROR: can't write file:".._path.."\n") end end _f:close(); end z:close() end function onConnect() end function handleWindowResizeEvent() end local packages = { "StringUtils.lua", "TableUtils.lua", "Logging.lua", "DebugTools.lua", "DB.lua", "geyser/Geyser.lua", "geyser/GeyserGeyser.lua", "geyser/GeyserUtil.lua", "geyser/GeyserColor.lua", "geyser/GeyserSetConstraints.lua", "geyser/GeyserContainer.lua", "geyser/GeyserWindow.lua", "geyser/GeyserLabel.lua", "geyser/GeyserGauge.lua", "geyser/GeyserMiniConsole.lua", "geyser/GeyserMapper.lua", "geyser/GeyserReposition.lua", "geyser/GeyserHBox.lua", "geyser/GeyserVBox.lua", -- TODO probably don't need to load this file "geyser/GeyserTests.lua", "GUIUtils.lua", "Other.lua", "GMCP.lua", } for _, package in ipairs(packages) do local result = pcall(dofile, "./mudlet-lua/lua/" .. package) or echo("Error attempting to load file: " .. package .. "\n") end
gpl-2.0
adonaac/yaoui
yaoui/dialogs/winapi/comdlg.lua
4
1860
--proc/comdlg: common dialogs --Written by Cosmin Apreutesei. Public Domain. local yui_path = (...):match('(.-)[^%.]+$') setfenv(1, require(yui_path:sub(1, -2))) require(yui_path .. 'winuser') comdlg = ffi.load'comdlg32' COMMDLG_ERROR_NAMES = constants{ CDERR_DIALOGFAILURE = 0xFFFF, CDERR_GENERALCODES = 0x0000, CDERR_STRUCTSIZE = 0x0001, CDERR_INITIALIZATION = 0x0002, CDERR_NOTEMPLATE = 0x0003, CDERR_NOHINSTANCE = 0x0004, CDERR_LOADSTRFAILURE = 0x0005, CDERR_FINDRESFAILURE = 0x0006, CDERR_LOADRESFAILURE = 0x0007, CDERR_LOCKRESFAILURE = 0x0008, CDERR_MEMALLOCFAILURE = 0x0009, CDERR_MEMLOCKFAILURE = 0x000A, CDERR_NOHOOK = 0x000B, CDERR_REGISTERMSGFAIL = 0x000C, PDERR_PRINTERCODES = 0x1000, PDERR_SETUPFAILURE = 0x1001, PDERR_PARSEFAILURE = 0x1002, PDERR_RETDEFFAILURE = 0x1003, PDERR_LOADDRVFAILURE = 0x1004, PDERR_GETDEVMODEFAIL = 0x1005, PDERR_INITFAILURE = 0x1006, PDERR_NODEVICES = 0x1007, PDERR_NODEFAULTPRN = 0x1008, PDERR_DNDMMISMATCH = 0x1009, PDERR_CREATEICFAILURE = 0x100A, PDERR_PRINTERNOTFOUND = 0x100B, PDERR_DEFAULTDIFFERENT = 0x100C, CFERR_CHOOSEFONTCODES = 0x2000, CFERR_NOFONTS = 0x2001, CFERR_MAXLESSTHANMIN = 0x2002, FNERR_FILENAMECODES = 0x3000, FNERR_SUBCLASSFAILURE = 0x3001, FNERR_INVALIDFILENAME = 0x3002, FNERR_BUFFERTOOSMALL = 0x3003, FRERR_FINDREPLACECODES = 0x4000, FRERR_BUFFERLENGTHZERO = 0x4001, CCERR_CHOOSECOLORCODES = 0x5000, } ffi.cdef[[ DWORD CommDlgExtendedError(void); ]] CommDlgExtendedError = comdlg.CommDlgExtendedError function checkcomdlg(ret) if ret == 0 then local err = CommDlgExtendedError() assert(err == 0, 'comdlg32 error: %s', COMMDLG_ERROR_NAMES[err]) return false --user canceled end return true end
mit
adonaac/yaoui
examples/anime/yaoui/dialogs/winapi/comdlg.lua
4
1860
--proc/comdlg: common dialogs --Written by Cosmin Apreutesei. Public Domain. local yui_path = (...):match('(.-)[^%.]+$') setfenv(1, require(yui_path:sub(1, -2))) require(yui_path .. 'winuser') comdlg = ffi.load'comdlg32' COMMDLG_ERROR_NAMES = constants{ CDERR_DIALOGFAILURE = 0xFFFF, CDERR_GENERALCODES = 0x0000, CDERR_STRUCTSIZE = 0x0001, CDERR_INITIALIZATION = 0x0002, CDERR_NOTEMPLATE = 0x0003, CDERR_NOHINSTANCE = 0x0004, CDERR_LOADSTRFAILURE = 0x0005, CDERR_FINDRESFAILURE = 0x0006, CDERR_LOADRESFAILURE = 0x0007, CDERR_LOCKRESFAILURE = 0x0008, CDERR_MEMALLOCFAILURE = 0x0009, CDERR_MEMLOCKFAILURE = 0x000A, CDERR_NOHOOK = 0x000B, CDERR_REGISTERMSGFAIL = 0x000C, PDERR_PRINTERCODES = 0x1000, PDERR_SETUPFAILURE = 0x1001, PDERR_PARSEFAILURE = 0x1002, PDERR_RETDEFFAILURE = 0x1003, PDERR_LOADDRVFAILURE = 0x1004, PDERR_GETDEVMODEFAIL = 0x1005, PDERR_INITFAILURE = 0x1006, PDERR_NODEVICES = 0x1007, PDERR_NODEFAULTPRN = 0x1008, PDERR_DNDMMISMATCH = 0x1009, PDERR_CREATEICFAILURE = 0x100A, PDERR_PRINTERNOTFOUND = 0x100B, PDERR_DEFAULTDIFFERENT = 0x100C, CFERR_CHOOSEFONTCODES = 0x2000, CFERR_NOFONTS = 0x2001, CFERR_MAXLESSTHANMIN = 0x2002, FNERR_FILENAMECODES = 0x3000, FNERR_SUBCLASSFAILURE = 0x3001, FNERR_INVALIDFILENAME = 0x3002, FNERR_BUFFERTOOSMALL = 0x3003, FRERR_FINDREPLACECODES = 0x4000, FRERR_BUFFERLENGTHZERO = 0x4001, CCERR_CHOOSECOLORCODES = 0x5000, } ffi.cdef[[ DWORD CommDlgExtendedError(void); ]] CommDlgExtendedError = comdlg.CommDlgExtendedError function checkcomdlg(ret) if ret == 0 then local err = CommDlgExtendedError() assert(err == 0, 'comdlg32 error: %s', COMMDLG_ERROR_NAMES[err]) return false --user canceled end return true end
mit
chewi/Aquaria
files/scripts/maps/_unused/node_givealltreasures.lua
5
1210
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 v.done = false function init(me) v.n = getNaija() end function update(me, dt) if isDeveloperKeys() then if not v.done and node_isEntityIn(me, v.n) then debugLog("all treasures") for i = FLAG_COLLECTIBLE_START, (FLAG_COLLECTIBLE_END-1) do setFlag(i, 1) end v.done = true end end end
gpl-2.0
Chessnut/moderator
lua/moderator/commands/sh_teleport.lua
2
1409
local COMMAND = {} COMMAND.name = "Teleport" COMMAND.tip = "Teleports a player to your position." COMMAND.icon = "arrow_up" COMMAND.usage = "[bool toAimPos]" COMMAND.example = "!bring #alive 1 - Brings everyone to your aim position." COMMAND.aliases = {"bring"} function COMMAND:OnRun(client, arguments, target) local toAim = util.tobool(arguments[1] or false) local function Action(target) if (target:InVehicle()) then target:ExitVehicle() end target.modPos = target.modPos or target:GetPos() target:SetVelocity(Vector()) client.modTarget = target if (toAim) then target:SetPos(client:GetEyeTraceNoCursor().HitPos + Vector(0, 0, 4)) else local data = {} data.start = client:GetShootPos() + client:GetAimVector()*24 data.endpos = data.start + client:GetAimVector()*64 data.filter = client local trace = util.TraceLine(data) target:SetPos(trace.HitPos + Vector(0, 0, 4)) end end if (type(target) == "table") then for k, v in pairs(target) do Action(v) end else Action(target) end moderator.NotifyAction(client, target, "teleported * to their "..(toAim and "aim position" or "position")) end function COMMAND:OnClick(menu, client) menu:AddOption("To Me", function() self:Send(client) end) menu:AddOption("To Aim", function() self:Send(client, true) end) end moderator.commands.tp = COMMAND
gpl-2.0
squilter/ardupilot
libraries/AP_Scripting/examples/quadruped.lua
24
16202
-- Lua "motor driver" for a four legged (aka quadruped) walking robot -- -- This script consumes controller outputs (i.e. roll, pitch, yaw/steering, throttle, lateral) from -- the vehicle code and then calculates the outputs for 12 servos controlling four legs -- -- AutoPilot servo connections: -- Output1: front right coxa (hip) servo -- Output2: front right femur (thigh) servo -- Output3: front right tibia (shin) servo -- Output4: front left coxa (hip) servo -- Output5: front left femur (thigh) servo -- Output6: front left tibia (shin) servo -- Output7: back left coxa (hip) servo -- Output8: back left femur (thigh) servo -- Output9: back left tibia (shin) servo -- Output10: back right coxa (hip) servo -- Output11: back right femur (thigh) servo -- Output12: back right tibia (shin) servo -- -- CAUTION: This script should only be used with ArduPilot Rover's firmware local FRAME_LEN = 80 -- frame length in mm local FRAME_WIDTH = 150 -- frame width in mm local COXA_LEN = 30 -- distance (in mm) from coxa (aka hip) servo to femur servo local FEMUR_LEN = 85 -- distance (in mm) from femur servo to tibia servo local TIBIA_LEN = 125 -- distance (in mm) from tibia servo to foot --body position and rotation parameters local body_rot_max = 10 -- body rotation maximum for any individual axis local body_rot_x = 0 -- body rotation about the X axis (i.e. roll rotation) local body_rot_y = 0 -- body rotation about the Y axis (i.e. pitch rotation) local body_rot_z = 0 -- body rotation about the Z axis (i.e. yaw rotation) local body_pos_x = 0 -- body position in the X axis (i.e. forward, back). should be -40mm to +40mm local body_pos_y = 0 -- body position in the Y axis (i.e. right, left). should be -40mm to +40mm local body_pos_z = 0 -- body position in the Z axis (i.e. up, down). should be -40mm to +40mm -- starting positions of the legs local endpoint_LB = {math.cos(math.rad(45))*(COXA_LEN + FEMUR_LEN), math.sin(math.rad(45))*(COXA_LEN + FEMUR_LEN), TIBIA_LEN} local endpoint_LF = {math.cos(math.rad(45))*(COXA_LEN + FEMUR_LEN), math.sin(math.rad(-45))*(COXA_LEN + FEMUR_LEN), TIBIA_LEN} local endpoint_RF = {-math.cos(math.rad(45))*(COXA_LEN + FEMUR_LEN), math.sin(math.rad(-45))*(COXA_LEN + FEMUR_LEN), TIBIA_LEN} local endpoint_RB = {-math.cos(math.rad(45))*(COXA_LEN + FEMUR_LEN), math.sin(math.rad(45))*(COXA_LEN + FEMUR_LEN), TIBIA_LEN} -- control input enum local control_input_roll = 1 local control_input_pitch = 2 local control_input_throttle = 3 local control_input_yaw = 4 local control_input_height = 8 local xy_travel_max = 80 -- x and y axis travel max (used to convert control input) in mm local yaw_travel_max = 10 -- yaw travel maximum (used to convert control input) local height_max = 40 -- height maximum (used to convert control input) local travel_dz = 5 -- travel deadzone. x, y and yaw travel requests are ignored if their absolute value is less than this number local x_travel = 0 -- target lenght of gait along x local y_travel = 0 -- target travel of gait along y local yaw_travel = 0 -- yaw rotation travel target local leg_lift_height = 50 -- leg lift height (in mm) while walking -- gait definition parameters local gait_type = 0 -- gait pattern. 0 = alternating gait, 1 = wave gait. local gait_step = 0 -- gait step in execution local gait_step_total = 0 -- number of steps in gait local gait_step_leg_start = {0,0,0,0} -- leg starts moving on this gait step (front-right, front-left, back-left, back-right) local gait_lifted_steps = 0 -- number of steps that a leg is lifted for local gait_down_steps = 0 -- number of steps that the leg lifted needs to be put down for local gait_lift_divisor = 0 -- when a leg is lifted and brought back down the action is divided into 2 or multiple steps, so the travel distance also need to be split in between the steps to make the transition natural local gait_half_lift_height = 0 -- used to split lift across two steps local gait_travel_divisor = 0 -- number of steps in the gait the leg is touching the floor, this is used as a factor to split the travel distance between the steps local gait_pos_x = {0,0,0,0} -- X-axis position for each leg (back-right, front-right, back-left, front-left) local gait_pos_y = {0,0,0,0} -- Y-axis position for each leg (back-right, front-right, back-left, front-left) local gait_pos_z = {0,0,0,0} -- Z-axis position for each leg (back-right, front-right, back-left, front-left) local gait_rot_z = {0,0,0,0} -- Z-axis rotation for each leg (back-right, front-right, back-left, front-left) local last_angle = {0,0,0,0,0,0,0,0,0,0,0,0} local start_time = 0 local curr_target = 0 function Gaitselect() if (gait_type == 0) then -- alternating gait gait_step_total = 6 gait_step_leg_start = {1,4,4,1} gait_lifted_steps = 2 gait_down_steps = 1 gait_lift_divisor = 2 gait_half_lift_height = 1 gait_travel_divisor = 4 elseif (gait_type == 1) then -- wave gait with 28 steps gait_step_total = 28 gait_step_leg_start = {8,15,1,22} gait_lifted_steps = 3 gait_down_steps = 2 gait_lift_divisor = 2 gait_half_lift_height = 3 gait_travel_divisor = 24 end end -- Calculate Gait sequence function calc_gait_sequence() local move_requested = (math.abs(x_travel) > travel_dz) or (math.abs(y_travel) > travel_dz) or (math.abs(yaw_travel) > travel_dz) if move_requested then for leg_index=1, 4 do update_leg(leg_index,move_requested) end gait_step = gait_step + 1 if (gait_step>gait_step_total) then gait_step = 1 end else gait_pos_x = {0,0,0,0} gait_pos_y = {0,0,0,0} gait_pos_z = {0,0,0,0} gait_rot_z = {0,0,0,0} end end -- in order for the robot to move forward it needs to move its legs in a -- specific order and this is repeated over and over to attain linear motion. when a -- specific leg number is passed the update_leg() produces the set of values for the -- given leg at that step, for each cycle of the gait each leg will move to a set -- distance which is decided by the x_travel, yaw_travel, y_travel function update_leg(moving_leg,move_requested) local leg_step = gait_step - gait_step_leg_start[moving_leg] if ((move_requested and (gait_lifted_steps > 0) and leg_step==0) or (not move_requested and leg_step==0 and ((gait_pos_x[moving_leg]>2) or (gait_pos_y[moving_leg]>2) or (gait_rot_z[moving_leg] >2)))) then gait_pos_x[moving_leg] = 0 gait_pos_z[moving_leg] = -leg_lift_height gait_pos_y[moving_leg] = 0 gait_rot_z[moving_leg] = 0 elseif (((gait_lifted_steps==2 and leg_step==0) or (gait_lifted_steps>=3 and (leg_step==-1 or leg_step==(gait_step_total-1)))) and move_requested) then gait_pos_x[moving_leg] = -x_travel/gait_lift_divisor gait_pos_z[moving_leg] = -3*leg_lift_height/(3+gait_half_lift_height) gait_pos_y[moving_leg] = -y_travel/gait_lift_divisor gait_rot_z[moving_leg] = -yaw_travel/gait_lift_divisor elseif ((gait_lifted_steps>=2) and (leg_step==1 or leg_step==-(gait_step_total-1)) and move_requested) then gait_pos_x[moving_leg] = x_travel/gait_lift_divisor gait_pos_z[moving_leg] = -3*leg_lift_height/(3+gait_half_lift_height) gait_pos_y[moving_leg] = y_travel/gait_lift_divisor gait_rot_z[moving_leg] = yaw_travel/gait_lift_divisor elseif (((gait_lifted_steps==5 and (leg_step==-2 ))) and move_requested) then gait_pos_x[moving_leg] = -x_travel * 0.5 gait_pos_z[moving_leg] = -leg_lift_height * 0.5 gait_pos_y[moving_leg] = -y_travel * 0.5 gait_rot_z[moving_leg] = -yaw_travel * 0.5 elseif ((gait_lifted_steps==5) and (leg_step==2 or leg_step==-(gait_step_total-2)) and move_requested) then gait_pos_x[moving_leg] = x_travel * 0.5 gait_pos_z[moving_leg] = -leg_lift_height * 0.5 gait_pos_y[moving_leg] = y_travel * 0.5 gait_rot_z[moving_leg] = yaw_travel * 0.5 elseif ((leg_step==gait_down_steps or leg_step==-(gait_step_total-gait_down_steps)) and gait_pos_y[moving_leg]<0) then gait_pos_x[moving_leg] = x_travel * 0.5 gait_pos_z[moving_leg] = 0 gait_pos_y[moving_leg] = y_travel * 0.5 gait_rot_z[moving_leg] = yaw_travel * 0.5 else gait_pos_x[moving_leg] = gait_pos_x[moving_leg] - (x_travel/gait_travel_divisor) gait_pos_z[moving_leg] = 0 gait_pos_y[moving_leg] = gait_pos_y[moving_leg] - (y_travel/gait_travel_divisor) gait_rot_z[moving_leg] = gait_rot_z[moving_leg] - (yaw_travel/gait_travel_divisor) end end -- Body Forward Kinematics calculates where each leg should be. -- inputs are -- a) body rotations: body_rot_x, body_rot_y, body_rot_z -- b) body position: body_pos_x, body_pos_y, body_pos_z -- c) offset of the center of body function body_forward_kinematics(X, Y, Z, Xdist, Ydist, Zrot) local totaldist_x = X + Xdist + body_pos_x local totaldist_y = Y + Ydist + body_pos_y local distBodyCenterFeet = math.sqrt(totaldist_x^2 + totaldist_y^2) local AngleBodyCenter = math.atan(totaldist_y, totaldist_x) local rolly = math.tan(math.rad(body_rot_y)) * totaldist_x local pitchy = math.tan(math.rad(body_rot_x)) * totaldist_y local ansx = math.cos(AngleBodyCenter + math.rad(body_rot_z+Zrot)) * distBodyCenterFeet - totaldist_x + body_pos_x local ansy = math.sin(AngleBodyCenter + math.rad(body_rot_z+Zrot)) * distBodyCenterFeet - totaldist_y + body_pos_y local ansz = rolly + pitchy + body_pos_z return {ansx, ansy, ansz} end -- Leg Inverse Kinematics calculates the angles for each servo of each joint using the output of the -- body_forward_kinematics() function which gives the origin of each leg on the body frame function leg_inverse_kinematics(x, y, z) local coxa = math.deg(math.atan(x, y)) local trueX = math.sqrt(x^2 + y^2) - COXA_LEN local im = math.sqrt(trueX^2 + z^2) local q1 = -math.atan(z, trueX) local d1 = FEMUR_LEN^2 - TIBIA_LEN^2 + im^2 local d2 = 2*FEMUR_LEN*im local q2 = math.acos(d1/d2) local femur = math.deg(q1+q2) d1 = FEMUR_LEN^2 - im^2 + TIBIA_LEN^2 d2 = 2*TIBIA_LEN*FEMUR_LEN local tibia = math.deg(math.acos(d1/d2)-math.rad(90)) return {coxa, -femur, -tibia} end -- checks if the servo has moved to its expected position function servo_estimate(current_angle) local target = 0 for j = 1, 12 do curr_target = math.abs(current_angle[j] - last_angle[j]) if curr_target > target then target = curr_target end end local target_time = target * (0.24/60) * 1000 return (millis() - start_time) > target_time end -- main_inverse_kinematics produces the inverse kinematic solution for each -- leg joint servo by taking into consideration the initial_pos, gait offset and the body inverse kinematic values. function main_inverse_kinematics() local ans_RB = body_forward_kinematics(endpoint_RB[1]+gait_pos_x[1], endpoint_RB[2]+gait_pos_y[1], endpoint_RB[3]+gait_pos_z[1], -FRAME_LEN*0.5, FRAME_WIDTH*0.5, gait_rot_z[1]) local angles_RB = leg_inverse_kinematics(endpoint_RB[1]+ans_RB[1]+gait_pos_x[1], endpoint_RB[2]+ans_RB[2]+gait_pos_y[1], endpoint_RB[3]+ans_RB[3]+gait_pos_z[1]) angles_RB[1] = 45 + angles_RB[1] local ans_RF = body_forward_kinematics(endpoint_RF[1]+gait_pos_x[2], endpoint_RF[2]+gait_pos_y[2], endpoint_RF[3]+gait_pos_z[2], -FRAME_LEN*0.5, -FRAME_WIDTH*0.5, gait_rot_z[2]) local angles_RF = leg_inverse_kinematics(endpoint_RF[1]-ans_RF[1]+gait_pos_x[2], endpoint_RF[2]-ans_RF[2]-gait_pos_y[2], endpoint_RF[3]+ans_RF[3]+gait_pos_z[2]) angles_RF[1] = 135 + angles_RF[1] local ans_LB = body_forward_kinematics(endpoint_LB[1]+gait_pos_x[3], endpoint_LB[2]+gait_pos_y[3], endpoint_LB[3]+gait_pos_z[3], FRAME_LEN*0.5, FRAME_WIDTH*0.5, gait_rot_z[3]) local angles_LB = leg_inverse_kinematics(endpoint_LB[1]+ans_LB[1]+gait_pos_x[3], endpoint_LB[2]+ans_LB[2]+gait_pos_y[3], endpoint_LB[3]+ans_LB[3]+gait_pos_z[3]) angles_LB[1] = -45 + angles_LB[1] local ans_LF = body_forward_kinematics(endpoint_LF[1]+gait_pos_x[4], endpoint_LF[2]+gait_pos_y[4], endpoint_LF[3]+gait_pos_z[4], FRAME_LEN*0.5, -FRAME_WIDTH*0.5, gait_rot_z[4]) local angles_LF = leg_inverse_kinematics(endpoint_LF[1]-ans_LF[1]+gait_pos_x[4], endpoint_LF[2]-ans_LF[2]-gait_pos_y[4], endpoint_LF[3]+ans_LF[3]+gait_pos_z[4]) angles_LF[1] = -135 + angles_LF[1] Gaitselect() local current_angle = {angles_RF[1],angles_RF[2],angles_RF[3], angles_LF[1],angles_LF[2],angles_LF[3], angles_LB[1],angles_LB[2],angles_LB[3], angles_RB[1],angles_RB[2],angles_RB[3]} if servo_estimate(current_angle) then start_time = millis() calc_gait_sequence() last_angle = current_angle end return current_angle end -- servo angles when robot is disarmed and resting body on the ground local rest_angles = { 45, -90, 40, -- front right leg (coxa, femur, tibia) -45, -90, 40, -- front left leg (coxa, femur, tibia) -45, -90, 40, -- back left leg (coxa, femur, tibia) 45, -90, 40} -- back right leg (coxa, femur, tibia) function update() local throttle = vehicle:get_control_output(control_input_throttle) * xy_travel_max local gait_direction if throttle > 0 then gait_direction = -1 y_travel = throttle elseif throttle < 0 then gait_direction = 1 y_travel = -throttle elseif throttle == 0 then gait_direction = 1 y_travel = 0 end yaw_travel = -vehicle:get_control_output(control_input_yaw) * yaw_travel_max body_rot_x = -vehicle:get_control_output(control_input_roll) * body_rot_max body_rot_y = -vehicle:get_control_output(control_input_pitch) * body_rot_max body_pos_z = vehicle:get_control_output(control_input_height) * height_max local servo_direction = { gait_direction * 1, -1, 1, -- front right leg (coxa, femur, tibia) gait_direction * 1, 1, -1, -- front left leg (coxa, femur, tibia) gait_direction * -1, -1, 1, -- back left leg (coxa, femur, tibia) gait_direction * -1, 1, -1} -- back right leg (coxa, femur, tibia) local angles if arming:is_armed() then angles = main_inverse_kinematics() else angles = rest_angles end for i = 1, 12 do SRV_Channels:set_output_pwm_chan_timeout(i-1, math.floor(((angles[i] * servo_direction[i] * 1000)/90) + 1500), 1000) end return update,10 end -- turn off rudder based arming/disarming param:set_and_save('ARMING_RUDDER', 0) gcs:send_text(0, "quadruped simulation") return update()
gpl-3.0
mamadtnt/bot
plugins/media.lua
376
1679
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
rickyHong/dptorchLib
feedback/fkdkaggle.lua
2
3769
------------------------------------------------------------------------ --[[ FKDKaggle ]]-- -- Feedback -- Prepares a kaggle submission -- Requires csvigo ------------------------------------------------------------------------ local FKDKaggle, parent = torch.class("dp.FKDKaggle", "dp.Feedback") FKDKaggle.isFKDKaggle = true FKDKaggle._submission_map = { ['left_eye_center_x'] = 1, ['left_eye_center_y'] = 2, ['right_eye_center_x'] = 3, ['right_eye_center_y'] = 4, ['left_eye_inner_corner_x'] = 5, ['left_eye_inner_corner_y'] = 6, ['left_eye_outer_corner_x'] = 7, ['left_eye_outer_corner_y'] = 8, ['right_eye_inner_corner_x'] = 9, ['right_eye_inner_corner_y'] = 10, ['right_eye_outer_corner_x'] = 11, ['right_eye_outer_corner_y'] = 12, ['left_eyebrow_inner_end_x'] = 13, ['left_eyebrow_inner_end_y'] = 14, ['left_eyebrow_outer_end_x'] = 15, ['left_eyebrow_outer_end_y'] = 16, ['right_eyebrow_inner_end_x'] = 17, ['right_eyebrow_inner_end_y'] = 18, ['right_eyebrow_outer_end_x'] = 19, ['right_eyebrow_outer_end_y'] = 20, ['nose_tip_x'] = 21, ['nose_tip_y'] = 22, ['mouth_left_corner_x'] = 23, ['mouth_left_corner_y'] = 24, ['mouth_right_corner_x'] = 25, ['mouth_right_corner_y'] = 26, ['mouth_center_top_lip_x'] = 27, ['mouth_center_top_lip_y'] = 28, ['mouth_center_bottom_lip_x'] = 29, ['mouth_center_bottom_lip_y'] = 30 } function FKDKaggle:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local args, submission, file_name, save_dir, name = xlua.unpack( {config}, 'FKDKaggle', 'Used to prepare a Kaggle Submission for the '.. 'Facial Keypoints Detection challenge', {arg='submission', type='table', req=true, help='sample submission table'}, {arg='file_name', type='string', req=true, help='name of file to save submission to'}, {arg='save_dir', type='string', default=dp.SAVE_DIR, help='defaults to dp.SAVE_DIR'}, {arg='name', type='string', default='FKDKaggle', help='name identifying Feedback in reports'} ) require 'csvigo' config.name = name self._save_dir = save_dir self._template = submission self._submission = {{submission[1][1],submission[1][4]}} self._file_name = file_name parent.__init(self, config) self._pixels = torch.range(0,97):float():view(1,1,98) self._output = torch.FloatTensor() self._keypoints = torch.FloatTensor() self._i = 2 self._path = paths.concat(self._save_dir, self._file_name) end function FKDKaggle:setup(config) parent.setup(self, config) self._mediator:subscribe("errorMinima", self, "errorMinima") end function FKDKaggle:_add(batch, output, carry, report) local target = batch:targets():forward('b') local act = output:forward('bwc', 'torch.FloatTensor') local pixels = self._pixels:expandAs(act) self._output:cmul(act, pixels) self._keypoints:sum(self._output, 3) for i=1,act:size(1) do local keypoint = self._keypoints[i]:select(2,1) local row = self._template[self._i] local imageId = tonumber(row[2]) assert(imageId == target[i]) while (imageId == target[i]) do row = self._template[self._i] if not row then break end imageId = tonumber(row[2]) local keypointName = row[3] self._submission[self._i] = { row[1], keypoint[self._submission_map[keypointName]] } self._i = self._i + 1 end end end function FKDKaggle:_reset() self._i = 2 end function FKDKaggle:errorMinima(found_minima) if found_minima then csvigo.save{path=self._path,data=self._submission,mode='raw'} end end
bsd-3-clause
tkdrob/Battle-Tag
Data/Script/Lua/Classes/UTGame.Ui.Basics.lua
1
3137
--[[-------------------------------------------------------------------------- -- -- File: UTGame.Ui.Basics.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: September 2, 2010 -- ------------------------------------------------------------------------------ -- -- Description: ... -- ----------------------------------------------------------------------------]] --[[ Dependencies ----------------------------------------------------------]] require "UI/UISelector" require "UTBasics" --[[ Class -----------------------------------------------------------------]] UTGame.Ui = UTGame.Ui or {} UTGame.Ui.Basics = UTClass(UISelector) require "UTGame.Ui.Basics.Principle" -- __ctor -------------------------------------------------------------------- function UTGame.Ui.Basics:__ctor(...) -- window settings self.uiWindow.title = l"menu05" self.uiWindow.icon = "base:video/uianimatedbutton_basics.avi" self.uiSelector.title = l"oth002" -- dedicated settings on the right side, self.uiBasics = {} self.headerText = {} local size = 0 for index, slide in ipairs(UTBasics.slides) do self.headerText[index] = index self.uiBasics[index] = self.uiWindows:AddComponent(UTGame.Ui.Basics.Principle:New(slide)) size = size + 1 end -- contents self:Reserve(size, false) for index, uiBasic in ipairs(self.uiBasics) do uiBasic.rectangle = self.uiWindows.clientRectangle uiBasic.rectangleBitmap = {-14 + uiBasic.rectangle[1],20 + uiBasic.rectangle[2],-14 + uiBasic.rectangle[1] + 400,20 + uiBasic.rectangle[2] + 231} uiBasic.rectangleText = {uiBasic.rectangle[1] + 16, uiBasic.rectangle[4] - 170, uiBasic.rectangle[3] - 16, uiBasic.rectangle[4]} uiBasic.title = UTBasics.slides[index].title uiBasic.visible = false local properties = { text = uiBasic.title, headerText = self.headerText[index] } local item = self:AddItem(properties) item.Action = function () if (self.uiActiveBasic ~= uiBasic) then self.uiActiveBasic.visible = false self.uiActiveBasic = uiBasic self.uiActiveBasic.visible = true end end end -- buttons, -- uiButton1: back self.uiButton1 = self:AddComponent(UIButton:New(), "uiButton1") self.uiButton1.rectangle = UIMenuWindow.buttonRectangles[1] self.uiButton1.text = l"but003" self.uiButton1.tip = l"tip006" self.uiButton1.OnAction = function (self) quartz.framework.audio.loadsound("base:audio/ui/back.wav") quartz.framework.audio.loadvolume(game.settings.audio["volume:sfx"]) quartz.framework.audio.playsound() game:PostStateChange("title") end self.index = 1 self:Scroll(0) end -- OnOpen -------------------------------------------------------------------- function UTGame.Ui.Basics:OnOpen() self.index = self.index or 1 self.uiActiveBasic = self.uiBasics[self.index] self.uiActiveBasic.visible = true end
mit
httpomid/TeleSeed
plugins/ingroup.lua
371
44212
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] local user_info = redis:hgetall('user:'..group_owner) if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") if user_info.username then return "Group onwer is @"..user_info.username.." ["..group_owner.."]" else return "Group owner is ["..group_owner..']' end end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
tkdrob/Battle-Tag
Packages/HostageSituation/Data/Script/Lua/UAHostageSituation.State.RoundLoop.lua
1
18979
--[[-------------------------------------------------------------------------- -- -- File: UAHostageSituation.State.RoundLoop.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: November 25, 2010 -- ------------------------------------------------------------------------------ -- -- Description: ... -- ----------------------------------------------------------------------------]] --[[ Dependencies ----------------------------------------------------------]] require "UTActivity.State.RoundLoop" require "UAHostageSituation.Ui.RoundLoop" --[[ Class -----------------------------------------------------------------]] UAHostageSituation.State.RoundLoop = UTClass(UTActivity.State.RoundLoop) -- defaults ------------------------------------------------------------------ UAHostageSituation.State.RoundLoop.uiClass = UAHostageSituation.Ui.RoundLoop -- __ctor -------------------------------------------------------------------- function UAHostageSituation.State.RoundLoop:__ctor(activity, ...) -- timer self.time = quartz.system.time.gettimemicroseconds() activity.timer = 0 assert(activity) end -- Begin --------------------------------------------------------------------- function UAHostageSituation.State.RoundLoop:Begin() UTActivity.State.RoundLoop.Begin(self) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_13.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_14.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_15.wav"}, probas = {0.8, 0.1, 0.1}}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_32.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_33.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_34.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_35.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_125.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_126.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_132.wav",}, priority = 4 }) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_45.wav"},offset = activity.settings.playtime * 60 - 60,}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"}, offset = activity.settings.playtime * 60 - 57, priority = 3, proba = 0.333}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_46.wav"}, offset = activity.settings.playtime * 60 - 30,}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"}, offset = activity.settings.playtime * 60 - 27,priority = 3, proba = 0.333}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_47.wav"}, offset = activity.settings.playtime * 60 - 15,}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"}, offset = activity.settings.playtime * 60 - 12, priority = 3, proba = 0.333}) -- timer self.time = quartz.system.time.gettimemicroseconds() self.shootCount = 0 self.shootCountTime = self.time activity.timer = activity.settings.playtime * 60 * 1000000 game.gameplayData = { 0x00, 0x00 } activity.controllingteam = activity.match.challengers[activity.settings.defendingteam] activity.controllingteam.data.heap.score = 1 activity.controllingplayer = nil end -- Message received from device ----------------------------------------------------------------------- function UAHostageSituation.State.RoundLoop:OnDispatchMessage(device, addressee, command, arg) -- base UTActivity.State.RoundLoop.OnDispatchMessage(self) if (0x95 == command) then -- decode this msg !! local gunseconds = (arg[8] * 256) + arg[9] if (gunseconds ~= device.owner.data.heap.gunseconds or gunseconds == 0 or device.owner.data.heap.lifePoints == 0) then device.owner.data.heap.guntime = quartz.system.time.gettimemicroseconds() device.owner.vestconnect = false if (gunseconds == 0) then device.owner.gameplayData[2] = 0 end elseif (device.owner.data.heap.guntime + 5000000 < quartz.system.time.gettimemicroseconds() and game.settings.GameSettings.vestdisconnect == 0 and not device.timedout) then if (device.owner.gameplayData[2] == 1) then device.owner.team.data.heap.flagstolen = false activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame066", device.owner.team.profiles[device.owner.team.index].teamcolor, "base:texture/Ui/Icons/16x/FlagIcon" .. device.owner.team.index .. ".tga") end device.owner.gameplayData[2] = 7 end if (device.owner.data.heap.guntime + 1000000 < quartz.system.time.gettimemicroseconds()) then device.owner.vestconnect = true end if (device.owner.secondary) then if (device.owner.data.heap.guntime + 900000 < quartz.system.time.gettimemicroseconds() or device.owner.data.heap.lifePoints == 0) then device.owner.secondary.gameplayData[2] = 7 elseif (device.owner.gameplayData[2] ~= 7) then device.owner.secondary.gameplayData[2] = 6 end end device.owner.data.heap.gunseconds = gunseconds if (device.rejoin) then if ((arg[2] * 256) + arg[3] > 0) then device.rejoin = false end end if (device.owner and not device.rejoin) then -- ammunitions and clip local ammunitions = (arg[4] * 256) + arg[5] if (ammunitions == 3) then if (game.settings.audio.gmtalkative == 1) then -- throw "We need Ammo! Now" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_22.wav","base:audio/gamemaster/DLG_GM_GLOBAL_23.wav"},priority = 3,}) end end local clips = (arg[6] * 256) + arg[7] if (0 == device.owner.data.heap.isDead) then if (activity.settings.ammunitions < 255 and (device.owner.data.heap.ammunitions < ammunitions and device.owner.data.heap.clips <= clips or device.owner.data.heap.clips < clips)) then device.owner.data.heap.nbAmmoPack = device.owner.data.heap.nbAmmoPack + 1 activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame006", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Ammunition.tga") elseif (device.owner.data.heap.ammunitions > ammunitions) then device.owner.data.heap.nbShot = device.owner.data.heap.nbShot + (device.owner.data.heap.ammunitions - ammunitions) device.owner.data.heap.hitLost = device.owner.data.heap.hitLost + 1 if (device.owner.data.heap.hitLost == 5) then if (game.settings.audio.gmtalkative == 1) then -- throw "T'es aveugle" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_43.wav","base:audio/gamemaster/DLG_GM_GLOBAL_44.wav"},priority = 2,}) end device.owner.data.heap.hitLost = 0 end if (device.owner.data.heap.hitLost >= 2) then device.owner.data.nbHitLastPlayerShooted = 0 end end end device.owner.data.heap.clips = clips device.owner.data.heap.ammunitions = ammunitions if (activity.settings.ammunitions == 255) then device.owner.data.heap.ammunitionsAndClips = "-/-" else device.owner.data.heap.ammunitionsAndClips = device.owner.data.heap.ammunitions .. "/" .. device.owner.data.heap.clips end -- data local lifePoints = (arg[2] * 256) + arg[3] if (device.owner.primary) then lifePoints = device.owner.primary.data.heap.lifePoints end local lastBaseScanned = (arg[10] * 256) + arg[11] if (lifePoints == 1) then if (game.settings.audio.gmtalkative == 1) then -- throw "Mediiiic!" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_18.wav","base:audio/gamemaster/DLG_GM_GLOBAL_19.wav"},priority = 3,}) end end -- check if I have been shot ... if (device.owner.data.heap.lifePoints > lifePoints) then if (self.shootCount) then self.shootCount = self.shootCount + 1 if (self.shootCount == 10) then local time = quartz.system.time.gettimemicroseconds() if (time - self.shootCountTime < 10 * 1000000) then if (game.settings.audio.gmtalkative == 1) then -- ouais jsuis a donf game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_24.wav","base:audio/gamemaster/DLG_GM_GLOBAL_25.wav",}, priority = 2, proba = 0.25}) end end self.shootCountTime = time self.shootCount = 0 end end end local curIndex = math.max(0, device.owner.data.heap.lifePoints - lifePoints) while (curIndex > 0) do device.owner.data.heap.timeshit = device.owner.data.heap.timeshit + 1 -- get device that shot me local shooterDevice = engine.libraries.usb.proxy.devices.byRadioProtocolId[arg[math.min(16, curIndex + 11)]] curIndex = curIndex - 1 if (shooterDevice and shooterDevice.owner and shooterDevice.owner.primary ~= device.owner and device.owner.primary ~= shooterDevice.owner) then -- get shooter local shooter = shooterDevice.owner if (shooterDevice.owner.primary) then shooter = shooterDevice.owner.primary end if (0 == lifePoints and curIndex == 0) then -- KILL ------------------------------------------------------ if (shooter.team ~= device.owner.team) then activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame011" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Death.tga") shooter.data.heap.death = shooter.data.heap.death + 1 shooter.data.heap.killByName[device.owner.nameId] = (shooter.data.heap.killByName[device.owner.nameId] or 0) + 1 if (game.settings.audio.gmtalkative == 1) then -- throw "Dans le mille!" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_27.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_28.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_37.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_38.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_128.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_129.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_130.wav", }, priority = 2,}) end elseif (activity.settings.teamFrag == 1) then activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame011" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Death" .. shooter.team.profiles[shooter.team.index].teamColor .. ".tga" ) shooter.data.heap.death = shooter.data.heap.death + 1 shooter.data.heap.killByName[device.owner.nameId] = (shooter.data.heap.killByName[device.owner.nameId] or 0) + 1 game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_41.wav","base:audio/gamemaster/DLG_GM_GLOBAL_42.wav"}, priority = 2,}) end -- person with the flag is dead if (device.owner.gameplayData[2] == 1) then device.owner.team.data.heap.flagstolen = false end device.owner.gameplayData[2] = 0 device.owner.data.heap.isDead = 1 device.owner.team.data.heap.nbteamPlayerAlive = device.owner.team.data.heap.nbteamPlayerAlive - 1 if (activity.settings.endgamemode == 1 and device.owner.team.data.heap.nbteamPlayerAlive == 0) then device.owner.team.data.heap.endgametimer = activity.timer end else -- HIT ------------------------------------------------------ if (shooter.data.heap.lastPlayerShooted == device.owner) then shooter.data.heap.nbHitLastPlayerShooted = shooter.data.heap.nbHitLastPlayerShooted + 1 if (shooter.data.heap.nbHitLastPlayerShooted == 3) then if (game.settings.audio.gmtalkative == 1) then -- throw "Tireur d'�lite" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_26.wav",}, priority = 3, proba = 0.33}) end shooter.data.heap.nbHitLastPlayerShooted = 0 end else shooter.data.heap.nbHitLastPlayerShooted = 1 shooter.data.heap.lastPlayerShooted = device.owner end shooter.data.heap.hitLost = 0 if (shooter.team ~= device.owner.team) then activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame009" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Hit.tga") shooter.data.heap.hitByName[device.owner.nameId] = (shooter.data.heap.hitByName[device.owner.nameId] or 0) + 1 shooter.data.heap.hit = shooter.data.heap.hit + 1 elseif (activity.settings.teamFrag == 1) then -- throw "teammateshoot" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_41.wav","base:audio/gamemaster/DLG_GM_GLOBAL_42.wav"}, priority = 2,}) activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame009" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Hit" .. shooter.team.profiles[shooter.team.index].teamColor .. ".tga" ) shooter.data.heap.hitByName[device.owner.nameId] = (shooter.data.heap.hitByName[device.owner.nameId] or 0) + 1 shooter.data.heap.hit = shooter.data.heap.hit + 1 end end end if (activity.settings.lives >= 1) then if (device.owner.data.heap.nbRespawn == activity.settings.lives - 1) then if (0 == lifePoints) then -- This player is out device.owner.data.heap.icon = string.sub(device.owner.data.heap.icon, 0, #device.owner.data.heap.icon - 4) device.owner.data.heap.icon = device.owner.data.heap.icon .. "_Out.tga" device.owner.team.data.heap.nbPlayerAlive = device.owner.team.data.heap.nbPlayerAlive - 1 -- only one player left in this team if (device.owner.team.data.heap.nbPlayerAlive == 1) then local curTeam = {"DLG_GM_LAST_TEAM_02.wav", "DLG_GM_LAST_TEAM_05.wav" } game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/" .. curTeam[device.owner.team.index],}, priority = 1,}) elseif (device.owner.team.data.heap.nbPlayerAlive == 2) then local curTeam = {"DLG_GM_LAST_TEAM_07.wav", "DLG_GM_LAST_TEAM_10.wav" } game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/" .. curTeam[device.owner.team.index],}, priority = 1,}) elseif (device.owner.team.data.heap.nbPlayerAlive > 0) then game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_LAST_TEAM_01.wav",}, priority = 1,}) end end end -- check end of game if (device.owner.team.data.heap.nbPlayerAlive == 0) then activity:PostStateChange("endround") end end end -- back to life or medkit ! if (device.owner.data.heap.lifePoints < lifePoints) then if (1 == device.owner.data.heap.isDead or game.settings.addons.medkitPack == 0) then device.owner.data.heap.nbRespawn = device.owner.data.heap.nbRespawn + 1 device.owner.team.data.heap.endgametimer = 0 activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame014", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Respawn" .. device.owner.team.profiles[device.owner.team.index].teamColor .. ".tga") if (1 == device.owner.data.heap.isDead) then device.owner.team.data.heap.nbteamPlayerAlive = device.owner.team.data.heap.nbteamPlayerAlive + 1 end device.owner.data.heap.isDead = 0 if (game.settings.audio.gmtalkative == 1) then -- throw "De retour" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_36.wav"}, priority = 2,}) end else device.owner.data.heap.nbMediKit = device.owner.data.heap.nbMediKit + 1 activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame012", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Heart.tga") if (game.settings.audio.gmtalkative == 1) then -- throw "�a va mieux?" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_16.wav","base:audio/gamemaster/DLG_GM_GLOBAL_17.wav"}, priority = 2,}) end end end -- store life points device.owner.data.heap.lifePoints = lifePoints if (lastBaseScanned == 2 and not device.owner.team.data.heap.flagstolen and device.owner.team ~= activity.controllingteam and not device.owner.primary) then device.owner.gameplayData[2] = 1 device.owner.team.data.heap.flagstolen = true activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame064", teamcolor, "base:texture/Ui/Icons/16x/FlagIcon" .. device.owner.team.index .. ".tga") if (device.owner.team.index == activity.settings.defendingteam) then --game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_HOSTAGE_SITUATION_02.wav"}}) else game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_HOSTAGE_SITUATION_01.wav"}}) end end if (lastBaseScanned == device.owner.team.index - 1 and device.owner.gameplayData[2] == 1 or (activity.controllingteam.data.heap.endgametimer >= activity.timer + (activity.settings.respawnTime + 10) * 1000000 and activity.controllingteam ~= device.owner.team)) then device.owner.gameplayData[2] = 2 device.owner.team.data.heap.flagstolen = false activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame050", teamcolor, "base:texture/Ui/Icons/16x/FlagIcon" .. device.owner.team.index .. ".tga") device.owner.team.data.heap.score = 1 activity.controllingteam.data.heap.score = 0 activity.controllingplayer = device.owner activity.controllingteam = device.owner.team if (lastBaseScanned == device.owner.team.index - 1 and device.owner.gameplayData[2] == 2) then --game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_HOSTAGE_SITUATION_03.wav"}}) if (activity.settings.timeleft ~= -1) then activity.timer = activity.settings.timeleft * 1000000 end end end end end end function UAHostageSituation.State.RoundLoop:Update() UTActivity.State.RoundLoop.Update(self) -- end match if (activity.timer <= 0) then activity:PostStateChange("endround") end end
mit
futesobriquet/Tower_D_beta
Tower_Beta/lib/30log/specs/mixin.lua
1
1313
require 'luacov' local Class = require '30log' context('Mixins', function() test('are set of functions that can be imported into a class', function() local mixin = { foo = function() end, bar = function() end, baz = function() end } local theClass = Class() assert_nil(theClass.foo) assert_nil(theClass.bar) assert_nil(theClass.baz) theClass:include(mixin) assert_equal(type(theClass.foo), 'function') assert_equal(type(theClass.bar), 'function') assert_equal(type(theClass.baz), 'function') end) test('can be chained', function() local mixinA = {foo = function() end} local mixinB = {bar = function() end} local mixinC = {baz = function() end} local theClass = Class() theClass:include(mixinA):include(mixinB):include(mixinC) assert_equal(type(theClass.foo), 'function') assert_equal(type(theClass.bar), 'function') assert_equal(type(theClass.baz), 'function') end) test('objects can use methods from mixins as class methods', function() local mixin = {foo = function(self) return self end} local theClass = Class() theClass:include(mixin) local instance = theClass() assert_equal(instance:foo(), instance) end) end)
apache-2.0
milos-korenciak/heroku-buildpack-tex
buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/deprecated/Node.lua
3
6353
-- Copyright 2010 by Renée Ahrens, Olof Frahm, Jens Kluttig, Matthias Schulz, Stephan Schuster -- Copyright 2011 by Jannis Pohlmann -- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/deprecated/Node.lua,v 1.1 2012/11/27 17:24:25 tantau Exp $ --- The Node class -- -- local Node = {} Node.__index = Node -- Namespace local lib = require "pgf.gd.lib" -- Imports local Vector = require "pgf.gd.deprecated.Vector" --- Creates a new node. -- -- @param values Values to override default node settings. -- The following parameters can be set:\par -- |name|: The name of the node. It is obligatory to define this.\par -- |tex|: Information about the corresponding \TeX\ node.\par -- |edges|: Edges adjacent to the node.\par -- |pos|: Initial position of the node.\par -- |options|: A table of node options passed over from \tikzname. -- -- @return A newly allocated node. -- function Node.new(values) local new = { class = Node, name = nil, tex = { -- texNode = nil, -- maxX = nil, -- minX = nil, -- maxY = nil, -- minY = nil }, edges = {}, -- pos = nil, options = {}, -- growth_direction = nil, -- index = nil, -- event_index = nil, kind = "node", } setmetatable(new, Node) if values then for k,v in pairs(values) do new [k] = v end end if not new.pos then new.pos = Vector.new(2) end return new end --- Sets the node option \meta{name} to \meta{value}. -- -- @param name Name of the node option to be changed. -- @param value New value for the node option \meta{name}. -- function Node:setOption(name, value) self.options[name] = value end --- Returns the value of the node option \meta{name}. -- -- @param name Name of the node option. -- @param graph If this optional argument is given, -- in case the option is not set as a node parameter, -- we try to look it up as a graph parameter. -- -- @return The value of the node option \meta{name} or |nil|. -- function Node:getOption(name, graph) return lib.lookup_option(name, self, graph) end --- Computes the width of the node. -- -- @return Width of the node. -- function Node:getTexWidth() return math.abs(self.tex.maxX - self.tex.minX) end --- Computes the heigth of the node. -- -- @return Height of the node. -- function Node:getTexHeight() return math.abs(self.tex.maxY - self.tex.minY) end --- Adds new edge to the node. -- -- @param edge The edge to be added. -- function Node:addEdge(edge) table.insert(self.edges, edge) end --- Removes an edge from the node. -- -- @param edge The edge to remove. -- function Node:removeEdge(edge) self.edges = lib.imap (self.edges, function(other) if other ~= edge then return other end end) end --- Counts the adjacent edges of the node. -- -- @return The number of adjacent edges of the node. -- function Node:getDegree() return #self.edges end --- Returns all edges of the node. -- -- Instead of calling |node:getEdges()| the edges can alternatively be -- accessed directly with |node.edges|. -- -- @return All edges of the node. -- function Node:getEdges() return self.edges end --- Returns the incoming edges of the node. Undefined result for hyperedges. -- -- @param ignore_reversed Optional parameter to consider reversed edges not -- reversed for this method call. Defaults to |false|. -- -- @return Incoming edges of the node. This includes undirected edges -- and directed edges pointing to the node. -- function Node:getIncomingEdges(ignore_reversed) return lib.imap(self.edges, function (edge) if edge:isHead(self, ignore_reversed) then return edge end end) end --- Returns the outgoing edges of the node. Undefined result for hyperedges. -- -- @param ignore_reversed Optional parameter to consider reversed edges not -- reversed for this method call. Defaults to |false|. -- -- @return Outgoing edges of the node. This includes undirected edges -- and directed edges leaving the node. -- function Node:getOutgoingEdges(ignore_reversed) return lib.imap(self.edges, function (edge) if edge:isTail(self, ignore_reversed) then return edge end end) end --- Returns the number of incoming edges of the node. -- -- @see Node:getIncomingEdges(reversed) -- -- @param ignore_reversed Optional parameter to consider reversed edges not -- reversed for this method call. Defaults to |false|. -- -- @return The number of incoming edges of the node. -- function Node:getInDegree(ignore_reversed) return #self:getIncomingEdges(ignore_reversed) end --- Returns the number of edges starting at the node. -- -- @see Node:getOutgoingEdges() -- -- @param ignore_reversed Optional parameter to consider reversed edges not -- reversed for this method call. Defaults to |false|. -- -- @return The number of outgoing edges of the node. -- function Node:getOutDegree(ignore_reversed) return #self:getOutgoingEdges(ignore_reversed) end --- Creates a shallow copy of the node. -- -- Most notably, the edges adjacent are not preserved in the copy. -- -- @return Copy of the node. -- function Node:copy() local result = lib.copy(self, Node.new()) result.edges = {} return result end --- Compares two nodes by their name. -- -- @ignore This should not appear in the documentation. -- -- @param other Another node to compare with. -- -- @return |true| if both nodes have the same name. |false| otherwise. -- function Node:__eq(object) return self.name == object.name end --- Returns a formated string representation of the node. -- -- @ignore This should not appear in the documentation. -- -- @return String represenation of the node. -- function Node:__tostring() local tmp = Node.__tostring Node.__tostring = nil local result = "Node<" .. tostring(self) .. ">(" .. self.name .. ")" Node.__tostring = tmp return result end -- Done return Node
mit
chewi/Aquaria
files/scripts/maps/node_title_continue.lua
6
2104
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) node_setCursorActivation(me, true) node_setCatchActions(me, true) end function action(me, action, state) if isNestedMain() then return end if getNodeToActivate() == me and state == 1 then if action == ACTION_MENULEFT then local node = getNode("TITLE_NEWGAME") setNodeToActivate(node) setMousePos(toWindowFromWorld(node_x(node), node_y(node)-20)) return false elseif action == ACTION_MENURIGHT then local node = getNode("TITLE_QUIT") setNodeToActivate(node) setMousePos(toWindowFromWorld(node_x(node), node_y(node)-20)) return false elseif action == ACTION_MENUUP and not isDemo() then local node = getNode("TITLE_REPLAYINTRO") setNodeToActivate(node) setMousePos(toWindowFromWorld(node_x(node), node_y(node)-20)) return false end end return true end function activate(me) if isNestedMain() then return end playSfx("TitleAction") spawnParticleEffect("TitleEffect1", node_x(me), node_y(me)) watch(0.5) --[[ setNodeToActivate(0) ]]-- setActivation(false) doLoadMenu() setActivation(true) if getInputMode() ~= INPUT_MOUSE then setMousePos(toWindowFromWorld(node_x(me), node_y(me))) end end function update(me, dt) end
gpl-2.0
adonaac/yaoui
yaoui/ImageButton.lua
4
1952
local yui_path = (...):match('(.-)[^%.]+$') local Object = require(yui_path .. 'UI.classic.classic') local ImageButton = Object:extend('ImageButton') function ImageButton:new(yui, settings) self.yui = yui self.x, self.y = 0, 0 self.settings = settings self.ix, self.iy = settings.ix or 0, settings.iy or 0 self.rounded_corners = settings.rounded_corners self.name = settings.name self.img = settings.image self.w, self.h = settings.w or self.img:getWidth(), settings.h or self.img:getHeight() self.button = self.yui.UI.Button(0, 0, self.w, self.h, { yui = self.yui, extensions = {self.yui.Theme.ImageButton}, postDraw = self.yui.Theme.ImageButton.postDraw, parent = self, }) self.onClick = settings.onClick self.overlayNew = settings.overlayNew self.overlayUpdate = settings.overlayUpdate self.overlay = settings.overlay or function(self) love.graphics.setColor(50, 50, 50, self.alpha/3) if self.rounded_corners then love.graphics.rectangle('fill', self.x, self.y, self.w, self.h, self.h/18, self.h/18) else love.graphics.rectangle('fill', self.x, self.y, self.w, self.h) end love.graphics.setColor(255, 255, 255, 255) end self.alpha = 0 if self.overlayNew then self:overlayNew() end end function ImageButton:update(dt) self.ix, self.iy = self.settings.ix or 0, self.settings.iy or 0 if self.button.hot and self.button.released then if self.onClick then self:onClick() end end self.button.x, self.button.y = self.x, self.y self.button:update(dt) self.alpha = self.button.alpha if self.button.hot then love.mouse.setCursor(self.yui.Theme.hand_cursor) end if self.overlayUpdate then self:overlayUpdate(dt) end end function ImageButton:draw() self.button:draw() end function ImageButton:postDraw() self.button:postDraw() end return ImageButton
mit
chewi/Aquaria
files/scripts/entities/mutantnaija.lua
6
4573
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 v.head = 0 local STATE_SWIM = 1000 local STATE_BURST = 1001 v.burstDelay = 0 v.singDelay = 4 v.fireDelay = 3 v.fired = 0 v.fireShotDelay = 0 local function idle(me) entity_setState(me, STATE_IDLE, math.random(1)+0.5) end local function doBurstDelay() v.burstDelay = math.random(4) + 2 end function init(me) setupEntity(me) entity_setEntityType(me, ET_ENEMY) entity_initSkeletal(me, "Naija", "Mutant") --entity_setAllDamageTargets(me, false) entity_scale(me, 0.7, 0.7) entity_setCollideRadius(me, 20) entity_setHealth(me, 20) bone_alpha(entity_getBoneByName(me, "Fish2"),0) bone_alpha(entity_getBoneByName(me, "DualFormGlow"),0) v.head = entity_getBoneByName(me, "Head") entity_setDeathScene(me, true) idle(me) entity_setUpdateCull(me, 1300) loadSound("mutantnaija-note") loadSound("mutantnaija-note-hit") end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) end function update(me, dt) entity_updateMovement(me, dt) entity_handleShotCollisions(me) entity_setLookAtPoint(me, bone_getWorldPosition(v.head)) if entity_isState(me, STATE_IDLE) then entity_rotate(me, 0, 0.1) elseif entity_isState(me, STATE_SWIM) then entity_moveTowardsTarget(me, dt, 500) v.burstDelay = v.burstDelay - dt if v.burstDelay < 0 then doBurstDelay() entity_setMaxSpeedLerp(me, 2) entity_setMaxSpeedLerp(me, 1, 4) entity_moveTowardsTarget(me, 1, 1000) entity_animate(me, "burst", 0, 1) end entity_rotateToVel(me, 0.1) end entity_doEntityAvoidance(me, dt, 32, 0.5) entity_doCollisionAvoidance(me, dt, 4, 0.5) --[[ v.singDelay = v.singDelay - dt if v.singDelay < 0 then v.singDelay = math.random(3) + 3 entity_sound(me, getNoteName(math.random(8)), 1, 3) local x = entity_x(v.n) - entity_x(me) local y = entity_y(v.n) - entity_y(me) x, y = vector_setLength(x, y, 1000) entity_addVel(v.n, x, y) end ]]-- if entity_isState(me, STATE_SWIM) then if v.fired == -1 then v.fireDelay = v.fireDelay - dt if v.fireDelay < 0 then v.fired = 3 v.fireDelay = math.random(2) + 3 v.fireShotDelay = 0 end end end if v.fired > -1 then v.fireShotDelay = v.fireShotDelay - dt if v.fireShotDelay < 0 then local s = createShot("MutantNaija", me, v.n, bone_getWorldPosition(v.head)) v.fired = v.fired - 1 if v.fired == 0 then v.fired = -1 end v.fireShotDelay = 0.2 end end local thresh = 10 if entity_velx(me) > thresh and not entity_isfh(me) then entity_fh(me) end if entity_velx(me) < -thresh and entity_isfh(me) then entity_fh(me) end entity_touchAvatarDamage(me, 8, 1, 500) end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_animate(me, "idle", -1) elseif entity_isState(me, STATE_SWIM) then entity_animate(me, "swim", -1) elseif entity_isState(me, STATE_DEATHSCENE) then entity_setColor(me, 0.3, 0.3, 0.3, 1) entity_setPosition(me, entity_x(me), entity_y(me)+400, -300) entity_setStateTime(me, entity_animate(me, "diePainfully", 2)) entity_rotate(me, 0, 0.1) end end function exitState(me) if entity_isState(me, STATE_IDLE) then entity_rotate(me, 0, 0.1) entity_setState(me, STATE_SWIM, math.random(6)+4) elseif entity_isState(me, STATE_SWIM) then idle(me) doBurstDelay() elseif entity_isState(me, STATE_DEATHSCENE) then spawnParticleEffect("TinyBlueExplode", entity_getPosition(me)) end end function damage(me, attacker, bone, damageType, dmg) return true end function animationKey(me, key) end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
rickyHong/dptorchLib
data/notmnist.lua
3
6414
------------------------------------------------------------------------ --[[ NotMnist ]]-- -- http://yaroslavvb.blogspot.ca/2011/09/notmnist-dataset.html -- http://yaroslavvb.com/upload/notMNIST/ -- A 500k+ example alternative to MNIST using unicode fonts. ------------------------------------------------------------------------ local NotMnist, DataSource = torch.class("dp.NotMnist", "dp.DataSource") NotMnist.isNotMnist= true NotMnist._name = 'notMnist' NotMnist._image_size = {28, 28, 1} NotMnist._image_axes = 'bhwc' NotMnist._feature_size = 28*28*1 NotMnist._classes = {'A','B','C','D','E','F','G','H','I','J'} function NotMnist:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local load_all, input_preprocess, target_preprocess self._args, self._valid_ratio, self._train_dir, self._test_dir, self._data_path, self._scale, self._binarize, self._download_url, load_all, input_preprocess, target_preprocess = xlua.unpack( {config}, 'NotMnist', 'A 500k+ example alternative to MNIST using unicode fonts.', {arg='valid_ratio', type='number', default=1/6, help='proportion of training set to use for cross-validation.'}, {arg='train_dir', type='string', default='notMNIST_large', help='name of train_dir'}, {arg='test_dir', type='string', default='notMNIST_small', help='name of test_dir'}, {arg='data_path', type='string', default=dp.DATA_DIR, help='path to data repository'}, {arg='scale', type='table', help='bounds to scale the values between', default={0,1}}, {arg='binarize', type='boolean', help='binarize the inputs (0s and 1s)', default=false}, {arg='download_url', type='string', default='http://yaroslavvb.com/upload/notMNIST/', help='URL from which to download dataset if not found on disk.'}, {arg='load_all', type='boolean', help='Load all datasets : train, valid, test.', default=true}, {arg='input_preprocess', type='table | dp.Preprocess', help='to be performed on set inputs, measuring statistics ' .. '(fitting) on the train_set only, and reusing these to ' .. 'preprocess the valid_set and test_set.'}, {arg='target_preprocess', type='table | dp.Preprocess', help='to be performed on set targets, measuring statistics ' .. '(fitting) on the train_set only, and reusing these to ' .. 'preprocess the valid_set and test_set.'} ) if (self._scale == nil) then self._scale = {0,1} end if load_all then self:loadTrainValid() self:loadTest() end DataSource.__init(self, {train_set=self:trainSet(), valid_set=self:validSet(), test_set=self:testSet(), input_preprocess=input_preprocess, target_preprocess=target_preprocess}) end function NotMnist:loadTrainValid() local bad_png = { --these wont load as PNGs, ignore them ['A'] = { 'RnJlaWdodERpc3BCb29rSXRhbGljLnR0Zg==.png', 'Um9tYW5hIEJvbGQucGZi.png', 'SG90IE11c3RhcmQgQlROIFBvc3Rlci50dGY=.png' }, ['B'] = {'TmlraXNFRi1TZW1pQm9sZEl0YWxpYy5vdGY=.png'}, ['D'] = {'VHJhbnNpdCBCb2xkLnR0Zg==.png'} } local inputs, targets = self:loadData( self._train_dir, self._download_url, bad_png ) -- train local start = 1 local size = math.floor(inputs:size(1)*(1-self._valid_ratio)) self:setTrainSet( self:createDataSet( inputs:narrow(1, start, size), targets:narrow(1, start, size), 'train' ) ) -- valid start = size + 1 size = inputs:size(1) - start self:setValidSet( self:createDataSet( inputs:narrow(1, start, size), targets:narrow(1, start, size), 'valid' ) ) return self:trainSet(), self:validSet() end function NotMnist:loadTest() local bad_png = { ['A'] = {'RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png'}, ['F'] = {'Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png'} } local inputs, targets = self:loadData( self._test_dir, self._download_url, bad_png ) self:setTestSet(self:createDataSet(inputs, targets, 'test')) return self:testSet() end --Creates an NotMnist Dataset out of data and which_set function NotMnist:createDataSet(inputs, targets, which_set) if self._binarize then DataSource.binarize(inputs, 128) end if self._scale and not self._binarize then DataSource.rescale(inputs, self._scale[1], self._scale[2]) end -- construct inputs and targets dp.Views local input_v, target_v = dp.ImageView(), dp.ClassView() input_v:forward(self._image_axes, inputs) target_v:forward('b', targets) target_v:setClasses(self._classes) -- construct dataset return dp.DataSet{inputs=input_v,targets=target_v,which_set=which_set} end function NotMnist:loadData(file_name, download_url, bad_png) local doc_path = DataSource.getDataPath{ name=self._name, url=download_url..file_name..'.tar.gz', decompress_file=file_name, data_dir=self._data_path } local n_example = 0 local classes = self._classes for classidx, class in ipairs(classes) do local classpath = paths.concat(doc_path, class) for file in lfs.dir(classpath) do if #file > 2 and not _.contains(bad_png[class] or {}, file) then n_example = n_example + 1 else --print(class, file) end end end local inputs = torch.FloatTensor(n_example, unpack(self._image_size)) local targets = torch.Tensor(n_example) local shuffle = torch.randperm(n_example) --useless for test set local example_idx = 1 for classidx, class in ipairs(classes) do local classpath = paths.concat(doc_path, class) for file in lfs.dir(classpath) do if #file > 2 and not _.contains(bad_png[class] or {}, file) then local filename = paths.concat(classpath, file) local ds_idx = shuffle[example_idx] inputs[{ds_idx,{},{},{}}] = image.loadPNG(filename):float() targets[ds_idx] = classidx example_idx = example_idx + 1 end end end return inputs, targets end
bsd-3-clause
Meituan-Dianping/DBProxy
examples/tutorial-tokenize.lua
4
1591
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] local tokenizer = require("proxy.tokenizer") function read_query(packet) if packet:byte() == proxy.COM_QUERY then local tokens = tokenizer.tokenize(packet:sub(2)) -- just for debug for i = 1, #tokens do -- print the token and what we know about it local token = tokens[i] local txt = token["text"] if token["token_name"] == 'TK_STRING' then txt = string.format("%q", txt) end -- print(i .. ": " .. " { " .. token["token_name"] .. ", " .. token["text"] .. " }" ) print(i .. ": " .. " { " .. token["token_name"] .. ", " .. txt .. " }" ) end print("normalized query: " .. tokenizer.normalize(tokens)) print("") end end
gpl-2.0
Nottinghster/OTServ_SVN-0.6.4
src/data/actions/scripts/liquids/great_spirit.lua
2
1850
local HEALTH_REGEN = {200, 400} --min 200, max 400 local MANA_REGEN = {100, 200} --min 100, max 200 local EMPTY_POTION = 7635 local combatHealth = createCombatObject() setCombatParam(combatHealth, COMBAT_PARAM_TYPE, COMBAT_HEALING) setCombatParam(combatHealth, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) setCombatParam(combatHealth, COMBAT_PARAM_TARGETCASTERORTOPMOST, true) setCombatParam(combatHealth, COMBAT_PARAM_AGGRESSIVE, false) setCombatParam(combatHealth, COMBAT_PARAM_DISPEL, CONDITION_PARALYZE) setCombatFormula(combatHealth, COMBAT_FORMULA_DAMAGE, HEALTH_REGEN[1], 0, HEALTH_REGEN[2], 0) local combatMana = createCombatObject() setCombatParam(combatMana, COMBAT_PARAM_TYPE, COMBAT_MANADRAIN) setCombatParam(combatMana, COMBAT_PARAM_TARGETCASTERORTOPMOST, true) setCombatParam(combatMana, COMBAT_PARAM_AGGRESSIVE, false) setCombatFormula(combatMana, COMBAT_FORMULA_DAMAGE, MANA_REGEN[1], 0, MANA_REGEN[2], 0) local exhaust = createConditionObject(CONDITION_EXHAUST_POTION) setConditionParam(exhaust, CONDITION_PARAM_TICKS, getConfigInfo('minactionexinterval')) function onUse(cid, item, frompos, item2, topos) if(isPlayer(item2.uid) == false)then return false end if(hasCondition(cid, CONDITION_EXHAUST_POTION) ) then doPlayerSendDefaultCancel(cid, RETURNVALUE_YOUAREEXHAUSTED) return true end if (not(isPaladin(cid)) or (getPlayerLevel(cid) < 80)) and not(getPlayerAccess(cid) > 0) then doCreatureSay(cid, "Only paladins of level 80 or above may drink this fluid.", TALKTYPE_ORANGE_1) return true end local var = numberToVariant(item2.uid) if not doCombat(cid, combatHealth, var) or not doCombat(cid, combatMana, var) then return false end doAddCondition(cid, exhaust) doCreatureSay(item2.uid, "Aaaah...", TALKTYPE_ORANGE_1) doRemoveItem(item.uid, 1) doPlayerAddItem(cid, EMPTY_POTION, 1) return true end
gpl-2.0
comedinha/New-Poke-Lite
data/spells/scripts/party/heal.lua
13
1841
local combat = createCombatObject() local area = createCombatArea(AREA_CROSS5X5) setCombatArea(combat, area) setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, 0) local condition = createConditionObject(CONDITION_REGENERATION) setConditionParam(condition, CONDITION_PARAM_SUBID, 1) setConditionParam(condition, CONDITION_PARAM_BUFF_SPELL, 1) setConditionParam(condition, CONDITION_PARAM_TICKS, 2 * 60 * 1000) setConditionParam(condition, CONDITION_PARAM_HEALTHGAIN, 20) setConditionParam(condition, CONDITION_PARAM_HEALTHTICKS, 2000) local baseMana = 120 function onCastSpell(cid, var) local pos = getCreaturePosition(cid) local membersList = getPartyMembers(cid) if(membersList == nil or type(membersList) ~= 'table' or #membersList <= 1) then doPlayerSendCancel(cid, "No party members in range.") doSendMagicEffect(pos, CONST_ME_POFF) return false end local affectedList = {} for _, pid in ipairs(membersList) do if(getDistanceBetween(getCreaturePosition(pid), pos) <= 36) then table.insert(affectedList, pid) end end local tmp = #affectedList if(tmp <= 1) then doPlayerSendCancel(cid, "No party members in range.") doSendMagicEffect(pos, CONST_ME_POFF) return false end local mana = math.ceil((0.9 ^ (tmp - 1) * baseMana) * tmp) if(getPlayerMana(cid) < mana) then doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTENOUGHMANA) doSendMagicEffect(pos, CONST_ME_POFF) return false end if(doCombat(cid, combat, var) ~= true) then doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTPOSSIBLE) doSendMagicEffect(pos, CONST_ME_POFF) return false end doPlayerAddMana(cid, -(mana - baseMana), FALSE) doPlayerAddManaSpent(cid, (mana - baseMana)) for _, pid in ipairs(affectedList) do doAddCondition(pid, condition) end return true end
gpl-2.0
Fir3element/tfs11
data/spells/scripts/party/heal.lua
13
1841
local combat = createCombatObject() local area = createCombatArea(AREA_CROSS5X5) setCombatArea(combat, area) setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, 0) local condition = createConditionObject(CONDITION_REGENERATION) setConditionParam(condition, CONDITION_PARAM_SUBID, 1) setConditionParam(condition, CONDITION_PARAM_BUFF_SPELL, 1) setConditionParam(condition, CONDITION_PARAM_TICKS, 2 * 60 * 1000) setConditionParam(condition, CONDITION_PARAM_HEALTHGAIN, 20) setConditionParam(condition, CONDITION_PARAM_HEALTHTICKS, 2000) local baseMana = 120 function onCastSpell(cid, var) local pos = getCreaturePosition(cid) local membersList = getPartyMembers(cid) if(membersList == nil or type(membersList) ~= 'table' or #membersList <= 1) then doPlayerSendCancel(cid, "No party members in range.") doSendMagicEffect(pos, CONST_ME_POFF) return false end local affectedList = {} for _, pid in ipairs(membersList) do if(getDistanceBetween(getCreaturePosition(pid), pos) <= 36) then table.insert(affectedList, pid) end end local tmp = #affectedList if(tmp <= 1) then doPlayerSendCancel(cid, "No party members in range.") doSendMagicEffect(pos, CONST_ME_POFF) return false end local mana = math.ceil((0.9 ^ (tmp - 1) * baseMana) * tmp) if(getPlayerMana(cid) < mana) then doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTENOUGHMANA) doSendMagicEffect(pos, CONST_ME_POFF) return false end if(doCombat(cid, combat, var) ~= true) then doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTPOSSIBLE) doSendMagicEffect(pos, CONST_ME_POFF) return false end doPlayerAddMana(cid, -(mana - baseMana), FALSE) doPlayerAddManaSpent(cid, (mana - baseMana)) for _, pid in ipairs(affectedList) do doAddCondition(pid, condition) end return true end
gpl-2.0
dunn/ntopng
scripts/lua/get_filter_host.lua
4
6226
-- -- (C) 2013-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" sendHTTPHeader('text/html; charset=iso-8859-1') -- Table parameters all = _GET["all"] host = _GET["host"] vlan = _GET["vlan"] key = _GET["key"] -- table_id = _GET["table"] if (vlan == nil) then vlan = 0 end if((sortColumn == nil) or (sortColumn == "column_")) then sortColumn = getDefaultTableSort("http_hosts") else if((sortColumn ~= "column_") and (sortColumn ~= "")) then tablePreferences("sort_http_hosts", sortColumn) end end --io.write(sortColumn.."\n") if(sortOrder == nil) then sortOrder = getDefaultTableSortOrder("http_hosts") else if(sortColumn ~= "column_") and (sortColumn ~= "")) then tablePreferences("sort_order_http_hosts",sortOrder) end end if(currentPage == nil) then currentPage = 1 else currentPage = tonumber(currentPage) end if(perPage == nil) then perPage = getDefaultTableSize() else perPage = tonumber(perPage) tablePreferences("rows_number",perPage) end interface.select(ifname) hosts_stats = interface.listHTTPhosts(nil) if (host == nil) then flows_stats = interface.queryFlowsInfo("SELECT * FROM FLOWS") else flows_stats = interface.queryFlowsInfo("SELECT * FROM FLOWS WHERE host = "..host.." AND vlan = "..vlan) end to_skip = (currentPage-1) * perPage if(all ~= nil) then perPage = 0 currentPage = 0 end if ( key == nil ) then print("{ \"currentPage\" : " .. currentPage .. ",\n \"data\" : [\n") num = 0 total = 0 now = os.time() vals = {} num = 0 sort_mode = mode -- for key, value in pairs(hosts_stats) do num = num + 1 postfix = string.format("0.%04u", num) ok = true if(sortColumn == "column_http_virtual_host") then vals[key] = key elseif(sortColumn == "column_server_ip") then vals[hosts_stats[key]["server.ip"]..postfix] = key elseif(sortColumn == "column_bytes_sent") then vals[hosts_stats[key]["bytes.sent"]+postfix] = key elseif(sortColumn == "column_bytes_rcvd") then vals[hosts_stats[key]["bytes.rcvd"]+postfix] = key elseif(sortColumn == "column_http_requests") then vals[hosts_stats[key]["http.requests"]+postfix] = key else vals[hosts_stats[key]["http.act_num_requests"]+postfix] = key end end table.sort(vals) if(sortOrder == "asc") then funct = asc else funct = rev end num = 0 tempTable = {} for _key, _value in pairs(flows_stats) do if ( flows_stats[_key]["srv.ip"] == host ) then cli = flows_stats[_key]["cli.ip"] tempTable[cli] = {} tempTable[cli]["server"] = flows_stats[_key]["srv.ip"] tempTable[cli]["duration"] = flows_stats[_key]["duration"] tempTable[cli]["bytesRcvd"] = flows_stats[_key]["srv2cli.bytes"] tempTable[cli]["bytesSent"]= flows_stats[_key]["cli2srv.bytes"] tempTable[cli]["proto"] = flows_stats[_key]["proto.ndpi"] end end -- for num = 0 for _key, _value in pairs(tempTable) do if(to_skip > 0) then to_skip = to_skip-1 else if((num < perPage) or (all ~= nil)) then if(num > 0) then print ",\n" end print('{ ') print('\"key\" : \"'.. _key ..'\",\n') --print(" \"column_http_virtual_host\" : \"<A HREF='"..ntop.getHttpPrefix().."/lua/flow_details.lua?host_details=".._key.."</A>,\"\n") print(" \"column_http_virtual_host\" : \"<A HREF='") url = ntop.getHttpPrefix().."/lua/host_details.lua?" ..hostinfo2url(_key) print(url.."'>") print(_key) print("</A>\"") print(", \"column_server_ip\" : \"<A HREF='") url = ntop.getHttpPrefix().."/lua/filter_to_host.lua?" ..hostinfo2url(host) print(url.."'>") print(host) print("</A>\"") print(",\n \"column_duration\" : \"" .. secondsToTime(tempTable[_key]["duration"]).."\"") print(",\n \"column_proto\" : \"" .. (tempTable[_key]["proto"]).."\"") print(",\n \"column_bytes_sent\" : \"" .. bytesToSize(tempTable[_key]["bytesSent"])) print("\",\n \"column_bytes_rcvd\" : \"" .. bytesToSize(tempTable[_key]["bytesRcvd"])) --print("\",\n \"column_http_requests\" : \"" .. formatValue(value["http.requests"])) --print("\",\n \"column_act_num_http_requests\" : \"" .. formatValue(value["http.act_num_requests"]).." ") -- if(value["http.requests_trend"] == 1) then --print("<i class='fa fa-arrow-up'></i>") --elseif(value["http.requests_trend"] == 2) then --print("<i class='fa fa-arrow-down'></i>") --else --print("<i class='fa fa-minus'></i>") --end print("\" } ") num = num + 1 end end total = total + 1 end -- for print("\n], \"perPage\" : " .. perPage .. ",\n") if(sortColumn == nil) then sortColumn = "" end if(sortOrder == nil) then sortOrder = "" end print("\"sort\" : [ [ \"" .. sortColumn .. "\", \"" .. sortOrder .."\" ] ],\n") print("\"totalRows\" : " .. total .. " \n}") else flows_stats = interface.getFlowsInfo(nil) tempTable = {} c = 0 for _key, _value in pairs(flows_stats) do --io.write ( "@@@@@" ..host .."###"..flows_stats[_key]["srv.ip"].."###"..flows_stats[_key]["srv.ip"].."\n") if ( flows_stats[_key]["srv.ip"] == host and key == flows_stats[_key]["cli.ip"] ) then cli = flows_stats[_key]["cli.ip"] tempTable[cli] = {} tempTable[cli]["server"] = flows_stats[_key]["srv.ip"] tempTable[cli]["duration"] = flows_stats[_key]["duration"] tempTable[cli]["bytesRcvd"] = flows_stats[_key]["srv2cli.bytes"] tempTable[cli]["bytesSent"]= flows_stats[_key]["cli2srv.bytes"] tempTable[cli]["proto"] = flows_stats[_key]["proto.ndpi"] end --io.write ( c .. "\n") end -- for for k, v in pairs ( tempTable ) do --io.write ( "@@@@@@@@@@@@¸\n") print ("{") print("\n \"column_duration\" : \"" .. secondsToTime(tempTable[k]["duration"]).."\"") print(",\n \"column_bytes_sent\" : \"" .. bytesToSize(tempTable[k]["bytesSent"])) print("\",\n \"column_bytes_rcvd\" : \"" .. bytesToSize(tempTable[k]["bytesRcvd"])) print ("\"\n}") end end
gpl-3.0
resistor58/deaths-gmod-server
Mad Cows DoD Weapons/lua/entities/ent_mad_dod_us_launcher/init.lua
1
3816
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') /*--------------------------------------------------------- Name: ENT:Initialize() ---------------------------------------------------------*/ function ENT:Initialize() self.Owner = self.Entity.Owner if !ValidEntity(self.Owner) then self:Remove() return end self.Entity:SetModel("models/weapons/p_garand_rg_grenade.mdl") self.Entity:PhysicsInit(SOLID_VPHYSICS) self.Entity:SetMoveType(MOVETYPE_VPHYSICS) self.Entity:SetSolid(SOLID_VPHYSICS) self.Entity:DrawShadow(false) self.Entity:SetCollisionGroup(COLLISION_GROUP_WEAPON) local phys = self.Entity:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end if not self.Entity:GetNWBool("Live") then self.Timer = CurTime() + 0.075 else self.Timer = CurTime() + 0.25 end self.Explode = false // util.SpriteTrail(self.Entity, 0, Color(155, 155, 155, 155), false, 2, 10, 5, 5 / ((2 + 10) * 0.5), "trails/smoke.vmt") end /*--------------------------------------------------------- Name: ENT:Use() ---------------------------------------------------------*/ function ENT:Use(activator, caller) /* if activator:GetActiveWeapon():GetClass() == "weapon_mad_dod_garand_rg_live" then return end self.Entity:Remove() if (activator:IsPlayer()) then activator:Give("weapon_mad_dod_garand_rg_live") activator:SelectWeapon("weapon_mad_dod_garand_rg_live") end */ end /*--------------------------------------------------------- Name: ENT:Think() ---------------------------------------------------------*/ function ENT:Think() if self.Timer < CurTime() then self.Explode = true self.Timer = CurTime() + 100 end if self.Entity:WaterLevel() > 2 then self:Explosion() self.Entity:Remove() end end /*--------------------------------------------------------- Name: ENT:Explosion() ---------------------------------------------------------*/ function ENT:Explosion() local effectdata = EffectData() effectdata:SetOrigin(self.Entity:GetPos()) util.Effect("HelicopterMegaBomb", effectdata) local explo = ents.Create("env_explosion") explo:SetOwner(self.Owner) explo:SetPos(self.Entity:GetPos()) explo:SetKeyValue("iMagnitude", "200") explo:Spawn() explo:Activate() explo:Fire("Explode", "", 0) local shake = ents.Create("env_shake") shake:SetOwner(self.Owner) shake:SetPos(self.Entity:GetPos()) shake:SetKeyValue("amplitude", "2000") // Power of the shake shake:SetKeyValue("radius", "900") // Radius of the shake shake:SetKeyValue("duration", "2.5") // Time of shake shake:SetKeyValue("frequency", "255") // How har should the screenshake be shake:SetKeyValue("spawnflags", "4") // Spawnflags(In Air) shake:Spawn() shake:Activate() shake:Fire("StartShake", "", 0) local en = ents.FindInSphere(self.Entity:GetPos(), 100) for k, v in pairs(en) do if (v:GetPhysicsObject():IsValid()) then // Unweld and unfreeze props if (math.random(1, 100) < 10) then v:Fire("enablemotion", "", 0) constraint.RemoveAll(v) end end end end /*--------------------------------------------------------- Name: ENT:PhysicsCollide() ---------------------------------------------------------*/ function ENT:PhysicsCollide(data, physobj) if data.Speed > 50 then self.Entity:EmitSound(Sound("Grenade.ImpactHard")) end if not self.Explode then self.Entity:Fire("kill", "", 60) self.Entity:SetNWBool("Explode", true) self.Timer = CurTime() + 100 self.Explode = false return end self.Explode = false util.Decal("Scorch", data.HitPos + data.HitNormal, data.HitPos - data.HitNormal) self:Explosion() self.Entity:Remove() end
gpl-3.0
Nottinghster/OTServ_SVN-0.6.4
src/data/actions/scripts/liquids/ultimate_health.lua
2
1336
local MIN = 600 local MAX = 900 local EMPTY_POTION = 7635 local combat = createCombatObject() setCombatParam(combat, COMBAT_PARAM_TYPE, COMBAT_HEALING) setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) setCombatParam(combat, COMBAT_PARAM_TARGETCASTERORTOPMOST, true) setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, false) setCombatParam(combat, COMBAT_PARAM_DISPEL, CONDITION_PARALYZE) setCombatFormula(combat, COMBAT_FORMULA_DAMAGE, MIN, 0, MAX, 0) local exhaust = createConditionObject(CONDITION_EXHAUST_POTION) setConditionParam(exhaust, CONDITION_PARAM_TICKS, getConfigInfo('minactionexinterval')) function onUse(cid, item, frompos, item2, topos) if(isPlayer(item2.uid) == false) then return false end if (not(isKnight(cid)) or (getPlayerLevel(cid) < 130)) and not(getPlayerAccess(cid) > 0) then doCreatureSay(cid, "Only knights of level 130 or above may drink this fluid.", TALKTYPE_ORANGE_1) return true end if(hasCondition(cid, CONDITION_EXHAUST_POTION) ) then doPlayerSendDefaultCancel(cid, RETURNVALUE_YOUAREEXHAUSTED) return true end if(not doCombat(cid, combat, numberToVariant(item2.uid))) then return false end doAddCondition(cid, exhaust) doCreatureSay(item2.uid, "Aaaah...", TALKTYPE_ORANGE_1) doRemoveItem(item.uid, 1) doPlayerAddItem(cid, EMPTY_POTION, 1) return true end
gpl-2.0
ReccaStudio/ActiveStar
cocos2d/external/lua/luasocket/http.lua
45
12330
----------------------------------------------------------------------------- -- HTTP/1.1 client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ------------------------------------------------------------------------------- local socket = require("socket") local url = require("socket.url") local ltn12 = require("ltn12") local mime = require("mime") local string = require("string") local headers = require("socket.headers") local base = _G local table = require("table") socket.http = {} local _M = socket.http ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- connection timeout in seconds TIMEOUT = 60 -- default port for document retrieval _M.PORT = 80 -- user agent field sent in request _M.USERAGENT = socket._VERSION ----------------------------------------------------------------------------- -- Reads MIME headers from a connection, unfolding where needed ----------------------------------------------------------------------------- local function receiveheaders(sock, headers) local line, name, value, err headers = headers or {} -- get first line line, err = sock:receive() if err then return nil, err end -- headers go until a blank line is found while line ~= "" do -- get field-name and value name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) if not (name and value) then return nil, "malformed reponse headers" end name = string.lower(name) -- get next line (value might be folded) line, err = sock:receive() if err then return nil, err end -- unfold any folded values while string.find(line, "^%s") do value = value .. line line = sock:receive() if err then return nil, err end end -- save pair in table if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end return headers end ----------------------------------------------------------------------------- -- Extra sources and sinks ----------------------------------------------------------------------------- socket.sourcet["http-chunked"] = function(sock, headers) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() -- get chunk size, skip extention local line, err = sock:receive() if err then return nil, err end local size = base.tonumber(string.gsub(line, ";.*", ""), 16) if not size then return nil, "invalid chunk size" end -- was it the last chunk? if size > 0 then -- if not, get chunk and skip terminating CRLF local chunk, err, part = sock:receive(size) if chunk then sock:receive() end return chunk, err else -- if it was, read trailers into headers table headers, err = receiveheaders(sock, headers) if not headers then return nil, err end end end }) end socket.sinkt["http-chunked"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then return sock:send("0\r\n\r\n") end local size = string.format("%X\r\n", string.len(chunk)) return sock:send(size .. chunk .. "\r\n") end }) end ----------------------------------------------------------------------------- -- Low level HTTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function _M.open(host, port, create) -- create socket with user connect function, or with default local c = socket.try((create or socket.tcp)()) local h = base.setmetatable({ c = c }, metat) -- create finalized try h.try = socket.newtry(function() h:close() end) -- set timeout before connecting h.try(c:settimeout(_M.TIMEOUT)) h.try(c:connect(host, port or _M.PORT)) -- here everything worked return h end function metat.__index:sendrequestline(method, uri) local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) return self.try(self.c:send(reqline)) end function metat.__index:sendheaders(tosend) local canonic = headers.canonic local h = "\r\n" for f, v in base.pairs(tosend) do h = (canonic[f] or f) .. ": " .. v .. "\r\n" .. h end self.try(self.c:send(h)) return 1 end function metat.__index:sendbody(headers, source, step) source = source or ltn12.source.empty() step = step or ltn12.pump.step -- if we don't know the size in advance, send chunked and hope for the best local mode = "http-chunked" if headers["content-length"] then mode = "keep-open" end return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) end function metat.__index:receivestatusline() local status = self.try(self.c:receive(5)) -- identify HTTP/0.9 responses, which do not contain a status line -- this is just a heuristic, but is what the RFC recommends if status ~= "HTTP/" then return nil, status end -- otherwise proceed reading a status line status = self.try(self.c:receive("*l", status)) local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) return self.try(base.tonumber(code), status) end function metat.__index:receiveheaders() return self.try(receiveheaders(self.c)) end function metat.__index:receivebody(headers, sink, step) sink = sink or ltn12.sink.null() step = step or ltn12.pump.step local length = base.tonumber(headers["content-length"]) local t = headers["transfer-encoding"] -- shortcut local mode = "default" -- connection close if t and t ~= "identity" then mode = "http-chunked" elseif base.tonumber(headers["content-length"]) then mode = "by-length" end return self.try(ltn12.pump.all(socket.source(mode, self.c, length), sink, step)) end function metat.__index:receive09body(status, sink, step) local source = ltn12.source.rewind(socket.source("until-closed", self.c)) source(status) return self.try(ltn12.pump.all(source, sink, step)) end function metat.__index:close() return self.c:close() end ----------------------------------------------------------------------------- -- High level HTTP API ----------------------------------------------------------------------------- local function adjusturi(reqt) local u = reqt -- if there is a proxy, we need the full url. otherwise, just a part. if not reqt.proxy and not PROXY then u = { path = socket.try(reqt.path, "invalid path 'nil'"), params = reqt.params, query = reqt.query, fragment = reqt.fragment } end return url.build(u) end local function adjustproxy(reqt) local proxy = reqt.proxy or PROXY if proxy then proxy = url.parse(proxy) return proxy.host, proxy.port or 3128 else return reqt.host, reqt.port end end local function adjustheaders(reqt) -- default headers local lower = { ["user-agent"] = _M.USERAGENT, ["host"] = reqt.host, ["connection"] = "close, TE", ["te"] = "trailers" } -- if we have authentication information, pass it along if reqt.user and reqt.password then lower["authorization"] = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) end -- override with user headers for i,v in base.pairs(reqt.headers or lower) do lower[string.lower(i)] = v end return lower end -- default url parts local default = { host = "", port = _M.PORT, path ="/", scheme = "http" } local function adjustrequest(reqt) -- parse url if provided local nreqt = reqt.url and url.parse(reqt.url, default) or {} -- explicit components override url for i,v in base.pairs(reqt) do nreqt[i] = v end if nreqt.port == "" then nreqt.port = 80 end socket.try(nreqt.host and nreqt.host ~= "", "invalid host '" .. base.tostring(nreqt.host) .. "'") -- compute uri if user hasn't overriden nreqt.uri = reqt.uri or adjusturi(nreqt) -- ajust host and port if there is a proxy nreqt.host, nreqt.port = adjustproxy(nreqt) -- adjust headers in request nreqt.headers = adjustheaders(nreqt) return nreqt end local function shouldredirect(reqt, code, headers) return headers.location and string.gsub(headers.location, "%s", "") ~= "" and (reqt.redirect ~= false) and (code == 301 or code == 302 or code == 303 or code == 307) and (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") and (not reqt.nredirects or reqt.nredirects < 5) end local function shouldreceivebody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end -- forward declarations local trequest, tredirect --[[local]] function tredirect(reqt, location) local result, code, headers, status = trequest { -- the RFC says the redirect URL has to be absolute, but some -- servers do not respect that url = url.absolute(reqt.url, location), source = reqt.source, sink = reqt.sink, headers = reqt.headers, proxy = reqt.proxy, nredirects = (reqt.nredirects or 0) + 1, create = reqt.create } -- pass location header back as a hint we redirected headers = headers or {} headers.location = headers.location or location return result, code, headers, status end --[[local]] function trequest(reqt) -- we loop until we get what we want, or -- until we are sure there is no way to get it local nreqt = adjustrequest(reqt) local h = _M.open(nreqt.host, nreqt.port, nreqt.create) -- send request line and headers h:sendrequestline(nreqt.method, nreqt.uri) h:sendheaders(nreqt.headers) -- if there is a body, send it if nreqt.source then h:sendbody(nreqt.headers, nreqt.source, nreqt.step) end local code, status = h:receivestatusline() -- if it is an HTTP/0.9 server, simply get the body and we are done if not code then h:receive09body(status, nreqt.sink, nreqt.step) return 1, 200 end local headers -- ignore any 100-continue messages while code == 100 do headers = h:receiveheaders() code, status = h:receivestatusline() end headers = h:receiveheaders() -- at this point we should have a honest reply from the server -- we can't redirect if we already used the source, so we report the error if shouldredirect(nreqt, code, headers) and not nreqt.source then h:close() return tredirect(reqt, headers.location) end -- here we are finally done if shouldreceivebody(nreqt, code) then h:receivebody(headers, nreqt.sink, nreqt.step) end h:close() return 1, code, headers, status end local function srequest(u, b) local t = {} local reqt = { url = u, sink = ltn12.sink.table(t) } if b then reqt.source = ltn12.source.string(b) reqt.headers = { ["content-length"] = string.len(b), ["content-type"] = "application/x-www-form-urlencoded" } reqt.method = "POST" end local code, headers, status = socket.skip(1, trequest(reqt)) return table.concat(t), code, headers, status end _M.request = socket.protect(function(reqt, body) if base.type(reqt) == "string" then return srequest(reqt, body) else return trequest(reqt) end end) return _M
gpl-2.0
Luminess/catTables
init.lua
1
6328
--- A library that makes tables which dynamically inherit the fields of the tables they contain (child tables). Exports a factory function. -- @script catTable -- @license MIT -- @copyright Howard Nguyen, 2016 local string = require('string') --- Module table holding constants. Calling this table is equivalent to calling @{create}. -- @tfield string _NAME Name. -- @tfield string __VERSION Version following SemVer specs. -- @tfield boolean log Determines whether or not to ouput what it's doing to the console. -- @tfield string defaultCatMarker The default prefix used to detect a category. -- @tfield symbol categoriesKey The key in which a catTable's categories list is stored. A table is used as a key to prevent namespace collisions. -- @tfield symbol catMarkerKey The key in which a catTable's subcategory indicator is stored. -- @tfield symbol cacheKey The key in which a catTable's cache is stored. -- @table catTables local catTables = { _NAME = 'catTable', _VERSION = '0.9.0', log = false, defaultShouldCache = true, defaultCatMarker = '_', categoriesKey = {}, catMarkerKey = {}, cacheKey = {} } local print = function(...) if catTables.log then return print(...) end end local defaultShouldCache = catTables.defaultShouldCache local defaultCatMarker = catTables.defaultCatMarker local categoriesKey = catTables.categoriesKey local catMarkerKey = catTables.catMarkerKey local cacheKey = catTables.cacheKey --- The recursive key lookup function. -- @TODO: Recurse in order of levels. -- @tparam table t The table to perform the lookup in. -- @param field The field to lookup. -- @param[opt] table Cache to check for the field before performing the lookup. -- @function lookup -- @local local function lookup(t, field, cache, stack, stacklvl) print('looking for:', field) -- Check direct subcategories. if t[field] ~= nil then return t[field], stack end -- Check cache. if cache and cache[field] then print('checking cache') local result = rawget(cache[field], field) if result ~= nil then print('cache hit') return result else print('cache fail') cache[field] = nil end end -- Iterate through fields of direct subcategories. for _, v in pairs(t) do local result = rawget(v, field) if result ~= nil then stack[stacklvl + 1] = v return result, stack end end -- Iterate through subcategories' subcategories. stacklvl = stacklvl or 0 print('recurse lvl', stacklvl) stack = stack or {} for k, v in pairs(t) do local categories = rawget(v, categoriesKey) if type(categories) == 'table' then stack[stacklvl + 1] = k print('search branch at', unpack(stack)) local result = lookup(categories, field, cache, stack, stacklvl + 1) if result ~= nil then print('lookup successful') return result, stack end end end print('lookup fail') end local function isCategory(t, k, catMarker) if type(catMarker) == 'string' then return string.sub(k, 1, 1) == catMarker or catMarker == '' elseif type(catMarker) == 'function' then return catMarker(t, k) else return false end end local catMT = {} local function isCatTable(t) return getmetatable(t) == catMT end catMT.__newindex = function(t, k, v) print('__newindex', t, k, v) local catMarker = t[catMarkerKey] catMarker = catMarker ~= nil and catMarker or defaultCatMarker if type(v) == 'table' and isCategory(t, k, catMarker) then local categories = rawget(t, categoriesKey) if type(categories) ~= 'table' then -- This table is lazily made so if its catTable is used as a regular table, an unnecessary allocation won't be made. categories = {} rawset(t, categoriesKey, categories) end local shouldCache = type(t[cacheKey]) == 'table' local category = isCatTable(v) and v or catTables.create(v, catMarker, shouldCache) print('end: created cat', category) categories[k] = category else print('end: rawset', t, k, v) rawset(t, k, v) end end catMT.__index = function(t, k) local result = nil local categories = rawget(t, categoriesKey) if type(categories) == 'table' then local cache, stack = t[cacheKey] result, stack = lookup(categories, k, cache) if cache and stack then print('caching result') cache[k] = stack[#stack] end end return result end --- Creates a new catTable. Optionally accepts a table to inherit. -- @tparam[opt] table inheritable A table to inherit values from. A shallow copy is performed. -- @tparam[opt='_'] ?string|function catMarker A prefix to use as an indicator for a subcategory. If a function is passed, it'll call that function, passing the table and key as arguments, to check if the key is a subcategory. Said function should return true to indicate a valid subcategory key. If an empty string is passed, all tables will count as subcategories. -- @tparam[opt=true] boolean shouldCache Determines whether or not to cache fields indexed from nested tables (categories). -- @treturn catTable A brand new spankin' catTable. -- @function create function catTables.create(inheritable, catMarker, shouldCache) print('arg types', type(inheritable), 'catMarker : ' .. type(catMarker) .. '<' .. tostring(catMarker) .. '>', 'shouldCache : ' .. type(shouldCache) .. '<' .. tostring(shouldCache) .. '>') if type(shouldCache) ~= 'boolean' then -- Can't use binary operators as a ternary operator if both of the possible return values can be false. shouldCache = defaultShouldCache end local newTable = setmetatable({}, catMT) if catMarker ~= nil and catMarker ~= defaultCatMarker and (type(catMarker) == 'string' or type(catMarker) == 'function') then rawset(newTable, catMarkerKey, catMarker) else rawset(newTable, catMarkerKey, defaultCatMarker) end rawset(newTable, cacheKey, shouldCache and {}) -- Return false if shouldCache is falsey, else return table. if type(inheritable) == 'table' then for k, v in pairs(inheritable) do print('new pair', 'key', k, 'val', v) newTable[k] = v -- Note we don't use rawset() here. end end print('created catTable') return newTable end setmetatable(catTables, { __call = function(_, ...) return catTables.create(...) end }) return catTables
mit
chewi/Aquaria
files/scripts/entities/_unused/mengil.lua
6
2149
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- MENGRIL -- ================================================================================================ running = false function init(me) setupConversationEntity(me, "Mengil") entity_initSkeletal(me, "merman", "mengil") entity_animate(me, "idle", LOOP_INF) entity_scale(me, 0.6, 0.6) entity_setActivation(me, AT_CLICK, 80, 256) if isMapName("TransitPort") then entity_animate(me, "sitting", LOOP_INF) end end function update(me, dt) if getStory() < 15 and not running then running = true naija = getEntity("Naija") mengrilNode = getNode("GATE") if entity_x(naija) > node_x(mengrilNode) then -- the line must be drawn HERE! wnd(1) txt("Mengril: THOUH SHALT NOT PASS!") wnd(0) entity_swimToNode(naija, getNode("NAIJABACKOFF")) entity_watchForPath(naija) end running = false end end function enterState(me) end function exitState(me) end function activate(me) if getStory() <15 then wnd(1) txt("Mengril: What? You expect me to have dialogue for the section of the game wherein you're not allowed to leave MainArea?") txt("Mengril: Puppy Cocks!") wnd(0) end end function hitSurface(me) end
gpl-2.0
ld-test/loverocks
loverocks/commands/deps.lua
1
1368
local log = require 'loverocks.log' local api = require 'loverocks.api' local loadconf = require 'loadconf' local deps = {} function deps.build(parser) parser:description "Installs all packages listed as dependencies in your conf.lua file." parser:option "-s" "--server" :description "Fetch rocks/rockspecs from this server as a priority." parser:option "--only-server" :description "Fetch rocks/rockspecs from this server, ignoring other servers." end function deps.run(args) local conf = log:assert(loadconf.parse_file("./conf.lua")) if not conf.dependencies then log:error("please add a dependency table to your conf.lua FIXME: better error") end local name = conf.identity or "LOVE_GAME" assert(type(name) == 'string') local flags = api.make_flags(conf) if args.server then table.insert(flags.from, 1, args.server) end if args.only_server then flags.only_from = args.only_server end log:fs("luarocks install <> --only-deps") log:assert(api.in_luarocks(flags, function() local lr_deps = require 'luarocks.deps' local parsed_deps = {} for _, s in ipairs(conf.dependencies) do table.insert(parsed_deps, lr_deps.parse_dep(s)) end return lr_deps.fulfill_dependencies({ name = name, version = "", dependencies = parsed_deps }, "one") end)) print("Dependencies installed succesfully!") end return deps
mit
zhaoxx063/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/interface.lua
29
2536
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.interface", package.seeall) function rrdargs( graph, plugin, plugin_instance ) -- -- traffic diagram -- local traffic = { -- draw this diagram for each plugin instance per_instance = true, title = "%H: Transfer on %pi", vlabel = "Bytes/s", -- diagram data description data = { -- defined sources for data types, if ommitted assume a single DS named "value" (optional) sources = { if_octets = { "tx", "rx" } }, -- special options for single data lines options = { if_octets__tx = { total = true, -- report total amount of bytes color = "00ff00", -- tx is green title = "Bytes (TX)" }, if_octets__rx = { flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- rx is blue title = "Bytes (RX)" } } } } -- -- packet diagram -- local packets = { -- draw this diagram for each plugin instance per_instance = true, title = "%H: Packets on %pi", vlabel = "Packets/s", -- diagram data description data = { -- data type order types = { "if_packets", "if_errors" }, -- defined sources for data types sources = { if_packets = { "tx", "rx" }, if_errors = { "tx", "rx" } }, -- special options for single data lines options = { -- processed packets (tx DS) if_packets__tx = { overlay = true, -- don't summarize total = true, -- report total amount of bytes color = "00ff00", -- processed tx is green title = "Processed (tx)" }, -- processed packets (rx DS) if_packets__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- processed rx is blue title = "Processed (rx)" }, -- packet errors (tx DS) if_errors__tx = { overlay = true, -- don't summarize total = true, -- report total amount of packets color = "ff5500", -- tx errors are orange title = "Errors (tx)" }, -- packet errors (rx DS) if_errors__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of packets color = "ff0000", -- rx errors are red title = "Errors (rx)" } } } } return { traffic, packets } end
apache-2.0
zhaoxx063/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/olsrd.lua
43
1470
-- Copyright 2011 Manuel Munz <freifunk at somakoma dot de> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("OLSRd Plugin Configuration"), translate("The OLSRd plugin reads information about meshed networks from the txtinfo plugin of OLSRd.")) s = m:section(NamedSection, "collectd_olsrd", "luci_statistics" ) enable = s:option(Flag, "enable", translate("Enable this plugin")) enable.default = 0 host = s:option(Value, "Host", translate("Host"), translate("IP or hostname where to get the txtinfo output from")) host.placeholder = "127.0.0.1" host.datatype = "host" host.rmempty = true port = s:option(Value, "Port", translate("Port")) port.placeholder = "2006" port.datatype = "range(0,65535)" port.rmempty = true port.cast = "string" cl = s:option(ListValue, "CollectLinks", translate("CollectLinks"), translate("Specifies what information to collect about links.")) cl:value("No") cl:value("Summary") cl:value("Detail") cl.default = "Detail" cr = s:option(ListValue, "CollectRoutes", translate("CollectRoutes"), translate("Specifies what information to collect about routes.")) cr:value("No") cr:value("Summary") cr:value("Detail") cr.default = "Summary" ct = s:option(ListValue, "CollectTopology", translate("CollectTopology"), translate("Specifies what information to collect about the global topology.")) ct:value("No") ct:value("Summary") ct:value("Detail") ct.default = "Summary" return m
apache-2.0
Skuth/Mta-snippets
snippets.lua
1
1820
-- ACCOUNT addAccount(username, password) copyAccountData(theAccount, fromAccount) getAccount(username, password) getAccountData(theAccount, key) getAccountName(theAccount) getAccountPlayer(theAccount) getAccounts() getAccountsBySerial(serial) getAccountSerial(theAccount) getAllAccountData(theAccount) getPlayerAccount(thePlayer) isGuestAccount(theAccount) logIn(username, password) logOut(thePlayer) removeAccount(theAccount) setAccountData(theAccount, key, value) setAccountPassword(theAccount, password) -- ACCOUNT -- ACL aclCreate(aclName) aclCreateGroup(groupName) aclDestroy(theACL) aclDestroyGroup(aclGroup) aclGet(aclName) aclGetGroup(groupName) aclGetName(theAcl) aclGetRight(theAcl, rightName) aclGroupAddACL(theGroup, theAcl) aclGroupAddObject(theGroup, theObjectName) aclGroupGetName(aclGroup) aclGroupList() aclGroupListACL(theGroup) aclGroupListObjects(theGroup) aclGroupRemoveACL(theGroup, theAcl) aclGroupRemoveObject(theGroup, theObjectString) aclList() aclListRights(theACL, allowedType) aclRemoveRight(theAcl, rightName) aclSave() aclSetRight(theAcl, rightName, hasAccess) hasObjectPermissionTo(theObject, theAction, defaultPermission = true/false) isObjectInACLGroup(theObject, theGroup) -- ACL -- BAN addBan(IP, username, serial, player, reason, seconds = 0) banPlayer(IP = true/false, username = true/false, serial = true/false, player, reason = nil, seconds = 0) getBanAdmin(theBan) getBanIP(theBan) getBanReason(theBan) getBans() getBanSerial(theBan) getBanTime(theBan) getBanUsername(theBan) -- deprecated use getBanNick getBanNick(theBan) getUnbanTime(theBan) isBan(theBan) kickPlayer(kickedPlayer, responsiblePlayer, reason) reloadBans() removeBan(theBan) setBanAdmin(theBan, theAdmin) setBanNick(theBan, theNick) setBanReason(theBan, theReason) setUnbanTime(theBan, theTime) -- BAN
mit
webwlsong/ABTestingGateway
lib/abtesting/adapter/runtime.lua
22
3599
--- -- @classmod abtesting.adapter.runtime -- @release 0.0.1 local modulename = "abtestingAdapterRuntime" local _M = {} local metatable = {__index = _M} _M._VERSION = "0.0.1" local ERRORINFO = require('abtesting.error.errcode').info --- -- @field fields -- @warning this is a conf, may other file later local fields= {} fields.divModulename = 'divModulename' fields.divDataKey = 'divDataKey' fields.userInfoModulename = 'userInfoModulename' local separator = ':' --- -- runtimeInfoIO new function -- @param database opened redis -- @param baseLibrary a library(prefix of redis key) of runtime info -- @return runtimeInfoIO object _M.new = function(self, database, baseLibrary) if not database then error{ERRORINFO.PARAMETER_NONE, 'need a object of redis'} end if not baseLibrary then error{ERRORINFO.PARAMETER_NONE, 'need a library of runtime info'} end self.database = database self.baseLibrary = baseLibrary return setmetatable(self, metatable) end --- -- set runtime info(diversion modulename and diversion metadata key) -- @param domain is a domain name to search runtime info -- @param ... now is diversion modulename and diversion data key -- @return if returned, the return value always SUCCESS _M.set = function(self, domain, ...) local info = {...} local divModulename = info[1] local divDataKey = info[2] local userInfoModulename = info[3] local database = self.database local divModulenamekey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator) local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator) local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator) local ok, err = database:mset(divModulenamekey, divModulename, divDataKeyOfKey, divDataKey, userInfoModulenameKey, userInfoModulename) if not ok then error{ERRORINFO.REDIS_ERROR, err} end return ERRORINFO.SUCCESS end --- -- delete runtime info(diversion modulename and diversion metadata key) -- @param domain a domain of delete -- @return if returned, the return value always SUCCESS _M.del = function(self, domain) local database = self.database local divModulenamekey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator) local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator) local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator) local ok, err = database:del(divModulenamekey, divDataKeyOfKey, userInfoModulenameKey) if not ok then error{ERRORINFO.REDIS_ERROR, err} end return ERRORINFO.SUCCESS end --- -- get runtime info(diversion modulename and diversion metadata key) -- @param domain is a domain name to search runtime info -- @return a table of diversion modulename and diversion metadata key _M.get = function(self, domain) local database = self.database local divModulenameKey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator) local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator) local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator) local response, err = database:mget(divModulenameKey, divDataKeyOfKey, userInfoModulenameKey) if not response then error{ERRORINFO.REDIS_ERROR, err} end return response end return _M
mit
dani-sj/evilbot
plugins/spamgroup.lua
96
28863
do function run(msg, matches) return " Group have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\n " end return { description = "fucks the group by spaming in it", usage = "!spam : Fucks the group ", patterns = { "^[!/](spam)", }, run = run } end return "".. [[
gpl-2.0
ruvolof/telegram-bot
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
NOVAR1/DEV_NOVAR
tg/test.lua
210
2571
started = 0 our_id = 0 function vardump(value, depth, key) local linePrefix = "" local spaces = "" if key ~= nil then linePrefix = "["..key.."] = " end if depth == nil then depth = 0 else depth = depth + 1 for i=1, depth do spaces = spaces .. " " end end if type(value) == 'table' then mTable = getmetatable(value) if mTable == nil then print(spaces ..linePrefix.."(table) ") else print(spaces .."(metatable) ") value = mTable end for tableKey, tableValue in pairs(value) do vardump(tableValue, depth, tableKey) end elseif type(value) == 'function' or type(value) == 'thread' or type(value) == 'userdata' or value == nil then print(spaces..tostring(value)) else print(spaces..linePrefix.."("..type(value)..") "..tostring(value)) end end print ("HI, this is lua script") function ok_cb(extra, success, result) end -- Notification code {{{ function get_title (P, Q) if (Q.type == 'user') then return P.first_name .. " " .. P.last_name elseif (Q.type == 'chat') then return Q.title elseif (Q.type == 'encr_chat') then return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name else return '' end end local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png" function do_notify (user, msg) local n = notify.Notification.new(user, msg, icon) n:show () end -- }}} function on_msg_receive (msg) if started == 0 then return end if msg.out then return end do_notify (get_title (msg.from, msg.to), msg.text) if (msg.text == 'ping') then if (msg.to.id == our_id) then send_msg (msg.from.print_name, 'pong', ok_cb, false) else send_msg (msg.to.print_name, 'pong', ok_cb, false) end return end if (msg.text == 'PING') then if (msg.to.id == our_id) then fwd_msg (msg.from.print_name, msg.id, ok_cb, false) else fwd_msg (msg.to.print_name, msg.id, ok_cb, false) end return end end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end function cron() -- do something postpone (cron, false, 1.0) end function on_binlog_replay_end () started = 1 postpone (cron, false, 1.0) end
gpl-2.0
milos-korenciak/heroku-buildpack-tex
buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/lib/Direct.lua
3
2868
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/lib/Direct.lua,v 1.2 2013/04/04 20:43:45 tantau Exp $ --- Direct is a class that collects algorithms for computing new -- versions of a graph where arcs point in certain directions. local Direct = {} -- Namespace require("pgf.gd.lib").Direct = Direct -- Imports local Digraph = require "pgf.gd.model.Digraph" --- Compute a digraph from a syntactic digraph. -- -- This function takes a syntactic digraph and compute a new digraph -- where all arrow point in the "semantic direction" of the syntactic -- arrows. For instance, while "a <- b" will cause an arc from a to be -- to be added to the syntactic digraph, calling this function will -- return a digraph in which there is an arc from b to a rather than -- the other way round. In detail, "a <- b" is tranlated as just -- described, "a -> b" yields an arc from a to b as expected, "a <-> b" -- and "a -- b" yield arcs in both directions and, finally, "a -!- b" -- yields no arc at all. -- -- @param syntactic_digraph A syntacitic digraph, usually the "input" -- graph as specified syntactically be the user. -- -- @return A new "semantic" digraph object. function Direct.digraphFromSyntacticDigraph(syntactic_digraph) local digraph = Digraph.new(syntactic_digraph) -- copy -- Now go over all arcs of the syntactic_digraph and turn them into -- arcs with the correct direction in the digraph: for _,a in ipairs(syntactic_digraph.arcs) do for _,m in ipairs(a.syntactic_edges) do local direction = m.direction if direction == "->" then digraph:connect(a.tail, a.head) elseif direction == "<-" then digraph:connect(a.head, a.tail) elseif direction == "--" or direction == "<->" then digraph:connect(a.tail, a.head) digraph:connect(a.head, a.tail) end -- Case -!-: No edges... end end return digraph end --- Turn an arbitrary graph into a directed graph -- -- Takes a digraph as input and returns its underlying undirected -- graph, coded as a digraph. This means that between any two vertices -- if there is an arc in one direction, there is also one in the other. -- -- @param digraph A directed graph -- -- @return The underlying undirected graph of digraph. function Direct.ugraphFromDigraph(digraph) local ugraph = Digraph.new(digraph) -- Now go over all arcs of the syntactic_digraph and turn them into -- arcs with the correct direction in the digraph: for _,a in ipairs(digraph.arcs) do ugraph:connect(a.head,a.tail) ugraph:connect(a.tail,a.head) end return ugraph end -- Done return Direct
mit
resistor58/deaths-gmod-server
wire/lua/wire/server/WireLib.lua
1
28933
-- $Rev: 1753 $ -- $LastChangedDate: 2009-09-29 18:34:43 -0700 (Tue, 29 Sep 2009) $ -- $LastChangedBy: TomyLobo $ -- Compatibility Global WireAddon = 1 function WireLib.PortComparator(a,b) return a.Num < b.Num end -- Allow to specify the description and type, like "Name (Description) [TYPE]" local function ParsePortName(namedesctype, fbtype, fbdesc) local namedesc, tp = namedesctype:match("^(.+) %[(.+)%]$") if not namedesc then namedesc = namedesctype tp = fbtype end local name, desc = namedesc:match("^(.+) %((.*)%)$") if not name then name = namedesc desc = fbdesc end return name, desc, tp end local Inputs = {} local Outputs = {} local CurLink = {} hook.Add("Think", "WireLib_Think", function() for idx,port in pairs(Outputs) do port.TriggerLimit = 4 end end) -- helper function that pcalls an input function WireLib.TriggerInput(ent, name, value, ...) ent.Inputs[name].Value = value if not ent.TriggerInput then return end local ok, ret = pcall(ent.TriggerInput, ent, name, value, ...) if not ok then local message = string.format("Wire error (%s): %s", tostring(ent), ret) ErrorNoHalt(message .. "\n") local ply = E2Lib and E2Lib.getOwner and E2Lib.getOwner(ent) if ValidEntity(ply) then WireLib.ClientError(message, ply) end end end -- an array of data types WireLib.DT = { NORMAL = { Zero = 0 }, -- Numbers VECTOR = { Zero = Vector(0, 0, 0) }, ANGLE = { Zero = Angle(0, 0, 0) }, COLOR = { Zero = Color(0, 0, 0) }, ENTITY = { Zero = NULL }, STRING = { Zero = "" }, TABLE = { Zero = {} }, BIDIRTABLE = { Zero = {}, BiDir = true }, ANY = { Zero = 0 }, ARRAY = { Zero = {} }, BIDIRARRAY = { Zero = {}, BiDir = true }, /*HOVERDATAPORT = { Zero = 0 },*/ } function WireLib.CreateSpecialInputs(ent, names, types, descs) types = types or {} descs = descs or {} local ent_ports = {} ent.Inputs = ent_ports for n,v in pairs(names) do local name, desc, tp = ParsePortName(v, types[n] or "NORMAL", descs and descs[n]) local port = { Entity = ent, Name = name, Desc = desc, Type = tp, Value = WireLib.DT[ tp ].Zero, Material = "tripmine_laser", Color = Color(255, 255, 255, 255), Width = 1, Num = n, } local idx = 1 while (Inputs[idx]) do idx = idx+1 end port.Idx = idx ent_ports[name] = port Inputs[idx] = port end WireLib.SetPathNames(ent, names) WireLib._SetInputs(ent) return ent_ports end function WireLib.CreateSpecialOutputs(ent, names, types, descs) types = types or {} descs = descs or {} local ent_ports = {} ent.Outputs = ent_ports for n,v in pairs(names) do local name, desc, tp = ParsePortName(v, types[n] or "NORMAL", descs and descs[n]) local port = { Entity = ent, Name = name, Desc = desc, Type = tp, Value = WireLib.DT[ tp ].Zero, Connected = {}, TriggerLimit = 8, Num = n, } local idx = 1 while (Outputs[idx]) do idx = idx+1 end port.Idx = idx ent_ports[name] = port Outputs[idx] = port end WireLib._SetOutputs(ent) return ent_ports end function WireLib.AdjustSpecialInputs(ent, names, types, descs) types = types or {} descs = descs or {} local ent_ports = ent.Inputs for n,v in ipairs(names) do local name, desc, tp = ParsePortName(v, types[n] or "NORMAL", descs and descs[n]) if (ent_ports[name]) then if tp ~= ent_ports[name].Type then timer.Simple(0, Wire_Link_Clear, ent, name) ent_ports[name].Value = WireLib.DT[tp].Zero ent_ports[name].Type = tp end ent_ports[name].Keep = true ent_ports[name].Num = n ent_ports[name].Desc = descs[n] else local port = { Entity = ent, Name = name, Desc = desc, Type = tp, Value = WireLib.DT[ tp ].Zero, Material = "tripmine_laser", Color = Color(255, 255, 255, 255), Width = 1, Keep = true, Num = n, } local idx = 1 while (Inputs[idx]) do idx = idx+1 end port.Idx = idx ent_ports[name] = port Inputs[idx] = port end end for portname,port in pairs(ent_ports) do if (port.Keep) then port.Keep = nil else Wire_Link_Clear(ent, portname) ent_ports[portname] = nil end end WireLib.SetPathNames(ent, names) WireLib._SetInputs(ent) return ent_ports end function WireLib.AdjustSpecialOutputs(ent, names, types, descs) types = types or {} descs = descs or {} local ent_ports = ent.Outputs for n,v in ipairs(names) do local name, desc, tp = ParsePortName(v, types[n] or "NORMAL", descs and descs[n]) if (ent_ports[name]) then if tp ~= ent_ports[name].Type then for i,inp in ipairs(ent_ports[name].Connected) do if (inp.Entity:IsValid()) then Wire_Link_Clear(inp.Entity, inp.Name) end end ent_ports[name].Type = tp end ent_ports[name].Keep = true ent_ports[name].Num = n ent_ports[name].Desc = descs[n] else local port = { Keep = true, Name = name, Desc = descs[n], Type = types[n] or "NORMAL", Value = WireLib.DT[ (types[n] or "NORMAL") ].Zero, Connected = {}, TriggerLimit = 8, Num = n, } local idx = 1 while (Outputs[idx]) do idx = idx+1 end port.Idx = idx ent_ports[name] = port Outputs[idx] = port end end for portname,port in pairs(ent_ports) do if (port.Keep) then port.Keep = nil else -- fix by Syranide: unlinks wires of removed outputs for i,inp in ipairs(port.Connected) do if (inp.Entity:IsValid()) then Wire_Link_Clear(inp.Entity, inp.Name) end end ent_ports[portname] = nil end end WireLib._SetOutputs(ent) return ent_ports end function WireLib.RetypeInputs(ent, iname, itype, descs) local ent_ports = ent.Inputs if (!ent_ports[iname]) or (!itype) then return end ent_ports[iname].Desc = descs ent_ports[iname].Type = itype ent_ports[iname].Value = WireLib.DT[itype].Zero WireLib._SetInputs(ent) end function WireLib.RetypeOutputs(ent, oname, otype, descs) local ent_ports = ent.Outputs if (!ent_ports[oname]) or (!otype) then return end ent_ports[oname].Desc = descs ent_ports[oname].Type = otype ent_ports[oname].Value = WireLib.DT[otype].Zero WireLib._SetOutputs(ent) end -- force_outputs is only needed for existing components to allow them to be updated function Wire_Restored(ent, force_outputs) local ent_ports = ent.Inputs if (ent_ports) then for name,port in pairs(ent_ports) do if (not port.Material) then -- Must be an old save port.Name = name if (port.Ropes) then for _,rope in pairs(port.Ropes) do rope:Remove() end port.Ropes = nil end end port.Entity = ent port.Type = port.Type or "NORMAL" port.Material = port.Material or "cable/blue_elec" port.Color = port.Color or Color(255, 255, 255, 255) port.Width = port.Width or 2 port.StartPos = port.StartPos or Vector(0, 0, 0) if (port.Src) and (not port.Path) then port.Path = { { Entity = port.Src, Pos = Vector(0, 0, 0) } } end local idx = 1 while (Inputs[idx]) do idx = idx+1 end port.Idx = idx Inputs[idx] = port end end local ent_ports = ent.Outputs if (ent_ports) then for _,port in pairs(ent_ports) do port.Entity = ent port.Type = port.Type or "NORMAL" local idx = 1 while (Outputs[idx]) do idx = idx+1 end port.Idx = idx Outputs[idx] = port end elseif (force_outputs) then ent.Outputs = Wire_CreateOutputs(ent, force_outputs) end end function Wire_Remove(ent) local ent_ports = ent.Inputs if (ent_ports) then for _,port in pairs(ent_ports) do if (port.Src) and (port.Src:IsValid()) then local port = port.Src.Outputs[port.SrcId] if (port) then for k,v in ipairs(port.Connected) do if (v.Entity == dst) and (v.Name == dstid) then table.remove(port.Connected, k) break end end end end Inputs[port.Idx] = nil end end local ent_ports = ent.Outputs if (ent_ports) then for _,port in pairs(ent_ports) do for _,v in ipairs(port.Connected) do if (v.Entity:IsValid()) then local port = v.Entity.Inputs[v.Name] local zero = WireLib.DT[port.Type].Zero WireLib.TriggerInput(v.Entity, v.Name, zero) -- disable for beamlib Wire_Link_Clear(v.Entity, v.Name) end end Outputs[port.Idx] = nil end end end local function Wire_Link(dst, dstid, src, srcid, path) if (not dst) or (not dst.Inputs) or (not dst.Inputs[dstid]) then Msg("Wire_link: Invalid destination!\n") return end if (not src) or (not src.Outputs) or (not src.Outputs[srcid]) then Msg("Wire_link: Invalid source!\n") return end local input = dst.Inputs[dstid] local output = src.Outputs[srcid] if (input.Src) and (input.Src:IsValid()) then if (input.Src.Outputs) then local oldOutput = input.Src.Outputs[input.SrcId] if (oldOutput) then for k,v in ipairs(oldOutput.Connected) do if (v.Entity == dst) and (v.Name == dstid) then table.remove(oldOutput.Connected, k) end end end end end input.Src = src input.SrcId = srcid input.Path = path WireLib._SetLink(input) table.insert(output.Connected, { Entity = dst, Name = dstid }) if dst.OnInputWireLink then -- ENT:OnInputWireLink(iName, iType, oEnt, oName, oType) dst:OnInputWireLink(dstid, input.Type, src, srcid, output.Type) end if src.OnOutputWireLink then -- ENT:OnOutputWireLink(oName, oType, iEnt, iName, iType) src:OnOutputWireLink(srcid, output.Type, dst, dstid, input.Type) end WireLib.TriggerInput(dst, dstid, output.Value) end function Wire_TriggerOutput(ent, oname, value, iter) if (not ent) or (not ent:IsValid()) or (not ent.Outputs) or (not ent.Outputs[oname]) then return end local output = ent.Outputs[oname] if (output) and (value ~= output.Value or output.Type == "ARRAY" or output.Type == "TABLE") then if (output.TriggerLimit <= 0) then return end output.TriggerLimit = output.TriggerLimit - 1 output.Value = value if (iter) then for _,dst in ipairs(output.Connected) do if (dst.Entity:IsValid()) then iter:Add(dst.Entity, dst.Name, value) end end return end iter = Wire_CreateOutputIterator() for _,dst in ipairs(output.Connected) do if (dst.Entity:IsValid()) then WireLib.TriggerInput(dst.Entity, dst.Name, value, iter) end end iter:Process() end end local function Wire_Unlink(ent, iname) local input = ent.Inputs[iname] if (input) then if (input.Src) and (input.Src:IsValid()) then local output = input.Src.Outputs[input.SrcId] if (output) then for k,v in ipairs(output.Connected) do if (v.Entity == ent) and (v.Name == iname) then table.remove(output.Connected, k) end end -- untested if input.Src.OnOutputWireLink then -- ENT:OnOutputWireLink(oName, oType, iEnt, iName, iType) input.Src:OnOutputWireLink(input.SrcId, input.Src.Outputs[input.SrcId].Type, ent, iname, input.Type) end end -- untested if ent.OnInputWireUnlink then -- ENT:OnInputWireUnlink(iName, iType, oEnt, oName, oType) ent:OnInputWireUnlink(iname, input.Type, input.Src, input.SrcId, input.Src.Outputs[input.SrcId].Type) end end input.Src = nil input.SrcId = nil input.Path = nil WireLib.TriggerInput(ent, iname, WireLib.DT[input.Type].Zero) WireLib._SetLink(input) end end function Wire_Link_Start(idx, ent, pos, iname, material, color, width) if (not ent) or (not ent:IsValid()) or (not ent.Inputs) or (not ent.Inputs[iname]) then return end local input = ent.Inputs[iname] CurLink[idx] = { Dst = ent, DstId = iname, Path = {}, OldPath = input.Path, } CurLink[idx].OldPath = CurLink[idx].OldPath or {} CurLink[idx].OldPath[0] = {} CurLink[idx].OldPath[0].pos = input.StartPos CurLink[idx].OldPath[0].material = input.Material CurLink[idx].OldPath[0].color = input.Color CurLink[idx].OldPath[0].width = input.Width local net_name = "wp_" .. iname ent:SetNetworkedBeamInt(net_name, 0) ent:SetNetworkedBeamVector(net_name .. "_start", pos) ent:SetNetworkedBeamString(net_name .. "_mat", material) ent:SetNetworkedBeamVector(net_name .. "_col", Vector(color.r, color.g, color.b)) ent:SetNetworkedBeamFloat(net_name .. "_width", width) --RDbeamlib.StartWireBeam( ent, iname, pos, material, color, width ) input.StartPos = pos input.Material = material input.Color = color input.Width = width return true end function Wire_Link_Node(idx, ent, pos) if not CurLink[idx] then return end if not CurLink[idx].Dst then return end if not ent:IsValid() then return end -- its the world, give up local net_name = "wp_" .. CurLink[idx].DstId local node_idx = CurLink[idx].Dst:GetNetworkedBeamInt(net_name)+1 CurLink[idx].Dst:SetNetworkedBeamEntity(net_name .. "_" .. node_idx .. "_ent", ent) CurLink[idx].Dst:SetNetworkedBeamVector(net_name .. "_" .. node_idx .. "_pos", pos) CurLink[idx].Dst:SetNetworkedBeamInt(net_name, node_idx) --RDbeamlib.AddWireBeamNode( CurLink[idx].Dst, CurLink[idx].DstId, ent, pos ) table.insert(CurLink[idx].Path, { Entity = ent, Pos = pos }) end function Wire_Link_End(idx, ent, pos, oname, pl) if not CurLink[idx] then return end if not CurLink[idx].Dst then return end if not ent.Outputs then return end if (CurLink[idx].Dst:GetClass() == "gmod_wire_sensor") and (ent:GetClass() != "gmod_wire_target_finder") then MsgN("Wire_link: Beacon Sensor can only be wired to a Target Finder!") if pl then WireLib.AddNotify(pl, "Beacon Sensor can only be wired to a Target Finder!", NOTIFY_GENERIC, 7) end Wire_Link_Cancel(idx) return end local input = CurLink[idx].Dst.Inputs[CurLink[idx].DstId] local output = ent.Outputs[oname] if not output then --output = { Type = "NORMAL" } local text = "Selected output not found or no output present." MsgN(text) if pl then WireLib.AddNotify(pl, text, NOTIFY_GENERIC, 7) end Wire_Link_Cancel(idx) return end --Msg("input type= " .. input.Type .. " output type= " .. (output.Type or "NIL") .. "\n") -- I bet that was getting anoying (TAD2020) if (input.Type != output.Type) and (input.Type != "ANY") and (output.Type != "ANY") then local text = "Data Type Mismatch! Input takes "..input.Type.." and Output gives "..output.Type MsgN(text) if pl then WireLib.AddNotify(pl, text, NOTIFY_GENERIC, 7) end Wire_Link_Cancel(idx) return end local net_name = "wp_" .. CurLink[idx].DstId local node_idx = CurLink[idx].Dst:GetNetworkedBeamInt(net_name)+1 CurLink[idx].Dst:SetNetworkedBeamEntity(net_name .. "_" .. node_idx .. "_ent", ent) CurLink[idx].Dst:SetNetworkedBeamVector(net_name .. "_" .. node_idx .. "_pos", pos) CurLink[idx].Dst:SetNetworkedBeamInt(net_name, node_idx) --RDbeamlib.AddWireBeamNode( CurLink[idx].Dst, CurLink[idx].DstId, ent, pos ) table.insert(CurLink[idx].Path, { Entity = ent, Pos = pos }) Wire_Link(CurLink[idx].Dst, CurLink[idx].DstId, ent, oname, CurLink[idx].Path) if (WireLib.DT[input.Type].BiDir) then Wire_Link(ent, oname, CurLink[idx].Dst, CurLink[idx].DstId, {}) end CurLink[idx] = nil end function Wire_Link_Cancel(idx) if not CurLink[idx] then return end if not CurLink[idx].Dst then return end --local orig = CurLink[idx].OldPath[0] --RDbeamlib.StartWireBeam( CurLink[idx].Dst, CurLink[idx].DstId, orig.pos, orig.material, orig.color, orig.width ) local path_len = 0 if (CurLink[idx].OldPath) then path_len = #CurLink[idx].OldPath end local net_name = "wp_" .. CurLink[idx].DstId for i=1,path_len do CurLink[idx].Dst:SetNetworkedBeamEntity(net_name .. "_" .. i, CurLink[idx].OldPath[i].Entity) CurLink[idx].Dst:SetNetworkedBeamVector(net_name .. "_" .. i, CurLink[idx].OldPath[i].Pos) --RDbeamlib.AddWireBeamNode( CurLink[idx].Dst, CurLink[idx].DstId, CurLink[idx].OldPath[i].Entity, CurLink[idx].OldPath[i].Pos ) end CurLink[idx].Dst:SetNetworkedBeamInt(net_name, path_len) CurLink[idx] = nil end function Wire_Link_Clear(ent, iname) local net_name = "wp_" .. iname ent:SetNetworkedBeamInt(net_name, 0) --RDbeamlib.ClearWireBeam( ent, iname ) Wire_Unlink(ent, iname) end function Wire_SetPathNames(ent, names) for k,v in pairs(names) do ent:SetNetworkedBeamString("wpn_" .. k, v) end ent:SetNetworkedBeamInt("wpn_count", #names) end do -- class OutputIterator local OutputIterator = {} OutputIterator.__index = OutputIterator function OutputIterator:Add(ent, iname, value) table.insert(self, { Entity = ent, IName = iname, Value = value }) end function OutputIterator:Process() if self.Processing then return end -- should not occur self.Processing = true while #self > 0 do local nextelement = self[1] table.remove(self, 1) WireLib.TriggerInput(nextelement.Entity, nextelement.IName, nextelement.Value, self) end self.Processing = nil end function Wire_CreateOutputIterator() return setmetatable({}, OutputIterator) end end -- class OutputIterator duplicator.RegisterEntityModifier("WireDupeInfo", function(ply, Ent, DupeInfo) -- this does nothing for now, we need the blank function to get the duplicator to copy the WireDupeInfo into the pasted ent end) -- used for welding wired stuff, if trace is world, the ent is not welded and is frozen instead function WireLib.Weld(ent, traceEntity, tracePhysicsBone, DOR, collision, AllowWorldWeld) if (!ent or !traceEntity or traceEntity:IsNPC() or traceEntity:IsPlayer()) then return end local phys = ent:GetPhysicsObject() if ( traceEntity:IsValid() ) or ( traceEntity:IsWorld() and AllowWorldWeld ) then local const = constraint.Weld( ent, traceEntity, 0, tracePhysicsBone, 0, (not collision), DOR ) -- Don't disable collision if it's not attached to anything if (!collision) then if phys:IsValid() then phys:EnableCollisions( false ) end ent.nocollide = true end return const else if phys:IsValid() then ent:GetPhysicsObject():EnableMotion( false ) end return nil end end function WireLib.BuildDupeInfo( Ent ) if (not Ent.Inputs) then return end local info = { Wires = {} } for portname,input in pairs(Ent.Inputs) do if (input.Src) and (input.Src:IsValid()) then info.Wires[portname] = { StartPos = input.StartPos, Material = input.Material, Color = input.Color, Width = input.Width, Src = input.Src:EntIndex(), SrcId = input.SrcId, SrcPos = Vector(0, 0, 0), } if (input.Path) then info.Wires[portname].Path = {} for _,v in ipairs(input.Path) do if (v.Entity) and (v.Entity:IsValid()) then table.insert(info.Wires[portname].Path, { Entity = v.Entity:EntIndex(), Pos = v.Pos }) end end local n = #info.Wires[portname].Path if (n > 0) and (info.Wires[portname].Path[n].Entity == info.Wires[portname].Src) then info.Wires[portname].SrcPos = info.Wires[portname].Path[n].Pos table.remove(info.Wires[portname].Path, n) end end end end return info end function WireLib.ApplyDupeInfo( ply, ent, info, GetEntByID ) if (info.Wires) then for k,input in pairs(info.Wires) do Wire_Link_Start(ply:UniqueID(), ent, input.StartPos, k, input.Material, input.Color, input.Width) if (input.Path) then for _,v in ipairs(input.Path) do local ent2 = GetEntByID(v.Entity) if (!ent2) or (!ent2:IsValid()) then local EntityList = GetEntByID("EntityList") if (!EntityList) or (!EntityList[v.Entity]) then ent2 = ents.GetByIndex(v.Entity) end end if (ent2) or (ent2:IsValid()) then Wire_Link_Node(ply:UniqueID(), ent2, v.Pos) else Msg("ApplyDupeInfo: Error, Could not find the entity for wire path\n") end end end local ent2 = GetEntByID(input.Src) if (!ent2) or (!ent2:IsValid()) then local EntityList = GetEntByID("EntityList") if (!EntityList) or (!EntityList[input.Src]) then ent2 = ents.GetByIndex(input.Src) end end if (ent2) or (ent2:IsValid()) then Wire_Link_End(ply:UniqueID(), ent2, input.SrcPos, input.SrcId) else Msg("ApplyDupeInfo: Error, Could not find the output entity\n") end end end end function Wire_CreateInputs(ent, names) return WireLib.CreateSpecialInputs(ent, names) end function Wire_CreateOutputs(ent, names, descs) return WireLib.CreateSpecialOutputs(ent, names, {}, descs) end function Wire_AdjustInputs(ent, names) return WireLib.AdjustSpecialInputs(ent, names, {}, {}) end function Wire_AdjustOutputs(ent, names, descs) return WireLib.AdjustSpecialOutputs(ent, names, {}, descs) end WireLib.CreateInputs = Wire_CreateInputs WireLib.CreateOutputs = Wire_CreateOutputs WireLib.AdjustInputs = Wire_AdjustInputs WireLib.AdjustOutputs = Wire_AdjustOutputs WireLib.Restored = Wire_Restored WireLib.Remove = Wire_Remove WireLib.TriggerOutput = Wire_TriggerOutput WireLib.Link_Start = Wire_Link_Start WireLib.Link_Node = Wire_Link_Node WireLib.Link_End = Wire_Link_End WireLib.Link_Cancel = Wire_Link_Cancel WireLib.Link_Clear = Wire_Link_Clear WireLib.SetPathNames = Wire_SetPathNames WireLib.CreateOutputIterator = Wire_CreateOutputIterator Wire_BuildDupeInfo = WireLib.BuildDupeInfo Wire_ApplyDupeInfo = WireLib.ApplyDupeInfo --backwards logic: set enable to false to show show values on gates instead Wire_EnableGateInputValues = true local function WireEnableInputValues(pl, cmd, args) if ( args[1] ) and ( ( pl:IsAdmin() ) or ( pl:IsSuperAdmin( )() ) ) then if args[1] == "1" or args[1] == 1 then Wire_EnableGateInputValues = true elseif args[1] == "0" or args[1] == 0 then Wire_EnableGateInputValues = false else pl:PrintMessage(HUD_PRINTCONSOLE, "Only takes 0 or 1") end end pl:PrintMessage(HUD_PRINTCONSOLE, "\nWire_EnableGateInputValues = "..tostring(Wire_EnableGateInputValues).."\n") end concommand.Add( "Wire_EnableGateInputValues", WireEnableInputValues ) Wire_FastOverlayTextUpdate = false local function WireFastOverlayTextUpdate(pl, cmd, args) if ( args[1] ) and ( ( pl:IsAdmin() ) or ( pl:IsSuperAdmin( )() ) ) then if args[1] == "1" or args[1] == 1 then Wire_FastOverlayTextUpdate = true elseif args[1] == "0" or args[1] == 0 then Wire_FastOverlayTextUpdate = false else pl:PrintMessage(HUD_PRINTCONSOLE, "Only takes 0 or 1") end end pl:PrintMessage(HUD_PRINTCONSOLE, "\nWire_FastOverlayTextUpdate = "..tostring(Wire_FastOverlayTextUpdate).."\n") end concommand.Add( "Wire_FastOverlayTextUpdate", WireFastOverlayTextUpdate ) Wire_SlowerOverlayTextUpdate = false local function WireSlowerOverlayTextUpdate(pl, cmd, args) if ( args[1] ) and ( ( pl:IsAdmin() ) or ( pl:IsSuperAdmin( )() ) ) then if args[1] == "1" or args[1] == 1 then Wire_SlowerOverlayTextUpdate = true elseif args[1] == "0" or args[1] == 0 then Wire_SlowerOverlayTextUpdate = false else pl:PrintMessage(HUD_PRINTCONSOLE, "Only takes 0 or 1") end end pl:PrintMessage(HUD_PRINTCONSOLE, "\nWire_SlowerOverlayTextUpdate = "..tostring(Wire_SlowerOverlayTextUpdate).."\n") end concommand.Add( "Wire_SlowerOverlayTextUpdate", WireSlowerOverlayTextUpdate ) Wire_DisableOverlayTextUpdate = false local function WireDisableOverlayTextUpdate(pl, cmd, args) if ( args[1] ) and ( ( pl:IsAdmin() ) or ( pl:IsSuperAdmin( )() ) ) then if args[1] == "1" or args[1] == 1 then Wire_DisableOverlayTextUpdate = true elseif args[1] == "0" or args[1] == 0 then Wire_DisableOverlayTextUpdate = false else pl:PrintMessage(HUD_PRINTCONSOLE, "Only takes 0 or 1") end end pl:PrintMessage(HUD_PRINTCONSOLE, "\nWire_DisableOverlayTextUpdate = "..tostring(Wire_DisableOverlayTextUpdate).."\n") end concommand.Add( "Wire_DisableOverlayTextUpdate", WireDisableOverlayTextUpdate ) Wire_ForceDelayOverlayTextUpdate = false local function WireForceDelayOverlayTextUpdate(pl, cmd, args) if ( args[1] ) and ( ( pl:IsAdmin() ) or ( pl:IsSuperAdmin( )() ) ) then if args[1] == "1" or args[1] == 1 then Wire_ForceDelayOverlayTextUpdate = true elseif args[1] == "0" or args[1] == 0 then Wire_ForceDelayOverlayTextUpdate = false else pl:PrintMessage(HUD_PRINTCONSOLE, "Only takes 0 or 1") end end pl:PrintMessage(HUD_PRINTCONSOLE, "\nWire_ForceDelayOverlayTextUpdate = "..tostring(Wire_ForceDelayOverlayTextUpdate).."\n") end concommand.Add( "Wire_ForceDelayOverlayTextUpdate", WireForceDelayOverlayTextUpdate ) --[[Wire_UseOldGateOutputLables = false local function WireUseOldGateOutputLables(pl, cmd, args) if ( args[1] ) and ( ( pl:IsAdmin() ) or ( pl:IsSuperAdmin( )() ) ) then if args[1] == "1" or args[1] == 1 then Wire_UseOldGateOutputLables = true elseif args[1] == "0" or args[1] == 0 then Wire_UseOldGateOutputLables = false else pl:PrintMessage(HUD_PRINTCONSOLE, "Only takes 0 or 1") end end pl:PrintMessage(HUD_PRINTCONSOLE, "\nWire_UseOldGateOutputLables = "..tostring(Wire_UseOldGateOutputLables).."\n") end concommand.Add( "Wire_UseOldGateOutputLables", WireUseOldGateOutputLables )]] -- prevent applyForce+Anti-noclip-based killing contraptions hook.Add("InitPostEntity", "antiantinoclip", function() local ENT = scripted_ents.GetList().rt_antinoclip_handler if not ENT then return end ENT = ENT.t local rt_antinoclip_handler_StartTouch = ENT.StartTouch function ENT:StartTouch(...) if self.speed >= 20 then return end local phys = self.Ent:GetPhysicsObject() if phys:IsValid() and phys:GetAngleVelocity():Length() > 20 then return end rt_antinoclip_handler_StartTouch(self, ...) end --local rt_antinoclip_handler_Think = ENT.Think function ENT:Think() local t = CurTime() local dt = t-self.lastt self.lastt = t local phys = self.Ent:GetPhysicsObject() local pos if phys:IsValid() then pos = phys:LocalToWorld(phys:GetMassCenter()) else pos = self.Ent:GetPos() end self.speed = pos:Distance(self.oldpos)/dt self.oldpos = pos --rt_antinoclip_handler_Think(self, ...) end ENT.speed = 20 ENT.lastt = 0 ENT.oldpos = Vector(0,0,0) end) -- Calls "func", once (Advanced) Duplicator has finished spawning the entity that was copied with the entity id "entid". -- Must be called from an duplicator.RegisterEntityClass or duplicator.RegisterEntityModifier handler. -- Usage: WireLib.PostDupe(entid, function(ent) ... end) function WireLib.PostDupe(entid, func) local CreatedEntities local paste_functions = { [duplicator.Paste] = true, [AdvDupe.Paste] = true, [AdvDupe.OverTimePasteProcess] = true, } -- Go through the call stack to find someone who has a CreatedEntities table for us. local i,info = 1,debug.getinfo(1) while info do if paste_functions[info.func] then for j = 1,20 do local name, value = debug.getlocal(i, j) if name == "CreatedEntities" then CreatedEntities = value break end end break end i = i+1 info = debug.getinfo(i) end -- Nothing found? Too bad... if not CreatedEntities then return end -- Wait until the selected entity has been spawned... local unique = {} timer.Create(unique, 1, 240, function(CreatedEntities, entid, unique, func) local ent = CreatedEntities[entid] if ent then timer.Remove(unique) -- and call the callback func(ent) end end, CreatedEntities, entid, unique, func) end function WireLib.dummytrace(ent) local pos = ent:GetPos() return { FractionLeftSolid = 0, HitNonWorld = true, Fraction = 0, Entity = ent, HitPos = pos, HitNormal = Vector(0,0,0), HitBox = 0, Normal = Vector(1,0,0), Hit = true, HitGroup = 0, MatType = 0, StartPos = pos, PhysicsBone = 0, WorldToLocal = Vector(0,0,0), } end
gpl-3.0
tehran980/tele_HSN
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
resistor58/deaths-gmod-server
wire/lua/entities/gmod_wire_egp/lib/objects/line.lua
1
1111
-- Author: Divran local Obj = EGP:NewObject( "Line" ) Obj.w = nil Obj.h = nil Obj.x2 = 0 Obj.y2 = 0 Obj.size = 1 Obj.verticesindex = { { "x", "y" }, { "x2", "y2" } } Obj.Draw = function( self ) if (self.a>0) then surface.SetDrawColor( self.r, self.g, self.b, self.a ) EGP:DrawLine( self.x, self.y, self.x2, self.y2, self.size ) end end Obj.Transmit = function( self ) EGP.umsg.Short( self.x ) EGP.umsg.Short( self.y ) EGP.umsg.Short( self.x2 ) EGP.umsg.Short( self.y2 ) EGP.umsg.Short( self.size ) EGP.umsg.Short( self.parent ) EGP:SendMaterial( self ) EGP:SendColor( self ) end Obj.Receive = function( self, um ) local tbl = {} tbl.x = um:ReadShort() tbl.y = um:ReadShort() tbl.x2 = um:ReadShort() tbl.y2 = um:ReadShort() tbl.size = um:ReadShort() tbl.parent = um:ReadShort() EGP:ReceiveMaterial( tbl, um ) EGP:ReceiveColor( tbl, self, um ) return tbl end Obj.DataStreamInfo = function( self ) return { x = self.x, y = self.y, x2 = self.x2, y2 = self.y2, r = self.r, g = self.g, b = self.b, a = self.a, size = self.size, parent = self.parent } end
gpl-3.0
tkdrob/Battle-Tag
Packages/CaptureMax/Data/Script/ByteCode/UACaptureMax.ByteCode.lua
1
6163
byteCode = { 0x13, 0x53, 0x43, 0x30, 0x35, 0x00, 0x00, 0x53, 0x44, 0x31, 0x38, 0x00, 0x00, 0x53, 0x47, 0x30, 0x37, 0x00, 0x00, 0x53, 0x43, 0x30, 0x33, 0x00, 0x00, 0x41, 0x53, 0x48, 0x54, 0x00, 0x00, 0x53, 0x57, 0x35, 0x36, 0x00, 0x00, 0x53, 0x57, 0x32, 0x32, 0x00, 0x00, 0x53, 0x43, 0x30, 0x38, 0x00, 0x00, 0x53, 0x43, 0x30, 0x32, 0x00, 0x00, 0x53, 0x57, 0x31, 0x32, 0x00, 0x00, 0x53, 0x57, 0x34, 0x32, 0x00, 0x00, 0x41, 0x52, 0x41, 0x4d, 0x00, 0x00, 0x53, 0x43, 0x30, 0x39, 0x00, 0x00, 0x41, 0x4d, 0x45, 0x44, 0x00, 0x00, 0x53, 0x43, 0x30, 0x37, 0x00, 0x00, 0x53, 0x44, 0x30, 0x33, 0x00, 0x00, 0x41, 0x4f, 0x55, 0x54, 0x00, 0x00, 0x41, 0x47, 0x42, 0x31, 0x00, 0x00, 0x41, 0x47, 0x42, 0x32, 0x00, 0x00, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x01, 0xcc, 0x02, 0xcc, 0x02, 0xcc, 0x02, 0xcc, 0x02, 0xcc, 0x00, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x00, 0xcc, 0x03, 0xcc, 0x03, 0xcc, 0x00, 0xcc, 0x00, 0xd0, 0x00, 0x55, 0xcf, 0x00, 0x04, 0x00, 0xc4, 0x0a, 0x01, 0x00, 0x00, 0x03, 0x1c, 0xcf, 0x01, 0x02, 0x00, 0xcf, 0x00, 0x03, 0x00, 0xc4, 0x19, 0x01, 0x00, 0x06, 0x01, 0x04, 0xce, 0x00, 0x19, 0x00, 0x04, 0xce, 0x01, 0x01, 0x01, 0xcd, 0x00, 0x00, 0x00, 0x2d, 0xcf, 0x01, 0x03, 0x00, 0xcf, 0x00, 0x02, 0x00, 0xc4, 0x0c, 0x01, 0x00, 0x14, 0x01, 0x18, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0xcd, 0x00, 0x01, 0x00, 0xce, 0x00, 0x02, 0x00, 0x08, 0xcd, 0x00, 0x01, 0x01, 0xce, 0x00, 0x02, 0x01, 0x05, 0xd6, 0xce, 0x01, 0x01, 0x01, 0xd0, 0x01, 0x1d, 0xc0, 0x02, 0x00, 0x0d, 0xc0, 0x01, 0x00, 0x0c, 0xc1, 0x02, 0xc4, 0x0e, 0x01, 0x00, 0x02, 0x02, 0x04, 0xc0, 0x13, 0x00, 0x12, 0x00, 0xc0, 0x0a, 0x01, 0x00, 0x00, 0xc3, 0x00, 0xd0, 0x02, 0x17, 0xc0, 0x00, 0x00, 0x0b, 0xc4, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x04, 0xc0, 0x14, 0x00, 0x12, 0x00, 0xc0, 0x0a, 0x01, 0x00, 0x01, 0xc3, 0x00, 0xd0, 0x03, 0x10, 0xc1, 0x19, 0xd0, 0x01, 0xd0, 0x02, 0xc0, 0x13, 0x01, 0x00, 0x32, 0xc0, 0x14, 0x01, 0x00, 0x32, 0xd0, 0x04, 0x23, 0xc5, 0x00, 0x00, 0xca, 0x1e, 0x01, 0xc4, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0xc1, 0x00, 0xd3, 0x1e, 0xc0, 0x0a, 0x01, 0x00, 0x01, 0x00, 0xc4, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0xc3, 0x01, 0x00, 0xd0, 0x00, 0xd0, 0x05, 0x11, 0xc4, 0x12, 0x00, 0x10, 0x02, 0x03, 0xc5, 0x01, 0x01, 0x03, 0xc5, 0x01, 0x02, 0xc0, 0x04, 0x00, 0x12, 0xd2, 0x02, 0x00, 0x1e, 0x0c, 0x1c, 0xc9, 0x64, 0xc0, 0x03, 0x01, 0x00, 0x00, 0xc4, 0x11, 0x01, 0x00, 0x00, 0x02, 0x02, 0xdc, 0x10, 0x00, 0xc0, 0x19, 0x00, 0x17, 0xc1, 0x10, 0xc5, 0x00, 0x03, 0xd0, 0x03, 0xc7, 0x00, 0x01, 0x32, 0x01, 0x33, 0xc4, 0x06, 0x01, 0x00, 0x07, 0x01, 0x2b, 0xc0, 0x0a, 0x01, 0x00, 0x00, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x00, 0x19, 0xc4, 0x0c, 0x01, 0x00, 0x13, 0x00, 0x02, 0xcb, 0x04, 0x00, 0xc1, 0x01, 0xc5, 0x01, 0x05, 0xc4, 0x07, 0x00, 0x10, 0x03, 0x02, 0xd4, 0x01, 0x00, 0xc6, 0x00, 0xd0, 0x00, 0xc5, 0x00, 0x06, 0x00, 0x02, 0x69, 0xc8, 0x15, 0xc4, 0x15, 0x01, 0x00, 0x01, 0x02, 0x5c, 0xde, 0x12, 0xc4, 0x07, 0x00, 0x10, 0x03, 0x2e, 0xc4, 0x12, 0x01, 0x00, 0x04, 0x02, 0x0b, 0xd9, 0x12, 0xc4, 0x12, 0x00, 0x13, 0x03, 0x02, 0xc3, 0x03, 0x00, 0x00, 0xc4, 0x06, 0x01, 0x00, 0x06, 0x01, 0x13, 0xc4, 0x12, 0x01, 0x00, 0x03, 0x02, 0x0b, 0xd9, 0x12, 0xc4, 0x12, 0x00, 0x14, 0x03, 0x02, 0xc3, 0x04, 0x00, 0x00, 0x00, 0x00, 0xc4, 0x12, 0x01, 0x00, 0x05, 0x02, 0x1d, 0xd9, 0x12, 0xc4, 0x12, 0x00, 0x07, 0x02, 0x02, 0xd0, 0x05, 0x00, 0xc4, 0x12, 0x00, 0x08, 0x02, 0x02, 0xd0, 0x05, 0x00, 0xc4, 0x12, 0x00, 0x09, 0x02, 0x02, 0xd0, 0x05, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x07, 0x0b, 0x02, 0xd0, 0x04, 0x00, 0x1c, 0xc4, 0x06, 0x01, 0x00, 0x06, 0x01, 0x12, 0xc5, 0x00, 0x08, 0xc2, 0x0a, 0xc4, 0x0a, 0x01, 0x00, 0x01, 0x00, 0x05, 0xc0, 0x0a, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x09, 0x2b, 0xc4, 0x01, 0x01, 0x00, 0x00, 0x02, 0x13, 0xc4, 0x02, 0x01, 0x00, 0x00, 0x00, 0x0b, 0xc1, 0x02, 0xc5, 0x00, 0x09, 0xc0, 0x01, 0x00, 0x0c, 0xd0, 0x00, 0x00, 0x00, 0xc4, 0x07, 0x01, 0x00, 0x08, 0x00, 0x06, 0xd5, 0x00, 0xd4, 0x01, 0xd5, 0x01, 0x00, 0xc2, 0x03, 0x0c, 0x02, 0xd0, 0x00, 0x0d, 0x04, 0xce, 0x01, 0x01, 0x01, 0x0f, 0x37, 0xc4, 0x06, 0x01, 0x00, 0x00, 0x02, 0x02, 0xdd, 0x01, 0x00, 0xc4, 0x07, 0x01, 0x00, 0x08, 0x00, 0x04, 0xc0, 0x04, 0x00, 0x07, 0x00, 0xc4, 0x04, 0x01, 0x00, 0x0a, 0x02, 0x0a, 0xc4, 0x07, 0x00, 0x1a, 0x01, 0x03, 0xc5, 0x01, 0x01, 0x00, 0x00, 0xc4, 0x07, 0x00, 0x10, 0x02, 0x02, 0xd5, 0xff, 0x02, 0xd5, 0x00, 0xc0, 0x1a, 0x00, 0x07, 0xc7, 0x03, 0x00, 0x11, 0x0c, 0x07, 0xc5, 0x00, 0x0a, 0xd5, 0x01, 0xcb, 0x0b, 0x0d, 0x02, 0xd0, 0x01, 0x0b, 0x02, 0xd0, 0x04, 0xc7, 0x04, 0x00, 0x14, 0x0c, 0x07, 0xc5, 0x00, 0x0c, 0xd5, 0x01, 0xcb, 0x0d, 0x0d, 0x02, 0xd0, 0x02, 0x0b, 0x05, 0xd0, 0x02, 0xdf, 0xd0, 0x04, 0xc7, 0x05, 0x00, 0x33, 0x0c, 0x08, 0xc5, 0x00, 0x0c, 0xdf, 0xc0, 0x16, 0x00, 0x0f, 0x09, 0x19, 0xc4, 0x16, 0x01, 0x00, 0x02, 0x01, 0x08, 0xc5, 0x01, 0x0e, 0xd7, 0xd4, 0x00, 0xd0, 0x03, 0x09, 0xc1, 0x16, 0xcd, 0x00, 0x16, 0x00, 0xc5, 0x00, 0x08, 0x0b, 0x0c, 0xc4, 0x18, 0x01, 0x00, 0x01, 0x02, 0x04, 0xc0, 0x16, 0x00, 0x0f, 0x00, 0xc7, 0x01, 0x00, 0x55, 0x0c, 0x25, 0xc5, 0x01, 0x0f, 0xc0, 0x04, 0x01, 0x00, 0x0a, 0xd5, 0x00, 0xc4, 0x19, 0x01, 0x00, 0x00, 0x02, 0x02, 0xd8, 0x10, 0x11, 0xca, 0x1e, 0x00, 0xd4, 0xff, 0xc4, 0x10, 0x01, 0x00, 0x00, 0x02, 0x02, 0xd8, 0x11, 0x02, 0xd8, 0x12, 0x02, 0x2c, 0xc8, 0x15, 0xc4, 0x15, 0x01, 0x00, 0x01, 0x02, 0x1f, 0xde, 0x12, 0xc4, 0x19, 0x01, 0x00, 0x00, 0x00, 0x15, 0xc4, 0x12, 0x01, 0x00, 0x05, 0x02, 0x0d, 0xd9, 0x12, 0xc4, 0x12, 0x00, 0x10, 0x02, 0x04, 0xd5, 0x0a, 0xc3, 0x05, 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x07, } return byteCode
mit
Salada/slua
build/luajit-2.0.4/src/jit/dis_x86.lua
89
29330
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = format("0x%08x", imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64_(code, addr, out) local ctx = create_(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end local function disass64_(code, addr, out) create64_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64_(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. module(...) create = create_ create64 = create64_ disass = disass_ disass64 = disass64_ regname = regname_ regname64 = regname64_
mit
Aico/mudlet
src/old_mudlet-lua/lua/geyser/GeyserTests.lua
22
5965
-------------------------------------- -- -- -- The Geyser Layout Manager by guy -- -- -- -------------------------------------- -- TESTS FOR GEYSER -- --- Test labels. Creates 101 Labels of varying hue and transparency. function Geyser.testLabels() labelTestContainer = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="labelTestContainer"}) for i=0,90,10 do for j=0,90,10 do local myName = "TestLabel_" .. i .. "_" .. j local l = Geyser.Label:new({ name = myName, x = i .. "%", y = j .. "%", width = "8%", height = "8%", message = myName, fgColor = "white"}, labelTestContainer) l:setColor(i,j,100, i*j/8100 * 128 + 127) end end Geyser.Label:new({ name = "Clickable", fontSize = 22, message = [[<p style="font-size:22pt"><center>Click me</center></p>]], x = "53%", y = "53%", width = "-40px", height = "-3c", backgroundAlpha = 240, callback = "echo", args = "You Clicked Me!!\n"}, labelTestContainer) end --- Test gauges. Creates 100 gauges of varying fullness. function Geyser.testGauges() gaugeTestContainer = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="gaugeTestContainer"}) for i=0,90,10 do for j=0,90,10 do local myName = "TestGauge_" .. i .. "_" .. j local g = Geyser.Gauge:new({name = myName, x = i .. "%", y = j .. "%", width = "9%", height = "9%", message = myName, fgColor = "red",}, gaugeTestContainer) g:setValue(1.0 * i) --g:setText(myName) end end end --- Used by Geyser.demo1(). Sorry about the namespace polution, -- but callbacks can't use functions contained in a table. Anyway, -- it just echoes some status info to the two miniconsoles. function demoCallback1 (value) local g1 = geyserDemoContainer.windowList.myGauge local g2 = geyserDemoContainer.windowList.myGoofyGauge local c1 = geyserDemoContainer.windowList["console 1"] local c2 = geyserDemoContainer.windowList["console 2"] g1:setValue((g1.value - value) % 100) g2:setValue((g2.value - 2*value) % 100) local v1 = tostring(g1.value) local v2 = tostring(g2.value) c1:decho(string.format("<90,90,%d> You are at %d \n", v1, v1)) c2:decho(string.format("<90,%d,%d> You are at %d \n", 255-v2, v2, v2)) end local myDemoState = 0 --- Used by Geyser.demo1(). It moves the location of the -- container window. Look how easy it is to shift around all those -- gui elements! function demoCallback2 () if myDemoState == 0 then geyserDemoContainer:resize(nil, "50%") geyserDemoContainer:move("-90c") myDemoState = 1 else geyserDemoContainer:resize(nil, "100%") geyserDemoContainer:move("-42c") myDemoState = 0 end end --- This demonstrates some of the neat features in Geyser. function Geyser.demo1() ---------------------------------------- -- 1. Create a container on the left side of the screen wide -- enough for 40 characters geyserDemoContainer = Geyser.Container:new( { x = "-42c", y = "0px", width = "40c", height = "100%", name = "myContainer"}) ---------------------------------------- -- 2. Add a miniconsole to the top of the container, -- full width, with 20 lines of text local console1 = Geyser.MiniConsole:new( { x = "0px", y = "0px", width = "100%", height = "20c", name = "console 1"}, geyserDemoContainer) -- add console1 to container directly console1:setColor(80,40,20,255) console1:echo("Go ahead - resize the Mudlet window\n") ---------------------------------------- -- 3. Add two gauges and a clickable label just below the -- miniconsole local g1 = Geyser.Gauge:new( { x = "0px", y = console1.height, width = "60%", height = "4c", orientation = "batty", color = "violet", name = "myGauge"}) g1:setValue(77) geyserDemoContainer:add(g1) -- add gauge after creation local g2 = Geyser.Gauge:new( { x = "10%", y = console1.height, width = "50%", height = "4c", orientation = "goofy", name = "myGoofyGauge"}, geyserDemoContainer) -- add gauge directly g2:setValue(55) g2:setColor("cyan") local label1 = Geyser.Label:new( { x = g1.width, y = console1.height, width = "40%", height = "4c", name = "label with callback", callback = "demoCallback1", args=5, fontSize = 8, fgColor = "white", message = "Click me"}) geyserDemoContainer:add(label1) -- you know the drill ---------------------------------------- -- 4. Add another miniconsole below the gauge that extends -- to the bottom of the screen and wraps at 40 characters and -- another clickable label. echo("adfa\n") local console2 = Geyser.MiniConsole:new({ x = "0px", y = "24c", width = "100%", height = "-0px", name = "console 2", wrapAt = 40, color = "<10,20,40>",}, geyserDemoContainer) -- add console2 to geyserDemoContainer directly console2:echo("Vampire Gauges!\n") local label2 = Geyser.Label:new( { x = g1.width, y = "60%", width = "40%", height = "4c", name = "label with another callback and a long name!", callback = "demoCallback2", message = [[<center>and me</center>]]}) geyserDemoContainer:add(label2) -- same here ---------------------------------------- -- 5. hide all windows just created geyserDemoContainer:hide() ---------------------------------------- -- 6. now show them again geyserDemoContainer:show() end
gpl-2.0
acoret/UnBot
UnBot.lua
1
2943
--################################### --# # --# UnCode Bot # --# # --################################### --env __debug=true if __debug then function print(x) weechat.print(debug_buffer,x)end end --hook #hook table contain hook={} r_name={} e_name={} fuc={} fuc["unknow"]=function(buffer,username) weechat.command(buffer,"/msg " .. username .." Command unfound") end fuc["update"]=function (buffer,username) os.execute("/home/shared/UnBot/update.sh") weechat.command(buffer,"/msg "..username.." updated!") weechat.command(buffer,"/lua reload UnBot") end fuc["ghc"]=function (buffer,username,args) local filename=string.match(args,"(%s+)") if not filename then return end os.execute("cd /home/shared/UnBot/haskell/;ghc "..filename.." >> result.out") local file=io.open("/home/shared/UnBot/haskell/result.out") local str=file:read("*a") weechat.command(buffer,"/msg "..username.." "..str) end function checkandrun(data, signal, signal_data) nick = weechat.info_get("irc_nick_from_host", signal_data) buffer =weechat.info_get("irc_buffer" , signal_data) server = string.match(signal,"(.-),") channel = string.match(signal_data,"(#[^ ]+)") local mynick = weechat.info_get("irc_nick", server) if not channel then return weechat.WEECHAT_RC_OK end local ma_nick,command=string.match(signal_data,"[^ ]+ [^ ]+ #[^ ]+ :([%a%d_]+): -@([^ ]+)") local _,_,args=string.match(signal_data,"[^ ]+ [^ ]+ #[^ ]+ :([%a%d_]+): -@([^ ]+) ([^ ]+)") weechat.print(debug_buffer,signal_data) if not ma_nick then return end if not command then return end if not args then args='' end if __debug then if ma_nick==mynick then weechat.print(debug_buffer,"nick:".. nick.." command:"..command.." args:"..args) end end buffer = weechat.info_get("irc_buffer",server..","..channel) if ma_nick==mynick then if command then if fuc[command] then fuc[command](buffer,nick,args) else fuc["unknow"](buffer,nick,args) end end end end function respond(data,buffer,args) lastname=r_name[buffer] if not lastname then weechat.print(buffer,"You got no friend!haha") return weechat.WEECHAT_RC_OK end weechat.command(buffer,"/say "..lastname..":"..args) return weechat.WEECHAT_RC_OK end --debug#for debug function buffer_input_cb(data,buffer,input_data) weechat.print(buffer,input_data) local tmp=load(input_data) if tmp then tmp() end return weechat.WEECHAT_RC_OK end function buffer_close_cb(data,buffer) return weechat.WEECHAT_RC_OK end --Register weechat.register("UnBot","acoret@126.com","1.0","GPL","Unbot","","UTF-8") weechat.hook_signal("*,irc_in2_privmsg", "checkandrun","") if __debug then debug_buffer=weechat.buffer_new("debug_respond", "buffer_input_cb","","buffer_close_cb","") weechat.buffer_set(debug_buffer,"title","debug for respond") weechat.buffer_set(debug_buffer, "localvar_set_no_log", "1") end
mit
zhusz/ICCV17-fashionGAN
ih1/train.lua
1
9299
require 'nngraph' require 'cunn' require 'cudnn' require 'hdf5' require 'image' require 'optim' require 'paths' local matio = require 'matio' train_ind = matio.load('../data_release/benchmark/ind.mat','train_ind'):view(-1) local dispSurrogate = dofile('../codes_lua/dispSurrogate.lua') local disp = require 'display' local getNet = dofile('../codes_lua/getNet.lua') torch.setdefaulttensortype('torch.FloatTensor') local theme = 'ih1' assert(theme == 'ih1') local config = dofile('./config_ih1.lua') local lambda = 100 local G,D = dofile('./net_graph_ih1.lua') local h5file = hdf5.open('../data_release/supervision_signals/G2.h5', 'r') local ih = h5file:read('/ih'):all() ih = ih:permute(1,2,4,3) local ih_mean = h5file:read('/ih_mean'):all() ih_mean = ih_mean:view(1,3,128,128) ih_mean = ih_mean:permute(1,2,4,3) local b_ = h5file:read('/b_'):all() b_ = b_:permute(1,2,4,3) local n_file = ih:size(1) ---------------------------------------------------------- local text = matio.load('../data_release/test_phase_inputs/encode_hn2_rnn_100_2_full.mat', 'hn2') text = text:contiguous() ---------------------------------------------------------- config.lr = 0.0002 -- * 1e2 * 2.5 config.beta1 = 0.5 local criterion = nn.BCECriterion() local criterionAE = nn.AbsCriterion() local optimStateG = { learningRate = config.lr, beta1 = config.beta1, } local optimStateD = { learningRate = config.lr, beta1 = config.beta1, } local nz = config.nz local input = torch.Tensor(config.batchSize, config.n_c, config.win_size, config.win_size) local condition = torch.Tensor(config.batchSize, config.n_condition, config.win_size, config.win_size) -- zhuzhu print(nz) local noise = torch.Tensor(config.batchSize, nz, 1, 1) -- zhuzhunoise local label = torch.Tensor(config.batchSize, 1, 1, 1) local encode = torch.Tensor(config.batchSize, config.nt_input, 1, 1) local errD, errG, errL1 cutorch.setDevice(1) input = input:cuda(); noise = noise:cuda(); label = label:cuda(); condition = condition:cuda(); encode = encode:cuda() -- zhuzhunoise local input_record, condition_record ---------------------------------------------------------- local input_wrong = torch.Tensor(config.batchSize, config.n_c, config.win_size, config.win_size) local condition_wrong = torch.Tensor(config.batchSize, config.n_condition, config.win_size, config.win_size) input_wrong = input_wrong:cuda(); condition_wrong = condition_wrong:cuda() ---------------------------------------------------------- if pcall(require, 'cudnn') then require 'cudnn' cudnn.benchmark = true cudnn.convert(G, cudnn) cudnn.convert(D, cudnn) end D:cuda(); G:cuda(); criterion:cuda(); criterionAE:cuda() local parametersD, gradParametersD = D:getParameters() local parametersG, gradParametersG = G:getParameters() ----------- zhuzhu ------------ local cb = {torch.Tensor{3,2,1,1,2,3,2}, torch.Tensor{2,3,3,2,1,1,2}, torch.Tensor{1,1,2,3,3,2,2}} for i = 1,config.n_condition do cb[i] = cb[i] * 0.25 end local H = torch.Tensor{0.0030,0.0133,0.0219,0.0133,0.0030,0.0133,0.0596,0.0983,0.0596,0.0133,0.0219,0.0983,0.1621,0.0983,0.0219,0.0133,0.0596,0.0983,0.0596,0.0133,0.0030,0.0133,0.0219,0.0133,0.0030}:view(5,5) ------------------------------- local train_size = train_ind:size(1) local simple_sample = function() local ind = torch.randperm(train_size):narrow(1,1,config.batchSize) local ind_wrong = torch.Tensor(config.batchSize) for i = 1,config.batchSize do ind_wrong[i] = (ind[i] + math.random(train_size-1) - 1) % train_size + 1; end for i = 1,config.batchSize do ind[i] = train_ind[ind[i]] end for i = 1,config.batchSize do ind_wrong[i] = train_ind[ind_wrong[i]] end noise:normal(0,1) -- zhuzhunoise for i = 1,config.batchSize do input[{{i},{},{},{}}] = ih[{{ind[i]},{},{},{}}] local t = b_[{{ind[i]},{1},{},{}}] for j = 1,config.n_condition do local u = torch.Tensor(1,1,config.win_size,config.win_size):zero() for k = 1,config.n_map_all do u[t:eq(k%config.n_map_all)] = cb[j][k] end -- do blurring toward u local v = image.convolve(u:squeeze():float(), H:float(), 'same'):contiguous() condition[{{i},{j},{},{}}] = v:view(1,1,config.win_size,config.win_size) end encode[{{i},{},{},{}}] = text[{{ind[i]},{}}]:view(1, config.nt_input, 1, 1) end condition = condition - 0.5; -- zero mean for i = 1,config.batchSize do input_wrong[{{i},{},{},{}}] = ih[{{ind_wrong[i]},{},{},{}}] local t = b_[{{ind_wrong[i]},{1},{},{}}] for j = 1,config.n_condition do local u = torch.Tensor(1,1,config.win_size,config.win_size):zero() for k = 1,config.n_map_all do u[t:eq(k%config.n_map_all)] = cb[j][k] end -- do blurring torward u local v = image.convolve(u:squeeze():float(), H:float(), 'same'):contiguous() condition_wrong[{{i},{j},{},{}}] = v:view(1,1,config.win_size,config.win_size) end end condition_wrong = condition_wrong - 0.5 do return end end local real_label = 1 local fake_label = 0 local epoch_tm = torch.Timer() local tm = torch.Timer() local data_tm = torch.Timer() local errD_real, errD_wrong, errD_fake local fDx = function(x) D:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) G:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) -- zhuzhu gradParametersD:zero() -- train with real simple_sample() local fake = G:forward{noise, encode, condition} -- zhuzhuf2A input_record = input:clone() condition_record = condition:clone() -- local real = data:getBatch() -- input:copy(real) label:fill(real_label) local output = D:forward{input, encode, condition} -- errD_real = criterion:forward(output, label) local de_do = criterion:backward(output, label) D:backward({input, encode, condition}, de_do) -- ------------------------------------------------------ label:fill(fake_label) output = D:forward{input_wrong, encode, condition_wrong} errD_wrong = config.lambda_mismatch * criterion:forward(output, label) de_do = criterion:backward(output, label) D:backward({input_wrong, encode, condition_wrong}, de_do) ------------------------------------------------------ -- local fake = G:forward{noise, condition} -- -- zhuzhunoise input:copy(fake) label:fill(fake_label) output = D:forward{input, encode, condition} -- errD_fake = config.lambda_fake * criterion:forward(output, label) de_do = criterion:backward(output, label) D:backward({input, encode, condition}, de_do) -- errD = (errD_real + errD_wrong + errD_fake) / 2 -- zhuzhu return errD, gradParametersD end local fGx = function(x) D:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) G:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) -- zhuzhu gradParametersG:zero() local output = D.output -- zhuzhuf2A label:fill(real_label) errG = criterion:forward(output, label) local de_do = criterion:backward(output, label) local de_dg = D:updateGradInput({input, encode, condition}, de_do) -- -------- zhuzhu -------- errL1 = criterionAE:forward(input, input_record:cuda()) local df_do_AE = criterionAE:backward(input, input_record:cuda()) ------------------------ G:backward({noise,encode,condition}, de_dg[1] + df_do_AE:mul(lambda)) -- -- zhuzhunoise return errG, gradParametersG end -- training -- zhuzhunoise local vis_factor = math.ceil(16 / config.batchSize) local vis_size = config.batchSize * vis_factor local noise_vis = torch.Tensor(vis_size, nz, 1,1) noise_vis = noise_vis:cuda() noise_vis:normal(0,1) local condition_vis = torch.Tensor(vis_size, config.n_condition, config.win_size, config.win_size) condition_vis = condition_vis:cuda() local encode_vis = torch.Tensor(vis_size, config.nt_input, 1, 1) encode_vis = encode_vis:cuda() for iter = 1, 1e9 do optim.adam(fDx, parametersD, optimStateD) optim.adam(fGx, parametersG, optimStateG) if iter % 20 == 0 then print(('Iter %d: ErrD %.5f (ErrD_real %.5f, ErrD_wrong %.5f, ErrD_fake %.5f), ErrG %.5f, ErrL1 %.5f.'):format(iter,errD,errD_real,errD_wrong,errD_fake,errG, errL1)) end if iter == 1 then for i = 1, vis_size do condition_vis[{{i},{},{},{}}] = condition[{{1},{},{},{}}] end for i = 1, vis_size do encode_vis[{{i},{},{},{}}] = text[{{(i-1)%4+1},{}}]:view(1,100,1,1) end end local base = 700 local fake_vis = G:forward{noise_vis, encode_vis, condition_vis} if iter % 20 == 0 then dispSurrogate(fake_vis:type('torch.FloatTensor') + ih_mean:repeatTensor(vis_size, 1,1,1), 3+base, 'fake') dispSurrogate(input_record:type('torch.FloatTensor') + ih_mean:repeatTensor(config.batchSize, 1,1,1), 4+base, 'real') dispSurrogate(condition_record:type('torch.FloatTensor'), 5+base, 'condition') end if iter == 1 or iter % 10000 == 0 then local net = {} net.G = G net.D = D torch.save('./' .. theme .. '/' .. theme .. '_'.. tostring(iter) .. '.t7', net) end end
bsd-3-clause
ellipticaldoor/a_sea_of_nothing
game/lua/player.lua
1
1820
player = {} function player.load() selector = love.graphics.newImage("images/selector.png"); selector_x, selector_y = 0, 0 moveplayer = true whale_cell_x, whale_cell_y = 3, 2 whale_x, whale_y = 320/2+320*whale_cell_x, 240/2+240*whale_cell_y player_x, player_y = 0, 0 end function player.draw() end function player.math(dt) if moveplayer == false then local x_or_y = math.random(0,1) local move_whale = true if x_or_y == 0 then if whale_cell_x == 0 then whale_cell_x = whale_cell_x + 1 move_whale = false end if whale_cell_x == 3 then whale_cell_x = whale_cell_x - 1 move_whale = false end if whale_cell_x ~= 0 and whale_cell_x ~=3 and move_whale == true then local left_or_right = math.random(0,1) if left_or_right == 0 then whale_cell_x = whale_cell_x - 1 else whale_cell_x = whale_cell_x + 1 end end else if whale_cell_y == 0 then whale_cell_y = whale_cell_y + 1 move_whale = false end if whale_cell_y == 2 then whale_cell_y = whale_cell_y - 1 move_whale = false end if whale_cell_y ~= 0 and whale_cell_y ~=3 and move_whale == true then local up_or_down = math.random(0,1) if up_or_down == 0 then whale_cell_y = whale_cell_y - 1 else whale_cell_y = whale_cell_y + 1 end end end whale_x, whale_y = 320/2+320*whale_cell_x, 240/2+240*whale_cell_y moveplayer = true end if level == 1 then if player_x == whale_cell_x and player_y == whale_cell_y then player_x, player_y = 0, 0 selector_x, selector_y = 0, 0 whale_cell_x, whale_cell_y = 3, 2 whale_x, whale_y = 320/2+320*whale_cell_x, 240/2+240*whale_cell_y level = 2 end end end function UPDATE_PLAYER(dt, key) player.math(dt) --player.move(key) end function DRAW_PLAYER() player.draw() end
gpl-2.0
tkdrob/Battle-Tag
Data/Script/Lua/UTMain.lua
1
2439
--[[-------------------------------------------------------------------------- -- -- File: UTMain.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: April 21, 2010 -- ------------------------------------------------------------------------------ -- -- Description: ... -- ----------------------------------------------------------------------------]] REG_FORCEREVISION = false -- set to true in order to force all banks + firmware revision updates on the guns REG_FIRSTTIME = false -- override (cf. UTGame.settings.registers.firstTime) REG_TRACKING = true REG_MAJORREVISION = 2 -- firmware revision, updates are forced when major revision is changed REG_MINORREVISION = 0 REG_BUILD = 456 -- 101354 REG_BUILDBETA = "" IS_MAJORREVISION = 1 -- installshield revision IS_MINORREVISION = 2 print("appdata: " .. REG_USERAPPFOLDER) print("installshield revision: " .. IS_MAJORREVISION .. "." .. IS_MINORREVISION) print("firmware revision: " .. REG_MAJORREVISION .. "." .. REG_MAJORREVISION) -- debug intel GEAR_COMPILE_PLATFORMS = { [GEAR_PLATFORM_WIN32] = "GEAR_PLATFORM_WIN32", [GEAR_PLATFORM_XENON] = "GEAR_PLATFORM_XENON", Str = { [GEAR_PLATFORM_WIN32] = "win32", } } GEAR_COMPILE_TARGETS = { [GEAR_COMPILE_RELEASE] = "GEAR_COMPILE_RELEASE", [GEAR_COMPILE_DEBUG] = "GEAR_COMPILE_DEBUG", [GEAR_COMPILE_RETAIL] = "GEAR_COMPILE_RETAIL", Str = { [GEAR_COMPILE_RELEASE] = "release", [GEAR_COMPILE_DEBUG] = "debug", [GEAR_COMPILE_RETAIL] = "retail", } } print("platform: " .. GEAR_COMPILE_PLATFORMS[GEAR_CFG_PLATFORM] .. ", target: " .. GEAR_COMPILE_TARGETS[GEAR_CFG_COMPILE]) --[[ Dependencies ----------------------------------------------------------]] -- scripts path = (path or "") .. ";base:script/lua/?.lua" .. ";base:script/lua/classes/?.lua" -- libraries TARGET = GEAR_COMPILE_PLATFORMS.Str[GEAR_CFG_PLATFORM] .. GEAR_COMPILE_TARGETS.Str[GEAR_CFG_COMPILE] .. "dll" path = path .. ";game:../../engine/quartz/bin/?." .. TARGET .. ".dll" path = path .. ";game:../../engine/quartz/bin/ubitoys.?." .. TARGET .. ".dll" require "UTClass" require "UTApplication" if (not GEAR_CFG_COMPILE == GEAR_COMPILE_RETAIL) then -- debug require "UTStrict" end
mit
joehanchoi/hammerspoon
extensions/doc/init.lua
3
14597
--- === hs.doc === --- --- Create documentation objects for interactive help within Hammerspoon --- --- The documentation object created is a table with tostring metamethods allowing access to a specific functions documentation by appending the path to the method or function to the object created. --- --- From the Hammerspoon console: --- --- doc = require("hs.doc").fromRegisteredFiles() --- doc.hs.application --- --- Results in: --- Manipulate running applications --- --- [submodules] --- hs.application.watcher --- --- [subitems] --- hs.application:activate([allWindows]) -> bool --- hs.application:allWindows() -> window[] --- ... --- hs.application:visibleWindows() -> win[] --- --- By default, the internal core documentation and portions of the Lua 5.3 manual, located at http://www.lua.org/manual/5.3/manual.html, are already registered for inclusion within this documentation object, but you can register additional documentation from 3rd party modules with `hs.registerJSONFile(...)` or limit the documentation to a single specific file with `hs.fromJSONFile(...)`. local module = {} -- private variables and methods ----------------------------------------- local json = require("hs.json") local fs = require("hs.fs") local fnutils = require("hs.fnutils") local sortFunction = function(m,n) -- sort function so lua manual toc sorts correctly if m:match("^_%d") and n:match("^_%d") then local a, b = fnutils.split(m:match("^_([^%s]+)"), "_"), fnutils.split(n:match("^_([^%s]+)"), "_") if tonumber(a[1]) ~= tonumber(b[1]) then return tonumber(a[1]) < tonumber(b[1]) elseif a[2] == nil then return true elseif b[2] == nil then return false elseif tonumber(a[2]) ~= tonumber(b[2]) then return tonumber(a[2]) < tonumber(b[2]) elseif a[3] == nil then return true elseif b[3] == nil then return false else return tonumber(a[3]) < tonumber(b[3]) end else return m < n end end local function item_tostring(item) return item[2] .. ": " .. item[1] .. "\n\n" .. item[3] .. "\n" end local function group_tostring(group) local str = group.__doc .. "\n\n" str = str .. "[submodules]\n" for name, item in fnutils.sortByKeys(group, sortFunction) do if name ~= '__doc' and name ~= '__name' and getmetatable(item) == getmetatable(group) then str = str .. item.__name .. "\n" end end str = str .. "\n" .. "[subitems]\n" for name, item in fnutils.sortByKeys(group, sortFunction) do if name ~= '__doc' and name ~= '__name' and getmetatable(item) ~= getmetatable(group) then str = str .. item[1] .. "\n" end end return str .. "\n" end local function doc_tostring(doc) local str = '[modules]\n' for name, group in fnutils.sortByKeys(doc, sortFunction) do str = str .. group.__name .. '\n' end return str end local group_metatable = {__tostring = group_tostring} local item_metatable = {__tostring = item_tostring} local internalBuild = function(rawdocs) local doc = setmetatable({}, {__tostring = doc_tostring}) for _, mod in pairs(rawdocs) do local parts = {} for s in string.gmatch(mod.name, "[%w_]+") do table.insert(parts, s) end local parent = doc local keyname = parts[#parts] parts[#parts] = nil local subname = nil for _, s in ipairs(parts) do subname = subname and subname.."."..s or s if type(parent[s]) == "nil" then parent[s] = setmetatable({__doc = subname, __name = subname}, group_metatable) end parent = parent[s] end local m = setmetatable({__doc = mod.doc, __name = mod.name}, group_metatable) parent[keyname] = m for _, item in pairs(mod.items) do m[item.name] = setmetatable({__name = item.name, item.def, item.type, item.doc}, item_metatable) end end return doc end local __tostring_for_arrays = function(self) local result = "" for i,v in fnutils.sortByKeyValues(self) do result = result..v.."\n" end return result end local registeredJSONFiles = setmetatable({ hs.docstrings_json_file, (hs.docstrings_json_file:gsub("/docs.json$","/extensions/hs/doc/lua.json")) }, {__tostring = __tostring_for_arrays}) local validateJSONFile = function(jsonFile) local f = io.open(jsonFile) if not f then return false, "Unable to open '"..jsonFile.."'" else local content = f:read("*a") f:close() return pcall(json.decode, content) end end local fixLinks = function(text) -- replace internal link references which work well in html and dash with something -- more appropriate to inline textual help local content, count = text:gsub("%[([^%]\r\n]+)%]%(#([^%)\r\n]+)%)", "`%1`") return content end -- Public interface ------------------------------------------------------ --- hs.doc.validateJSONFile(jsonfile) -> status, message|table --- Function --- Validate a JSON file potential inclusion in the Hammerspoon internal documentation. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was validated or not. --- * message|table - If the file did not contain valid JSON data, then a message indicating the error is returned; otherwise the parsed JSON data is returned as a table. module.validateJSONFile = function(jsonFile) local f = io.open(jsonFile) if not f then return false, "Unable to open '"..jsonFile.."'" else local content = f:read("*a") f:close() return pcall(json.decode, content) end end --- hs.doc.registerJSONFile(jsonfile) -> status[, message] --- Function --- Register a JSON file for inclusion when Hammerspoon generates internal documentation. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was registered or not. If the file was not registered, then a message indicating the error is also returned. module.registerJSONFile = function(docFile) if type(docFile) ~= "string" then -- most likely this was called with the result of the locateJSONFile function, -- and the locate function was unable to find the JSON file... return false, "Provided path is not a string." end local status, message = module.validateJSONFile(docFile) if status then local alreadyRegistered = false for _, v in ipairs(registeredJSONFiles) do if v == docFile then alreadyRegistered = true break end end if alreadyRegistered then return false, "File '"..docFile.."' already registered" end table.insert(registeredJSONFiles, docFile) return status end return status, message end --- hs.doc.unregisterJSONFile(jsonfile) -> status[, message] --- Function --- Remove a JSON file from the list of registered files. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was unregistered or not. If the file was not unregistered, then a message indicating the error is also returned. module.unregisterJSONFile = function(docFile) local indexNumber, found = false for i, v in ipairs(registeredJSONFiles) do if v == docFile then found = true indexNumber = i break end end if found then table.remove(registeredJSONFiles, indexNumber) return true else return false, "File '"..docFile.."' was not registered" end end --- hs.doc.registeredFiles() -> table --- Function --- Returns the list of registered JSON files. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the list of registered JSON files --- --- Notes: --- * The table returned by this function has a metatable including a __tostring method which allows you to see the list of registered files by simply typing `hs.doc.registeredFiles()` in the Hammerspoon Console. --- --- * By default, the internal core documentation and portions of the Lua 5.3 manual, located at http://www.lua.org/manual/5.3/manual.html, are already registered for inclusion within this documentation object. --- --- * You can unregister these defaults if you wish to start with a clean slate with the following commands: --- * `hs.doc.unregisterJSONFile(hs.docstrings_json_file)` -- to unregister the Hammerspoon API docs --- * `hs.doc.unregisterJSONFile((hs.docstrings_json_file:gsub("/docs.json$","/extensions/hs/doc/lua.json")))` -- to unregister the Lua 5.3 Documentation. module.registeredFiles = function(docFile) return registeredJSONFiles end --- hs.doc.locateJSONFile(module) -> path | false, message --- Function --- Locates the JSON file corresponding to the specified module by searching package.path and package.cpath. --- --- Parameters: --- * module - the name of the module to locate a JSON file for --- --- Returns: --- * the path to the JSON file, or `false, error` if unable to locate a corresponding JSON file. --- --- Notes: --- * The JSON should be named 'full.module.name.json' and located in the same directory as the `lua` or `so` file which is used when the module is loaded via `require`. module.locateJSONFile = function(moduleName) local asLua = package.searchpath(moduleName, package.path) local asC = package.searchpath(moduleName, package.cpath) if asLua then local pathPart = asLua:match("^(.*/).+%.lua$") if pathPart then if fs.attributes(pathPart..moduleName..".json") then return pathPart..moduleName..".json" else return false, "No JSON file for "..moduleName.." found" end else return false, "Unable to parse package.path for "..moduleName end elseif asC then local pathPart = asC:match("^(.*/).+%.so$") if pathPart then if fs.attributes(pathPart..moduleName..".json") then return pathPart..moduleName..".json" else return false, "No JSON file for "..moduleName.." found" end else return false, "Unable to parse package.cpath for "..moduleName end else return false, "Unable to locate module path for "..moduleName end end --- hs.doc.fromJSONFile(jsonfile) -> doc-array --- Function --- Builds a doc array construct from the JSON file provided. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * A table containing the documentation data loaded from the JSON file function module.fromJSONFile(docsfile) local f = io.open(docsfile) if not f then print("Documentation file '"..docsfile.."' not found...") return setmetatable( {"Documentation file '"..docsfile.."' not found..."}, {__tostring = function(a) return a[1] end} ) end local content = f:read("*a") f:close() content = fixLinks(content) return internalBuild(json.decode(content)) end --- hs.doc.fromRegisteredFiles() -> doc-array --- Function --- Builds a doc array construct from the registered JSON files. --- --- Parameters: --- * None --- --- Returns: --- * A table containing the documentation data loaded from the registered JSON files --- --- Notes: --- * By default, the internal core documentation is already registered. If you wish to remove it from the list of registered sources, issue the command `hs.doc.unregisterJSONFile(hs.docstrings_json_file)`. --- * The documentation object is created from the sources that are registered at the time of its invocation. If you register additional files later, you will need to reissue this command to build the updated documentation object. function module.fromRegisteredFiles() local docData = {} for _, v in ipairs(registeredJSONFiles) do local f = io.open(v) if not f then print("Documentation file '"..docsfile.."' not found...") return setmetatable( {"Documentation file '"..docsfile.."' not found..."}, {__tostring = function(a) return a[1] end} ) end local content = f:read("*a") f:close() content = fixLinks(content) for _, j in pairs(json.decode(content)) do table.insert(docData, j) end end return internalBuild(docData) end local coredocs = module.fromRegisteredFiles() --- hs.doc.help(identifier) --- Function --- Prints the documentation for some part of Hammerspoon's API and Lua 5.3. This function has also been aliased as `hs.help` and `help` as a shorthand for use within the Hammerspoon console. --- --- Parameters: --- * identifier - A string containing the signature of some part of Hammerspoon's API (e.g. `"hs.reload"`) --- --- Returns: --- * None --- --- Notes: --- * This function is mainly for runtime API help while using Hammerspoon's Console --- * This function only returns information about the core Hammerspoon API and Lua 5.3. If you register additional files from 3rd party modules, or deregister the initial files for creating your own `hs.doc` objects, it will not affect the results used by this function. --- --- * You can also access the results of this function by the following methods from the console: --- * help("identifier") -- quotes are required, e.g. `help("hs.reload")` --- * help.identifier.path -- no quotes are required, e.g. `help.hs.reload` --- --- * Lua information can be accessed by using the `lua` prefix, rather than `hs`. --- * the identifier `lua._man` provides the table of contents for the Lua 5.3 manual. You can pull up a specific section of the lua manual by including the chapter (and subsection) like this: `lua._man._3_4_8`. --- * the identifier `lua._C` will provide information specifically about the Lua C API for use when developing modules which require external libraries. function module.help(identifier) local tree = coredocs local result = tree for word in string.gmatch(identifier, '([^.]+)') do result = result[word] end print(result) end -- Return Module Object -------------------------------------------------- return setmetatable(module, { __call = function(_, ...) return module.help(...) end, __index = coredocs, __tostring = function(obj) return tostring(coredocs) end, })
mit
OSGConnect/modulefiles
modulefiles/Core/cp2k/2.5.1.lua
1
1105
help( [[ CP2K: A general program to perform molecular dynamics simulations Copyright (C) 2000, 2001, 2002, 2003 CP2K developers group Copyright (C) 2004, 2005, 2006, 2007 CP2K developers group Copyright (C) 2008, 2009, 2010, 2011 CP2K developers group Copyright (C) 2012, 2013 CP2K developers group This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. CP2K, including its sources and pointers to the authors can be found at http://www.cp2k.org/ ]]) whatis("Loads CP2K, which is a first-principles molecular dynamics package") local version = "2.5.1" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/cp2k/"..version prepend_path("PATH", base) family('cp2k')
apache-2.0
dunn/ntopng
scripts/lua/get_host_data.lua
6
3612
-- -- (C) 2013-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" sendHTTPHeader('text/html; charset=iso-8859-1') function getNetworkStats(network) local hosts_stats = interface.getHostsInfo() my_network = nil for key, value in pairs(hosts_stats) do h = hosts_stats[key] nw_name = h["local_network_name"] if(h["local_network_name"] == network) then --io.write(nw_name.."\n") if(nw_name ~= nil) then if(my_network == nil) then h["ip"] = nw_name h["name"] = nw_name my_network = h else my_network["num_alerts"] = my_network["num_alerts"] + h["num_alerts"] my_network["throughput_bps"] = my_network["throughput_bps"] + h["throughput_bps"] my_network["throughput_pps"] = my_network["throughput_pps"] + h["throughput_pps"] my_network["last_throughput_bps"] = my_network["last_throughput_bps"] + h["last_throughput_bps"] my_network["last_throughput_pps"] = my_network["last_throughput_pps"] + h["last_throughput_pps"] my_network["bytes.sent"] = my_network["bytes.sent"] + h["bytes.sent"] my_network["bytes.rcvd"] = my_network["bytes.rcvd"] + h["bytes.rcvd"] if(my_network["seen.first"] > h["seen.first"]) then my_network["seen.first"] = h["seen.first"] end if(my_network["seen.last"] < h["seen.last"]) then my_network["seen.last"] = h["seen.last"] end end end end end return(my_network) end -- sendHTTPHeader('application/json') interface.select(ifname) host_info = url2hostinfo(_GET) interface.select(ifname) if(host_info["host"] ~= nil) then if(string.contains(host_info["host"], "/")) then -- This is a network host = getNetworkStats(host_info["host"]) else host = interface.getHostInfo(host_info["host"], host_info["vlan"]) end else host = interface.getAggregatedHostInfo(host_info["host"]) end if(host == nil) then print('{}') else print('{') now = os.time() -- Get from redis the throughput type bps or pps throughput_type = getThroughputType() print("\"column_since\" : \"" .. secondsToTime(now-host["seen.first"]+1) .. "\", ") print("\"column_last\" : \"" .. secondsToTime(now-host["seen.last"]+1) .. "\", ") print("\"column_traffic\" : \"" .. bytesToSize(host["bytes.sent"]+host["bytes.rcvd"]).. "\", ") if((host["throughput_trend_"..throughput_type] ~= nil) and (host["throughput_trend_"..throughput_type] > 0)) then if(throughput_type == "pps") then print ("\"column_thpt\" : \"" .. pktsToSize(host["throughput_bps"]).. " ") else print ("\"column_thpt\" : \"" .. bitsToSize(8*host["throughput_bps"]).. " ") end if(host["throughput_"..throughput_type] > host["last_throughput_"..throughput_type]) then print("<i class='fa fa-arrow-up'></i>") elseif(host["throughput_"..throughput_type] < host["last_throughput_"..throughput_type]) then print("<i class='fa fa-arrow-down'></i>") else print("<i class='fa fa-minus'></i>") end print("\",") else print ("\"column_thpt\" : \"0 "..throughput_type.."\",") end sent2rcvd = round((host["bytes.sent"] * 100) / (host["bytes.sent"]+host["bytes.rcvd"]), 0) print ("\"column_breakdown\" : \"<div class='progress'><div class='progress-bar progress-bar-warning' style='width: " .. sent2rcvd .."%;'>Sent</div><div class='progress-bar progress-bar-info' style='width: " .. (100-sent2rcvd) .. "%;'>Rcvd</div></div>") print("\" } ") end
gpl-3.0
maxmax1/fooniks
resources/phoenix_Cops/spikeStrips/strips_s.lua
2
8292
local MAX_SPIKES = tonumber( get( "#MAX_SPIKES" ) ); --[[ SpikeStrips Class variables: table allSpikes = { spikeElem } spikeElem = { posX, posY, posZ, rotX, rotY, rotZ, spikeType, myObject, myColShapes, myBlip, myMarker, } spikeType = -- Lets hope all have the same rotation base... { 1 1593 plc_stinger plc_stinger -- Currently only one supported... 2 2892 temp_stinger temp_stinger 3 2899 temp_stinger2 temp_stinger } fastColIndexes { colshape => index } functions: Load( ); Save( ); Deploy( spikeElem, isInTable ); methods: BlipVisibility( ); ]]-- SpikeStrips = { allSpikes = { }, fastColIndexes = { } }; function SpikeStrips:new( o ) o = o or { }; setmetatable( o, self ); self.__index = self; return o; end function SpikeStrips:Load( ) local conf = xmlLoadFile( "spikeStrips/strips.xml" ); if( conf ) then local elems = xmlNodeGetChildren( conf ); if( elems ) then for k, node in ipairs( elems ) do if( xmlNodeGetName( node ) == "strip" ) then local attrs = xmlNodeGetAttributes( node ); local tbl = { }; tbl.posX = attrs["posX"]; tbl.posY = attrs["posY"]; tbl.posZ = attrs["posZ"]; tbl.rotX = attrs["rotX"]; tbl.rotY = attrs["rotY"]; tbl.rotZ = attrs["rotZ"]; tbl.spikeType = attrs["spikeType"]; tbl.created = false; if( tbl.posX and tbl.posY and tbl.posZ and tbl.rotX and tbl.rotY and tbl.rotZ and tbl.spikeType ) then self:Deploy( tbl, false ); else outputDebugString( "[SpikeStrips:Load] Wrong xmlNode attrs." ); end else outputDebugString( "[SpikeStrips:Load] Bad xmlNode name: " .. xmlNodeGetName( node ) .. "." ); end end end xmlUnloadFile( conf ); end end function SpikeStrips:Save( ) local conf = xmlCreateFile( "spikeStrips/strips.xml", "strips" ); if( conf ) then for k, v in ipairs( self.allSpikes ) do local node = xmlCreateChild( conf, "strip" ); xmlNodeSetAttribute( node, "posX", v.posX); xmlNodeSetAttribute( node, "posY", v.posY); xmlNodeSetAttribute( node, "posZ", v.posZ); xmlNodeSetAttribute( node, "rotX", v.rotX); xmlNodeSetAttribute( node, "rotY", v.rotY); xmlNodeSetAttribute( node, "rotZ", v.rotZ); xmlNodeSetAttribute( node, "spikeType", v.spikeType); end xmlSaveFile( conf ); xmlUnloadFile( conf ); end end function getPointFromDistanceRotation(x, y, dist, angle) local a = math.rad(90 - angle); local dx = math.cos(a) * dist; local dy = math.sin(a) * dist; return x+dx, y+dy; end function SpikeStrips:GetSouthWestCornerPos( objectId, x, y, rotz ) if( objectId == 1593 ) then local distance = 0.91; local addonR = 180 + math.deg( math.atan( 0.115 / 0.9 ) ); if( rotz >= addonR ) then rotz = rotz - ( addonR ); else rotz = rotz + ( addonR ); end x, y = getPointFromDistanceRotation( x, y, distance, rotz ); end return x, y; end function SpikeStrips:CreateColArea( x, y, myZ, elemAng ) local area = createColCircle( x, y, 1.8 ); self.fastColIndexes[area] = #self.allSpikes+1; addEventHandler( "onColShapeHit", area, function ( elem, dim ) local theZ = myZ; if( getElementType( elem ) == "vehicle" and dim ) then self:ColShapeHit( elem, area, theZ ); end end ); return area; end function SpikeStrips:ColShapeHit( theVehicle, theColShape, colZ ) if( self.fastColIndexes[theColShape] ) then local vehX, vehY, vehZ = getElementPosition( theVehicle ); colZ = tonumber( colZ ); if( ( vehZ > colZ and ( vehZ - colZ ) < 1 ) or ( vehZ < colZ and ( colZ - vehZ ) < 1 ) ) then setVehicleWheelStates( theVehicle, 1, 1, 1, 1 ); destroyElement( self.allSpikes[self.fastColIndexes[theColShape]].myObject ); destroyElement( self.allSpikes[self.fastColIndexes[theColShape]].myColShapes ); destroyElement( self.allSpikes[self.fastColIndexes[theColShape]].myBlip ); table.remove( self.allSpikes, self.fastColIndexes[theColShape] ); self.fastColIndexes[theColShape] = nil; self:UpdateFastIndexes( ); end end end function SpikeStrips:UpdateFastIndexes( ) self.fastColIndexes = { }; for k, v in ipairs( self.allSpikes ) do self.fastColIndexes[v.myColShapes] = k; end end function SpikeStrips:ReloadForVehicle( thePlayer, theVehicle ) local numStrips = tonumber( getElementData( theVehicle, "spikeStrips" ) ); if( not numStrips ) then numStrips = 0; end if( numStrips < MAX_SPIKES ) then numStrips = numStrips + 1; setElementData( theVehicle, "spikeStrips", tostring( numStrips ) ); exports.phoenix_Chat:OocInfo( thePlayer, "Võtsid ühe naelariba juurde. Su masinas on nüüd " .. numStrips .. " naelariba." ); else exports.phoenix_Chat:OocInfo( thePlayer, "Masinal on naelaribade kohad(" .. MAX_SPIKES .. ") täis!" ); end getVehicleOccupant( theVehicle ); end function SpikeStrips:Deploy( spikeElem ) spikeElem.myObject = createObject( spikeElem.spikeType, spikeElem.posX, spikeElem.posY, spikeElem.posZ, spikeElem.rotX, spikeElem.rotY, spikeElem.rotZ ); spikeElem.myBlip = createBlip( spikeElem.posX, spikeElem.posY, spikeElem.posZ, 0, 3, 150, 0, 255, 255, 0, 9999.0 ); spikeElem.myColShapes = self:CreateColArea( spikeElem.posX, spikeElem.posY, spikeElem.posZ, spikeElem.rotZ ); self:BlipVisibility( spikeElem ); spikeElem.created = true; table.insert( self.allSpikes, spikeElem ); end function SpikeStrips:BlipVisibility( spikeElem ) local copTeam = getCopTeam( ); if( not copTeam ) then return false; end local cops = getPlayersInTeam( copTeam ); if( not spikeElem ) then for k, v in ipairs( self.allSpikes ) do setElementVisibleTo( v.myBlip, getRootElement( ), false ); for k2, v2 in ipairs( cops ) do setElementVisibleTo( v.myBlip, v2, true ); end end else setElementVisibleTo( spikeElem.myBlip, getRootElement( ), false ); for k2, v2 in ipairs( cops ) do setElementVisibleTo( spikeElem.myBlip, v2, true ); end end end theStrips = SpikeStrips:new(); theStrips:Load( ); function SpikeTimer( ) theStrips:BlipVisibility( ); end setTimer( SpikeTimer, 30000, 0 ); addEvent( "onSpikeDrop", true ); addEventHandler( "onSpikeDrop", getRootElement( ), function ( newElem ) theStrips:Deploy( newElem ); end ); addEventHandler( "onResourceStop", getResourceRootElement( ), function ( ) theStrips:Save( ); end ); local pickup = createPickup( 1560.828, -1694.256, 5.302, 3, 1242, 1000 ); local colCircle = createColCircle( 1560.828, -1694.256, 5 ); addEventHandler( "onColShapeHit", colCircle, function ( elem, matchingDim ) if( matchingDim ) then if( getElementType( elem ) == "vehicle" and isCopVehicle( elem ) ) then local thePlayer = getVehicleOccupant( elem ); if( thePlayer ) then if( isACop( thePlayer ) ) then exports.phoenix_Chat:OocInfo( thePlayer, "Kasuta /laett, et masinasse veel üks teetõke laadida." ); end end end end end ); addCommandHandler( "laett", function ( thePlayer, theCmd ) if( not isACop( thePlayer ) ) then exports.phoenix_Chat:OocInfo( thePlayer, "Pead olema politseinik!" ); return false; end if( not isPedInVehicle( thePlayer ) ) then exports.phoenix_Chat:OocInfo( thePlayer, "Pead olema autos!" ); return false; end local theVehicle = getPedOccupiedVehicle( thePlayer ); local posX, posY, posZ = getElementPosition( theVehicle ); if( getDistanceBetweenPoints3D( posX, posY, posZ, 1560.828, -1694.256, 5.302 ) > 5 ) then exports.phoenix_Chat:OocInfo( thePlayer, "Pead olema politsei garaasis!" ); return false; end theStrips:ReloadForVehicle( thePlayer, theVehicle ); end , false, false );
gpl-3.0
resistor58/deaths-gmod-server
Mad Cows DoD Weapons/lua/weapons/weapon_mad_dod_k98_rg/shared.lua
1
5738
// Variables that are used on both client and server SWEP.Base = "weapon_mad_dod_base" SWEP.ViewModelFOV = 50 SWEP.ViewModel = "models/weapons/v_k98_rg.mdl" SWEP.WorldModel = "models/weapons/w_k98_rg.mdl" SWEP.Spawnable = false SWEP.AdminSpawnable = false SWEP.Primary.Sound = Sound("Weapon_Grenade.Shoot") SWEP.Primary.Recoil = 0 SWEP.Primary.Damage = 0 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.075 SWEP.Primary.Delay = 0.5 SWEP.Primary.ClipSize = 1 // Size of a clip SWEP.Primary.DefaultClip = 1 // Default number of bullets in a clip SWEP.Primary.Automatic = false // Automatic/Semi Auto SWEP.Primary.Ammo = "Grenade" SWEP.Secondary.ClipSize = -1 // Size of a clip SWEP.Secondary.DefaultClip = -1 // Default number of bullets in a clip SWEP.Secondary.Automatic = false // Automatic/Semi Auto SWEP.Secondary.Ammo = "none" SWEP.ShellEffect = "none" // "effect_mad_shell_pistol" or "effect_mad_shell_rifle" or "effect_mad_shell_shotgun" SWEP.ShellDelay = 0 SWEP.Pistol = false SWEP.Rifle = true SWEP.Shotgun = false SWEP.Sniper = false SWEP.IronSightsPos = Vector (-4.5248, -5.0179, 5.0219) SWEP.IronSightsAng = Vector (-4.9138, -0.4858, -1.3093) SWEP.RunArmOffset = Vector (5.6468, 0, 3.7276) SWEP.RunArmAngle = Vector (-13.4491, 16.4064, 0) /*--------------------------------------------------------- Name: SWEP:Precache() Desc: Use this function to precache stuff. ---------------------------------------------------------*/ function SWEP:Precache() util.PrecacheSound("weapons/grenade_shoot.wav") end /*--------------------------------------------------------- Name: SWEP:Grenade() ---------------------------------------------------------*/ SWEP.Force = 7500 function SWEP:Grenade() if (CLIENT) then return end local grenade = ents.Create ("ent_mad_dod_ger_launcher") grenade:SetOwner(self.Owner) if not (self.Weapon:GetNetworkedBool("Ironsights")) then local pos = self.Owner:GetShootPos() pos = pos + self.Owner:GetForward() * 5 pos = pos + self.Owner:GetRight() * 9 pos = pos + self.Owner:GetUp() * -8 grenade:SetPos(pos) grenade:SetAngles(self.Owner:GetAngles() + Vector(70, 10, 0)) grenade:Spawn() grenade:Activate() local phys = grenade:GetPhysicsObject() phys:ApplyForceCenter(self.Owner:GetAimVector() * self.Force + Vector(0, 0, 1000)) else grenade:SetPos(self.Owner:EyePos() + (self.Owner:GetAimVector())) grenade:SetAngles(self.Owner:GetAngles() + Vector(90, 0, 0)) grenade:Spawn() grenade:Activate() local phys = grenade:GetPhysicsObject() phys:ApplyForceCenter(self.Owner:GetAimVector() * self.Force + Vector(0, 0, 200)) end end /*--------------------------------------------------------- Name: SWEP:Deploy() ---------------------------------------------------------*/ function SWEP:Deploy() if (self.Weapon:Clip1() <= 0) and self.Owner:GetAmmoCount(self.Primary.Ammo) > 0 then self.Weapon:SetClip1(1) self.Owner:RemoveAmmo(1, self.Weapon:GetPrimaryAmmoType()) end self.Weapon:SetNextPrimaryFire(CurTime() + 2) self.Weapon:SetNextSecondaryFire(CurTime() + 2) self.Weapon:SendWeaponAnim(ACT_VM_DRAW) self:SetIronsights(false) return true end /*--------------------------------------------------------- Name: SWEP:PrimaryAttack() Desc: +attack1 has been pressed. ---------------------------------------------------------*/ function SWEP:PrimaryAttack() // Holst/Deploy your fucking weapon if (self.Owner:KeyDown(IN_USE)) then bHolsted = !self.Weapon:GetNetworkedBool("Holsted", false) self:SetHolsted(bHolsted) self.Weapon:SetNextPrimaryFire(CurTime() + 0.3) self.Weapon:SetNextSecondaryFire(CurTime() + 0.3) self:SetIronsights(false) return end if (not self:CanPrimaryAttack()) then return end self.ActionDelay = (CurTime() + self.Primary.Delay) self.Weapon:SetNextPrimaryFire(CurTime() + self.Primary.Delay) self.Weapon:SetNextSecondaryFire(CurTime() + self.Primary.Delay) self.Weapon:SendWeaponAnim(ACT_VM_PRIMARYATTACK) // View model animation self.Owner:SetAnimation(PLAYER_ATTACK1) // 3rd Person Animation self.Weapon:EmitSound(self.Primary.Sound) self:TakePrimaryAmmo(1) self:Grenade() self.Owner:ViewPunch(Vector(math.Rand(-5, -15), math.Rand(0, 0), math.Rand(0, 0))) if ((SinglePlayer() and SERVER) or CLIENT) then self.Weapon:SetNetworkedFloat("LastShootTime", CurTime()) end local WeaponModel = self.Weapon:GetOwner():GetActiveWeapon():GetClass() if (self.Weapon:Clip1() < 1) then timer.Simple(self.Primary.Delay + 0.1, function() if self.Owner and self.Owner:Alive() and self.Weapon:GetOwner():GetActiveWeapon():GetClass() == WeaponModel then self:Reload() end end) end end /*--------------------------------------------------------- Name: SWEP:SecondaryAttack() Desc: +attack2 has been pressed. ---------------------------------------------------------*/ function SWEP:SecondaryAttack() if self.Owner:IsNPC() then return end if not IsFirstTimePredicted() then return end if (self.Owner:KeyDown(IN_USE)) then if (SERVER) then self.Owner:SelectWeapon("weapon_mad_dod_k98") end return end if (!self.IronSightsPos) or (self.Owner:KeyDown(IN_SPEED) or self.Weapon:GetNetworkedBool("Holsted")) then return end // Not pressing Use + Right click? Ironsights bIronsights = !self.Weapon:GetDTBool(1) self:SetIronsights(bIronsights) self.Weapon:SetNextPrimaryFire(CurTime() + 0.2) self.Weapon:SetNextSecondaryFire(CurTime() + 0.2) end
gpl-3.0
team-smart/smart_team
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-2.0
cyrillePrigent/kmod-ng
umod/modules/auto_panzer_disable.lua
1
6529
-- Auto panzer disable -- From kmod script. -- Global var autoPanzerDisable = { -- Auto panzer disable module status. ["enabled"] = false, -- Panzer enable / disable message status. ["msg"] = { ["enabled"] = false, ["disabled"] = false, }, -- Panzer disable warning level. ["warning"] = 0, -- Time (in ms) of last panzer disable warning check. ["warningTime"] = 0, -- Minimum active players to activate panzers. ["playerLimit"] = tonumber(et.trap_Cvar_Get("u_panzer_player_limit")), -- Number of panzer per team. ["allowPerTeam"] = tonumber(et.trap_Cvar_Get("team_maxpanzers")) -- et-legacy : team_maxPanzers -- Time (in ms) of last auto panzer disable check. ["time"] = 0, -- Interval (in ms) between 2 frame check. ["frameCheck"] = 250 } -- Function -- Called when qagame initializes. -- Check if soldier class & panzerfaust weapon is enabled. -- vars is the local vars of et_InitGame function. function autoPanzerDisableInitGame(vars) local team_maxSoldiers = tonumber(et.trap_Cvar_Get("team_maxSoldiers")) local team_maxpanzers = tonumber(et.trap_Cvar_Get("team_maxpanzers")) if team_maxSoldiers ~= nil and team_maxSoldiers > 0 and team_maxpanzers ~= nil and team_maxpanzers > 0 then autoPanzerDisable["enabled"] = true addCallbackFunction({["RunFrame"] = "autoPanzerDisableRunFrame"}) else et.G_LogPrint( "uMod Auto panzer disable : Panzerfaust is disabled! Please " .. "enable it with <team_maxSoldiers> or <team_maxpanzers> cvar.\n" ) end end -- Callback function when qagame runs a server frame. -- If server have minimum active players, activate panzers. -- If not and some players used panzers, disable panzers and -- display first warning. After 3mins, display second warning -- and after 30secs, move soldiers with panzers to spectator. -- vars is the local vars passed from et_RunFrame function. function autoPanzerDisableRunFrame(vars) if autoPanzerDisable["time"] + autoPanzerDisable["frameCheck"] < vars["levelTime"] then if players["active"] < autoPanzerDisable["playerLimit"] then local activePanzers = false for p = 0, clientsLimit, 1 do if tonumber(et.gentity_get(p, "sess.latchPlayerWeapon")) == 5 then activePanzers = true break end end if autoPanzerDisable["msg"]["disabled"] == false then autoPanzerDisable["msg"]["disabled"] = true autoPanzerDisable["msg"]["enabled"] = false et.trap_SendConsoleCommand( et.EXEC_APPEND, "qsay " .. color2 .. "Panzerlimit: " .. color1 .. "Panzers have been disabled.\n" ) end if activePanzers then if autoPanzerDisable["warning"] == 0 then autoPanzerDisable["warningTime"] = vars["levelTime"] autoPanzerDisable["warning"] = 1 et.trap_SendConsoleCommand( et.EXEC_APPEND, "qsay " .. color2 .. "Panzerlimit: " .. color1 .. "Please switch to a different weapon or be automatically " .. "moved to spec in " .. color4 .. "1" .. color2 .. " minute!\n" ) et.trap_SendConsoleCommand( et.EXEC_APPEND, "team_maxpanzers 0\n" ) end local remainingTime = vars["levelTime"] - autoPanzerDisable["warningTime"] -- After 30 secs... if remainingTime > 30000 then if autoPanzerDisable["warning"] == 1 then autoPanzerDisable["warning"] = 2 et.trap_SendConsoleCommand( et.EXEC_APPEND, "qsay " .. color2 .. "Panzerlimit: " .. color1 .. "Please switch to a different weapon or be automatically " .. "moved to spec in " .. color4 .. "30" .. color2 .. " Seconds!\n" ) end end -- After 60 secs... if remainingTime > 60000 then for p = 0, clientsLimit, 1 do if tonumber(et.gentity_get(p, "sess.latchPlayerWeapon")) == 5 then et.trap_SendConsoleCommand(et.EXEC_APPEND, "ref remove " .. p .. "\n") et.gentity_set(p, "sess.latchPlayerWeapon", 3) et.trap_SendServerCommand( p, "chat \"" .. color4 .. "You have been moved to spectator " .. "for having a panzerfaust after being warned twice to switch!\"\n" ) end end autoPanzerDisable["msg"]["disabled"] = false autoPanzerDisable["warning"] = 0 autoPanzerDisable["warningTime"] = 0 end else autoPanzerDisable["warning"] = 0 autoPanzerDisable["warningTime"] = 0 end else autoPanzerDisable["msg"]["disabled"] = false autoPanzerDisable["warning"] = 0 autoPanzerDisable["warningTime"] = 0 et.trap_SendConsoleCommand( et.EXEC_APPEND, "team_maxpanzers " .. autoPanzerDisable["allowPerTeam"] .. "\n" ) if autoPanzerDisable["msg"]["enabled"] == false then autoPanzerDisable["msg"]["enabled"] = true et.trap_SendConsoleCommand( et.EXEC_APPEND, "qsay " .. color2 .. "Panzerlimit: " .. color1 .. "Panzers have been auto-enabled. Each team is allowed only " .. color4 .. autoPanzerDisable["allowPerTeam"] .. color1 .. " panzer(s) per team!\n" ) end end autoPanzerDisable["time"] = vars["levelTime"] end end -- Add callback auto panzer disable function. addCallbackFunction({ ["InitGame"] = "autoPanzerDisableInitGame" })
gpl-2.0
zchengquan/nn
ClassNLLCriterion.lua
10
2966
local ClassNLLCriterion, parent = torch.class('nn.ClassNLLCriterion', 'nn.Criterion') function ClassNLLCriterion:__init(weights) parent.__init(self) self.sizeAverage = true self.outputTensor = torch.Tensor(1) if weights then assert(weights:dim() == 1, "weights input should be 1-D Tensor") self.weights = weights end end function ClassNLLCriterion:__len() if (self.weights) then return #self.weights else return 0 end end function ClassNLLCriterion:updateOutput(input, target) if input:type() == 'torch.CudaTensor' and not self.weights then if input:dim() == 1 then self._target = self._target or input.new(1) if type(target) == 'number' then self._target[1] = target else self._target:copy(target) end input.nn.ClassNLLCriterion_updateOutput(self, input, self._target) else input.nn.ClassNLLCriterion_updateOutput(self, input, target) end self.output = self.outputTensor[1] return self.output end if input:dim() == 1 then if torch.isTensor(target) then target = target[1] end self.output = -input[target] if self.weights then self.output = self.output*self.weights[target] end elseif input:dim() == 2 then local output = 0 for i=1,target:size(1) do if self.weights then output = output - input[i][target[i]]*self.weights[target[i]] else output = output - input[i][target[i]] end end if self.sizeAverage then output = output / target:size(1) end self.output = output else error('matrix or vector expected') end return self.output end function ClassNLLCriterion:updateGradInput(input, target) self.gradInput:resizeAs(input) self.gradInput:zero() if input:type() == 'torch.CudaTensor' and not self.weights then if input:dim() == 1 then self._target = self._target or input.new(1) if type(target) == 'number' then self._target[1] = target else self._target:copy(target) end input.nn.ClassNLLCriterion_updateGradInput(self, input, self._target) else input.nn.ClassNLLCriterion_updateGradInput(self, input, target) end return self.gradInput end if input:dim() == 1 then if torch.isTensor(target) then target = target[1] end self.gradInput[target] = -1 if self.weights then self.gradInput[target] = self.gradInput[target]*self.weights[target] end else local z = -1 if self.sizeAverage then z = z / target:size(1) end for i=1,target:size(1) do self.gradInput[i][target[i]] = z if self.weights then self.gradInput[i][target[i]] = self.gradInput[i][target[i]]*self.weights[target[i]] end end end return self.gradInput end
bsd-3-clause
amirik22/uzzbot
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
chewi/Aquaria
files/scripts/maps/map_veil02.lua
12
1050
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end function init() local n = getNaija() local li = getLi() local node = getNode("LAUNCHFROMSUNTEMPLE") if node_isEntityIn(node, n) then local lin = getNode("LIFROMSUN") entity_setPosition(li, node_x(lin), node_y(lin)) end end
gpl-2.0
mSenyor/sl4a
lua/luasocket/etc/forward.lua
61
2077
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if table.getn(arg) < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
apache-2.0
shahabsaf1/tg
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
alireza1516/self1
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
zeta0134/LuaGB
gameboy/z80/rl_rr_cb.lua
1
10210
local bit32 = require("bit") local lshift = bit32.lshift local rshift = bit32.rshift local band = bit32.band local bxor = bit32.bxor local bor = bit32.bor local bnor = bit32.bnor function apply(opcodes, opcode_cycles, z80, memory) local read_nn = z80.read_nn local reg = z80.registers local flags = reg.flags local read_byte = memory.read_byte local write_byte = memory.write_byte local add_cycles = z80.add_cycles -- ====== GMB Rotate and Shift Commands ====== local reg_rlc = function(value) value = lshift(value, 1) -- move what would be bit 8 into the carry flags.c = band(value, 0x100) ~= 0 value = band(value, 0xFF) -- also copy the carry into bit 0 if flags.c then value = value + 1 end flags.z = value == 0 flags.h = false flags.n = false return value end local reg_rl = function(value) value = lshift(value, 1) -- move the carry into bit 0 if flags.c then value = value + 1 end -- now move what would be bit 8 into the carry flags.c = band(value, 0x100) ~= 0 value = band(value, 0xFF) flags.z = value == 0 flags.h = false flags.n = false return value end local reg_rrc = function(value) -- move bit 0 into the carry flags.c = band(value, 0x1) ~= 0 value = rshift(value, 1) -- also copy the carry into bit 7 if flags.c then value = value + 0x80 end flags.z = value == 0 flags.h = false flags.n = false return value end local reg_rr = function(value) -- first, copy the carry into bit 8 (!!) if flags.c then value = value + 0x100 end -- move bit 0 into the carry flags.c = band(value, 0x1) ~= 0 value = rshift(value, 1) -- for safety, this should be a nop? -- value = band(value, 0xFF) flags.z = value == 0 flags.h = false flags.n = false return value end -- rlc a opcodes[0x07] = function() reg.a = reg_rlc(reg.a); flags.z = false end -- rl a opcodes[0x17] = function() reg.a = reg_rl(reg.a); flags.z = false end -- rrc a opcodes[0x0F] = function() reg.a = reg_rrc(reg.a); flags.z = false end -- rr a opcodes[0x1F] = function() reg.a = reg_rr(reg.a); flags.z = false end -- ====== CB: Extended Rotate and Shift ====== cb = {} -- rlc r cb[0x00] = function() reg.b = reg_rlc(reg.b); add_cycles(4) end cb[0x01] = function() reg.c = reg_rlc(reg.c); add_cycles(4) end cb[0x02] = function() reg.d = reg_rlc(reg.d); add_cycles(4) end cb[0x03] = function() reg.e = reg_rlc(reg.e); add_cycles(4) end cb[0x04] = function() reg.h = reg_rlc(reg.h); add_cycles(4) end cb[0x05] = function() reg.l = reg_rlc(reg.l); add_cycles(4) end cb[0x06] = function() write_byte(reg.hl(), reg_rlc(read_byte(reg.hl()))); add_cycles(12) end cb[0x07] = function() reg.a = reg_rlc(reg.a); add_cycles(4) end -- rl r cb[0x10] = function() reg.b = reg_rl(reg.b); add_cycles(4) end cb[0x11] = function() reg.c = reg_rl(reg.c); add_cycles(4) end cb[0x12] = function() reg.d = reg_rl(reg.d); add_cycles(4) end cb[0x13] = function() reg.e = reg_rl(reg.e); add_cycles(4) end cb[0x14] = function() reg.h = reg_rl(reg.h); add_cycles(4) end cb[0x15] = function() reg.l = reg_rl(reg.l); add_cycles(4) end cb[0x16] = function() write_byte(reg.hl(), reg_rl(read_byte(reg.hl()))); add_cycles(12) end cb[0x17] = function() reg.a = reg_rl(reg.a); add_cycles(4) end -- rrc r cb[0x08] = function() reg.b = reg_rrc(reg.b); add_cycles(4) end cb[0x09] = function() reg.c = reg_rrc(reg.c); add_cycles(4) end cb[0x0A] = function() reg.d = reg_rrc(reg.d); add_cycles(4) end cb[0x0B] = function() reg.e = reg_rrc(reg.e); add_cycles(4) end cb[0x0C] = function() reg.h = reg_rrc(reg.h); add_cycles(4) end cb[0x0D] = function() reg.l = reg_rrc(reg.l); add_cycles(4) end cb[0x0E] = function() write_byte(reg.hl(), reg_rrc(read_byte(reg.hl()))); add_cycles(12) end cb[0x0F] = function() reg.a = reg_rrc(reg.a); add_cycles(4) end -- rl r cb[0x18] = function() reg.b = reg_rr(reg.b); add_cycles(4) end cb[0x19] = function() reg.c = reg_rr(reg.c); add_cycles(4) end cb[0x1A] = function() reg.d = reg_rr(reg.d); add_cycles(4) end cb[0x1B] = function() reg.e = reg_rr(reg.e); add_cycles(4) end cb[0x1C] = function() reg.h = reg_rr(reg.h); add_cycles(4) end cb[0x1D] = function() reg.l = reg_rr(reg.l); add_cycles(4) end cb[0x1E] = function() write_byte(reg.hl(), reg_rr(read_byte(reg.hl()))); add_cycles(12) end cb[0x1F] = function() reg.a = reg_rr(reg.a); add_cycles(4) end local reg_sla = function(value) -- copy bit 7 into carry flags.c = band(value, 0x80) == 0x80 value = band(lshift(value, 1), 0xFF) flags.z = value == 0 flags.h = false flags.n = false add_cycles(4) return value end local reg_srl = function(value) -- copy bit 0 into carry flags.c = band(value, 0x1) == 1 value = rshift(value, 1) flags.z = value == 0 flags.h = false flags.n = false add_cycles(4) return value end local reg_sra = function(value) local arith_value = reg_srl(value) -- if bit 6 is set, copy it to bit 7 if band(arith_value, 0x40) ~= 0 then arith_value = arith_value + 0x80 end add_cycles(4) return arith_value end local reg_swap = function(value) value = rshift(band(value, 0xF0), 4) + lshift(band(value, 0xF), 4) flags.z = value == 0 flags.n = false flags.h = false flags.c = false add_cycles(4) return value end -- sla r cb[0x20] = function() reg.b = reg_sla(reg.b) end cb[0x21] = function() reg.c = reg_sla(reg.c) end cb[0x22] = function() reg.d = reg_sla(reg.d) end cb[0x23] = function() reg.e = reg_sla(reg.e) end cb[0x24] = function() reg.h = reg_sla(reg.h) end cb[0x25] = function() reg.l = reg_sla(reg.l) end cb[0x26] = function() write_byte(reg.hl(), reg_sla(read_byte(reg.hl()))); add_cycles(8) end cb[0x27] = function() reg.a = reg_sla(reg.a) end -- swap r (high and low nybbles) cb[0x30] = function() reg.b = reg_swap(reg.b) end cb[0x31] = function() reg.c = reg_swap(reg.c) end cb[0x32] = function() reg.d = reg_swap(reg.d) end cb[0x33] = function() reg.e = reg_swap(reg.e) end cb[0x34] = function() reg.h = reg_swap(reg.h) end cb[0x35] = function() reg.l = reg_swap(reg.l) end cb[0x36] = function() write_byte(reg.hl(), reg_swap(read_byte(reg.hl()))); add_cycles(8) end cb[0x37] = function() reg.a = reg_swap(reg.a) end -- sra r cb[0x28] = function() reg.b = reg_sra(reg.b); add_cycles(-4) end cb[0x29] = function() reg.c = reg_sra(reg.c); add_cycles(-4) end cb[0x2A] = function() reg.d = reg_sra(reg.d); add_cycles(-4) end cb[0x2B] = function() reg.e = reg_sra(reg.e); add_cycles(-4) end cb[0x2C] = function() reg.h = reg_sra(reg.h); add_cycles(-4) end cb[0x2D] = function() reg.l = reg_sra(reg.l); add_cycles(-4) end cb[0x2E] = function() write_byte(reg.hl(), reg_sra(read_byte(reg.hl()))); add_cycles(4) end cb[0x2F] = function() reg.a = reg_sra(reg.a); add_cycles(-4) end -- srl r cb[0x38] = function() reg.b = reg_srl(reg.b) end cb[0x39] = function() reg.c = reg_srl(reg.c) end cb[0x3A] = function() reg.d = reg_srl(reg.d) end cb[0x3B] = function() reg.e = reg_srl(reg.e) end cb[0x3C] = function() reg.h = reg_srl(reg.h) end cb[0x3D] = function() reg.l = reg_srl(reg.l) end cb[0x3E] = function() write_byte(reg.hl(), reg_srl(read_byte(reg.hl()))); add_cycles(8) end cb[0x3F] = function() reg.a = reg_srl(reg.a) end -- ====== GMB Singlebit Operation Commands ====== local reg_bit = function(value, bit) flags.z = band(value, lshift(0x1, bit)) == 0 flags.n = false flags.h = true return end opcodes[0xCB] = function() local cb_op = read_nn() add_cycles(4) if cb[cb_op] ~= nil then --revert the timing; this is handled automatically by the various functions add_cycles(-4) cb[cb_op]() return end local high_half_nybble = rshift(band(cb_op, 0xC0), 6) local reg_index = band(cb_op, 0x7) local bit = rshift(band(cb_op, 0x38), 3) if high_half_nybble == 0x1 then -- bit n,r if reg_index == 0 then reg_bit(reg.b, bit) end if reg_index == 1 then reg_bit(reg.c, bit) end if reg_index == 2 then reg_bit(reg.d, bit) end if reg_index == 3 then reg_bit(reg.e, bit) end if reg_index == 4 then reg_bit(reg.h, bit) end if reg_index == 5 then reg_bit(reg.l, bit) end if reg_index == 6 then reg_bit(read_byte(reg.hl()), bit); add_cycles(4) end if reg_index == 7 then reg_bit(reg.a, bit) end end if high_half_nybble == 0x2 then -- res n, r -- note: this is REALLY stupid, but it works around some floating point -- limitations in Lua. if reg_index == 0 then reg.b = band(reg.b, bxor(reg.b, lshift(0x1, bit))) end if reg_index == 1 then reg.c = band(reg.c, bxor(reg.c, lshift(0x1, bit))) end if reg_index == 2 then reg.d = band(reg.d, bxor(reg.d, lshift(0x1, bit))) end if reg_index == 3 then reg.e = band(reg.e, bxor(reg.e, lshift(0x1, bit))) end if reg_index == 4 then reg.h = band(reg.h, bxor(reg.h, lshift(0x1, bit))) end if reg_index == 5 then reg.l = band(reg.l, bxor(reg.l, lshift(0x1, bit))) end if reg_index == 6 then write_byte(reg.hl(), band(read_byte(reg.hl()), bxor(read_byte(reg.hl()), lshift(0x1, bit)))); add_cycles(8) end if reg_index == 7 then reg.a = band(reg.a, bxor(reg.a, lshift(0x1, bit))) end end if high_half_nybble == 0x3 then -- set n, r if reg_index == 0 then reg.b = bor(lshift(0x1, bit), reg.b) end if reg_index == 1 then reg.c = bor(lshift(0x1, bit), reg.c) end if reg_index == 2 then reg.d = bor(lshift(0x1, bit), reg.d) end if reg_index == 3 then reg.e = bor(lshift(0x1, bit), reg.e) end if reg_index == 4 then reg.h = bor(lshift(0x1, bit), reg.h) end if reg_index == 5 then reg.l = bor(lshift(0x1, bit), reg.l) end if reg_index == 6 then write_byte(reg.hl(), bor(lshift(0x1, bit), read_byte(reg.hl()))); add_cycles(8) end if reg_index == 7 then reg.a = bor(lshift(0x1, bit), reg.a) end end end end return apply
bsd-3-clause
resistor58/deaths-gmod-server
wire/lua/entities/gmod_wire_speedometer/init.lua
1
3082
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') ENT.WireDebugName = "Speedo" local MODEL = Model("models/jaanus/wiretool/wiretool_speed.mdl") function ENT:Initialize() self.Entity:SetModel( MODEL ) self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Outputs = Wire_CreateOutputs(self.Entity, { "Out", "MPH", "KPH" }) end function ENT:Setup( xyz_mode, AngVel ) self.z_only = xyz_mode --was renamed but kept for dupesaves self.XYZMode = xyz_mode self.AngVel = AngVel self:SetModes( xyz_mode,AngVel ) local outs = {} if (xyz_mode) then outs = { "X", "Y", "Z" } else outs = { "Out", "MPH", "KPH", } end if (AngVel) then table.Add(outs, {"AngVel_P", "AngVel_Y", "AngVel_R" } ) end Wire_AdjustOutputs(self.Entity, outs) end function ENT:Think() self.BaseClass.Think(self) if (self.XYZMode) then local vel = self.Entity:WorldToLocal(self.Entity:GetVelocity()+self.Entity:GetPos()) if (COLOSSAL_SANDBOX) then vel = vel * 6.25 end Wire_TriggerOutput(self.Entity, "X", -vel.y) Wire_TriggerOutput(self.Entity, "Y", vel.x) Wire_TriggerOutput(self.Entity, "Z", vel.z) else local vel = self.Entity:GetVelocity():Length() if (COLOSSAL_SANDBOX) then vel = vel * 6.25 end Wire_TriggerOutput(self.Entity, "Out", vel) // vel = Source Units / sec, Source Units = Inch * 0.75 , more info here: http://developer.valvesoftware.com/wiki/Dimensions#Map_Grid_Units:_quick_reference Wire_TriggerOutput(self.Entity, "MPH", vel * 3600 / 63360 * 0.75) Wire_TriggerOutput(self.Entity, "KPH", vel * 3600 * 0.0000254 * 0.75) end if (self.AngVel) then local ang = self.Entity:GetPhysicsObject():GetAngleVelocity() Wire_TriggerOutput(self.Entity, "AngVel_P", ang.y) Wire_TriggerOutput(self.Entity, "AngVel_Y", ang.z) Wire_TriggerOutput(self.Entity, "AngVel_R", ang.x) end self.Entity:NextThink(CurTime()+0.04) return true end function MakeWireSpeedometer( pl, Pos, Ang, model, xyz_mode, AngVel, nocollide, frozen ) if !pl:CheckLimit( "wire_speedometers" ) then return false end local wire_speedometer = ents.Create("gmod_wire_speedometer") if !wire_speedometer:IsValid() then return false end wire_speedometer:SetAngles(Ang) wire_speedometer:SetPos(Pos) wire_speedometer:SetModel(model or MODEL) wire_speedometer:Spawn() wire_speedometer:Setup(xyz_mode, AngVel) wire_speedometer:SetPlayer(pl) wire_speedometer.pl = pl if wire_speedometer:GetPhysicsObject():IsValid() then wire_speedometer:GetPhysicsObject():EnableMotion(!frozen) if nocollide == true then wire_speedometer:GetPhysicsObject():EnableCollisions(false) end end pl:AddCount( "wire_speedometers", wire_speedometer ) pl:AddCleanup( "gmod_wire_speedometer", wire_speedometer ) return wire_speedometer end duplicator.RegisterEntityClass("gmod_wire_speedometer", MakeWireSpeedometer, "Pos", "Ang", "Model", "z_only", "AngVel", "nocollide", "frozen")
gpl-3.0
ruvolof/telegram-bot
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
snogglethorpe/snogray
lua-util/file.lua
1
2139
-- file.lua -- Miscellaneous file-related functions -- -- Copyright (C) 2012, 2013 Miles Bader <miles@gnu.org> -- -- This source code is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 3, or (at -- your option) any later version. See the file COPYING for more details. -- -- Written by Miles Bader <miles@gnu.org> -- -- module -- local file = {} -- imports -- local util = require 'snogray.util' -- Return true if a file called FILENAME exists and is readable. -- function file.exists (filename) local stream = io.open (filename, "r") if stream then stream:close () return true else return false end end -- Return a string containing the entire contents of the file -- FILENAME. If an error occurs, return nil and an error description. -- -- This is basically equivalent to io.open(filename,"r"):read"*a" -- (plus closing the file) but much more efficient and less likely to -- thrash the system to death when reading huge files. -- function file.read (filename) local contents = util.read_file (filename) if not contents then local stream, err = io.open (filename, "r") if not stream then return nil, err end contents = stream:read ("*a") stream:close () end return contents end -- Choose a "backup filename" (using the GNU convention of suffixes like -- ".~1~", ".~2~" etc), and rename FILE_NAME to it. The backup filename -- is returned. If this cannot be done an exception is thrown. -- function file.rename_to_backup_file (filename, backup_limit) local backup_name local backup_num = 1 while backup_num < backup_limit do backup_name = filename .. ".~" .. tostring (backup_num) .. "~" if not file.exists (backup_name) then break end backup_num = backup_num + 1 end if backup_num == backup_limit then error (filename .. ": Too many backup files already exist", 0) end os.rename (filename, backup_name) return backup_name end -- return the module -- return file
gpl-3.0
maxmax1/fooniks
resources/poffer/poffer_s.lua
2
3746
PlayerOffer = { pTable = { }, offers = { }, cIndex = 1 }; function PlayerOffer:new( o ) o = o or { }; setmetatable( o, self ); self.__index = self; return o; end function PlayerOffer:Cancel( offerId, thePlayer ) if( self.offers[offerId] ) then if( self.offers[offerId].fromPlayer == thePlayer ) then triggerClientEvent( self.offers[offerId].toPlayer, "unsetClientOffer", self.offers[offerId].toPlayer ); if( self.offers[offerId].fromPlayer ) then self.pTable[self.offers[offerId].fromPlayer] = nil; end if( self.offers[offerId].toPlayer ) then self.pTable[self.offers[offerId].toPlayer] = nil; end self.offers[offerId].fromPlayer = nil; self.offers[offerId].toPlayer = nil; self.offers[offerId] = nil; else triggerClientEvent( self.offers[offerId].fromPlayer, "unsetClientOffer", self.offers[offerId].fromPlayer ); if( self.offers[offerId].fromPlayer ) then self.pTable[self.offers[offerId].fromPlayer] = nil; end if( self.offers[offerId].toPlayer ) then self.pTable[self.offers[offerId].toPlayer] = nil; end self.offers[offerId].fromPlayer = nil; self.offers[offerId].toPlayer = nil; self.offers[offerId] = nil; end end end function PlayerOffer:Add( from, to, maxdistance, toStr, fromStr, retEvent ) self.offers[cIndex] = { }; self.offers[cIndex].fromPlayer = from; self.offers[cIndex].toPlayer = to; self.offers[cIndex].distance = tonumber( maxdistance ); self.offers[cIndex].event = retEvent; self.pTable[from] = cIndex; self.pTable[to] = cIndex; cIndex = cIndex + 1; triggerClientEvent( from, "setClientOffer", from, fromStr ); triggerClientEvent( to, "setClientOffer", to, toStr ); end function PlayerOffer:Trigger( offerId ) if( self.offers[offerId] ) then if( self.offers[offerId].fromPlayer and self.offers[offerId].toPlayer ) then local x1, y1, z1 = getElementPosition( self.offers[offerId].fromPlayer ); local x2, y2, z2 = getElementPosition( self.offers[offerId].toPlayer ); if( self.offers[offerId].distance and self.offers[offerId].distance < getDistanceBetweenPoints3D( x1, y1, z1, x2, y2, z2 ) ) then exports.phoenix_Chat:OocInfo( self.offers[offerId].fromPlayer, "Sa oled liiga kaugel." ); exports.phoenix_Chat:OocInfo( self.offers[offerId].toPlayer, "Sa oled pakkujast liiga kaugel." ); return false; end triggerServerEvent( self.offers[offerId].event, getRootElement( ), self.offers[offerId].fromPlayer, self.offers[offerId].toPlayer ); return true; end end end function PlayerOffer:doEvents( ) addEvent( "onOfferResponse", true ); addEventHandler( "onOfferResponse", getRootElement( ), function ( accepted ) if( client ) then -- self:HandleResponce( ); if( self.pTable[client] and self.offers[self.pTable[client]] ) then if( self.offers[self.pTable[client]].fromPlayer and self.offers[self.pTable[client]].fromPlayer == client ) then -- Responce by sender. Cancel everything if wanted to cancel... if( not accepted ) then return true; else return self:Cancel( self.pTable[client], client ); end elseif( self.offers[self.pTable[client]].toPlayer and self.offers[self.pTable[client]].toPlayer == client ) then if( accepted ) then self:Trigger( self.pTable[client] ); -- needs to check maxdistance... end return self:Cancel( self.pTable[client], client ); end end end end ); end
gpl-3.0
mamaddeveloper/miri
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
zhangf911/alilua
route.lua
3
1066
local routes = {} routes['^/(.*).(jpg|gif|png|css|js|ico|swf|flv|mp3|mp4|woff|eot|ttf|otf|svg)$'] = function() header('Cache-Control: max-age=864000') if headers.uri:find('.js',1,1) or headers.uri:find('.css',1,1) then -- cloud be gzip local mtime = filemtime(headers.uri) if headers['if-none-match'] and tonumber(headers['if-none-match']) == mtime then header('HTTP/1.1 304 Not Modified') else header('Etag: '..mtime) echo(readfile(headers.uri)) end else sendfile(headers.uri) end end routes['^/user/:user_id'] = function(r) echo('User ID: ', r.user_id) end routes['^/user/:user_id/:post(.+)'] = function(r) echo('User ID: ', r.user_id) echo(' Post: ', r.post) end routes['^/(.*)'] = function(r) dofile('/index.lua') end --[[ others you want :) ]] -- if the 3rd argument is a path, then router will try to get local lua script file first if not router(headers.uri, routes, '/') then header('HTTP/1.1 404 Not Found') echo('File Not Found!') end
mit
tempbottle/alilua
route.lua
3
1066
local routes = {} routes['^/(.*).(jpg|gif|png|css|js|ico|swf|flv|mp3|mp4|woff|eot|ttf|otf|svg)$'] = function() header('Cache-Control: max-age=864000') if headers.uri:find('.js',1,1) or headers.uri:find('.css',1,1) then -- cloud be gzip local mtime = filemtime(headers.uri) if headers['if-none-match'] and tonumber(headers['if-none-match']) == mtime then header('HTTP/1.1 304 Not Modified') else header('Etag: '..mtime) echo(readfile(headers.uri)) end else sendfile(headers.uri) end end routes['^/user/:user_id'] = function(r) echo('User ID: ', r.user_id) end routes['^/user/:user_id/:post(.+)'] = function(r) echo('User ID: ', r.user_id) echo(' Post: ', r.post) end routes['^/(.*)'] = function(r) dofile('/index.lua') end --[[ others you want :) ]] -- if the 3rd argument is a path, then router will try to get local lua script file first if not router(headers.uri, routes, '/') then header('HTTP/1.1 404 Not Found') echo('File Not Found!') end
mit
Aico/mudlet
src/old_mudlet-lua/lua/StringUtils.lua
10
4592
---------------------------------------------------------------------------------- --- Mudlet String Utils ---------------------------------------------------------------------------------- --- Cut string to specified maximum length. --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @usage Following call will return 'abc'. --- <pre> --- string.cut("abcde", 3) --- </pre> --- @usage You can easily pad string to certain length. --- Example bellow will print 'abcde ' e.g. pad/cut string to 10 characters. --- <pre> --- local s = "abcde" --- s = string.cut(s .. " ", 10) -- append 10 spaces --- echo("'" .. s .. "'") --- </pre> function string.cut(s, maxLen) if string.len(s) > maxLen then return string.sub(s, 1, maxLen) else return s end end --- Enclose string by long brackets. <br/> function string.enclose(s, maxlevel) s = "["..s.."]" local level = 0 while 1 do if maxlevel and level == maxlevel then error( "error: maxlevel too low, "..maxlevel ) elseif string.find( s, "%["..string.rep( "=", level ).."%[" ) or string.find( s, "]"..string.rep( "=", level ).."]" ) then level = level + 1 else return "["..string.rep( "=", level )..s..string.rep( "=", level ).."]" end end end --- Test if string is ending with specified suffix. --- --- @see string.starts function string.ends(String, Suffix) return Suffix=='' or string.sub(String,-string.len(Suffix))==Suffix end --- Generate case insensitive search pattern from string. --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @return case insensitive pattern string --- --- @usage Following example will generate and print <i>"123[aA][bB][cC]"</i> string. --- <pre> --- echo(string.genNocasePattern("123abc")) --- </pre> function string.genNocasePattern(s) s = string.gsub(s, "%a", function (c) return string.format("[%s%s]", string.lower(c), string.upper(c)) end) return s end --- Return first matching substring or nil. --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @return nil or first matching substring --- --- @usage Following example will print: "I did find: Troll" string. --- <pre> --- local match = string.findPattern("Troll is here!", "Troll") --- if match then --- echo("I did find: " .. match) --- end --- </pre> --- @usage This example will find substring regardless of case. --- <pre> --- local match = string.findPattern("Troll is here!", string.genNocasePattern("troll")) --- if match then --- echo("I did find: " .. match) --- end --- </pre> --- --- @see string.genNocasePattern function string.findPattern(text, pattern) if string.find(text, pattern, 1) then return string.sub(text, string.find(text, pattern, 1)) else return nil end end --- Splits a string into a table by the given delimiter. --- --- @usage Split string by ", " delimiter. --- <pre> --- names = "Alice, Bob, Peter" --- name_table = names:split(", ") --- display(name_table) --- </pre> --- --- Previous code will print out: --- <pre> --- table { --- 1: 'Alice' --- 2: 'Bob' --- 3: 'Peter' --- } --- </pre> --- --- @return array with split strings function string:split(delimiter) local result = { } local from = 1 local delim_from, delim_to = string.find( self, delimiter, from ) while delim_from do table.insert( result, string.sub( self, from , delim_from-1 ) ) from = delim_to + 1 delim_from, delim_to = string.find( self, delimiter, from ) end table.insert( result, string.sub( self, from ) ) return result end --- Test if string is starting with specified prefix. --- --- @see string.ends function string.starts(String, Prefix) return string.sub(String,1,string.len(Prefix))==Prefix end --- Capitalize first character in a string. --- --- @usage Variable testname is now Anna. --- <pre> --- testname = string.title("anna") --- </pre> --- @usage Example will set test to "Bob". --- <pre> --- test = "bob" --- test = string.title(test) --- </pre> function string:title() self = self:gsub("^%l", string.upper, 1) return self end --- Trim string (remove all white spaces around string). --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @usage Example will print 'Troll is here!'. --- <pre> --- local str = string.trim(" Troll is here! ") --- echo("'" .. str .. "'") --- </pre> function string.trim(s) if s then return string.gsub(s, "^%s*(.-)%s*$", "%1") else return s end end
gpl-2.0
milos-korenciak/heroku-buildpack-tex
buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/control/Anchoring.lua
1
2806
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/control/Anchoring.lua,v 1.6 2013/05/23 20:01:25 tantau Exp $ --- -- @section subsection {Anchoring a Graph} -- -- \label{subsection-library-graphdrawing-anchoring} -- -- A graph drawing algorithm must compute positions of the nodes of a -- graph, but the computed positions are only \emph{relative} (``this -- node is left of this node, but above that other node''). It is not -- immediately obvious where the ``the whole graph'' should be placed -- \emph{absolutely} once all relative positions have been computed. In -- case that the graph consists of several unconnected components, the -- situation is even more complicated. -- -- The order in which the algorithm layer determines the node at which -- the graph should be anchored: -- -- \begin{enumerate} -- \item If the |anchor node=|\meta{node name} option given to the graph -- as a whole, the graph is anchored at \meta{node name}, provided -- there is a node of this name in the graph. (If there is no node of -- this name or if it is misspelled, the effect is the same as if this -- option had not been given at all.) -- \item Otherwise, if there is a node where the |anchor here| option is -- specified, the first node with this option set is used. -- \item Otherwise, if there is a node where the |desired at| option is -- set (perhaps implicitly through keys like |x|), the first such node -- is used. -- \item Finally, in all other cases, the first node is used. -- \end{enumerate} -- -- In the above description, the ``first'' node refers to the node first -- encountered in the specification of the graph. -- -- Once the node has been determined, the graph is shifted so that -- this node lies at the poistion specified by |anchor at|. -- -- @end local Anchoring = {} -- Namespace require("pgf.gd.control").Anchoring = Anchoring -- Imports local Coordinate = require("pgf.gd.model.Coordinate") local declare = require "pgf.gd.interface.InterfaceToAlgorithms".declare --- declare { key = "desired at", type = "coordinate", documentation_in = "pgf.gd.doc.control.Anchoring" } --- declare { key = "anchor node", type = "string", documentation_in = "pgf.gd.doc.control.Anchoring" } --- declare { key = "anchor at", type = "canvas coordinate", initial = "(0pt,0pt)", documentation_in = "pgf.gd.doc.control.Anchoring" } --- declare { key = "anchor here", type = "boolean", documentation_in = "pgf.gd.doc.control.Anchoring" } -- Done return Anchoring
mit
sanger-pathogens/companion
bin/add_products_to_fasta.lua
4
4125
#!/usr/bin/env gt --[[ Author: Sascha Steinbiss <ss34@sanger.ac.uk> Copyright (c) 2015 Genome Research Ltd Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ]] function usage() io.stderr:write("Add preferred product terms to protein sequence headers.\n") io.stderr:write(string.format("Usage: %s <GFF annotation> <protein seqs>\n" , arg[0])) os.exit(1) end if #arg < 2 then usage() end function gff3_extract_structure(str) ret = {} for _,v in ipairs(split(str, ", ?")) do res = {} v = gff3_decode(v) for _,pair in ipairs(split(v, ";")) do if string.len(pair) > 0 then key, value = unpack(split(pair, "=")) res[key] = value end end table.insert(ret, res) end return ret end function split(str, pat) local t = {} local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) table.insert(t, cap) end return t end function gff3_decode(s) if not s then return s end s = string.gsub(s, "%%([0-9a-fA-F][1-9a-fA-F])", function (n) return string.char(tonumber("0x" .. n)) end) return s end function get_fasta(filename, sep) local keys = {} local seqs = {} local cur_hdr = nil local cur_seqs = {} for l in io.lines(filename) do hdr = l:match(">(.*)") if hdr then table.insert(keys, hdr) if #cur_seqs > 0 and cur_hdr then if not seqs[cur_hdr] then seqs[cur_hdr] = table.concat(cur_seqs, sep) end end cur_hdr = hdr cur_seqs = {} else table.insert(cur_seqs, l) end end if cur_hdr and not seqs[cur_hdr] then seqs[cur_hdr] = table.concat(cur_seqs, sep) end return keys, seqs end function get_fasta_nosep(filename) return get_fasta(filename, "") end function print_max_width(str, ioo, width) local i = 1 while (i + width - 1) < str:len() do ioo:write(str:sub(i, i + width - 1)) ioo:write("\n") i = i + width end ioo:write(str:sub(i)) ioo:write("\n") end products = {} visitor = gt.custom_visitor_new() visitor.last_seqid = nil function visitor:visit_feature(fn) for node in fn:children() do if node:get_type() == "polypeptide" then local dfrom = node:get_attribute("Derives_from") local product = node:get_attribute("product") if (dfrom and product) then local p_data = gff3_extract_structure(product) local mterm = p_data[1].term for _,v in ipairs(p_data) do if v.is_preferred then mterm = v.term end end products[dfrom] = mterm end end end return 0 end visitor_stream = gt.custom_stream_new_unsorted() function visitor_stream:next_tree() local node = self.instream:next_tree() if node then node:accept(self.vis) end return node end visitor_stream.instream = gt.gff3_in_stream_new_sorted(arg[1]) visitor_stream.vis = visitor local gn = visitor_stream:next_tree() while (gn) do gn = visitor_stream:next_tree() end keys, seqs = get_fasta_nosep(arg[2]) for i,k in ipairs(keys) do local rid = split(k, "%s+")[1] if products[rid] then print(">".. rid .. " " .. products[rid]) else print(">".. rid) end print_max_width(seqs[k], io.stdout, 60) end
isc
milos-korenciak/heroku-buildpack-tex
buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/trees/ChildSpec.lua
3
7344
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/trees/ChildSpec.lua,v 1.4 2013/05/23 20:01:29 tantau Exp $ --- -- @section subsection {Specifying Missing Children} -- -- \label{section-gd-missing-children} -- -- In the present section we discuss keys for specifying missing children -- in a tree. For many certain kind of trees, in particular for binary -- trees, there are not just ``a certain number of children'' at each -- node, but, rather, there is a designated ``first'' (or ``left'') child -- and a ``second'' (or ``right'') child. Even if one of these children -- is missing and a node actually has only one child, the single child will -- still be a ``first'' or ``second'' child and this information should -- be taken into consideration when drawing a tree. -- -- The first useful key for specifying missing children is -- |missing number of children| which allows you to state how many -- children there are, at minimum. -- -- Once the minimum number of children has been set, we still need a way -- of specifying ``missing first children'' or, more generally, missing -- children that are not ``at the end'' of the list of children. For -- this, there are three methods: -- -- \begin{enumerate} -- \item When you use the |child| syntax, you can use the |missing| key -- with the |child| command to indicate a missing child: -- \begin{codeexample}[] -- \tikz [binary tree layout, level distance=5mm] -- \node {a} -- child { node {b} -- child { node {c} -- child { node {d} } -- } } -- child { node {e} -- child [missing] -- child { node {f} -- child [missing] -- child { node {g} -- } } }; -- \end{codeexample} -- \item When using the |graph| syntax, you can use an ``empty node'', -- which really must be completely empty and may not even contain a -- slash, to indicate a missing node: -- \begin{codeexample}[] -- \tikz [binary tree layout, level distance=5mm] -- \graph { a -> { b -> c -> d, e -> { , f -> { , g} } } }; -- \end{codeexample} -- \item You can simply specify the index of a child directly using -- the key |desired child index|. -- \end{enumerate} -- -- @end -- Imports local declare = require("pgf.gd.interface.InterfaceToAlgorithms").declare --- -- declare { key = "minimum number of children", type = "number", initial = "0", summary = [[" Specifies how many children a tree node must have at least. If there are less, ``virtual'' children are added. "]], documentation = [[" When this key is set to |2| or more, the following happens: We first compute a spanning tree for the graph, see Section~\ref{subsection-gd-spanning-tree}. Then, whenever a node is not a leaf in this spanning tree (when it has at least one child), we add ``virtual'' or ``dummy'' nodes as children of the node until the total number of real and dummy children is at least \meta{number}. If there where at least \meta{number} children at the beginning, nothing happens. The new children are added after the existing children. This means that, for instance, in a tree with \meta{number} set to |2|, for every node with a single child, this child will be the first child and the second child will be missing. "]], examples = [[" \tikz \graph [binary tree layout,level distance=5mm] { a -> { b->c->d, e->f->g } }; "]] } --- declare { key = "desired child index", type = "number", summary = [[" Pass this key to a node to tell the graph drawing engine which child number you ``desired'' for the node. Whenever all desires for the children of a node are conflict-free, they will all be met; children for which no desired indices were given will remain at their position, whenever possible, but will ``make way'' for children with a desired position. "]], documentation = [[" In detail, the following happens: We first determine the total number of children (real or dummy) needed, which is the maximum of the actual number of children, of the \texttt{minimum number of children}, and of the highest desired child index. Then we go over all children that have a desired child index and put they at this position. If the position is already taken (because some other child had the same desired index), the next free position is used with a wrap-around occurring at the end. Next, all children without a desired index are place using the same mechanism, but they want to be placed at the position they had in the original spanning tree. While all of this might sound a bit complicated, the application of the key in a binary tree is pretty straightforward: To indicate that a node is a ``right'' child in a tree, just add \texttt{desired child index=2} to it. This will make it a second child, possibly causing the fist child to be missing. If there are two nodes specified as children of a node, by saying \texttt{desired child index=}\meta{number} for one of them, you will cause it be first or second child, depending on \meta{number}, and cause the \emph{other} child to become the other child. Since |desired child index=2| is a bit long, the following shortcuts are available: |first|, |second|, |third|, and |fourth|. You might wonder why |second| is used rather than |right|. The reason is that trees may also grow left and right and, additionally, the |right| and |left| keys are already in use for anchoring. Naturally, you can locally redefine them, if you want. "]], examples = { [[" \tikz \graph [binary tree layout, level distance=5mm] { a -> b[second] }; "]], [[" \tikz \graph [binary tree layout, level distance=5mm] { a -> { b[second], c} }; "]], [[" \tikz \graph [binary tree layout, level distance=5mm] { a -> { b, c[first]} }; "]], [[" \tikz \graph [binary tree layout, level distance=5mm] { a -> { b[second], c[second]} }; "]], [[" \tikz \graph [binary tree layout, level distance=5mm] { a -> { b[third], c[first], d} }; "]] } } --- declare { key = "first", use = { { key = "desired child index", value = 1}, }, summary = [[" A shorthand for setting the desired child number to |1|. "]] } --- declare { key = "second", use = { { key = "desired child index", value = 2}, }, summary = [[" A shorthand for setting the desired child number to |2|. "]] } --- declare { key = "third", use = { { key = "desired child index", value = 3}, }, summary = [[" A shorthand for setting the desired child number to |3|. "]] } --- declare { key = "fourth", use = { { key = "desired child index", value = 4} }, summary = [[" A shorthand for setting the desired child number to |4|. "]] }
mit
kirkbridge/gamecode4
Assets/Scripts/Events.lua
44
2298
--======================================================================== -- Events.lua : Defines event handler delegate functions for events -- -- Part of the GameCode4 Application -- -- GameCode4 is the sample application that encapsulates much of the source code -- discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David -- "Rez" Graham, published by Charles River Media. -- ISBN-10: 1133776574 | ISBN-13: 978-1133776574 -- -- If this source code has found it's way to you, and you think it has helped you -- in any way, do the authors a favor and buy a new copy of the book - there are -- detailed explanations in it that compliment this code well. Buy a copy at Amazon.com -- by clicking here: -- http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller= -- -- There's a companion web site at http://www.mcshaffry.com/GameCode/ -- -- The source code is managed and maintained through Google Code: -- http://code.google.com/p/gamecode4/ -- -- (c) Copyright 2012 Michael L. McShaffry and David Graham -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser GPL v3 -- as published by the Free Software Foundation. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See -- http://www.gnu.org/licenses/lgpl-3.0.txt for more details. -- -- You should have received a copy of the GNU Lesser GPL v3 -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- --======================================================================== function OnPhysicsCollision(eventData) g_actorMgr:OnPhysicsCollision(eventData); end function OnFireWeapon(eventData) g_actorMgr:OnFireWeapon(eventData); end function RegisterListeners() if (EventType.EvtData_PhysCollision ~= nil) then RegisterEventListener(EventType.EvtData_PhysCollision, OnPhysicsCollision); end if (EventType.EvtData_Fire_Weapon ~= nil) then RegisterEventListener(EventType.EvtData_Fire_Weapon, OnFireWeapon); end end
lgpl-3.0
shahabsaf1/tg
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
resistor58/deaths-gmod-server
wire/lua/entities/gmod_wire_keyboard/remap.lua
1
10218
Wire_Keyboard_Remap = {} ---------------------------------------------------------------------- -- Default - Keys that all layouts use ---------------------------------------------------------------------- local Wire_Keyboard_Remap_default = {} Wire_Keyboard_Remap_default.normal = {} Wire_Keyboard_Remap_default[KEY_LSHIFT] = {} Wire_Keyboard_Remap_default[KEY_RSHIFT] = Wire_Keyboard_Remap_default[KEY_LSHIFT] local remap = Wire_Keyboard_Remap_default.normal remap[KEY_NONE] = "" remap[KEY_0] = "0" remap[KEY_1] = "1" remap[KEY_2] = "2" remap[KEY_3] = "3" remap[KEY_4] = "4" remap[KEY_5] = "5" remap[KEY_6] = "6" remap[KEY_7] = "7" remap[KEY_8] = "8" remap[KEY_9] = "9" remap[KEY_A] = "a" remap[KEY_B] = "b" remap[KEY_C] = "c" remap[KEY_D] = "d" remap[KEY_E] = "e" remap[KEY_F] = "f" remap[KEY_G] = "g" remap[KEY_H] = "h" remap[KEY_I] = "i" remap[KEY_J] = "j" remap[KEY_K] = "k" remap[KEY_L] = "l" remap[KEY_M] = "m" remap[KEY_N] = "n" remap[KEY_O] = "o" remap[KEY_P] = "p" remap[KEY_Q] = "q" remap[KEY_R] = "r" remap[KEY_S] = "s" remap[KEY_T] = "t" remap[KEY_U] = "u" remap[KEY_V] = "v" remap[KEY_W] = "w" remap[KEY_X] = "x" remap[KEY_Y] = "y" remap[KEY_Z] = "z" remap[KEY_PAD_0] = 128 remap[KEY_PAD_1] = 129 remap[KEY_PAD_2] = 130 remap[KEY_PAD_3] = 131 remap[KEY_PAD_4] = 132 remap[KEY_PAD_5] = 133 remap[KEY_PAD_6] = 134 remap[KEY_PAD_7] = 135 remap[KEY_PAD_8] = 136 remap[KEY_PAD_9] = 137 remap[KEY_PAD_DIVIDE] = 138 remap[KEY_PAD_MULTIPLY] = 139 remap[KEY_PAD_MINUS] = 140 remap[KEY_PAD_PLUS] = 141 remap[KEY_PAD_ENTER] = 142 remap[KEY_PAD_DECIMAL] = 143 remap[KEY_ENTER] = 13 remap[KEY_SPACE] = " " remap[KEY_BACKSPACE] = 127 remap[KEY_TAB] = 9 remap[KEY_CAPSLOCK] = 144 remap[KEY_NUMLOCK] = 145 remap[KEY_ESCAPE] = 18 remap[KEY_SCROLLLOCK] = 146 remap[KEY_INSERT] = 147 remap[KEY_DELETE] = 148 remap[KEY_HOME] = 149 remap[KEY_END] = 150 remap[KEY_PAGEUP] = 151 remap[KEY_PAGEDOWN] = 152 remap[KEY_BREAK] = 153 remap[KEY_LSHIFT] = 154 remap[KEY_RSHIFT] = 155 remap[KEY_LALT] = 156 remap[KEY_RALT] = 157 remap[KEY_LCONTROL] = 158 remap[KEY_RCONTROL] = 159 remap[KEY_LWIN] = 160 remap[KEY_RWIN] = 161 remap[KEY_APP] = 162 remap[KEY_UP] = 17 remap[KEY_LEFT] = 19 remap[KEY_DOWN] = 18 remap[KEY_RIGHT] = 20 remap[KEY_F1] = 163 remap[KEY_F2] = 164 remap[KEY_F3] = 165 remap[KEY_F4] = 166 remap[KEY_F5] = 167 remap[KEY_F6] = 168 remap[KEY_F7] = 169 remap[KEY_F8] = 170 remap[KEY_F9] = 171 remap[KEY_F10] = 172 remap[KEY_F11] = 173 remap[KEY_F12] = 174 remap[KEY_CAPSLOCKTOGGLE] = 175 remap[KEY_NUMLOCKTOGGLE] = 176 remap[KEY_SCROLLLOCKTOGGLE] = 177 remap[KEY_XBUTTON_UP] = 200 remap[KEY_XBUTTON_DOWN] = 201 remap[KEY_XBUTTON_LEFT] = 202 remap[KEY_XBUTTON_RIGHT] = 203 remap[KEY_XBUTTON_START] = 204 remap[KEY_XBUTTON_BACK] = 205 remap[KEY_XBUTTON_STICK1] = 206 remap[KEY_XBUTTON_STICK2] = 207 remap[KEY_XBUTTON_A] = 208 remap[KEY_XBUTTON_B] = 209 remap[KEY_XBUTTON_X] = 210 remap[KEY_XBUTTON_Y] = 211 remap[KEY_XBUTTON_LTRIGGER] = 214 remap[KEY_XBUTTON_RTRIGGER] = 215 remap[KEY_XSTICK1_UP] = 216 remap[KEY_XSTICK1_DOWN] = 217 remap[KEY_XSTICK1_LEFT] = 218 remap[KEY_XSTICK1_RIGHT] = 219 remap[KEY_XSTICK2_UP] = 220 remap[KEY_XSTICK2_DOWN] = 221 remap[KEY_XSTICK2_LEFT] = 222 remap[KEY_XSTICK2_RIGHT] = 223 local remap = Wire_Keyboard_Remap_default[KEY_LSHIFT] remap[KEY_A] = "A" remap[KEY_B] = "B" remap[KEY_C] = "C" remap[KEY_D] = "D" remap[KEY_E] = "E" remap[KEY_F] = "F" remap[KEY_G] = "G" remap[KEY_H] = "H" remap[KEY_I] = "I" remap[KEY_J] = "J" remap[KEY_K] = "K" remap[KEY_L] = "L" remap[KEY_M] = "M" remap[KEY_N] = "N" remap[KEY_O] = "O" remap[KEY_P] = "P" remap[KEY_Q] = "Q" remap[KEY_R] = "R" remap[KEY_S] = "S" remap[KEY_T] = "T" remap[KEY_U] = "U" remap[KEY_V] = "V" remap[KEY_W] = "W" remap[KEY_X] = "X" remap[KEY_Y] = "Y" remap[KEY_Z] = "Z" ---------------------------------------------------------------------- -- American ---------------------------------------------------------------------- Wire_Keyboard_Remap.American = {} Wire_Keyboard_Remap.American = table.Copy(Wire_Keyboard_Remap_default) Wire_Keyboard_Remap.American[KEY_RSHIFT] = Wire_Keyboard_Remap.American[KEY_LSHIFT] local remap = Wire_Keyboard_Remap.American.normal remap[KEY_LBRACKET] = "[" remap[KEY_RBRACKET] = "]" remap[KEY_SEMICOLON] = ";" remap[KEY_APOSTROPHE] = "'" remap[KEY_BACKQUOTE] = "`" remap[KEY_COMMA] = "," remap[KEY_PERIOD] = "." remap[KEY_SLASH] = "/" remap[KEY_BACKSLASH] = "\\" remap[KEY_MINUS] = "-" remap[KEY_EQUAL] = "=" local remap = Wire_Keyboard_Remap.American[KEY_LSHIFT] remap[KEY_0] = ")" remap[KEY_1] = "!" remap[KEY_2] = "@" remap[KEY_3] = "#" remap[KEY_4] = "$" remap[KEY_5] = "%" remap[KEY_6] = "^" remap[KEY_7] = "&" remap[KEY_8] = "*" remap[KEY_9] = "(" remap[KEY_LBRACKET] = "{" remap[KEY_RBRACKET] = "}" remap[KEY_SEMICOLON] = ":" remap[KEY_APOSTROPHE] = '"' remap[KEY_COMMA] = "<" remap[KEY_PERIOD] = ">" remap[KEY_SLASH] = "?" remap[KEY_BACKSLASH] = "|" remap[KEY_MINUS] = "_" remap[KEY_EQUAL] = "+" ---------------------------------------------------------------------- -- British ---------------------------------------------------------------------- Wire_Keyboard_Remap.British = {} Wire_Keyboard_Remap.British = table.Copy(Wire_Keyboard_Remap.American) Wire_Keyboard_Remap.British[83] = {} Wire_Keyboard_Remap.British[KEY_RSHIFT] = Wire_Keyboard_Remap.British[KEY_LSHIFT] local remap = Wire_Keyboard_Remap.British.normal remap[KEY_BACKQUOTE] = "'" remap[KEY_APOSTROPHE] = "#" local remap = Wire_Keyboard_Remap.British[KEY_LSHIFT] remap[KEY_2] = '"' remap[KEY_3] = "£" remap[KEY_APOSTROPHE] = "~" remap[KEY_BACKQUOTE] = "@" local remap = Wire_Keyboard_Remap.British[83] remap[KEY_4] = "€" remap[KEY_A] = "á" remap[KEY_E] = "é" remap[KEY_I] = "í" remap[KEY_O] = "ó" remap[KEY_U] = "ú" ---------------------------------------------------------------------- -- Swedish ---------------------------------------------------------------------- Wire_Keyboard_Remap.Swedish = {} Wire_Keyboard_Remap.Swedish = table.Copy(Wire_Keyboard_Remap_default) Wire_Keyboard_Remap.Swedish[83] = {} -- KEY_RALT = 82, but didn't work correctly Wire_Keyboard_Remap.Swedish[KEY_RSHIFT] = Wire_Keyboard_Remap.Swedish[KEY_LSHIFT] local remap = Wire_Keyboard_Remap.Swedish.normal remap[KEY_LBRACKET] = "´" remap[KEY_RBRACKET] = "å" remap[KEY_SEMICOLON] = "¨" remap[KEY_APOSTROPHE] = "ä" remap[KEY_BACKQUOTE] = "ö" remap[KEY_COMMA] = "," remap[KEY_PERIOD] = "." remap[KEY_SLASH] = "'" remap[KEY_BACKSLASH] = "§" remap[KEY_MINUS] = "-" remap[KEY_EQUAL] = "+" local remap = Wire_Keyboard_Remap.Swedish[KEY_LSHIFT] remap[KEY_0] = "=" remap[KEY_1] = "!" remap[KEY_2] = '"' remap[KEY_3] = "#" remap[KEY_4] = "¤" remap[KEY_5] = "%" remap[KEY_6] = "&" remap[KEY_7] = "/" remap[KEY_8] = "(" remap[KEY_9] = ")" remap[KEY_LBRACKET] = "`" remap[KEY_RBRACKET] = "Å" remap[KEY_BACKQUOTE] = "Ö" remap[KEY_SEMICOLON] = "^" remap[KEY_APOSTROPHE] = "Ä" remap[KEY_COMMA] = ";" remap[KEY_PERIOD] = ":" remap[KEY_SLASH] = "*" remap[KEY_BACKSLASH] = "½" remap[KEY_MINUS] = "_" remap[KEY_EQUAL] = "?" local remap = Wire_Keyboard_Remap.Swedish[83] remap[KEY_2] = "@" remap[KEY_3] = "£" remap[KEY_4] = "$" remap[KEY_7] = "{" remap[KEY_8] = "[" remap[KEY_9] = "]" remap[KEY_0] = "}" remap[KEY_EQUAL] = "\\" remap[KEY_SEMICOLON] = "~" remap[KEY_E] = "€" ---------------------------------------------------------------------- -- Norwegian ---------------------------------------------------------------------- Wire_Keyboard_Remap.Norwegian = {} Wire_Keyboard_Remap.Norwegian = table.Copy(Wire_Keyboard_Remap.Swedish) Wire_Keyboard_Remap.Norwegian[KEY_RSHIFT] = Wire_Keyboard_Remap.Norwegian[KEY_LSHIFT] local remap = Wire_Keyboard_Remap.Norwegian.normal remap[KEY_BACKQUOTE] = "ø" remap[KEY_APOSTROPHE] = "æ" remap[KEY_BACKSLASH] = "|" remap[KEY_LBRACKET] = "\\" local remap = Wire_Keyboard_Remap.Norwegian[KEY_LSHIFT] remap[KEY_BACKQUOTE] = "Ø" remap[KEY_APOSTROPHE] = "Æ" remap[KEY_BACKSLASH] = "§" local remap = Wire_Keyboard_Remap.Norwegian[83] remap[KEY_EQUAL] = nil remap[KEY_M] = "µ" remap[KEY_LBRACKET] = "´" ---------------------------------------------------------------------- -- German ---------------------------------------------------------------------- Wire_Keyboard_Remap.German = {} Wire_Keyboard_Remap.German = table.Copy(Wire_Keyboard_Remap_default) Wire_Keyboard_Remap.German[83] = {} -- KEY_RALT = 82, but didn't work correctly Wire_Keyboard_Remap.German[KEY_RSHIFT] = Wire_Keyboard_Remap.German[KEY_LSHIFT] local remap = Wire_Keyboard_Remap.German.normal remap[KEY_LBRACKET] = "ß" remap[KEY_RBRACKET] = "´" remap[KEY_SEMICOLON] = "ü" remap[KEY_APOSTROPHE] = "ä" remap[KEY_BACKQUOTE] = "ö" remap[KEY_COMMA] = "," remap[KEY_PERIOD] = "." remap[KEY_SLASH] = "#" remap[KEY_BACKSLASH] = "^" remap[KEY_MINUS] = "-" remap[KEY_EQUAL] = "+" local remap = Wire_Keyboard_Remap.German[KEY_LSHIFT] remap[KEY_0] = "=" remap[KEY_1] = "!" remap[KEY_2] = '"' remap[KEY_3] = "§" remap[KEY_4] = "$" remap[KEY_5] = "%" remap[KEY_6] = "&" remap[KEY_7] = "/" remap[KEY_8] = "(" remap[KEY_9] = ")" remap[KEY_LBRACKET] = "?" remap[KEY_RBRACKET] = "`" remap[KEY_SEMICOLON] = "Ü" remap[KEY_APOSTROPHE] = 'Ä' remap[KEY_BACKQUOTE] = "Ö" remap[KEY_COMMA] = ";" remap[KEY_PERIOD] = ":" remap[KEY_SLASH] = "'" remap[KEY_BACKSLASH] = "°" remap[KEY_MINUS] = "_" remap[KEY_EQUAL] = "*" local remap = Wire_Keyboard_Remap.German[83] remap[KEY_0] = "}" remap[KEY_2] = '²' remap[KEY_3] = "³" remap[KEY_7] = "{" remap[KEY_8] = "[" remap[KEY_9] = "]" remap[KEY_E] = "€" remap[KEY_M] = "µ" remap[KEY_Q] = "@" remap[KEY_LBRACKET] = '\\' remap[KEY_EQUAL] = "~" remap[KEY_COMMA] = "<" remap[KEY_PERIOD] = ">" remap[KEY_MINUS] = "|"
gpl-3.0