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
DarkstarProject/darkstar
scripts/globals/abilities/scholars_roll.lua
12
2513
----------------------------------- -- Ability: Scholar's Roll -- Enhances Conserve MP effect for party members within area of effect -- Optimal Job: Scholar -- Lucky Number: 2 -- Unlucky Number: 6 -- Level: 64 -- Phantom Roll +1 Value: 1 -- -- Data unknown ----------------------------------- require("scripts/globals/settings") require("scripts/globals/ability") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = dsp.effect.SCHOLARS_ROLL ability:setRange(ability:getRange() + player:getMod(dsp.mod.ROLL_RANGE)) if (player:hasStatusEffect(effectID)) then return dsp.msg.basic.ROLL_ALREADY_ACTIVE,0 elseif atMaxCorsairBusts(player) then return dsp.msg.basic.CANNOT_PERFORM,0 else return 0,0 end end function onUseAbility(caster,target,ability,action) if (caster:getID() == target:getID()) then corsairSetup(caster, ability, action, dsp.effect.SCHOLARS_ROLL, dsp.job.SCH) end local total = caster:getLocalVar("corsairRollTotal") return applyRoll(caster,target,ability,action,total) end function applyRoll(caster,target,ability,action,total) local duration = 300 + caster:getMerit(dsp.merit.WINNING_STREAK) + caster:getMod(dsp.mod.PHANTOM_DURATION) local effectpowers = {2, 9, 3, 4, 5, 2, 6, 6, 7, 9, 14, 4} --mostly random guesses local effectpower = effectpowers[total] if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then effectpower = effectpower + 4 end -- Apply Additional Phantom Roll+ Buff local phantomBase = 1 -- Base increment buff local effectpower = effectpower + (phantomBase * phantombuffMultiple(caster)) -- Check if COR Main or Sub if (caster:getMainJob() == dsp.job.COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()) elseif (caster:getSubJob() == dsp.job.COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()) end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(dsp.merit.BUST_DURATION), dsp.effect.SCHOLARS_ROLL, effectpower, 0, duration, caster:getID(), total, dsp.mod.CONSERVE_MP) == false) then ability:setMsg(dsp.msg.basic.ROLL_MAIN_FAIL) elseif total > 11 then ability:setMsg(dsp.msg.basic.DOUBLEUP_BUST) end return total end
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Tavnazian_Safehold/npcs/_0q1.lua
9
1437
----------------------------------- -- Area: Tavnazian Safehold -- NPC: _0q1 (Sewer Entrance) -- !pos 28 -12 44 26 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_LOST_CITY and player:getCharVar("PromathiaStatus") > 0) then player:startEvent(103); elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.CHAINS_AND_BONDS and player:getCharVar("PromathiaStatus") == 3) then player:startEvent(116); elseif (player:getCurrentMission(COP) >= dsp.mission.id.cop.DISTANT_BELIEFS or player:hasCompletedMission(COP,dsp.mission.id.cop.THE_LAST_VERSE)) then player:startEvent(502); else -- player:messageSpecial(); end return 1; end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 103) then player:setCharVar("PromathiaStatus",0); player:completeMission(COP,dsp.mission.id.cop.THE_LOST_CITY); player:addMission(COP,dsp.mission.id.cop.DISTANT_BELIEFS); elseif (csid == 116) then player:setCharVar("PromathiaStatus",4); elseif (csid == 502 and option == 1) then player:setPos(260.068,0,-283.568,190,27); -- To Phomiuna Aqueducts {R} end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Buburimu_Peninsula/Zone.lua
15
4493
----------------------------------- -- -- Zone: Buburimu_Peninsula (118) -- ----------------------------------- package.loaded[ "scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/zone"); require("scripts/globals/conquest"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 847, 45, DIGREQ_NONE }, { 887, 1, DIGREQ_NONE }, { 893, 53, DIGREQ_NONE }, { 17395, 98, DIGREQ_NONE }, { 738, 3, DIGREQ_NONE }, { 888, 195, DIGREQ_NONE }, { 4484, 47, DIGREQ_NONE }, { 17397, 66, DIGREQ_NONE }, { 641, 134, DIGREQ_NONE }, { 885, 12, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 845, 125, DIGREQ_BURROW }, { 843, 1, DIGREQ_BURROW }, { 844, 64, DIGREQ_BURROW }, { 1845, 34, DIGREQ_BURROW }, { 838, 7, DIGREQ_BURROW }, { 880, 34, DIGREQ_BORE }, { 902, 5, DIGREQ_BORE }, { 886, 3, DIGREQ_BORE }, { 867, 3, DIGREQ_BORE }, { 864, 21, DIGREQ_BORE }, { 1587, 19, DIGREQ_BORE }, { 1586, 9, DIGREQ_BORE }, { 866, 2, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17261199,17261200}; SetFieldManual(manuals); SetRegionalConquestOverseers(zone:getRegionID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -276.529, 16.403, -324.519, 14); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0003; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0005; -- zone 4 buburimu no update (north) end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0003) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0005) then if (player:getPreviousZone() == 213 or player:getPreviousZone() == 249) then player:updateEvent(0,0,0,0,0,7); elseif (player:getPreviousZone() == 198) then player:updateEvent(0,0,0,0,0,6); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0003) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Hall_of_Transference/npcs/_0e1.lua
32
1340
----------------------------------- -- Area: Hall of Transference -- NPC: Cermet Gate - Dem -- @pos -220 -46 -279 14 ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) > BELOW_THE_ARKS) then player:startEvent(0x0096); else player:messageSpecial(NO_RESPONSE_OFFSET+1); -- The door is firmly shut. 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 == 0x0096 and option == 1) then player:setPos(185.891, 0, -52.331, 128, 18); -- To Promyvion Dem {R} end end;
gpl-3.0
oTibia/UnderLight-AK47
data/actions/scripts/liquids/strong_mana.lua
2
1328
local MIN = 110 local MAX = 190 local EMPTY_POTION = 7634 local combat = createCombatObject() setCombatParam(combat, COMBAT_PARAM_TYPE, COMBAT_MANADRAIN) setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) setCombatParam(combat, COMBAT_PARAM_TARGETCASTERORTOPMOST, true) setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, false) setCombatFormula(combat, COMBAT_FORMULA_DAMAGE, MIN, 0, MAX, 0) local exhaust = createConditionObject(CONDITION_EXHAUST_POTION) setConditionParam(exhaust, CONDITION_PARAM_TICKS, getConfigInfo('minactionexinterval')) function onUse(cid, item, frompos, item2, topos) if(isPlayer(item2.uid) == false) then return false end if not(isSorcerer(cid) or isDruid(cid) or isPaladin(cid)) or (getPlayerLevel(cid) < 50) and not(getPlayerAccess(cid) > 0) then doCreatureSay(cid, "Only sorcerers, druids and paladins of level 50 or above may drink this fluid.", TALKTYPE_ORANGE_1) return true end if(hasCondition(cid, CONDITION_EXHAUST_POTION) ) then doPlayerSendDefaultCancel(cid, RETURNVALUE_YOUAREEXHAUSTED) return true end if not doCombat(cid, combat, numberToVariant(item2.uid)) then return false end doAddCondition(cid, exhaust) doCreatureSay(item2.uid, "Aaaah...", TALKTYPE_ORANGE_1) doRemoveItem(item.uid, 1) doPlayerAddItem(cid, EMPTY_POTION, 1) return true end
gpl-2.0
gdewald/Sputter
dev/premake/premake/src/base/help.lua
26
1220
-- -- help.lua -- User help, displayed on /help option. -- Copyright (c) 2002-2008 Jason Perkins and the Premake project -- function premake.showhelp() -- display the basic usage printf("Premake %s, a build script generator", _PREMAKE_VERSION) printf(_PREMAKE_COPYRIGHT) printf("%s %s", _VERSION, _COPYRIGHT) printf("") printf("Usage: premake4 [options] action [arguments]") printf("") -- display all options printf("OPTIONS") printf("") for option in premake.option.each() do local trigger = option.trigger local description = option.description if (option.value) then trigger = trigger .. "=" .. option.value end if (option.allowed) then description = description .. "; one of:" end printf(" --%-15s %s", trigger, description) if (option.allowed) then for _, value in ipairs(option.allowed) do printf(" %-14s %s", value[1], value[2]) end end printf("") end -- display all actions printf("ACTIONS") printf("") for action in premake.action.each() do printf(" %-17s %s", action.trigger, action.description) end printf("") -- see more printf("For additional information, see http://industriousone.com/premake") end
mit
DarkstarProject/darkstar
scripts/zones/East_Ronfaure_[S]/Zone.lua
11
1245
----------------------------------- -- -- Zone: East_Ronfaure_[S] (81) -- ----------------------------------- local ID = require("scripts/zones/East_Ronfaure_[S]/IDs") require("scripts/globals/missions") require("scripts/globals/helm") require("scripts/globals/zone") ----------------------------------- function onInitialize(zone) UpdateNMSpawnPoint(ID.mob.MYRADROSH) GetMobByID(ID.mob.MYRADROSH):setRespawnTime(math.random(5400, 7200)) dsp.helm.initZone(zone, dsp.helm.type.LOGGING) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(86.131,-65.817,273.861,25); end if (prevZone == dsp.zone.SOUTHERN_SAN_DORIA_S) then if (player:getCurrentMission(WOTG) == dsp.mission.id.wotg.WHILE_THE_CAT_IS_AWAY) then cs = 7; end end return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 7) then player:completeMission(WOTG, dsp.mission.id.wotg.WHILE_THE_CAT_IS_AWAY); player:addMission(WOTG, dsp.mission.id.wotg.A_TIMESWEPT_BUTTERFLY); end end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Norg/npcs/Ryoma.lua
9
4100
----------------------------------- -- Area: Norg -- NPC: Ryoma -- Start and Finish Quest: 20 in Pirate Years, I'll Take the Big Box, True Will, Bugi Soden -- Involved in Quest: Ayame and Kaede -- !pos -23 0 -9 252 ----------------------------------- local ID = require("scripts/zones/Norg/IDs") require("scripts/globals/keyitems") require("scripts/globals/settings") require("scripts/globals/wsquest") require("scripts/globals/quests") require("scripts/globals/status") require("scripts/globals/shop") ----------------------------------- local wsQuest = dsp.wsquest.blade_ku function onTrade(player,npc,trade) local wsQuestEvent = dsp.wsquest.getTradeEvent(wsQuest,player,trade) if (wsQuestEvent ~= nil) then player:startEvent(wsQuestEvent) end end function onTrigger(player,npc) local wsQuestEvent = dsp.wsquest.getTriggerEvent(wsQuest,player) local twentyInPirateYears = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TWENTY_IN_PIRATE_YEARS) local illTakeTheBigBox = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.I_LL_TAKE_THE_BIG_BOX) local trueWill = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRUE_WILL) local mLvl = player:getMainLvl() local mJob = player:getMainJob() if (wsQuestEvent ~= nil) then player:startEvent(wsQuestEvent) elseif (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.AYAME_AND_KAEDE) == QUEST_ACCEPTED) then if (player:getCharVar("AyameAndKaede_Event") == 3) then player:startEvent(95) -- During Quest "Ayame and Kaede" else player:startEvent(94) end elseif (twentyInPirateYears == QUEST_AVAILABLE and mJob == dsp.job.NIN and mLvl >= 40) then player:startEvent(133) -- Start Quest "20 in Pirate Years" elseif (twentyInPirateYears == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TRICK_BOX)) then player:startEvent(134) -- Finish Quest "20 in Pirate Years" elseif (twentyInPirateYears == QUEST_COMPLETED and illTakeTheBigBox == QUEST_AVAILABLE and mJob == dsp.job.NIN and mLvl >= 50 and player:needToZone() == false) then player:startEvent(135) -- Start Quest "I'll Take the Big Box" elseif (illTakeTheBigBox == QUEST_COMPLETED and trueWill == QUEST_AVAILABLE) then player:startEvent(136) -- Start Quest "True Will" elseif (player:hasKeyItem(dsp.ki.OLD_TRICK_BOX) and player:getCharVar("trueWillCS") == 0) then player:startEvent(137) elseif (player:getCharVar("trueWillCS") == 1) then player:startEvent(138) else player:startEvent(94) end end function onEventFinish(player,csid,option) if (csid == 95) then player:addKeyItem(dsp.ki.SEALED_DAGGER) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.SEALED_DAGGER) player:delKeyItem(dsp.ki.STRANGELY_SHAPED_CORAL) player:setCharVar("AyameAndKaede_Event", 4) elseif (csid == 133) then player:addQuest(OUTLANDS,dsp.quest.id.outlands.TWENTY_IN_PIRATE_YEARS) player:setCharVar("twentyInPirateYearsCS",1) elseif (csid == 134) then if (player:getFreeSlotsCount() <= 1) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,17771) else player:delKeyItem(dsp.ki.TRICK_BOX) player:addItem(17771) player:addItem(17772) player:messageSpecial(ID.text.ITEM_OBTAINED, 17771) -- Anju player:messageSpecial(ID.text.ITEM_OBTAINED, 17772) -- Zushio player:needToZone() player:setCharVar("twentyInPirateYearsCS",0) player:addFame(NORG,30) player:completeQuest(OUTLANDS,dsp.quest.id.outlands.TWENTY_IN_PIRATE_YEARS) end elseif (csid == 135) then player:addQuest(OUTLANDS,dsp.quest.id.outlands.I_LL_TAKE_THE_BIG_BOX) elseif (csid == 136) then player:addQuest(OUTLANDS,dsp.quest.id.outlands.TRUE_WILL) elseif (csid == 137) then player:setCharVar("trueWillCS",1) else dsp.wsquest.handleEventFinish(wsQuest,player,csid,option,ID.text.BLADE_KU_LEARNED) end end
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/b.e.w._pitaru.lua
11
1039
----------------------------------------- -- ID: 5892 -- Item: b.e.w._pitaru -- Food Effect: 30 Min, All Races ----------------------------------------- -- MP +9% (cap 130) -- Increases rate of magic skill gains by 80% ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5892) end function onEffectGain(target, effect) target:addMod(dsp.mod.FOOD_MPP, 9) target:addMod(dsp.mod.FOOD_MP_CAP, 130) target:addMod(dsp.mod.MAGIC_SKILLUP_RATE, 80) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_MPP, 9) target:delMod(dsp.mod.FOOD_MP_CAP, 130) target:delMod(dsp.mod.MAGIC_SKILLUP_RATE, 80) end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Chateau_dOraguille/npcs/_6h1.lua
13
2327
----------------------------------- -- Area: Chateau d'Oraguille -- Door: Prince Regent's Rm -- Starts and Finishes Quest: Prelude of Black and White (Start), Pieuje's Decision (Start) -- @pos -37 -3 31 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) messengerFromBeyond = player:getQuestStatus(SANDORIA,MESSENGER_FROM_BEYOND); preludeOfBandW = player:getQuestStatus(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE); pieujesDecision = player:getQuestStatus(SANDORIA,PIEUJE_S_DECISION); if (player:getMainJob() == 3 and player:getMainLvl() >= AF2_QUEST_LEVEL) then if (messengerFromBeyond == QUEST_COMPLETED and preludeOfBandW == QUEST_AVAILABLE) then player:startEvent(0x0227); -- Start Quest "Prelude of Black and White" elseif (preludeOfBandW == QUEST_COMPLETED and pieujesDecision == QUEST_AVAILABLE) then player:startEvent(0x0228); -- Start Quest "Pieuje's Decision" end elseif (player:hasCompletedMission(SANDORIA,LIGHTBRINGER) and player:getRank() == 9 and player:getVar("Cutscenes_8-2") == 1) then player:startEvent(0x004A); else player:startEvent(0x020b); end return 1; 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 == 0x0227) then player:addQuest(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE); elseif (csid == 0x0228) then player:addQuest(SANDORIA,PIEUJE_S_DECISION); elseif (csid == 0x004A) then player:setVar("Cutscenes_8-2",2); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/items/woozyshroom.lua
18
1170
----------------------------------------- -- ID: 4373 -- Item: woozyshroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -4 -- Mind 2 ----------------------------------------- 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,4373); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -4); target:addMod(MOD_MND, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -4); target:delMod(MOD_MND, 2); end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/plate_of_tuna_sushi.lua
11
1452
----------------------------------------- -- ID: 5150 -- Item: plate_of_tuna_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 15 (cap 72) -- Ranged ACC % 15 (cap 72) -- Sleep Resist 1 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5150) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 20) target:addMod(dsp.mod.DEX, 3) target:addMod(dsp.mod.CHR, 5) target:addMod(dsp.mod.FOOD_ACCP, 15) target:addMod(dsp.mod.FOOD_ACC_CAP, 72) target:addMod(dsp.mod.FOOD_RACCP, 15) target:addMod(dsp.mod.FOOD_RACC_CAP, 72) target:addMod(dsp.mod.SLEEPRES, 1) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 20) target:delMod(dsp.mod.DEX, 3) target:delMod(dsp.mod.CHR, 5) target:delMod(dsp.mod.FOOD_ACCP, 15) target:delMod(dsp.mod.FOOD_ACC_CAP, 72) target:delMod(dsp.mod.FOOD_RACCP, 15) target:delMod(dsp.mod.FOOD_RACC_CAP, 72) target:delMod(dsp.mod.SLEEPRES, 1) end
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Temenos/mobs/Proto-Ultima.lua
9
1458
----------------------------------- -- Area: Temenos -- Mob: Proto-Ultima ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/limbus"); ----------------------------------- function onMobSpawn(mob) mob:SetMagicCastingEnabled(false); end; function onMobFight(mob,target) local phase = mob:getLocalVar("battlePhase"); if (mob:actionQueueEmpty() == true) then if (mob:getHPP() < (80 - (phase * 20))) then mob:useMobAbility(1524); -- use Dissipation on phase change phase = phase + 1; if (phase == 2) then -- enable Holy II mob:SetMagicCastingEnabled(true); end if (phase == 4) then -- add Regain in final phase if (mob:hasStatusEffect(dsp.effect.REGAIN) == false) then mob:addStatusEffect(dsp.effect.REGAIN,7,3,0); mob:getStatusEffect(dsp.effect.REGAIN):setFlag(dsp.effectFlag.DEATH); end end mob:setLocalVar("battlePhase", phase); -- incrementing the phase here instead of in the Dissipation skill because stunning it prevents use. end end end; function onMobDeath(mob, player, isKiller) player:addTitle(dsp.title.TEMENOS_LIBERATOR); GetNPCByID(16928768+79):setPos(-559,5,-357); GetNPCByID(16928768+79):setStatus(dsp.status.NORMAL); GetNPCByID(16928768+474):setStatus(dsp.status.NORMAL); end;
gpl-3.0
ungarscool1/HL2RP
hl2rp/gamemode/modules/fadmin/fadmin/playeractions/voicemute/cl_init.lua
4
2589
hook.Add("PlayerBindPress", "FAdmin_voicemuted", function(ply, bind, pressed) if ply:FAdmin_GetGlobal("FAdmin_voicemuted") and string.find(string.lower(bind), "voicerecord") then return true end -- The voice muting is not done clientside, this is just so people know they can't talk end) FAdmin.StartHooks["Voicemute"] = function() FAdmin.Access.AddPrivilege("Voicemute", 2) FAdmin.Commands.AddCommand("Voicemute", nil, "<Player>") FAdmin.Commands.AddCommand("UnVoicemute", nil, "<Player>") FAdmin.ScoreBoard.Player:AddActionButton(function(ply) if ply:FAdmin_GetGlobal("FAdmin_voicemuted") then return "Unmute voice globally" end return "Mute voice globally" end, function(ply) if ply:FAdmin_GetGlobal("FAdmin_voicemuted") then return "fadmin/icons/voicemute" end return "fadmin/icons/voicemute", "fadmin/icons/disable" end, Color(255, 130, 0, 255), function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Voicemute", ply) end, function(ply, button) if not ply:FAdmin_GetGlobal("FAdmin_voicemuted") then FAdmin.PlayerActions.addTimeMenu(function(secs) RunConsoleCommand("_FAdmin", "Voicemute", ply:UserID(), secs) button:SetImage2("null") button:SetText("Unmute voice globally") button:GetParent():InvalidateLayout() end) else RunConsoleCommand("_FAdmin", "UnVoicemute", ply:UserID()) end button:SetImage2("fadmin/icons/disable") button:SetText("Mute voice globally") button:GetParent():InvalidateLayout() end) FAdmin.ScoreBoard.Player:AddActionButton(function(ply) return ply.FAdminMuted and "Unmute voice" or "Mute voice" end, function(ply) if ply.FAdminMuted then return "fadmin/icons/voicemute" end return "fadmin/icons/voicemute", "fadmin/icons/disable" end, Color(255, 130, 0, 255), true, function(ply, button) ply:SetMuted(not ply.FAdminMuted) ply.FAdminMuted = not ply.FAdminMuted if ply.FAdminMuted then button:SetImage2("null") button:SetText("Unmute voice") button:GetParent():InvalidateLayout() return end button:SetImage2("fadmin/icons/disable") button:SetText("Mute voice") button:GetParent():InvalidateLayout() end) FAdmin.ScoreBoard.Main.AddPlayerRightClick("Mute/Unmute", function(ply, Panel) ply:SetMuted(not ply.FAdminMuted) ply.FAdminMuted = not ply.FAdminMuted end) end
agpl-3.0
asdofindia/prosody-modules
mod_roster_command/mod_roster_command.lua
31
5484
----------------------------------------------------------- -- mod_roster_command: Manage rosters through prosodyctl -- version 0.02 ----------------------------------------------------------- -- Copyright (C) 2011 Matthew Wild -- Copyright (C) 2011 Adam Nielsen -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. ----------------------------------------------------------- if not rawget(_G, "prosodyctl") then module:log("error", "Do not load this module in Prosody, for correct usage see: http://code.google.com/p/prosody-modules/wiki/mod_roster_command"); module.host = "*"; return; end -- Workaround for lack of util.startup... _G.bare_sessions = _G.bare_sessions or {}; local rostermanager = require "core.rostermanager"; local storagemanager = require "core.storagemanager"; local jid = require "util.jid"; local warn = prosodyctl.show_warning; -- Make a *one-way* subscription. User will see when contact is online, -- contact will not see when user is online. function subscribe(user_jid, contact_jid) local user_username, user_host = jid.split(user_jid); local contact_username, contact_host = jid.split(contact_jid); if not hosts[user_host] then warn("The host '%s' is not configured for this server.", user_host); return; end if hosts[user_host].users.name == "null" then storagemanager.initialize_host(user_host); usermanager.initialize_host(user_host); end -- Update user's roster to say subscription request is pending... rostermanager.set_contact_pending_out(user_username, user_host, contact_jid); if hosts[contact_host] then if contact_host ~= user_host and hosts[contact_host].users.name == "null" then storagemanager.initialize_host(contact_host); usermanager.initialize_host(contact_host); end -- Update contact's roster to say subscription request is pending... rostermanager.set_contact_pending_in(contact_username, contact_host, user_jid); -- Update contact's roster to say subscription request approved... rostermanager.subscribed(contact_username, contact_host, user_jid); -- Update user's roster to say subscription request approved... rostermanager.process_inbound_subscription_approval(user_username, user_host, contact_jid); end end -- Make a mutual subscription between jid1 and jid2. Each JID will see -- when the other one is online. function subscribe_both(jid1, jid2) subscribe(jid1, jid2); subscribe(jid2, jid1); end -- Unsubscribes user from contact (not contact from user, if subscribed). function unsubscribe(user_jid, contact_jid) local user_username, user_host = jid.split(user_jid); local contact_username, contact_host = jid.split(contact_jid); if not hosts[user_host] then warn("The host '%s' is not configured for this server.", user_host); return; end if hosts[user_host].users.name == "null" then storagemanager.initialize_host(user_host); usermanager.initialize_host(user_host); end -- Update user's roster to say subscription is cancelled... rostermanager.unsubscribe(user_username, user_host, contact_jid); if hosts[contact_host] then if contact_host ~= user_host and hosts[contact_host].users.name == "null" then storagemanager.initialize_host(contact_host); usermanager.initialize_host(contact_host); end -- Update contact's roster to say subscription is cancelled... rostermanager.unsubscribed(contact_username, contact_host, user_jid); end end -- Cancel any subscription in either direction. function unsubscribe_both(jid1, jid2) unsubscribe(jid1, jid2); unsubscribe(jid2, jid1); end -- Set the name shown and group used in the contact list function rename(user_jid, contact_jid, contact_nick, contact_group) local user_username, user_host = jid.split(user_jid); if not hosts[user_host] then warn("The host '%s' is not configured for this server.", user_host); return; end if hosts[user_host].users.name == "null" then storagemanager.initialize_host(user_host); usermanager.initialize_host(user_host); end -- Load user's roster and find the contact local roster = rostermanager.load_roster(user_username, user_host); local item = roster[contact_jid]; if item then if contact_nick then item.name = contact_nick; end if contact_group then item.groups = {}; -- Remove from all current groups item.groups[contact_group] = true; end rostermanager.save_roster(user_username, user_host, roster); end end function remove(user_jid, contact_jid) unsubscribe_both(user_jid, contact_jid); local user_username, user_host = jid.split(user_jid); local roster = rostermanager.load_roster(user_username, user_host); roster[contact_jid] = nil; rostermanager.save_roster(user_username, user_host, roster); end function module.command(arg) local command = arg[1]; if not command then warn("Valid subcommands: (un)subscribe(_both) | rename"); return 0; end table.remove(arg, 1); if command == "subscribe" then subscribe(arg[1], arg[2]); return 0; elseif command == "subscribe_both" then subscribe_both(arg[1], arg[2]); return 0; elseif command == "unsubscribe" then unsubscribe(arg[1], arg[2]); return 0; elseif command == "unsubscribe_both" then unsubscribe_both(arg[1], arg[2]); return 0; elseif command == "remove" then remove(arg[1], arg[2]); return 0; elseif command == "rename" then rename(arg[1], arg[2], arg[3], arg[4]); return 0; else warn("Unknown command: %s", command); return 1; end return 0; end
mit
eugeneia/snabbswitch
src/lib/numa.lua
3
5394
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Call bind_to_cpu(1) to bind the current Snabb process to CPU 1 (for -- example), to bind its memory to the corresponding NUMA node, to -- migrate mapped pages to that NUMA node, and to arrange to warn if -- you use a PCI device from a remote NUMA node. See README.numa.md -- for full API documentation. local S = require("syscall") local pci = require("lib.hardware.pci") local bound_cpu local bound_numa_node local node_path = '/sys/devices/system/node/node' local MAX_CPU = 1023 function cpu_get_numa_node (cpu) local node = 0 while true do local node_dir = S.open(node_path..node, 'rdonly, directory') if not node_dir then return 0 end -- default NUMA node local found = S.readlinkat(node_dir, 'cpu'..cpu) node_dir:close() if found then return node end node = node + 1 end end local function supports_numa () local node0 = S.open(node_path..tostring(0), 'rdonly, directory') if not node0 then return false end node0:close() return true end function has_numa () local node1 = S.open(node_path..tostring(1), 'rdonly, directory') if not node1 then return false end node1:close() return true end function pci_get_numa_node (addr) addr = pci.qualified(addr) local file = assert(io.open('/sys/bus/pci/devices/'..addr..'/numa_node')) local node = assert(tonumber(file:read())) -- node can be -1. return math.max(0, node) end function choose_numa_node_for_pci_addresses (addrs, require_affinity) local chosen_node, chosen_because_of_addr for _, addr in ipairs(addrs) do local node = pci_get_numa_node(addr) if not node or node == chosen_node then -- Keep trucking. elseif not chosen_node then chosen_node = node chosen_because_of_addr = addr else local msg = string.format( "PCI devices %s and %s have different NUMA node affinities", chosen_because_of_addr, addr) if require_affinity then error(msg) else print('Warning: '..msg) end end end return chosen_node end function check_affinity_for_pci_addresses (addrs) local policy = S.get_mempolicy() if policy.mode == S.c.MPOL_MODE['default'] then if has_numa() then print('Warning: No NUMA memory affinity.') print('Pass --cpu to bind to a CPU and its NUMA node.') end elseif policy.mode ~= S.c.MPOL_MODE['bind'] then print("Warning: NUMA memory policy already in effect, but it's not --membind.") else local node = S.getcpu().node local node_for_pci = choose_numa_node_for_pci_addresses(addrs) if node_for_pci and node ~= node_for_pci then print("Warning: Bound NUMA node does not have affinity with PCI devices.") end end end function unbind_cpu () local cpu_set = S.sched_getaffinity() cpu_set:zero() for i = 0, MAX_CPU do cpu_set:set(i) end assert(S.sched_setaffinity(0, cpu_set)) bound_cpu = nil end function bind_to_cpu (cpu) if cpu == bound_cpu then return end if not cpu then return unbind_cpu() end assert(not bound_cpu, "already bound") assert(S.sched_setaffinity(0, cpu), ("Couldn't set affinity for cpu %s"):format(cpu)) local cpu_and_node = S.getcpu() assert(cpu_and_node.cpu == cpu) bound_cpu = cpu bind_to_numa_node (cpu_and_node.node) end function unbind_numa_node () if supports_numa() then assert(S.set_mempolicy('default')) end bound_numa_node = nil end function bind_to_numa_node (node) if node == bound_numa_node then return end if not node then return unbind_numa_node() end assert(not bound_numa_node, "already bound") if supports_numa() then assert(S.set_mempolicy('bind', node)) -- Migrate any pages that might have the wrong affinity. local from_mask = assert(S.get_mempolicy(nil, nil, nil, 'mems_allowed')).mask assert(S.migrate_pages(0, from_mask, node)) end bound_numa_node = node end function prevent_preemption(priority) assert(S.sched_setscheduler(0, "fifo", priority or 1), 'Failed to enable real-time scheduling. Try running as root.') end function selftest () function test_cpu(cpu) local node = cpu_get_numa_node(cpu) bind_to_cpu(cpu) assert(bound_cpu == cpu) assert(bound_numa_node == node) assert(S.getcpu().cpu == cpu) assert(S.getcpu().node == node) bind_to_cpu(nil) assert(bound_cpu == nil) assert(bound_numa_node == node) assert(S.getcpu().node == node) bind_to_numa_node(nil) assert(bound_cpu == nil) assert(bound_numa_node == nil) end function test_pci_affinity (pciaddr) check_affinity_for_pci_addresses({pciaddr}) local node = choose_numa_node_for_pci_addresses({pciaddr}, true) bind_to_numa_node(node) assert(bound_numa_node == node) check_affinity_for_pci_addresses({pciaddr}) bind_to_numa_node(nil) assert(bound_numa_node == nil) end print('selftest: numa') local cpu_set = S.sched_getaffinity() for cpuid = 0, MAX_CPU do if cpu_set:get(cpuid) then test_cpu(cpuid) end end local pciaddr = os.getenv("SNABB_PCI0") if pciaddr then test_pci_affinity(pciaddr) end print('selftest: numa: ok') end
apache-2.0
Fenix-XI/Fenix
scripts/zones/Provenance/npcs/Tier42.lua
1
1307
----------------------------------- -- Area: Prov -- NPC: tier4 -- Guild Merchant NPC: Tier4 rewards -- @pos 0 0 0 0 zone ----------------------------------- package.loaded["scripts/zones/Provenance/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Provenance/TextIDs"); function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:PrintToPlayer("Welcome to the Tier 4 Rewards Shop #2. Please purchase your base item!"); stock = {0x5389,1, 0x515F,1, 0x48BB,1, 0x50EB,1, 0x51FA,1, 0x4A8D,1, 0x44DA,1, 0x48C3,1, 0x49DC,1, 0x410E,1, 0x4174,1, 0x42AD,1, 0x4A8C,1, 0x40C6,1, 0x497A,1, 0x497B,1, 0x3020,1, 0x2DF3,1, 0x4974,1 } showShop(player, STATIC, stock); 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
eugeneia/snabbswitch
src/program/snabbvmx/check/check.lua
9
1666
module(..., package.seeall) local config = require("core.config") local lib = require("core.lib") local util = require("program.lwaftr.check.util") local counters = require("program.lwaftr.counters") local setup = require("program.snabbvmx.lwaftr.setup") local function show_usage(code) print(require("program.snabbvmx.check.README_inc")) main.exit(code) end local function parse_args (args) local handlers = {} local opts = {} function handlers.h() show_usage(0) end function handlers.r() opts.r = true end args = lib.dogetopt(args, handlers, "hrD:", { help="h", regen="r", duration="D" }) if #args ~= 5 and #args ~= 6 then show_usage(1) end if not opts.duration then opts.duration = 0.10 end return opts, args end function run(args) local opts, args = parse_args(args) local conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap, counters_path = unpack(args) local c = config.new() setup.load_check(c, conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap) engine.configure(c) if counters_path then local initial_counters = counters.read_counters(c) engine.main({duration=opts.duration}) local final_counters = counters.read_counters(c) local counters_diff = util.diff_counters(final_counters, initial_counters) if opts.r then util.regen_counters(counters_diff, counters_path) else local req_counters = util.load_requested_counters(counters_path) util.validate_diff(counters_diff, req_counters) end else engine.main({duration=opts.duration}) end print("done") end
apache-2.0
abasshacker/abbasend
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
Giorox/AngelionOT-Repo
data/npc/scripts/bank.lua
1
12321
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local Topic, count, transferTo_name = {}, {}, {} function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local function getCount(string) local b, e = string:find('%d+') return b and e and tonumber(string:sub(b, e)) or -1 end local function playerExists(name) local v, ret = db.getResult("SELECT `name` FROM `players` WHERE `name` = " .. db.escapeString(name) .. ";"), nil if v:getID() ~= -1 then ret = v:getDataString('name') end v:free() return ret end function greetCallback(cid) Topic[cid], count[cid], transferTo_name[cid] = 0, 0,0 return true end function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false elseif msgcontains(msg, 'balance') then npcHandler:say('Your account balance is ' .. getPlayerBalance(cid) .. ' gold.', cid) Topic[cid] = 0 elseif msgcontains(msg, 'deposit') and msgcontains(msg, 'all') then if getPlayerMoney(cid) > 0 then count[cid] = getPlayerMoney(cid) npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid) Topic[cid] = 2 else npcHandler:say('Please tell me how much gold it is you would like to deposit.', cid) Topic[cid] = 1 end elseif msgcontains(msg, 'deposit') then if getCount(msg) == 0 then npcHandler:say('You are joking, aren\'t you??', cid) Topic[cid] = 0 elseif getCount(msg) ~= -1 then if getPlayerMoney(cid) >= getCount(msg) then count[cid] = getCount(msg) npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid) Topic[cid] = 2 else npcHandler:say('You do not have enough gold.', cid) Topic[cid] = 0 end else npcHandler:say('Please tell me how much gold it is you would like to deposit.', cid) Topic[cid] = 1 end elseif Topic[cid] == 1 then if getCount(msg) == -1 then npcHandler:say('Please tell me how much gold it is you would like to deposit.', cid) Topic[cid] = 1 else if getPlayerMoney(cid) >= getCount(msg) then count[cid] = getCount(msg) npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid) Topic[cid] = 2 else npcHandler:say('You do not have enough gold.', cid) Topic[cid] = 0 end end elseif msgcontains(msg, 'yes') and Topic[cid] == 2 then if doPlayerRemoveMoney(cid, count[cid]) then doPlayerSetBalance(cid, getPlayerBalance(cid) + count[cid]) npcHandler:say('Alright, we have added the amount of ' .. count[cid] .. ' gold to your balance. You can withdraw your money anytime you want to.', cid) else npcHandler:say('I am inconsolable, but it seems you have lost your gold. I hope you get it back.', cid) end Topic[cid] = 0 elseif msgcontains(msg, 'no') and Topic[cid] == 2 then npcHandler:say('As you wish. Is there something else I can do for you?', cid) Topic[cid] = 0 elseif msgcontains(msg, 'withdraw') then if getCount(msg) == 0 then npcHandler:say('Sure, you want nothing you get nothing!', cid) Topic[cid] = 0 elseif getCount(msg) ~= -1 then if getPlayerBalance(cid) >= getCount(msg) then count[cid] = getCount(msg) npcHandler:say('Are you sure you wish to withdraw ' .. count[cid] .. ' gold from your bank account?', cid) Topic[cid] = 4 else npcHandler:say('There is not enough gold on your account.', cid) Topic[cid] = 0 end else npcHandler:say('Please tell me how much gold you would like to withdraw.', cid) Topic[cid] = 3 end elseif Topic[cid] == 3 then if getCount(msg) == -1 then npcHandler:say('Please tell me how much gold you would like to withdraw.', cid) Topic[cid] = 3 else if getPlayerBalance(cid) >= getCount(msg) then count[cid] = getCount(msg) npcHandler:say('Are you sure you wish to withdraw ' .. count[cid] .. ' gold from your bank account?', cid) Topic[cid] = 4 else npcHandler:say('There is not enough gold on your account.', cid) Topic[cid] = 0 end end elseif msgcontains(msg, 'yes') and Topic[cid] == 4 then if getPlayerBalance(cid) >= count[cid] then doPlayerAddMoney(cid, count[cid]) doPlayerSetBalance(cid, getPlayerBalance(cid) - count[cid]) npcHandler:say('Here you are, ' .. count[cid] .. ' gold. Please let me know if there is something else I can do for you.', cid) else npcHandler:say('There is not enough gold on your account.', cid) end Topic[cid] = 0 elseif msgcontains(msg, 'no') and Topic[cid] == 4 then npcHandler:say('The customer is king! Come back anytime you want to if you wish to withdraw your money.', cid) Topic[cid] = 0 elseif msgcontains(msg, 'transfer') then if getCount(msg) == 0 then npcHandler:say('Please think about it. Okay?', cid) Topic[cid] = 0 elseif getCount(msg) ~= -1 then count[cid] = getCount(msg) if getPlayerBalance(cid) >= count[cid] then npcHandler:say('Who would you like to transfer ' .. count[cid] .. ' gold to?', cid) Topic[cid] = 6 else npcHandler:say('There is not enough gold on your account.', cid) Topic[cid] = 0 end else npcHandler:say('Please tell me the amount of gold you would like to transfer.', cid) Topic[cid] = 5 end elseif Topic[cid] == 5 then if getCount(msg) == -1 then npcHandler:say('Please tell me the amount of gold you would like to transfer.', cid) Topic[cid] = 5 else count[cid] = getCount(msg) if getPlayerBalance(cid) >= count[cid] then npcHandler:say('Who would you like to transfer ' .. count[cid] .. ' gold to?', cid) Topic[cid] = 6 else npcHandler:say('There is not enough gold on your account.', cid) Topic[cid] = 0 end end elseif Topic[cid] == 6 then local v = getPlayerByName(msg) if getPlayerBalance(cid) >= count[cid] then if v then transferTo_name[cid] = msg npcHandler:say('Would you really like to transfer ' .. count[cid] .. ' gold to ' .. getPlayerName(v) .. '?', cid) Topic[cid] = 7 elseif playerExists(msg):lower() == msg:lower() then transferTo_name[cid] = msg npcHandler:say('Would you really like to transfer ' .. count[cid] .. ' gold to ' .. playerExists(msg) .. '?', cid) Topic[cid] = 7 else npcHandler:say('This player does not exist.', cid) Topic[cid] = 0 end else npcHandler:say('There is not enough gold on your account.', cid) Topic[cid] = 0 end elseif Topic[cid] == 7 and msgcontains(msg, 'yes') then if getPlayerBalance(cid) >= count[cid] then local v = getPlayerByName(transferTo_name[cid]) if v then doPlayerSetBalance(cid, getPlayerBalance(cid) - count[cid]) doPlayerSetBalance(v, getPlayerBalance(v) + count[cid]) npcHandler:say('Very well. You have transferred ' .. count[cid] .. ' gold to ' .. getPlayerName(v) .. '.', cid) elseif playerExists(transferTo_name[cid]):lower() == transferTo_name[cid]:lower() then doPlayerSetBalance(cid, getPlayerBalance(cid) - count[cid]) db.executeQuery('UPDATE `players` SET `balance` = `balance` + ' .. count[cid] .. ' WHERE `name` = ' .. db.escapeString(transferTo_name[cid]) .. ' LIMIT 1;') npcHandler:say('Very well. You have transferred ' .. count[cid] .. ' gold to ' .. playerExists(transferTo_name[cid]) .. '.', cid) else npcHandler:say('This player does not exist.', cid) end else npcHandler:say('There is not enough gold on your account.', cid) end Topic[cid] = 0 elseif Topic[cid] == 7 and msgcontains(msg, 'no') then npcHandler:say('Alright, is there something else I can do for you?', cid) Topic[cid] = 0 elseif msgcontains(msg, 'change gold') then npcHandler:say('How many platinum coins would you like to get?', cid) Topic[cid] = 8 elseif Topic[cid] == 8 then if getCount(msg) < 1 then npcHandler:say('Hmm, can I help you with something else?', cid) Topic[cid] = 0 else count[cid] = getCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] * 100 .. ' of your gold coins into ' .. count[cid] .. ' platinum coins?', cid) Topic[cid] = 9 end elseif Topic[cid] == 9 then if msgcontains(msg, 'yes') then if doPlayerRemoveItem(cid, 2148, count[cid] * 100) then npcHandler:say('Here you are.', cid) doPlayerAddItem(cid, 2152, count[cid]) else npcHandler:say('Sorry, you do not have enough gold coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end Topic[cid] = 0 elseif msgcontains(msg, 'change platinum') then npcHandler:say('Would you like to change your platinum coins into gold or crystal?', cid) Topic[cid] = 10 elseif Topic[cid] == 10 then if msgcontains(msg, 'gold') then npcHandler:say('How many platinum coins would you like to change into gold?', cid) Topic[cid] = 11 elseif msgcontains(msg, 'crystal') then npcHandler:say('How many crystal coins would you like to get?', cid) Topic[cid] = 13 else npcHandler:say('Well, can I help you with something else?', cid) Topic[cid] = 0 end elseif Topic[cid] == 11 then if getCount(msg) < 1 then npcHandler:say('Hmm, can I help you with something else?', cid) Topic[cid] = 0 else count[cid] = getCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] .. ' of your platinum coins into ' .. count[cid] * 100 .. ' gold coins for you?', cid) Topic[cid] = 12 end elseif Topic[cid] == 12 then if msgcontains(msg, 'yes') then if doPlayerRemoveItem(cid, 2152, count[cid]) then npcHandler:say('Here you are.', cid) doPlayerAddItem(cid, 2148, count[cid] * 100) else npcHandler:say('Sorry, you do not have enough platinum coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end Topic[cid] = 0 elseif Topic[cid] == 13 then if getCount(msg) < 1 then npcHandler:say('Hmm, can I help you with something else?', cid) Topic[cid] = 0 else count[cid] = getCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] * 100 .. ' of your platinum coins into ' .. count[cid] .. ' crystal coins for you?', cid) Topic[cid] = 14 end elseif Topic[cid] == 14 then if msgcontains(msg, 'yes') then if doPlayerRemoveItem(cid, 2152, count[cid] * 100) then npcHandler:say('Here you are.', cid) doPlayerAddItem(cid, 2160, count[cid]) else npcHandler:say('Sorry, you do not have enough platinum coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end Topic[cid] = 0 elseif msgcontains(msg, 'change crystal') then npcHandler:say('How many crystal coins would you like to change into platinum?', cid) Topic[cid] = 15 elseif Topic[cid] == 15 then if getCount(msg) == -1 or getCount(msg) == 0 then npcHandler:say('Hmm, can I help you with something else?', cid) Topic[cid] = 0 else count[cid] = getCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] .. ' of your crystal coins into ' .. count[cid] * 100 .. ' platinum coins for you?', cid) Topic[cid] = 16 end elseif Topic[cid] == 16 then if msgcontains(msg, 'yes') then if doPlayerRemoveItem(cid, 2160, count[cid]) then npcHandler:say('Here you are.', cid) doPlayerAddItem(cid, 2152, count[cid] * 100) else npcHandler:say('Sorry, you do not have enough crystal coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end Topic[cid] = 0 elseif msgcontains(msg, 'change') then npcHandler:say('There are three different coin types in Tibia: 100 gold coins equal 1 platinum coin, 100 platinum coins equal 1 crystal coin. So if you\'d like to change 100 gold into 1 platinum, simply say \'{change gold}\' and then \'1 platinum\'.', cid) Topic[cid] = 0 elseif msgcontains(msg, 'bank') then npcHandler:say('We can change money for you. You can also access your bank account.', cid) Topic[cid] = 0 end return TRUE end npcHandler:setCallback(CALLBACK_GREET, greetCallback) npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Southern_San_dOria/npcs/Endracion.lua
9
6588
----------------------------------- -- Area: Southern San d'Oria -- NPC: Endracion -- !pos -110 1 -34 230 ----------------------------------- local ID = require("scripts/zones/Southern_San_dOria/IDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) local CurrentMission = player:getCurrentMission(SANDORIA); local OrcishScoutCompleted = player:hasCompletedMission(SANDORIA,dsp.mission.id.sandoria.SMASH_THE_ORCISH_SCOUTS); local BatHuntCompleted = player:hasCompletedMission(SANDORIA,dsp.mission.id.sandoria.BAT_HUNT); local TheCSpringCompleted = player:hasCompletedMission(SANDORIA,dsp.mission.id.sandoria.THE_CRYSTAL_SPRING); local MissionStatus = player:getCharVar("MissionStatus"); local Count = trade:getItemCount(); if (CurrentMission ~= dsp.mission.id.sandoria.NONE) then if (CurrentMission == dsp.mission.id.sandoria.SMASH_THE_ORCISH_SCOUTS and trade:hasItemQty(16656,1) and Count == 1 and OrcishScoutCompleted == false) then -- Trade Orcish Axe player:startEvent(1020); -- Finish Mission "Smash the Orcish scouts" (First Time) elseif (CurrentMission == dsp.mission.id.sandoria.SMASH_THE_ORCISH_SCOUTS and trade:hasItemQty(16656,1) and Count == 1) then -- Trade Orcish Axe player:startEvent(1002); -- Finish Mission "Smash the Orcish scouts" (Repeat) elseif (CurrentMission == dsp.mission.id.sandoria.BAT_HUNT and trade:hasItemQty(1112,1) and Count == 1 and BatHuntCompleted == false and MissionStatus == 2) then -- Trade Orcish Mail Scales player:startEvent(1023); -- Finish Mission "Bat Hunt" elseif (CurrentMission == dsp.mission.id.sandoria.BAT_HUNT and trade:hasItemQty(891,1) and Count == 1 and BatHuntCompleted == true) then -- Trade Bat Fang player:startEvent(1003); -- Finish Mission "Bat Hunt" (repeat) elseif (CurrentMission == dsp.mission.id.sandoria.THE_CRYSTAL_SPRING and trade:hasItemQty(4528,1) and Count == 1 and TheCSpringCompleted == false) then -- Trade Crystal Bass player:startEvent(1030); -- Dialog During Mission "The Crystal Spring" elseif (CurrentMission == dsp.mission.id.sandoria.THE_CRYSTAL_SPRING and trade:hasItemQty(4528,1) and Count == 1 and TheCSpringCompleted) then -- Trade Crystal Bass player:startEvent(1013); -- Finish Mission "The Crystal Spring" (repeat) else player:startEvent(1008); -- Wrong Item end else player:startEvent(1010); -- Mission not activated end end; function onTrigger(player,npc) local PresOfPapsqueCompleted = player:hasCompletedMission(SANDORIA,dsp.mission.id.sandoria.PRESTIGE_OF_THE_PAPSQUE); if (player:getNation() ~= dsp.nation.SANDORIA) then player:startEvent(1011); -- for Non-San d'Orians else local CurrentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getCharVar("MissionStatus"); local pRank = player:getRank(); local cs, p, offset = getMissionOffset(player,1,CurrentMission,MissionStatus); if (CurrentMission <= dsp.mission.id.sandoria.THE_SHADOW_LORD and (cs ~= 0 or offset ~= 0 or (CurrentMission == dsp.mission.id.sandoria.SMASH_THE_ORCISH_SCOUTS and offset == 0))) then if (cs == 0) then player:showText(npc,ID.text.ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (pRank == 1 and player:hasCompletedMission(SANDORIA,dsp.mission.id.sandoria.SMASH_THE_ORCISH_SCOUTS) == false) then player:startEvent(1000); -- Start First Mission "Smash the Orcish scouts" elseif (player:hasKeyItem(dsp.ki.ANCIENT_SANDORIAN_BOOK)) then player:startEvent(1035); elseif (CurrentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and player:getCharVar("MissionStatus",4) and tonumber(os.date("%j")) == player:getCharVar("Wait1DayForRanperre_date")) then player:startEvent(1037); elseif (CurrentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and player:getCharVar("MissionStatus") == 4 and tonumber(os.date("%j")) ~= player:getCharVar("Wait1DayForRanperre_date")) then -- Ready now. player:startEvent(1039); elseif (CurrentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and player:getCharVar("MissionStatus") == 6) then player:startEvent(1039); elseif (CurrentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and player:getCharVar("MissionStatus") == 9) then player:startEvent(1033); elseif (CurrentMission ~= dsp.mission.id.sandoria.THE_SECRET_WEAPON and pRank == 7 and PresOfPapsqueCompleted == true and getMissionRankPoints(player,19) == 1 and player:getCharVar("SecretWeaponStatus") == 0) then player:startEvent(61); elseif (CurrentMission == dsp.mission.id.sandoria.THE_SECRET_WEAPON and player:getCharVar("SecretWeaponStatus") == 3) then player:startEvent(1043); elseif ((CurrentMission ~= dsp.mission.id.sandoria.NONE) and not (player:getCharVar("MissionStatus") == 8)) then player:startEvent(1001); -- Have mission already activated else local mission_mask, repeat_mask = getMissionMask(player); player:startEvent(1009,mission_mask, 0, 0 ,0 ,0 ,repeat_mask); -- Mission List end end end; function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); end; function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); finishMissionTimeline(player,1,csid,option); if (csid == 1035) then player:setCharVar("MissionStatus",4); player:delKeyItem(dsp.ki.ANCIENT_SANDORIAN_BOOK); player:setCharVar("Wait1DayForRanperre_date", os.date("%j")); elseif (csid == 1037) then player:setCharVar("MissionStatus",6); elseif (csid == 1039) then player:setCharVar("MissionStatus",7); player:setCharVar("Wait1DayForRanperre_date",0); elseif (csid == 1033) then finishMissionTimeline(player,2,csid,option); elseif (csid == 61) then player:setCharVar("SecretWeaponStatus",1); elseif (csid == 1043) then finishMissionTimeline(player,2,csid,option); end end;
gpl-3.0
MartinFrancu/BETS
chili_clone/controls/progressbar_clone.lua
3
3524
--//============================================================================= --- Progressbar module --- Progressbar fields. -- Inherits from Control. -- @see control.Control -- @table Progressbar -- @int[opt=0] min minimum value of the Progressbar -- @int[opt=100] max maximum value of the Progressbar -- @int[opt=100] value value of the Progressbar -- @string[opt=""] caption text to be displayed -- @tparam {r,g,b,a} color specifies the color of the bar (default: {0,0,1,1}) -- @tparam {r,g,b,a} backgroundColor specifies the background color (default: {1,1,1,1}) -- @tparam {func1,fun2,...} OnChange function listeners for value change (default {}) Progressbar = Control:Inherit{ classname = "progressbar", defaultWidth = 90, defaultHeight = 20, min = 0, max = 100, value = 100, caption = "", color = {0,0,1,1}, backgroundColor = {1,1,1,1}, OnChange = {}, } local this = Progressbar local inherited = this.inherited --//============================================================================= function Progressbar:New(obj) obj = inherited.New(self,obj) obj:SetMinMax(obj.min,obj.max) obj:SetValue(obj.value) return obj end --//============================================================================= function Progressbar:_Clamp(v) if (self.min<self.max) then if (v<self.min) then v = self.min elseif (v>self.max) then v = self.max end else if (v>self.min) then v = self.min elseif (v<self.max) then v = self.max end end return v end --//============================================================================= --- Sets the new color -- @tparam {r,g,b,a} c color table function Progressbar:SetColor(...) local color = _ParseColorArgs(...) table.merge(color,self.color) if (not table.iequal(color,self.color)) then self.color = color self:Invalidate() end end --- Sets the minimum and maximum value of the progress bar -- @int[opt=0] min minimum value -- @int[opt=1] max maximum value (why is 1 the default?) function Progressbar:SetMinMax(min,max) self.min = tonumber(min) or 0 self.max = tonumber(max) or 1 self:SetValue(self.value) end --- Sets the value of the progress bar -- @int v value of the progress abr -- @bool[opt=false] setcaption whether the caption should be set as well function Progressbar:SetValue(v,setcaption) v = self:_Clamp(v) local oldvalue = self.value if (v ~= oldvalue) then self.value = v if (setcaption) then self:SetCaption(v) end self:CallListeners(self.OnChange,v,oldvalue) self:Invalidate() end end --- Sets the caption -- @string str caption to be set function Progressbar:SetCaption(str) if (self.caption ~= str) then self.caption = str self:Invalidate() end end --//============================================================================= function Progressbar:DrawControl() local percent = (self.value-self.min)/(self.max-self.min) local x = self.x local y = self.y local w = self.width local h = self.height gl.Color(self.backgroundColor) gl.Rect(w*percent,y,w,h) gl.Color(self.color) gl.Rect(0,y,w*percent,h) if (self.caption) then (self.font):Print(self.caption, w*0.5, h*0.5, "center", "center") end end --//=============================================================================
mit
ungarscool1/HL2RP
hl2rp/gamemode/modules/positions/sv_spawnpos.lua
10
1587
local function SetSpawnPos(ply, args) local pos = ply:GetPos() local t for k,v in pairs(RPExtraTeams) do if args == v.command then t = k DarkRP.notify(ply, 0, 4, DarkRP.getPhrase("created_spawnpos", v.name)) end end if t then DarkRP.storeTeamSpawnPos(t, {pos.x, pos.y, pos.z}) else DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", tostring(args))) end end DarkRP.definePrivilegedChatCommand("setspawn", "DarkRP_AdminCommands", SetSpawnPos) local function AddSpawnPos(ply, args) local pos = ply:GetPos() local t for k,v in pairs(RPExtraTeams) do if args == v.command then t = k DarkRP.notify(ply, 0, 4, DarkRP.getPhrase("updated_spawnpos", v.name)) end end if t then DarkRP.addTeamSpawnPos(t, {pos.x, pos.y, pos.z}) else DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", tostring(args))) end end DarkRP.definePrivilegedChatCommand("addspawn", "DarkRP_AdminCommands", AddSpawnPos) local function RemoveSpawnPos(ply, args) local t for k,v in pairs(RPExtraTeams) do if args == v.command then t = k DarkRP.notify(ply, 0, 4, DarkRP.getPhrase("updated_spawnpos", v.name)) break end end if t then DarkRP.removeTeamSpawnPos(t) else DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", tostring(args))) end end DarkRP.definePrivilegedChatCommand("removespawn", "DarkRP_AdminCommands", RemoveSpawnPos)
agpl-3.0
Fenix-XI/Fenix
scripts/zones/Windurst_Woods/npcs/Apururu.lua
12
7966
----------------------------------- -- Area: Windurst Woods -- NPC: Apururu -- Involved in Quests: The Kind Cardian, Can Cardians Cry? -- @zone 241 -- @pos -11 -2 13 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; package.loaded["scripts/globals/quests"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local TKC = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); local C3 = player:getQuestStatus(WINDURST,CAN_CARDIANS_CRY); -- The Kind Cardian if (TKC == QUEST_ACCEPTED) then if (trade:hasItemQty(969,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x018d); end -- Can Cardians Cry? elseif (C3 == QUEST_ACCEPTED) then count = trade:getItemCount(); if (trade:hasItemQty(551,1) and count == 1) then player:startEvent(0x0145,0,6000,5000); -- finish C3 end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ANC3K = player:getQuestStatus(WINDURST,THE_ALL_NEW_C_3000); -- previous quest in line local C3 = player:getQuestStatus(WINDURST,CAN_CARDIANS_CRY); local TKC = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); local MissionStatus = player:getVar("MissionStatus"); -- Windurst Mission 8-2 if (player:getCurrentMission(WINDURST) == THE_JESTER_WHO_D_BE_KING) then if (MissionStatus == 0) then player:startEvent(0x024C); elseif (MissionStatus == 2) then player:startEvent(0x0259); elseif (MissionStatus == 6) then player:startEvent(0x024E); elseif (MissionStatus == 7) then player:startEvent(0x024D); elseif (MissionStatus == 8) then player:startEvent(0x0250); elseif (MissionStatus == 10) then player:startEvent(0x0261); end --Windurst Mission 9-1-2 elseif (player:getCurrentMission(WINDURST) == DOLL_OF_THE_DEAD) then if (MissionStatus == 0) then player:startEvent(0x026B); elseif (MissionStatus == 3) then player:startEvent(0x026C); elseif (MissionStatus == 6) then --need to change satus player:startEvent(0x026D); end -- Windurst Mission 1-2 elseif (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then if (MissionStatus == 0) then player:startEvent(0x0089); elseif (MissionStatus < 4) then player:startEvent(0x008a); elseif (MissionStatus == 6) then -- Cardinals encountered, no orbs -- Mission's over - Bad end (ish anyway, you lost the orbs) player:startEvent(0x008f); elseif (MissionStatus == 5) then -- Cardinals not encountered -- Mission's over - Good end (you came back with the orbs) player:startEvent(0x0091); end -- The Kind Cardian elseif (TKC == QUEST_ACCEPTED) then if (player:getVar("theKindCardianVar") == 0) then player:startEvent(0x0188); elseif (player:getVar("theKindCardianVar") == 1) then player:startEvent(0x0189); elseif (player:getVar("theKindCardianVar") == 2) then player:startEvent(0x018e); end -- Can Cardians Cry? elseif (ANC3K == QUEST_COMPLETED and C3 == QUEST_AVAILABLE and player:getFameLevel (WINDURST) >= 5) then player:startEvent(0x013F,0,6000); -- start C3 elseif (C3 == QUEST_ACCEPTED) then player:startEvent(0x0140,0,6000); -- C3 reminder elseif (C3 == QUEST_COMPLETED) then player:startEvent(0x014A); -- new dialog after C3 -- standard dialog else player:startEvent(0x0112); 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); -- Windurst mission 1-2 start if (csid == 0x0089) then player:setVar("MissionStatus",1); player:addKeyItem(FIRST_DARK_MANA_ORB); -- Give the player the key items player:addKeyItem(SECOND_DARK_MANA_ORB); player:addKeyItem(THIRD_DARK_MANA_ORB); player:addKeyItem(FOURTH_DARK_MANA_ORB); player:addKeyItem(FIFTH_DARK_MANA_ORB); player:addKeyItem(SIXTH_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,FIRST_DARK_MANA_ORB); -- Display the key item messages player:messageSpecial(KEYITEM_OBTAINED,SECOND_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,THIRD_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,FOURTH_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,FIFTH_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,SIXTH_DARK_MANA_ORB); player:setVar("MissionStatus_orb1",1); -- Set the orb variables; 1 = not handled; 2 = handled; player:setVar("MissionStatus_orb2",1); player:setVar("MissionStatus_orb3",1); player:setVar("MissionStatus_orb4",1); player:setVar("MissionStatus_orb5",1); player:setVar("MissionStatus_orb6",1); elseif (csid == 0x008f or csid == 0x0091) then finishMissionTimeline(player,1,csid,option); player:setVar("MissionStatus_orb1",0); player:setVar("MissionStatus_orb2",0); player:setVar("MissionStatus_orb3",0); player:setVar("MissionStatus_orb4",0); player:setVar("MissionStatus_orb5",0); player:setVar("MissionStatus_orb6",0); player:delKeyItem(FIRST_GLOWING_MANA_ORB); -- Remove the glowing orb key items player:delKeyItem(SECOND_GLOWING_MANA_ORB); player:delKeyItem(THIRD_GLOWING_MANA_ORB); player:delKeyItem(FOURTH_GLOWING_MANA_ORB); player:delKeyItem(FIFTH_GLOWING_MANA_ORB); player:delKeyItem(SIXTH_GLOWING_MANA_ORB); -- The Kind Cardian elseif (csid == 0x0188 and option == 1) then player:setVar("theKindCardianVar",1); elseif (csid == 0x018d) then player:delKeyItem(TWO_OF_SWORDS); player:setVar("theKindCardianVar",2); player:addFame(WINDURST,30); player:tradeComplete(); -- Windurst 8-2 elseif (csid == 0x024C) then player:setVar("MissionStatus",1); player:addKeyItem(MANUSTERY_RING); elseif (csid == 0x0259) then player:setVar("MissionStatus",3); elseif (csid == 0x024E) then player:setVar("MissionStatus",7); elseif (csid == 0x0250) then player:setVar("MissionStatus",9); elseif (csid == 0x0261) then player:setVar("ShantottoCS",1) finishMissionTimeline(player,3,csid,option); --Windurst 9-1 elseif (csid == 0x026B) then player:setVar("MissionStatus",1); elseif (csid == 0x026C) then player:setVar("MissionStatus",4); elseif (csid == 0x026D) then player:setVar("MissionStatus",7); player:messageSpecial(KEYITEM_REMOVED,LETTER_FROM_ZONPAZIPPA); player:delKeyItem(LETTER_FROM_ZONPAZIPPA); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Ordelles_Caves/npcs/Grounds_Tome.lua
30
1098
----------------------------------- -- Area: Ordelle's Caves -- 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_ORDELLES_CAVES,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,655,656,657,658,659,660,661,662,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,655,656,657,658,659,660,661,662,0,0,GOV_MSG_ORDELLES_CAVES); end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Tavnazian_Safehold/npcs/Enaremand.lua
13
1062
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Enaremand -- Type: Standard NPC -- @zone: 26 -- @pos 95.962 -42.003 51.613 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0219); 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
ndbeals/Clip_Tool
lua/weapons/gmod_tool/stools/visual.lua
1
8106
/* Visual Clip Tool by TGiFallen */ TOOL.Category = "Construction" TOOL.Name = "#Visual Clip" TOOL.Command = nil TOOL.ConfigName = "" TOOL.ClientConVar["distance"] = "1" TOOL.ClientConVar["p"] = "0" TOOL.ClientConVar["y"] = "0" TOOL.ClientConVar["r"] = "0" if CLIENT then language.Add( "Tool.visual.name", "Visual Clip Tool" ) language.Add( "Tool.visual.desc", "Visually Clip Models" ) language.Add( "Tool.visual.0", "Primary: Define a clip plane Secondary: Clip Model (+Shift to toggle inside rendering of a prop) Reload: Remove Clips" ) language.Add( "Tool.visual.1", "Primary: Click on a second spot Secondary: Clip Model (+Shift to toggle inside rendering of a prop) Reload: Restart" ) language.Add( "Tool.visual.2", "Primary: Select the side of the prop you want to keep Secondary: Clip Model (+Shift to toggle inside rendering of a prop) Reload: Restart" ) language.Add( "Tool.visual.3", "Primary: Define a new plane based off of another prop Secondary: Clip Model (+Shift to toggle inside rendering of a prop) Reload: Restart") language.Add( "Tool.visual.4", "Aim at other props: Secondary: Clip Model (+Shift to toggle inside rendering of a prop) Reload: Restart") language.Add( "undone_clip", "Undone Clip" ) else util.AddNetworkString("clipping_cliptool_mode") end if SERVER then TOOL.Function = 1 function TOOL:Think() local ent = self:GetOwner():GetEyeTraceNoCursor( ).Entity if ent != self.LastEnt and IsValid(ent) and (self:GetStage() == 4 or self:GetStage() == 2) then self.LastEnt = ent local ang = self.Normal:Angle() local pos = ent:LocalToWorld( ent:OBBCenter() ) local linepoint1 = self.Position local linepoint2 = self.Position + ang:Forward() local dist = -(self.Normal:Dot(pos-linepoint1))/(self.Normal:Dot(linepoint2-linepoint1)) ang = ent:WorldToLocalAngles(self.Normal:Angle()) self:GetOwner():ConCommand("visual_distance ".. tostring(dist)) self:GetOwner():ConCommand("visual_p ".. tostring(ang.p)) self:GetOwner():ConCommand("visual_y ".. tostring(ang.y)) --net.Start("clipping_preview_clip") -- net.WriteFloat( ang.p ) -- net.WriteFloat( ang.y ) -- net.WriteFloat( ang.r ) -- net.WriteDouble( dist ) --net.Send( self:GetOwner() ) end end net.Receive("clipping_cliptool_mode" , function(_,ply) local mode = net.ReadInt(8) local tool = ply:GetTool("visual") tool.Function = mode if mode == 2 then tool.Points = {} tool.Step = 0 tool:SetStage(0) elseif mode == 1 then tool:SetStage(3) end end) end function TOOL:LeftClick( trace ) if CLIENT then return true end local ent = trace.Entity self.Points = self.Points or {} self.Step = self.Step or 0 if !IsValid(ent) then return end if ent:IsPlayer() or ent:IsWorld() then return end if self.Function == 1 then self:SetStage(4) self.Normal = -trace.HitNormal self.Position = trace.HitPos local ang = self.Normal:Angle() local pos = ent:LocalToWorld( ent:OBBCenter() ) local linepoint1 = self.Position local linepoint2 = self.Position + ang:Forward() local dist = -(self.Normal:Dot(pos-linepoint1))/(self.Normal:Dot(linepoint2-linepoint1)) ang = ent:WorldToLocalAngles(self.Normal:Angle()) --net.Start("clipping_preview_clip") -- net.WriteFloat( ang.p ) -- net.WriteFloat( ang.y ) -- net.WriteFloat( ang.r ) -- net.WriteDouble( dist ) --net.Send( self:GetOwner() ) self:GetOwner():ConCommand("visual_distance ".. tostring(dist)) self:GetOwner():ConCommand("visual_p ".. tostring(ang.p)) self:GetOwner():ConCommand("visual_y ".. tostring(ang.y)) elseif self.Function == 2 then self.Points[#self.Points+1] = trace.HitPos self:SetStage(#self.Points) if #self.Points > 1 then self:SetStage(2) self.Step = self.Step + 1 local normal = (self.Points[1] - self.Points[2]):GetNormalized() local ang = normal:Angle() local pos = ent:LocalToWorld( ent:OBBCenter() ) if self.Step == 1 then ang:RotateAroundAxis(ang:Right() , -90 ) elseif self.Step == 2 then ang:RotateAroundAxis(ang:Right() , 90 ) elseif self.Step == 3 then ang:RotateAroundAxis(ang:Up() , 90 ) elseif self.Step == 4 then ang:RotateAroundAxis(ang:Up() , -90 ) self.Step = 0 end normal=ang:Forward() local linepoint1 = self.Points[1] local linepoint2 = self.Points[1] + ang:Forward() local dist = -(normal:Dot(pos-linepoint1))/(normal:Dot(linepoint2-linepoint1)) ang = ent:WorldToLocalAngles(normal:Angle()) self.Position = linepoint1 self.Normal= -normal --net.Start("clipping_preview_clip") -- net.WriteFloat( ang.p ) -- net.WriteFloat( ang.y ) -- net.WriteFloat( ang.r ) -- net.WriteDouble( dist ) --net.Send( self:GetOwner() ) self:GetOwner():ConCommand("visual_distance ".. tostring(dist)) self:GetOwner():ConCommand("visual_p ".. tostring(ang.p)) self:GetOwner():ConCommand("visual_y ".. tostring(ang.y)) end end return true end function TOOL:RightClick( trace ) if CLIENT then return true end local ent = trace.Entity self:SetStage(0) if !IsValid(ent) then return end if ent:IsPlayer() or ent:IsWorld() then return end if self:GetOwner():KeyDown( IN_SPEED ) then Clipping.RenderInside( ent , !Clipping.GetRenderInside( ent ) ) else Clipping.NewClip( ent , {Angle(self:GetClientNumber("p"),self:GetClientNumber("y"),0) , self:GetClientNumber("distance") }) undo.Create("clip") undo.AddFunction(function( data , ent , numclips ) Clipping.RemoveClip( ent , numclips ) end, ent , #Clipping.GetClips(ent)) undo.SetPlayer(self:GetOwner()) undo.Finish() end return true; end function TOOL:Reload( trace ) if CLIENT then return true end if self:GetStage() == 2 or self:GetStage()==4 then if self.Function == 2 then self:SetStage(0) elseif self.Function == 1 then self:SetStage(3) end self.Points = {} self.Step = 0 return false end Clipping.RemoveClips( trace.Entity ) return true end if CLIENT then function TOOL.BuildCPanel( pnl ) pnl:Help("#Tool.visual.desc") local clipfunctions = vgui.Create("DListView",pnl) local tmp = clipfunctions:AddColumn("Plane functions") tmp.Header.DoClick=function()end clipfunctions:AddLine("Plane from Prop") clipfunctions:AddLine("Point to Point") clipfunctions:SetTall( 50 ) clipfunctions.OnClickLine = function( self , line , selected ) clipfunctions:ClearSelection() clipfunctions:SelectItem(line) net.Start("clipping_cliptool_mode") net.WriteInt(line:GetID() , 8) net.SendToServer() end pnl:AddPanel(clipfunctions) local temp = pnl:AddControl("Slider", { Label = "Distance", Type = "float", Min = "-100", Max = "100", Command = "visual_distance" } ) local temp2 = vgui.Create("DNumberScratch") temp2:SetParent(temp) temp2:SetMax(100) temp2:SetMin(-100) temp2:SetPos( 120 , 10) temp2:SetDecimals(4) temp2.OnValueChanged = function(self) RunConsoleCommand("visual_distance",self:GetFloatValue()) end --temp2:SetShouldDrawScreen(true) temp = pnl:AddControl("Slider", { Label = "Pitch", Type = "float", Min = "-180", Max = "180", Command = "visual_p" } ) temp2 = vgui.Create("DNumberScratch") temp2:SetParent(temp) temp2:SetMax(180) temp2:SetMin(-180) temp2:SetDecimals(4) temp2:SetPos( 120 , 10) temp2.OnValueChanged = function(self) RunConsoleCommand("visual_p",self:GetFloatValue()) end --temp2:SetShouldDrawScreen(true) temp = pnl:AddControl("Slider", { Label = "Yaw", Type = "float", Min = "-180", Max = "180", Command = "visual_y" } ) temp2 = vgui.Create("DNumberScratch") temp2:SetParent(temp) temp2:SetMax(180) temp2:SetMin(-180) temp2:SetDecimals(4) temp2:SetPos( 120 , 10) temp2.OnValueChanged = function(self) RunConsoleCommand("visual_y",self:GetFloatValue()) end --temp2:SetShouldDrawScreen(true) pnl:AddControl("Button", {Label = "Reset",Command = "visual_reset"}) pnl:AddControl("Slider", { Label = "Max Clips Per Prop", Type = "int", Min = "0", Max = "25", Command = "max_clips_per_prop" } ) end end
gpl-2.0
Fenix-XI/Fenix
scripts/zones/Davoi/npcs/Disused_Well.lua
13
1333
----------------------------------- -- Area: Davoi -- NPC: Disused Well -- Involved in Quest: A Knight's Test -- @pos -221 2 -293 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(KNIGHTS_SOUL) == false and player:hasKeyItem(BOOK_OF_TASKS) and player:hasKeyItem(BOOK_OF_THE_WEST) and player:hasKeyItem(BOOK_OF_THE_EAST)) then player:addKeyItem(KNIGHTS_SOUL); player:messageSpecial(KEYITEM_OBTAINED, KNIGHTS_SOUL); else player:messageSpecial(A_WELL); 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
DarkstarProject/darkstar
scripts/zones/Temenos/bcnms/temenos_eastern_tower.lua
9
1847
----------------------------------- -- Area: Temenos -- Name: Temenos Eastern Tower ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/battlefield") require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player,battlefield) if (GetMobByID(16928844):isSpawned()) then DespawnMob(16928844); end if (GetMobByID(16928853):isSpawned()) then DespawnMob(16928853); end if (GetMobByID(16928862):isSpawned()) then DespawnMob(16928862); end if (GetMobByID(16928871):isSpawned()) then DespawnMob(16928871); end if (GetMobByID(16928880):isSpawned()) then DespawnMob(16928880); end if (GetMobByID(16928889):isSpawned()) then DespawnMob(16928889); end if (GetMobByID(16928894):isSpawned()) then DespawnMob(16928894); end SetServerVariable("[Temenos_E_Tower]UniqueID",os.time()); HideArmouryCrates(Temenos_Eastern_Tower,TEMENOS); HideTemenosDoor(Temenos_Eastern_Tower); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBattlefieldEnter(player,battlefield) player:setCharVar("characterLimbusKey",GetServerVariable("[Temenos_E_Tower]UniqueID")); player:delKeyItem(dsp.ki.COSMOCLEANSE); player:delKeyItem(dsp.ki.WHITE_CARD); end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBattlefieldLeave(player,battlefield,leavecode) --print("leave code "..leavecode); if leavecode == dsp.battlefield.leaveCode.LOST then SetServerVariable("[Temenos_E_Tower]UniqueID",0); player:setPos(580,-1.5,4.452,192); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Ifrits_Cauldron/Zone.lua
13
2695
----------------------------------- -- -- Zone: Ifrits_Cauldron (205) -- ----------------------------------- package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Ifrits_Cauldron/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17617263,17617264,17617265,17617266,17617267,17617268,17617269,17617270}; SetGroundsTome(tomes); -- Mysticmaker Profblix SetRespawnTime(17617147, 900, 10800); UpdateTreasureSpawnPoint(17617220); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-60.296,48.884,105.967,69); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onGameHour ----------------------------------- function onGameHour() local VanadielHour = VanadielHour(); local FlameSpout = 17617204; if (VanadielHour % 3 == 0) then -- Opens flame spouts every 3 hours Vana'diel time GetNPCByID(FlameSpout):openDoor(90); -- Ifrit's Cauldron flame spout (H-6) Map 1 GetNPCByID(FlameSpout+1):openDoor(90); -- Ifrit's Cauldron flame spout (H-6) Map 5 GetNPCByID(FlameSpout+2):openDoor(90); -- Ifrit's Cauldron flame spout (I-10) Map 8 GetNPCByID(FlameSpout+3):openDoor(90); -- Ifrit's Cauldron flame spout (E-7) Map 8 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
AbolDalton/kia
plugins/abjad.lua
13
4026
local numbers = {} numbers['ا'] = 1 numbers['ب'] = 2 numbers['ج'] = 3 numbers['د'] = 4 numbers['ه'] = 5 numbers['و'] = 6 numbers['ز'] = 7 numbers['ح'] = 8 numbers['ط'] = 9 numbers['ی'] = 10 numbers['ک'] = 20 numbers['ل'] = 30 numbers['م'] = 40 numbers['ن'] = 50 numbers['س'] = 60 numbers['ع'] = 70 numbers['ف'] = 80 numbers['ص'] = 90 numbers['ق'] = 100 numbers['ر'] = 200 numbers['ش'] = 300 numbers['ت'] = 400 numbers['ث'] = 500 numbers['خ'] = 600 numbers['ذ'] = 700 numbers['ض'] = 800 numbers['ظ'] = 900 numbers['غ'] = 900 local function convert(text) local text = text:gsub('ژ','ز') local text = text:gsub('گ','ک') local text = text:gsub('چ','ج') local text = text:gsub('پ','ب') local text = text:gsub('ئ','ی') local text = text:gsub('آ','ا') local text = text:gsub('ۀ','ه') local text = text:gsub('ي','ی') local text = text:gsub('ة','ه') local text = text:gsub('ؤ','و') return text end local function abjad(text,num,str) local num = num local text = text if text:match(str) then for word in string.gmatch(text, str) do num = num + numbers[str] end text = text:gsub(str,'') end return text , num end local function run(msg, matches) if not matches[2] or matches[2] == '' then return [[حروف جمل یا به عبارت دیگر حروف ابجد،نام مجموع صور هشتگانه حروف عرب است. این صور ازین قرار است: ابجد – هوز- حطي - کلمن - سعفص - قرشت - ثخذ - ضظغ. ترتيب حروف (مراد،حروف صامت است) درين نسق همان ترتيب عبري آرامي است و اين امر با دلايل ديگر مؤید آنست که عرب الفباي خود را از آنان بوساطت نبطيان اقتباس کرده و شش حرف مخصوص عرب در آخر ترتيب ابجدي قرار داده شده است؛ علاوه برين ترتيب هشت کلمه تذکاريه که مفهومي ندارند با عبري و آرامي در اينکه حروف معرف اعدادند نيز شباهت دارد،از «همزه» تا «ی» نماينده ی 1تا10 ،«ک» تا «ق» نماینده ی 20تا100 و نه حرف آخر معرف 200تا1000 باشد. ابجد تجريد نوشتن (تصوف) ترک خواهش و آرزو کردن و از خودي و مزاحمت خواهش آمدن و از ماسوي الله مجرد گرديدن... ا=1 ک=20 ش=300 ب=2 ل=30 ت=400 ج=3 م=40 ث=500 د=4 ن=50 خ=600 ه=5 س=60 ذ=700 و=6 ع=70 ض=800 ز=7 ف=80 ظ=900 ح=8 ص=90 غ=1000 ط=9 ق=100 ی=10 ر=200 ]] end local text = convert(matches[2]) local num = 0 text , num = abjad(text,num,'ا') text , num = abjad(text,num,'ب') text , num = abjad(text,num,'ج') text , num = abjad(text,num,'د') text , num = abjad(text,num,'ه') text , num = abjad(text,num,'و') text , num = abjad(text,num,'ز') text , num = abjad(text,num,'ح') text , num = abjad(text,num,'ط') text , num = abjad(text,num,'ی') text , num = abjad(text,num,'ک') text , num = abjad(text,num,'ل') text , num = abjad(text,num,'م') text , num = abjad(text,num,'ن') text , num = abjad(text,num,'س') text , num = abjad(text,num,'ع') text , num = abjad(text,num,'ف') text , num = abjad(text,num,'ص') text , num = abjad(text,num,'ق') text , num = abjad(text,num,'ر') text , num = abjad(text,num,'ش') text , num = abjad(text,num,'ت') text , num = abjad(text,num,'ث') text , num = abjad(text,num,'خ') text , num = abjad(text,num,'ذ') text , num = abjad(text,num,'ض') text , num = abjad(text,num,'ظ') text , num = abjad(text,num,'غ') if text ~= '' then return 'فقط زبان فارسی پشتیبانی میشود' end return 'عدد ابجد کبیر : '..num end return { patterns = { "^[!/#]([Aa]bjad) (.*)$", "^[!/#]([Aa]bjad)$", "^([Aa]bjad) (.*)$", "^([Aa]bjad)$" }, run = run }
gpl-2.0
GameDevStudios/MrBallGuy2
assets/libs/loveframes/objects/base.lua
5
26989
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- base object local newobject = loveframes.NewObject("base", "loveframes_object_base") --[[--------------------------------------------------------- - func: initialize() - desc: intializes the element --]]--------------------------------------------------------- function newobject:initialize() -- width and height of the window local w = love.graphics.getWidth() local h = love.graphics.getHeight() self.type = "base" self.width = w self.height = h self.internal = true self.children = {} self.internals = {} end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local children = self.children local internals = self.internals for k, v in ipairs(children) do v:update(dt) end for k, v in ipairs(internals) do v:update(dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local children = self.children local internals = self.internals -- set the object's draw order self:SetDrawOrder() for k, v in ipairs(children) do v:draw() end for k, v in ipairs(internals) do v:draw() end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local children = self.children local internals = self.internals if not visible then return end if children then for k, v in ipairs(children) do v:mousepressed(x, y, button) end end if internals then for k, v in ipairs(internals) do v:mousepressed(x, y, button) end end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local children = self.children local internals = self.internals if not visible then return end if children then for k, v in ipairs(children) do v:mousereleased(x, y, button) end end if internals then for k, v in ipairs(internals) do v:mousereleased(x, y, button) end end end --[[--------------------------------------------------------- - func: keypressed(key) - desc: called when the player presses a key --]]--------------------------------------------------------- function newobject:keypressed(key, unicode) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local children = self.children local internals = self.internals if not visible then return end if children then for k, v in ipairs(children) do v:keypressed(key, unicode) end end if internals then for k, v in ipairs(internals) do v:keypressed(key, unicode) end end end --[[--------------------------------------------------------- - func: keyreleased(key) - desc: called when the player releases a key --]]--------------------------------------------------------- function newobject:keyreleased(key) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local children = self.children local internals = self.internals if not visible then return end if children then for k, v in ipairs(children) do v:keyreleased(key) end end if internals then for k, v in ipairs(internals) do v:keyreleased(key) end end end --[[--------------------------------------------------------- - func: SetPos(x, y, center) - desc: sets the object's position --]]--------------------------------------------------------- function newobject:SetPos(x, y, center) local base = loveframes.base local parent = self.parent if center then local width = self.width local height = self.height x = x - width/2 y = y - height/2 end if parent == base then self.x = x self.y = y else self.staticx = x self.staticy = y end end --[[--------------------------------------------------------- - func: SetX(x, center) - desc: sets the object's x position --]]--------------------------------------------------------- function newobject:SetX(x, center) local base = loveframes.base local parent = self.parent if center then local width = self.width x = x - width/2 end if parent == base then self.x = x else self.staticx = x end end --[[--------------------------------------------------------- - func: SetY(y, center) - desc: sets the object's y position --]]--------------------------------------------------------- function newobject:SetY(y, center) local base = loveframes.base local parent = self.parent if center then local height = self.height y = y - height/2 end if parent == base then self.y = y else self.staticy = y end end --[[--------------------------------------------------------- - func: GetPos() - desc: gets the object's position --]]--------------------------------------------------------- function newobject:GetPos() return self.x, self.y end --[[--------------------------------------------------------- - func: GetX() - desc: gets the object's x position --]]--------------------------------------------------------- function newobject:GetX() return self.x end --[[--------------------------------------------------------- - func: GetY() - desc: gets the object's y position --]]--------------------------------------------------------- function newobject:GetY() return self.y end --[[--------------------------------------------------------- - func: GetStaticPos() - desc: gets the object's static position --]]--------------------------------------------------------- function newobject:GetStaticPos() return self.staticx, self.staticy end --[[--------------------------------------------------------- - func: GetStaticX() - desc: gets the object's static x position --]]--------------------------------------------------------- function newobject:GetStaticX() return self.staticx end --[[--------------------------------------------------------- - func: GetStaticY() - desc: gets the object's static y position --]]--------------------------------------------------------- function newobject:GetStaticY() return self.staticy end --[[--------------------------------------------------------- - func: Center() - desc: centers the object in the game window or in its parent if it has one --]]--------------------------------------------------------- function newobject:Center(area) local base = loveframes.base local parent = self.parent if parent == base then local width = love.graphics.getWidth() local height = love.graphics.getHeight() self.x = width/2 - self.width/2 self.y = height/2 - self.height/2 else local width = parent.width local height = parent.height self.staticx = width/2 - self.width/2 self.staticy = height/2 - self.height/2 end end --[[--------------------------------------------------------- - func: CenterX() - desc: centers the object by its x value --]]--------------------------------------------------------- function newobject:CenterX() local base = loveframes.base local parent = self.parent if parent == base then local width = love.graphics.getWidth() self.x = width/2 - self.width/2 else local width = parent.width self.staticx = width/2 - self.width/2 end end --[[--------------------------------------------------------- - func: CenterY() - desc: centers the object by its y value --]]--------------------------------------------------------- function newobject:CenterY() local base = loveframes.base local parent = self.parent if parent == base then local height = love.graphics.getHeight() self.y = height/2 - self.height/2 else local height = parent.height self.staticy = height/2 - self.height/2 end end --[[--------------------------------------------------------- - func: CenterWithinArea() - desc: centers the object within the given area --]]--------------------------------------------------------- function newobject:CenterWithinArea(x, y, width, height) local selfwidth = self.width local selfheight = self.height self.x = x + width/2 - selfwidth/2 self.y = y + height/2 - selfheight/2 end --[[--------------------------------------------------------- - func: SetSize(width, height) - desc: sets the object's size --]]--------------------------------------------------------- function newobject:SetSize(width, height) self.width = width self.height = height end --[[--------------------------------------------------------- - func: SetWidth(width) - desc: sets the object's width --]]--------------------------------------------------------- function newobject:SetWidth(width) self.width = width end --[[--------------------------------------------------------- - func: SetHeight(height) - desc: sets the object's height --]]--------------------------------------------------------- function newobject:SetHeight(height) self.height = height end --[[--------------------------------------------------------- - func: GetSize() - desc: gets the object's size --]]--------------------------------------------------------- function newobject:GetSize() return self.width, self.height end --[[--------------------------------------------------------- - func: GetWidth() - desc: gets the object's width --]]--------------------------------------------------------- function newobject:GetWidth() return self.width end --[[--------------------------------------------------------- - func: GetHeight() - desc: gets the object's height --]]--------------------------------------------------------- function newobject:GetHeight() return self.height end --[[--------------------------------------------------------- - func: SetVisible(bool) - desc: sets the object's visibility --]]--------------------------------------------------------- function newobject:SetVisible(bool) local children = self.children local internals = self.internals self.visible = bool if children then for k, v in ipairs(children) do v:SetVisible(bool) end end if internals then for k, v in ipairs(internals) do v:SetVisible(bool) end end end --[[--------------------------------------------------------- - func: GetVisible() - desc: gets the object's visibility --]]--------------------------------------------------------- function newobject:GetVisible() return self.visible end --[[--------------------------------------------------------- - func: SetParent(parent) - desc: sets the object's parent --]]--------------------------------------------------------- function newobject:SetParent(parent) local tparent = parent local cparent = self.parent local ptype = tparent.type local stype = self.type if ptype ~= "frame" and ptype ~= "panel" and ptype ~= "list" then return end self:Remove() self.parent = tparent self:SetState(tparent.state) table.insert(tparent.children, self) end --[[--------------------------------------------------------- - func: GetParent() - desc: gets the object's parent --]]--------------------------------------------------------- function newobject:GetParent() local parent = self.parent return parent end --[[--------------------------------------------------------- - func: Remove() - desc: removes the object --]]--------------------------------------------------------- function newobject:Remove() local pinternals = self.parent.internals local pchildren = self.parent.children if pinternals then for k, v in ipairs(pinternals) do if v == self then table.remove(pinternals, k) end end end if pchildren then for k, v in ipairs(pchildren) do if v == self then table.remove(pchildren, k) end end end end --[[--------------------------------------------------------- - func: SetClickBounds(x, y, width, height) - desc: sets a boundary box for the object's collision detection --]]--------------------------------------------------------- function newobject:SetClickBounds(x, y, width, height) local internals = self.internals local children = self.children self.clickbounds = {x = x, y = y, width = width, height = height} if internals then for k, v in ipairs(internals) do v:SetClickBounds(x, y, width, height) end end if children then for k, v in ipairs(children) do v:SetClickBounds(x, y, width, height) end end end --[[--------------------------------------------------------- - func: GetClickBounds() - desc: gets the boundary box for the object's collision detection --]]--------------------------------------------------------- function newobject:GetClickBounds() return self.clickbounds end --[[--------------------------------------------------------- - func: RemoveClickBounds() - desc: removes the collision detection boundary for the object --]]--------------------------------------------------------- function newobject:RemoveClickBounds() local internals = self.internals local children = self.children self.clickbounds = nil if internals then for k, v in ipairs(internals) do v:RemoveClickBounds() end end if children then for k, v in ipairs(children) do v:RemoveClickBounds() end end end --[[--------------------------------------------------------- - func: InClickBounds() - desc: checks if the mouse is inside the object's collision detection boundaries --]]--------------------------------------------------------- function newobject:InClickBounds() local x, y = love.mouse.getPosition() local bounds = self.clickbounds if bounds then local col = loveframes.util.BoundingBox(x, bounds.x, y, bounds.y, 1, bounds.width, 1, bounds.height) return col else return false end end --[[--------------------------------------------------------- - func: IsTopCollision() - desc: checks if the object the top most object in a collision table --]]--------------------------------------------------------- function newobject:IsTopCollision() local cols = loveframes.util.GetCollisions() local draworder = self.draworder local found = false local top = true for k, v in ipairs(cols) do if v == self then found = true end end if not found then return false end -- loop through the object's parent's children for k, v in ipairs(cols) do if v.draworder > draworder then top = false end end return top end --[[--------------------------------------------------------- - func: GetBaseParent(object, t) - desc: finds the object's base parent --]]--------------------------------------------------------- function newobject:GetBaseParent(t) local t = t or {} local base = loveframes.base local parent = self.parent if parent ~= base then table.insert(t, parent) parent:GetBaseParent(t) end return t[#t] end --[[--------------------------------------------------------- - func: CheckHover() - desc: checks to see if the object should be in a hover state --]]--------------------------------------------------------- function newobject:CheckHover() local x, y = love.mouse.getPosition() local selfcol = loveframes.util.BoundingBox(x, self.x, y, self.y, 1, self.width, 1, self.height) local hoverobject = loveframes.hoverobject local modalobject = loveframes.modalobject local collisioncount = loveframes.collisioncount local clickbounds = self.clickbounds -- is the mouse inside the object? if selfcol then loveframes.collisioncount = collisioncount + 1 local top = self:IsTopCollision() if top then if not hoverobject then self.hover = true else if hoverobject == self then self.hover = true else self.hover = false end end else self.hover = false end if clickbounds then if not self:InClickBounds() then self.hover = false end end else self.hover = false end if modalobject then if modalobject ~= self then local baseparent = self:GetBaseParent() if baseparent ~= modalobject and self.type ~= "multichoicerow" then self.hover = false if self.focus then self.focus = false end end end end -- this chunk of code handles mouse enter and exit if self.hover then loveframes.hover = true if not self.calledmousefunc then if self.OnMouseEnter then self.OnMouseEnter(self) self.calledmousefunc = true else self.calledmousefunc = true end end else if self.calledmousefunc then if self.OnMouseExit then self.OnMouseExit(self) self.calledmousefunc = false else self.calledmousefunc = false end end end end --[[--------------------------------------------------------- - func: GetHover() - desc: return if the object is in a hover state or not --]]--------------------------------------------------------- function newobject:GetHover() return self.hover end --[[--------------------------------------------------------- - func: GetChildren() - desc: returns the object's children --]]--------------------------------------------------------- function newobject:GetChildren() local children = self.children if children then return children end end --[[--------------------------------------------------------- - func: GetInternals() - desc: returns the object's internals --]]--------------------------------------------------------- function newobject:GetInternals() local internals = self.internals if internals then return internals end end --[[--------------------------------------------------------- - func: IsTopList() - desc: returns true if the object is the top most list object or false if not --]]--------------------------------------------------------- function newobject:IsTopList() local cols = loveframes.util.GetCollisions() local children = self:GetChildren() local order = self.draworder local top = true local found = false local function IsChild(object) local parents = object:GetParents() for k, v in ipairs(parents) do if v == self then return true end end return false end for k, v in ipairs(cols) do if v == self then found = true else if v.draworder > order then if IsChild(v) ~= true then top = false break end end end end if found == false then top = false end return top end --[[--------------------------------------------------------- - func: IsTopChild() - desc: returns true if the object is the top most child in its parent's children table or false if not --]]--------------------------------------------------------- function newobject:IsTopChild() local children = self.parent.children local num = #children if children[num] == self then return true else return false end end --[[--------------------------------------------------------- - func: MoveToTop() - desc: moves the object to the top of its parent's children table --]]--------------------------------------------------------- function newobject:MoveToTop() local pchildren = self.parent.children local pinternals = self.parent.internals local internal = false for k, v in ipairs(pinternals) do if v == self then internal = true end end self:Remove() if internal then table.insert(pinternals, self) else table.insert(pchildren, self) end end --[[--------------------------------------------------------- - func: SetSkin(name) - desc: sets the object's skin --]]--------------------------------------------------------- function newobject:SetSkin(name) local children = self.children local internals = self.internals self.skin = name if children then for k, v in ipairs(children) do v:SetSkin(name) end end if internals then for k, v in ipairs(internals) do v:SetSkin(name) end end end --[[--------------------------------------------------------- - func: GetSkin(name) - desc: gets the object's skin --]]--------------------------------------------------------- function newobject:GetSkin(name) local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] return skin end --[[--------------------------------------------------------- - func: GetSkinName() - desc: gets the name of the object's skin --]]--------------------------------------------------------- function newobject:GetSkinName() return self.skin end --[[--------------------------------------------------------- - func: SetAlwaysUpdate(bool) - desc: sets the object's skin --]]--------------------------------------------------------- function newobject:SetAlwaysUpdate(bool) self.alwaysupdate = bool end --[[--------------------------------------------------------- - func: GetAlwaysUpdate() - desc: gets whether or not the object will always update --]]--------------------------------------------------------- function newobject:GetAlwaysUpdate() return self.alwaysupdate end --[[--------------------------------------------------------- - func: SetRetainSize(bool) - desc: sets whether or not the object should retain its size when another object tries to resize it --]]--------------------------------------------------------- function newobject:SetRetainSize(bool) self.retainsize = bool end --[[--------------------------------------------------------- - func: GetRetainSize() - desc: gets whether or not the object should retain its size when another object tries to resize it --]]--------------------------------------------------------- function newobject:GetRetainSize() return self.retainsize end --[[--------------------------------------------------------- - func: IsActive() - desc: gets whether or not the object is active within its parent's child table --]]--------------------------------------------------------- function newobject:IsActive() local parent = self.parent local pchildren = parent.children local valid = false for k, v in ipairs(pchildren) do if v == self then valid = true end end return valid end --[[--------------------------------------------------------- - func: GetParents() - desc: returns a table of the object's parents and its sub-parents --]]--------------------------------------------------------- function newobject:GetParents() local function GetParents(object, t) local t = t or {} local type = object.type local parent = object.parent if type ~= "base" then table.insert(t, parent) GetParents(parent, t) end return t end local parents = GetParents(self) return parents end --[[--------------------------------------------------------- - func: IsTopInternal() - desc: returns true if the object is the top most internal in its parent's internals table or false if not --]]--------------------------------------------------------- function newobject:IsTopInternal() local parent = self.parent local internals = parent.internals local topitem = internals[#internals] if topitem ~= self then return false else return true end end --[[--------------------------------------------------------- - func: IsInternal() - desc: returns true if the object is internal or false if not --]]--------------------------------------------------------- function newobject:IsInternal() return self.internal end --[[--------------------------------------------------------- - func: GetType() - desc: gets the type of the object --]]--------------------------------------------------------- function newobject:GetType() return self.type end --[[--------------------------------------------------------- - func: SetDrawOrder() - desc: sets the object's draw order --]]--------------------------------------------------------- function newobject:SetDrawOrder() loveframes.drawcount = loveframes.drawcount + 1 self.draworder = loveframes.drawcount end --[[--------------------------------------------------------- - func: GetDrawOrder() - desc: sets the object's draw order --]]--------------------------------------------------------- function newobject:GetDrawOrder() return self.draworder end --[[--------------------------------------------------------- - func: SetProperty(name, value) - desc: sets a property on the object --]]--------------------------------------------------------- function newobject:SetProperty(name, value) self[name] = value end --[[--------------------------------------------------------- - func: GetProperty(name) - desc: gets the value of an object's property --]]--------------------------------------------------------- function newobject:GetProperty(name) return self[name] end --[[--------------------------------------------------------- - func: IsInList() - desc: checks to see if an object is in a list --]]--------------------------------------------------------- function newobject:IsInList() local parents = self:GetParents() for k, v in ipairs(parents) do if v.type == "list" then return true, v end end return false, false end --[[--------------------------------------------------------- - func: SetState(name) - desc: sets the object's state --]]--------------------------------------------------------- function newobject:SetState(name) local children = self.children local internals = self.internals self.state = name if children then for k, v in ipairs(children) do v:SetState(name) end end if internals then for k, v in ipairs(internals) do v:SetState(name) end end end --[[--------------------------------------------------------- - func: GetState() - desc: gets the object's state --]]--------------------------------------------------------- function newobject:GetState() return self.state end
gpl-3.0
emender/emender
test/TestGitRepo.lua
1
1232
-- TestGitRepo.lua - check for basic Emender functionality -- Copyright (C) 2016 Pavel Tisnovsky -- -- This file is part of Emender. -- -- Emender is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 3 of the License. -- -- Emender is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Emender. If not, see <http://www.gnu.org/licenses/>. -- TestGitRepo = { -- required field metadata = { description = "Check that -g and --git-repo CLI options work correctly.", authors = "Pavel Tisnovsky", emails = "ptisnovs@redhat.com", changed = "2016-05-11", tags = {"BasicTest", "SmokeTest"}, } } -- -- Comment bound to the function TestGitRepo.testA(). -- function TestGitRepo.testGitRepo() if gitRepo then pass("GIT repo: " .. gitRepo) else fail("GIT repo is not set!") end end
gpl-3.0
dualface/killpests
src/framework/cc/Registry.lua
23
1841
local Registry = class("Registry") Registry.classes_ = {} Registry.objects_ = {} function Registry.add(cls, name) assert(type(cls) == "table" and cls.__cname ~= nil, "Registry.add() - invalid class") if not name then name = cls.__cname end assert(Registry.classes_[name] == nil, string.format("Registry.add() - class \"%s\" already exists", tostring(name))) Registry.classes_[name] = cls end function Registry.remove(name) assert(Registry.classes_[name] ~= nil, string.format("Registry.remove() - class \"%s\" not found", name)) Registry.classes_[name] = nil end function Registry.exists(name) return Registry.classes_[name] ~= nil end function Registry.newObject(name, ...) local cls = Registry.classes_[name] if not cls then -- auto load pcall(function() cls = require(name) Registry.add(cls, name) end) end assert(cls ~= nil, string.format("Registry.newObject() - invalid class \"%s\"", tostring(name))) return cls.new(...) end function Registry.setObject(object, name) assert(Registry.objects_[name] == nil, string.format("Registry.setObject() - object \"%s\" already exists", tostring(name))) assert(object ~= nil, "Registry.setObject() - object \"%s\" is nil", tostring(name)) Registry.objects_[name] = object end function Registry.getObject(name) assert(Registry.objects_[name] ~= nil, string.format("Registry.getObject() - object \"%s\" not exists", tostring(name))) return Registry.objects_[name] end function Registry.removeObject(name) assert(Registry.objects_[name] ~= nil, string.format("Registry.removeObject() - object \"%s\" not exists", tostring(name))) Registry.objects_[name] = nil end function Registry.isObjectExists(name) return Registry.objects_[name] ~= nil end return Registry
mit
Fenix-XI/Fenix
scripts/zones/Sea_Serpent_Grotto/npcs/_4w4.lua
13
2793
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: Gold Beastcoin Door -- @zone 176 -- @pos 60 8.55 -80 ----------------------------------- package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Sea_Serpent_Grotto/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(748,1) and trade:getItemCount() == 1) then if (player:getVar("SSG_GoldDoor") == 7) then npc:openDoor(5) --Open the door if a gold beastcoin has been traded after checking the door the required number of times end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) X = player:getXPos(); Z = player:getZPos(); GoldDoorCheck = player:getVar("SSG_GoldDoor"); if (X >= 55 and Z >= -80) then if (GoldDoorCheck == 0) then --Door has never been checked player:messageSpecial(FIRST_CHECK); player:setVar("SSG_GoldDoor",1); elseif (GoldDoorCheck == 1) then --Door has been checked once player:messageSpecial(SECOND_CHECK); player:setVar("SSG_GoldDoor",2); elseif (GoldDoorCheck == 2) then --Door has been checked twice player:messageSpecial(THIRD_CHECK); player:setVar("SSG_GoldDoor",3); elseif (GoldDoorCheck == 3) then --Door has been checked three times player:messageSpecial(FOURTH_CHECK); player:setVar("SSG_GoldDoor",4); elseif (GoldDoorCheck == 4) then --Door has been checked four times player:messageSpecial(FIFTH_CHECK); player:setVar("SSG_GoldDoor",5); elseif (GoldDoorCheck == 5) then --Door has been checked five times player:messageSpecial(GOLD_CHECK); player:setVar("SSG_GoldDoor",6); elseif (GoldDoorCheck == 6 or GoldDoorCheck == 7) then --Door has been checked six or more times player:messageSpecial(COMPLETED_CHECK,748); player:setVar("SSG_GoldDoor",7); end return 1 --Keep the door closed elseif (X > 55 and Z < -81) then return -1 --Open the door if coming from the "inside" 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
crunchuser/prosody-modules
mod_register_web/mod_register_web.lua
27
5718
local captcha_options = module:get_option("captcha_options", {}); local nodeprep = require "util.encodings".stringprep.nodeprep; local usermanager = require "core.usermanager"; local http = require "net.http"; local path_sep = package.config:sub(1,1); module:depends"http"; local extra_fields = { nick = true; name = true; first = true; last = true; email = true; address = true; city = true; state = true; zip = true; phone = true; url = true; date = true; } local template_path = module:get_option_string("register_web_template", "templates"); function template(data) -- Like util.template, but deals with plain text return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end } end local function get_template(name) local fh = assert(module:load_resource(template_path..path_sep..name..".html")); local data = assert(fh:read("*a")); fh:close(); return template(data); end local function render(template, data) return tostring(template.apply(data)); end local register_tpl = get_template "register"; local success_tpl = get_template "success"; if next(captcha_options) ~= nil then local recaptcha_tpl = get_template "recaptcha"; function generate_captcha(display_options) return recaptcha_tpl.apply(setmetatable({ recaptcha_display_error = display_options and display_options.recaptcha_error and ("&error="..display_options.recaptcha_error) or ""; }, { __index = function (t, k) if captcha_options[k] then return captcha_options[k]; end module:log("error", "Missing parameter from captcha_options: %s", k); end })); end function verify_captcha(request, form, callback) http.request("https://www.google.com/recaptcha/api/verify", { body = http.formencode { privatekey = captcha_options.recaptcha_private_key; remoteip = request.conn:ip(); challenge = form.recaptcha_challenge_field; response = form.recaptcha_response_field; }; }, function (verify_result, code) local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)"); if verify_ok == "true" then callback(true); else callback(false, verify_err) end end); end else module:log("debug", "No Recaptcha options set, using fallback captcha") local random = math.random; local hmac_sha1 = require "util.hashes".hmac_sha1; local secret = require "util.uuid".generate() local ops = { '+', '-' }; local captcha_tpl = get_template "simplecaptcha"; function generate_captcha() local op = ops[random(1, #ops)]; local x, y = random(1, 9) repeat y = random(1, 9); until x ~= y; local answer; if op == '+' then answer = x + y; elseif op == '-' then if x < y then -- Avoid negative numbers x, y = y, x; end answer = x - y; end local challenge = hmac_sha1(secret, answer, true); return captcha_tpl.apply { op = op, x = x, y = y, challenge = challenge; }; end function verify_captcha(request, form, callback) if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then callback(true); else callback(false, "Captcha verification failed"); end end end function generate_page(event, display_options) local request, response = event.request, event.response; response.headers.content_type = "text/html; charset=utf-8"; return render(register_tpl, { path = request.path; hostname = module.host; notice = display_options and display_options.register_error or ""; captcha = generate_captcha(display_options); }) end function register_user(form, origin) local prepped_username = nodeprep(form.username); if not prepped_username then return nil, "Username contains forbidden characters"; end if #prepped_username == 0 then return nil, "The username field was empty"; end if usermanager.user_exists(prepped_username, module.host) then return nil, "Username already taken"; end local registering = { username = prepped_username , host = module.host, allowed = true } module:fire_event("user-registering", registering); if not registering.allowed then return nil, "Registration not allowed"; end local ok, err = usermanager.create_user(prepped_username, form.password, module.host); if ok then local extra_data = {}; for field in pairs(extra_fields) do local field_value = form[field]; if field_value and #field_value > 0 then extra_data[field] = field_value; end end if next(extra_data) ~= nil then datamanager.store(prepped_username, module.host, "account_details", extra_data); end module:fire_event("user-registered", { username = prepped_username, host = module.host, source = module.name, ip = origin.conn:ip(), }); end return ok, err; end function generate_success(event, form) return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host }); end function generate_register_response(event, form, ok, err) local message; event.response.headers.content_type = "text/html; charset=utf-8"; if ok then return generate_success(event, form); else return generate_page(event, { register_error = err }); end end function handle_form(event) local request, response = event.request, event.response; local form = http.formdecode(request.body); verify_captcha(request, form, function (ok, err) if ok then local register_ok, register_err = register_user(form, request); response:send(generate_register_response(event, form, register_ok, register_err)); else response:send(generate_page(event, { register_error = err })); end end); return true; -- Leave connection open until we respond above end module:provides("http", { route = { GET = generate_page; ["GET /"] = generate_page; POST = handle_form; ["POST /"] = handle_form; }; });
mit
devFRIND/TAEMNEW
plugins/getfial.lua
2
1034
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY TAEMNEW ▀▄ ▄▀ ▀▄ ▄▀ BY TAEMNEW () ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY TAEMNEW ▀▄ ▄▀ ▀▄ ▄▀ get file : جلب ملف ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function run(msg, matches) if matches[1] == "جلب ملف" then local file = matches[2] if is_sudo(msg) then --sudo only ! local receiver = get_receiver(msg) send_document(receiver, "./plugins/"..file..".lua", ok_cb, false) else return nil end end end return { patterns = { "^(جلب ملف) (.*)$" }, run = run }
gpl-2.0
eugeneia/snabbswitch
lib/ljsyscall/syscall/linux/ioctl.lua
5
10292
-- ioctls, filling in as needed -- note there are some architecture dependent values local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local abi = require "syscall.abi" local s, t = types.s, types.t local strflag = require "syscall.helpers".strflag local arch = require("syscall.linux." .. abi.arch .. ".ioctl") local bit = require "syscall.bit" local band = bit.band local function bor(...) local r = bit.bor(...) if r < 0 then r = r + 4294967296 end -- TODO see note in NetBSD return r end local lshift = bit.lshift local rshift = bit.rshift -- these can vary by architecture local IOC = arch.IOC or { SIZEBITS = 14, DIRBITS = 2, NONE = 0, WRITE = 1, READ = 2, } IOC.READWRITE = IOC.READ + IOC.WRITE IOC.NRBITS = 8 IOC.TYPEBITS = 8 IOC.NRMASK = lshift(1, IOC.NRBITS) - 1 IOC.TYPEMASK = lshift(1, IOC.TYPEBITS) - 1 IOC.SIZEMASK = lshift(1, IOC.SIZEBITS) - 1 IOC.DIRMASK = lshift(1, IOC.DIRBITS) - 1 IOC.NRSHIFT = 0 IOC.TYPESHIFT = IOC.NRSHIFT + IOC.NRBITS IOC.SIZESHIFT = IOC.TYPESHIFT + IOC.TYPEBITS IOC.DIRSHIFT = IOC.SIZESHIFT + IOC.SIZEBITS local function ioc(dir, ch, nr, size) if type(ch) == "string" then ch = ch:byte() end return bor(lshift(dir, IOC.DIRSHIFT), lshift(ch, IOC.TYPESHIFT), lshift(nr, IOC.NRSHIFT), lshift(size, IOC.SIZESHIFT)) end local singletonmap = { int = "int1", char = "char1", uint = "uint1", uint32 = "uint32_1", uint64 = "uint64_1", } local function _IOC(dir, ch, nr, tp) if not tp or type(tp) == "number" then return ioc(dir, ch, nr, tp or 0) end local size = s[tp] local singleton = singletonmap[tp] ~= nil tp = singletonmap[tp] or tp return {number = ioc(dir, ch, nr, size), read = dir == IOC.READ or dir == IOC.READWRITE, write = dir == IOC.WRITE or dir == IOC.READWRITE, type = t[tp], singleton = singleton} end -- used to create numbers local _IO = function(ch, nr) return _IOC(IOC.NONE, ch, nr, 0) end local _IOR = function(ch, nr, tp) return _IOC(IOC.READ, ch, nr, tp) end local _IOW = function(ch, nr, tp) return _IOC(IOC.WRITE, ch, nr, tp) end local _IOWR = function(ch, nr, tp) return _IOC(IOC.READWRITE, ch, nr, tp) end -- used to decode ioctl numbers.. local _IOC_DIR = function(nr) return band(rshift(nr, IOC.DIRSHIFT), IOC.DIRMASK) end local _IOC_TYPE = function(nr) return band(rshift(nr, IOC.TYPESHIFT), IOC.TYPEMASK) end local _IOC_NR = function(nr) return band(rshift(nr, IOC.NRSHIFT), IOC.NRMASK) end local _IOC_SIZE = function(nr) return band(rshift(nr, IOC.SIZESHIFT), IOC.SIZEMASK) end -- ...and for the drivers/sound files... IOC.IN = lshift(IOC.WRITE, IOC.DIRSHIFT) IOC.OUT = lshift(IOC.READ, IOC.DIRSHIFT) IOC.INOUT = lshift(bor(IOC.WRITE, IOC.READ), IOC.DIRSHIFT) local IOCSIZE_MASK = lshift(IOC.SIZEMASK, IOC.SIZESHIFT) local IOCSIZE_SHIFT = IOC.SIZESHIFT -- VFIO driver writer decided not to use standard IOR/IOW alas local function vfio(dir, nr, tp) local ch = ";" nr = nr + 100 -- vfio base dir = IOC[string.upper(dir)] local io = _IOC(dir, ch, nr, tp) if type(io) == "number" then return io end -- if just IO, not return io.number = ioc(IOC.NONE, ch, nr, 0) -- number encode nothing, but we want to know anyway return io end local ioctl = strflag { -- termios, non standard values generally 0x54 = 'T' TCGETS = {number = 0x5401, read = true, type = "termios"}, TCSETS = 0x5402, TCSETSW = 0x5403, TCSETSF = 0x5404, TCSBRK = 0x5409, -- takes literal number TCXONC = 0x540A, TCFLSH = 0x540B, -- takes literal number TIOCEXCL = 0x540C, TIOCNXCL = 0x540D, TIOCSCTTY = 0x540E, TIOCGPGRP = 0x540F, TIOCSPGRP = 0x5410, TIOCOUTQ = 0x5411, TIOCSTI = 0x5412, TIOCGWINSZ = {number = 0x5413, read = true, type = "winsize"}, TIOCSWINSZ = {number = 0x5414, write = true, type = "winsize"}, TIOCMGET = 0x5415, TIOCMBIS = 0x5416, TIOCMBIC = 0x5417, TIOCMSET = 0x5418, TIOCGSOFTCAR = 0x5419, TIOCSSOFTCAR = 0x541A, FIONREAD = 0x541B, TIOCLINUX = 0x541C, TIOCCONS = 0x541D, TIOCGSERIAL = 0x541E, TIOCSSERIAL = 0x541F, TIOCPKT = 0x5420, FIONBIO = 0x5421, TIOCNOTTY = 0x5422, TIOCSETD = 0x5423, TIOCGETD = 0x5424, TCSBRKP = 0x5425, TIOCSBRK = 0x5427, TIOCCBRK = 0x5428, TIOCGSID = 0x5429, TCGETS2 = _IOR('T', 0x2A, "termios2"), TCSETS2 = _IOW('T', 0x2B, "termios2"), TCSETSW2 = _IOW('T', 0x2C, "termios2"), TCSETSF2 = _IOW('T', 0x2D, "termios2"), TIOCGPTN = _IOR('T', 0x30, "uint"), TIOCSPTLCK = _IOW('T', 0x31, "int"), TIOCGDEV = _IOR('T', 0x32, "uint"), TCGETX = 0x5432, TCSETX = 0x5433, TCSETXF = 0x5434, TCSETXW = 0x5435, TIOCSIG = _IOW('T', 0x36, "int"), TIOCVHANGUP = 0x5437, FIONCLEX = 0x5450, FIOCLEX = 0x5451, FIOASYNC = 0x5452, TIOCSERCONFIG = 0x5453, TIOCSERGWILD = 0x5454, TIOCSERSWILD = 0x5455, TIOCGLCKTRMIOS = 0x5456, TIOCSLCKTRMIOS = 0x5457, TIOCSERGSTRUCT = 0x5458, TIOCSERGETLSR = 0x5459, TIOCSERGETMULTI = 0x545A, TIOCSERSETMULTI = 0x545B, TIOCMIWAIT = 0x545C, TIOCGICOUNT = 0x545D, FIOQSIZE = 0x5460, -- socket ioctls from linux/sockios.h - for many of these you can use netlink instead FIOSETOWN = 0x8901, SIOCSPGRP = 0x8902, FIOGETOWN = 0x8903, SIOCGPGRP = 0x8904, SIOCATMARK = 0x8905, SIOCGSTAMP = 0x8906, SIOCGSTAMPNS = 0x8907, SIOCADDRT = 0x890B, SIOCDELRT = 0x890C, SIOCRTMSG = 0x890D, SIOCGIFFLAGS = 0x8913, SIOCSIFFLAGS = 0x8914, SIOCGIFMTU = 0x8921, SIOCSIFMTU = 0x8922, SIOCGIFHWADDR = 0x8927, SIOCGIFINDEX = 0x8933, SIOCDARP = 0x8953, SIOCGARP = 0x8954, SIOCSARP = 0x8955, SIOCBRADDBR = 0x89a0, SIOCBRDELBR = 0x89a1, SIOCBRADDIF = 0x89a2, SIOCBRDELIF = 0x89a3, -- event system EVIOCGVERSION = _IOR('E', 0x01, "int"), EVIOCGID = _IOR('E', 0x02, "input_id"), EVIOCGREP = _IOR('E', 0x03, "uint2"), EVIOCSREP = _IOW('E', 0x03, "uint2"), EVIOCGKEYCODE = _IOR('E', 0x04, "uint2"), EVIOCGKEYCODE_V2 = _IOR('E', 0x04, "input_keymap_entry"), EVIOCSKEYCODE = _IOW('E', 0x04, "uint2"), EVIOCSKEYCODE_V2 = _IOW('E', 0x04, "input_keymap_entry"), EVIOCGNAME = function(len) return _IOC(IOC.READ, 'E', 0x06, len) end, EVIOCGPHYS = function(len) return _IOC(IOC.READ, 'E', 0x07, len) end, EVIOCGUNIQ = function(len) return _IOC(IOC.READ, 'E', 0x08, len) end, EVIOCGPROP = function(len) return _IOC(IOC.READ, 'E', 0x09, len) end, EVIOCGKEY = function(len) return _IOC(IOC.READ, 'E', 0x18, len) end, EVIOCGLED = function(len) return _IOC(IOC.READ, 'E', 0x19, len) end, EVIOCGSND = function(len) return _IOC(IOC.READ, 'E', 0x1a, len) end, EVIOCGSW = function(len) return _IOC(IOC.READ, 'E', 0x1b, len) end, EVIOCGBIT = function(ev, len) return _IOC(IOC.READ, 'E', 0x20 + ev, len) end, EVIOCGABS = function(abs) return _IOR('E', 0x40 + abs, "input_absinfo") end, EVIOCSABS = function(abs) return _IOW('E', 0xc0 + abs, "input_absinfo") end, EVIOCSFF = _IOC(IOC.WRITE, 'E', 0x80, "ff_effect"), EVIOCRMFF = _IOW('E', 0x81, "int"), EVIOCGEFFECTS = _IOR('E', 0x84, "int"), EVIOCGRAB = _IOW('E', 0x90, "int"), -- input devices UI_DEV_CREATE = _IO ('U', 1), UI_DEV_DESTROY = _IO ('U', 2), UI_SET_EVBIT = _IOW('U', 100, "int"), UI_SET_KEYBIT = _IOW('U', 101, "int"), -- tun/tap TUNSETNOCSUM = _IOW('T', 200, "int"), TUNSETDEBUG = _IOW('T', 201, "int"), TUNSETIFF = _IOW('T', 202, "int"), TUNSETPERSIST = _IOW('T', 203, "int"), TUNSETOWNER = _IOW('T', 204, "int"), TUNSETLINK = _IOW('T', 205, "int"), TUNSETGROUP = _IOW('T', 206, "int"), TUNGETFEATURES = _IOR('T', 207, "uint"), TUNSETOFFLOAD = _IOW('T', 208, "uint"), TUNSETTXFILTER = _IOW('T', 209, "uint"), TUNGETIFF = _IOR('T', 210, "uint"), TUNGETSNDBUF = _IOR('T', 211, "int"), TUNSETSNDBUF = _IOW('T', 212, "int"), TUNATTACHFILTER= _IOW('T', 213, "sock_fprog"), TUNDETACHFILTER= _IOW('T', 214, "sock_fprog"), TUNGETVNETHDRSZ= _IOR('T', 215, "int"), TUNSETVNETHDRSZ= _IOW('T', 216, "int"), TUNSETQUEUE = _IOW('T', 217, "int"), -- from linux/vhost.h VHOST_VIRTIO 0xAF VHOST_GET_FEATURES = _IOR(0xAF, 0x00, "uint64"), VHOST_SET_FEATURES = _IOW(0xAF, 0x00, "uint64"), VHOST_SET_OWNER = _IO(0xAF, 0x01), VHOST_RESET_OWNER = _IO(0xAF, 0x02), VHOST_SET_MEM_TABLE = _IOW(0xAF, 0x03, "vhost_memory"), VHOST_SET_LOG_BASE = _IOW(0xAF, 0x04, "uint64"), VHOST_SET_LOG_FD = _IOW(0xAF, 0x07, "int"), VHOST_SET_VRING_NUM = _IOW(0xAF, 0x10, "vhost_vring_state"), VHOST_SET_VRING_ADDR = _IOW(0xAF, 0x11, "vhost_vring_addr"), VHOST_SET_VRING_BASE = _IOW(0xAF, 0x12, "vhost_vring_state"), VHOST_GET_VRING_BASE = _IOWR(0xAF, 0x12, "vhost_vring_state"), VHOST_SET_VRING_KICK = _IOW(0xAF, 0x20, "vhost_vring_file"), VHOST_SET_VRING_CALL = _IOW(0xAF, 0x21, "vhost_vring_file"), VHOST_SET_VRING_ERR = _IOW(0xAF, 0x22, "vhost_vring_file"), VHOST_NET_SET_BACKEND= _IOW(0xAF, 0x30, "vhost_vring_file"), -- from linux/vfio.h type is ';' base is 100 VFIO_GET_API_VERSION = vfio('NONE', 0), VFIO_CHECK_EXTENSION = vfio('WRITE', 1, "uint32"), -- allow user defined ioctls _IO = _IO, _IOR = _IOR, _IOW = _IOW, _IOWR = _IOWR, } local override = arch.ioctl or {} if type(override) == "function" then override = override(_IO, _IOR, _IOW, _IOWR) end for k, v in pairs(override) do ioctl[k] = v end -- allow names for types in table ioctls for k, v in pairs(ioctl) do if type(v) == "table" and type(v.type) == "string" then v.type = t[v.type] end end -- alternate names ioctl.TIOCINQ = ioctl.FIONREAD return ioctl end return {init = init}
apache-2.0
DarkstarProject/darkstar
scripts/globals/mobskills/pw_acheron_flame.lua
11
1631
--------------------------------------------- -- Acheron Flame -- -- Description: Deals severe Fire damage to enemies within an area of effect. Additional effect: Burn -- Type: Magical -- -- -- Utsusemi/Blink absorb: Wipes shadows -- Range: 20' radial -- Notes: Only used when a cerberus's health is 25% or lower (may not be the case for Orthrus). The burn effect takes off upwards of 20 HP per tick. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId() if (mobSkin == 1793) then return 0 else return 1 end end function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.BURN local statmod = dsp.mod.INT local element = mob:getStatusEffectElement(typeEffect) local resist = applyPlayerResistance(mob,typeEffect,target,mob:getStat(statmod)-target:getStat(statmod),0,element) local power = ((resist * 10) - 5) * math.random(1,2) + 19 -- makes dot damage between 20 - 28, based off resistance and random variable. local dmgmod = 3 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*6,dsp.magic.ele.FIRE,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.FIRE,MOBPARAM_WIPE_SHADOWS) MobStatusEffectMove(mob, target, typeEffect, power, 3, 60) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.FIRE) return dmg end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Windurst_Waters_[S]/npcs/Kolin-Olin.lua
13
1062
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Kolin-Olin -- Type: Standard NPC -- @zone: 94 -- @pos 9.981 -2.478 33.786 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0132); 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
Fenix-XI/Fenix
scripts/zones/Arrapago_Reef/npcs/_jic.lua
27
3547
----------------------------------- -- Area: Arrapago Reef -- Door: Runic Seal -- @pos 36 -10 620 54 ----------------------------------- package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/besieged"); require("scripts/zones/Arrapago_Reef/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(ILRUSI_ASSAULT_ORDERS)) then local assaultid = player:getCurrentAssault(); local recommendedLevel = getRecommendedAssaultLevel(assaultid); local armband = 0; if (player:hasKeyItem(ASSAULT_ARMBAND)) then armband = 1; end player:startEvent(0x00DB, assaultid, -4, 0, recommendedLevel, 2, armband); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local assaultid = player:getCurrentAssault(); local cap = bit.band(option, 0x03); if (cap == 0) then cap = 99; elseif (cap == 1) then cap = 70; elseif (cap == 2) then cap = 60; else cap = 50; end player:setVar("AssaultCap", cap); local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if (not (v:hasKeyItem(ILRUSI_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then player:messageText(target,MEMBER_NO_REQS, false); player:instanceEntry(target,1); return; elseif (v:getZone() == player:getZone() and v:checkDistance(player) > 50) then player:messageText(target,MEMBER_TOO_FAR, false); player:instanceEntry(target,1); return; end end end player:createInstance(player:getCurrentAssault(), 55); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x6C or (csid == 0xDB and option == 4)) then player:setPos(0,0,0,0,55); end end; ----------------------------------- -- onInstanceLoaded ----------------------------------- function onInstanceCreated(player,target,instance) if (instance) then instance:setLevelCap(player:getVar("AssaultCap")); player:setVar("AssaultCap", 0); player:setInstance(instance); player:instanceEntry(target,4); player:delKeyItem(ILRUSI_ASSAULT_ORDERS); player:delKeyItem(ASSAULT_ARMBAND); if (party ~= nil) then for i,v in ipairs(party) do if v:getID() ~= player:getID() and v:getZone() == player:getZone() then v:setInstance(instance); v:startEvent(0x6C, 2); v:delKeyItem(ILRUSI_ASSAULT_ORDERS); end end end else player:messageText(target,CANNOT_ENTER, false); player:instanceEntry(target,3); end end;
gpl-3.0
sprcpu/F80-V3.0
QrCode.lua
1
1271
local function get_hex(str) local colors = { red = "r", blue = "b", green = "g", yellow = "y", purple = "f0f", white = "w", black = "b", gray = "g" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { patterns = { '^[Qq]rcode "(%w+)" "(%w+)" (.+)$', "^[Qq]rcode (.+)$" }, run = run }
gpl-2.0
Fenix-XI/Fenix
scripts/zones/Port_Windurst/npcs/Odilia.lua
13
1044
----------------------------------- -- Area: Port Windurst -- NPC: Odilia -- Type: Standard NPC -- @zone: 240 -- @pos 78.801 -6 118.653 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0121); 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
Jezza/Lava
src/test/resources/speed/nbody.lua
1
3468
-- The Great Computer Language Shootout -- http://shootout.alioth.debian.org/ -- contributed by Isaac Gouy, tuned by Mike Pall local sqrt = math.sqrt local PI = 3.141592653589793 local SOLAR_MASS = 4 * PI * PI local DAYS_PER_YEAR = 365.24 local Jupiter = { x = 4.84143144246472090e+00 ,y = -1.16032004402742839e+00 ,z = -1.03622044471123109e-01 ,vx = 1.66007664274403694e-03 * DAYS_PER_YEAR ,vy = 7.69901118419740425e-03 * DAYS_PER_YEAR ,vz = -6.90460016972063023e-05 * DAYS_PER_YEAR ,mass = 9.54791938424326609e-04 * SOLAR_MASS } local Saturn = { x = 8.34336671824457987e+00 ,y = 4.12479856412430479e+00 ,z = -4.03523417114321381e-01 ,vx = -2.76742510726862411e-03 * DAYS_PER_YEAR ,vy = 4.99852801234917238e-03 * DAYS_PER_YEAR ,vz = 2.30417297573763929e-05 * DAYS_PER_YEAR ,mass = 2.85885980666130812e-04 * SOLAR_MASS } local Uranus = { x = 1.28943695621391310e+01 ,y = -1.51111514016986312e+01 ,z = -2.23307578892655734e-01 ,vx = 2.96460137564761618e-03 * DAYS_PER_YEAR ,vy = 2.37847173959480950e-03 * DAYS_PER_YEAR ,vz = -2.96589568540237556e-05 * DAYS_PER_YEAR ,mass = 4.36624404335156298e-05 * SOLAR_MASS } local Neptune = { x = 1.53796971148509165e+01 ,y = -2.59193146099879641e+01 ,z = 1.79258772950371181e-01 ,vx = 2.68067772490389322e-03 * DAYS_PER_YEAR ,vy = 1.62824170038242295e-03 * DAYS_PER_YEAR ,vz = -9.51592254519715870e-05 * DAYS_PER_YEAR ,mass = 5.15138902046611451e-05 * SOLAR_MASS } local Sun = { x = 0, y = 0, z = 0, vx = 0, vy = 0, vz = 0, mass = SOLAR_MASS } local function advance(bodies, nbody, dt) for i=1,nbody do local bi = bodies[i] local bix, biy, biz, bimass = bi.x, bi.y, bi.z, bi.mass local bivx, bivy, bivz = bi.vx, bi.vy, bi.vz for j=i+1,nbody do local bj = bodies[j] local dx, dy, dz = bix-bj.x, biy-bj.y, biz-bj.z local distance = sqrt(dx*dx + dy*dy + dz*dz) local mag = dt / (distance * distance * distance) local bim, bjm = bimass*mag, bj.mass*mag bivx = bivx - (dx * bjm) bivy = bivy - (dy * bjm) bivz = bivz - (dz * bjm) bj.vx = bj.vx + (dx * bim) bj.vy = bj.vy + (dy * bim) bj.vz = bj.vz + (dz * bim) end bi.vx = bivx bi.vy = bivy bi.vz = bivz end for i=1,nbody do local bi = bodies[i] bi.x = bi.x + (dt * bi.vx) bi.y = bi.y + (dt * bi.vy) bi.z = bi.z + (dt * bi.vz) end end local function energy(bodies, nbody) local e = 0 for i=1,nbody do local bi = bodies[i] local vx, vy, vz, bim = bi.vx, bi.vy, bi.vz, bi.mass e = e + (0.5 * bim * (vx*vx + vy*vy + vz*vz)) for j=i+1,nbody do local bj = bodies[j] local dx, dy, dz = bi.x-bj.x, bi.y-bj.y, bi.z-bj.z local distance = sqrt(dx*dx + dy*dy + dz*dz) e = e - ((bim * bj.mass) / distance) end end return e end local function offsetMomentum(b, nbody) local px, py, pz = 0, 0, 0 for i=1,nbody do local bi = b[i] local bim = bi.mass px = px + (bi.vx * bim) py = py + (bi.vy * bim) pz = pz + (bi.vz * bim) end b[1].vx = -px / SOLAR_MASS b[1].vy = -py / SOLAR_MASS b[1].vz = -pz / SOLAR_MASS end local N = tonumber((...)) or 1e6 local bodies = { Sun, Jupiter, Saturn, Uranus, Neptune } local nbody = #(bodies) offsetMomentum(bodies, nbody) print( string.format("%0.9f",energy(bodies, nbody))) for i=1,N do advance(bodies, nbody, 0.01) end print( string.format("%0.9f",energy(bodies, nbody)))
lgpl-3.0
andreynovikov/maptrek
app/src/main/jni/libtess2/premake4.lua
6
1111
local action = _ACTION or "" solution "libtess2" location ( "Build" ) configurations { "Debug", "Release" } platforms {"native", "x64", "x32"} configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "tess2" language "C" kind "StaticLib" includedirs { "Include", "Source" } files { "Source/*.c" } targetdir("Build") -- more dynamic example project "example" kind "ConsoleApp" language "C" links { "tess2" } files { "Example/example.c", "Contrib/*.c" } includedirs { "Include", "Contrib" } targetdir("Build") configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32" } defines { "NANOVG_GLEW" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" }
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Windurst_Waters/npcs/HomePoint#3.lua
13
1270
----------------------------------- -- Area: Windurst Waters -- NPC: HomePoint#3 -- @pos: 4 -4 -174 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 103); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Windurst_Waters/npcs/Ness_Rugetomal.lua
12
1686
----------------------------------- -- Area: Windurst Waters -- NPC: Ness Rugetomal -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/events/harvest_festivals") require("scripts/globals/shop"); package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NESSRUGETOMALL_SHOP_DIALOG); stock = { 0x112A, 10,1, --Ginger Cookie 0x1137, 727,1, --Carp Sushi 0x1149, 323,1, --Tomato Juice 0x116B, 1656,1, --Nebimonite Bake 0x112D, 14,2, --Cinna-cookie 0x1146, 184,2, --Orange Juice 0x1168, 2070,2, --Boiled Crab 0x119E, 21,3, --Acorn Cookie 0x1118, 108,3, --Meat Jerky 0x119D, 10,3, --Distilled Water 0x11BA, 846,3 --Roast Pipira } showNationShop(player, WINDURST, stock); 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
Giorox/AngelionOT-Repo
data/npc/scripts/cityguard.lua
6
2144
local target = 0 local prevTarget = 0 local maxChaseDistance = 20 local origPos = 0 local lastAttack = 0 local followTimeout = 10 local function isSkulled(cid) if(getCreatureSkullType(cid) >= SKULL_WHITE and isPlayerPzLocked(cid)) then return true end return false end local function goToOrigPos() target = 0 lastAttack = 0 selfFollow(0) doTeleportThing(getNpcCid(), origPos) end local function updateTarget() if(not isPlayer(target)) then goToOrigPos() elseif(not isSkulled(target)) then selfSay("Now, behave in the future.") goToOrigPos() end if(target == 0) then local list = getSpectators(getNpcPos(), 9, 9, false) for i = 1, table.getn(list) do local _target = list[i] if(_target ~= 0) then if(isPlayer(_target) and isSkulled(_target)) then if(not getTilePzInfo(getCreaturePosition(_target))) then if(selfFollow(_target)) then target = _target if(target ~= prevTarget) then selfSay("We do not tolerate people like you here!") end prevTarget = target break end end end end end end end function onCreatureAppear(cid) if(cid == getNpcCid()) then origPos = getNpcPos() end end function onCreatureDisappear(cid) if(cid == target) then goToOrigPos() end end function onCreatureMove(creature, oldPos, newPos) -- end function onThink() updateTarget() if(target == 0) then return end local playerPos = getCreaturePosition(target) local myPos = getNpcPos() if(myPos.z ~= playerPos.z) then goToOrigPos() return end if(math.abs(myPos.x - origPos.x) > maxChaseDistance or math.abs(myPos.y - origPos.y) > maxChaseDistance) then selfSay("I'll catch you next time.") goToOrigPos() return end if(lastAttack == 0) then lastAttack = os.clock() end if(os.clock() - lastAttack > followTimeout) then selfSay("You got me this time, but just wait.") goToOrigPos() return end if((math.abs(playerPos.x - myPos.x) <= 1) and (math.abs(playerPos.y - myPos.y) <= 1)) then doTargetCombatHealth(getNpcCid(), target, COMBAT_LIFEDRAIN, -200, -300, CONST_ME_BLOCKHIT) lastAttack = os.clock() end end
gpl-3.0
kashif/optim
polyinterp.lua
13
6321
local function isreal(x) return x == x end local function isnan(x) return not x == x end local function roots(c) local tol=1e-12 c[torch.lt(torch.abs(c),tol)]=0 local nonzero = torch.ne(c,0) if nonzero:max() == 0 then return 0 end -- first non-zero local _,pos = torch.max(nonzero,1) pos = pos[1] c=c[{ {pos,-1} }] local nz = 0 for i=c:size(1),1,-1 do if c[i] ~= 0 then break else nz = nz + 1 end end c=c[{ {1,c:size(1)-nz} }] local n = c:size(1)-1 if n == 1 then local e = torch.Tensor({{-c[2]/c[1], 0}}) if nz > 0 then return torch.cat(e, torch.zeros(nz, 2), 1) else return e end elseif n > 1 then local A = torch.diag(torch.ones(n-1),-1) A[1] = -c[{ {2,n+1} }]/c[1]; local e = torch.eig(A,'N') if nz > 0 then return torch.cat(e, torch.zeros(nz,2), 1) else return e end else return torch.zeros(nz,2) end end local function real(x) if type(x) == number then return x end return x[{ {} , 1}] end local function imag(x) if type(x) == 'number' then return 0 end if x:nDimension() == 1 then return torch.zeros(x:size(1)) else return x[{ {}, 2}] end end local function polyval(p,x) local pwr = p:size(1) if type(x) == 'number' then local val = 0 p:apply(function(pc) pwr = pwr-1; val = val + pc*x^pwr; return pc end) return val else local val = x.new(x:size(1)) p:apply(function(pc) pwr = pwr-1; val:add(pc,torch.pow(x,pwr)); return pc end) return val end end ---------------------------------------------------------------------- -- Minimum of interpolating polynomial based on function and -- derivative values -- -- ARGS: -- points : N triplets (x,f,g), must be a Tensor -- xmin : min value that brackets minimum (default: min of points) -- xmax : max value that brackets maximum (default: max of points) -- -- RETURN: -- minPos : position of minimum -- function optim.polyinterp(points,xminBound,xmaxBound) -- locals local sqrt = torch.sqrt local mean = torch.mean local Tensor = torch.Tensor local zeros = torch.zeros local max = math.max local min = math.min -- nb of points / order of polynomial local nPoints = points:size(1) local order = nPoints*2-1 -- returned values local minPos -- Code for most common case: -- + cubic interpolation of 2 points w/ function and derivative values for both -- + no xminBound/xmaxBound if nPoints == 2 and order == 3 and not xminBound and not xmaxBound then -- Solution in this case (where x2 is the farthest point): -- d1 = g1 + g2 - 3*(f1-f2)/(x1-x2); -- d2 = sqrt(d1^2 - g1*g2); -- minPos = x2 - (x2 - x1)*((g2 + d2 - d1)/(g2 - g1 + 2*d2)); -- t_new = min(max(minPos,x1),x2); local minVal,minPos = points[{ {},1 }]:min(1) minVal = minVal[1] minPos = minPos[1] local notMinPos = -minPos+3; local d1 = points[{minPos,3}] + points[{notMinPos,3}] - 3*(points[{minPos,2}]-points[{notMinPos,2}]) / (points[{minPos,1}]-points[{notMinPos,1}]); local d2 = sqrt(d1^2 - points[{minPos,3}]*points[{notMinPos,3}]); if isreal(d2) then -- isreal() local t = points[{notMinPos,1}] - (points[{notMinPos,1}] - points[{minPos,1}]) * ((points[{notMinPos,3}] + d2 - d1) / (points[{notMinPos,3}] - points[{minPos,3}] + 2*d2)) minPos = min(max(t,points[{minPos,1}]),points[{notMinPos,1}]) else minPos = mean(points[{{},1}]) end return minPos end -- TODO: get the code below to work! --error('<optim.polyinterp> extrapolation not implemented yet...') -- Compute Bounds of Interpolation Area local xmin = points[{{},1}]:min() local xmax = points[{{},1}]:max() xminBound = xminBound or xmin xmaxBound = xmaxBound or xmax -- Add constraints on function values local A = zeros(nPoints*2,order+1) local b = zeros(nPoints*2,1) for i = 1,nPoints do local constraint = zeros(order+1) for j = order,0,-1 do constraint[order-j+1] = points[{i,1}]^j end A[i] = constraint b[i] = points[{i,2}] end -- Add constraints based on derivatives for i = 1,nPoints do local constraint = zeros(order+1) for j = 1,order do constraint[j] = (order-j+1)*points[{i,1}]^(order-j) end A[nPoints+i] = constraint b[nPoints+i] = points[{i,3}] end -- Find interpolating polynomial local res = torch.gels(b,A) local params = res[{ {1,nPoints*2} }]:squeeze() --print(A) --print(b) --print(params) params[torch.le(torch.abs(params),1e-12)]=0 -- Compute Critical Points local dParams = zeros(order); for i = 1,params:size(1)-1 do dParams[i] = params[i]*(order-i+1) end -- nan/inf? local nans = false if torch.ne(dParams,dParams):max() > 0 or torch.eq(dParams,math.huge):max() > 0 then nans = true end -- for i = 1,dParams:size(1) do -- if dParams[i] ~= dParams[i] or dParams[i] == math.huge then -- nans = true -- break -- end -- end local cp = torch.cat(Tensor{xminBound,xmaxBound},points[{{},1}]) if not nans then local cproots = roots(dParams) local cpi = zeros(cp:size(1),2) cpi[{ {1,cp:size(1)} , 1 }] = cp cp = torch.cat(cpi,cproots,1) end --print(dParams) --print(cp) -- Test Critical Points local fmin = math.huge -- Default to Bisection if no critical points valid: minPos = (xminBound+xmaxBound)/2 --print(minPos,fmin) --print(xminBound,xmaxBound) for i = 1,cp:size(1) do local xCP = cp[{ {i,i} , {} }] --print('xcp=') --print(xCP) local ixCP = imag(xCP)[1] local rxCP = real(xCP)[1] if ixCP == 0 and rxCP >= xminBound and rxCP <= xmaxBound then local fCP = polyval(params,rxCP) --print('fcp=') --print(fCP) --print(fCP < fmin) if fCP < fmin then minPos = rxCP fmin = fCP --print('u',minPos,fmin) end --print('v',minPos,fmin) end end return minPos,fmin end
bsd-3-clause
Fenix-XI/Fenix
scripts/zones/Port_San_dOria/npcs/_6g7.lua
13
1116
----------------------------------- -- Area: Port San d'Oria -- NPC: Door: Arrivals Entrance -- @zone 232 -- @pos -24 -8 15 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getZPos() >= 12) then player:startEvent(0x0206); end return 1; 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
Fenix-XI/Fenix
scripts/zones/Dynamis-Windurst/mobs/Xoo_Kaza_the_Solemn.lua
7
1032
----------------------------------- -- Area: Dynamis Windurst -- NPC: Xoo Kaza the Solemn -- Boss Trigger for RDM NM ----------------------------------- ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local bossTrigger = GetServerVariable("[DynaWindurst]Boss_Trigger"); if (bossTrigger == 0 or bossTrigger == 1 or bossTrigger == 4 or bossTrigger == 5) then SetServerVariable("[DynaWindurst]Boss_Trigger",bossTrigger + 2); SpawnMob(17543586); -- 110 SpawnMob(17543587); -- 111 end -- If 3 first boss trigger are killed -> pop the last trigger if (GetServerVariable("[DynaWindurst]Boss_Trigger") == 7) then SpawnMob(17543590); -- 114 SpawnMob(17543591); -- 115 SpawnMob(17543592); -- 116 SetServerVariable("[DynaWindurst]Boss_Trigger",8); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Bastok_Mines/npcs/Tami.lua
12
2870
----------------------------------- -- Area: Bastok Mines -- NPC: Tami -- Starts & Finishes Repeatable Quest: Groceries -- Note: Repeatable until proper completion ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ViewedNote = player:getVar("GroceriesViewedNote"); if (ViewedNote == 1) then count = trade:getItemCount(); MeatJerky = trade:hasItemQty(4376,1); if (MeatJerky == true and count == 1) then player:startEvent(0x0071); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Groceries = player:getQuestStatus(BASTOK,GROCERIES); GroceriesVar = player:getVar("Groceries"); if (Groceries == QUEST_COMPLETED) then player:startEvent(0x0073); elseif (Groceries == QUEST_AVAILABLE or GroceriesVar == 0) then player:startEvent(0x006e); elseif (GroceriesVar == 1) then player:showText(npc,10510); elseif (GroceriesVar == 2) then player:startEvent(0x0070); 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); if (csid == 0x006e) then Groceries = player:getQuestStatus(BASTOK,GROCERIES); if (Groceries == QUEST_AVAILABLE) then player:addQuest(BASTOK,GROCERIES); end player:addKeyItem(0x98); player:messageSpecial(KEYITEM_OBTAINED,0x98); player:setVar("Groceries",1); elseif (csid == 0x0070) then player:addFame(BASTOK,8); player:setVar("Groceries",0); player:addGil(GIL_RATE*10); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10); elseif (csid == 0x0071) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:tradeComplete(); player:setVar("Groceries",0); player:setVar("GroceriesViewedNote",0); player:completeQuest(BASTOK,GROCERIES); player:addFame(BASTOK,75); player:addItem(13594); player:messageSpecial(ITEM_OBTAINED,13594); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13594); end end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Northern_San_dOria/npcs/Coullene.lua
13
1581
----------------------------------- -- Area: Northern San d'Oria -- NPC: Coullene -- Type: Involved in Quest (Flyers for Regine) -- @zone: 231 -- @pos 146.420 0.000 127.601 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_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 and player:getVar("tradeCoulene") == 0) then player:messageSpecial(COULLENE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeCoulene",1); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); elseif (player:getVar("tradeCoulene") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,COULLENE_DIALOG); 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
Fenix-XI/Fenix
scripts/zones/Al_Zahbi/npcs/Gaweesh.lua
13
1044
----------------------------------- -- Area: Al Zahbi -- NPC: Gaweesh -- Type: Najelith's Attendant -- @zone: 48 -- @pos -64.537 -8 37.928 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0102); 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
Fenix-XI/Fenix
scripts/zones/Riverne-Site_A01/npcs/HomePoint#1.lua
27
1258
----------------------------------- -- Area: Riverne-Site A01 -- NPC: HomePoint#1 -- @pos ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 84); 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 == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Arrapago_Reef/npcs/Runic_Portal.lua
9
1302
----------------------------------- -- Area: Arrapago Reef -- NPC: Runic Portal -- Arrapago Reef Teleporter Back to Aht Urgan Whitegate -- !pos 15 -7 627 54 ----------------------------------- local ID = require("scripts/zones/Arrapago_Reef/IDs") ----------------------------------- require("scripts/globals/besieged") require("scripts/globals/missions") require("scripts/globals/teleports") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if player:getCurrentMission(TOAU) == dsp.mission.id.toau.IMMORTAL_SENTRIES and player:getCharVar("AhtUrganStatus") == 1 then player:startEvent(111) elseif player:getCurrentMission(TOAU) > dsp.mission.id.toau.IMMORTAL_SENTRIES then if dsp.besieged.hasRunicPortal(player, dsp.teleport.runic_portal.ILRUSI) then player:startEvent(109) else player:startEvent(111) end else player:messageSpecial(ID.text.RESPONSE) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if option == 1 then if csid == 111 then dsp.besieged.addRunicPortal(player, dsp.teleport.runic_portal.ILRUSI) end dsp.teleport.toChamberOfPassage(player) end end
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/serving_of_karni_yarik.lua
11
1362
----------------------------------------- -- ID: 5588 -- Item: serving_of_karni_yarik -- Food Effect: 30Min, All Races ----------------------------------------- -- Agility 3 -- Vitality -1 -- Attack % 20 (cap 65) -- Ranged Attack % 20 (cap 65) -- Evasion +6 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5588) end function onEffectGain(target, effect) target:addMod(dsp.mod.AGI, 3) target:addMod(dsp.mod.VIT, -1) target:addMod(dsp.mod.FOOD_ATTP, 20) target:addMod(dsp.mod.FOOD_ATT_CAP, 65) target:addMod(dsp.mod.FOOD_RATTP, 20) target:addMod(dsp.mod.FOOD_RATT_CAP, 65) target:addMod(dsp.mod.EVA, 6) end function onEffectLose(target, effect) target:delMod(dsp.mod.AGI, 3) target:delMod(dsp.mod.VIT, -1) target:delMod(dsp.mod.FOOD_ATTP, 20) target:delMod(dsp.mod.FOOD_ATT_CAP, 65) target:delMod(dsp.mod.FOOD_RATTP, 20) target:delMod(dsp.mod.FOOD_RATT_CAP, 65) target:delMod(dsp.mod.EVA, 6) end
gpl-3.0
grilofw/grilo-plugins
src/lua-factory/sources/grl-spotify-cover.lua
3
2524
--[[ * Copyright (C) 2015 Bastien Nocera. * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-spotify-cover", name = "Spotify Cover", description = "a source for music covers", supported_keys = { 'thumbnail' }, supported_media = { 'audio' }, resolve_keys = { ["type"] = "audio", required = { "artist", "album" }, }, tags = { 'music', 'net:internet' }, } ------------------ -- Source utils -- ------------------ SPOTIFY_SEARCH_ALBUM = 'https://api.spotify.com/v1/search?q=album:%s+artist:%s&type=album&limit=1' --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve() local url, req local artist, title req = grl.get_media_keys() if not req or not req.artist or not req.album or #req.artist == 0 or #req.album == 0 then grl.callback() return end -- Prepare artist and title strings to the url artist = grl.encode(req.artist) album = grl.encode(req.album) url = string.format(SPOTIFY_SEARCH_ALBUM, album, artist) grl.fetch(url, fetch_page_cb) end --------------- -- Utilities -- --------------- function fetch_page_cb(result) local json = {} if not result then grl.callback() return end json = grl.lua.json.string_to_table(result) if not json or not json.albums or json.albums.total == 0 or not json.albums.items or not #json.albums.items or not json.albums.items[1].images then grl.callback() return end local media = {} media.thumbnail = {} for i, item in ipairs(json.albums.items[1].images) do table.insert(media.thumbnail, item.url) end grl.callback(media, 0) end
lgpl-2.1
devFRIND/TAEMNEW
plugins/help4.lua
2
1866
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY TAEMNEW ▀▄ ▄▀ ▀▄ ▄▀ BY TAEMNEW (@illOlli) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY TAEMNEW ▀▄ ▄▀ ▀▄ ▄▀ مساعدة4 ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do function bakury(msg, matches) local reply_id = msg['id'] local S = [[ 📍💭 اوامر فتح وقفل الميديا 🀄️ ❄️"قفل / فتح" الفيديو :التحكم بالفيديو داخل المجموعه). ❄️"قفل / فتح" الصوت :التحكم بالصوت داخل المجموعه). ❄️"قفل / فتح" الصور :التحكم بالصور داخل المجموعه) ❄️"قفل / فتح" الملصقات :فتح وقفل الملصقات في المجموعه) ❄️"قفل / فتح" الجماعيه :التحكم بالجماعيه داخل المجموعه) ❄️"قفل / فتح" الصور المتحركه : فتح وقفل الملصقات المتحركه) ـ🔸➖🔹➖🔸➖🔹➖🔸ـ 📍💭 اوامر اضافيه 🔥صوره : ↭↜ (لتحويل الملصق الى صوره) 🔥ملصق : ↭↜ (لتحويل الصوره الى ملصق) ➖💎➖💎➖💎➖💎➖💎➖💎➖💎 💯-ĐEV💀: @illOlli 💯-ĐEV BOT: @Twsl_devbot 💯-ĐEV Ϲḫ₳ͷͷєℓ💀: ]] reply_msg(reply_id, S, ok_cb, false) end return { description = "Help list", usage = "Help list", patterns = { "^(م4)$", }, run = BAKER } end
gpl-2.0
DarkstarProject/darkstar
scripts/zones/Port_Jeuno/npcs/Zuah_Lepahnyu.lua
12
4213
----------------------------------- -- Area: Port Jeuno -- NPC: ZuahLepahnyu -- Title Change NPC -- !pos 0 0 8 246 ----------------------------------- require("scripts/globals/titles") ----------------------------------- local eventId = 330 local titleInfo = { { cost = 200, title = { dsp.title.VISITOR_TO_ABYSSEA, dsp.title.FRIEND_OF_ABYSSEA, dsp.title.WARRIOR_OF_ABYSSEA, dsp.title.STORMER_OF_ABYSSEA, dsp.title.DEVASTATOR_OF_ABYSSEA, dsp.title.HERO_OF_ABYSSEA, dsp.title.CHAMPION_OF_ABYSSEA, dsp.title.CONQUEROR_OF_ABYSSEA, dsp.title.SAVIOR_OF_ABYSSEA, }, }, { cost = 300, title = { dsp.title.GOLDWING_SQUASHER, dsp.title.SILAGILITH_DETONATOR, dsp.title.SURTR_SMOTHERER, dsp.title.DREYRUK_PREDOMINATOR, dsp.title.SAMURSK_VITIATOR, }, }, { cost = 400, title = { dsp.title.YAANEI_CRASHER, dsp.title.KUTHAREI_UNHORSER, dsp.title.SIPPOY_CAPTURER, dsp.title.RANI_DECROWNER, dsp.title.ORTHRUS_DECAPITATOR, dsp.title.DRAGUA_SLAYER, dsp.title.BENNU_DEPLUMER, dsp.title.HEDJEDJET_DESTINGER, dsp.title.CUIJATENDER_DESICCATOR, dsp.title.BRULO_EXTINGUISHER, dsp.title.PANTOKRATOR_DISPROVER, dsp.title.APADEMAK_ANNIHILATOR, dsp.title.ISGEBIND_DEFROSTER, dsp.title.RESHEPH_ERADICATOR, dsp.title.EMPOUSA_EXPURGATOR, dsp.title.INDRIK_IMMOLATOR, dsp.title.OGOPOGO_OVERTURNER, dsp.title.RAJA_REGICIDE, dsp.title.ALFARD_DETOXIFIER, dsp.title.AZDAJA_ABOLISHER, dsp.title.AMPHITRITE_SHUCKER, dsp.title.FUATH_PURIFIER, dsp.title.KILLAKRIQ_EXCORIATOR, dsp.title.MAERE_BESTIRRER, dsp.title.WYRM_GOD_DEFIER, }, }, { cost = 500, title = { dsp.title.TITLACAUAN_DISMEMBERER, dsp.title.SMOK_DEFOGGER, dsp.title.AMHULUK_INUNDATER, dsp.title.PULVERIZER_DISMANTLER, dsp.title.DURINN_DECEIVER, dsp.title.KARKADANN_EXOCULATOR, dsp.title.TEMENOS_EMANCIPATOR, dsp.title.APOLLYON_RAZER, dsp.title.UMAGRHK_MANEMANGLER, }, }, { cost = 600, title = { dsp.title.KARKINOS_CLAWCRUSHER, dsp.title.CARABOSSE_QUASHER, dsp.title.OVNI_OBLITERATOR, dsp.title.RUMINATOR_CONFOUNDER, dsp.title.FISTULE_DRAINER, dsp.title.TURUL_GROUNDER, dsp.title.BLOODEYE_BANISHER, dsp.title.SATIATOR_DEPRIVER, dsp.title.CHLORIS_UPROOTER, dsp.title.MYRMECOLEON_TAMER, dsp.title.GLAVOID_STAMPEDER, dsp.title.USURPER_DEPOSER, dsp.title.ULHUADSHI_DESICCATOR, dsp.title.ITZPAPALOTL_DECLAWER, dsp.title.SOBEK_MUMMIFIER, dsp.title.CIREINCROIN_HARPOONER, dsp.title.BUKHIS_TETHERER, dsp.title.SEDNA_TUSKBREAKER, dsp.title.CLEAVER_DISMANTLER, dsp.title.EXECUTIONER_DISMANTLER, dsp.title.SEVERER_DISMANTLER, }, }, { cost = 700, title = { dsp.title.HADHAYOSH_HALTERER, dsp.title.BRIAREUS_FELLER, dsp.title.ECCENTRICITY_EXPUNGER, dsp.title.KUKULKAN_DEFANGER, dsp.title.IRATHAM_CAPTURER, dsp.title.LACOVIE_CAPSIZER, dsp.title.LUSCA_DEBUNKER, dsp.title.TRISTITIA_DELIVERER, dsp.title.KETEA_BEACHER, }, }, } function onTrade(player,npc,trade) end function onTrigger(player,npc) dsp.title.changerOnTrigger(player, eventId, titleInfo) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) dsp.title.changerOnEventFinish(player, csid, option, eventId, titleInfo) end
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/meatloaf_+1.lua
11
1092
----------------------------------------- -- ID: 5690 -- Item: Meatloaf +1 -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- Strength 6 -- Agility 2 -- Intelligence -3 -- Attack 18% Cap 95 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:hasStatusEffect(dsp.effect.FOOD)) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5690) end function onEffectGain(target,effect) target:addMod(dsp.mod.STR, 6) target:addMod(dsp.mod.AGI, 2) target:addMod(dsp.mod.INT, -3) target:addMod(dsp.mod.FOOD_ATTP, 18) target:addMod(dsp.mod.FOOD_ATT_CAP, 95) end function onEffectLose(target, effect) target:delMod(dsp.mod.STR, 6) target:delMod(dsp.mod.AGI, 2) target:delMod(dsp.mod.INT, -3) target:delMod(dsp.mod.FOOD_ATTP, 18) target:delMod(dsp.mod.FOOD_ATT_CAP, 95) end
gpl-3.0
kalkin/prosody-playbook
files/mod_smacks.lua
2
13412
local st = require "util.stanza"; local uuid_generate = require "util.uuid".generate; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local os_time = os.time; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local timer = require "util.timer"; local datetime = require "util.datetime"; local xmlns_sm2 = "urn:xmpp:sm:2"; local xmlns_sm3 = "urn:xmpp:sm:3"; local xmlns_errors = "urn:ietf:params:xml:ns:xmpp-stanzas"; local xmlns_delay = "urn:xmpp:delay"; local sm2_attr = { xmlns = xmlns_sm2 }; local sm3_attr = { xmlns = xmlns_sm3 }; local resume_timeout = module:get_option_number("smacks_hibernation_time", 300); local s2s_smacks = module:get_option_boolean("smacks_enabled_s2s", false); local max_unacked_stanzas = module:get_option_number("smacks_max_unacked_stanzas", 0); local core_process_stanza = prosody.core_process_stanza; local sessionmanager = require"core.sessionmanager"; local c2s_sessions = module:shared("/*/c2s/sessions"); local session_registry = {}; local function can_do_smacks(session, advertise_only) if session.smacks then return false, "unexpected-request", "Stream management is already enabled"; end local session_type = session.type; if session_type == "c2s" then if not(advertise_only) and not(session.resource) then -- Fail unless we're only advertising sm return false, "unexpected-request", "Client must bind a resource before enabling stream management"; end return true; elseif s2s_smacks and (session_type == "s2sin" or session_type == "s2sout") then return true; end return false, "service-unavailable", "Stream management is not available for this stream"; end module:hook("stream-features", function (event) if can_do_smacks(event.origin, true) then event.features:tag("sm", sm2_attr):tag("optional"):up():up(); event.features:tag("sm", sm3_attr):tag("optional"):up():up(); end end); module:hook("s2s-stream-features", function (event) if can_do_smacks(event.origin, true) then event.features:tag("sm", sm2_attr):tag("optional"):up():up(); event.features:tag("sm", sm3_attr):tag("optional"):up():up(); end end); module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza) if can_do_smacks(session) then if stanza:get_child("sm", xmlns_sm3) then session.sends2s(st.stanza("enable", sm3_attr)); elseif stanza:get_child("sm", xmlns_sm2) then session.sends2s(st.stanza("enable", sm2_attr)); end end end); local function wrap_session(session, resume, xmlns_sm) local sm_attr = { xmlns = xmlns_sm }; -- Overwrite process_stanza() and send() local queue; if not resume then queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; else queue = session.outgoing_stanza_queue; end local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace local cached_stanza = st.clone(stanza); if cached_stanza and cached_stanza:get_child("delay", xmlns_delay) == nil then cached_stanza = cached_stanza:tag("delay", { xmlns = xmlns_delay, from = session.host, stamp = datetime.datetime()}); end queue[#queue+1] = cached_stanza; end if session.hibernating then -- The session is hibernating, no point in sending the stanza -- over a dead connection. It will be delivered upon resumption. return true; end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack and attr and not attr.xmlns then session.awaiting_ack = true; return _send(st.stanza("r", sm_attr)); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end local session_close = session.close; function session.close(...) if session.resumption_token then session_registry[session.resumption_token] = nil; session.resumption_token = nil; end return session_close(...); end if not resume then session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); end return session; end function handle_enable(session, stanza, xmlns_sm) local ok, err, err_text = can_do_smacks(session); if not ok then session.log("warn", "Failed to enable smacks: %s", err_text); -- TODO: XEP doesn't say we can send error text, should it? session.send(st.stanza("failed", { xmlns = xmlns_sm }):tag(err, { xmlns = xmlns_errors})); return true; end module:log("debug", "Enabling stream management"); session.smacks = true; wrap_session(session, false, xmlns_sm); local resume_token; local resume = stanza.attr.resume; if resume == "true" or resume == "1" then resume_token = uuid_generate(); session_registry[resume_token] = session; session.resumption_token = resume_token; end (session.sends2s or session.send)(st.stanza("enabled", { xmlns = xmlns_sm, id = resume_token, resume = resume })); return true; end module:hook_stanza(xmlns_sm2, "enable", function (session, stanza) return handle_enable(session, stanza, xmlns_sm2); end, 100); module:hook_stanza(xmlns_sm3, "enable", function (session, stanza) return handle_enable(session, stanza, xmlns_sm3); end, 100); function handle_enabled(session, stanza, xmlns_sm) module:log("debug", "Enabling stream management"); session.smacks = true; wrap_session(session, false, xmlns_sm); -- FIXME Resume? return true; end module:hook_stanza(xmlns_sm2, "enabled", function (session, stanza) return handle_enabled(session, stanza, xmlns_sm2); end, 100); module:hook_stanza(xmlns_sm3, "enabled", function (session, stanza) return handle_enabled(session, stanza, xmlns_sm3); end, 100); function handle_r(origin, stanza, xmlns_sm) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end module:hook_stanza(xmlns_sm2, "r", function (origin, stanza) return handle_r(origin, stanza, xmlns_sm2); end); module:hook_stanza(xmlns_sm3, "r", function (origin, stanza) return handle_r(origin, stanza, xmlns_sm3); end); function handle_a(origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue --log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or ""); local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); module:log("debug", "Client h: %d, our h: %d", tonumber(stanza.attr.h), origin.last_acknowledged_stanza); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end module:hook_stanza(xmlns_sm2, "a", handle_a); module:hook_stanza(xmlns_sm3, "a", handle_a); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = st.reply(queue[i]); if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, reply); end end end end module:hook("pre-resource-unbind", function (event) local session, err = event.session, event.error; if session.smacks then if not session.resumption_token then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas", #queue); handle_unacked_stanzas(session); end else session.log("debug", "mod_smacks hibernating session for up to %d seconds", resume_timeout); local hibernate_time = os_time(); -- Track the time we went into hibernation session.hibernating = hibernate_time; local resumption_token = session.resumption_token; timer.add_task(resume_timeout, function () session.log("debug", "mod_smacks hibernation timeout reached..."); -- We need to check the current resumption token for this resource -- matches the smacks session this timer is for in case it changed -- (for example, the client may have bound a new resource and -- started a new smacks session, or not be using smacks) local curr_session = full_sessions[session.full_jid]; if false and session.destroyed then session.log("debug", "The session has already been destroyed"); elseif curr_session and curr_session.resumption_token == resumption_token -- Check the hibernate time still matches what we think it is, -- otherwise the session resumed and re-hibernated. and session.hibernating == hibernate_time then session.log("debug", "Destroying session for hibernating too long"); session_registry[session.resumption_token] = nil; session.resumption_token = nil; sessionmanager.destroy_session(session); else session.log("debug", "Session resumed before hibernation timeout, all is well") end end); return true; -- Postpone destruction for now end end end); function handle_resume(session, stanza, xmlns_sm) if session.full_jid then session.log("warn", "Tried to resume after resource binding"); session.send(st.stanza("failed", { xmlns = xmlns_sm }) :tag("unexpected-request", { xmlns = xmlns_errors }) ); return true; end local id = stanza.attr.previd; local original_session = session_registry[id]; if not original_session then session.log("debug", "Tried to resume non-existent session with id %s", id); session.send(st.stanza("failed", { xmlns = xmlns_sm }) :tag("item-not-found", { xmlns = xmlns_errors }) ); elseif session.username == original_session.username and session.host == original_session.host then session.log("debug", "mod_smacks resuming existing session..."); -- TODO: All this should move to sessionmanager (e.g. session:replace(new_session)) if original_session.conn then session.log("debug", "mod_smacks closing an old connection for this session"); local conn = original_session.conn; c2s_sessions[conn] = nil; conn:close(); end original_session.ip = session.ip; original_session.conn = session.conn; original_session.send = session.send; original_session.stream = session.stream; original_session.secure = session.secure; original_session.hibernating = nil; local filter = original_session.filter; local stream = session.stream; local log = session.log; function original_session.data(data) data = filter("bytes/in", data); if data then local ok, err = stream:feed(data); if ok then return; end log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_")); original_session:close("xml-not-well-formed"); end end wrap_session(original_session, true, xmlns_sm); -- Inform xmppstream of the new session (passed to its callbacks) stream:set_session(original_session); -- Similar for connlisteners c2s_sessions[session.conn] = original_session; session.send(st.stanza("resumed", { xmlns = xmlns_sm, h = original_session.handled_stanza_count, previd = id })); -- Fake an <a> with the h of the <resume/> from the client original_session:dispatch_stanza(st.stanza("a", { xmlns = xmlns_sm, h = stanza.attr.h })); -- Ok, we need to re-send any stanzas that the client didn't see -- ...they are what is now left in the outgoing stanza queue local queue = original_session.outgoing_stanza_queue; for i=1,#queue do session.send(queue[i]); end else module:log("warn", "Client %s@%s[%s] tried to resume stream for %s@%s[%s]", session.username or "?", session.host or "?", session.type, original_session.username or "?", original_session.host or "?", original_session.type); session.send(st.stanza("failed", { xmlns = xmlns_sm }) :tag("not-authorized", { xmlns = xmlns_errors })); end return true; end module:hook_stanza(xmlns_sm2, "resume", function (session, stanza) return handle_resume(session, stanza, xmlns_sm2); end); module:hook_stanza(xmlns_sm3, "resume", function (session, stanza) return handle_resume(session, stanza, xmlns_sm3); end);
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Apollyon/mobs/Proto-Omega.lua
8
3205
----------------------------------- -- Area: Apollyon (Central) -- MOB: 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"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); mob:setMod(MOD_UDMGPHYS, -75); mob:setMod(MOD_UDMGRANGE, -75); mob:setMod(MOD_UDMGMAGIC, 0); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local mobID = mob:getID(); local formTime = mob:getLocalVar("formWait") local lifePercent = mob:getHPP(); local currentForm = mob:getLocalVar("form") if (lifePercent < 70 and currentForm < 1) then currentForm = 1; mob:setLocalVar("form", currentForm) mob:AnimationSub(2); formTime = os.time() + 60; mob:setMod(MOD_UDMGPHYS, 0); mob:setMod(MOD_UDMGRANGE, 0); mob:setMod(MOD_UDMGMAGIC, -75); end if (currentForm == 1) then if (formTime < os.time()) then if (mob:AnimationSub() == 1) then mob:AnimationSub(2); else mob:AnimationSub(1); end mob:setLocalVar("formWait", os.time() + 60); end if (lifePercent < 30) then mob:AnimationSub(2); mob:setMod(MOD_UDMGPHYS, -50); mob:setMod(MOD_UDMGRANGE, -50); mob:setMod(MOD_UDMGMAGIC, -50); mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain, mob:getStatusEffect(EFFECT_REGAIN):setFlag(32); currentForm = 2; mob:setLocalVar("form", currentForm) end end end; ----------------------------------- -- onAdditionalEffect ----------------------------------- function onAdditionalEffect(mob, player) local chance = 20; -- wiki lists ~20% stun chance local resist = applyResistanceAddEffect(mob,player,ELE_THUNDER,EFFECT_STUN); if (math.random(0,99) >= chance or resist <= 0.5) then return 0,0,0; else local duration = 5 * resist; if (player:hasStatusEffect(EFFECT_STUN) == false) then player:addStatusEffect(EFFECT_STUN, 0, 0, duration); end return SUBEFFECT_STUN, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_STUN; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) ally: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
marcel-sch/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/network.lua
20
2738
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("Network Plugin Configuration"), translate( "The network plugin provides network based communication between " .. "different collectd instances. Collectd can operate both in client " .. "and server mode. In client mode locally collected date is " .. "transferred to a collectd server instance, in server mode the " .. "local instance receives data from other hosts." )) -- collectd_network config section s = m:section( NamedSection, "collectd_network", "luci_statistics" ) -- collectd_network.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_network_listen config section (Listen) listen = m:section( TypedSection, "collectd_network_listen", translate("Listener interfaces"), translate( "This section defines on which interfaces collectd will wait " .. "for incoming connections." )) listen.addremove = true listen.anonymous = true -- collectd_network_listen.host listen_host = listen:option( Value, "host", translate("Listen host") ) listen_host.default = "0.0.0.0" -- collectd_network_listen.port listen_port = listen:option( Value, "port", translate("Listen port") ) listen_port.default = 25826 listen_port.isinteger = true listen_port.optional = true -- collectd_network_server config section (Server) server = m:section( TypedSection, "collectd_network_server", translate("server interfaces"), translate( "This section defines to which servers the locally collected " .. "data is sent to." )) server.addremove = true server.anonymous = true -- collectd_network_server.host server_host = server:option( Value, "host", translate("Server host") ) server_host.default = "0.0.0.0" -- collectd_network_server.port server_port = server:option( Value, "port", translate("Server port") ) server_port.default = 25826 server_port.isinteger = true server_port.optional = true -- collectd_network.timetolive (TimeToLive) ttl = s:option( Value, "TimeToLive", translate("TTL for network packets") ) ttl.default = 128 ttl.isinteger = true ttl.optional = true ttl:depends( "enable", 1 ) -- collectd_network.forward (Forward) forward = s:option( Flag, "Forward", translate("Forwarding between listen and server addresses") ) forward.default = 0 forward.optional = true forward:depends( "enable", 1 ) -- collectd_network.cacheflush (CacheFlush) cacheflush = s:option( Value, "CacheFlush", translate("Cache flush interval"), translate("Seconds") ) cacheflush.default = 86400 cacheflush.isinteger = true cacheflush.optional = true cacheflush:depends( "enable", 1 ) return m
apache-2.0
LazyShpee/discord-egobot
libs/bitwise_ops/log2.lua
1
3337
--- Operations dealing with binary logarithms. -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- [ MIT license: http://www.opensource.org/licenses/mit-license.php ] -- -- Standard library imports -- local ceil = math.ceil local frexp = math.frexp -- Exports -- local M = {} --- Ceiling of binary logarithm of _n_. -- @uint n Integer, &isin; [1, 2^53]. -- @treturn uint Ceilinged logarithm. function M.Lg_Ceil (n) local frac, exp = frexp(n) return exp + ceil(frac - 1.5) end --- Floor of binary logarithm of _n_. -- @uint n Integer, &isin; [1, 2^53]. -- @treturn uint Floored logarithm. function M.Lg_Floor (n) local _, exp = frexp(n) return exp - 1 end --- Populates a perfect hash table for powers of 2: 2^_i_ | _i_ &isin; [0, 35]. -- -- Given a power of 2, the binary logarithm can be extracted as `i = t[power % 37]`. -- -- For 32-bit _power_, one may compute `power % 37` according to one of the methods from -- @{tektite_core.number.divide.GenerateUnsignedConstants}, with _x_ = _power_, _m_ = **0xDD67C8A7**, -- and _p_ = **37** (generated with _nmax_ = **2^31** and _d_ = **37**). -- @ptable[opt] t Table to populate. If absent, one is provided. -- @treturn table _t_. function M.PopulateMod37 (t) t = t or {} -- Fill in the values, terminating at i = 36 where the first clash occurs; conveniently, -- no slot remains unfilled, i.e. this is a minimal perfect hash. local n = 1 for i = 0, 35 do t[n % 37], n = i, 2 * n end return t end --- Populates a perfect hash table for powers of 2: 2^_i_ | _i_ &isin; [0, 54]. -- -- Given a power of 2, the binary logarithm can be extracted as `i = t[power % 59]`. -- -- For 32-bit _power_, one may compute `power % 59` according to one of the methods from -- @{tektite_core.number.divide.GenerateUnsignedConstants}, with _x_ = _power_, _m_ = **0x22B63CBF**, -- and _p_ = **35** (generated with _nmax_ = **2^31** and _d_ = **59**). -- @ptable[opt] t Table to populate. If absent, one is provided. -- @treturn table _t_. function M.PopulateMod59 (t) t = t or {} -- Fill in the values... local n = 1 for i = 0, 54 do -- n.b. integers still representable up to 2^53, evens up to 2^54 t[n % 59], n = i, 2 * n end -- ...and plug holes. t[15] = false t[30] = false t[37] = false return t end -- Export the module. return M
mit
Giorox/AngelionOT-Repo
data/npc/scripts/Sigurd.lua
7
9472
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local talkState = {} function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local shopModule = ShopModule:new() npcHandler:addModule(shopModule) shopModule:addBuyableItem({'spellbook'}, 2175, 150, 1, 'spellbook') shopModule:addBuyableItem({'magic lightwand'}, 2163, 400, 1, 'magic lightwand') shopModule:addBuyableItem({'small health'}, 8704, 20, 1, 'small health potion') shopModule:addBuyableItem({'health potion'}, 7618, 45, 1, 'health potion') shopModule:addBuyableItem({'mana potion'}, 7620, 50, 1, 'mana potion') shopModule:addBuyableItem({'strong health'}, 7588, 100, 1, 'strong health potion') shopModule:addBuyableItem({'strong mana'}, 7589, 80, 1, 'strong mana potion') shopModule:addBuyableItem({'great health'}, 7591, 190, 1, 'great health potion') shopModule:addBuyableItem({'great mana'}, 7590, 120, 1, 'great mana potion') shopModule:addBuyableItem({'great spirit'}, 8472, 190, 1, 'great spirit potion') shopModule:addBuyableItem({'ultimate health'}, 8473, 310, 1, 'ultimate health potion') shopModule:addSellableItem({'normal potion flask', 'normal flask'}, 7636, 5, 'empty small potion flask') shopModule:addSellableItem({'strong potion flask', 'strong flask'}, 7634, 10, 'empty strong potion flask') shopModule:addSellableItem({'great potion flask', 'great flask'}, 7635, 15, 'empty great potion flask') shopModule:addBuyableItem({'instense healing'}, 2265, 95, 1, 'intense healing rune') shopModule:addBuyableItem({'ultimate healing'}, 2273, 175, 1, 'ultimate healing rune') shopModule:addBuyableItem({'fire bomb'}, 2305, 117, 2, 'fire bomb') shopModule:addBuyableItem({'destroy field'}, 2261, 15, 3, 'destroy field rune') shopModule:addBuyableItem({'light magic missile'}, 2287, 4, 10, 'light magic missile rune') shopModule:addBuyableItem({'heavy magic missile'}, 2311, 12, 10, 'heavy magic missile rune') shopModule:addBuyableItem({'great fireball'}, 2304, 45, 4, 'great fireball rune') shopModule:addBuyableItem({'explosion'}, 2313, 31, 6, 'explosion rune') shopModule:addBuyableItem({'sudden death'}, 2268, 108, 10, 'sudden death rune') shopModule:addBuyableItem({'convince creature'}, 2290, 80, 1, 'convince creature rune') shopModule:addBuyableItem({'chameleon'}, 2291, 210, 1, 'chameleon rune') shopModule:addBuyableItem({'desintegrate'}, 2310, 80, 3, 'desintegreate rune') shopModule:addBuyableItem({'fire field'}, 2301, 28, 3, 'fire field rune') shopModule:addBuyableItem({'energy field'}, 2301, 38, 3, 'energy field rune') shopModule:addBuyableItem({'avalanche rune'}, 2274, 45, 4, 'avalanche rune') shopModule:addBuyableItem({'antidote rune'}, 2266, 65, 1, 'antidote rune') shopModule:addBuyableItem({'energy wall'}, 2279, 85, 4, 'energy wall rune') shopModule:addBuyableItem({'icicle'}, 2271, 30, 5, 'icicle rune') shopModule:addBuyableItem({'poison field'}, 2285, 21, 3, 'poison field rune') shopModule:addBuyableItem({'poison wall'}, 2289, 52, 4, 'poison wall rune') shopModule:addBuyableItem({'blank'}, 2260, 10, 1, 'blank rune') shopModule:addBuyableItem({'fire ball'}, 2302, 30, 5, 'fire ball rune') shopModule:addBuyableItemContainer({'bp blank'}, 1998, 2260, 220, 1, 'bp blank rune') shopModule:addBuyableItemContainer({'bp animate dead'}, 1998, 2316, 7520, 1, 'bp animate dead rune') shopModule:addBuyableItemContainer({'bp antidote'}, 2003, 2266, 1320, 1, 'bp antidote rune') shopModule:addBuyableItemContainer({'bp avalanche'}, 2002, 2274, 3600,4, 'bp avalanche rune') shopModule:addBuyableItemContainer({'bp chameleon'}, 1998, 2291, 4220,1, 'bp chameleon rune') shopModule:addBuyableItemContainer({'bp convince creature'}, 1998, 2290, 1620,1, 'bp convince creature rune') shopModule:addBuyableItemContainer({'bp desintegrate'}, 2001, 2310, 1620,3, 'bp desintegrate rune') shopModule:addBuyableItemContainer({'bp destroy field'}, 2003, 2261, 920,3, 'bp destroy field') shopModule:addBuyableItemContainer({'bp energy bomb'}, 2003, 2262, 6520,2, 'bp energy bomb rune') shopModule:addBuyableItemContainer({'bp energy field'}, 1998, 2277, 2320,3, 'bp energy field') shopModule:addBuyableItemContainer({'bp energy wall'}, 2002, 2279, 6820,4, 'bp energy wall rune') shopModule:addBuyableItemContainer({'bp explosion'}, 2001, 2313, 3820,6, 'bp explosion rune') shopModule:addBuyableItemContainer({'bp fire bomb'}, 2000, 2305, 4720,2, 'bp fire bomb rune') shopModule:addBuyableItemContainer({'bp fire field'}, 2000, 2301, 1720,3, 'bp fire field rune') shopModule:addBuyableItemContainer({'bp fireball'}, 2000, 2302, 3020,5, 'bp fire ball') shopModule:addBuyableItemContainer({'bp gfb'}, 2000, 2304, 3620,4, 'bp gfb') shopModule:addBuyableItemContainer({'bp hmm'}, 2001, 2311, 2420,10, 'bp hmm') shopModule:addBuyableItemContainer({'bp icicle'}, 2002, 2271, 3020,5, 'bp icicle') shopModule:addBuyableItemContainer({'bp ih'}, 2003, 2265, 1920,1, 'bp ih') shopModule:addBuyableItemContainer({'bp lmm'}, 1998, 2287, 820,10, 'bp lmm') shopModule:addBuyableItemContainer({'bp poison field'}, 1998, 2285, 1320,3, 'bp poison field') shopModule:addBuyableItemContainer({'bp poison wall'}, 1998, 2289, 4220,4, 'bp poison wall rune') shopModule:addBuyableItemContainer({'bp sd'}, 2003, 2268, 6500 ,10, 'bp sd') shopModule:addBuyableItemContainer({'bp uh'}, 2002, 2273, 3520,3, 'bp uh') shopModule:addBuyableItemContainer({'bp shp'}, 2000, 8704, 400, 1, 'backpack of small health potions') shopModule:addBuyableItemContainer({'bp hp'}, 2000, 7618, 900, 1, 'backpack of health potions') shopModule:addBuyableItemContainer({'bp mp'}, 2001, 7620, 1000, 1, 'backpack of mana potions') shopModule:addBuyableItemContainer({'bp shp'}, 2000, 7588, 2000, 1, 'backpack of strong health potions') shopModule:addBuyableItemContainer({'bp smp'}, 2001, 7589, 1600, 1, 'backpack of strong mana potions') shopModule:addBuyableItemContainer({'bp ghp'}, 2000, 7591, 3800, 1, 'backpack of great health potions') shopModule:addBuyableItemContainer({'bp gmp'}, 2001, 7590, 2400, 1, 'backpack of great mana potions') shopModule:addBuyableItemContainer({'bp gsp'}, 1999, 8472, 3820, 1, 'backpack of great spirit potions') shopModule:addBuyableItemContainer({'bp uhp'}, 2000, 8473, 6200, 1, 'backpack of ultimate health potions') shopModule:addBuyableItem({'wand of vortex', 'vortex'}, 2190, 500, 1, 'wand of vortex') shopModule:addBuyableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 1000, 1, 'wand of dragonbreath') shopModule:addBuyableItem({'wand of decay', 'decay'}, 2188, 5000, 1, 'wand of decay') shopModule:addBuyableItem({'wand of draconia', 'draconia'}, 8921, 7500, 1, 'wand of draconia') shopModule:addBuyableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 10000, 1, 'wand of cosmic energy') shopModule:addBuyableItem({'wand of inferno', 'inferno'}, 2187, 15000, 1, 'wand of inferno') shopModule:addBuyableItem({'wand of starstorm', 'starstorm'}, 8920, 18000, 1, 'wand of starstorm') shopModule:addBuyableItem({'wand of voodoo', 'voodoo'}, 8922, 22000, 1, 'wand of voodoo') shopModule:addBuyableItem({'snakebite rod', 'snakebite'}, 2182, 500, 1, 'snakebite rod') shopModule:addBuyableItem({'moonlight rod', 'moonlight'}, 2186, 1000, 1, 'moonlight rod') shopModule:addBuyableItem({'necrotic rod', 'necrotic'}, 2185, 5000, 1, 'necrotic rod') shopModule:addBuyableItem({'northwind rod', 'northwind'}, 8911, 7500, 1, 'northwind rod') shopModule:addBuyableItem({'terra rod', 'terra'}, 2181, 10000, 1, 'terra rod') shopModule:addBuyableItem({'hailstorm rod', 'hailstorm'}, 2183, 15000, 1, 'hailstorm rod') shopModule:addBuyableItem({'springsprout rod', 'springsprout'}, 8912, 18000, 1, 'springsprout rod') shopModule:addBuyableItem({'underworld rod', 'underworld'}, 8910, 22000, 1, 'underworld rod') function creatureSayCallback(cid, type, msg) if(not npcHandler:isFocused(cid)) then return false end local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and 0 or cid local items = {[1] = 2190, [2] = 2182, [5] = 2190, [6] = 2182} if(msgcontains(msg, 'first rod') or msgcontains(msg, 'first wand')) then if(isSorcerer(cid) or isDruid(cid)) then if(getPlayerStorageValue(cid, 30002) == -1) then selfSay('So you ask me for a {' .. getItemNameById(items[getPlayerVocation(cid)]) .. '} to begin your advanture?', cid) talkState[talkUser] = 1 else selfSay('What? I have already gave you one {' .. getItemNameById(items[getPlayerVocation(cid)]) .. '}!', cid) end else selfSay('Sorry, you aren\'t a druid either a sorcerer.', cid) end elseif(msgcontains(msg, 'yes')) then if(talkState[talkUser] == 1) then doPlayerAddItem(cid, items[getPlayerVocation(cid)], 1) selfSay('Here you are young adept, take care yourself.', cid) setPlayerStorageValue(cid, 30002, 1) end talkState[talkUser] = 0 elseif(msgcontains(msg, 'no') and isInArray({1}, talkState[talkUser]) == TRUE) then selfSay('Ok then.', cid) talkState[talkUser] = 0 end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
gpl-3.0
Fenix-XI/Fenix
scripts/globals/spells/foe_requiem_iv.lua
26
1631
----------------------------------------- -- Spell: Foe Requiem IV ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_REQUIEM; local duration = 111; local power = 4; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,SINGING_SKILL,0); if (resm < 0.5) then spell:setMsg(85);--resist message return 1; end local iBoost = caster:getMod(MOD_REQUIEM_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Try to overwrite weaker slow / haste if (canOverwrite(target, effect, power)) then -- overwrite them target:delStatusEffect(effect); target:addStatusEffect(effect,power,3,duration); spell:setMsg(237); else spell:setMsg(75); -- no effect end return effect; end;
gpl-3.0
franko/gsl-shell
data/demo-init.lua
1
1273
local demo_list = {} local function load_demo(name) local record = require('demos.' .. name) local group, info = record[1], record[2] local section = demo_list[group] if not section then section = {} demo_list[group] = section end local i = #section for k, v in ipairs(info) do section[i+k] = v end end local demo_files = { 'fft', 'bspline', 'wave-particle', 'plot', 'fractals', 'ode', 'nlinfit', 'integ', 'anim', 'linfit', 'contour', 'svg', 'graphics', 'sf', 'vegas', 'gdt-lm'} for i, name in ipairs(demo_files) do load_demo(name) end local function print_demos_list() for group, t in pairs(demo_list) do io.write('*** ', group, '\n') for k, v in ipairs(t) do print(v.name .. ' - ' .. v.description) end print '' print("***************************************************") end print("Type demo(<name>) to execute the demo.") print("For example type demo(\"wave\") for wave particle demo.") print '' end local function load_demo(name) for group, t in pairs(demo_list) do for k, entry in ipairs(t) do if entry.name == name then return entry end end end end return { list = print_demos_list, load = load_demo, }
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Bastok_Mines/npcs/Explorer_Moogle.lua
13
1711
----------------------------------- -- Area: Bastok Mines -- NPC: Explorer Moogle -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) accept = 0; event = 0x0249; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); 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); local price = 300; if (csid == 0x0249) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Tavnazian_Safehold/npcs/Mazuro-Oozuro.lua
13
1256
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Mazuro-Oozuro -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MAZUROOOZURO_SHOP_DIALOG); stock = {0x426d,108, -- Lufaise Fly 0x43e7,2640, -- Clothespole 0x02b0,200, -- Arrowwood Log 0x02b2,7800, -- Elm Log 0x0b37,10000} -- Safehold Waystone showShop(player, STATIC, stock); 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
DarkstarProject/darkstar
scripts/zones/Metalworks/npcs/Mighty_Fist.lua
9
2275
----------------------------------- -- Area: Metalworks -- NPC: Mighty Fist -- Starts & Finishes Quest: The Darksmith (R) -- Involved in Quest: Dark Legacy -- !pos -47 2 -30 237 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Metalworks/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH) ~= QUEST_AVAILABLE) then if (trade:hasItemQty(645,2) and trade:getItemCount() == 2) then player:startEvent(566); end end end; function onTrigger(player,npc) if (player:getCharVar("darkLegacyCS") == 1) then player:startEvent(752); elseif (player:hasKeyItem(dsp.ki.DARKSTEEL_FORMULA)) then player:startEvent(754); elseif (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH) == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 3) then player:startEvent(565); else Message = math.random(0,1); if (Message == 1) then player:startEvent(560); else player:startEvent(561); end end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) if (csid == 565) then player:addQuest(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH); elseif (csid == 566) then TheDarksmith = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH); player:tradeComplete(); player:addGil(GIL_RATE*8000); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*8000); if (TheDarksmith == QUEST_ACCEPTED) then player:addFame(BASTOK,30); player:completeQuest(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH); else player:addFame(BASTOK,5); end elseif (csid == 752) then player:setCharVar("darkLegacyCS",2); player:addKeyItem(dsp.ki.LETTER_FROM_THE_DARKSTEEL_FORGE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LETTER_FROM_THE_DARKSTEEL_FORGE); end end;
gpl-3.0
Giorox/AngelionOT-Repo
data/globalevents/scripts/raidSystem.lua
1
4556
--Unannounced Boss Raid Sytem --Script by Giorox raidTable = { {boss = "Fernfang", pos = {x=32851,y=32339,z=6}}, {boss = "Captain Jones", pos = {x=33276,y=32215,z=7}}, {boss = "Rukor Zad", pos = {x=32602,y=32383,z=10}}, {boss = "Yaga The Crone", pos = {x=32716,y=32009,z=11}}, {boss = "Zarabustor", pos = {x=32509,y=31582,z=14}}, {boss = "Zevelon Duskbringer", pos = {x=32754,y=31578,z=11}}, {boss = "The Evil Eye", pos = {x=32798,y=31668,z=14}}, {boss = "General Murius", pos = {x=32428,y=32113,z=15}}, {boss = "Warlord Ruzad", pos = {x=32970,y=31722,z=5}}, {boss = "Rotworm Queen", pos = {x=32774,y=31601,z=12}}, -- Hellgate {boss = "Rotworm Queen", pos = {x=33237,y=31842,z=9}}, -- Rotworm Cave (Edron) {boss = "Rotworm Queen", pos = {x=32263,y=32688,z=10}}, -- Rotworm Cave (Vandura) {boss = "Rotworm Queen", pos = {x=33305,y=32329,z=9}}, -- Rotworm Cave (Darashia) {boss = "Grorlam", pos = {x=32030,y=32687,z=13}}, {boss = "Diblis The Fair", pos = {x=32009,y=32795,z=10}}, {boss = "Arachir The Ancient One", pos = {x=32965,y=32400,z=12}}, {boss = "Sir Valorcrest", pos = {x=33264,y=31768,z=10}}, {boss = "The Horned Fox", pos = {x=32463,y=31954,z=4}}, {boss = "Necropharus", pos = {x=33044,y=32401,z=10}}, -- Medusa Shield Quest {boss = "Necropharus", pos = {x=33082,y=31674,z=11}}, -- Edron Hero Cave {boss = "Necropharus", pos = {x=31963,y=32592,z=10}}, -- Lich Hell {boss = "Demodras", pos = {x=32776,y=32289,z=10}}, -- POH DLair {boss = "Demodras", pos = {x=32793,y=32337,z=12}}, -- POI Dlair {boss = "Demodras", pos = {x=32352,y=32091,z=10}}, -- Thais DLair {boss = "Demodras", pos = {x=33236,y=32277,z=12}}, -- Darashia DLair {boss = "Demodras", pos = {x=32876,y=32154,z=9}}, -- Venore DLair {boss = "Dracola", pos = {x=32837,y=32309,z=15}}, {boss = "The Imperor", pos = {x=32904,y=32217,z=15}}, {boss = "The Plasmother", pos = {x=32844,y=32332,z=15}}, {boss = "The Handmaiden", pos = {x=32785,y=32276,z=15}}, {boss = "Massacre", pos = {x=32877,y=32271,z=15}}, {boss = "Countess Sorrow", pos = {x=32803,y=32333,z=15}}, {boss = "Mr. Punish", pos = {x=32763,y=32243,z=15}}, {boss = "Yeti", pos = {x=32011,y=31595,z=7}}, {boss = "Barbaria", pos = {x=32022,y=31395,z=7}}, {boss = "Gravelord Oshuran", pos = {x=32897,y=32437,z=11}}, {boss = "Tiquandas Revenge", pos = {x=32872,y=32665,z=7}}, {boss = "High Templar Cobrass", pos = {x=32957,y=32854,z=8}}, {boss = "Hatebreeder", pos = {x=33045,y=31093,z=14}}, {boss = "Flamecaller Zazrak", pos = {x=33184,y=31220,z=7}}, {boss = "Dreadmaw", pos = {x=33294,y=31159,z=7}}, {boss = "Battlemaster Zunzu", pos = {x=33204,y=31356,z=7}}, {boss = "The Voice of Ruin", pos = {x=33311,y=31130,z=9}}, {boss = "Munster", pos = {x=32100,y=32217,z=9}}, {boss = "Rottie the Rotworm", pos = {x=32059,y=32076,z=10}}, -- Poison Spider Cave {boss = "Rottie the Rotworm", pos = {x=32174,y=32147,z=11}}, -- Katana Quest {boss = "Teleskor", pos = {x=31976,y=32248,z=10}}, {boss = "Apprentice Sheng", pos = {x=32129,y=32060,z=12}}, {boss = "Dharalion", pos = {x=33039,y=32177,z=9}}, {boss = "Man In The Cave", pos = {x=32133,y=31147,z=2}}, {boss = "The Frog Prince", pos = {x=32382,y=32131,z=7}}, {boss = "Fleabringer", pos = {x=33089,y=31383,z=8}}, -- First Cave {boss = "Fleabringer", pos = {x=33111,y=31458,z=8}}, -- Second Cave {boss = "Fleabringer", pos = {x=33228,y=31415,z=7}}, -- Steppe {boss = "Big Boss Trolliver", pos = {x=33081,y=31742,z=10}}, {boss = "Smuggler Baron Silvertoe", pos = {x=32542,y=32647,z=10}}, {boss = "The Big Bad One", pos = {x=33170,y=31678,z=7}}, {boss = "Hairman The Huge", pos = {x=32841,y=32523,z=8}}, {boss = "Xenia", pos = {x=32843,y=31924,z=7}}, {boss = "Foreman Kneebiter", pos = {x=32555,y=31898,z=14}}, {boss = "The Old Whopper", pos = {x=33314,y=31666,z=11}}, {boss = "Grandfather Tridian", pos = {x=32400,y=32791,z=10}}, {boss = "Thul", pos = {x=32020,y=32743,z=12}}, {boss = "Stonecracker", pos = {x=33293,y=31704,z=11}}, } local function checkArea(pos, monster) local spectators = getSpectators(pos, 2, 2) -- 2 tile left, 2 right, 2 up, 2 down if spectators ~= NULL then for _, pid in pairs(spectators) do if isMonster(pid) and getCreatureName(pid):lower() == monster:lower() then return true end end end return false end function onThink(interval) choosen = math.random(#raidTable) if (checkArea(raidTable[choosen].pos, raidTable[choosen].boss) == false) then doSummonCreature(raidTable[choosen].boss, raidTable[choosen].pos) end return true end
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Middle_Delkfutts_Tower/npcs/qm1.lua
9
1277
----------------------------------- -- Area: Middle Delfutt's Tower -- NPC: ??? (qm1) -- Involved In Quest: Blade of Evil -- !pos 84 -79 77 157 ----------------------------------- local ID = require("scripts/zones/Middle_Delkfutts_Tower/IDs") require("scripts/globals/npc_util") require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) if player:getQuestStatus(BASTOK, dsp.quest.id.bastok.BLADE_OF_EVIL) == QUEST_ACCEPTED and player:getCharVar("bladeOfEvilCS") == 0 and npcUtil.tradeHas(trade, 1114) and not GetMobByID(ID.mob.BLADE_OF_EVIL_MOB_OFFSET + 0):isSpawned() and not GetMobByID(ID.mob.BLADE_OF_EVIL_MOB_OFFSET + 1):isSpawned() and not GetMobByID(ID.mob.BLADE_OF_EVIL_MOB_OFFSET + 2):isSpawned() then player:confirmTrade() SpawnMob(ID.mob.BLADE_OF_EVIL_MOB_OFFSET + 0):updateClaim(player) SpawnMob(ID.mob.BLADE_OF_EVIL_MOB_OFFSET + 1):updateClaim(player) SpawnMob(ID.mob.BLADE_OF_EVIL_MOB_OFFSET + 2):updateClaim(player) end end function onTrigger(player, npc) player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
ehsan/wesnoth
data/campaigns/Legend_of_Wesmere/lua/replace_map.lua
8
1074
--! #textdomain wesnoth-low local replace_map = wesnoth.wml_actions.replace_map function wesnoth.wml_actions.replace_map(cfg) if not cfg.x and not cfg.y then return replace_map(cfg) end local x1,x2 = string.match(cfg.x, "(%d+)-(%d+)") local y1,y2 = string.match(cfg.y, "(%d+)-(%d+)") local header,map = string.match(cfg.map_data, "(.-)\n\n(.*)") local b = string.match(header, "border_size=(%d+)") x1 = tonumber(x1) y1 = tonumber(y1) x2 = x2 + 2 * b y2 = y2 + 2 * b local t = {} local y = 1 for row in string.gmatch(map, "[^\n]+") do if y >= y1 and y <= y2 then local r = {} local x = 1 for tile in string.gmatch(row, "[^,]+") do if x >= x1 and x <= x2 then r[x - x1 + 1] = tile end x = x + 1 end t[y - y1 + 1] = table.concat(r, ',') end y = y + 1 end local s = table.concat(t, '\n') local new_map = string.format("border_size=%d\nusage=map\n\n%s", b, s) replace_map { map = new_map, expand = true, shrink = true } end
gpl-2.0
Fenix-XI/Fenix
scripts/zones/Ilrusi_Atoll/npcs/Excaliace.lua
30
4512
----------------------------------- -- Area: Periqia -- NPC: Excaliace ----------------------------------- require("scripts/zones/Periqia/IDs"); require("scripts/globals/pathfind"); local start = {-322,-16.5,380}; local startToChoice1 = { -320.349548, -16.046591, 379.684570 -318.312317, -16.046591, 379.579865 -316.286530, -16.046591, 379.472992 -314.249298, -16.048323, 379.368164 -312.212616, -16.050047, 379.263855 -310.348267, -16.057688, 378.513367 -309.100250, -16.063747, 376.912720 -307.959656, -16.077335, 375.221832 -306.816345, -16.077335, 373.532349 -305.671082, -16.077335, 371.846008 -304.516022, -16.077335, 370.168579 -303.362549, -16.077335, 368.489624 -302.209167, -16.087559, 366.807190 -301.054626, -16.087715, 365.125336 -299.976593, -16.119972, 363.402710 -299.820740, -16.189123, 361.399994 -300.012909, -16.189123, 359.369080 -300.204407, -16.189123, 357.341705 -300.397125, -16.189123, 355.314880 -300.588409, -16.189123, 353.283936 -300.780060, -16.189123, 351.253296 -300.971313, -16.191444, 349.222321 -301.163574, -16.214754, 347.192749 -301.389923, -16.229296, 345.167511 -302.813599, -16.249445, 343.574554 -304.622406, -16.276562, 342.632568 -306.459869, -16.276562, 341.757172 -308.455261, -16.276562, 341.393158 -310.489380, -16.276562, 341.389252 -312.521088, -16.279837, 341.571747 -314.551819, -16.298687, 341.754822 -316.585144, -15.753593, 341.876556 -318.621338, -15.789236, 341.765198 -320.658966, -15.779417, 341.662872 -322.697296, -15.765886, 341.574463 -324.727234, -15.980421, 341.479340 -326.660187, -16.012735, 342.099487 -328.550476, -15.933064, 342.860687 -330.435150, -15.771011, 343.625427 -332.294006, -15.696083, 344.450684 -333.912903, -16.043205, 345.705078 -335.720062, -15.788860, 346.616364 -337.668945, -15.706074, 347.100769 -339.570679, -15.741604, 346.444336 -340.824524, -15.691669, 344.865021 -341.839478, -15.428291, 343.124268 -342.645996, -15.079435, 341.120239 -342.902252, -15.113903, 339.113068 -342.625366, -15.397438, 337.113739 -342.355469, -15.772522, 335.126404 -341.725372, -16.081879, 333.186157 -341.358307, -16.052465, 331.183319 -340.988190, -15.890514, 329.183777 -340.739380, -15.852081, 327.166229 -340.652344, -15.829269, 325.153931 -340.602631, -15.811451, 323.125397 -340.650421, -15.682171, 321.093201 -340.440063, -15.661972, 318.978729 -340.534454, -15.702602, 316.816895 -340.532501, -15.702147, 314.776947 -340.536591, -15.697933, 312.737244 -340.542572, -15.670002, 310.697632 -340.545624, -15.678772, 308.657776 -340.554047, -15.631170, 306.619476 -340.412598, -15.624416, 304.459137 -340.379303, -15.661182, 302.420258 }; function onSpawn(npc) npc:initNpcAi(); npc:pathThrough(start, PATHFLAG_REPEAT); end; function onPath(npc) local instance = npc:getInstance(); local progress = instance:getProgress(); local chars = instance:getChars(); if (progress == 0) then for tid,player in pairs(chars) do if (npc:checkDistance(player) < 10) then instance:setProgress(1); npc:messageText(npc,Periqia.text.EXCALIACE_START); npc:pathThrough(startToChoice1); end end elseif (progress == 1) then local run = true; for tid,player in pairs(chars) do if (npc:checkDistance(player) < 10) then run = false; end end if (run) then npc:messageText(npc,Periqia.text.EXCALIACE_RUN); end end -- go back and forth the set path -- pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
tcatm/luci
modules/luci-base/luasrc/dispatcher.lua
31
19783
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local util = require "luci.util" local http = require "luci.http" local nixio = require "nixio", require "nixio.util" module("luci.dispatcher", package.seeall) context = util.threadlocal() uci = require "luci.model.uci" i18n = require "luci.i18n" _M.fs = fs authenticator = {} -- Index table local index = nil -- Fastindex local fi function build_url(...) local path = {...} local url = { http.getenv("SCRIPT_NAME") or "" } local k, v for k, v in pairs(context.urltoken) do url[#url+1] = "/;" url[#url+1] = http.urlencode(k) url[#url+1] = "=" url[#url+1] = http.urlencode(v) end local p for _, p in ipairs(path) do if p:match("^[a-zA-Z0-9_%-%.%%/,;]+$") then url[#url+1] = "/" url[#url+1] = p end end return table.concat(url, "") end function node_visible(node) if node then return not ( (not node.title or #node.title == 0) or (not node.target or node.hidden == true) or (type(node.target) == "table" and node.target.type == "firstchild" and (type(node.nodes) ~= "table" or not next(node.nodes))) ) end return false end function node_childs(node) local rv = { } if node then local k, v for k, v in util.spairs(node.nodes, function(a, b) return (node.nodes[a].order or 100) < (node.nodes[b].order or 100) end) do if node_visible(v) then rv[#rv+1] = k end end end return rv end function error404(message) http.status(404, "Not Found") message = message or "Not Found" require("luci.template") if not util.copcall(luci.template.render, "error404") then http.prepare_content("text/plain") http.write(message) end return false end function error500(message) util.perror(message) if not context.template_header_sent then http.status(500, "Internal Server Error") http.prepare_content("text/plain") http.write(message) else require("luci.template") if not util.copcall(luci.template.render, "error500", {message=message}) then http.prepare_content("text/plain") http.write(message) end end return false end function authenticator.htmlauth(validator, accs, default) local user = http.formvalue("luci_username") local pass = http.formvalue("luci_password") if user and validator(user, pass) then return user end if context.urltoken.stok then context.urltoken.stok = nil local cookie = 'sysauth=%s; expires=%s; path=%s/' %{ http.getcookie('sysauth') or 'x', 'Thu, 01 Jan 1970 01:00:00 GMT', build_url() } http.header("Set-Cookie", cookie) http.redirect(build_url()) else require("luci.i18n") require("luci.template") context.path = {} http.status(403, "Forbidden") luci.template.render("sysauth", {duser=default, fuser=user}) end return false end function httpdispatch(request, prefix) http.context.request = request local r = {} context.request = r context.urltoken = {} local pathinfo = http.urldecode(request:getenv("PATH_INFO") or "", true) if prefix then for _, node in ipairs(prefix) do r[#r+1] = node end end local tokensok = true for node in pathinfo:gmatch("[^/]+") do local tkey, tval if tokensok then tkey, tval = node:match(";(%w+)=([a-fA-F0-9]*)") end if tkey then context.urltoken[tkey] = tval else tokensok = false r[#r+1] = node end end local stat, err = util.coxpcall(function() dispatch(context.request) end, error500) http.close() --context._disable_memtrace() end function dispatch(request) --context._disable_memtrace = require "luci.debug".trap_memtrace("l") local ctx = context ctx.path = request local conf = require "luci.config" assert(conf.main, "/etc/config/luci seems to be corrupt, unable to find section 'main'") local lang = conf.main.lang or "auto" if lang == "auto" then local aclang = http.getenv("HTTP_ACCEPT_LANGUAGE") or "" for lpat in aclang:gmatch("[%w-]+") do lpat = lpat and lpat:gsub("-", "_") if conf.languages[lpat] then lang = lpat break end end end require "luci.i18n".setlanguage(lang) local c = ctx.tree local stat if not c then c = createtree() end local track = {} local args = {} ctx.args = args ctx.requestargs = ctx.requestargs or args local n local token = ctx.urltoken local preq = {} local freq = {} for i, s in ipairs(request) do preq[#preq+1] = s freq[#freq+1] = s c = c.nodes[s] n = i if not c then break end util.update(track, c) if c.leaf then break end end if c and c.leaf then for j=n+1, #request do args[#args+1] = request[j] freq[#freq+1] = request[j] end end ctx.requestpath = ctx.requestpath or freq ctx.path = preq if track.i18n then i18n.loadc(track.i18n) end -- Init template engine if (c and c.index) or not track.notemplate then local tpl = require("luci.template") local media = track.mediaurlbase or luci.config.main.mediaurlbase if not pcall(tpl.Template, "themes/%s/header" % fs.basename(media)) then media = nil for name, theme in pairs(luci.config.themes) do if name:sub(1,1) ~= "." and pcall(tpl.Template, "themes/%s/header" % fs.basename(theme)) then media = theme end end assert(media, "No valid theme found") end local function _ifattr(cond, key, val) if cond then local env = getfenv(3) local scope = (type(env.self) == "table") and env.self return string.format( ' %s="%s"', tostring(key), util.pcdata(tostring( val or (type(env[key]) ~= "function" and env[key]) or (scope and type(scope[key]) ~= "function" and scope[key]) or "" )) ) else return '' end end tpl.context.viewns = setmetatable({ write = http.write; include = function(name) tpl.Template(name):render(getfenv(2)) end; translate = i18n.translate; translatef = i18n.translatef; export = function(k, v) if tpl.context.viewns[k] == nil then tpl.context.viewns[k] = v end end; striptags = util.striptags; pcdata = util.pcdata; media = media; theme = fs.basename(media); resource = luci.config.main.resourcebase; ifattr = function(...) return _ifattr(...) end; attr = function(...) return _ifattr(true, ...) end; }, {__index=function(table, key) if key == "controller" then return build_url() elseif key == "REQUEST_URI" then return build_url(unpack(ctx.requestpath)) else return rawget(table, key) or _G[key] end end}) end track.dependent = (track.dependent ~= false) assert(not track.dependent or not track.auto, "Access Violation\nThe page at '" .. table.concat(request, "/") .. "/' " .. "has no parent node so the access to this location has been denied.\n" .. "This is a software bug, please report this message at " .. "http://luci.subsignal.org/trac/newticket" ) if track.sysauth then local authen = type(track.sysauth_authenticator) == "function" and track.sysauth_authenticator or authenticator[track.sysauth_authenticator] local def = (type(track.sysauth) == "string") and track.sysauth local accs = def and {track.sysauth} or track.sysauth local sess = ctx.authsession local verifytoken = false if not sess then sess = http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") verifytoken = true end local sdat = (util.ubus("session", "get", { ubus_rpc_session = sess }) or { }).values local user if sdat then if not verifytoken or ctx.urltoken.stok == sdat.token then user = sdat.user end else local eu = http.getenv("HTTP_AUTH_USER") local ep = http.getenv("HTTP_AUTH_PASS") if eu and ep and sys.user.checkpasswd(eu, ep) then authen = function() return eu end end end if not util.contains(accs, user) then if authen then local user, sess = authen(sys.user.checkpasswd, accs, def) local token if not user or not util.contains(accs, user) then return else if not sess then local sdat = util.ubus("session", "create", { timeout = tonumber(luci.config.sauth.sessiontime) }) if sdat then token = sys.uniqueid(16) util.ubus("session", "set", { ubus_rpc_session = sdat.ubus_rpc_session, values = { user = user, token = token, section = sys.uniqueid(16) } }) sess = sdat.ubus_rpc_session end end if sess and token then http.header("Set-Cookie", 'sysauth=%s; path=%s/' %{ sess, build_url() }) ctx.urltoken.stok = token ctx.authsession = sess ctx.authuser = user http.redirect(build_url(unpack(ctx.requestpath))) end end else http.status(403, "Forbidden") return end else ctx.authsession = sess ctx.authuser = user end end if track.setgroup then sys.process.setgroup(track.setgroup) end if track.setuser then -- trigger ubus connection before dropping root privs util.ubus() sys.process.setuser(track.setuser) end local target = nil if c then if type(c.target) == "function" then target = c.target elseif type(c.target) == "table" then target = c.target.target end end if c and (c.index or type(target) == "function") then ctx.dispatched = c ctx.requested = ctx.requested or ctx.dispatched end if c and c.index then local tpl = require "luci.template" if util.copcall(tpl.render, "indexer", {}) then return true end end if type(target) == "function" then util.copcall(function() local oldenv = getfenv(target) local module = require(c.module) local env = setmetatable({}, {__index= function(tbl, key) return rawget(tbl, key) or module[key] or oldenv[key] end}) setfenv(target, env) end) local ok, err if type(c.target) == "table" then ok, err = util.copcall(target, c.target, unpack(args)) else ok, err = util.copcall(target, unpack(args)) end assert(ok, "Failed to execute " .. (type(c.target) == "function" and "function" or c.target.type or "unknown") .. " dispatcher target for entry '/" .. table.concat(request, "/") .. "'.\n" .. "The called action terminated with an exception:\n" .. tostring(err or "(unknown)")) else local root = node() if not root or not root.target then error404("No root node was registered, this usually happens if no module was installed.\n" .. "Install luci-mod-admin-full and retry. " .. "If the module is already installed, try removing the /tmp/luci-indexcache file.") else error404("No page is registered at '/" .. table.concat(request, "/") .. "'.\n" .. "If this url belongs to an extension, make sure it is properly installed.\n" .. "If the extension was recently installed, try removing the /tmp/luci-indexcache file.") end end end function createindex() local controllers = { } local base = "%s/controller/" % util.libpath() local _, path for path in (fs.glob("%s*.lua" % base) or function() end) do controllers[#controllers+1] = path end for path in (fs.glob("%s*/*.lua" % base) or function() end) do controllers[#controllers+1] = path end if indexcache then local cachedate = fs.stat(indexcache, "mtime") if cachedate then local realdate = 0 for _, obj in ipairs(controllers) do local omtime = fs.stat(obj, "mtime") realdate = (omtime and omtime > realdate) and omtime or realdate end if cachedate > realdate and sys.process.info("uid") == 0 then assert( sys.process.info("uid") == fs.stat(indexcache, "uid") and fs.stat(indexcache, "modestr") == "rw-------", "Fatal: Indexcache is not sane!" ) index = loadfile(indexcache)() return index end end end index = {} for _, path in ipairs(controllers) do local modname = "luci.controller." .. path:sub(#base+1, #path-4):gsub("/", ".") local mod = require(modname) assert(mod ~= true, "Invalid controller file found\n" .. "The file '" .. path .. "' contains an invalid module line.\n" .. "Please verify whether the module name is set to '" .. modname .. "' - It must correspond to the file path!") local idx = mod.index assert(type(idx) == "function", "Invalid controller file found\n" .. "The file '" .. path .. "' contains no index() function.\n" .. "Please make sure that the controller contains a valid " .. "index function and verify the spelling!") index[modname] = idx end if indexcache then local f = nixio.open(indexcache, "w", 600) f:writeall(util.get_bytecode(index)) f:close() end end -- Build the index before if it does not exist yet. function createtree() if not index then createindex() end local ctx = context local tree = {nodes={}, inreq=true} local modi = {} ctx.treecache = setmetatable({}, {__mode="v"}) ctx.tree = tree ctx.modifiers = modi -- Load default translation require "luci.i18n".loadc("base") local scope = setmetatable({}, {__index = luci.dispatcher}) for k, v in pairs(index) do scope._NAME = k setfenv(v, scope) v() end local function modisort(a,b) return modi[a].order < modi[b].order end for _, v in util.spairs(modi, modisort) do scope._NAME = v.module setfenv(v.func, scope) v.func() end return tree end function modifier(func, order) context.modifiers[#context.modifiers+1] = { func = func, order = order or 0, module = getfenv(2)._NAME } end function assign(path, clone, title, order) local obj = node(unpack(path)) obj.nodes = nil obj.module = nil obj.title = title obj.order = order setmetatable(obj, {__index = _create_node(clone)}) return obj end function entry(path, target, title, order) local c = node(unpack(path)) c.target = target c.title = title c.order = order c.module = getfenv(2)._NAME return c end -- enabling the node. function get(...) return _create_node({...}) end function node(...) local c = _create_node({...}) c.module = getfenv(2)._NAME c.auto = nil return c end function _create_node(path) if #path == 0 then return context.tree end local name = table.concat(path, ".") local c = context.treecache[name] if not c then local last = table.remove(path) local parent = _create_node(path) c = {nodes={}, auto=true} -- the node is "in request" if the request path matches -- at least up to the length of the node path if parent.inreq and context.path[#path+1] == last then c.inreq = true end parent.nodes[last] = c context.treecache[name] = c end return c end -- Subdispatchers -- function _firstchild() local path = { unpack(context.path) } local name = table.concat(path, ".") local node = context.treecache[name] local lowest if node and node.nodes and next(node.nodes) then local k, v for k, v in pairs(node.nodes) do if not lowest or (v.order or 100) < (node.nodes[lowest].order or 100) then lowest = k end end end assert(lowest ~= nil, "The requested node contains no childs, unable to redispatch") path[#path+1] = lowest dispatch(path) end function firstchild() return { type = "firstchild", target = _firstchild } end function alias(...) local req = {...} return function(...) for _, r in ipairs({...}) do req[#req+1] = r end dispatch(req) end end function rewrite(n, ...) local req = {...} return function(...) local dispatched = util.clone(context.dispatched) for i=1,n do table.remove(dispatched, 1) end for i, r in ipairs(req) do table.insert(dispatched, i, r) end for _, r in ipairs({...}) do dispatched[#dispatched+1] = r end dispatch(dispatched) end end local function _call(self, ...) local func = getfenv()[self.name] assert(func ~= nil, 'Cannot resolve function "' .. self.name .. '". Is it misspelled or local?') assert(type(func) == "function", 'The symbol "' .. self.name .. '" does not refer to a function but data ' .. 'of type "' .. type(func) .. '".') if #self.argv > 0 then return func(unpack(self.argv), ...) else return func(...) end end function call(name, ...) return {type = "call", argv = {...}, name = name, target = _call} end local _template = function(self, ...) require "luci.template".render(self.view) end function template(name) return {type = "template", view = name, target = _template} end local function _cbi(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local config = self.config or {} local maps = cbi.load(self.model, ...) local state = nil for i, res in ipairs(maps) do res.flow = config local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end local function _resolve_path(path) return type(path) == "table" and build_url(unpack(path)) or path end if config.on_valid_to and state and state > 0 and state < 2 then http.redirect(_resolve_path(config.on_valid_to)) return end if config.on_changed_to and state and state > 1 then http.redirect(_resolve_path(config.on_changed_to)) return end if config.on_success_to and state and state > 0 then http.redirect(_resolve_path(config.on_success_to)) return end if config.state_handler then if not config.state_handler(state, maps) then return end end http.header("X-CBI-State", state or 0) if not config.noheader then tpl.render("cbi/header", {state = state}) end local redirect local messages local applymap = false local pageaction = true local parsechain = { } for i, res in ipairs(maps) do if res.apply_needed and res.parsechain then local c for _, c in ipairs(res.parsechain) do parsechain[#parsechain+1] = c end applymap = true end if res.redirect then redirect = redirect or res.redirect end if res.pageaction == false then pageaction = false end if res.message then messages = messages or { } messages[#messages+1] = res.message end end for i, res in ipairs(maps) do res:render({ firstmap = (i == 1), applymap = applymap, redirect = redirect, messages = messages, pageaction = pageaction, parsechain = parsechain }) end if not config.nofooter then tpl.render("cbi/footer", { flow = config, pageaction = pageaction, redirect = redirect, state = state, autoapply = config.autoapply }) end end function cbi(model, config) return {type = "cbi", config = config, model = model, target = _cbi} end local function _arcombine(self, ...) local argv = {...} local target = #argv > 0 and self.targets[2] or self.targets[1] setfenv(target.target, self.env) target:target(unpack(argv)) end function arcombine(trg1, trg2) return {type = "arcombine", env = getfenv(), target = _arcombine, targets = {trg1, trg2}} end local function _form(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local maps = luci.cbi.load(self.model, ...) local state = nil for i, res in ipairs(maps) do local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end http.header("X-CBI-State", state or 0) tpl.render("header") for i, res in ipairs(maps) do res:render() end tpl.render("footer") end function form(model) return {type = "cbi", model = model, target = _form} end translate = i18n.translate -- This function does not actually translate the given argument but -- is used by build/i18n-scan.pl to find translatable entries. function _(text) return text end
apache-2.0
Fenix-XI/Fenix
scripts/globals/items/meat_chiefkabob.lua
18
1449
----------------------------------------- -- ID: 4574 -- Item: meat_chiefkabob -- Food Effect: 60Min, All Races ----------------------------------------- -- Strength 5 -- Agility 1 -- Intelligence -2 -- Attack % 22 -- Attack Cap 65 ----------------------------------------- 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,3600,4574); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 65); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 65); end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Navukgo_Execution_Chamber/Zone.lua
20
1305
----------------------------------- -- -- Zone: Navukgo_Execution_Chamber (64) -- ----------------------------------- package.loaded["scripts/zones/Navukgo_Execution_Chamber/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Navukgo_Execution_Chamber/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-660.185,-12.079,-199.532,192); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
Fenix-XI/Fenix
scripts/globals/spells/bluemagic/spiral_spin.lua
31
2001
----------------------------------------- -- Spell: Spiral Spin -- Chance of effect varies with TP. Additional Effect: Accuracy Down -- Spell cost: 39 MP -- Monster Type: Vermin -- Spell Type: Physical (Slashing) -- Blue Magic Points: 3 -- Stat Bonus: STR+1 HP+5 -- Level: 60 -- Casting Time: 4 seconds -- Recast Time: 45 seconds -- Skillchain property: Transfixion (can open Compression, Reverberation, or Distortion) -- Combos: Plantoid Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_TRANSFIXION; params.numhits = 1; params.multiplier = 1.925; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 60; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.30; params.int_wsc = 0.10; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 4) then local typeEffect = EFFECT_ACCURACY_DOWN; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
8devices/carambola2-luci
modules/admin-full/luasrc/model/cbi/admin_system/startup.lua
67
2805
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010-2012 Jo-Philipp Wich <xm@subsignal.org> Copyright 2010 Manuel Munz <freifunk at somakoma dot de> 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$ ]]-- require "luci.fs" require "luci.sys" require "luci.util" local inits = { } for _, name in ipairs(luci.sys.init.names()) do local index = luci.sys.init.index(name) local enabled = luci.sys.init.enabled(name) if index < 255 then inits["%02i.%s" % { index, name }] = { name = name, index = tostring(index), enabled = enabled } end end m = SimpleForm("initmgr", translate("Initscripts"), translate("You can enable or disable installed init scripts here. Changes will applied after a device reboot.<br /><strong>Warning: If you disable essential init scripts like \"network\", your device might become inaccessible!</strong>")) m.reset = false m.submit = false s = m:section(Table, inits) i = s:option(DummyValue, "index", translate("Start priority")) n = s:option(DummyValue, "name", translate("Initscript")) e = s:option(Button, "endisable", translate("Enable/Disable")) e.render = function(self, section, scope) if inits[section].enabled then self.title = translate("Enabled") self.inputstyle = "save" else self.title = translate("Disabled") self.inputstyle = "reset" end Button.render(self, section, scope) end e.write = function(self, section) if inits[section].enabled then inits[section].enabled = false return luci.sys.init.disable(inits[section].name) else inits[section].enabled = true return luci.sys.init.enable(inits[section].name) end end start = s:option(Button, "start", translate("Start")) start.inputstyle = "apply" start.write = function(self, section) luci.sys.call("/etc/init.d/%s %s >/dev/null" %{ inits[section].name, self.option }) end restart = s:option(Button, "restart", translate("Restart")) restart.inputstyle = "reload" restart.write = start.write stop = s:option(Button, "stop", translate("Stop")) stop.inputstyle = "remove" stop.write = start.write f = SimpleForm("rc", translate("Local Startup"), translate("This is the content of /etc/rc.local. Insert your own commands here (in front of 'exit 0') to execute them at the end of the boot process.")) t = f:field(TextValue, "rcs") t.rmempty = true t.rows = 20 function t.cfgvalue() return luci.fs.readfile("/etc/rc.local") or "" end function f.handle(self, state, data) if state == FORM_VALID then if data.rcs then luci.fs.writefile("/etc/rc.local", data.rcs:gsub("\r\n", "\n")) end end return true end return m, f
apache-2.0
facebokiii/ghosto
plugins/urbandictionary.lua
11
1055
local doc = [[ /urbandictionary <query> Returns a definition from Urban Dictionary. ]] local triggers = { '^/u[rban]*d[ictionary]*[@'..bot.username..']*', '^/urban[@'..bot.username..']*' } local action = function(msg) local input = msg.text:input() if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else sendReply(msg, doc) return end end local url = 'http://api.urbandictionary.com/v0/define?term=' .. URL.escape(input) local jstr, res = HTTP.request(url) if res ~= 200 then sendReply(msg, config.errors.connection) return end local jdat = JSON.decode(jstr) if jdat.result_type == "no_results" then sendReply(msg, config.errors.results) return end local message = '"' .. jdat.list[1].word .. '"\n' .. jdat.list[1].definition:trim() if string.len(jdat.list[1].example) > 0 then message = message .. '\n\nExample:\n' .. jdat.list[1].example:trim() end sendReply(msg, message) end return { action = action, triggers = triggers, doc = doc }
gpl-2.0
Jezza/Lava
src/test/resources/MultiTask.lua
1
1900
-- $Header: //info.ravenbrook.com/project/jili/version/1.1/test/mnj/lua/MultiTask.lua#1 $ -- Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). -- All rights reserved. -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject -- to the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -- ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -- CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- See MultiTask.java which uses this script (to illustrate multi-tasking) -- This script excepts to receive two arguments: -- The first argument is a thread identifier, -- the second argument is used to create a port (passed to mkport). -- This script uses the read and mkport functions defined by the -- MultiTask.java host code. local id, p = ... print("Script: " .. id) local port = mkport(p) local a = '' -- accumulates all the strings returned by read() while true do local s = read(port) if s == '' then break end a = a .. s print("Script: " .. id .. string.rep(' ', 8*id) .. " got [" .. s .. "]") end return a
lgpl-3.0
marcel-sch/luci
modules/luci-base/luasrc/model/uci.lua
49
4995
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local os = require "os" local uci = require "uci" local util = require "luci.util" local table = require "table" local setmetatable, rawget, rawset = setmetatable, rawget, rawset local require, getmetatable = require, getmetatable local error, pairs, ipairs = error, pairs, ipairs local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack -- The typical workflow for UCI is: Get a cursor instance from the -- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.), -- save the changes to the staging area via Cursor.save and finally -- Cursor.commit the data to the actual config files. -- LuCI then needs to Cursor.apply the changes so deamons etc. are -- reloaded. module "luci.model.uci" cursor = uci.cursor APIVERSION = uci.APIVERSION function cursor_state() return cursor(nil, "/var/state") end inst = cursor() inst_state = cursor_state() local Cursor = getmetatable(inst) function Cursor.apply(self, configlist, command) configlist = self:_affected(configlist) if command then return { "/sbin/luci-reload", unpack(configlist) } else return os.execute("/sbin/luci-reload %s >/dev/null 2>&1" % table.concat(configlist, " ")) end end -- returns a boolean whether to delete the current section (optional) function Cursor.delete_all(self, config, stype, comparator) local del = {} if type(comparator) == "table" then local tbl = comparator comparator = function(section) for k, v in pairs(tbl) do if section[k] ~= v then return false end end return true end end local function helper (section) if not comparator or comparator(section) then del[#del+1] = section[".name"] end end self:foreach(config, stype, helper) for i, j in ipairs(del) do self:delete(config, j) end end function Cursor.section(self, config, type, name, values) local stat = true if name then stat = self:set(config, name, type) else name = self:add(config, type) stat = name and true end if stat and values then stat = self:tset(config, name, values) end return stat and name end function Cursor.tset(self, config, section, values) local stat = true for k, v in pairs(values) do if k:sub(1, 1) ~= "." then stat = stat and self:set(config, section, k, v) end end return stat end function Cursor.get_bool(self, ...) local val = self:get(...) return ( val == "1" or val == "true" or val == "yes" or val == "on" ) end function Cursor.get_list(self, config, section, option) if config and section and option then local val = self:get(config, section, option) return ( type(val) == "table" and val or { val } ) end return nil end function Cursor.get_first(self, conf, stype, opt, def) local rv = def self:foreach(conf, stype, function(s) local val = not opt and s['.name'] or s[opt] if type(def) == "number" then val = tonumber(val) elseif type(def) == "boolean" then val = (val == "1" or val == "true" or val == "yes" or val == "on") end if val ~= nil then rv = val return false end end) return rv end function Cursor.set_list(self, config, section, option, value) if config and section and option then return self:set( config, section, option, ( type(value) == "table" and value or { value } ) ) end return false end -- Return a list of initscripts affected by configuration changes. function Cursor._affected(self, configlist) configlist = type(configlist) == "table" and configlist or {configlist} local c = cursor() c:load("ucitrack") -- Resolve dependencies local reloadlist = {} local function _resolve_deps(name) local reload = {name} local deps = {} c:foreach("ucitrack", name, function(section) if section.affects then for i, aff in ipairs(section.affects) do deps[#deps+1] = aff end end end) for i, dep in ipairs(deps) do for j, add in ipairs(_resolve_deps(dep)) do reload[#reload+1] = add end end return reload end -- Collect initscripts for j, config in ipairs(configlist) do for i, e in ipairs(_resolve_deps(config)) do if not util.contains(reloadlist, e) then reloadlist[#reloadlist+1] = e end end end return reloadlist end -- curser, means it the parent unloads or loads configs, the sub state will -- do so as well. function Cursor.substate(self) Cursor._substates = Cursor._substates or { } Cursor._substates[self] = Cursor._substates[self] or cursor_state() return Cursor._substates[self] end local _load = Cursor.load function Cursor.load(self, ...) if Cursor._substates and Cursor._substates[self] then _load(Cursor._substates[self], ...) end return _load(self, ...) end local _unload = Cursor.unload function Cursor.unload(self, ...) if Cursor._substates and Cursor._substates[self] then _unload(Cursor._substates[self], ...) end return _unload(self, ...) end
apache-2.0
DarkstarProject/darkstar
scripts/globals/mobskills/pw_groundburst.lua
11
1089
--------------------------------------------- -- Groundburst -- -- Description: Expels a fireball on targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown radial -- Notes: Only used by notorious monsters, and from any Mamool Ja in besieged. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId() if (mobSkin == 1863) then return 0 else return 1 end end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 3 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,MOBPARAM_WIPE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT) return dmg end
gpl-3.0
br101/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/wifi.lua
25
1527
local ubus = require "ubus" local iwinfo = require "iwinfo" local function scrape() local metric_wifi_network_quality = metric("wifi_network_quality","gauge") local metric_wifi_network_bitrate = metric("wifi_network_bitrate","gauge") local metric_wifi_network_noise = metric("wifi_network_noise_dbm","gauge") local metric_wifi_network_signal = metric("wifi_network_signal_dbm","gauge") local u = ubus.connect() local status = u:call("network.wireless", "status", {}) for dev, dev_table in pairs(status) do for _, intf in ipairs(dev_table['interfaces']) do local ifname = intf['ifname'] if ifname ~= nil then local iw = iwinfo[iwinfo.type(ifname)] local labels = { channel = iw.channel(ifname), ssid = iw.ssid(ifname), bssid = iw.bssid(ifname), mode = iw.mode(ifname), ifname = ifname, country = iw.country(ifname), frequency = iw.frequency(ifname), device = dev, } local qc = iw.quality(ifname) or 0 local qm = iw.quality_max(ifname) or 0 local quality = 0 if qc > 0 and qm > 0 then quality = math.floor((100 / qm) * qc) end metric_wifi_network_quality(labels, quality) metric_wifi_network_noise(labels, iw.noise(ifname) or 0) metric_wifi_network_bitrate(labels, iw.bitrate(ifname) or 0) metric_wifi_network_signal(labels, iw.signal(ifname) or -255) end end end end return { scrape = scrape }
gpl-2.0
Fenix-XI/Fenix
scripts/zones/Selbina/npcs/Yulon-Polon.lua
13
3958
----------------------------------- -- Area: Selbina -- NPC: Yulon-Polon -- Type: Title Change NPC -- @pos 45.998 -16.273 15.739 248 ----------------------------------- require("scripts/globals/titles"); local title2 = { CORDON_BLEU_FISHER , ECOLOGIST , LIL_CUPID , ACE_ANGLER , GOLD_HOOK , MYTHRIL_HOOK , SILVER_HOOK , COPPER_HOOK , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { SAVIOR_OF_LOVE , HONORARY_CITIZEN_OF_SELBINA , THE_LOVE_DOCTOR , LU_SHANGLIKE_FISHER_KING , ORCISH_SERJEANT , BRONZE_QUADAV , YAGUDO_INITIATE , MOBLIN_KINSMAN , TEAM_PLAYER , DYNAMISVALKURM_INTERLOPER , DISTURBER_OF_SLUMBER , INTERRUPTER_OF_DREAMS , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { FODDERCHIEF_FLAYER , WARCHIEF_WRECKER , DREAD_DRAGON_SLAYER , OVERLORD_EXECUTIONER , DARK_DRAGON_SLAYER , ADAMANTKING_KILLER , BLACK_DRAGON_SLAYER , MANIFEST_MAULER , BEHEMOTHS_BANE , ARCHMAGE_ASSASSIN , HELLSBANE , GIANT_KILLER , LICH_BANISHER , JELLYBANE , BOGEYDOWNER , BEAKBENDER , SKULLCRUSHER , MORBOLBANE , GOLIATH_KILLER , MARYS_GUIDE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { SIMURGH_POACHER , ROC_STAR , SERKET_BREAKER , CASSIENOVA , THE_HORNSPLITTER , TORTOISE_TORTURER , MON_CHERRY , BEHEMOTH_DETHRONER , THE_VIVISECTOR , DRAGON_ASHER , EXPEDITIONARY_TROOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { ADAMANTKING_USURPER , OVERLORD_OVERTHROWER , DEITY_DEBUNKER , FAFNIR_SLAYER , ASPIDOCHELONE_SINKER , NIDHOGG_SLAYER , MAAT_MASHER , KIRIN_CAPTIVATOR , CACTROT_DESACELERADOR , LIFTER_OF_SHADOWS , TIAMAT_TROUNCER , VRTRA_VANQUISHER , WORLD_SERPENT_SLAYER , XOLOTL_XTRAPOLATOR , BOROKA_BELEAGUERER , OURYU_OVERWHELMER , VINEGAR_EVAPORATOR , VIRTUOUS_SAINT , BYEBYE_TAISAI , TEMENOS_LIBERATOR , APOLLYON_RAVAGER , WYRM_ASTONISHER , NIGHTMARE_AWAKENER , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2711,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); 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==0x2711) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Apollyon/npcs/Radiant_Aureole.lua
12
6386
----------------------------------- -- Area: Appolyon -- NPC: Radiant_Aureole -- @pos ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/keyitems"); package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); if (player:hasKeyItem(COSMOCLEANSE)) then if (count==1 and trade:hasItemQty(2127,1)) then-- metal chip player:setVar("Limbus_Trade_Item",32); player:tradeComplete(); player:messageSpecial(CHIP_TRADE); player:startEvent(0x7d00,0,0,0,32,0,0,0,0); player:setVar("limbusbitmap",32); elseif (count==4 and trade:hasItemQty(1988,1) and trade:hasItemQty(1987,1) and trade:hasItemQty(1910,1) and trade:hasItemQty(1909,1)) then player:setVar("Limbus_Trade_Item",16); player:tradeComplete(); player:messageSpecial(CHIP_TRADE); player:startEvent(0x7d00,0,0,0,16,0,0,0,0); player:setVar("limbusbitmap",16); end else player:messageSpecial(CONDITION_FOR_LIMBUS); print("error player don't have cosmo clean"); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local instancelist ={}; local limbusbitmap = 0 ; local AllowLimbusToPlayer = true ; local currentlimbus= TryTobackOnCurrentLimbus(player); if ( npc:getID() == 16933242) then instancelist = APPOLLYON_SE_NE_BCNM_LIST; else instancelist = APPOLLYON_NW_SW_BCNM_LIST; end printf("currentlimbus: %u",currentlimbus); if (player:hasKeyItem(COSMOCLEANSE)) then if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then local LimbusTradeItem = player:getVar("Limbus_Trade_Item"); for nt = 1,table.getn (instancelist),2 do -- printf("list d'instance: %u",instancelist[nt]); if (instancelist[nt+1][1]==true and player:hasKeyItem(WHITE_CARD)) then -- print("player_have_white_card"); limbusbitmap = limbusbitmap + instancelist[nt+1][4]; -- printf("bitmapadd: %u",instancelist[nt+1][4]); end if (instancelist[nt+1][2]==true and player:hasKeyItem(RED_CARD)) then -- print("player_have_red_card"); limbusbitmap = limbusbitmap + instancelist[nt+1][4]; -- printf("bitmapadd: %u",instancelist[nt+1][4]); end if (instancelist[nt+1][3]==true and player:hasKeyItem(BLACK_CARD)) then -- print("player_have_black_card"); limbusbitmap = limbusbitmap + instancelist[nt+1][4]; -- printf("bitmapadd: %u",instancelist[nt+1][4]); end end limbusbitmap= limbusbitmap + LimbusTradeItem; ----- /////////////////////////////////////////////on doit ajouter le mipmap pour l'item trade ici else local status = player:getStatusEffect(EFFECT_BATTLEFIELD); local playerbcnmid = status:getPower(); -- check if the player has the key item for the current battlefield for nt = 1,table.getn (instancelist),2 do -- printf("list d'instance: %u",instancelist[nt]); if (instancelist[nt] == playerbcnmid) then if (instancelist[nt+1][1]== true and player:hasKeyItem(WHITE_CARD) == false) then AllowLimbusToPlayer = false; end if (instancelist[nt+1][2]== true and player:hasKeyItem(RED_CARD) == false ) then AllowLimbusToPlayer = false; end if (instancelist[nt+1][3]== true and player:hasKeyItem(BLACK_CARD) == false ) then AllowLimbusToPlayer = false; end if (AllowLimbusToPlayer == true) then --player have the correct key item for the current battflield limbusbitmap = instancelist[nt+1][4]; end end end end if (limbusbitmap~= 0 ) then player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0); player:setVar("limbusbitmap",limbusbitmap); else player:messageSpecial(CONDITION_FOR_LIMBUS); print("player need a card for basic limbus"); end elseif (currentlimbus~=0) then for nt = 1,table.getn (instancelist),2 do -- printf("list d'instance: %u",instancelist[nt]); if (instancelist[nt] == currentlimbus) then limbusbitmap = instancelist[nt+1][4]; end end player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0); player:setVar("limbusbitmap",limbusbitmap); else player:messageSpecial(CONDITION_FOR_LIMBUS); print("error player don't have cosmo clean"); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == 0x7d00) then if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then ResetPlayerLimbusVariable(player); player:setVar("characterLimbusKey",0); else local status = player:getStatusEffect(EFFECT_BATTLEFIELD); player:setVar("LimbusID",status:getPower()); player:setVar("characterLimbusKey",GetLimbusKeyFromInstance(status:getPower())); end player:updateEvent(2,player:getVar("limbusbitmap"),0,1,1,0); player:setVar("limbusbitmap",0); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x7d00) then end end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/items/piece_of_witch_nougat.lua
18
1272
----------------------------------------- -- ID: 5645 -- Item: piece_of_witch_nougat -- Food Effect: 1hour, All Races ----------------------------------------- -- HP 50 -- Intelligence 3 -- Agility -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,3600,5645); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 50); target:addMod(MOD_INT, 3); target:addMod(MOD_AGI, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 50); target:delMod(MOD_INT, 3); target:delMod(MOD_AGI, -3); end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/aileens_delight.lua
11
1521
----------------------------------------- -- ID: 5674 -- Item: Aileen's Delight -- Food Effect: 60 Min, All Races ----------------------------------------- -- HP +50 -- MP +50 -- STR +4 -- DEX +4 -- VIT +4 -- AGI +4 -- INT +4 -- MND +4 -- CHR +4 -- MP recovered while healing +2 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD)) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,5674) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 50) target:addMod(dsp.mod.MP, 50) target:addMod(dsp.mod.STR, 4) target:addMod(dsp.mod.DEX, 4) target:addMod(dsp.mod.VIT, 4) target:addMod(dsp.mod.AGI, 4) target:addMod(dsp.mod.INT, 4) target:addMod(dsp.mod.MND, 4) target:addMod(dsp.mod.CHR, 4) target:addMod(dsp.mod.MPHEAL, 2) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 50) target:delMod(dsp.mod.MP, 50) target:delMod(dsp.mod.STR, 4) target:delMod(dsp.mod.DEX, 4) target:delMod(dsp.mod.VIT, 4) target:delMod(dsp.mod.AGI, 4) target:delMod(dsp.mod.INT, 4) target:delMod(dsp.mod.MND, 4) target:delMod(dsp.mod.CHR, 4) target:delMod(dsp.mod.MPHEAL, 2) end
gpl-3.0
Oarcinae/FactorioScenarioMultiplayerSpawn
lib/player_list.lua
1
1749
-- oarc_player_list.lua -- Mar 2019 -------------------------------------------------------------------------------- -- Player List GUI - My own version -------------------------------------------------------------------------------- function CreatePlayerListGuiTab(tab_container, player) local scrollFrame = tab_container.add{type="scroll-pane", name="playerList-panel", direction = "vertical"} ApplyStyle(scrollFrame, my_player_list_fixed_width_style) scrollFrame.horizontal_scroll_policy = "never" AddLabel(scrollFrame, "online_title_msg", "Online Players:", my_label_header_style) for _,player in pairs(game.connected_players) do local caption_str = player.name.." ["..player.force.name.."]".." ("..formattime_hours_mins(player.online_time)..")" if (player.admin) then AddLabel(scrollFrame, player.name.."_plist", caption_str, my_player_list_admin_style) else AddLabel(scrollFrame, player.name.."_plist", caption_str, my_player_list_style) end end -- List offline players if (global.ocfg.list_offline_players) then AddSpacerLine(scrollFrame) AddLabel(scrollFrame, "offline_title_msg", "Offline Players:", my_label_header_grey_style) for _,player in pairs(game.players) do if (not player.connected) then local caption_str = player.name.." ["..player.force.name.."]".." ("..formattime_hours_mins(player.online_time)..")" local text = scrollFrame.add{type="label", caption=caption_str, name=player.name.."_plist"} ApplyStyle(text, my_player_list_offline_style) end end end end
mit
soheildiscover/soheil
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
punisherbot/-
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
DarkstarProject/darkstar
scripts/globals/abilities/pets/arcuballista.lua
12
1169
--------------------------------------------------- -- Arcuballista --------------------------------------------------- require("scripts/globals/status") require("scripts/globals/settings") require("scripts/globals/automatonweaponskills") --------------------------------------------------- function onMobSkillCheck(target, automaton, skill) local master = automaton:getMaster() return master:countEffect(dsp.effect.FIRE_MANEUVER) end function onPetAbility(target, automaton, skill, master, action) local params = { numHits = 1, atkmulti = 1, accBonus = 100, ftp100 = 2.5, ftp200 = 3.0, ftp300 = 4.0, acc100 = 0.0, acc200 = 0.0, acc300 = 0.0, str_wsc = 0.0, dex_wsc = 0.5, vit_wsc = 0.0, agi_wsc = 0.0, int_wsc = 0.0, mnd_wsc = 0.0, chr_wsc = 0.0 } if USE_ADOULIN_WEAPON_SKILL_CHANGES then params.ftp100 = 7.0 params.ftp200 = 10.0 params.ftp300 = 13.0 end local damage = doAutoRangedWeaponskill(automaton, target, 0, params, skill:getTP(), true, skill, action) return damage end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Ifrits_Cauldron/npcs/Treasure_Coffer.lua
13
5076
----------------------------------- -- Area: Ifrit's Cauldron -- NPC: Treasure Coffer -- @zone 205 -- @pos 188 0 -28 ----------------------------------- package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Ifrits_Cauldron/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1053,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1053,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local zone = player:getZoneID(); local AFHandsActivated = player:getVar("BorghertzAlreadyActiveWithJob"); local listAF = getAFbyZone(zone); if (player:hasKeyItem(MAP_OF_IFRITS_CAULDRON) == false) then questItemNeeded = 3; end if (AFHandsActivated == 13 and player:hasKeyItem(OLD_GAUNTLETS) == false) then questItemNeeded = 1; else for nb = 1,table.getn(listAF),3 do if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(OLD_GAUNTLETS); player:messageSpecial(KEYITEM_OBTAINED,OLD_GAUNTLETS); -- Old Gauntlets (KI) elseif (questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end elseif (questItemNeeded == 3) then player:addKeyItem(MAP_OF_IFRITS_CAULDRON); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_IFRITS_CAULDRON); -- Map of Ifrit's Cauldron (KI) else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1053); 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
Fenix-XI/Fenix
scripts/globals/mobskills/Dark_Wave.lua
33
1185
--------------------------------------------- -- Dark Wave -- -- Description: A wave of dark energy washes over targets in an area of effect. Additional effect: Bio -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: 10' radial -- Notes: Severity of Bio effect varies by time of day, from 8/tic at midday to 20/tic at midnight. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_BIO; local cTime = VanadielHour(); local power = 8; if (12 <= cTime) then local power = 8 + (cTime - 11); end MobStatusEffectMove(mob, target, typeEffect, power, 3, 60); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_DARK,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/abilities/drain_samba_ii.lua
25
1434
----------------------------------- -- Ability: Drain Samba II -- Inflicts the next target you strike with Drain Daze, allowing all those engaged in battle with it to drain its HP. -- Obtained: Dancer Level 35 -- TP Required: 25% -- Recast Time: 1:00 -- Duration: 1:30 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 250) then return MSGBASIC_NOT_ENOUGH_TP,0; else return 0,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(250); end; local duration = 120 + player:getMod(MOD_SAMBA_DURATION); duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100; player:delStatusEffect(EFFECT_HASTE_SAMBA); player:delStatusEffect(EFFECT_ASPIR_SAMBA); player:addStatusEffect(EFFECT_DRAIN_SAMBA,2,0,duration); end;
gpl-3.0
marcel-sch/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/wifi_add.lua
50
4887
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local nw = require "luci.model.network" local fw = require "luci.model.firewall" local uci = require "luci.model.uci".cursor() local http = require "luci.http" local iw = luci.sys.wifi.getiwinfo(http.formvalue("device")) local has_firewall = fs.access("/etc/config/firewall") if not iw then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) return end m = SimpleForm("network", translate("Join Network: Settings")) m.cancel = translate("Back to scan results") m.reset = false function m.on_cancel() local dev = http.formvalue("device") http.redirect(luci.dispatcher.build_url( dev and "admin/network/wireless_join?device=" .. dev or "admin/network/wireless" )) end nw.init(uci) fw.init(uci) m.hidden = { device = http.formvalue("device"), join = http.formvalue("join"), channel = http.formvalue("channel"), mode = http.formvalue("mode"), bssid = http.formvalue("bssid"), wep = http.formvalue("wep"), wpa_suites = http.formvalue("wpa_suites"), wpa_version = http.formvalue("wpa_version") } if iw and iw.mbssid_support then replace = m:field(Flag, "replace", translate("Replace wireless configuration"), translate("An additional network will be created if you leave this unchecked.")) function replace.cfgvalue() return "1" end else replace = m:field(DummyValue, "replace", translate("Replace wireless configuration")) replace.default = translate("The hardware is not multi-SSID capable and the existing " .. "configuration will be replaced if you proceed.") function replace.formvalue() return "1" end end if http.formvalue("wep") == "1" then key = m:field(Value, "key", translate("WEP passphrase"), translate("Specify the secret encryption key here.")) key.password = true key.datatype = "wepkey" elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and (m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2") then key = m:field(Value, "key", translate("WPA passphrase"), translate("Specify the secret encryption key here.")) key.password = true key.datatype = "wpakey" --m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk" end newnet = m:field(Value, "_netname_new", translate("Name of the new network"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code>" )) newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan" newnet.datatype = "uciname" if has_firewall then fwzone = m:field(Value, "_fwzone", translate("Create / Assign firewall-zone"), translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it.")) fwzone.template = "cbi/firewall_zonelist" fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan" end function newnet.parse(self, section) local net, zone if has_firewall then local zval = fwzone:formvalue(section) zone = fw:get_zone(zval) if not zone and zval == '-' then zval = m:formvalue(fwzone:cbid(section) .. ".newzone") if zval and #zval > 0 then zone = fw:add_zone(zval) end end end local wdev = nw:get_wifidev(m.hidden.device) wdev:set("disabled", false) wdev:set("channel", m.hidden.channel) if replace:formvalue(section) then local n for _, n in ipairs(wdev:get_wifinets()) do wdev:del_wifinet(n) end end local wconf = { device = m.hidden.device, ssid = m.hidden.join, mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta") } if m.hidden.wep == "1" then wconf.encryption = "wep-open" wconf.key = "1" wconf.key1 = key and key:formvalue(section) or "" elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk" wconf.key = key and key:formvalue(section) or "" else wconf.encryption = "none" end if wconf.mode == "adhoc" or wconf.mode == "sta" then wconf.bssid = m.hidden.bssid end local value = self:formvalue(section) net = nw:add_network(value, { proto = "dhcp" }) if not net then self.error = { [section] = "missing" } else wconf.network = net:name() local wnet = wdev:add_wifinet(wconf) if wnet then if zone then fw:del_network(net:name()) zone:add_network(net:name()) end uci:save("wireless") uci:save("network") uci:save("firewall") luci.http.redirect(wnet:adminlink()) end end end if has_firewall then function fwzone.cfgvalue(self, section) self.iface = section local z = fw:get_zone_by_network(section) return z and z:name() end end return m
apache-2.0
Fenix-XI/Fenix
scripts/globals/abilities/warlocks_roll.lua
5
2594
----------------------------------- -- Ability: Warlock's Roll -- Enhances magic accuracy for party members within area of effect -- Optimal Job: Red Mage -- Lucky Number: 4 -- Unlucky Number: 8 -- Level: 46 -- -- Die Roll |No RDM |With RDM -- -------- -------- ----------- -- 1 |+2 |+7 -- 2 |+3 |+8 -- 3 |+4 |+9 -- 4 |+12 |+17 -- 5 |+5 |+10 -- 6 |+6 |+11 -- 7 |+7 |+12 -- 8 |+1 |+6 -- 9 |+8 |+13 -- 10 |+9 |+14 -- 11 |+15 |+20 -- Bust |-5 |-5 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/ability"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = EFFECT_WARLOCKS_ROLL ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else return 0,0; end end; ----------------------------------- -- onUseAbilityRoll ----------------------------------- function onUseAbility(caster,target,ability,action) if (caster:getID() == target:getID()) then corsairSetup(caster, ability, action, EFFECT_WARLOCKS_ROLL, JOB_RDM); end local total = caster:getLocalVar("corsairRollTotal") return applyRoll(caster,target,ability,action,total) end; function applyRoll(caster,target,ability,action,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {2, 3, 4, 12, 5, 6, 7, 1, 8, 9, 15, 5} local effectpower = effectpowers[total]; if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then effectpower = effectpower + 5 end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_WARLOCKS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_MACC) == false) then ability:setMsg(422); elseif total > 11 then ability:setMsg(426); end return total; end
gpl-3.0
tcatm/luci
applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson 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$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
apache-2.0
Fenix-XI/Fenix
scripts/zones/Dangruf_Wadi/npcs/qm3.lua
13
1989
----------------------------------- -- NPC: ??? (QM3) -- Type: Saltvix dice roll game part 2 -- @zone: 191 -- Involved in quest "As Thick As Thieves" ----------------------------------- package.loaded["scripts/zones/Dangruf_Wadi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Dangruf_Wadi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local thickAsThievesGamblingCS = player:getVar("thickAsThievesGamblingCS"); if (thickAsThievesGamblingCS == 2) then if (trade:hasItemQty(936,1) and trade:getItemCount() == 1) then -- Trade 1x rock slat local rand1 = math.random(1,999); local rand2 = math.random(1,999); if (rand1 > rand2) then player:startEvent(0x0088,1092,0,rand1,rand2); -- complete 1/3 gamble mini quest else player:startEvent(0x008b,0,0,rand1,rand2); -- player looses end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) 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 == 0x008b and option == 1) then -- player looses dice game player:tradeComplete(); player:setVar("thickAsThievesGamblingCS",2); elseif (csid == 0x0088 and option == 0) then -- player wins dice game player:tradeComplete(); player:setVar("thickAsThievesGamblingCS",3); end end;
gpl-3.0