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
nesstea/darkstar
scripts/zones/Temenos/mobs/Abyssdweller_Jhabdebb.lua
7
1581
----------------------------------- -- Area: Temenos -- NPC: ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (IsMobDead(16929010)==true and IsMobDead(16929011)==true and IsMobDead(16929012)==true and IsMobDead(16929013)==true and IsMobDead(16929014)==true and IsMobDead(16929015)==true ) then mob:setMod(MOD_SLASHRES,1400); mob:setMod(MOD_PIERCERES,1400); mob:setMod(MOD_IMPACTRES,1400); mob:setMod(MOD_HTHRES,1400); else mob:setMod(MOD_SLASHRES,300); mob:setMod(MOD_PIERCERES,300); mob:setMod(MOD_IMPACTRES,300); mob:setMod(MOD_HTHRES,300); end GetMobByID(16929006):updateEnmity(target); GetMobByID(16929007):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) if (IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true) then GetNPCByID(16928768+78):setPos(-280,-161,-440); GetNPCByID(16928768+78):setStatus(STATUS_NORMAL); GetNPCByID(16928768+473):setStatus(STATUS_NORMAL); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/qm2.lua
24
2318
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: ??? (Ix'aern (Dark Knight) Spawn) -- Allows players to spawn the Ix'aern (Dark Knight) by checking ??? only after killing the required mobs in the same room as the ???. -- @pos ,-560 5 239 ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/zones/The_Garden_of_RuHmet/MobIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ Kills = GetServerVariable("[PH]Ix_aern_drk"); --print(Kills) moba = GetMobByID(16921018); mobb = GetMobByID(16921019); mobc = GetMobByID(16921020); if (Kills == 0) then player:messageSpecial(UNKNOWN_PRESENCE); elseif (Kills == 1) then player:messageSpecial(NONE_HOSTILE); elseif (Kills == 2) then player:messageSpecial(NONE_HOSTILE);--(SHEER_ANIMOSITY); elseif (Kills == 3) then moba:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos. SpawnMob(16921018,180):updateClaim(player); mobb:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos. SpawnMob(16921019,180):updateClaim(player); mobc:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos. SpawnMob(16921020,180):updateClaim(player); GetNPCByID(16921028):hideNPC(900); if (math.random(0,1) == 1) then -- random do select which item do drop. Will select one item 100% of the time. SetDropRate(4397,1854,000); else SetDropRate(4397,1902,000); end end ]]-- end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); end;
gpl-3.0
xTVaser/ramwatches
docs/samples/games/sample_layouts.lua
1
3121
-- Layouts to use with sample.lua. package.loaded.utils = nil local utils = require 'utils' local subclass = utils.subclass package.loaded.layouts = nil local layoutsModule = require 'layouts' local Layout = layoutsModule.Layout local layouts = {} layouts.positionAndVelocity = subclass(Layout) function layouts.positionAndVelocity:init() self:setUpdatesPerSecond(30) self.window:setSize(400, 200) self:addLabel{x=6, y=6, fontSize=12, fontName="Consolas"} self:addItem(self.game.posX) self:addItem(self.game.posY) self:addItem(self.game.posZ) self:addItem(self.game.velX) self:addItem(self.game.velY) self:addItem(self.game.velZ) end layouts.displayExamples = subclass(Layout) function layouts.displayExamples:init() self:setUpdatesPerSecond(30) -- Let's have multiple labels which are spaced vertically across the window -- automatically. self:activateAutoPositioningY() self.window:setSize(400, 250) self.labelDefaults = {fontSize=12, fontName="Consolas"} self:addLabel() -- You can specify display options. self:addItem(self.game.posX, {afterDecimal=5, beforeDecimal=5, signed=true}) -- Display a Vector3Value. self:addItem(self.game.pos, {narrow=true}) self:addLabel() -- addItem() can take a string constant. self:addItem("----------") self:addLabel() -- addItem() can take a function that returns a string. self:addItem( function() local vx = self.game.velX:get() local vy = self.game.velY:get() local speedXY = math.sqrt(vx*vx + vy*vy) return "Speed XY: "..utils.floatToStr(speedXY) end ) end layouts.positionRecording = subclass(Layout) function layouts.positionRecording:init() -- This update method ensures that we record every frame, but this may incur -- a performance hit. If you want performance and it's OK to miss frames, -- use setUpdatesPerSecond() instead. self:setBreakpointUpdateMethod() self:activateAutoPositioningY() self.window:setSize(400, 160) self.labelDefaults = {fontSize=12, fontName="Consolas"} -- Display position. self:addLabel() self:addItem(self.game.posX) self:addItem(self.game.posY) self:addItem(self.game.posZ) local tabSeparatedPosition = function() local positionComponents = { self.game.posX:display{afterDecimal=8, nolabel=true}, self.game.posY:display{afterDecimal=8, nolabel=true}, self.game.posZ:display{afterDecimal=8, nolabel=true}, } return table.concat(positionComponents, '\t') end -- This adds a GUI element with a button. Click the button to start recording -- stats to a file. For every frame of recording, one line is added to -- the file. -- -- Look for the output .txt file in: -- A. The folder you saved your .CT file -- B. The folder with your Cheat Engine installation, if not running from a -- saved .CT file -- -- Because we separated the data elements with linebreaks and tabs (\t), we -- can easily paste the .txt contents into a spreadsheet for analysis. self:addFileWriter( tabSeparatedPosition, 'ram_watch_output.txt') end return { layouts = layouts, }
mit
Xileck/forgottenserver
config.lua
18
2408
-- Combat settings -- NOTE: valid values for worldType are: "pvp", "no-pvp" and "pvp-enforced" worldType = "pvp" hotkeyAimbotEnabled = true protectionLevel = 1 killsToRedSkull = 3 killsToBlackSkull = 6 pzLocked = 60000 removeChargesFromRunes = true timeToDecreaseFrags = 24 * 60 * 60 * 1000 whiteSkullTime = 15 * 60 * 1000 stairJumpExhaustion = 2000 experienceByKillingPlayers = false expFromPlayersLevelRange = 75 -- Connection Config -- NOTE: maxPlayers set to 0 means no limit ip = "127.0.0.1" bindOnlyGlobalAddress = false loginProtocolPort = 7171 gameProtocolPort = 7172 statusProtocolPort = 7171 maxPlayers = 0 motd = "Welcome to The Forgotten Server!" onePlayerOnlinePerAccount = true allowClones = false serverName = "Forgotten" statusTimeout = 5000 replaceKickOnLogin = true maxPacketsPerSecond = 25 -- Deaths -- NOTE: Leave deathLosePercent as -1 if you want to use the default -- death penalty formula. For the old formula, set it to 10. For -- no skill/experience loss, set it to 0. deathLosePercent = -1 -- Houses -- NOTE: set housePriceEachSQM to -1 to disable the ingame buy house functionality housePriceEachSQM = 1000 houseRentPeriod = "never" -- Item Usage timeBetweenActions = 200 timeBetweenExActions = 1000 -- Map -- NOTE: set mapName WITHOUT .otbm at the end mapName = "forgotten" mapAuthor = "Komic" -- Market marketOfferDuration = 30 * 24 * 60 * 60 premiumToCreateMarketOffer = true checkExpiredMarketOffersEachMinutes = 60 maxMarketOffersAtATimePerPlayer = 100 -- MySQL mysqlHost = "127.0.0.1" mysqlUser = "forgottenserver" mysqlPass = "" mysqlDatabase = "forgottenserver" mysqlPort = 3306 mysqlSock = "" -- Misc. allowChangeOutfit = true freePremium = false kickIdlePlayerAfterMinutes = 15 maxMessageBuffer = 4 emoteSpells = false classicEquipmentSlots = false -- Rates -- NOTE: rateExp is not used if you have enabled stages in data/XML/stages.xml rateExp = 5 rateSkill = 3 rateLoot = 2 rateMagic = 3 rateSpawn = 1 -- Monsters deSpawnRange = 2 deSpawnRadius = 50 -- Stamina staminaSystem = true -- Scripts warnUnsafeScripts = true convertUnsafeScripts = true -- Startup -- NOTE: defaultPriority only works on Windows and sets process -- priority, valid values are: "normal", "above-normal", "high" defaultPriority = "high" startupDatabaseOptimization = false -- Status server information ownerName = "" ownerEmail = "" url = "https://otland.net/" location = "Sweden"
gpl-2.0
nesstea/darkstar
scripts/zones/Sauromugue_Champaign/npcs/Tiger_Bones.lua
12
1894
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Tiger Bones -- Involed in Quest: The Fanged One. -- @pos 666 -8 -379 120 ------------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,THE_FANGED_ONE) == QUEST_ACCEPTED) then local oldTiger = 17268808; local tigerAction = GetMobAction(oldTiger); local fangedOneCS = player:getVar("TheFangedOneCS"); if (player:hasKeyItem(OLD_TIGERS_FANG) == false and fangedOneCS == 2) then player:addKeyItem(OLD_TIGERS_FANG); player:messageSpecial(KEYITEM_OBTAINED, OLD_TIGERS_FANG); player:setVar("TheFangedOneCS", 0); elseif (tigerAction == ACTION_NONE and fangedOneCS == 1) then SpawnMob(oldTiger):addStatusEffect(EFFECT_POISON,40,10,210); player:messageSpecial(OLD_SABERTOOTH_DIALOG_I); else player:messageSpecial(NOTHING_HAPPENS); end; end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Waughroon_Shrine/bcnms/shattering_stars.lua
13
1930
----------------------------------- -- Area: Waughroon Shrine -- Name: Shattering stars - Maat Fight -- @pos -345 104 -260 144 ----------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Waughroon_Shrine/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) -- player:messageSpecial(107); end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if(csid == 0x7d01) then if(player:getQuestStatus(JEUNO,SHATTERING_STARS) == QUEST_ACCEPTED and player:getFreeSlotsCount() > 0) then player:addItem(4181); player:messageSpecial(ITEM_OBTAINED,4181); end local pjob = player:getMainJob(); player:setVar("maatDefeated",pjob); local maatsCap = player:getVar("maatsCap") if (bit.band(maatsCap, bit.lshift(1, (pjob -1))) ~= 1)then player:setVar("maatsCap",bit.bor(maatsCap, bit.lshift(1, (pjob -1)))) end player:addTitle(MAAT_MASHER); end end;
gpl-3.0
ld-test/fun-alloyed
tests/operators.lua
5
4619
-- -- All these functions are fully covered by Lua tests. -- This test just checks that all functions were defined correctly. -- print(op == operator) -- an alias --[[test true --test]] -------------------------------------------------------------------------------- -- Comparison operators -------------------------------------------------------------------------------- local comparators = { 'le', 'lt', 'eq', 'ne', 'ge', 'gt' } for _k, op in iter(comparators) do print('op', op) print('==') print('num:') print(operator[op](0, 1)) print(operator[op](1, 0)) print(operator[op](0, 0)) print('str:') print(operator[op]("abc", "cde")) print(operator[op]("cde", "abc")) print(operator[op]("abc", "abc")) print('') end --[[test op le == num: true false true str: true false true op lt == num: true false false str: true false false op eq == num: false false true str: false false true op ne == num: true true false str: true true false op ge == num: false true true str: false true true op gt == num: false true false str: false true false --test]] -------------------------------------------------------------------------------- -- Arithmetic operators -------------------------------------------------------------------------------- print(operator.add(-1.0, 1.0)) print(operator.add(0, 0)) print(operator.add(12, 2)) --[[test 0 0 14 --test]] print(operator.div(10, 2)) print(operator.div(10, 3)) print(operator.div(-10, 3)) --[[test 5 3.3333333333333 -3.3333333333333 --test]] print(operator.floordiv(10, 3)) print(operator.floordiv(11, 3)) print(operator.floordiv(12, 3)) print(operator.floordiv(-10, 3)) print(operator.floordiv(-11, 3)) print(operator.floordiv(-12, 3)) --[[test 3 3 4 -4 -4 -4 --test]] print(operator.intdiv(10, 3)) print(operator.intdiv(11, 3)) print(operator.intdiv(12, 3)) print(operator.intdiv(-10, 3)) print(operator.intdiv(-11, 3)) print(operator.intdiv(-12, 3)) --[[test 3 3 4 -3 -3 -4 --test]] print(operator.truediv(10, 3)) print(operator.truediv(11, 3)) print(operator.truediv(12, 3)) print(operator.truediv(-10, 3)) print(operator.truediv(-11, 3)) print(operator.truediv(-12, 3)) --[[test 3.3333333333333 3.6666666666667 4 -3.3333333333333 -3.6666666666667 -4 --test]] print(operator.mod(10, 2)) print(operator.mod(10, 3)) print(operator.mod(-10, 3)) --[[test 0 1 2 --test]] print(operator.mul(10, 0.1)) print(operator.mul(0, 0)) print(operator.mul(-1, -1)) --[[test 1 0 1 --test]] print(operator.neq(1)) print(operator.neq(0) == 0) print(operator.neq(-0) == 0) print(operator.neq(-1)) --[[test -1 true true 1 --test]] print(operator.unm(1)) print(operator.unm(0) == 0) print(operator.unm(-0) == 0) print(operator.unm(-1)) --[[test -1 true true 1 --test]] print(operator.pow(2, 3)) print(operator.pow(0, 10)) print(operator.pow(2, 0)) --[[test 8 0 1 --test]] print(operator.sub(2, 3)) print(operator.sub(0, 10)) print(operator.sub(2, 2)) --[[test -1 -10 0 --test]] -------------------------------------------------------------------------------- -- String operators -------------------------------------------------------------------------------- print(operator.concat("aa", "bb")) print(operator.concat("aa", "")) print(operator.concat("", "bb")) --[[test aabb aa bb --test]] print(operator.len("")) print(operator.len("ab")) print(operator.len("abcd")) --[[test 0 2 4 --test]] print(operator.length("")) print(operator.length("ab")) print(operator.length("abcd")) --[[test 0 2 4 --test]] ---------------------------------------------------------------------------- -- Logical operators ---------------------------------------------------------------------------- print(operator.land(true, true)) print(operator.land(true, false)) print(operator.land(false, true)) print(operator.land(false, false)) print(operator.land(1, 0)) print(operator.land(0, 1)) print(operator.land(1, 1)) print(operator.land(0, 0)) --[[test true false false false 0 1 1 0 --test]] print(operator.lor(true, true)) print(operator.lor(true, false)) print(operator.lor(false, true)) print(operator.lor(false, false)) print(operator.lor(1, 0)) print(operator.lor(0, 1)) print(operator.lor(1, 1)) print(operator.lor(0, 0)) --[[test true true true false 1 0 1 0 --test]] print(operator.lnot(true)) print(operator.lnot(false)) print(operator.lor(1)) print(operator.lor(0)) --[[test false true 1 0 --test]] print(operator.truth(true)) print(operator.truth(false)) print(operator.truth(1)) print(operator.truth(0)) print(operator.truth(nil)) print(operator.truth("")) print(operator.truth({})) --[[test true false true true false true true --test]]
mit
UnfortunateFruit/darkstar
scripts/zones/Den_of_Rancor/npcs/_4g3.lua
10
2115
----------------------------------- -- Area: Den of Rancor -- NPC: Lantern (SW) -- @pos -59 45 24 160 ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Den_of_Rancor/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Lantern_ID = 17433047 local LSW = GetNPCByID(Lantern_ID):getAnimation(); local LNW = GetNPCByID(Lantern_ID+1):getAnimation(); local LNE = GetNPCByID(Lantern_ID+2):getAnimation(); local LSE = GetNPCByID(Lantern_ID+3):getAnimation(); -- Trade Crimson Rancor Flame if(trade:hasItemQty(1139,1) and trade:getItemCount() == 1) then if (LSW == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit elseif(LSW == 9)then npc:openDoor(LANTERNS_STAY_LIT); local ALL = LNW+LNE+LSE; player:tradeComplete(); player:addItem(1138); -- Unlit Lantern if ALL == 27 then player:messageSpecial(LANTERN_OFFSET + 9); elseif ALL == 26 then player:messageSpecial(LANTERN_OFFSET + 10); elseif ALL == 25 then player:messageSpecial(LANTERN_OFFSET + 11); elseif ALL == 24 then player:messageSpecial(LANTERN_OFFSET + 12); GetNPCByID(Lantern_ID+3):closeDoor(1); GetNPCByID(Lantern_ID+2):closeDoor(1); GetNPCByID(Lantern_ID+1):closeDoor(1); GetNPCByID(Lantern_ID):closeDoor(1); GetNPCByID(Lantern_ID+4):openDoor(30); GetNPCByID(Lantern_ID+3):openDoor(30); GetNPCByID(Lantern_ID+2):openDoor(30); GetNPCByID(Lantern_ID+1):openDoor(30); GetNPCByID(Lantern_ID):openDoor(30); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local npca = npc:getAnimation() if (npca == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit else player:messageSpecial(LANTERN_OFFSET + 20); -- unlit end return 0; end;
gpl-3.0
Mashape/kong
spec/01-unit/01-db/05-cassandra_spec.lua
2
3510
local connector = require "kong.db.strategies.cassandra.connector" local cassandra = require "cassandra" local helpers = require "spec.helpers" describe("kong.db [#cassandra] connector", function() describe(".new()", function() local test_conf = helpers.test_conf local test_conf_lb_policy = test_conf.cassandra_lb_policy local test_conf_local_datacenter = test_conf.cassandra_local_datacenter lazy_teardown(function() test_conf.cassandra_lb_policy = test_conf_lb_policy test_conf.cassandra_local_datacenter = test_conf_local_datacenter end) it("sets serial_consistency to serial if LB policy is not DCAware", function() for _, policy in ipairs({ "RoundRobin", "RequestRoundRobin" }) do test_conf.cassandra_lb_policy = policy local c = assert(connector.new(test_conf)) assert.equal(cassandra.consistencies.serial, c.opts.serial_consistency) end end) it("sets serial_consistency to local_serial if LB policy is DCAware", function() test_conf.cassandra_local_datacenter = "dc1" for _, policy in ipairs({ "DCAwareRoundRobin", "RequestDCAwareRoundRobin" }) do test_conf.cassandra_lb_policy = policy local c = assert(connector.new(test_conf)) assert.equal(cassandra.consistencies.local_serial, c.opts.serial_consistency) end end) end) describe(":infos()", function() it("returns infos db_ver always with two digit groups divided with dot (.)", function() local infos = connector.infos{ major_version = 2, major_minor_version = "2.10" } assert.same({ db_desc = "keyspace", db_ver = "2.10", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 2, major_minor_version = "2.10.1" } assert.same({ db_desc = "keyspace", db_ver = "2.10", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 3, major_minor_version = "3.7" } assert.same({ db_desc = "keyspace", db_ver = "3.7", strategy = "Cassandra", }, infos) end) it("returns infos with db_ver as \"unknown\" when missing major_minor_version", function() local infos = connector.infos{ major_version = 2 } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 3 } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{} assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) end) it("returns infos with db_ver as \"unknown\" when invalid major_minor_version", function() local infos = connector.infos{ major_version = 2, major_minor_version = "invalid" } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 3, major_minor_version = "invalid" } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{ major_minor_version = "invalid" } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) end) end) end)
apache-2.0
nesstea/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm7 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED1); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm7 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED1); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/black_bubble-eye.lua
18
1336
----------------------------------------- -- ID: 4311 -- Item: Black Bubble-Eye -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4311); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Upper_Jeuno/npcs/Migliorozz.lua
38
1033
----------------------------------- -- Area: Upper Jeuno -- NPC: Migliorozz -- Type: Standard NPC -- @zone: 244 -- @pos -37.760 -2.499 12.924 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x272a); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/globals/spells/bluemagic/tail_slap.lua
21
2101
----------------------------------------- -- Spell: Tail Slap -- Delivers an area attack. Additional effect: "Stun." Damage varies with TP -- Spell cost: 77 MP -- Monster Type: Beastmen -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: MND+2 -- Level: 69 -- Casting Time: 1 seconds -- Recast Time: 28.5 seconds -- Skillchain Element: Water (can open Impaction and Induration; can close Reverberation and Fragmentation) -- Combos: Store TP ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistanceEffect(caster,spell,target,dINT,SKILL_BLU,0,EFFECT_STUN) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_REVERBERATION; params.numhits = 1; params.multiplier = 1.625; params.tp150 = 1.625; params.tp300 = 1.625; params.azuretp = 1.625; params.duppercap = 75; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; local damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (resist > 0.5) then -- This line may need adjusting for retail accuracy. target:addStatusEffect(EFFECT_STUN, 1, 0, 5 * resist); -- pre-resist duration needs confirmed/adjusted end return damage; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/warm_egg.lua
35
1186
----------------------------------------- -- ID: 4602 -- Item: warm_egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 18 -- Magic 18 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4602); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 18); target:addMod(MOD_MP, 18); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 18); target:delMod(MOD_MP, 18); end;
gpl-3.0
bowlofstew/Macaroni
Main/App/Source/test/lua/Macaroni/Model/DocumentTests/FunctionTests.lua
2
2126
-------------------------------------------------------------------------------- -- Copyright 2011 Tim Simpson -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -------------------------------------------------------------------------------- require "Macaroni.Model.Document"; -- These are for the stand alone tests. local Document = Macaroni.Model.Document; Test.register( { name = "Document Tests - Functions", --[[init = { ["Constructing and reading a file"] = function(this) this.doc = Macaroni.Model.Document.New(this.testFile); end }, shutdown = { },]]-- tests={ ["Simple function."] = function(this) --pddsfs(); doc = Document.New("SimpleMain"); doc:Read([[ // Comment. namespace A::B::C { void DoSomething() { std::cout << "Hello, EARTH!"; } // comment } ]]); Test.assert(1, #(doc.Namespaces)); Test.assert("A::B::C", tostring(doc.Namespaces[0])); abc = Namespaces[0]; func = abc.GetFunctions(0); func. end, --[[["Namespaces are generated correctly."] = function(this) Test.assert("3", #(this.file.Namespaces)); end]]-- } } -- End of Test table. ); --[[ Test.register( { name = "Document Tests - Classes", init = { ["Constructing and reading a file"] = function(this) this.doc = Macaroni.Model.Document.New(this.testFile); end }, shutdown = { },]]--
apache-2.0
anoidgit/Residue-RNN
test/testrnn.lua
1
4511
require 'paths' require 'rnn' local dl = require 'dataload' torch.setdefaulttensortype('torch.FloatTensor') function savemodel(fname,modelsave) file=torch.DiskFile(fname,'w') file:writeObject(modelsave) file:close() end startlr=0.005 minlr=0.000001 saturate=120--'epoch at which linear decayed LR will reach minlr' batchsize=256 maxepoch=200 earlystop=15 cutoff=5 seqlen=64 hiddensize=200 progress=true savepath=paths.concat(dl.SAVE_PATH, 'rnnlm') id="20160504rnn" local trainset, validset, testset = dl.loadPTB({batchsize,1,1}) print("Vocabulary size : "..#trainset.ivocab) print("Train set split into "..batchsize.." sequences of length "..trainset:size()) local lm = nn.Sequential() -- input layer (i.e. word embedding space) local lookup = nn.LookupTable(#trainset.ivocab, hiddensize) lookup.maxnormout = -1 -- prevent weird maxnormout behaviour lm:add(lookup) -- input is seqlen x batchsize lm:add(nn.SplitTable(1)) -- tensor to table of tensors -- rnn layers local stepmodule = nn.Sequential() -- applied at each time-step local inputsize = hiddensize local rm = nn.Sequential() -- input is {x[t], h[t-1]} :add(nn.ParallelTable() :add(i==1 and nn.Identity() or nn.Linear(inputsize, hiddensize)) -- input layer :add(nn.Linear(hiddensize, hiddensize))) -- recurrent layer :add(nn.CAddTable()) -- merge :add(nn.Sigmoid()) -- transfer rnn = nn.Recurrence(rm, hiddensize, 1) stepmodule:add(rnn) inputsize = hiddensize -- output layer stepmodule:add(nn.Linear(inputsize, #trainset.ivocab)) stepmodule:add(nn.LogSoftMax()) -- encapsulate stepmodule into a Sequencer lm:add(nn.Sequencer(stepmodule)) print"Language Model:" print(lm) -- target is also seqlen x batchsize. local targetmodule = nn.SplitTable(1) --[[ loss function ]]-- local crit = nn.ClassNLLCriterion() local criterion = nn.SequencerCriterion(crit) --[[ experiment log ]]-- -- is saved to file every time a new validation minima is found local xplog = {} xplog.dataset = 'PennTreeBank' xplog.vocab = trainset.vocab -- will only serialize params xplog.model = nn.Serial(lm) xplog.model:mediumSerial() --xplog.model = lm xplog.criterion = criterion xplog.targetmodule = targetmodule -- keep a log of NLL for each epoch xplog.trainppl = {} xplog.valppl = {} -- will be used for early-stopping xplog.minvalppl = 99999999 xplog.epoch = 0 local ntrial = 0 paths.mkdir(savepath) local epoch = 1 lr = startlr trainsize=trainset:size() validsize=validset:size() while epoch <= maxepoch do print("") print("Epoch #"..epoch.." :") -- 1. training local a = torch.Timer() lm:training() local sumErr = 0 for i, inputs, targets in trainset:subiter(seqlen, trainsize) do targets = targetmodule:forward(targets) -- forward local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err -- backward local gradOutputs = criterion:backward(outputs, targets) lm:zeroGradParameters() lm:backward(inputs, gradOutputs) -- update lm:updateParameters(lr) -- affects params if progress then xlua.progress(math.min(i + seqlen, trainsize), trainsize) end if i % 1000 == 0 then collectgarbage() end end -- learning rate decay lr = lr + (minlr - startlr)/saturate lr = math.max(minlr, lr) print("learning rate", lr) local speed = a:time().real/trainsize print(string.format("Speed : %f sec/batch ", speed)) local ppl = torch.exp(sumErr/trainsize) print("Training PPL : "..ppl) xplog.trainppl[epoch] = ppl -- 2. cross-validation lm:evaluate() local sumErr = 0 for i, inputs, targets in validset:subiter(seqlen, validsize) do targets = targetmodule:forward(targets) local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err end local ppl = torch.exp(sumErr/validsize) print("Validation PPL : "..ppl) xplog.valppl[epoch] = ppl ntrial = ntrial + 1 -- early-stopping if ppl < xplog.minvalppl then -- save best version of model xplog.minvalppl = ppl xplog.epoch = epoch local filename = paths.concat(savepath, id..'.t7') print("Found new minima. Saving to "..filename) torch.save(filename, xplog) savemodel(filename..'.lm',lm) ntrial = 0 elseif ntrial >= earlystop then print("No new minima found after "..ntrial.." epochs.") print("Stopping experiment.") break else lr=lr/2 end collectgarbage() epoch = epoch + 1 end print("Evaluate model using : ") print("th scripts/evaluate-rnnlm.lua --xplogpath "..paths.concat(savepath, id..'.t7'))
bsd-3-clause
UnfortunateFruit/darkstar
scripts/zones/AlTaieu/npcs/_0x3.lua
8
2001
----------------------------------- -- Area: Al'Taieu -- NPC: Rubious Crystal (East Tower) -- @pos 683.718 -6.250 -222.167 33 ----------------------------------- package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil; ----------------------------------- require("scripts/zones/AlTaieu/TextIDs"); require("scripts/zones/AlTaieu/mobIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ---------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 2 and player:getVar("[SEA][AlTieu]EastTower") == 0 and player:getVar("[SEA][AlTieu]EastTowerCS") == 0) then player:messageSpecial(OMINOUS_SHADOW); SpawnMob(EastTowerAern,180):updateClaim(player); SpawnMob(EastTowerAern+1,180):updateClaim(player); SpawnMob(EastTowerAern+2,180):updateClaim(player); elseif(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 2 and player:getVar("[SEA][AlTieu]EastTower") == 1 and player:getVar("[SEA][AlTieu]EastTowerCS") == 0) then player:startEvent(0x00A3); else player:messageSpecial(NOTHING_OF_INTEREST); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x00A3) then player:setVar("[SEA][AlTieu]EastTowerCS", 1); player:setVar("[SEA][AlTieu]EastTower", 0); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/moon_ball.lua
18
1162
----------------------------------------- -- ID: 4568 -- Item: moon_ball -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 3 -- Magic 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4568); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 3); target:addMod(MOD_MP, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 3); target:delMod(MOD_MP, 3); end;
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_Skins/components/blizzard/timemanager.lua
2
2481
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## --]] --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; --[[ ADDON ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## TIMEMANAGER MODR ########################################################## ]]-- local function TimeManagerStyle() if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.timemanager ~= true then return end SV.API:Set("Window", TimeManagerFrame, true) SV.API:Set("CloseButton", TimeManagerFrameCloseButton) TimeManagerFrameInset:Die() SV.API:Set("DropDown", TimeManagerAlarmHourDropDown, 80) SV.API:Set("DropDown", TimeManagerAlarmMinuteDropDown, 80) SV.API:Set("DropDown", TimeManagerAlarmAMPMDropDown, 80) TimeManagerAlarmMessageEditBox:SetStyle("Editbox") TimeManagerAlarmEnabledButton:SetStyle("CheckButton") TimeManagerMilitaryTimeCheck:SetStyle("CheckButton") TimeManagerLocalTimeCheck:SetStyle("CheckButton") TimeManagerStopwatchFrame:RemoveTextures() TimeManagerStopwatchCheck:SetStyle("!_Frame", "Default") TimeManagerStopwatchCheck:GetNormalTexture():SetTexCoord(unpack(_G.SVUI_ICON_COORDS)) TimeManagerStopwatchCheck:GetNormalTexture():InsetPoints() local sWatch = TimeManagerStopwatchCheck:CreateTexture(nil, "OVERLAY") sWatch:SetColorTexture(1, 1, 1, 0.3) sWatch:SetPoint("TOPLEFT", TimeManagerStopwatchCheck, 2, -2) sWatch:SetPoint("BOTTOMRIGHT", TimeManagerStopwatchCheck, -2, 2) TimeManagerStopwatchCheck:SetHighlightTexture(sWatch) StopwatchFrame:RemoveTextures() StopwatchFrame:SetStyle("Frame", 'Transparent') StopwatchFrame.Panel:SetPoint("TOPLEFT", 0, -17) StopwatchFrame.Panel:SetPoint("BOTTOMRIGHT", 0, 2) StopwatchTabFrame:RemoveTextures() SV.API:Set("CloseButton", StopwatchCloseButton) SV.API:Set("PageButton", StopwatchPlayPauseButton) SV.API:Set("PageButton", StopwatchResetButton) StopwatchPlayPauseButton:SetPoint("RIGHT", StopwatchResetButton, "LEFT", -4, 0) StopwatchResetButton:SetPoint("BOTTOMRIGHT", StopwatchFrame, "BOTTOMRIGHT", -4, 6) end --[[ ########################################################## MOD LOADING ########################################################## ]]-- MOD:SaveBlizzardStyle("Blizzard_TimeManager",TimeManagerStyle)
mit
dios-game/dios-cocos-samples
src/lua-coin-tree/Resources/src/dxm/data_structures/list.lua
4
2231
--region *.lua --Date --此文件由[BabeLua]插件自动生成 dxm = dxm or {} -- 链表节点 dxm.CNode = class("CNode") local CNode = dxm.CNode function CNode:ctor() self.prev = nil self.next = nil self.value = nil end -- 链表 dxm.CList = class("CList") local CList = dxm.CList function CList:ctor() self.first = nil -- 头 self.last = nil -- 尾 self.size = 0 -- 容量 end -- 成员函数 function CList:Clear() local node = self.first while node ~= nil do local next_node = node.next node.prev = nil node.value = nil node.next = nil node = next_node end self.first = nil self.last = nil end function CList:Erase(node) if node == nil then return end local node_prev = node.prev local node_next = node.next if node_prev ~= nil then node_prev.next = node_next end if node_next ~= nil then node_next.prev = node_prev end if node == self.first then self.first = node.next end if node == self.last then self.last = node.prev end self.size = self.size - 1 node.prev = nil node.next = nil node.value = nil end function CList:PushBack(value) local node = { prev = self.last, value = value } if self.last ~= nil then self.last.next = node end self.last = node if self.first == nil then self.first = node end self.size = self.size + 1 end function CList:PopFront() local node = self.first if node == nil then return nil end self.first = node.next if self.last == node then self.last = nil end self.size = self.size - 1 node.next = nil node.prev = nil return node.value end function CList:Begin() local node = self.first return function () if not node then return nil end local ret = node node = node.next return ret end end function CList:End() local node = self.last return function () if not node then return nil end local ret = node node = node.prev return ret end end return CList --endregion
mit
dstodev/MC-Fluid-Tank-Controller
lib/schmitt_trigger.lua
1
1105
local Trigger = {} Trigger.__index = Trigger setmetatable(Trigger, { __call = function (cls, ...) return cls.new(...) end, }) function Trigger.new(left, right, left_callback, right_callback) local self = {} setmetatable(self, Trigger) self._left = left self._right = right self._position = 0 self._state = -1 self._left_callback = left_callback self._right_callback = right_callback return self end function Trigger:increment(value) self._position = self._position + value self:_manage_state() end function Trigger:decrement(value) self._position = self._position - value self:_manage_state() end function Trigger:update(value) self._position = value self:_manage_state() end function Trigger:_manage_state() if (self._state == 0 or self._state == -1) and self._position > self._right then self._right_callback() self._state = 1 elseif (self._state == 1 or self._state == -1) and self._position < self._left then self._left_callback() self._state = 0 end end return Trigger
mit
drakmaniso/Flapoline
src/dot.lua
1
1037
Dot = {} Dot.__index = Dot --------------------------------------------------------------------------------------------------- Dot.radius = 4 Dot.segments = 6 --------------------------------------------------------------------------------------------------- function Dot:new(x, y) object = { x = x, y = y, age = 0} setmetatable(object, self) return object end --------------------------------------------------------------------------------------------------- function Dot:move(dx) self.x = self.x - dx self.age = self.age + dx / 16 end --------------------------------------------------------------------------------------------------- function Dot:draw() local alpha = math.max(0, 29 - self.age) love.graphics.setColor(10, 10, 10, alpha) love.graphics.circle("fill", self.x, self.y, Dot.radius, Dot.segments) end --------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 - Laurent Moussault <moussault.laurent@gmail.com>
gpl-3.0
dpino/snabb
src/program/packetblaster/synth/synth.lua
14
1360
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local config = require("core.config") local main = require("core.main") local Synth = require("apps.test.synth").Synth local lib = require("core.lib") local packetblaster = require("program.packetblaster.packetblaster") local long_opts = { duration = "D", help = "h", src = "s", dst = "d", sizes = "S", } local function show_usage (code) print(require("program.packetblaster.synth.README_inc")) main.exit(code) end function run (args) local c = config.new() local handlers = {} local opts = {} function handlers.D (arg) opts.duration = assert(tonumber(arg), "duration is not a number!") end function handlers.h () show_usage(0) end local source local destination local sizes function handlers.s (arg) source = arg end function handlers.d (arg) destination = arg end function handlers.S (arg) sizes = {} for size in string.gmatch(arg, "%d+") do sizes[#sizes+1] = tonumber(size) end end args = lib.dogetopt(args, handlers, "hD:s:d:S:", long_opts) config.app(c, "source", Synth, { sizes = sizes, src = source, dst = destination }) packetblaster.run_loadgen(c, args, opts) end
apache-2.0
Kthulupwns/darkstar
scripts/zones/Southern_San_dOria/npcs/Femitte.lua
17
3106
----------------------------------- -- Area: Southern San d'Oria -- NPC: Femitte -- Involved in Quest: Lure of the Wildcat (San d'Oria), Distant Loyalties -- @pos -17 2 10 230 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DistantLoyaltiesProgress = player:getVar("DistantLoyaltiesProgress"); local DistantLoyalties = player:getQuestStatus(SANDORIA,DISTANT_LOYALTIES); local WildcatSandy = player:getVar("WildcatSandy"); if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,3) == false) then player:startEvent(0x0327); elseif (player:getFameLevel(SANDORIA) >= 4 and DistantLoyalties == 0) then player:startEvent(0x0297); elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 1) then player:startEvent(0x0298); elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 4 and player:hasKeyItem(MYTHRIL_HEARTS)) then player:startEvent(0x0299); else player:startEvent(0x295); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0327) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",3,true); elseif (csid == 0x0297 and option == 0) then player:addKeyItem(GOLDSMITHING_ORDER); player:messageSpecial(KEYITEM_OBTAINED,GOLDSMITHING_ORDER); player:addQuest(SANDORIA,DISTANT_LOYALTIES); player:setVar("DistantLoyaltiesProgress",1); elseif (csid == 0x0299) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13585); else player:delKeyItem(MYTHRIL_HEARTS); player:addItem(13585,1); player:messageSpecial(ITEM_OBTAINED,13585); player:setVar("DistantLoyaltiesProgress",0); player:completeQuest(SANDORIA,DISTANT_LOYALTIES); end; end; end; --------Other CS --0x7fb4 --0x0000 --0x0295 Standard dialog --0x0297 --0x0298 --0x0299 --0x02d5 --0x02eb --0x02ec --0x0327 Lure of the Wildcat --0x03b1 CS with small mythra dancer
gpl-3.0
FPtje/DarkRP
gamemode/modules/f4menu/cl_interface.lua
13
2912
DarkRP.openF4Menu = DarkRP.stub{ name = "openF4Menu", description = "Open the F4 menu.", parameters = { }, returns = { }, metatable = DarkRP } DarkRP.closeF4Menu = DarkRP.stub{ name = "closeF4Menu", description = "Close the F4 menu if it's open.", parameters = { }, returns = { }, metatable = DarkRP } DarkRP.toggleF4Menu = DarkRP.stub{ name = "toggleF4Menu", description = "Toggle the state of the F4 menu (open or closed).", parameters = { }, returns = { }, metatable = DarkRP } DarkRP.getF4MenuPanel = DarkRP.stub{ name = "getF4MenuPanel", description = "Get the F4 menu panel.", parameters = { }, returns = { { name = "panel", description = "The F4 menu panel. It will be invalid until the F4 menu has been opened.", type = "Panel", optional = false } }, metatable = DarkRP } DarkRP.addF4MenuTab = DarkRP.stub{ name = "addF4MenuTab", description = "Add a tab to the F4 menu.", parameters = { { name = "name", description = "The title of the tab.", type = "string", optional = false }, { name = "panel", description = "The panel of the tab.", type = "Panel", optional = false } }, returns = { { name = "index", description = "The index of the tab in the menu. This is the number you use for the tab in DarkRP.switchTabOrder.", type = "number" }, { name = "sheet", description = "The tab sheet.", type = "Panel" } }, metatable = DarkRP } DarkRP.removeF4MenuTab = DarkRP.stub{ name = "removeF4MenuTab", description = "Remove a tab from the F4 menu by name.", parameters = { { name = "name", description = "The name of the tab it should remove.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.switchTabOrder = DarkRP.stub{ name = "switchTabOrder", description = "Switch the order of two tabs.", parameters = { { name = "firstTab", description = "The number of the first tab (if it's the second tab, then this number is 2).", type = "number", optional = false }, { name = "secondTab", description = "The number of the second tab.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.hookStub{ name = "F4MenuTabs", description = "Called when tabs are generated. Add and remove tabs in this hook.", parameters = { }, returns = { } }
mit
Kthulupwns/darkstar
scripts/zones/King_Ranperres_Tomb/npcs/Grounds_Tome.lua
34
1155
----------------------------------- -- Area: King Ranperre's Tomb -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_KING_RANPERRES_TOMB,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,631,632,633,634,635,636,637,638,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,631,632,633,634,635,636,637,638,0,0,GOV_MSG_KING_RANPERRES_TOMB); end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Southern_San_dOria/npcs/Taumila.lua
17
2257
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taumila -- Starts and Finishes Quest: Tiger's Teeth (R) -- @pos -140 -5 -8 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,TIGER_S_TEETH) ~= QUEST_AVAILABLE) then if(trade:hasItemQty(884,3) and trade:getItemCount() == 3) then player:startEvent(0x023c); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local tigersTeeth = player:getQuestStatus(SANDORIA,TIGER_S_TEETH); if(player:getFameLevel(SANDORIA) >= 3 and tigersTeeth == QUEST_AVAILABLE) then player:startEvent(0x023e); elseif(tigersTeeth == QUEST_ACCEPTED) then player:startEvent(0x023f); elseif(tigersTeeth == QUEST_COMPLETED) then player:startEvent(0x023d); else player:startEvent(0x023b); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x023e and option == 0) then player:addQuest(SANDORIA,TIGER_S_TEETH); elseif(csid == 0x023c) then player:tradeComplete(); player:addTitle(FANG_FINDER); player:addGil(GIL_RATE*2100); player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100) if(player:getQuestStatus(SANDORIA,TIGER_S_TEETH) == QUEST_ACCEPTED) then player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,TIGER_S_TEETH); else player:addFame(SANDORIA,SAN_FAME*5); end end end;
gpl-3.0
mlody1039/ModernOts
data/npc/scripts/TP1/boat_liberty3.lua
1
2225
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) -- OTServ event handling functions start 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 -- OTServ event handling functions end -- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions! local travelNode = keywordHandler:addKeyword({'calassa'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to sail to Calassa for free?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, level = 0, cost = 0, destination = {x=31747, y=32718, z=6} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Then stay here!'}) local travelNode = keywordHandler:addKeyword({'yalahar'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to sail to Yalahar for free?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, level = 0, cost = 0, destination = {x=601, y=669, z=6} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Then stay here!'}) keywordHandler:addKeyword({'sail'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I can take you to Calassa and Yalahar.'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I am the captain of this ship.'}) keywordHandler:addKeyword({'travel'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I can only offer you a trip to Calassa and Yalahar.'}) -- Makes sure the npc reacts when you say hi, bye etc. npcHandler:addModule(FocusModule:new())
gpl-3.0
Kthulupwns/darkstar
scripts/zones/PsoXja/npcs/_092.lua
9
1609
----------------------------------- -- Area: Pso'Xja -- NPC: _092 (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos -330.000 14.074 -261.600 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local X=player:getXPos(); if (npc:getAnimation() == 9) then if(X >= 339)then if(GetMobAction(16814083) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED); SpawnMob(16814083,120):updateEnmity(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif(X <= 338)then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if(csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
aa65535/luci
modules/luci-base/luasrc/http/protocol.lua
16
16196
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- This class contains several functions useful for http message- and content -- decoding and to retrive form data from raw http messages. module("luci.http.protocol", package.seeall) local ltn12 = require("luci.ltn12") HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size -- the "+" sign to " " - and return the decoded string. function urldecode( str, no_plus ) local function __chrdec( hex ) return string.char( tonumber( hex, 16 ) ) end if type(str) == "string" then if not no_plus then str = str:gsub( "+", " " ) end str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec ) end return str end -- from given url or string. Returns a table with urldecoded values. -- Simple parameters are stored as string values associated with the parameter -- name within the table. Parameters with multiple values are stored as array -- containing the corresponding values. function urldecode_params( url, tbl ) local params = tbl or { } if url:find("?") then url = url:gsub( "^.+%?([^?]+)", "%1" ) end for pair in url:gmatch( "[^&;]+" ) do -- find key and value local key = urldecode( pair:match("^([^=]+)") ) local val = urldecode( pair:match("^[^=]+=(.+)$") ) -- store if type(key) == "string" and key:len() > 0 then if type(val) ~= "string" then val = "" end if not params[key] then params[key] = val elseif type(params[key]) ~= "table" then params[key] = { params[key], val } else table.insert( params[key], val ) end end end return params end function urlencode( str ) local function __chrenc( chr ) return string.format( "%%%02x", string.byte( chr ) ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.%~])", __chrenc ) end return str end -- separated by "&". Tables are encoded as parameters with multiple values by -- repeating the parameter name with each value. function urlencode_params( tbl ) local enc = "" for k, v in pairs(tbl) do if type(v) == "table" then for i, v2 in ipairs(v) do enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v2) end else enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v) end end return enc end -- (Internal function) -- Initialize given parameter and coerce string into table when the parameter -- already exists. local function __initval( tbl, key ) if tbl[key] == nil then tbl[key] = "" elseif type(tbl[key]) == "string" then tbl[key] = { tbl[key], "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Initialize given file parameter. local function __initfileval( tbl, key, filename, fd ) if tbl[key] == nil then tbl[key] = { file=filename, fd=fd, name=key, "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Append given data to given parameter, either by extending the string value -- or by appending it to the last string in the parameter's value table. local function __appendval( tbl, key, chunk ) if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk else tbl[key] = tbl[key] .. chunk end end -- (Internal function) -- Finish the value of given parameter, either by transforming the string value -- or - in the case of multi value parameters - the last element in the -- associated values table. local function __finishval( tbl, key, handler ) if handler then if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] ) else tbl[key] = handler( tbl[key] ) end end end -- Table of our process states local process_states = { } -- Extract "magic", the first line of a http message. -- Extracts the message type ("get", "post" or "response"), the requested uri -- or the status code if the line descripes a http response. process_states['magic'] = function( msg, chunk, err ) if chunk ~= nil then -- ignore empty lines before request if #chunk == 0 then return true, nil end -- Is it a request? local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$") -- Yup, it is if method then msg.type = "request" msg.request_method = method:lower() msg.request_uri = uri msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end -- Is it a response? else local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$") -- Is a response if code then msg.type = "response" msg.status_code = code msg.status_message = message msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end end end end -- Can't handle it return nil, "Invalid HTTP message magic" end -- Extract headers from given string. process_states['headers'] = function( msg, chunk ) if chunk ~= nil then -- Look for a valid header format local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" ) if type(hdr) == "string" and hdr:len() > 0 and type(val) == "string" and val:len() > 0 then msg.headers[hdr] = val -- Valid header line, proceed return true, nil elseif #chunk == 0 then -- Empty line, we won't accept data anymore return false, nil else -- Junk data return nil, "Invalid HTTP header received" end else return nil, "Unexpected EOF" end end -- data line by line with the trailing \r\n stripped of. function header_source( sock ) return ltn12.source.simplify( function() local chunk, err, part = sock:receive("*l") -- Line too long if chunk == nil then if err ~= "timeout" then return nil, part and "Line exceeds maximum allowed length" or "Unexpected EOF" else return nil, err end -- Line ok elseif chunk ~= nil then -- Strip trailing CR chunk = chunk:gsub("\r$","") return chunk, nil end end ) end -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- If an optional file callback function is given then it is feeded with the -- file contents chunk by chunk and only the extracted file name is stored -- within the params table. The callback function will be called subsequently -- with three arguments: -- o Table containing decoded (name, file) and raw (headers) mime header data -- o String value containing a chunk of the file data -- o Boolean which indicates wheather the current chunk is the last one (eof) function mimedecode_message_body( src, msg, filecb ) if msg and msg.env.CONTENT_TYPE then msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$") end if not msg.mime_boundary then return nil, "Invalid Content-Type found" end local tlen = 0 local inhdr = false local field = nil local store = nil local lchunk = nil local function parse_headers( chunk, field ) local stat repeat chunk, stat = chunk:gsub( "^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n", function(k,v) field.headers[k] = v return "" end ) until stat == 0 chunk, stat = chunk:gsub("^\r\n","") -- End of headers if stat > 0 then if field.headers["Content-Disposition"] then if field.headers["Content-Disposition"]:match("^form%-data; ") then field.name = field.headers["Content-Disposition"]:match('name="(.-)"') field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$') end end if not field.headers["Content-Type"] then field.headers["Content-Type"] = "text/plain" end if field.name and field.file and filecb then __initval( msg.params, field.name ) __appendval( msg.params, field.name, field.file ) store = filecb elseif field.name and field.file then local nxf = require "nixio" local fd = nxf.mkstemp(field.name) __initfileval ( msg.params, field.name, field.file, fd ) if fd then store = function(hdr, buf, eof) fd:write(buf) if (eof) then fd:seek(0, "set") end end else store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end end elseif field.name then __initval( msg.params, field.name ) store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end else store = nil end return chunk, true end return chunk, false end local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" end if chunk and not lchunk then lchunk = "\r\n" .. chunk elseif lchunk then local data = lchunk .. ( chunk or "" ) local spos, epos, found repeat spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true ) if not spos then spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true ) end if spos then local predata = data:sub( 1, spos - 1 ) if inhdr then predata, eof = parse_headers( predata, field ) if not eof then return nil, "Invalid MIME section header" elseif not field.name then return nil, "Invalid Content-Disposition header" end end if store then store( field, predata, true ) end field = { headers = { } } found = found or true data, eof = parse_headers( data:sub( epos + 1, #data ), field ) inhdr = not eof end until not spos if found then -- We found at least some boundary. Save -- the unparsed remaining data for the -- next chunk. lchunk, data = data, nil else -- There was a complete chunk without a boundary. Parse it as headers or -- append it as data, depending on our current state. if inhdr then lchunk, eof = parse_headers( data, field ) inhdr = not eof else -- We're inside data, so append the data. Note that we only append -- lchunk, not all of data, since there is a chance that chunk -- contains half a boundary. Assuming that each chunk is at least the -- boundary in size, this should prevent problems store( field, lchunk, false ) lchunk, chunk = chunk, nil end end end return true end return ltn12.pump.all( src, snk ) end -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. function urldecode_message_body( src, msg ) local tlen = 0 local lchunk = nil local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" elseif tlen > HTTP_MAX_CONTENT then return nil, "Message body size exceeds maximum allowed length" end if not lchunk and chunk then lchunk = chunk elseif lchunk then local data = lchunk .. ( chunk or "&" ) local spos, epos repeat spos, epos = data:find("^.-[;&]") if spos then local pair = data:sub( spos, epos - 1 ) local key = pair:match("^(.-)=") local val = pair:match("=([^%s]*)%s*$") if key and #key > 0 then __initval( msg.params, key ) __appendval( msg.params, key, val ) __finishval( msg.params, key, urldecode ) end data = data:sub( epos + 1, #data ) end until not spos lchunk = data end return true end return ltn12.pump.all( src, snk ) end -- version, message headers and resulting CGI environment variables from the -- given ltn12 source. function parse_message_header( src ) local ok = true local msg = { } local sink = ltn12.sink.simplify( function( chunk ) return process_states['magic']( msg, chunk ) end ) -- Pump input data... while ok do -- get data ok, err = ltn12.pump.step( src, sink ) -- error if not ok and err then return nil, err -- eof elseif not ok then -- Process get parameters if ( msg.request_method == "get" or msg.request_method == "post" ) and msg.request_uri:match("?") then msg.params = urldecode_params( msg.request_uri ) else msg.params = { } end -- Populate common environment variables msg.env = { CONTENT_LENGTH = msg.headers['Content-Length']; CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type']; REQUEST_METHOD = msg.request_method:upper(); REQUEST_URI = msg.request_uri; SCRIPT_NAME = msg.request_uri:gsub("?.+$",""); SCRIPT_FILENAME = ""; -- XXX implement me SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version); QUERY_STRING = msg.request_uri:match("?") and msg.request_uri:gsub("^.+?","") or "" } -- Populate HTTP_* environment variables for i, hdr in ipairs( { 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Connection', 'Cookie', 'Host', 'Referer', 'User-Agent', } ) do local var = 'HTTP_' .. hdr:upper():gsub("%-","_") local val = msg.headers[hdr] msg.env[var] = val end end end return msg end -- This function will examine the Content-Type within the given message object -- to select the appropriate content decoder. -- Currently the application/x-www-urlencoded and application/form-data -- mime types are supported. If the encountered content encoding can't be -- handled then the whole message body will be stored unaltered as "content" -- property within the given message object. function parse_message_body( src, msg, filecb ) -- Is it multipart/mime ? if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^multipart/form%-data") then return mimedecode_message_body( src, msg, filecb ) -- Is it application/x-www-form-urlencoded ? elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded") then return urldecode_message_body( src, msg, filecb ) -- Unhandled encoding -- If a file callback is given then feed it chunk by chunk, else -- store whole buffer in message.content else local sink -- If we have a file callback then feed it if type(filecb) == "function" then local meta = { name = "raw", encoding = msg.env.CONTENT_TYPE } sink = function( chunk ) if chunk then return filecb(meta, chunk, false) else return filecb(meta, nil, true) end end -- ... else append to .content else msg.content = "" msg.content_length = 0 sink = function( chunk ) if chunk then if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then msg.content = msg.content .. chunk msg.content_length = msg.content_length + #chunk return true else return nil, "POST data exceeds maximum allowed length" end end return true end end -- Pump data... while true do local ok, err = ltn12.pump.step( src, sink ) if not ok and err then return nil, err elseif not ok then -- eof return true end end return true end end statusmsg = { [200] = "OK", [206] = "Partial Content", [301] = "Moved Permanently", [302] = "Found", [304] = "Not Modified", [400] = "Bad Request", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [408] = "Request Time-out", [411] = "Length Required", [412] = "Precondition Failed", [416] = "Requested range not satisfiable", [500] = "Internal Server Error", [503] = "Server Unavailable", }
apache-2.0
Kthulupwns/darkstar
scripts/globals/items/acorn_cookie.lua
35
1338
----------------------------------------- -- ID: 4510 -- Item: Acorn Cookie -- Food Effect: 3Min, All Races ----------------------------------------- -- Magic Regen While Healing 3 -- Aquan Killer 5 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,180,4510); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_AQUAN_KILLER, 5); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_AQUAN_KILLER, 5); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
dpino/snabb
src/lib/ipsec/esp.lua
3
18586
-- Implementation of IPsec ESP using AES-128-GCM with a 12 byte ICV and -- “Extended Sequence Number” (see RFC 4303 and RFC 4106). Provides -- address-family independent encapsulation/decapsulation routines for -- “tunnel mode” and “transport mode” routines for IPv6. -- -- Notes: -- -- * Wrapping around of the Extended Sequence Number is *not* detected because -- it is assumed to be an unrealistic scenario as it would take 584 years to -- overflow the counter when transmitting 10^9 packets per second. -- -- * decapsulate_transport6: Rejection of IP fragments is *not* implemented -- because `lib.protocol.ipv6' does not support fragmentation. E.g. -- fragments will be rejected because they can not be parsed as IPv6 -- packets. If however `lib.protocol.ipv6' were to be updated to be able to -- parse IP fragments this implementation would have to be updated as well -- to remain correct. See the “Reassembly” section of RFC 4303 for details: -- https://tools.ietf.org/html/rfc4303#section-3.4.1 -- module(..., package.seeall) local header = require("lib.protocol.header") local datagram = require("lib.protocol.datagram") local ethernet = require("lib.protocol.ethernet") local ipv6 = require("lib.protocol.ipv6") local esp = require("lib.protocol.esp") local esp_tail = require("lib.protocol.esp_tail") local aes_128_gcm = require("lib.ipsec.aes_128_gcm") local seq_no_t = require("lib.ipsec.seq_no_t") local lib = require("core.lib") local ffi = require("ffi") local C = ffi.C local logger = lib.logger_new({ rate = 32, module = 'esp' }) require("lib.ipsec.track_seq_no_h") local window_t = ffi.typeof("uint8_t[?]") PROTOCOL = 50 -- https://tools.ietf.org/html/rfc4303#section-2 local ETHERNET_SIZE = ethernet:sizeof() local IPV6_SIZE = ipv6:sizeof() local ESP_SIZE = esp:sizeof() local ESP_TAIL_SIZE = esp_tail:sizeof() local TRANSPORT6_PAYLOAD_OFFSET = ETHERNET_SIZE + IPV6_SIZE local function padding (a, l) return (a - l%a) % a end function esp_new (conf) assert(conf.mode == "aes-gcm-128-12", "Only supports 'aes-gcm-128-12'.") assert(conf.spi, "Need SPI.") local o = { cipher = aes_128_gcm:new(conf.spi, conf.key, conf.salt), spi = conf.spi, seq = ffi.new(seq_no_t), pad_to = 4, -- minimal padding esp = esp:new({}), esp_tail = esp_tail:new({}), ip = ipv6:new({}) -- for transport mode } o.ESP_CTEXT_OVERHEAD = o.cipher.IV_SIZE + ESP_TAIL_SIZE o.ESP_OVERHEAD = ESP_SIZE + o.ESP_CTEXT_OVERHEAD + o.cipher.AUTH_SIZE return o end encrypt = {} function encrypt:new (conf) return setmetatable(esp_new(conf), {__index=encrypt}) end -- Increment sequence number. function encrypt:next_seq_no () self.seq.no = self.seq.no + 1 end function encrypt:padding (length) -- See https://tools.ietf.org/html/rfc4303#section-2.4 return padding(self.pad_to, length + self.ESP_CTEXT_OVERHEAD) end function encrypt:encode_esp_trailer (ptr, next_header, pad_length) self.esp_tail:new_from_mem(ptr, ESP_TAIL_SIZE) self.esp_tail:next_header(next_header) self.esp_tail:pad_length(pad_length) end function encrypt:encrypt_payload (ptr, length) self:next_seq_no() local seq, low, high = self.seq, self.seq:low(), self.seq:high() self.cipher:encrypt(ptr, seq, low, high, ptr, length, ptr + length) end function encrypt:encode_esp_header (ptr) self.esp:new_from_mem(ptr, ESP_SIZE) self.esp:spi(self.spi) self.esp:seq_no(self.seq:low()) ffi.copy(ptr + ESP_SIZE, self.seq, self.cipher.IV_SIZE) end -- Encapsulation in transport mode is performed as follows: -- 1. Grow p to fit ESP overhead -- 2. Append ESP trailer to p -- 3. Encrypt payload+trailer in place -- 4. Move resulting ciphertext to make room for ESP header -- 5. Write ESP header function encrypt:encapsulate_transport6 (p) if p.length < TRANSPORT6_PAYLOAD_OFFSET then return nil end local payload = p.data + TRANSPORT6_PAYLOAD_OFFSET local payload_length = p.length - TRANSPORT6_PAYLOAD_OFFSET local pad_length = self:padding(payload_length) local overhead = self.ESP_OVERHEAD + pad_length p = packet.resize(p, p.length + overhead) self.ip:new_from_mem(p.data + ETHERNET_SIZE, IPV6_SIZE) local tail = payload + payload_length + pad_length self:encode_esp_trailer(tail, self.ip:next_header(), pad_length) local ctext_length = payload_length + pad_length + ESP_TAIL_SIZE self:encrypt_payload(payload, ctext_length) local ctext = payload + ESP_SIZE + self.cipher.IV_SIZE C.memmove(ctext, payload, ctext_length + self.cipher.AUTH_SIZE) self:encode_esp_header(payload) self.ip:next_header(PROTOCOL) self.ip:payload_length(payload_length + overhead) return p end -- Encapsulation in tunnel mode is performed as follows: -- (In tunnel mode, the input packet must be an IP frame already stripped of -- its Ethernet header.) -- 1. Grow and shift p to fit ESP overhead -- 2. Append ESP trailer to p -- 3. Encrypt payload+trailer in place -- 4. Write ESP header -- (The resulting packet contains the raw ESP frame, without IP or Ethernet -- headers.) function encrypt:encapsulate_tunnel (p, next_header) local pad_length = self:padding(p.length) local trailer_overhead = pad_length + ESP_TAIL_SIZE + self.cipher.AUTH_SIZE local orig_length = p.length p = packet.resize(p, orig_length + trailer_overhead) local tail = p.data + orig_length + pad_length self:encode_esp_trailer(tail, next_header, pad_length) local ctext_length = orig_length + pad_length + ESP_TAIL_SIZE self:encrypt_payload(p.data, ctext_length) local len = p.length p = packet.shiftright(p, ESP_SIZE + self.cipher.IV_SIZE) self:encode_esp_header(p.data) return p end decrypt = {} function decrypt:new (conf) local o = esp_new(conf) o.MIN_SIZE = o.ESP_OVERHEAD + padding(o.pad_to, o.ESP_OVERHEAD) o.CTEXT_OFFSET = ESP_SIZE + o.cipher.IV_SIZE o.PLAIN_OVERHEAD = ESP_SIZE + o.cipher.IV_SIZE + o.cipher.AUTH_SIZE local window_size = conf.window_size or 128 o.window_size = window_size + padding(8, window_size) o.window = ffi.new(window_t, o.window_size / 8) o.resync_threshold = conf.resync_threshold or 1024 o.resync_attempts = conf.resync_attempts or 8 o.decap_fail = 0 o.auditing = conf.auditing return setmetatable(o, {__index=decrypt}) end function decrypt:decrypt_payload (ptr, length) -- NB: bounds check is performed by caller local esp = self.esp:new_from_mem(ptr, esp:sizeof()) local iv_start = ptr + ESP_SIZE local ctext_start = ptr + self.CTEXT_OFFSET local ctext_length = length - self.PLAIN_OVERHEAD local seq_low = esp:seq_no() local seq_high = tonumber( C.check_seq_no(seq_low, self.seq.no, self.window, self.window_size) ) local error = nil if seq_high < 0 or not self.cipher:decrypt( ctext_start, seq_low, seq_high, iv_start, ctext_start, ctext_length ) then if seq_high < 0 then error = "replayed" else error = "integrity error" end self.decap_fail = self.decap_fail + 1 if self.decap_fail > self.resync_threshold then seq_high = self:resync(ptr, length, seq_low, seq_high) if seq_high then error = nil end end end if error then self:audit(error) return nil end self.decap_fail = 0 self.seq.no = C.track_seq_no( seq_high, seq_low, self.seq.no, self.window, self.window_size ) local esp_tail_start = ctext_start + ctext_length - ESP_TAIL_SIZE self.esp_tail:new_from_mem(esp_tail_start, ESP_TAIL_SIZE) local ptext_length = ctext_length - self.esp_tail:pad_length() - ESP_TAIL_SIZE return ctext_start, ptext_length end -- Decapsulation in transport mode is performed as follows: -- 1. Parse IP and ESP headers and check Sequence Number -- 2. Decrypt ciphertext in place -- 3. Parse ESP trailer and update IP header -- 4. Move cleartext up to IP payload -- 5. Shrink p by ESP overhead function decrypt:decapsulate_transport6 (p) if p.length - TRANSPORT6_PAYLOAD_OFFSET < self.MIN_SIZE then return nil end self.ip:new_from_mem(p.data + ETHERNET_SIZE, IPV6_SIZE) local payload = p.data + TRANSPORT6_PAYLOAD_OFFSET local payload_length = p.length - TRANSPORT6_PAYLOAD_OFFSET local ptext_start, ptext_length = self:decrypt_payload(payload, payload_length) if not ptext_start then return nil end self.ip:next_header(self.esp_tail:next_header()) self.ip:payload_length(ptext_length) C.memmove(payload, ptext_start, ptext_length) p = packet.resize(p, TRANSPORT6_PAYLOAD_OFFSET + ptext_length) return p end -- Decapsulation in tunnel mode is performed as follows: -- (In tunnel mode, the input packet must be already stripped of its outer -- Ethernet and IP headers.) -- 1. Parse ESP header and check Sequence Number -- 2. Decrypt ciphertext in place -- 3. Parse ESP trailer and shrink p by overhead -- (The resulting packet contains the raw ESP payload (i.e. an IP frame), -- without an Ethernet header.) function decrypt:decapsulate_tunnel (p) if p.length < self.MIN_SIZE then return nil end local ptext_start, ptext_length = self:decrypt_payload(p.data, p.length) if not ptext_start then return nil end p = packet.shiftleft(p, self.CTEXT_OFFSET) p = packet.resize(p, ptext_length) return p, self.esp_tail:next_header() end function decrypt:audit (reason) if not self.auditing then return end -- This is the information RFC4303 says we SHOULD log logger:log("Rejecting packet (" .. "SPI=" .. self.spi .. ", " .. "src_addr='" .. self.ip:ntop(self.ip:src()) .. "', " .. "dst_addr='" .. self.ip:ntop(self.ip:dst()) .. "', " .. "seq_low=" .. self.esp:seq_no() .. ", " .. "flow_id=" .. self.ip:flow_label() .. ", " .. "reason='" .. reason .. "'" .. ")") end function decrypt:resync (ptr, length, seq_low, seq_high) local iv_start = ptr + ESP_SIZE local ctext_start = ptr + self.CTEXT_OFFSET local ctext_length = length - self.PLAIN_OVERHEAD if seq_high < 0 then -- The sequence number looked replayed, we use the last seq_high we have -- seen seq_high = self.seq:high() else -- We failed to decrypt in-place, undo the damage to recover the original -- ctext (ignore bogus auth data) self.cipher:encrypt( ctext_start, iv_start, seq_low, seq_high, ctext_start, ctext_length ) end local p_orig = packet.from_pointer(ptr, length) for i = 1, self.resync_attempts do seq_high = seq_high + 1 if self.cipher:decrypt( ctext_start, seq_low, seq_high, iv_start, ctext_start, ctext_length ) then packet.free(p_orig) return seq_high else ffi.copy(ptr, p_orig.data, length) end end end function selftest () local conf = { spi = 0x0, mode = "aes-gcm-128-12", key = "00112233445566778899AABBCCDDEEFF", salt = "00112233", resync_threshold = 16, resync_attempts = 8} local enc, dec = encrypt:new(conf), decrypt:new(conf) local payload = packet.from_string( [[abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789]] ) local d = datagram:new(payload) local ip = ipv6:new({}) ip:payload_length(payload.length) d:push(ip) d:push(ethernet:new({type=0x86dd})) local p = d:packet() -- Check integrity print("original", lib.hexdump(ffi.string(p.data, p.length))) local p_enc = assert(enc:encapsulate_transport6(packet.clone(p)), "encapsulation failed") print("encrypted", lib.hexdump(ffi.string(p_enc.data, p_enc.length))) local p2 = assert(dec:decapsulate_transport6(packet.clone(p_enc)), "decapsulation failed") print("decrypted", lib.hexdump(ffi.string(p2.data, p2.length))) assert(p2.length == p.length and C.memcmp(p.data, p2.data, p.length) == 0, "integrity check failed") -- ... for tunnel mode local p_enc = assert(enc:encapsulate_tunnel(packet.clone(p), 42), "encapsulation failed") print("enc. (tun)", lib.hexdump(ffi.string(p_enc.data, p_enc.length))) local p2, nh = dec:decapsulate_tunnel(packet.clone(p_enc)) assert(p2 and nh == 42, "decapsulation failed") print("dec. (tun)", lib.hexdump(ffi.string(p2.data, p2.length))) assert(p2.length == p.length and C.memcmp(p.data, p2.data, p.length) == 0, "integrity check failed") -- Check invalid packets. assert(not enc:encapsulate_transport6(packet.from_string("invalid")), "encapsulated invalid packet") assert(not dec:decapsulate_transport6(packet.from_string("invalid")), "decapsulated invalid packet") -- ... for tunnel mode assert(not dec:decapsulate_tunnel(packet.from_string("invalid")), "decapsulated invalid packet") -- Check minimum packet. local p_min = packet.from_string("012345678901234567890123456789012345678901234567890123") p_min.data[18] = 0 -- Set IPv6 payload length to zero p_min.data[19] = 0 -- ... assert(p_min.length == TRANSPORT6_PAYLOAD_OFFSET) print("original", lib.hexdump(ffi.string(p_min.data, p_min.length))) local e_min = assert(enc:encapsulate_transport6(packet.clone(p_min))) print("encrypted", lib.hexdump(ffi.string(e_min.data, e_min.length))) assert(e_min.length == dec.MIN_SIZE+TRANSPORT6_PAYLOAD_OFFSET) e_min = assert(dec:decapsulate_transport6(e_min), "decapsulation of minimum packet failed") print("decrypted", lib.hexdump(ffi.string(e_min.data, e_min.length))) assert(e_min.length == TRANSPORT6_PAYLOAD_OFFSET) assert(p_min.length == e_min.length and C.memcmp(p_min.data, e_min.data, p_min.length) == 0, "integrity check failed") -- ... for tunnel mode print("original", "(empty)") local e_min = assert(enc:encapsulate_tunnel(packet.allocate(), 0)) print("enc. (tun)", lib.hexdump(ffi.string(e_min.data, e_min.length))) e_min = assert(dec:decapsulate_tunnel(e_min)) assert(e_min.length == 0) -- Tunnel/transport mode independent tests for _, op in ipairs( {{encap=function (p) return enc:encapsulate_transport6(p) end, decap=function (p) return dec:decapsulate_transport6(p) end}, {encap=function (p) return enc:encapsulate_tunnel(p, 0) end, decap=function (p) return dec:decapsulate_tunnel(p) end}} ) do -- Check transmitted Sequence Number wrap around C.memset(dec.window, 0, dec.window_size / 8) -- clear window enc.seq.no = 2^32 - 1 -- so next encapsulated will be seq 2^32 dec.seq.no = 2^32 - 1 -- pretend to have seen 2^32-1 local px = op.encap(packet.clone(p)) assert(op.decap(px), "Transmitted Sequence Number wrap around failed.") assert(dec.seq:high() == 1 and dec.seq:low() == 0, "Lost Sequence Number synchronization.") -- Check Sequence Number exceeding window C.memset(dec.window, 0, dec.window_size / 8) -- clear window enc.seq.no = 2^32 dec.seq.no = 2^32 + dec.window_size + 1 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "Accepted out of window Sequence Number.") assert(dec.seq:high() == 1 and dec.seq:low() == dec.window_size+1, "Corrupted Sequence Number.") -- Test anti-replay: From a set of 15 packets, first send all those -- that have an even sequence number. Then, send all 15. Verify that -- in the 2nd run, packets with even sequence numbers are rejected while -- the others are not. -- Then do the same thing again, but with offset sequence numbers so that -- we have a 32bit wraparound in the middle. local offset = 0 -- close to 2^32 in the 2nd iteration for offset = 0, 2^32-7, 2^32-7 do -- duh C.memset(dec.window, 0, dec.window_size / 8) -- clear window dec.seq.no = offset for i = 1+offset, 15+offset do if (i % 2 == 0) then enc.seq.no = i-1 -- so next seq will be i local px = op.encap(packet.clone(p)) assert(op.decap(px), "rejected legitimate packet seq=" .. i) assert(dec.seq.no == i, "Lost sequence number synchronization") end end for i = 1+offset, 15+offset do enc.seq.no = i-1 local px = op.encap(packet.clone(p)) if (i % 2 == 0) then assert(not op.decap(px), "accepted replayed packet seq=" .. i) else assert(op.decap(px), "rejected legitimate packet seq=" .. i) end end end -- Check that packets from way in the past/way in the future (further -- than the biggest allowable window size) are rejected This is where we -- ultimately want resynchronization (wrt. future packets) C.memset(dec.window, 0, dec.window_size / 8) -- clear window dec.seq.no = 2^34 + 42 enc.seq.no = 2^36 + 24 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "accepted packet from way into the future") enc.seq.no = 2^32 + 42 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "accepted packet from way into the past") -- Test resynchronization after having lost >2^32 packets enc.seq.no = 0 dec.seq.no = 0 C.memset(dec.window, 0, dec.window_size / 8) -- clear window local px = op.encap(packet.clone(p)) -- do an initial packet assert(op.decap(px), "decapsulation failed") enc.seq:high(3) -- pretend there has been massive packet loss enc.seq:low(24) for i = 1, dec.resync_threshold do local px = op.encap(packet.clone(p)) assert(not op.decap(px), "decapsulated pre-resync packet") end local px = op.encap(packet.clone(p)) assert(op.decap(px), "failed to resynchronize") -- Make sure we don't accidentally resynchronize with very old replayed -- traffic enc.seq.no = 42 for i = 1, dec.resync_threshold do local px = op.encap(packet.clone(p)) assert(not op.decap(px), "decapsulated very old packet") end local px = op.encap(packet.clone(p)) assert(not op.decap(px), "resynchronized with the past!") end end
apache-2.0
beni55/lua-resty-http
lib/resty/http_headers.lua
69
1716
local rawget, rawset, setmetatable = rawget, rawset, setmetatable local str_gsub = string.gsub local str_lower = string.lower local _M = { _VERSION = '0.01', } -- Returns an empty headers table with internalised case normalisation. -- Supports the same cases as in ngx_lua: -- -- headers.content_length -- headers["content-length"] -- headers["Content-Length"] function _M.new(self) local mt = { normalised = {}, } mt.__index = function(t, k) local k_hyphened = str_gsub(k, "_", "-") local matched = rawget(t, k) if matched then return matched else local k_normalised = str_lower(k_hyphened) return rawget(t, mt.normalised[k_normalised]) end end -- First check the normalised table. If there's no match (first time) add an entry for -- our current case in the normalised table. This is to preserve the human (prettier) case -- instead of outputting lowercased header names. -- -- If there's a match, we're being updated, just with a different case for the key. We use -- the normalised table to give us the original key, and perorm a rawset(). mt.__newindex = function(t, k, v) -- we support underscore syntax, so always hyphenate. local k_hyphened = str_gsub(k, "_", "-") -- lowercase hyphenated is "normalised" local k_normalised = str_lower(k_hyphened) if not mt.normalised[k_normalised] then mt.normalised[k_normalised] = k_hyphened rawset(t, k_hyphened, v) else rawset(t, mt.normalised[k_normalised], v) end end return setmetatable({}, mt) end return _M
bsd-2-clause
kayru/tundra
scripts/tundra/syntax/native.lua
9
10662
-- native.lua -- support for programs, static libraries and such module(..., package.seeall) local util = require "tundra.util" local nodegen = require "tundra.nodegen" local path = require "tundra.path" local depgraph = require "tundra.depgraph" local _native_mt = nodegen.create_eval_subclass { DeclToEnvMappings = { Libs = "LIBS", Defines = "CPPDEFS", Includes = "CPPPATH", Frameworks = "FRAMEWORKS", LibPaths = "LIBPATH", }, } local _object_mt = nodegen.create_eval_subclass({ Suffix = "$(OBJECTSUFFIX)", Prefix = "", Action = "$(OBJCOM)", Label = "Object $(<)", OverwriteOutputs = true, }, _native_mt) local _program_mt = nodegen.create_eval_subclass({ Suffix = "$(PROGSUFFIX)", Prefix = "$(PROGPREFIX)", Action = "$(PROGCOM)", Label = "Program $(@)", PreciousOutputs = true, OverwriteOutputs = true, Expensive = true, }, _native_mt) local _staticlib_mt = nodegen.create_eval_subclass({ Suffix = "$(LIBSUFFIX)", Prefix = "$(LIBPREFIX)", Action = "$(LIBCOM)", Label = "StaticLibrary $(@)", -- Play it safe and delete the output files of this node before re-running it. -- Solves iterative issues with e.g. AR OverwriteOutputs = false, IsStaticLib = true, }, _native_mt) local _objgroup_mt = nodegen.create_eval_subclass({ Label = "ObjGroup $(<)", }, _native_mt) local _shlib_mt = nodegen.create_eval_subclass({ Suffix = "$(SHLIBSUFFIX)", Prefix = "$(SHLIBPREFIX)", Action = "$(SHLIBCOM)", Label = "SharedLibrary $(@)", PreciousOutputs = true, OverwriteOutputs = true, Expensive = true, }, _native_mt) local _extlib_mt = nodegen.create_eval_subclass({ Suffix = "", Prefix = "", Label = "", }, _native_mt) local cpp_exts = util.make_lookup_table { ".cpp", ".cc", ".cxx", ".C" } local _is_native_mt = util.make_lookup_table { _object_mt, _program_mt, _staticlib_mt, _shlib_mt, _extlib_mt, _objgroup_mt } -- sources can be a mix of raw strings like {"file1.cpp", "file2.cpp"} -- or files with filters like {{"file1.cpp", "file2.cpp"; Config = "..."}} local function is_file_in_sources(sources, fn) for k,v in pairs(sources) do if type(v) == 'table' then return util.array_contains(v, fn) elseif v == fn then return true end end return false end function _native_mt:customize_env(env, raw_data) if env:get('GENERATE_PDB', '0') ~= '0' then -- Figure out the final linked PDB (the one next to the dll or exe) if raw_data.Target then local target = env:interpolate(raw_data.Target) local link_pdb = path.drop_suffix(target) .. '.pdb' env:set('_PDB_LINK_FILE', link_pdb) else env:set('_PDB_LINK_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. ".pdb") end -- Keep the compiler's idea of the PDB file separate env:set('_PDB_CC_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. "_ccpdb.pdb") env:set('_USE_PDB_CC', '$(_USE_PDB_CC_OPT)') env:set('_USE_PDB_LINK', '$(_USE_PDB_LINK_OPT)') end local pch = raw_data.PrecompiledHeader if pch and env:get('_PCH_SUPPORTED', '0') ~= '0' then assert(pch.Header) if not nodegen.resolve_pass(pch.Pass) then croak("%s: PrecompiledHeader requires a valid Pass", raw_data.Name) end local pch_dir = "$(OBJECTDIR)/__" .. raw_data.Name env:set('_PCH_HEADER', pch.Header) env:set('_PCH_FILE', pch_dir .. '/' .. pch.Header .. '$(_PCH_SUFFIX)') env:set('_PCH_INCLUDE_PATH', path.join(pch_dir, pch.Header)) env:set('_USE_PCH', '$(_USE_PCH_OPT)') env:set('_PCH_SOURCE', path.normalize(pch.Source)) env:set('_PCH_PASS', pch.Pass) if cpp_exts[path.get_extension(pch.Source)] then env:set('PCHCOMPILE', '$(PCHCOMPILE_CXX)') else env:set('PCHCOMPILE', '$(PCHCOMPILE_CC)') end local pch_source = path.remove_prefix(raw_data.SourceDir or '', pch.Source) if not is_file_in_sources(raw_data.Sources, pch_source) then raw_data.Sources[#raw_data.Sources + 1] = pch_source end end if env:has_key('MODDEF') then env:set('_USE_MODDEF', '$(_USE_MODDEF_OPT)') end end function _native_mt:create_dag(env, data, input_deps) local build_id = env:get("BUILD_ID") local my_pass = data.Pass local sources = data.Sources local libsuffix = { env:get("LIBSUFFIX") } local shlibsuffix = { env:get("SHLIBLINKSUFFIX") } local my_extra_deps = {} -- Link with libraries in dependencies. for _, dep in util.nil_ipairs(data.Depends) do if dep.Keyword == "SharedLibrary" then -- On Win32 toolsets, we need foo.lib -- On UNIX toolsets, we need -lfoo -- -- We only want to add this if the node actually produced any output (i.e -- it's not completely filtered out.) local node = dep:get_dag(env:get_parent()) if #node.outputs > 0 then my_extra_deps[#my_extra_deps + 1] = node local target = dep.Decl.Target or dep.Decl.Name target = env:interpolate(target) local dir, fn = path.split(target) local libpfx = env:interpolate("$(LIBPREFIX)") if fn:sub(1, libpfx:len()) == libpfx then fn = fn:sub(libpfx:len()+1) end local link_lib = path.drop_suffix(fn) .. '$(SHLIBLINKSUFFIX)' env:append('LIBS', link_lib) if dir:len() > 0 then env:append('LIBPATH', dir) end end elseif dep.Keyword == "StaticLibrary" then local node = dep:get_dag(env:get_parent()) my_extra_deps[#my_extra_deps + 1] = node if not self.IsStaticLib then node:insert_output_files(sources, libsuffix) end elseif dep.Keyword == "ObjGroup" then -- We want all .obj files local objsuffix = { env:get("OBJECTSUFFIX") } -- And also .res files, if we know what that is if env:has_key("W32RESSUFFIX") then objsuffix[#objsuffix + 1] = env:get("W32RESSUFFIX") end local node = dep:get_dag(env:get_parent()) my_extra_deps[#my_extra_deps + 1] = node if not sources then sources = {} end for _, dep in util.nil_ipairs(node.deps) do my_extra_deps[#my_extra_deps + 1] = dep dep:insert_output_files(sources, objsuffix) end else --[[ A note about win32 import libraries: It is tempting to add an implicit input dependency on the import library of the linked-to shared library here; but this would be suboptimal: 1. Because there is a dependency between the nodes themselves, the import library generation will always run before this link step is run. Therefore, the import lib will always exist and be updated before this link step runs. 2. Because the import library is regenerated whenever the DLL is relinked we would have to custom-sign it (using a hash of the DLLs export list) to avoid relinking the executable all the time when only the DLL's internals change. 3. The DLL's export list should be available in headers anyway, which is already covered in the compilation of the object files that actually uses those APIs. Therefore the best way right now is to not tell Tundra about the import lib at all and rely on header scanning to pick up API changes. An implicit input dependency would be needed however if someone is doing funky things with their import library (adding non-linker-generated code for example). These cases are so rare that we can safely put them off. ]]-- end end -- Make sure sources are not specified more than once. This can happen when -- there are recursive dependencies on object groups. if data.Sources and #data.Sources > 0 then data.Sources = util.uniq(data.Sources) end local aux_outputs = env:get_list("AUX_FILES_" .. self.Keyword:upper(), {}) if env:get('GENERATE_PDB', '0') ~= '0' then aux_outputs[#aux_outputs + 1] = "$(_PDB_LINK_FILE)" aux_outputs[#aux_outputs + 1] = "$(_PDB_CC_FILE)" end local extra_inputs = {} if env:has_key('MODDEF') then extra_inputs[#extra_inputs + 1] = "$(MODDEF)" end local targets = nil if self.Action then targets = { nodegen.get_target(data, self.Suffix, self.Prefix) } end local deps = util.merge_arrays(input_deps, my_extra_deps) local dag = depgraph.make_node { Env = env, Label = self.Label, Pass = data.Pass, Action = self.Action, PreAction = data.PreAction, InputFiles = data.Sources, InputFilesUntracked = data.UntrackedSources, OutputFiles = targets, AuxOutputFiles = aux_outputs, ImplicitInputs = extra_inputs, Dependencies = deps, OverwriteOutputs = self.OverwriteOutputs, PreciousOutputs = self.PreciousOutputs, Expensive = self.Expensive, } -- Remember this dag node for IDE file generation purposes data.__DagNode = dag return dag end local native_blueprint = { Name = { Required = true, Help = "Set output (base) filename", Type = "string", }, Sources = { Required = true, Help = "List of source files", Type = "source_list", ExtensionKey = "NATIVE_SUFFIXES", }, UntrackedSources = { Help = "List of input files that are not tracked", Type = "source_list", ExtensionKey = "NATIVE_SUFFIXES", }, Target = { Help = "Override target location", Type = "string", }, PreAction = { Help = "Optional action to run before main action.", Type = "string", }, PrecompiledHeader = { Help = "Enable precompiled header (if supported)", Type = "table", }, IdeGenerationHints = { Help = "Data to support control IDE file generation", Type = "table", }, } local external_blueprint = { Name = { Required = true, Help = "Set name of the external library", Type = "string", }, } local external_counter = 1 function _extlib_mt:create_dag(env, data, input_deps) local name = string.format("dummy node for %s (%d)", data.Name, external_counter) external_counter = external_counter + 1 return depgraph.make_node { Env = env, Label = name, Pass = data.Pass, Dependencies = input_deps, } end nodegen.add_evaluator("Object", _object_mt, native_blueprint) nodegen.add_evaluator("Program", _program_mt, native_blueprint) nodegen.add_evaluator("StaticLibrary", _staticlib_mt, native_blueprint) nodegen.add_evaluator("SharedLibrary", _shlib_mt, native_blueprint) nodegen.add_evaluator("ExternalLibrary", _extlib_mt, external_blueprint) nodegen.add_evaluator("ObjGroup", _objgroup_mt, native_blueprint)
gpl-3.0
moteus/lua-odbc-pool
examples/fusionpbx/odbc_pool.lua
1
1666
require "resources.functions.config" require "resources.functions.file_exists" local log = require "resources.functions.log".dbpool local odbc = require "odbc" local odbcpool = require "odbc.pool" -- Configuration local POLL_TIMEOUT = 5 local run_file = scripts_dir .. "/run/dbpool.tmp"; -- Pool ctor local function run_odbc_pool(name, n) local connection_string = assert(database[name]) local typ, dsn, user, password = connection_string:match("^(.-)://(.-):(.-):(.-)$") assert(typ == 'odbc', "unsupported connection string:" .. connection_string) local cli = odbcpool.client(name) log.noticef("Starting reconnect thread[%s] ...", name) local rthread = odbcpool.reconnect_thread(cli, dsn, user, password) rthread:start() log.noticef("Reconnect thread[%s] started", name) local env = odbc.environment() local connections = {} for i = 1, (n or 10) do local cnn = odbc.assert(env:connection()) connections[#connections+1] = cnn cli:reconnect(cnn) end return { name = name; cli = cli; cnn = connections; thr = rthread; } end local function stop_odbc_pool(ctx) log.noticef("Stopping reconnect thread[%s] ...", ctx.name) ctx.thr:stop() log.noticef("Reconnect thread[%s] stopped", ctx.name) end local function main() local system_pool = run_odbc_pool("system", 10) local switch_pool = run_odbc_pool("switch", 10) local file = assert(io.open(run_file, "w")); file:write("remove this file to stop the script"); file:close() while file_exists(run_file) do freeswitch.msleep(POLL_TIMEOUT*1000) end stop_odbc_pool(system_pool) stop_odbc_pool(switch_pool) end main()
mit
ASHRAF97/ASHRAFKASPERV3
plugins/iq_abs.lua
2
15268
-- made by { @Mouamle } do ws = {} rs = {} -- some examples of how to use this :3 ws[1] = "هلاو" rs[1] = "هـﮩـڵآوآت 🦀❤" ws[2] = "هلو" -- msg rs[2] = "هـﮩـڵآوآت 🦀❤️" -- reply ws[3] = "شلونكم" -- msg rs[3] = "تـمـآم وأنتـہ 🌝💙" -- reply ws[4] = "دووم" -- msg rs[4] = "يدوم نبضك 🌝💙" -- reply ws[5] = "شونك" rs[5] = "تـمـآم وأنتـہ 🌝💙" ws[6] = "شلونك" rs[6] = "تـمـآم وأنتـہ 🌝💙" ws[7] = "غنيلي" rs[7] = " 🙈 احبك اني 🙊 اني احبك 🙉 واتحدى واحد بلبشر مثلي يحبك 🙊" ws[8] = "شغل المبردة" rs[8] = " تم تشغيل المبردة بنجاح ❄️" ws[9] = "طفي المبردة" rs[9] = "طفيتهه 😒🍃" ws[10] = "شغل السبلت" rs[10] = "شغلته 🌚🍃 بس حثلجون معليه ترا " ws[11] = "مايا خليفه" rs[11] = " 😂 عيب صايمين" ws[12] = "فطور" rs[12] = "واخيراً 😍😍 خل اروح افطر " ws[13] = "جاسم" rs[13] = "خير 🌚🍃" ws[14] = "اه" rs[14] = "ادخله 🍆" ws[15] = "تخليني" rs[15] = "لـمن يصـير عـندڪ عود اخليګ 😹🌝" ws[16] = "زاحف" rs[16] = "🌝😹 هاي عود انته جبير" ws[17] = "تركيا" rs[17] = "😐🍃 فديتهه" ws[18] = "داعش" rs[18] = "دي خل يولون 😒💙" ws[19] = "الدولة الاسلامية" rs[19] = "انته داعشي ؟؟ 😒💔" ws[20] = "سني" rs[20] = "لتصير طائفي 😐💙" ws[21] = "شيعي" rs[21] = "لتصير طائفي 😐💙" ws[22] = "تبادل" rs[22] = "كافي ملينه 😒 ما اريد اتبادل" ws[23] = "العراقيين" rs[23] = "احلى ناس ولله 😻🙈" ws[24] = "من وين" rs[24] = "شعليك زاحف 😹🌶" ws[25] = "هاي" rs[25] = "هـٱيـآت🙈🍷" ws[26] = "البوت" rs[26] = "معاجبك؟😕😒🍃" ws[27] = "البوت واكف" rs[27] = "لتجذب🙄💙" ws[28] = "منو ديحذف رسائلي" rs[28] = "مـحـد 🏌" ws[29] = "كلاش اوف كلانس" rs[29] = "تلعبهه ؟ شكد لفلك ؟" ws[30] = "جوني" rs[30] = "😹مأذيك ؟" ws[31] = "ازحف " rs[31] = "عـلـﻰ ٱخـتـڪ ٱزحـف 🐉" ws[32] = "اكطع" rs[32] = " سِـلُـطِـُه مٌـنَ بّْعـدِ 😅الُبّـ🤖ـوَتْ🎄 " ws[33] = "بوت" rs[33] = "ها نعم ..{✮ خٍّـٌٍّـٍَْيْـٌٍّرَُ ✮}.. ✭ شتريد مني خلوني انام شوي ✾ ٱڵـڵـه واكبر عليكم اربعه وعشرين ساعه كاعد احمي بكروبكم شوي خلوني ارتاح تكسبون اجر 😭 بَـßÊـسّ كلولي شلون احمي كروبكم اذا زباله ازعل واطلع واذا عاجبكم خلوني انام 😢😂" ws[34] = "اريد بوت" rs[34] = " تريد بوت بكروبك وسيرفر مدفوع 24 ساعه راسل المطور ويضيفني بكروبك @IQ_ABS ❥" ws[35] = "اريد اكبل" rs[35] = "زُاحُـفَ مٌـوَ بّـيَـدِكِ 😒😂" ws[37] = "عبوسي" rs[37] = "ٲلمطور ماڵتي فديتهہ 😻💙 @IQ_ABS" ws[38] = "نجب" rs[38] = "بّـحُـلُـكِكِ😑👊" ws[39] = "المنصور" rs[39] = " احلى ناس ولله " ws[40] = "المدرسه" rs[40] = "😒🍃الله لا يراوينه" ws[41] = "تحبني" rs[41] = "اعـشقـڪ😻" ws[42] = "يعني شكد" rs[42] = "فوك متتوقع" ws[43] = "😂" rs[43] = " دوم حبي ❤️" ws[44] = "هههه" rs[44] = "❀دِْوم حبيْ❀" ws[45] = "ههههه" rs[45] = "️❀دِْوم حبيْ❀" ws[46] = "😹" rs[46] = "❀دِْوم حبيْ❀" ws[47] = "🌚" rs[47] = "مـنـور صخـام الـجـدر 🌚😹" ws[48] = "😍" rs[48] = "آإمـ﴿😚﴾ـحہ" ws[49] = "مح" rs[49] = "عہ🍯🙊سہل" ws[50] = "انمي" rs[50] = "اته اوتاكو ؟ ❤️" ws[51] = "منحرف" rs[51] = "وينه حطردة 🌚☝️🏻" ws[52] = "😭" rs[52] = "ڵـتبجـي 😿" ws[53] = "😢" rs[53] = "ڵـتبجـي 😿" ws[54] = "شكد عمرك" rs[54] = "زاحـﮩـف 😹" ws[55] = "شكد عمرج" rs[55] = "زاحـﮩـف 😹" ws[56] = "اقرالي دعاء" rs[56] = " اللهم عذب المدرسين 😢 منهم الاحياء والاموات 😭🔥 اللهم عذب ام الانكليزي 😭💔 وكهربها بلتيار الرئيسي 😇 اللهم عذب ام الرياضيات وحولها الى غساله بطانيات 🙊 اللهم عذب ام الاسلاميه واجعلها بائعة الشاميه 😭🍃 اللهم عذب ام العربي وحولها الى بائعه البلبي اللهم عذب ام الجغرافيه واجعلها كلدجاجه الحافية اللهم عذب ام التاريخ وزحلقها بقشره من البطيخ وارسلها الى المريخ اللهم عذب ام الاحياء واجعلها كل مومياء اللهم عذب المعاون اقتله بلمدرسه بهاون 😂😂😂" ws[57] = "غبي" rs[57] = " انـت ٱڵٱغبۍ" ws[58] = "دي" rs[58] = "دي تنـڪاڵ لـبوك 🌝🖕" ws[59] = "منو حبيبك" rs[59] = "ٲخـتڪ 🙈" ws[60] = "تكرهني" rs[60] = "ٲمـوت منڪ 😖" ws[61] = "اكرهك" rs[61] = "عـلسـاس ٲنـﮩـي ٲحـبڪ هه😒😂" ws[62] = "😂" rs[62] = "❀دِْوم حبيْ❀" ws[63] = "الاعضميه" rs[63] = " احسن ناس وربي❤️" ws[64] = "الكرادة" rs[64] = " احسن ناس وربي❤️" ws[65] = "شارع فلسطين" rs[65] = " احسن ناس وربي❤️" ws[66] = "ببكن ملف" rs[66] = " دﮩہہ⇣﴿🐎﴾⇣ہہﮩيہ❥ تحلم 🐞" ws[67] = "😇" rs[67] = "شـﮩﮩـدتـﮩـحس 🐛" ws[68] = "😐" rs[68] = "شِـبـيک صـﮩـٲفـﮩـن 😒👋🏻" ws[69] = "انجب" rs[69] = "بـحـلكڪ😒💦" ws[70] = "حارة" rs[70] = "ايَيَ ڪوَلڵشِ⚶ " ws[71] = "خالتك" rs[71] = " راح اطـﮩـردڪ ڵـﮩۦـڪ 😒🐞" ws[72] = "اطرد البوت" rs[72] = " راح ابقة احترمك❤️" ws[73] = "هه" rs[73] = " شـﮩـدتـحـﮩـس 🕊" ws[74] = "شدتحس" rs[74] = " نـﮩـفـﮩـس شـعـﮩـورك 🍁🐎" ws[75] = "اكولك" rs[75] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐿" ws[76] = "اكلك" rs[76] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐿" ws[78] = "بغداد" rs[78] = " 😍 فديتهه" ws[79] = "البصرة" rs[79] = " احسن ناس وربي❤️" ws[80] = "تركماني" rs[80] = " والنعم منك❤️" ws[81] = "@IQ_ABS" rs[81] = "ٲلمطور ماڵتي فديتهہ 😻💙 @IQ_ABS" ws[83] = "باي" rs[83] = " ✾ ٱڵـڵـه ✾ ٱڵـڵـه ✾ ٱڵـڵـه وياك 🕊" ws[84] = "تنح" rs[84] = "عـيـب ٲبـنـي 😒🍃" ws[85] = "جوعان" rs[85] = "تـﮩـعال اڪـﮩـلنـي 😐😂" ws[86] = "عطشان" rs[86] = "روح ٲشـﮩـرب مــيي" ws[87] = "صايم" rs[87] = "شًـﮩـسـويـلـك 😐🍃" ws[88] = "☹️" rs[88] = "لـﮩـضـوج פـٍـٍبيبي 😢❤️🍃" ws[89] = "😔" rs[89] = " لـﮩـيـﺵ ضـٲيـﮩـج 😿🍃" ws[90] = "فرخ" rs[90] = " عيبب 😱😱" ws[92] = "كسمك" rs[92] = " عيب 😱😱😱" ws[93] = "نعال" rs[93] = " بـﮩـوجـهـڪ 😐😂" ws[94] = "حروح اسبح" rs[94] = " واخيراً 😹🌝" ws[95] = "حروح اغسل" rs[95] = " واخيراً 😹🌝" ws[96] = "حروح اطب للحمام" rs[96] = " واخيراً 😹🌝" ws[97] = "حبيبتي" rs[97] = " منو هاي 😱 تخوني 😔☹" ws[98] = "كبلت" rs[98] = " بلخير 😂💔" ws[99] = "البوت عاوي" rs[99] = " اطردك ؟ 😒" ws[100] = "منور" rs[100] = " بـﮩـنورك حـﮩـبـﮩـي 😍🍷" ws[101] = "حفلش" rs[101] = " افلش راسك" ws[102] = "كردي" rs[102] = "والنعم منك ❤️" ws[103] = "طفي السبلت" rs[103] = " تم اطفاء السبلت بنجاح 🌚🍃" ws[104] = "🌝" rs[104] = "مــﮩﮩﮩــننوورر 🌝💙" ws[105] = "اذن المغرب" rs[105] = "ٲسـﮩـتـحـﮩـرم 🌚🍃" ws[106] = "حلو" rs[106] = "ٱنـﮩـت الاحـلآ 🌚❤️️" ws[107] = "احبك" rs[107] = " اني اكثر 😍🍃" ws[108] = "😑" rs[108] = " شبيك 🍃☹" ws[109] = "😒" rs[109] = "شِـبـيک کآڵـب وجـهہهـڪ 😐" ws[110] = "منو تحب" rs[110] = "خـﮩـالـتڪ ٱلـشـڪـرﮪ 😹🏃🏻" ws[111] = "اباجر العيد" rs[111] = "كل عام وانت بالف خير حبي 😇❤️" ws[112] = "فديت" rs[112] = "ها زاحف كمشتك" ws[113] = "مضغوط" rs[113] = "دي انضغظ منك ؟ 😂😂" ws[114] = "فديت" rs[114] = "ها زاحف كمشتك" ws[115] = "فديتك" rs[115] = "ها زاحف كمشتك" ws[116] = "فديتج" rs[116] = "ها زاحف كمشتك" ws[117] = "شوف خاصك" rs[117] = "شدازله 😱😨" ws[118] = "تعال خاص" rs[118] = "شحسوون 😱" ws[119] = "تعالي خاص" rs[119] = "شحسوون 😱" ws[120] = "دخل السبام" rs[120] = "شحسوون 😱" ws[121] = "😎" rs[121] = "يلا عود انته فد نعال 😐🍃" ws[122] = "😱" rs[122] = "خير خوفتني 😨" ws[123] = "كحبه" rs[123] = "عيب 😱" ws[124] = "بيش ساعة" rs[124] = "ما اعرف 🌚🍃" ws[125] = "🚶🏻" rs[125] = "لُـﮩـضڵ تتـمشـﮥ اڪعـد ﺳـﯠڵـف 🤖👋🏻" ws[126] = "منو اكثر واحد تحبه" rs[126] = "خالتك" ws[127] = "ليش" rs[127] = "تاكل خرة الجيش 😂😂" ws[128] = "طاسه" rs[128] = "امك حلوة ورقاصه 💃🏻" ws[129] = "عشرين" rs[129] = "تاكل جدر خنين 😫" ws[130] = "ميه" rs[130] = "😂تشرب مميه" ws[131] = "اربعة" rs[131] = "😂لحيه ابوك مربعه" ws[132] = "فارة" rs[132] = "😂دفترك كله صفارة" ws[133] = "ميتين" rs[133] = "😂فوك راسك قندرتين" ws[134] = "مات" rs[134] = "ابو الحمامات 🐦" ws[135] = "توفه" rs[135] = "ابو اللفه 🌯" ws[136] = "احترك" rs[136] = "🍾البو العرك" ws[137] = "غرك" rs[137] = "ابو العرك 🍾" ws[138] = "طار" rs[138] = "ابن الطيار" ws[139] = "ديسحك" rs[139] = "😂😂 هاي بعده" ws[140] = "لتسحك" rs[140] = "😐😂 وك" ws[141] = "اندرويد" rs[141] = "افشل نظام بلعالم 🌝🍷" ws[142] = "ios" rs[142] = "احسن نظام بلعالم🌚❤️" ws[143] = "ايفون" rs[143] = "فديتك اته والايفون 🌚🔥" ws[144] = "كلكسي" rs[144] = "فاشل اخرة نوع تلفون🔥☹" ws[145] = "سامسونك" rs[145] = "فاشل اخرة نوع تلفون🔥☹" ws[146] = "لتزحف" rs[146] = "وك اسف 🙁😔" ws[147] = "حاته" rs[147] = "زاحف 😂 منو هاي دزلي صورتهه" ws[148] = "حات" rs[148] = "زاحفه 😂 منو هذا دزيلي صورته" ws[149] = "صاكه" rs[149] = "زاحف 😂 منو هاي دزلي صورتهه" ws[150] = "صاك" rs[150] = "زاحفه 😂 منو هذا دزيلي صورهه" ws[151] = "منو اني" rs[151] = "انته احلى شي بحياتي ❤️🍃" ws[152] = "ابن الكلب" rs[152] = "عيب ابني 🔥☹" ws[153] = "انجب انته" rs[153] = "وك وك 😭😔" ws[154] = "حطردك" rs[154] = "اعصابك 😨 لتتهور" ws[155] = "المطور" rs[155] = "شتريد من المطور 😐🍃" ws[156] = "منو اكثر واحد تكرهه" rs[156] = "انته" ws[157] = "شباب" rs[157] = "هًّْـــُ﴿⍨﴾ـٍِٰـــہاا حـﮩـب 🚶🏻🌝" ws[158] = "اته زلمه" rs[158] = "تعال لزمه 😐😂" ws[159] = "الاحد" rs[159] = "هذا اليوم نحس بلنسبه الي" ws[160] = "الاثنين" rs[160] = "يوم اجة بي ناس عزيزين وفقدت بي ناس هم ☹" ws[161] = "هلاوو" rs[161] = "هـﮩـڵآوآت 🦀❤️" ws[162] = "اختك" rs[162] = "شبيهه 😱" ws[163] = "كواد" rs[163] = "عيب 😨😨" ws[164] = "😌" rs[164] = "ٱڵـمـطـڵـوب ¿ ❥" ws[165] = "هلا" rs[165] = "✾ هـﮩـڵا ہبـﮩـک 💙🖐🏻" ws[166] = "مرحبا" rs[166] = "✾ مٌـﮩۚـرحـﮩۘـبـتـيـن 💙🖐🏻" ws[167] = "سلام" rs[167] = "✾ ٲلـﮩـسـلا۾م ؏ـﮩـڵـيڪم 💙🖐🏻" ws[168] = "السلام" rs[168] = "✾ ٲلـﮩـسـلا۾م ؏ـﮩـڵـيڪم 💙🖐🏻" ws[169] = "السلام عليكم" rs[169] = "✾ وَْ؏ـﮩـڵـيڪم ٲلـﮩـسـلا۾م 💙🖐🏻" ws[170] = "تسلم" rs[170] = "✾ ٱڵـڵـه يسـلـمـڪ 💙🖐🏻" ws[171] = "ممكن" rs[171] = "ﺗْـ•ـﮩ؏ْﮩـ•ــ🚶ـاْلْ اويـلـي 😋👙" ws[172] = "ماسكو" rs[172] = "ٲلمطور ماڵتي فديتهہ 😻💙 @IQ_ABS" ws[173] = "القناة" rs[173] = "قناة ديف بروكس خاصة بالتطوير وبرمجة البوتات وغبرها معرف القناة @DEV_PROX" ws[174] = "ديف بروكس" rs[174] = "احسن سورس في التليكرام ☻☂ القناة @DEV_PROX" -- the main function function run( msg, matches ) -- just a local variables that i used in my algorithm local i = 0; local w = false -- the main part that get the message that the user send and check if it equals to one of the words in the ws table :) -- this section loops through all the words table and assign { k } to the word index and { v } to the word itself for k,v in pairs(ws) do -- change the message text to uppercase and the { v } value that toke form the { ws } table and than compare it in a specific pattern if ( string.find(string.upper(msg.text), "^" .. string.upper(v) .. "$") ) then -- assign the { i } to the index of the reply and the { w } to true ( we will use it later ) i = k; w = true; end end -- check if { w } is not false and { i } not equals to 0 if ( (w ~= false) and (i ~= 0) ) then -- get the receiver :3 R = get_receiver(msg) -- send him the proper message from the index that { i } assigned to --send_large_msg ( R , rs[i] ); --send_reply(msg.id, rs[i]) reply_msg(msg.id, rs[i], ok_cb, false ) end -- don't edit this section if ( msg.text == "about" ) then if ( msg.from.username == "Mouamle" ) then R = get_receiver(msg) send_large_msg ( R , "Made by @Mouamle" ); end end end return { patterns = { "(.*)" }, run = run } end
gpl-2.0
Kthulupwns/darkstar
scripts/zones/Northern_San_dOria/npcs/Rondipur.lua
38
1049
----------------------------------- -- Area: Northern San d'Oria -- NPC: Rondipur -- Type: Quest Giver -- @zone: 231 -- @pos -154.415 10.999 153.744 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02d1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Apollyon/mobs/Proto-Omega.lua
12
3065
----------------------------------- -- Area: Apollyon Centrale -- NPC: Proto-Omega ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) --print("Proto-omega_engaged"); mob:setMod(MOD_SLASHRES,300); mob:setMod(MOD_PIERCERES,300); mob:setMod(MOD_IMPACTRES,300); mob:setMod(MOD_HTHRES,300); for n =1,table.getn (resistMod),1 do mob:setMod(resistMod[n],-50); end for n =1,table.getn (defenseMod),1 do mob:setMod(defenseMod[n],-50); end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local mobID = mob:getID(); local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100); if(lifepourcent > 70 or lifepourcent <30)then mob:AnimationSub(1); elseif(lifepourcent > 30 and lifepourcent < 70)then mob:AnimationSub(2); end if(lifepourcent > 30 and lifepourcent < 70 and mob:getLocalVar("form") == 8)then -- bipede mob:setMod(MOD_SLASHRES,1400); mob:setMod(MOD_PIERCERES,1400); mob:setMod(MOD_IMPACTRES,1400); mob:setMod(MOD_HTHRES,1400); for n =1,table.getn (resistMod),1 do mob:setMod(resistMod[n],100); end for n =1,table.getn (defenseMod),1 do mob:setMod(defenseMod[n],100); end SpawnMob(16933125):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());-- spawn gunpod mob:setLocalVar("form", 9) -- print("bipede"); elseif(lifepourcent < 30 and mob:getLocalVar("form") == 9 )then -- quadripede mob:setMod(MOD_SLASHRES,1450); mob:setMod(MOD_PIERCERES,1450); mob:setMod(MOD_IMPACTRES,1450); mob:setMod(MOD_HTHRES,1450); for n =1,table.getn (resistMod),1 do mob:setMod(resistMod[n],-50); end for n =1,table.getn (defenseMod),1 do mob:setMod(defenseMod[n],-50); end mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain, SpawnMob(16933125):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());-- spawn gunpod mob:setLocalVar("form", 8); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:addTitle(APOLLYON_RAVAGER); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); GetNPCByID(16932864+39):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+39):setStatus(STATUS_NORMAL); end;
gpl-3.0
amenophis1er/prosody-modules
mod_broadcast/mod_broadcast.lua
32
1043
local is_admin = require "core.usermanager".is_admin; local allowed_senders = module:get_option_set("broadcast_senders", {}); local from_address = module:get_option_string("broadcast_from"); local jid_bare = require "util.jid".bare; function send_to_online(message) local c = 0; for hostname, host_session in pairs(hosts) do if host_session.sessions then for username in pairs(host_session.sessions) do c = c + 1; message.attr.to = username.."@"..hostname; module:send(message); end end end return c; end function send_message(event) local stanza = event.stanza; local from = stanza.attr.from; if is_admin(from) or allowed_senders:contains(jid_bare(from)) then if from_address then stanza = st.clone(stanza); stanza.attr.from = from_address; end local c = send_to_online(stanza); module:log("debug", "Broadcast stanza from %s to %d online users", from, c); return true; else module:log("warn", "Broadcasting is not allowed for %s", from); end end module:hook("message/bare", send_message);
mit
GabrielNicolasAvellaneda/luvit-upstream
tests/test-fs-write-sync.lua
14
1192
--[[ Copyright 2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local FS = require('fs') local Path = require('path') local Buffer = require('buffer').Buffer test('fs.writeSync', function() local fn = Path.join(module.dir, 'write.txt') local foo = 'foo' local fd = FS.openSync(fn, 'w') local written = FS.writeSync(fd, -1, '') assert(written == 0) FS.writeSync(fd, -1, foo) local bar = 'bár' -- TODO: Support buffer argument written = FS.writeSync(fd, -1, Buffer:new(bar):toString()) assert(written > 3) FS.closeSync(fd) assert(FS.readFileSync(fn) == 'foobár') end) end)
apache-2.0
Kthulupwns/darkstar
scripts/zones/Mhaura/npcs/Dieh_Yamilsiah.lua
38
2198
----------------------------------- -- Area: Mhaura -- NPC: Dieh Yamilsiah -- Reports the time remaining before boat arrival. -- @pos 7.057 -2.364 2.489 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Each boat comes every 1152 seconds/8 game hours, 4 hour offset between Selbina and Aht Urghan -- Original timer: local timer = 1152 - ((os.time() - 1009810584)%1152); local timer = 1152 - ((os.time() - 1009810802)%1152); local destination = 0; -- Selbina, set to 1 for Al Zhabi local direction = 0; -- Arrive, 1 for depart local waiting = 216; -- Offset for Selbina -- Next ferry is Al Zhabi for higher values. if (timer >= 576) then destination = 1; timer = timer - 576; waiting = 193; end -- Logic to manipulate cutscene results. if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231,timer,direction,0,destination); -- timer arriving/departing ??? destination --[[Other cutscenes: 233 "This ship is headed for Selbina." 234 "The Selbina ferry will deparrrt soon! Passengers are to board the ship immediately!" Can't find a way to toggle the destination on 233 or 234, so they are not used. Users knowing which ferry is which > using all CSs.]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dpino/snabb
src/lib/protocol/header.lua
9
11831
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Protocol header base class -- -- This is an abstract class (should not be instantiated) -- -- Derived classes must implement the following class variables -- -- _name a string that describes the header type in a -- human readable form -- -- _ulp a table that holds information about the "upper -- layer protocols" supported by the header. It -- contains two keys -- method the name of the method of the header -- class whose result identifies the ULP -- and is used as key for the class_map -- table -- class_map a table whose keys must represent -- valid return values of the instance -- method given by the 'method' name -- above. The corresponding value must -- be the name of the header class that -- parses this particular ULP -- -- In the simplest case, a protocol header consists of a single data -- structure of a fixed size, e.g. an untagged Ethernet II header. -- Such headers are supported by this framework in a straight forward -- manner. More complex headers may have representations that differ -- in size and structure, depending on the use-case, e.g. GRE. -- Headers of that kind can be supported as long as all variants can -- be enumerated and represented by a separate fixed-sized data -- structure. This requirement is necessary because all data -- structures must be pre-allocated for performance reasons and to -- support the instance recycling mechanism of the class framework. -- Each header is described by a ctype object that serves as a -- template for the header. -- -- A protocol header can be created in two different manners. In the -- first case (provided by the new() constructor method), the protocol -- instance contains the header structure itself, where as in the -- second case (provided by the new_from_mem() constructor), the -- protocol instance contains a pointer to an arbitrary location in -- memory where the actual header resides (usually a packet buffer). -- The pointer is cast to the appropriate ctype to access the fields -- of the header. -- -- To support the second mode of creation for protocols with variable -- header structures, one of the headers must be designated as the -- "base header". It must be chosen such that it contains enough -- information to determine the actual header that is present in -- memory. -- -- The constructors in the header base class deal exclusively with the -- base header, i.e. the instances created by the new() and -- new_from_mem() methods only provide access to the fields present in -- the base header. Protocols that implement variable headers must -- extend the base methods to select the appropriate header variant. -- -- The header class uses the following data structures to support this -- mechanism. Each header variant is described by a table with the -- following elements -- -- t the ctype that represents the header itself -- ptr_t a ctype constructed by ffi.typeof("$*", ctype) used for -- casting of pointers -- box_t a ctype that represents a "box" to store a ptr_t, i.e. -- ffi.typeof("$[1]", ptr_t) -- -- These tables are stored as an array in the class variable _headers, -- where, by definition, the first element designates the base header. -- -- This array is initialized by the class method init(), which must be -- called by every derived class. -- -- When a new instance of a protocol class is created, it receives its -- own, private array of headers stored in the instance variable of -- the same name. The elements from the header tables stored in the -- class are inherited by the instance by means of setmetatable(). -- For each header, one instance of the header itself and one instance -- of a box are created from the t and box_t ctypes, respectively. -- These objects are stored in the keys "data" and "box" and are -- private to the instance. The following schematic should make the -- relationship clearer -- -- class._headers = { -- [1] = { t = ..., -- ptr_t = ..., -- box_t = ..., -- }, <---------------+ -- [2] = { t = ..., | -- ptr_t = ..., | -- box_t = ..., | -- }, <------------+ | -- ... | | -- } | | -- | | -- instance._headers = { | | -- [1] = { data = t(), | | -- box = box_t()| | -- }, ----------------+ metatable -- [2] = { data = t(), | -- box = box_t()| -- }, -------------+ metatable -- ... -- } -- -- The constructors of the base class store a reference to the base -- header (i.e. _headers[1]) in the instance variable _header. In -- other words, the box and data can be accessed by dereferencing -- _header.data and _header.box, respectively. -- -- This initialization is common to both constructors. The difference -- lies in the contents of the pointer stored in the box. The new() -- constructor stores a pointer to the data object, i.e. -- -- _header.box[0] = ffi.cast(_header.ptr_t, _header.data) -- -- where as the new_from_mem() constructor stores the pointer to the -- region of memory supplied as argument to the method call, i.e. -- -- _header.box[0] = ffi.cast(_header.ptr_t, mem) -- -- In that case, the _header.data object is not used at all. -- -- When a derived class overrides these constructors, it should first -- call the construcor of the super class, which will initialize the -- base header as described above. An extension of the new() method -- will replace the reference to the base header stored in _header by -- a reference to the header variant selected by the configuration -- passed as arguments to the method, i.e. it will eventually do -- -- _header = _headers[foo] -- -- where <foo> is the index of the selected header. -- -- An extension of the new_from_mem() constructor uses the base header -- to determine the actual header variant to use and override the base -- header with it. -- -- Refer to the lib.protocol.ethernet and lib.protocol.gre classes for -- examples. -- -- For convenience, the class variable class._header exists as well -- and contains a reference to the base header class._headers[1]. -- This promotes the instance methods sizeof() and ctype() to class -- methods, which will provide the size and ctype of a protocol's base -- header from the class itself. For example, the size of an ethernet -- header can be obtained by -- -- local ethernet = require("lib.protocol.ethernet") -- local ether_size = ethernet:sizeof() -- -- without creating an instance first. module(..., package.seeall) local ffi = require("ffi") local header = subClass(nil) -- Class methods -- Initialize a subclass with a set of headers, which must contain at -- least one element (the base header). function header:init (headers) assert(self and headers and #headers > 0) self._singleton_p = #headers == 1 local _headers = {} for i = 1, #headers do local header = {} local ctype = headers[i] header.t = ctype header.ptr_t = ffi.typeof("$*", ctype) header.box_t = ffi.typeof("$*[1]", ctype) header.meta = { __index = header } _headers[i] = header end self._headers = _headers self._header = _headers[1] end -- Initialize an instance of the class. If the instance is new (has -- not been recycled), an instance of each header struct and a box -- that holds a pointer to it are allocated. A reference to the base -- header is installed in the _header instance variable. local function _new (self) local o = header:superClass().new(self) if not o._recycled then -- Allocate boxes and headers for all variants of the -- classe's header structures o._headers = {} for i = 1, #self._headers do -- This code is only executed when a new instance is created -- via the class construcor, i.e. self is the class itself -- (as opposed to the case when an instance is recycled by -- calling the constructor as an instance method, in which -- case self would be the instance instead of the class). -- This is why it is safe to use self._headers[i].meta as -- metatable here. The effect is that the ctypes are -- inherited from the class while the data and box table are -- private to the instance. local _header = setmetatable({}, self._headers[i].meta) _header.data = _header.t() _header.box = _header.box_t() o._headers[i] = _header end end -- Make the base header the active header o._header = o._headers[1] return o end -- Initialize the base protocol header with 0 and store a pointer to -- it in the header box. function header:new () local o = _new(self) local header = o._header ffi.fill(header.data, ffi.sizeof(header.t)) header.box[0] = ffi.cast(header.ptr_t, header.data) return o end -- This alternative constructor creates a protocol header from a chunk -- of memory by "overlaying" a header structure. In this mode, the -- protocol ctype _header.data is unused and _header.box stores the -- pointer to the memory location supplied by the caller. function header:new_from_mem (mem, size) local o = _new(self) local header = o._header if ffi.sizeof(header.t) > size then o:free() return nil end header.box[0] = ffi.cast(header.ptr_t, mem) return o end -- Instance methods -- Return a reference to the header function header:header () return self._header.box[0][0] end -- Return a pointer to the header function header:header_ptr () return self._header.box[0] end -- Return the ctype of header function header:ctype () return self._header.t end -- Return the size of the header function header:sizeof () return ffi.sizeof(self._header.t) end -- Return true if <other> is of the same type and contains identical -- data, false otherwise. function header:eq (other) local ctype = self:ctype() local size = self:sizeof() local other_ctype = other:ctype() return (ctype == other_ctype and ffi.string(self:header_ptr(), size) == ffi.string(other:header_ptr(), size)) end -- Copy the header to some location in memory (usually a packet -- buffer). The caller must make sure that there is enough space at -- the destination. If relocate is a true value, the copy is promoted -- to be the active storage of the header. function header:copy (dst, relocate) ffi.copy(dst, self:header_ptr(), self:sizeof()) if relocate then self._header.box[0] = ffi.cast(self._header.ptr_t, dst) end end -- Create a new protocol instance that is a copy of this instance. -- This is horribly inefficient and should not be used in the fast -- path. function header:clone () local header = self:ctype()() local sizeof = ffi.sizeof(header) ffi.copy(header, self:header_ptr(), sizeof) return self:class():new_from_mem(header, sizeof) end -- Return the class that can handle the upper layer protocol or nil if -- the protocol is not supported or the protocol has no upper-layer. function header:upper_layer () local method = self._ulp.method if not method then return nil end local class = self._ulp.class_map[self[method](self)] if class then if package.loaded[class] then return package.loaded[class] else return require(class) end else return nil end end return header
apache-2.0
Kthulupwns/darkstar
scripts/globals/items/love_chocolate.lua
35
1149
----------------------------------------- -- ID: 5230 -- Item: love_chocolate -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic Regen While Healing 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5230); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Bastok_Mines/npcs/Maymunah.lua
19
1152
----------------------------------- -- Area: Bastok Mines -- NPC: Maymunah -- Guild Merchant NPC: Alchemy Guild -- @pos 108.738 5.017 -3.129 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:sendGuild(5262,8,23,6)) then player:showText(npc, MAYMUNAH_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Kthulupwns/darkstar
scripts/globals/weaponskills/herculean_slash.lua
12
1575
----------------------------------- -- Herculean Slash -- Great Sword weapon skill -- Skill Level: 290 -- Paralyzes target. Duration of effect varies with TP. -- Aligned with the Snow Gorget, Thunder Gorget & Breeze Gorget. -- Aligned with the Snow Belt, Thunder Belt & Breeze Belt. -- Element: Ice -- Modifiers: VIT:60% -- As this is a magic-based weaponskill it is also modified by Magic Attack Bonus. -- 100%TP 200%TP 300%TP -- 3.50 3.50 3.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_ICE; params.skill = SKILL_GSD; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.vit_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 60) if(target:hasStatusEffect(EFFECT_PARALYSIS) == false) then target:addStatusEffect(EFFECT_PARALYSIS, 30, 0, duration); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Mleaf/mleaf_luci
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdiface.lua
49
6797
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd") if not arg[1] or m.uci:get("olsrd", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to 192.168.0.1 by half: 192.168.0.1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv4(host) or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv4 or IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip4b = i:taboption("addrs", Value, "Ip4Broadcast", translate("IPv4 broadcast"), translate("IPv4 broadcast address for outgoing OLSR packets. One useful example would be 255.255.255.255. ".. "Default is \"0.0.0.0\", which triggers the usage of the interface broadcast IP.")) ip4b.optional = true ip4b.datatype = "ip4addr" ip4b.placeholder = "0.0.0.0" ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip4s = i:taboption("addrs", Value, "IPv4Src", translate("IPv4 source"), translate("IPv4 src address for outgoing OLSR packages. Default is \"0.0.0.0\", which triggers usage of the interface IP.")) ip4s.optional = true ip4s.datatype = "ip4addr" ip4s.placeholder = "0.0.0.0" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
apache-2.0
dpino/snabb
src/apps/wall/l7fw.lua
9
12868
module(..., package.seeall) -- This module implements a level 7 firewall app that consumes the result -- of DPI scanning done by l7spy. -- -- The firewall rules are a table mapping protocol names to either -- * a simple action ("drop", "reject", "accept") -- * a pfmatch expression local bit = require("bit") local ffi = require("ffi") local link = require("core.link") local packet = require("core.packet") local datagram = require("lib.protocol.datagram") local ether = require("lib.protocol.ethernet") local icmp = require("lib.protocol.icmp.header") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local tcp = require("lib.protocol.tcp") local match = require("pf.match") ffi.cdef[[ void syslog(int priority, const char*format, ...); ]] -- constants from <syslog.h> for syslog priority argument local LOG_USER = 8 local LOG_INFO = 6 -- network constants local ETHER_PROTO_IPV4 = 0x0800 local ETHER_PROTO_IPV6 = 0x86dd local IP_PROTO_ICMPV4 = 1 local IP_PROTO_TCP = 6 local IP_PROTO_ICMPV6 = 58 L7Fw = {} L7Fw.__index = L7Fw -- create a new firewall app object given an instance of Scanner -- and firewall rules function L7Fw:new(config) local obj = { local_ipv4 = config.local_ipv4, local_ipv6 = config.local_ipv6, local_macaddr = config.local_macaddr, scanner = config.scanner, rules = config.rules, -- this map tracks flows to compiled pfmatch functions -- so that we only compile them once per flow handler_map = {}, -- log level for logging filtered packets logging = config.logging or "off", -- for stats accepted = 0, rejected = 0, dropped = 0, total = 0 } assert(obj.logging == "on" or obj.logging == "off", ("invalid log level: %s"):format(obj.logging)) return setmetatable(obj, self) end -- called by pfmatch handlers, just drop the packet on the floor function L7Fw:drop(pkt, len) if self.logging == "on" then self:log_packet("DROP") end packet.free(self.current_packet) self.dropped = self.dropped + 1 end -- called by pfmatch handler, handle rejection response function L7Fw:reject(pkt, len) link.transmit(self.output.reject, self:make_reject_response()) self.rejected = self.rejected + 1 if self.logging == "on" then self:log_packet("REJECT") end packet.free(self.current_packet) end -- called by pfmatch handler, forward packet function L7Fw:accept(pkt, len) link.transmit(self.output.output, self.current_packet) self.accepted = self.accepted + 1 end function L7Fw:push() local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") local rules = self.rules local scanner = self.scanner assert(self.output.reject, "output port for reject policy not found") while not link.empty(i) do local pkt = link.receive(i) local flow = scanner:get_flow(pkt) -- so that pfmatch handler methods can access the original packet self.current_packet = pkt self.total = self.total + 1 if flow then local name = scanner:protocol_name(flow.protocol) local policy = rules[name] or rules["default"] self.current_protocol = name if policy == "accept" then self:accept(pkt.data, pkt.length) elseif policy == "drop" then self:drop(pkt.data, pkt.length) elseif policy == "reject" then self:reject(pkt.data, pkt.length) -- handle a pfmatch string case elseif type(policy) == "string" then if self.handler_map[policy] then -- we've already compiled a matcher for this policy self.handler_map[policy](self, pkt.data, pkt.length, flow.packets) else local opts = { extra_args = { "flow_count" } } local handler = match.compile(policy, opts) self.handler_map[policy] = handler handler(self, pkt.data, pkt.length, flow.packets) end -- TODO: what should the default policy be if there is none specified? else self:accept(pkt.data, pkt.length) end else -- TODO: we may wish to have a default policy for packets -- without detected flows instead of just forwarding self:accept(pkt.data, pkt.length) end end end function L7Fw:report() local accepted, rejected, dropped = self.accepted, self.rejected, self.dropped local total = self.total local a_pct = math.ceil((accepted / total) * 100) local r_pct = math.ceil((rejected / total) * 100) local d_pct = math.ceil((dropped / total) * 100) print(("Accepted packets: %d (%d%%)"):format(accepted, a_pct)) print(("Rejected packets: %d (%d%%)"):format(rejected, r_pct)) print(("Dropped packets: %d (%d%%)"):format(dropped, d_pct)) end local logging_priority = bit.bor(LOG_USER, LOG_INFO) function L7Fw:log_packet(type) local pkt = self.current_packet local protocol = self.current_protocol local eth_h = assert(ether:new_from_mem(pkt.data, pkt.length)) local ip_h if eth_h:type() == ETHER_PROTO_IPV4 then ip_h = ipv4:new_from_mem(pkt.data + eth_h:sizeof(), pkt.length - eth_h:sizeof()) elseif eth_h:type() == ETHER_PROTO_IPV6 then ip_h = ipv6:new_from_mem(pkt.data + eth_h:sizeof(), pkt.length - eth_h:sizeof()) end assert(ip_h) local msg = string.format("[Snabbwall %s] PROTOCOL=%s MAC=%s SRC=%s DST=%s", type, protocol, ether:ntop(eth_h:src()), ip_h:ntop(ip_h:src()), ip_h:ntop(ip_h:dst())) ffi.C.syslog(logging_priority, msg) end -- create either an ICMP port unreachable packet or a TCP RST to -- send in case of a reject policy function L7Fw:make_reject_response() local pkt = self.current_packet local ether_orig = assert(ether:new_from_mem(pkt.data, pkt.length)) local ip_orig if ether_orig:type() == ETHER_PROTO_IPV4 then ip_orig = ipv4:new_from_mem(pkt.data + ether_orig:sizeof(), pkt.length - ether_orig:sizeof()) elseif ether_orig:type() == ETHER_PROTO_IPV6 then ip_orig = ipv6:new_from_mem(pkt.data + ether_orig:sizeof(), pkt.length - ether_orig:sizeof()) else -- no responses to non-IP packes return end assert(ip_orig) local is_tcp = false local ip_protocol if ip_orig:version() == 4 then if ip_orig:protocol() == 6 then is_tcp = true ip_protocol = IP_PROTO_TCP else ip_protocol = IP_PROTO_ICMPV4 end else if ip_orig:next_header() == 6 then is_tcp = true ip_protocol = IP_PROTO_TCP else ip_protocol = IP_PROTO_ICMPV6 end end local dgram = datagram:new() local ether_h, ip_h if ip_orig:version() == 4 then ether_h = ether:new({ dst = ether_orig:src(), src = self.local_macaddr, type = ETHER_PROTO_IPV4 }) assert(self.local_ipv4, "config is missing local_ipv4") ip_h = ipv4:new({ dst = ip_orig:src(), src = ipv4:pton(self.local_ipv4), protocol = ip_protocol, ttl = 64 }) else ether_h = ether:new({ dst = ether_orig:src(), src = self.local_macaddr, type = ETHER_PROTO_IPV6 }) assert(self.local_ipv6, "config is missing local_ipv6") ip_h = ipv6:new({ dst = ip_orig:src(), src = ipv6:pton(self.local_ipv6), next_header = ip_protocol, ttl = 64 }) end if is_tcp then local tcp_orig = tcp:new_from_mem(pkt.data + ether_orig:sizeof() + ip_orig:sizeof(), pkt.length - ether_orig:sizeof() - ip_orig:sizeof()) assert(tcp_orig) local tcp_h = tcp:new({src_port = tcp_orig:dst_port(), dst_port = tcp_orig:src_port(), seq_num = tcp_orig:seq_num() + 1, ack_num = tcp_orig:ack_num() + 1, ack = 1, rst = 1, -- minimum TCP header size is 5 words offset = 5 }) -- checksum needs a non-nil first argument, but we have zero payload bytes -- so give a bogus value tcp_h:checksum(ffi.new("uint8_t[0]"), 0) dgram:push(tcp_h) if ip_h:version() == 4 then ip_h:total_length(ip_h:sizeof() + tcp_h:sizeof()) else ip_h:payload_length(ip_h:sizeof() + tcp_h:sizeof()) end else local icmp_h if ip_h:version() == 4 then -- ICMPv4 code & type for "port unreachable" icmp_h = icmp:new(3, 3) else -- ICMPv6 code & type for "administratively prohibited" icmp_h = icmp:new(1, 1) end dgram:payload(ffi.new("uint8_t [4]"), 4) if ip_h:version() == 4 then dgram:payload(ip_orig:header(), ip_orig:sizeof()) -- ICMPv4 port unreachable errors come with the original IPv4 -- header and 8 bytes of the original payload dgram:payload(pkt.data + ether_orig:sizeof() + ip_orig:sizeof(), 8) icmp_h:checksum(dgram:payload()) dgram:push(icmp_h) ip_h:total_length(ip_h:sizeof() + icmp_h:sizeof() + 4 + -- extra zero bytes ip_orig:sizeof() + 8) else -- ICMPv6 destination unreachable packets contain up to 1232 bytes -- of the original packet -- (the minimum MTU 1280 - IPv6 header length - ICMPv6 header) local payload_len = math.min(1232, pkt.length - ether_orig:sizeof() - ip_orig:sizeof()) dgram:payload(ip_orig:header(), ip_orig:sizeof()) dgram:payload(pkt.data + ether_orig:sizeof() + ip_orig:sizeof(), payload_len) local mem, len = dgram:payload() icmp_h:checksum(mem, len, ip_h) dgram:push(icmp_h) ip_h:payload_length(icmp_h:sizeof() + 4 + -- extra zero bytes ip_orig:sizeof() + payload_len) end end dgram:push(ip_h) dgram:push(ether_h) return dgram:packet() end function selftest() local savefile = require("pf.savefile") local pflua = require("pf") local function test(name, packet, pflang) local fake_self = { local_ipv4 = "192.168.42.42", local_ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334", local_macaddr = "01:23:45:67:89:ab", current_packet = { data = packet.packet, length = packet.len } } local response = L7Fw.make_reject_response(fake_self) local pred = pf.compile_filter(pflang) assert(pred(response.data, response.length), string.format("test %s failed", name)) end local base_dir = "./program/wall/tests/data/" local dhcp = savefile.load_packets(base_dir .. "dhcp.pcap") local dhcpv6 = savefile.load_packets(base_dir .. "dhcpv6.pcap") local v4http = savefile.load_packets(base_dir .. "http.cap") local v6http = savefile.load_packets(base_dir .. "v6-http.cap") test("icmpv4-1", dhcp[2], [[ether proto ip]]) test("icmpv4-2", dhcp[2], [[ip proto icmp]]) test("icmpv4-3", dhcp[2], [[icmp and dst net 192.168.0.1]]) test("icmpv4-3", dhcp[2], [[icmp[icmptype] = 3 and icmp[icmpcode] = 3]]) test("icmpv6-1", dhcpv6[1], [[ether proto ip6]]) -- TODO: ip6 protochain is not implemented in pflang --test("icmpv6-2", dhcpv6[1], [[ip6 protochain 58]]) -- it would be nice to test the icmp type & code here, but pflang -- does not have good support for dereferencing ip6 protocols test("icmpv6-3", dhcpv6[1], [[icmp6 and dst net fe80::a00:27ff:fefe:8f95]]) test("tcpv4-1", v4http[5], [[ether proto ip]]) test("tcpv4-2", v4http[5], [[tcp and tcp[tcpflags] & (tcp-rst|tcp-ack) != 0]]) test("tcpv6-1", v6http[50], [[ether proto ip6]]) test("tcpv6-2", v6http[50], [[tcp]]) print("selftest ok") end
apache-2.0

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card