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
kidaa/FFXIOrgins
scripts/globals/items/slice_of_dhalmel_meat.lua
1
1294
----------------------------------------- -- ID: 4359 -- Item: slice_of_dhalmel_meat -- Food Effect: 5Min, Galka only ----------------------------------------- -- Strength 3 -- Intelligence -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if(target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4359); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -5); end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Windurst_Woods/npcs/Nokkhi_Jinjahl.lua
4
9812
----------------------------------- -- Area: Windurst Woods -- NPC: Nokkhi Jinjahl -- Type: Traveling Merchant NPC -- @zone: 241 -- @pos: 3.306 0.84 -41.601 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local carnation = trade:getItemQty(948) ----------------ARROWS---------------------------- --antlion = (trade:getItemQty(19195) / 99) local beetle = (trade:getItemQty(18154) / 99) local demon = (trade:getItemQty(18159) / 99) --gargouille = (trade:getItemQty(19800) / 99) local horn = (trade:getItemQty(18156) / 99) local irona = (trade:getItemQty(17320) / 99) local kabura = (trade:getItemQty(17325) / 99) --ruszor = (trade:getItemQty(19182) / 99) local scorpion = (trade:getItemQty(18155) / 99) local silvera = (trade:getItemQty(17321) / 99) local sleepa = (trade:getItemQty(18158) / 99) ----------------BOLTS----------------------------- local acid = (trade:getItemQty(18148) / 99) --adamana = (trade:getItemQty(19801) / 99) local blind = (trade:getItemQty(18150) / 99) local bloody = (trade:getItemQty(18151) / 99) --darka = (trade:getItemQty(19183) / 99) --darkling = (trade:getItemQty(19196) / 99) local darksteel = (trade:getItemQty(17338) / 99) local holy = (trade:getItemQty(18153) / 99) local mythril = (trade:getItemQty(17337) / 99) local sleepb = (trade:getItemQty(18149) / 99) local venom = (trade:getItemQty(18152) / 99) ----------------BULLETS--------------------------- --adamanb = (trade:getItemQty(19803) / 99) local bullet = (trade:getItemQty(17340) / 99) local bronze = (trade:getItemQty(17343) / 99) --darkb = (trade:getItemQty(19184) / 99) --dweomer = (trade:getItemQty(19198) / 99) local ironb = (trade:getItemQty(17312) / 99) --oberons = (trade:getItemQty(19199) / 99) --orichalcum= (trade:getItemQty(19802) / 99) local silverb = (trade:getItemQty(17341) / 99) local steel = (trade:getItemQty(18723) / 99) local spartan = (trade:getItemQty(18160) / 99) ----------------CARDS----------------------------- --fire = (trade:getItemQty(2176) / 99) --ice = (trade:getItemQty(2177) / 99) --wind = (trade:getItemQty(2178) / 99) --earth = (trade:getItemQty(2179) / 99) --thunder = (trade:getItemQty(2180) / 99) --water = (trade:getItemQty(2181) / 99) --light = (trade:getItemQty(2182) / 99) --dark = (trade:getItemQty(2183) / 99) ----------------------------------------------------- local quiver = (beetle + demon + horn + irona + kabura + scorpion + silvera + sleepa + acid + blind + bloody + darksteel + holy + mythril + sleepb + venom + bullet + bronze + ironb + silverb + steel + spartan) if(((quiver * 99) + carnation) == count) then if((quiver == math.floor(quiver)) and (quiver == carnation) and (player:getFreeSlotsCount() >= carnation)) then player:tradeComplete(); --if(antlion > 0) then -- player:addItem(5819,antlion); -- player:messageSpecial(ITEM_OBTAINED,5819); --end if(beetle > 0) then player:addItem(4221,beetle); player:messageSpecial(ITEM_OBTAINED,4221); end if(demon > 0) then player:addItem(4224,demon); player:messageSpecial(ITEM_OBTAINED,4224); end --if(gargouille > 0) then -- player:addItem(5912,gargouille); -- player:messageSpecial(ITEM_OBTAINED,5912); --end if(horn > 0) then player:addItem(4222,horn); player:messageSpecial(ITEM_OBTAINED,4222); end if(irona > 0) then player:addItem(4225,irona); player:messageSpecial(ITEM_OBTAINED,4225); end if(kabura > 0) then player:addItem(5332,kabura); player:messageSpecial(ITEM_OBTAINED,5332); end --if(ruszor > 0) then -- player:addItem(5871,ruszor); -- player:messageSpecial(ITEM_OBTAINED,5871); --end if(scorpion > 0) then player:addItem(4223,scorpion); player:messageSpecial(ITEM_OBTAINED,4223); end if(silvera > 0) then player:addItem(4226,silvera); player:messageSpecial(ITEM_OBTAINED,4226); end if(sleepa > 0) then player:addItem(5333,sleepa); player:messageSpecial(ITEM_OBTAINED,5333); end if(acid > 0) then player:addItem(5335,acid); player:messageSpecial(ITEM_OBTAINED,5335); end --if(adamana > 0) then -- player:addItem(5913,adamana); -- player:messageSpecial(ITEM_OBTAINED,5913); --end if(blind > 0) then player:addItem(5334,blind); player:messageSpecial(ITEM_OBTAINED,5334); end if(bloody > 0) then player:addItem(5339,bloody); player:messageSpecial(ITEM_OBTAINED,5339); end --if(darka > 0) then -- player:addItem(5872,darka); -- player:messageSpecial(ITEM_OBTAINED,5872); --end --if(darkling > 0) then -- player:addItem(5820,darkling); -- player:messageSpecial(ITEM_OBTAINED,5820); --end if(darksteel > 0) then player:addItem(4229,darksteel); player:messageSpecial(ITEM_OBTAINED,4229); end if(holy > 0) then player:addItem(5336,holy); player:messageSpecial(ITEM_OBTAINED,5336); end if(mythril > 0) then player:addItem(4228,mythril); player:messageSpecial(ITEM_OBTAINED,4228); end if(sleepb > 0) then player:addItem(5337,sleepb); player:messageSpecial(ITEM_OBTAINED,5337); end if(venom > 0) then player:addItem(5338,venom); player:messageSpecial(ITEM_OBTAINED,5338); end --if(adamanb > 0) then -- player:addItem(5915,adamanb); -- player:messageSpecial(ITEM_OBTAINED,5915); --end if(bullet > 0) then player:addItem(5363,bullet); player:messageSpecial(ITEM_OBTAINED,5363); end if(bronze > 0) then player:addItem(5359,bronze); player:messageSpecial(ITEM_OBTAINED,5359); end --if(darkb > 0) then -- player:addItem(5873,darkb); -- player:messageSpecial(ITEM_OBTAINED,5873); --end --if(dweomer > 0) then -- player:addItem(5822,dweomer); -- player:messageSpecial(ITEM_OBTAINED,5822); --end if(ironb > 0) then player:addItem(5353,ironb); player:messageSpecial(ITEM_OBTAINED,5353); end --if(oberons > 0) then -- player:addItem(5823,oberons); -- player:messageSpecial(ITEM_OBTAINED,5823); --end --if(orichalcum > 0) then -- player:addItem(5914,orichalcum); -- player:messageSpecial(ITEM_OBTAINED,5914); --end if(silverb > 0) then player:addItem(5340,silverb); player:messageSpecial(ITEM_OBTAINED,5340); end if(steel > 0) then player:addItem(5416,steel); player:messageSpecial(ITEM_OBTAINED,5416); end if(spartan > 0) then player:addItem(5341,spartan); player:messageSpecial(ITEM_OBTAINED,5341); end --if(fire > 0) then -- player:addItem(5402,fire); -- player:messageSpecial(ITEM_OBTAINED,5402); --end --if(ice > 0) then -- player:addItem(5403,ice); -- player:messageSpecial(ITEM_OBTAINED,5403); --end --if(wind > 0) then -- player:addItem(5404,wind); -- player:messageSpecial(ITEM_OBTAINED,5404); --end --if(earth > 0) then -- player:addItem(5405,earth); -- player:messageSpecial(ITEM_OBTAINED,5405); --end --if(thunder > 0) then -- player:addItem(5406,thunder); -- player:messageSpecial(ITEM_OBTAINED,5406); --end --if(water > 0) then -- player:addItem(5407,water); -- player:messageSpecial(ITEM_OBTAINED,5407); --end --if(light > 0) then -- player:addItem(5408,light); -- player:messageSpecial(ITEM_OBTAINED,5408); --end --if(dark > 0) then -- player:addItem(5409,dark); -- player:messageSpecial(ITEM_OBTAINED,5409); --end end end --948 - carnation --SINGLE--ARROWS----------------STACK --19195 - antlion arrow - 5819 --18154 - beetle arrow - 4221 --18159 - demon arrow - 4224 --19800 - gargouille arrow - 5912 --18156 - horn arrow - 4222 --17320 - iron arrow - 4225 --17325 - kabura arrow - 5332 --19182 - ruszor arrow - 5871 --18155 - scorpion arrow - 4223 --17321 - silver arrow - 4226 --18158 - sleep arrow - 5333 ----------BOLTS----------------------- --18148 - acid bolt - 5335 --19801 - adaman bolt - 5913 --18150 - blind bolt - 5334 --18151 - bloody bolt - 5339 --19183 - dark adaman bolt - 5872 --19196 - darkling bolt - 5820 --17338 - darksteel bolt - 4229 --18153 - holy bolt - 5336 --17337 - mythril bolt - 4228 --18149 - sleep bolt - 5337 --18152 - venom bolt - 5338 ----------BULLETS--------------------- --19803 - adaman bullet - 5915 --17340 - bullet - 5363 --17343 - bronze bullet - 5359 --19184 - dark adaman bullet- 5873 --19198 - dweomer bullet - 5822 --17312 - iron bullet - 5353 --19199 - oberon's bullet - 5823 --19802 - orichalcum bullet - 5914 --17341 - silver bullet - 5340 --18723 - steel bullet - 5416 --18160 - spartan bullet - 5341 ----------CARDS----------------------- --2176 - fire card - 5402 --2177 - ice card - 5403 --2178 - wind card - 5404 --2179 - earth card - 5405 --2180 - thunder card - 5406 --2181 - water card - 5407 --2182 - light card - 5408 --2183 - dark card - 5409 -------------------------------------- end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x029b,npc:getID()); 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
jiang42/Algorithm-Implementations
Run_Length_Encoding/Lua/Yonaba/rle_test.lua
26
1931
-- Tests for rle.lua local rle = require 'rle' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Encoding string tests', function() assert(rle.encode('W') == '1W') assert(rle.encode('WWWW') == '4W') assert(rle.encode('wwwwwiiiikkkkkkkiiippppppeeeeeddddiia') == '5w4i7k3i6p5e4d2i1a') assert(rle.encode('BBBBBBBBBBBBNBBBBBBBBBBBBNNNBBBBBBBBBBBBBBBBBBBBBBBBNBBBBBBBBBBBBBB') == '12B1N12B3N24B1N14B') assert(rle.encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW') == '12W1B12W3B24W1B14W') end) run('Decoding string tests', function() assert(rle.decode(rle.encode('WW')) == 'WW') assert(rle.decode(rle.encode('WWWW')) == 'WWWW') assert(rle.decode(rle.encode('wwwwwiiiikkkkkkkiiippppppeeeeeddddiia')) == 'wwwwwiiiikkkkkkkiiippppppeeeeeddddiia') assert(rle.decode(rle.encode('BBBBBBBBBBBBNBBBBBBBBBBBBNNNBBBBBBBBBBBBBBBBBBBBBBBBNBBBBBBBBBBBBBB')) == 'BBBBBBBBBBBBNBBBBBBBBBBBBNNNBBBBBBBBBBBBBBBBBBBBBBBBNBBBBBBBBBBBBBB') assert(rle.decode(rle.encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')) == 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW') end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
Fatalerror66/ffxi-a
scripts/zones/Valkurm_Dunes/npcs/Swirling_Vortex.lua
2
1301
----------------------------------- -- Area: Valkurm Dunes -- NPC: Swirling Vortex -- Entrance to Lufaise Meadows ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if(player:hasCompletedMission(COP,THE_MOTHERCRYSTALS)) then player:startEvent(0x000c); else player:messageSpecial(AN_EMPTY_LIGHT_SWIRLS); 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 == 0x000c and option == 1) then toLufaiseMeadows(player); end end;
gpl-3.0
actionless/awesome
tests/examples/wibox/widget/graph/subpixel.lua
2
1399
--DOC_GEN_IMAGE --DOC_HIDE local parent = ... --DOC_HIDE local wibox = require("wibox") --DOC_HIDE local data = { --DOC_HIDE 3, 5, 6,4, 11,15,19,29,17,17,14,0,0,3,1,0,0, 22, 17,7, 1,0,0,5, --DOC_HIDE } --DOC_HIDE local l = wibox.layout { --DOC_HIDE forced_height = 100, --DOC_HIDE forced_width = 100, --DOC_HIDE spacing = 0, --DOC_HIDE layout = wibox.layout.flex.vertical --DOC_HIDE } --DOC_HIDE for _, small_step in ipairs {1, 1/2, 1/3} do _ = small_step --DOC_HIDE silence luacheck unused var warning end --DOC_HIDE actually use truncated numbers, hopefully helps with reproducibility for _, small_step in ipairs {1, 0.5, 21845/65536} do --DOC_HIDE local w = --DOC_HIDE wibox.widget { -- width = 1000, max_value = 29, step_width = small_step, step_spacing = 0, color = "#ff0000", background_color = "#000000", border_width = 2, --DOC_HIDE margins = 0, --DOC_HIDE widget = wibox.widget.graph, } l:add(w) --DOC_HIDE for _ = 1, 16 do --DOC_HIDE repeat the data enough times to fill the graphs for _, v in ipairs(data) do --DOC_HIDE w:add_value(v) --DOC_HIDE end --DOC_HIDE end --DOC_HIDE end parent:add(l) --DOC_HIDE --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
Wedge009/wesnoth
data/campaigns/Secrets_of_the_Ancients/utils/zombie_recruit_dialog.lua
6
4416
local T = wml.tag local W = wml.fire local _ = wesnoth.textdomain 'wesnoth-sota' -- After preshow, this variable will hold the unit_types being shown in the listbox. local listedZombies = {} -- These two variables will be passed back to the WML engine. local recruitedType local recruitCost local zombies = wml.array_access.get("zombies") local sides = wesnoth.sides.find() local zombie_recruit_dialog = wml.load "campaigns/Secrets_of_the_Ancients/gui/zombie_recruit_dialog.cfg" local function preshow(dialog) local function select() -- TODO: why not use unit_preview_pane widget ? local unit_type = wesnoth.unit_types[ listedZombies[dialog.unit_list.selected_index] ] dialog.large_unit_sprite.label = unit_type.image .. "~RC(magenta>red)~XBRZ(2)" dialog.large_unit_type.label = "<span size='large'>" .. unit_type.name .. "</span>" dialog.unit_points.label = "<span color='#20dc00'><b>".. _"HP: ".. "</b>" .. unit_type.max_hitpoints .. "</span> | <span color='#00a0e1'><b>".. _"XP: ".. "</b>" .. unit_type.max_experience .. "</span> | <b>".. _"MP: ".. "</b>" .. unit_type.max_moves dialog.unit_attack.label = "<span color='#f5e6c1'> 6×2 " .. unit_type.attacks[1].description .. "</span>" dialog.damage_type.label = "<span color='#a69275'> melee–" .. unit_type.attacks[1].type .. "</span>" end dialog.unit_list.on_modified = select function dialog.help_button.on_button_click() W.open_help { topic="recruit_and_recall" } end function dialog.unit_help_button.on_button_click() W.open_help { topic="unit_" .. listedZombies[dialog.unit_list.selected_index] } end for i,z in ipairs(zombies) do if z.allow_recruit then local unit_type = wesnoth.unit_types[z.type] local afford_color_span_start = "" local afford_color_span_end = "" if sides[1].gold < unit_type.cost then afford_color_span_start = "<span color='red'>" afford_color_span_end = "</span>" end local list_item = dialog.unit_list:add_item() if z.sota_name_in_recruit_dialog then list_item.unit_type.label = afford_color_span_start .. z.sota_name_in_recruit_dialog .. afford_color_span_end else -- the player started the campaign with 1.15.6 or earlier list_item.unit_type.label = afford_color_span_start .. unit_type.name .. " " .. z.sota_variation .. afford_color_span_end end list_item.unit_sprite.label = unit_type.image .. "~RC(magenta>red)" list_item.unit_cost.label = afford_color_span_start .. unit_type.cost .. afford_color_span_end print("dialog.unit_list.size", dialog.unit_list.item_count) listedZombies[ dialog.unit_list.item_count ] = z.type end end dialog.unit_list.selected_index = 1 select() end local function postshow(dialog) recruitedType = listedZombies[dialog.unit_list.selected_index] recruitCost = wesnoth.unit_types[ recruitedType ].cost end -- Start execution -- -- Find out if there is at least one zombie in the list box. -- This will only be necessary if the WML changes, but it could, so we'll check. local zArrayIndex = 1 -- Start index of the WML array in lua. local zExists = false while zombies[zArrayIndex] and zExists == false do local z=zombies[zArrayIndex] if z.allow_recruit then zExists=true end zArrayIndex = zArrayIndex + 1 end wml.variables["recruitedZombieType"] = "cancel" -- default value if zExists==false then gui.show_prompt("", _ "There are no corpses available.", "") else local result = wesnoth.sync.evaluate_single(function() local res = gui.show_dialog(wml.get_child(zombie_recruit_dialog, 'resolution'), preshow, postshow) if res == -2 then return {recruitCost = 0, recruitedType = "cancel"} end if sides[1].gold < recruitCost then gui.show_prompt("", _ "You do not have enough gold to recruit that unit", "") return {recruitCost = 0, recruitedType = "cancel"} end return {recruitCost = recruitCost, recruitedType = recruitedType} end) wml.variables["recruitedZombieType"] = result.recruitedType wml.variables["recruitedZombieCost"] = result.recruitCost end
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/Sacrificial_Chamber/bcnms/temple_of_uggalepih.lua
4
2929
----------------------------------- -- Area: Sacrificial Chamber -- Name: Zilart Mission 4 -- @pos 299 0 349 163 ----------------------------------- package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Sacrificial_Chamber/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function OnBcnmRegister(player,instance) local randnum = math.random(1,3); local elemental = GetMobByID(17444868 + ((instance:getInstanceNumber() - 1) * 5)); -- TODO: Pet's magic resistance should probably change. if (randnum == 1) then -- Fire elemental:changeSkin(32); elemental:setSpellList(17); elseif (randnum == 2) then -- Water elemental:changeSkin(34); elemental:setSpellList(15); elseif (randnum == 3) then -- Light elemental:changeSkin(38); elemental:setSpellList(19); end end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function OnBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function OnBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if(player:hasCompletedMission(ZILART,THE_TEMPLE_OF_UGGALEPIH)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); --[[TODO: This simply fixes the cutscene leaving you at a black screen. It does not address @cs 7 and @cs 8 not playing after the victory cutscene. Loading those cutscenes onEventFinish also does not work, because of the "walk out" scene at the end. This is not a proper fix, this is not correct, but players are getting stuck, and it fixes that.]] if (csid == 32001 and option == 6) then player:updateEvent(0); end end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if(csid == 0x7d01) then player:addTitle(BEARER_OF_THE_WISEWOMANS_HOPE); if(player:hasKeyItem(SACRIFICIAL_CHAMBER_KEY)) then player:delKeyItem(SACRIFICIAL_CHAMBER_KEY); player:addKeyItem(DARK_FRAGMENT); player:messageSpecial(KEYITEM_OBTAINED,DARK_FRAGMENT); player:completeMission(ZILART,THE_TEMPLE_OF_UGGALEPIH); player:addMission(ZILART,HEADSTONE_PILGRIMAGE); end end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Dynamis-Beaucedine/Zone.lua
4
2096
----------------------------------- -- -- Zone: Dynamis-Beaucedine -- ----------------------------------- package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Dynamis-Beaucedine/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-284.751,-39.923,-422.948,235); end if((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBeaucedine]UniqueID")) then if(player:isBcnmsFull() == 1) then if(player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1284); if(inst == 1)then player:bcnmEnter(1284); else cs = 0; end else player:bcnmEnter(1284); end else inst = player:bcnmRegister(1284); if(inst == 1)then player:bcnmEnter(1284); else cs = 0; end end else cs = 0; 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); if(csid == 0) then player:setPos(-284.751,-39.923,-422.948,235,0x6F); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Abyssea-Konschtat/npcs/Atma_Fabricant.lua
33
1061
----------------------------------- -- Zone: Abyssea - Konschtat -- NPC: Atma Fabricant -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Konschtat/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/abyssea"); require("scripts/zones/Abyssea-Konschtat/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0886); 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
RockySeven3161/Unknown.
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
Puccio7/bot-telegram
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
apache-2.0
dromozoa/dromozoa-unix
bind/test/test_core.lua
5
3338
-- Copyright (C) 2018 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-bind. -- -- dromozoa-bind is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- dromozoa-bind 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 dromozoa-bind. If not, see <http://www.gnu.org/licenses/>. local bind = require "dromozoa.bind" local verbose = os.getenv "VERBOSE" == "1" -- -- result -- local function check_result(...) assert(select("#", ...) == 5) if verbose then print(...) end local a, b, c, d, e = ... assert(a == nil) assert(b == 0.25) assert(c == 42) assert(d == true) assert(e == "foo") end check_result(bind.core.result_int()) check_result(bind.core.result_void()) local function check_none_or_nil(n, ...) assert(select("#", ...) == n) assert(... == nil) end -- -- push -- check_none_or_nil(0, bind.core.push_none()) check_none_or_nil(1, bind.core.push_nil()) assert(bind.core.push_enum() == 42) local function check_string(...) assert(select("#", ...) == 14) if verbose then print(...) end for i = 1, 5 do assert(select(i, ...) == "あいうえお") end assert(select(6, ...) == "foo\0bar\0baz") for i = 7, 10 do assert(select(i, ...) == "foo") end for i = 11, 14 do assert(select(i, ...) == "bar") end end check_string(bind.core.push_string()) assert(bind.core.push_success() == true) assert(bind.core.push_success(42) == 42) -- -- error -- local function check_error(fn, expect) local result, message = pcall(fn) if verbose then print(result, message) end assert(not result) if expect then assert(message:find(expect, 1, true)) end end bind.core.unexpected() check_error(bind.core.throw, "exception caught: runtime_error") check_error(bind.core.field_error1, "field nil not an integer") check_error(bind.core.field_error2, "field userdata:") check_error(bind.core.field_error3, [[field "\1\2\3\4\5\6\a\b\t\n\v\f\r\14\15\16]]) check_error(bind.core.field_error4, [[field "foo\0bar\0baz"]]) -- -- field -- local t = bind.core.set_field(16) assert(#t == 16) for i = 1, 16 do assert(t[i] == i) end assert(t.foo == "bar") assert(t.baz == "qux") local t = bind.core.set_metafield() assert(getmetatable(t)["dromozoa.bind.a"] == 42) assert(getmetatable(t)["dromozoa.bind.b"] == "あいうえお") -- -- failure -- local result, message, code = bind.core.failure1() assert(not result) assert(message == "failure1") assert(not code) local result, message, code = bind.core.failure2() assert(not result) assert(message == "failure2") assert(code == 69) local result, message, code = bind.core.failure3() assert(not result) assert(message == "failure3") assert(not code) local result, message, code = bind.core.failure4() assert(not result) assert(message == "failure4") assert(code == 69) -- -- top_saver -- local result = bind.core.top_saver() assert(result == 0)
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/plate_of_dulcet_panettones.lua
3
1277
----------------------------------------- -- ID: 5979 -- Item: Plate of Dulcet Panettones -- Food Effect: 240 Min, All Races ----------------------------------------- -- MP % 6 Cap 105 -- Intelligence +8 -- MP Healing +4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5979); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 6); target:addMod(MOD_FOOD_MP_CAP, 105); target:addMod(MOD_INT, 8); target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 6); target:delMod(MOD_FOOD_MP_CAP, 105); target:delMod(MOD_INT, 8); target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Nashmau/npcs/Awaheen.lua
2
1788
----------------------------------- -- Area: Nashmau -- NPC: Awaheen -- Standard Info NPC ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade: Receive: -- 1 x Imperial Gold Piece (2187) 5 x Imperial Mythril Piece(2186) -- 1 x Imperial Mythril Piece(2186) 2 x Imperial Silver Piece(2185) -- 1 x Imperial Silver Piece (2185) 5 x Imperial Bronze Piece(2184) local nbr = 0; local reward = 0; if(trade:getItemCount() == 1)then if (trade:hasItemQty(2187,1))then nbr = 5 ; reward = 2186; elseif (trade:hasItemQty(2186,1))then nbr = 2 ; reward = 2185; elseif (trade:hasItemQty(2185,1))then nbr = 5 ; reward = 2184; end end if (reward > 0)then local boucle; if(player:getFreeSlotsCount() >= 1)then player:tradeComplete(); player:addItem(reward,nbr); for boucle=1,nbr,1 do player:messageSpecial(ITEM_OBTAINED,reward); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00F0); 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
Fatalerror66/ffxi-a
scripts/zones/Aht_Urhgan_Whitegate/npcs/Ironbound_Gate.lua
2
1212
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Ironbound Gate -- ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(npc:getID() == 16982050) then player:startEvent(0x0083); else player:startEvent(0x0082); 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 == 0x0083 and option == 1) then player:setPos(690,-18.5,220,128,0x33); --> Wajaom Woodlands, at northeastern tower elseif(csid == 0x0082 and option == 1) then player:setPos(570.5,-10.5,140,128,0x34); --> Bhaflau Thickets, at southeastern tower end end;
gpl-3.0
Segs/Segs
Data/scripts/Hazard_01_01/Spawndefs/Hellions_Perez.spawndef.lua
3
5408
--This is a rank table --There could be multiple tables to generate spawns from local Hellions_Ranks_01 = { ["Underlings"] = { --NA }, ["Minions"] = { "Thug_Hellion_01", "Thug_Hellion_02", "Thug_Hellion_03", "Thug_Hellion_04", "Thug_Hellion_05", "Thug_Hellion_06", }, ["SkullMinions"] = { "Thug_Skull_01", "Thug_Skull_02", "Thug_Skull_03", "Thug_Skull_04", "Thug_Skull_05", "Thug_Skull_06", }, ["Lieutenants"] = { "Thug_Hellion_01", "Thug_Hellion_02", "Thug_Hellion_03", "Thug_Hellion_04", "Thug_Hellion_05", "Thug_Hellion_06", }, ["Sniper"] = { --NA }, ["Boss"] = { "Thug_Hellion_Boss_01", "Thug_Hellion_Boss_02", "Thug_Hellion_Boss_03", }, ["Elite Boss"] = { --NA }, ["Victims"] = { }, ["Specials"] = { }, } local Vahzilok_Rumble_01 = { ["Minions"] = { "Slab_01", "Slab_02", "Slab_03", "Slab_04", "Cylok_01", "Cylok_02", "Cylok_03", "Cylok_04", "Cylok_Slab_01", "Cylok_Slab_02", "Cylok_Slab_03", "Cylok_Slab_04", }, ["Lieutenants"] = { "Reaper_01", "Reaper_02", "Reaper_03", "Reaper_04", "Reaper_05", "Reaper_06", "Reaper_07", "Reaper_08", "Reaper_09", "Reaper_10", "Reaper_11", "Reaper_12", "Reaper_13", "Reaper_14", "Reaper_15", "Reaper_16", }, ["Boss"] = { "Eidola_Male", "Eidola_Female", } } --[[ These are the spawndefs. ]] Loiter_Hellions_L1_3_V0 = { ["Markers"] = { ["Encounter_S_31"] = Hellions_Ranks_01.Lieutenants, ["Encounter_S_32"] = Hellions_Ranks_01.Boss, ["Encounter_E_06"] = Hellions_Ranks_01.Minions, ["Encounter_E_05"] = Hellions_Ranks_01.Minions, ["Encounter_E_07"] = Hellions_Ranks_01.Minions, ["Encounter_E_08"] = Hellions_Ranks_01.Minions, ["Encounter_E_01"] = Hellions_Ranks_01.Minions, }, } Loiter_Hellions_L1_3_V1 = Loiter_Hellions_L1_3_V0 Loiter_Hellions_L1_3_V2 = Loiter_Hellions_L1_3_V0 Loiter_Hellions_L1_3_V3 = Loiter_Hellions_L1_3_V0 Loiter_Hellions_L1_3_V4 = Loiter_Hellions_L1_3_V0 Loiter_Hellions_L4_7_V0 = { ["Markers"] = { ["Encounter_E_01"] = Hellions_Ranks_01.Minions, ["Encounter_E_02"] = Hellions_Ranks_01.Minions, ["Encounter_E_03"] = Hellions_Ranks_01.Minions, ["Encounter_E_04"] = Hellions_Ranks_01.Minions, ["Encounter_E_07"] = Hellions_Ranks_01.Minions, ["Encounter_E_05"] = Hellions_Ranks_01.Boss, }, } Loiter_Hellions_L4_7_V1 = Loiter_Hellions_L4_7_V0 Loiter_Hellions_L4_7_V2 = Loiter_Hellions_L4_7_V0 Loiter_Hellions_L4_7_V3 = Loiter_Hellions_L4_7_V0 Loiter_Hellions_L4_7_V4 = Loiter_Hellions_L4_7_V0 Loiter_Hellions_L8_10_V0 = { ["Markers"] = { ["Encounter_S_30"] = Hellions_Ranks_01.Lieutenants, ["Encounter_S_31"] = Hellions_Ranks_01.Boss, ["Encounter_S_32"] = Hellions_Ranks_01.Lieutenants, ["Encounter_E_01"] = Hellions_Ranks_01.Minions, ["Encounter_E_02"] = Hellions_Ranks_01.Minions, ["Encounter_E_03"] = Hellions_Ranks_01.Minions, ["Encounter_E_04"] = Hellions_Ranks_01.Minions, ["Encounter_E_05"] = Hellions_Ranks_01.Minions, ["Encounter_E_06"] = Hellions_Ranks_01.Minions, ["Encounter_E_07"] = Hellions_Ranks_01.Minions, ["Encounter_E_08"] = Hellions_Ranks_01.Minions, }, } Rumble_HellionsSkulls_L4_7_V0 = { ["Markers"] = { ["Encounter_E_09"] = Hellions_Ranks_01.Minions, ["Encounter_E_03"] = Hellions_Ranks_01.Lieutenants, ["Encounter_E_01"] = Hellions_Ranks_01.Minions, ["Encounter_E_11"] = Hellions_Ranks_01.Minions, ["Encounter_E_05"] = Hellions_Ranks_01.Minions, ["Encounter_E_07"] = Hellions_Ranks_01.Lieutenants, ["Encounter_S_33"] = Hellions_Ranks_01.Minions, ["Encounter_S_31"] = Hellions_Ranks_01.Minions, ["Encounter_S_35"] = Hellions_Ranks_01.Minions, ["Encounter_E_02"] = Vahzilok_Rumble_01.Minions, ["Encounter_E_10"] = Vahzilok_Rumble_01.Minions, ["Encounter_E_04"] = Vahzilok_Rumble_01.Minions, ["Encounter_E_12"] = Vahzilok_Rumble_01.Lieutenants, ["Encounter_E_06"] = Vahzilok_Rumble_01.Lieutenants, ["Encounter_E_08"] = Vahzilok_Rumble_01.Minions, ["Encounter_S_32"] = Vahzilok_Rumble_01.Minions, ["Encounter_S_34"] = Vahzilok_Rumble_01.Minions, ["Encounter_S_30"] = Vahzilok_Rumble_01.Minions, }, } Rumble_HellionsSkulls_L4_7_V1 = Rumble_HellionsSkulls_L4_7_V0 Rumble_HellionsSkulls_L4_7_V2 = Rumble_HellionsSkulls_L4_7_V0 Rumble_HellionsSkulls_L8_10_V0 = Rumble_HellionsSkulls_L4_7_V0 Rumble_HellionsSkulls_L8_10_V1 = Rumble_HellionsSkulls_L4_7_V0 Rumble_HellionsSkulls_L8_10_V2 = Rumble_HellionsSkulls_L4_7_V0
bsd-3-clause
LuaDist2/xlsxwriter
xlsxwriter/xmlwriter.lua
2
6498
---- -- Xmlwriter - A base class for xlsxwriter.lua xml classes. -- -- Copyright 2014, John McNamara, jmcnamara@cpan.org -- require "xlsxwriter.strict" local Xmlwriter = {} ---- -- The Xmlwriter object constructor. -- function Xmlwriter:new (instance) instance = instance or {} setmetatable(instance, self) self.__index = self return instance end ---- -- Create the XML writer filehandle for the object. -- function Xmlwriter:_set_xml_writer(filename) self.fh = assert(io.open(filename, "w")) self.internal_fh = true end ---- -- Set an externally created filehandle. Mainly for testing. -- function Xmlwriter:_set_filehandle(filehandle) self.fh = filehandle self.internal_fh = false end ---- -- Set the filename used in the zipfile. -- function Xmlwriter:_set_filename(filename) self.filename = filename end ---- -- Close the XML filehandle if we created it. -- function Xmlwriter:_xml_close() if self.internal_fh then self.fh:close() end end ---- -- Return all of the data in the current filehandle. -- function Xmlwriter:_get_data() self.fh:seek('set', 0) return self.fh:read('*a') end ---- -- Return all of the data in the current filehandle as an iterator. --Used by the ZipWriter module. -- function Xmlwriter:_get_xml_reader() self.fh:seek('set', 0) return function() local buffer = self.fh:read(4096) if buffer then return buffer end end end ---- -- Write the XML declaration. -- function Xmlwriter:_xml_declaration() self.fh:write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n') end ---- -- Write an XML start tag with optional attributes. -- function Xmlwriter:_xml_start_tag(tag, attributes) local attr = self._format_attributes(attributes) self.fh:write(string.format('<%s%s>', tag, attr)) end ---- -- Write an XML start tag with optional, unencoded, attributes. -- function Xmlwriter:_xml_start_tag_unencoded(tag, attributes) local attr = self._format_attributes_unencoded(attributes) self.fh:write(string.format('<%s%s>', tag, attr)) end ---- -- Write an XML end tag. -- function Xmlwriter:_xml_end_tag(tag) self.fh:write(string.format('</%s>', tag)) end ---- -- Write an XML empty tag with optional attributes. -- function Xmlwriter:_xml_empty_tag(tag, attributes) local attr = self._format_attributes(attributes) self.fh:write(string.format('<%s%s/>', tag, attr)) end ---- -- Write an XML empty tag with optional, unencoded, attributes. -- function Xmlwriter:_xml_empty_tag_unencoded(tag, attributes) local attr = self._format_attributes_unencoded(attributes) self.fh:write(string.format('<%s%s/>', tag, attr)) end ---- -- Write an XML element containing data with optional attributes. -- function Xmlwriter:_xml_data_element(tag, data, attributes) local attr = self._format_attributes(attributes) data = self._escape_data(data) self.fh:write(string.format('<%s%s>%s</%s>', tag, attr, data, tag)) end ---- -- Optimised tag writer for <c> cell string elements in the inner loop. -- function Xmlwriter:_xml_string_element(index, attributes) local attr = self._format_attributes(attributes) self.fh:write(string.format('<c%s t="s"><v>%d</v></c>', attr, index)) end ---- -- Optimised tag writer for shared strings <si> elements. -- function Xmlwriter:_xml_si_element(str, attributes) local attr = self._format_attributes(attributes) str = self._escape_data(str) self.fh:write(string.format('<si><t%s>%s</t></si>', attr, str)) end ---- -- Optimised tag writer for shared strings <si> rich string elements. -- function Xmlwriter:_xml_rich_si_element(str) self.fh:write(string.format('<si>%s</si>', str)) end ---- -- Optimised tag writer for <c> cell number elements in the inner loop. -- function Xmlwriter:_xml_number_element(number, attributes) local attr = self._format_attributes(attributes) self.fh:write(string.format('<c%s><v>%.15g</v></c>', attr, number)) end ---- -- Optimised tag writer for <c> cell formula elements in the inner loop. -- function Xmlwriter:_xml_formula_element(formula, result, attributes) local attr = self._format_attributes(attributes) formula = self._escape_data(formula) result = self._escape_data(result) self.fh:write(string.format('<c%s><f>%s</f><v>%s</v></c>', attr, formula, result)) end ---- -- Optimised tag writer for inlineStr cell elements in the inner loop. -- function Xmlwriter:_xml_inline_string(str, preserve, attributes) local attr = self._format_attributes(attributes) local t_attr = '' if preserve then t_attr = ' xml:space="preserve"' end str = self._escape_data(str) self.fh:write(string.format('<c%s t="inlineStr"><is><t%s>%s</t></is></c>', attr, t_attr, str)) end ---- -- Optimised tag writer for rich inlineStr in the inner loop. -- function Xmlwriter:_xml_rich_inline_string(str, attributes) local attr = self._format_attributes(attributes) str = self._escape_data(str) self.fh:write(string.format('<c%s t="inlineStr"><is>%s</is></c>', attr, str)) end ---- -- Format attribute value pairs. -- function Xmlwriter._format_attributes(attributes) local attr = '' if attributes then for i = 1, #attributes do for key, value in pairs(attributes[i]) do value = Xmlwriter._escape_attributes(value) attr = attr .. string.format(' %s="%s"', key, value) end end end return attr end ---- -- Format attribute value pairs with unencoded attributes. -- This is a minor speed optimisation for elements that -- don't need encoding. -- function Xmlwriter._format_attributes_unencoded(attributes) local attr = '' if attributes then for i = 1, #attributes do for key, value in pairs(attributes[i]) do attr = attr .. string.format(' %s="%s"', key, value) end end end return attr end ---- -- Escape XML characters in attributes. -- function Xmlwriter._escape_attributes(attribute) attribute = string.gsub(attribute, '&', '&amp;') attribute = string.gsub(attribute, '"', '&quot;') attribute = string.gsub(attribute, '<', '&lt;') attribute = string.gsub(attribute, '>', '&gt;') return attribute end ---- -- Escape XML characters in data sections of tags. Double quotes -- are not escaped by Excel in XML data. -- function Xmlwriter._escape_data(data) data = string.gsub(data, '&', '&amp;') data = string.gsub(data, '<', '&lt;') data = string.gsub(data, '>', '&gt;') return data end return Xmlwriter
mit
bartbes/lube-demo
NetPong-Server/Binary.lua
3
2717
--[[ Copyright © 2008 BartBes <bart.bes+nospam@gmail.com> 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. The above license is the MIT/X11 license, check the license for information about distribution. Also used: -LuaSocket (MIT license) Copyright © 2004-2007 Diego Nehab. All rights reserved. -Lua (MIT license) Copyright © 1994-2008 Lua.org, PUC-Rio. ]]-- bin = {} bin.__index = bin bin.null = string.char(30) bin.one = string.char(31) bin.defnull = bin.null bin.defone = bin.one function bin:setseperators(null, one) null = null or self.defnull one = one or self.defone self.null = null self.one = one end function bin:pack(t) local result = "" for i, v in pairs(t) do result = result .. self:packvalue(i, v) end return result end function bin:packvalue(i, v) local id = "" local typev = type(v) if typev == "string" then id = "S" elseif typev == "number" then id = "N" elseif typev == "boolean" then id = "B" elseif typev == "userdata" then id = "U" elseif typev == "nil" then id = "0" else error("Type " .. typev .. " is not supported by Binary.lua") return end return tostring(id .. bin.one .. i .. bin.one .. tostring(v) .. bin.null) end function bin:unpack(s) local t = {} local i, v for s2 in string.gmatch(s, "[^" .. bin.null .. "]+") do i, v = self:unpackvalue(s2) t[i] = v end return t end function bin:unpackvalue(s) local id = s:sub(1, 1) s = s:sub(3) local len = s:find(bin.one) local i = s:sub(1, len-1) local v = s:sub(len+1) if id == "N" then v = tonumber(v) elseif id == "B" then v = (v == "true") elseif id == "0" then v = nil end return i, v end
mit
3RaGaming/3Ra-Enhanced-Vanilla
showhealth.lua
1
1389
-- Show the health of a player as a small piece of colored text above their head -- A 3Ra Gaming creation local function showhealth (event) if game.tick % 30 ~= 0 then return end for k, player in pairs(game.players) do if player.connected then if player.character then if player.character.health == nil then return end local index = player.index local health = math.ceil(player.character.health) if global.player_health == nil then global.player_health = {} end if global.player_health[index] == nil then global.player_health[index] = health end if global.player_health[index] ~= health then global.player_health[index] = health if health < 250 then if health > 125 then player.surface.create_entity { name = "flying-text", color = { b = 0.2, r = 0.1, g = 1, a = 0.8 }, text = (health), position = { player.position.x, player.position.y - 2 } } elseif health > 74 then player.surface.create_entity { name = "flying-text", color = { r = 1, g = 1, b = 0 }, text = (health), position = { player.position.x, player.position.y - 2 } } else player.surface.create_entity { name = "flying-text", color = { b = 0.1, r = 1, g = 0, a = 0.8 }, text = (health), position = { player.position.x, player.position.y - 2 } } end end end end end end end Event.register(defines.events.on_tick, showhealth)
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Chamber_of_Oracles/npcs/Pedestal_of_Earth.lua
4
2190
----------------------------------- -- Area: Chamber of Oracles -- NPC: Pedestal of Earth -- Involved in Zilart Mission 7 -- @pos 199 -2 36 168 ------------------------------------- package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Chamber_of_Oracles/TextIDs"); ------------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ZilartStatus = player:getVar("ZilartStatus"); if(player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then if(player:hasKeyItem(EARTH_FRAGMENT)) then player:delKeyItem(EARTH_FRAGMENT); player:setVar("ZilartStatus",ZilartStatus + 4); player:messageSpecial(YOU_PLACE_THE,EARTH_FRAGMENT); if(ZilartStatus == 255) then player:startEvent(0x0001); end elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted. player:startEvent(0x0001); else player:messageSpecial(IS_SET_IN_THE_PEDESTAL,EARTH_FRAGMENT); end elseif(player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES)) then player:messageSpecial(HAS_LOST_ITS_POWER,EARTH_FRAGMENT); else player:messageSpecial(PLACED_INTO_THE_PEDESTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(csid == 0x0001) then player:addTitle(LIGHTWEAVER); player:setVar("ZilartStatus",0); player:addKeyItem(PRISMATIC_FRAGMENT); player:messageSpecial(KEYITEM_OBTAINED,PRISMATIC_FRAGMENT); player:completeMission(ZILART,THE_CHAMBER_OF_ORACLES); player:addMission(ZILART,RETURN_TO_DELKFUTTS_TOWER); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Bastok_Markets/npcs/Reinberta.lua
2
1971
----------------------------------- -- Area: Bastok Markets -- NPC: Reinberta -- Type: Goldsmithing Guild Master -- @pos -190.605 -7.814 -59.432 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); local SKILLID = 51; -- Goldsmithing ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILLID); if(newRank ~= 0) then player:setSkillRank(SKILLID,newRank); player:startEvent(0x012d,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILLID); local testItem = getTestItem(player,npc,SKILLID); local guildMember = isGuildMember(player,6); if(guildMember == 1) then guildMember = 150995375; end if(canGetNewRank(player,craftSkill,SKILLID) == 1) then getNewRank = 100; end player:startEvent(0x012c,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x012c 0x012d 0x0192 ----------------------------------- -- 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 == 0x012c and option == 1) then signupGuild(player,64); local crystal = math.random(4096,4101); if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); end end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/pipin_hot_popoto.lua
2
1230
----------------------------------------- -- ID: 4282 -- Item: pipin_hot_popoto -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 25 -- Vitality 3 -- HP recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4282); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_VIT, 3); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_VIT, 3); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
Segs/Segs
Data/scripts/City_02_01/Spawndefs/Outcasts_Steel.spawndef.lua
3
16177
--This is a rank table --There could be multiple tables to generate spawns from local Outcasts_Ranks_01 = { ["Underlings"] = { --NA }, ["Minions"] = { "Thug_Outcast_01", "Thug_Outcast_02", "Thug_Outcast_03", "Thug_Outcast_04", "Thug_Outcast_05", "Thug_Outcast_06", "Thug_Outcast_07", "Thug_Outcast_08", }, ["Lieutenants"] = { "Thug_Outcast_Boss_01", "Thug_Outcast_Boss_02", "Thug_Outcast_Boss_03", "Thug_Outcast_Boss_04", "Thug_Outcast_Boss_05", "Thug_Outcast_Boss_06", "Thug_Outcast_Boss_07", "Thug_Outcast_Boss_08", }, ["Sniper"] = { --NA }, ["Boss"] = { }, ["Elite Boss"] = { --NA }, ["Victims"] = { "FemaleNPC_51", "FemaleNPC_56", "FemaleNPC_52", "FemaleNPC_53", "FemaleNPC_54", "FemaleNPC_55", "MaleNPC_50", "MaleNPC_51", "MaleNPC_52", "MaleNPC_53", "MaleNPC_54", "MaleNPC_55", "MaleNPC_56", "MaleNPC_57", "MaleNPC_58", "MaleNPC_59", }, ["FemaleVictims"] = { "FemaleNPC_51", "FemaleNPC_56", "FemaleNPC_52", "FemaleNPC_54", "FemaleNPC_58", "FemaleNPC_57", }, ["Specials"] = { }, } local Trolls_Rumble_01 = { ["Minions"] = { "Thug_Troll_01", "Thug_Troll_02", "Thug_Troll_03", "Thug_Troll_04", "Thug_Troll_05", "Thug_Troll_06", }, ["Lieutenants"] = { "Thug_Troll_Boss_01", "Thug_Troll_Boss_02", "Thug_Troll_Boss_03", }, ["Boss"] = { } } local Family_Rumble_01 = { ["Minions"] = { "Thug_Family_01", "Thug_Family_02", "Thug_Family_03", "Thug_Family_04", "Thug_Family_05", "Thug_Family_06", }, ["Lieutenants"] = { "Thug_Family_Boss_01", "Thug_Family_Boss_02", }, ["Boss"] = { } } --== MUGGINGS ==-- Mugging_Outcasts_D1_V0 = { ["Markers"] = { ["Encounter_V_42"] = Outcasts_Ranks_01.Victims, ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_07"] = Outcasts_Ranks_01.Minions, ["Encounter_E_08"] = Outcasts_Ranks_01.Minions, }, } Mugging_Outcasts_D1_V1 = { ["Markers"] = { ["Encounter_V_42"] = Outcasts_Ranks_01.Victims, ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_07"] = Outcasts_Ranks_01.Minions, }, } Mugging_Outcasts_D1_V2 = { ["Markers"] = { ["Encounter_V_42"] = Outcasts_Ranks_01.Victims, ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_07"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, }, } Mugging_Outcasts_D1_V3 = { ["Markers"] = { ["Encounter_V_42"] = Outcasts_Ranks_01.Victims, ["Encounter_V_40"] = Outcasts_Ranks_01.Victims, ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_07"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_03"] = Outcasts_Ranks_01.Minions, ["Encounter_E_04"] = Outcasts_Ranks_01.Minions, }, } Mugging_Outcasts_D5_V0 = Mugging_Outcasts_D1_V0 Mugging_Outcasts_D5_V1 = Mugging_Outcasts_D1_V1 Mugging_Outcasts_D5_V2 = Mugging_Outcasts_D1_V2 Mugging_Outcasts_D5_V3 = Mugging_Outcasts_D1_V3 Mugging_Outcasts_D9_V0 = Mugging_Outcasts_D1_V0 Mugging_Outcasts_D9_V1 = Mugging_Outcasts_D1_V1 Mugging_Outcasts_D9_V2 = Mugging_Outcasts_D1_V2 Mugging_Outcasts_D9_V3 = Mugging_Outcasts_D1_V3 --== SHADY DEALS ==-- ShadyDeal_Outcasts_D1_V0 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, }, } ShadyDeal_Outcasts_D1_V1 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_S_32"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_E_04"] = Outcasts_Ranks_01.Minions, }, } ShadyDeal_Outcasts_D1_V2 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_S_32"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_E_04"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_08"] = Outcasts_Ranks_01.Minions, }, } ShadyDeal_Outcasts_D5_V0 = ShadyDeal_Outcasts_D1_V0 ShadyDeal_Outcasts_D5_V1 = ShadyDeal_Outcasts_D1_V1 ShadyDeal_Outcasts_D5_V2 = ShadyDeal_Outcasts_D1_V2 ShadyDeal_Outcasts_D9_V0 = ShadyDeal_Outcasts_D1_V0 ShadyDeal_Outcasts_D9_V1 = ShadyDeal_Outcasts_D1_V1 ShadyDeal_Outcasts_D9_V2 = ShadyDeal_Outcasts_D1_V2 --== FIGHT CLUB ==-- FightClub_Outcasts_D3_V0 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, }, } FightClub_Outcasts_D3_V1 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_04"] = Outcasts_Ranks_01.Lieutenants, }, } FightClub_Outcasts_D3_V2 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_04"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_08"] = Outcasts_Ranks_01.Minions, }, } FightClub_Outcasts_D8_V0 = FightClub_Outcasts_D3_V0 FightClub_Outcasts_D8_V1 = FightClub_Outcasts_D3_V1 FightClub_Outcasts_D8_V2 = FightClub_Outcasts_D3_V2 --== LOITERING ==-- Loiter_Outcasts_D3_V0 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, }, } Loiter_Outcasts_D3_V1 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_04"] = Outcasts_Ranks_01.Lieutenants, }, } Loiter_Outcasts_D3_V2 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_32"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_04"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_08"] = Outcasts_Ranks_01.Minions, }, } Loiter_Outcasts_D8_V0 = Loiter_Outcasts_D3_V0 Loiter_Outcasts_D8_V1 = Loiter_Outcasts_D3_V1 Loiter_Outcasts_D8_V2 = Loiter_Outcasts_D3_V2 --== PURSE SNATCH ==-- PurseSnatch_Outcasts_D1_V0 = { ["Markers"] = { ["Encounter_V_40"] = Outcasts_Ranks_01.FemaleVictims, ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, }, } PurseSnatch_Outcasts_D1_V1 = { ["Markers"] = { ["Encounter_V_40"] = Outcasts_Ranks_01.FemaleVictims, ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_03"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, }, } PurseSnatch_Outcasts_D1_V2 = { ["Markers"] = { ["Encounter_V_40"] = Outcasts_Ranks_01.FemaleVictims, ["Encounter_V_41"] = Outcasts_Ranks_01.Victims, ["Encounter_S_30"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_E_03"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Lieutenants, }, } PurseSnatch_Outcasts_D5_V0 = PurseSnatch_Outcasts_D1_V0 PurseSnatch_Outcasts_D5_V1 = PurseSnatch_Outcasts_D1_V1 PurseSnatch_Outcasts_D5_V2 = PurseSnatch_Outcasts_D1_V2 PurseSnatch_Outcasts_D9_V0 = PurseSnatch_Outcasts_D1_V0 PurseSnatch_Outcasts_D9_V1 = PurseSnatch_Outcasts_D1_V1 PurseSnatch_Outcasts_D9_V2 = PurseSnatch_Outcasts_D1_V2 --== VANDALISM ==-- Vandalism_Outcasts_D3_V0 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_02"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, }, } Vandalism_Outcasts_D3_V1 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_02"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_07"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, }, } Vandalism_Outcasts_D3_V2 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_05"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_06"] = Outcasts_Ranks_01.Minions, ["Encounter_E_03"] = Outcasts_Ranks_01.Minions, ["Encounter_E_02"] = Outcasts_Ranks_01.Minions, }, } Vandalism_Outcasts_D8_V0 = Vandalism_Outcasts_D3_V0 Vandalism_Outcasts_D8_V1 = Vandalism_Outcasts_D3_V1 Vandalism_Outcasts_D8_V2 = Vandalism_Outcasts_D3_V2 --== BREAK-INS ==-- BreakingIn_Outcasts_D3_V0 = { ["Markers"] = { ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_06"] = Outcasts_Ranks_01.Lieutenants, }, } BreakingIn_Outcasts_D3_V1 = { ["Markers"] = { ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_04"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_06"] = Outcasts_Ranks_01.Minions, }, } BreakingIn_Outcasts_D3_V2 = { ["Markers"] = { ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_S_30"] = Outcasts_Ranks_01.Minions, ["Encounter_E_01"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_02"] = Outcasts_Ranks_01.Minions, ["Encounter_E_04"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_06"] = Outcasts_Ranks_01.Minions, ["Encounter_E_08"] = Outcasts_Ranks_01.Minions, }, } BreakingIn_Outcasts_D8_V0 = BreakingIn_Outcasts_D3_V0 BreakingIn_Outcasts_D8_V1 = BreakingIn_Outcasts_D3_V1 BreakingIn_Outcasts_D8_V2 = BreakingIn_Outcasts_D3_V2 --==RUMBLE: Outcasts vs. Trolls ==-- Rumble_OutcastsTrolls_D1_V0 = { ["Markers"] = { ["Encounter_E_09"] = Outcasts_Ranks_01.Minions, ["Encounter_E_03"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_S_33"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_E_02"] = Trolls_Rumble_01.Minions, ["Encounter_E_10"] = Trolls_Rumble_01.Minions, ["Encounter_E_04"] = Trolls_Rumble_01.Minions, ["Encounter_E_06"] = Trolls_Rumble_01.Lieutenants, ["Encounter_S_32"] = Trolls_Rumble_01.Minions, ["Encounter_S_30"] = Trolls_Rumble_01.Minions, }, } Rumble_OutcastsTrolls_D1_V1 = { ["Markers"] = { ["Encounter_E_09"] = Outcasts_Ranks_01.Minions, ["Encounter_E_03"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_S_33"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_S_35"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_10"] = Trolls_Rumble_01.Minions, ["Encounter_E_12"] = Trolls_Rumble_01.Lieutenants, ["Encounter_E_08"] = Trolls_Rumble_01.Lieutenants, ["Encounter_S_32"] = Trolls_Rumble_01.Minions, ["Encounter_S_34"] = Trolls_Rumble_01.Lieutenants, ["Encounter_S_30"] = Trolls_Rumble_01.Minions, }, } Rumble_OutcastsTrolls_D1_V2 = { ["Markers"] = { ["Encounter_E_09"] = Outcasts_Ranks_01.Minions, ["Encounter_E_03"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_E_11"] = Outcasts_Ranks_01.Minions, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_E_07"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_S_33"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_S_35"] = Outcasts_Ranks_01.Minions, ["Encounter_E_02"] = Family_Rumble_01.Minions, ["Encounter_E_10"] = Family_Rumble_01.Minions, ["Encounter_E_04"] = Family_Rumble_01.Minions, ["Encounter_E_12"] = Family_Rumble_01.Lieutenants, ["Encounter_E_06"] = Family_Rumble_01.Lieutenants, ["Encounter_E_08"] = Family_Rumble_01.Minions, ["Encounter_S_32"] = Family_Rumble_01.Minions, ["Encounter_S_34"] = Family_Rumble_01.Minions, ["Encounter_S_30"] = Family_Rumble_01.Minions, }, } Rumble_OutcastsTrolls_D5_V0 = Rumble_OutcastsTrolls_D1_V0 Rumble_OutcastsTrolls_D5_V1 = Rumble_OutcastsTrolls_D1_V1 Rumble_OutcastsTrolls_D5_V2 = Rumble_OutcastsTrolls_D1_V2 --==RUMBLE: Outcasts vs. Family ==-- Negotiation_OutcastsFamily_D3_V0 = { ["Markers"] = { ["Encounter_E_03"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_05"] = Outcasts_Ranks_01.Minions, ["Encounter_S_33"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_E_10"] = Family_Rumble_01.Minions, ["Encounter_E_06"] = Family_Rumble_01.Lieutenants, ["Encounter_S_32"] = Family_Rumble_01.Minions, ["Encounter_S_30"] = Family_Rumble_01.Minions, }, } Negotiation_OutcastsFamily_D3_V1 = { ["Markers"] = { ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_S_33"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_S_35"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_12"] = Family_Rumble_01.Lieutenants, ["Encounter_E_08"] = Family_Rumble_01.Lieutenants, ["Encounter_S_34"] = Family_Rumble_01.Lieutenants, ["Encounter_S_30"] = Family_Rumble_01.Minions, }, } Negotiation_OutcastsFamily_D3_V2 = { ["Markers"] = { ["Encounter_E_09"] = Outcasts_Ranks_01.Minions, ["Encounter_E_03"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_E_01"] = Outcasts_Ranks_01.Minions, ["Encounter_E_07"] = Outcasts_Ranks_01.Lieutenants, ["Encounter_S_33"] = Outcasts_Ranks_01.Minions, ["Encounter_S_31"] = Outcasts_Ranks_01.Minions, ["Encounter_S_35"] = Outcasts_Ranks_01.Minions, ["Encounter_E_02"] = Family_Rumble_01.Minions, ["Encounter_E_10"] = Family_Rumble_01.Minions, ["Encounter_E_04"] = Family_Rumble_01.Lieutenants, ["Encounter_E_08"] = Family_Rumble_01.Minions, ["Encounter_S_32"] = Family_Rumble_01.Minions, ["Encounter_S_34"] = Family_Rumble_01.Lieutenants, ["Encounter_S_30"] = Family_Rumble_01.Minions, }, } Negotiation_OutcastsFamily_D8_V0 = Negotiation_OutcastsFamily_D3_V0 Negotiation_OutcastsFamily_D8_V1 = Negotiation_OutcastsFamily_D3_V1 Negotiation_OutcastsFamily_D8_V2 = Negotiation_OutcastsFamily_D3_V2
bsd-3-clause
nenau/naev
dat/missions/dvaered/dv_antiflf02.lua
2
14179
--[[ -- This is the second mission in the anti-FLF Dvaered campaign. The player is part of a Dvaered plot to smoke out the FLF base. -- stack variable flfbase_intro: -- 1 - The player has turned in the FLF agent or rescued the Dvaered crew. Conditional for dv_antiflf02 -- 2 - The player has rescued the FLF agent. Conditional for flf_pre02 -- 3 - The player has found the FLF base for the Dvaered, or has betrayed the FLF after rescuing the agent. Conditional for dv_antiflf03 --]] -- localization stuff, translators would work here include("fleethelper.lua") title = {} text = {} failtitle = {} failtext = {} osd_desc = {} comm_msg = {} title[1] = _("House Dvaered needs YOU") text[1] = _([[You join the Dvaered official at his table. He greets you in a cordial fashion, at least by Dvaered standards. You explain to him that you wish to know more about the anti-FLF operation that House Dvaered is supposedly working on. "Ah! It's good to see such righteous enthusiasm among our citizenry. Indeed, our forces have been preparing to deal a significant blow to the FLF terrorists. I can't disclose the details, of course - this is a military operation. However, if you have a combat-capable ship and enough sense of duty to assist us, there is an opportunity to serve alongside the real Dvaered warriors. How about it? Can we count on your support?"]]) title[2] = _("A clever ruse") text[2] = _([["Splendid. You have the right mindset, citizen. If only all were like you! But that is neither here nor there. Come, I will take you to the local command bunker. The details of this operation will be explained to you there." True to his word, the Dvaered liaison escorts you out of the spaceport bar, and within the hour you find yourself deep inside a highly secured Dvaered military complex. You are ushered into a room, in which you find a large table and several important-looking military men. At the head of the table sits a man whose name tag identifies him as Colonel Urnus. Evidently he's the man in charge. A Dvaered soldier instructs you to take a seat.]]) text[3] = _([[As you take the last empty seat at the table, Colonel Urnus starts the meeting. "Welcome, citizen. You know why you are here and you know what this meeting is about, so let me get right to the point. We have reason to believe the FLF terrorists are operating from a secret base of operations. We know this base is located somewhere in the nebula, and we have recently uncovered intel that indicates the base is likely to be in the %s system." One of the walls lights up, showing part of the galaxy map. The %s system is colored red, and it's pulsating gently. "Of course, we have conducted patrols in this system, but so far without result. Our sensors are severely impaired by the nebula in this system, so the chances of us finding the terrorist hive by our own devices are slim. Fortunately, our top strategists have come up with a ruse, one that will make the FLF come to us." "We will use a civilian ship - your ship, naturally - as a decoy," Urnus continues. The image on the wall zooms up to the %s system, and a white blip representing your ship appears near the jump point. "Your ship will be equipped with an IFF transponder in use by the FLF, so to anyone who isn't looking too closely you will appear as an FLF ship. Of course, this alone is not enough. The FLF will assume you know where their base is, since you look like one of them." The image on the wall updates again, this time showing several House Dvaered crests near your ship. "Some time after you enter the system, several of our military assets will jump in and open fire. To the FLF, it will look like one of their own has come under attack! Since their base is nearby, they will undoubtably send reinforcements to help their 'comrade' out of a tight situation."]]) text[4] = _([["As soon as the FLF ships join the battle, you and the Dvaered ships will disengage and target the FLF instead. Your mission is to render at least one of their ships incapable of fighting, and board it. You can then access the ship's computer and download the flight log, which will include the location of the FLF base. Take this information to a Dvaered base, and your mission will be complete." The image on the wall updates one last time, simulating the battle as described by Colonel Urnus. Several FLF logos appear, which are promptly surrounded by the Dvaered ones. Then the logos turn gray, indicating that they've been disabled. "Let me make one thing clear, citizen. You are allowed, even expected to fire on the Dvaered ships that are firing on you. However, you must make it look you're on the losing side, or the FLF will not come to your aid! So, do NOT disable or destroy any Dvaered ships, and make sure your own armor takes a bit of a beating. This is vital to the success of the mission. Do not fail." Colonel Urnus to have concluded his explanation, so you, having spotted the obvious flaw in the Dvaereds' plan, pop the question of what happens if the FLF never show up. "Well," the Colonel muses, "That will mean our intel was probably wrong. But don't worry, citizen, we'll get those terrorists eventually! Now, time is of the essence, so get to your ship and follow your orders. Dismissed!"]]) title[5] = _("Take no prisoners - only their logs") text[5] = _([[You successfully board the FLF ship and secure its flight logs. This is what the Dvaered want - you should take it to a Dvaered planet immediately.]]) title[6] = _("X marks the spot") text[6] = _([[As soon as you land, a Dvaered military operator contacts you and requests you turn over the flight log you procured from the FLF ship, so you do. The Dvaered are then silent for some twenty minutes, time you use to complete your post-landing routines. Then, you are summoned to the local Dvaered security station. Colonel Urnus welcomes you. "Well met, citizen. I have received word of your accomplishment in our recent operation. It seems HQ is quite pleased with the result, and they have instructed me to reward you appropriately." He hands you a credit chip that represents a decent sum of money, though you feel that a mere monetary reward doesn't begin to compensate for the insane plan the Dvaered made you part of. However, you wisely opt not to give voice to that thought. "In addition," Urnus resumes, "Dvaered military command has decided that you may participate in the upcoming battle against the FLF stronghold, in recognition of your courage and your skill in battle. You may contact our liaison whenever you're ready." That concludes the pleasantries, and you are unceremoniously deposited outside the security compound. But at least you earned some money - and a chance to see some real action.]]) refusetitle = _("House Dvaered is out of luck") refusetext = _([["I see. In that case, I'm going to have to ask you to leave. My job is to recruit a civilian, but you're clearly not the man I'm looking for. You may excuse yourself, citizen."]]) failtitle[1] = _("You ran away!") failtext[1] = _("You have left the system without first completing your mission. The operation ended in failure.") failtitle[2] = _("You fought too hard!") failtext[2] = _("You have disabled a Dvaered ship, thereby violating your orders. The operation is canceled thanks to you. The Dvaered are less than pleased.") failtitle[3] = _("All the FLF are dead!") failtext[3] = _("Unfortunately, all the FLF ships have been destroyed before you managed to board one of them. The operation ended in failure.") npc_desc = _("This must be the Dvaered liaison you heard about. Allegedly, he may have a job for you that involves fighting the Frontier Liberation Front.") misn_title = _("Lure out the FLF") osd_desc[1] = _("Fly to the %s system") osd_desc[2] = _("Wait for the Dvaered military to jump in and attack you") osd_desc[3] = _("Fight the Dvaered until the FLF step in") osd_desc[4] = _("Disable and board at least one FLF ship") osd_desc[5] = _("Return to any Dvaered world") misn_desc = _("You have been recruited to act as a red herring in a military operation of Dvaered design. Your chief purpose is to goad the FLF into showing themselves, then disabling and boarding one of their ships. You will fail this mission if you disable or destroy any Dvaered ship, or if you leave the system before the operation is complete.") comm_msg["enter"] = _("Here come the FLF! All units, switch to EMPs and disable the terrorist ships!") comm_msg["victory"] = _("All targets neutralized. Download the flight log and let's get out of here!") function create() missys = {system.get(var.peek("flfbase_sysname"))} if not misn.claim(missys) then abort() end misn.setNPC("Dvaered liaison", "dvaered/dv_military_m1") misn.setDesc(npc_desc) end function accept() if tk.yesno(title[1], text[1]) then destsysname = var.peek("flfbase_sysname") tk.msg(title[2], text[2]) tk.msg(title[2], string.format(text[3], destsysname, destsysname, destsysname)) tk.msg(title[2], text[4]) misn.accept() osd_desc[1] = string.format(osd_desc[1], destsysname) misn.osdCreate(misn_title, osd_desc) misn.setDesc(misn_desc) misn.setTitle(misn_title) marker = misn.markerAdd( system.get(destsysname), "low" ) missionstarted = false DVdisablefail = true logsfound = false flfdead = 0 misn.cargoAdd("FLF IFF Transponder", 0) hook.jumpout("jumpout") hook.enter("enter") hook.land("land") else tk.msg(refusetitle, refusetext) misn.finish() end end function jumpout() last_sys = system.cur() end function enter() if system.cur():name() == destsysname and not logsfound then pilot.clear() pilot.toggleSpawn(false) misn.osdActive(2) hook.timer(15000, "spawnDV") elseif missionstarted then -- The player has jumped away from the mission theater, which instantly ends the mission. tk.msg(failtitle[1], failtext[1]) faction.get("Dvaered"):modPlayerSingle(-10) abort() end end function land() if logsfound and planet.cur():faction():name() == "Dvaered" then tk.msg(title[6], text[6]) var.push("flfbase_intro", 3) faction.get("Dvaered"):modPlayerSingle(5) player.pay(70000) -- 70K misn.finish(true) end end function spawnDV() misn.osdActive(3) missionstarted = true fleetDV = pilot.add("Dvaered Strike Force", "dvaered_norun", last_sys) -- The Dvaered ships should attack the player, so set them hostile. -- These are Vigilances, so we should tune them WAY down so the player doesn't insta-die. for i, j in ipairs(fleetDV) do j:setHostile() j:setHilight(true) j:setVisplayer(true) j:rmOutfit("all") j:addOutfit("Turreted Gauss Gun", 1) j:addOutfit("Small Shield Booster", 1) j:addOutfit("Steering Thrusters", 1) j:addOutfit("Solar Panel", 1) hook.pilot(j, "disable", "disableDV") end hook.timer(500, "pollHealth") end -- Polls the player's health and the Dvaereds' shields, and spawns the FLF fleet if shields and armor are below a certain value. function pollHealth() shieldDV = 0 parmor, pshield = player.pilot():health() local maxshieldDV = 0 for i, j in ipairs(fleetDV) do maxshieldDV = maxshieldDV + j:stats()["shield"] armor, shield = j:health() shieldDV = shieldDV + shield end if parmor <= 60 and pshield <= 10 and shieldDV <= (maxshieldDV - 50) then spawnFLF() else hook.timer(500, "pollHealth") end end -- Spawn the FLF ships, reset the Dvaered. function spawnFLF() DVdisablefail = false -- The player no longer fails the mission if a Dvaered ship is disabled misn.osdActive(4) for i, j in ipairs(fleetDV) do j:setFriendly() j:setHilight(false) j:changeAI("dvaered_norun") j:setInvincPlayer() -- Re-outfit the ships to use disable weapons. Kind of ugly, should probably be handled via AI orders in the future. j:addOutfit("EMP Grenade Launcher", 3) end angle = rnd.rnd() * 2 * math.pi dist = 800 vecFLF = vec2.new(math.cos(angle) * dist, math.sin(angle) * dist) fleetFLF = addShips( "FLF Vendetta", "flf_norun", player.pilot():pos() + vecFLF, 4 ) flfactive = #fleetFLF fleetDV[1]:comm(comm_msg["enter"]) for i, j in ipairs(fleetFLF) do j:setHilight(true) j:setVisplayer() hook.pilot(j, "disable", "disableFLF") hook.pilot(j, "death", "deathFLF") hook.pilot(j, "board", "boardFLF") end end function disableDV() if DVdisablefail then -- Only true as long as the FLF aren't there yet tk.msg(failtitle[2], failtext[2]) faction.get("Dvaered"):modPlayerSingle(-10) abort() end end function disableFLF() flfactive = flfactive - 1 -- Persuade the Dvaered to stop shooting at disabled FLF for i, j in ipairs(fleetDV) do if j:exists() then if flfactive == 0 and not messaged then fleetDV[i]:comm(comm_msg["victory"]) messaged = true end j:changeAI("dvaered_norun") end end end function deathFLF() flfdead = flfdead + 1 if flfdead == 6 and not logsfound then tk.msg(failtitle[3], failtext[3]) abort() end end function boardFLF() misn.osdActive(5) tk.msg(title[5], text[5]) missionstarted = false logsfound = true player.unboard() misn.markerRm(marker) for i, j in ipairs(fleetDV) do if j:exists() then j:changeAI("flee") -- Make them jump out (if they're not dead!) end end for _, j in ipairs(fleetFLF) do if j:exists() then j:setHilight(false) j:setVisplayer(false) j:setNoboard(true) end end end function abort() misn.finish(false) end
gpl-3.0
amirattackerxyz/xyamirattacker
bot/utils.lua
473
24167
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 local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end 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 local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end 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
Segs/Segs
Data/scripts/Trial_01_01/entities.lua
3
1741
--- Abandoned Sewer Network local spawnOnce = false -- Called after MOTD for now. function player_connected(id) --Id is player entity Id printDebug('player_connected Id: ' .. tostring(id)) if spawnOnce == false then spinSpawners() spinPersists() RandomSpawn(0) --There are no SpawnDefs set up here yet spawnOnce = true end return '' end function npc_added(id) printDebug('npc_added Id: ' .. tostring(id)) Contacts.SpawnedContact(id) -- Spawn next contact Contacts.SpawnContacts('Atlas Park') return '' end entity_interact = function(id, location) Contacts.SetContactDialogsWithHeroName(heroName) if location ~= nil then printDebug("entity id " .. tostring(id) .. " location info: x: " .. tostring(location.x) .. " y: " .. tostring(location.y) .. " z: " .. tostring(location.z)) else printDebug("entity id " .. tostring(id)) end if(Contacts.OpenContactDialog(id) ~= true) then -- Generic NPC -- Create generic NPC message script for zone? end --[[ NPC chat message test MapClientSession.npcMessage(client, 'Hello Hero!', id) MapClientSession.npcMessage(client, 'What are you doing here?', id) ]] return "" end dialog_button = function(id) -- Will be called if no callback is set printDebug("No Callback set! ButtonId: " .. tostring(id)) return "" end contact_call = function(contactIndex) printDebug("Contact Call. contactIndex: " .. tostring(contactIndex)) return "" end revive_ok = function(id) printDebug("revive Ok. Entity: " .. tostring(id)) Character.respawn(client, 'Gurney'); -- Hospital Player.Revive(0); return "ok" end
bsd-3-clause
e1d1s1/OpenRA
mods/cnc/maps/nod09/nod09-AI.lua
5
6491
AttackPaths = { { AttackPath1 }, { AttackPath2 } } GDIBase = { GDICYard, GDIPyle, GDIWeap, GDIHQ, GDIProc, GDINuke1, GDINuke2, GDINuke3, GDIBuilding1, GDIBuilding2, GDIBuilding3, GDIBuilding4, GDIBuilding5, GDIBuilding6, GDIBuilding7, GDIBuilding8, GDIBuilding9, GDIBuilding10, GDIBuilding11 } GDIOrcas = { GDIOrca1, GDIOrca2 } InfantryAttackGroup = { } InfantryGroupSize = 5 InfantryProductionCooldown = DateTime.Minutes(3) InfantryProductionTypes = { "e1", "e1", "e2" } HarvesterProductionType = { "harv" } VehicleAttackGroup = { } VehicleGroupSize = 5 VehicleProductionCooldown = DateTime.Minutes(3) VehicleProductionTypes = { "jeep", "jeep", "mtnk", "mtnk", "mtnk", "msam" } StartingCash = 4000 BaseProc = { type = "proc", pos = CPos.New(54, 10), cost = 1500, exists = true } BaseNuke1 = { type = "nuke", pos = CPos.New(57, 7), cost = 500, exists = true } BaseNuke2 = { type = "nuke", pos = CPos.New(55, 7), cost = 500, exists = true } BaseNuke3 = { type = "nuke", pos = CPos.New(59, 7), cost = 500, exists = true } BaseNuke4 = { type = "nuke", pos = CPos.New(59, 10), cost = 500, exists = true } InfantryProduction = { type = "pyle", pos = CPos.New(49, 4), cost = 500, exists = true } VehicleProduction = { type = "weap", pos = CPos.New(51, 7), cost = 2000, exists = true } BaseBuildings = { BaseProc, BaseNuke1, BaseNuke2, BaseNuke3, BaseNuke4, InfantryProduction, VehicleProduction } AutoGuard = function(guards) Utils.Do(guards, function(guard) Trigger.OnDamaged(guard, function(guard) IdleHunt(guard) end) end) end BuildBase = function(cyard) Utils.Do(BaseBuildings, function(building) if not building.exists and not cyardIsBuilding then BuildBuilding(building, cyard) return end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end BuildBuilding = function(building, cyard) cyardIsBuilding = true Trigger.AfterDelay(Actor.BuildTime(building.type), function() cyardIsBuilding = false if cyard.IsDead or cyard.Owner ~= enemy then return end local actor = Actor.Create(building.type, true, { Owner = enemy, Location = building.pos }) enemy.Cash = enemy.Cash - building.cost building.exists = true if actor.Type == 'pyle' or actor.Type == 'hand' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(actor) end) elseif actor.Type == 'weap' or actor.Type == 'afld' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(actor) end) end Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end) end CheckForHarvester = function() local harv = enemy.GetActorsByType("harv") return #harv > 0 end GuardBase = function() Utils.Do(GDIBase, function(building) Trigger.OnDamaged(building, function(guard) Utils.Do(GDIOrcas, function(guard) if not guard.IsDead and not building.IsDead then guard.Guard(building) end end) end) end) end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function(enemy) local lazyUnits = enemy.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) IdleHunt(unit) end) end ProduceHarvester = function(building) if not buildingHarvester then buildingHarvester = true building.Build(HarvesterProductionType, function() buildingHarvester = false end) end end ProduceInfantry = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(InfantryProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) InfantryAttackGroup[#InfantryAttackGroup + 1] = unit[1] if #InfantryAttackGroup >= InfantryGroupSize then SendUnits(InfantryAttackGroup, Path) InfantryAttackGroup = { } Trigger.AfterDelay(InfantryProductionCooldown, function() ProduceInfantry(building) end) else Trigger.AfterDelay(delay, function() ProduceInfantry(building) end) end end) end ProduceVehicle = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then ProduceHarvester(building) Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(VehicleProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) VehicleAttackGroup[#VehicleAttackGroup + 1] = unit[1] if #VehicleAttackGroup >= VehicleGroupSize then SendUnits(VehicleAttackGroup, Path) VehicleAttackGroup = { } Trigger.AfterDelay(VehicleProductionCooldown, function() ProduceVehicle(building) end) else Trigger.AfterDelay(delay, function() ProduceVehicle(building) end) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end) end StartAI = function(cyard) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) enemy.Cash = StartingCash BuildBase(cyard) GuardBase() end Trigger.OnAllKilledOrCaptured(GDIBase, function() IdlingUnits(enemy) end) Trigger.OnKilled(GDIProc, function(building) BaseProc.exists = false end) Trigger.OnKilled(GDINuke1, function(building) BaseNuke1.exists = false end) Trigger.OnKilled(GDINuke2, function(building) BaseNuke2.exists = false end) Trigger.OnKilled(GDINuke3, function(building) BaseNuke3.exists = false end) Trigger.OnKilled(GDINuke4, function(building) BaseNuke4.exists = false end) Trigger.OnKilled(GDIPyle, function(building) InfantryProduction.exists = false end) Trigger.OnKilled(GDIWeap, function(building) VehicleProduction.exists = false end)
gpl-3.0
tboox/xmake-repo
packages/p/python/xmake.lua
1
7387
package("python") set_kind("binary") set_homepage("https://www.python.org/") set_description("The python programming language.") if is_host("windows") then if os.arch() == "x64" then add_urls("https://gitlab.com/xmake-mirror/python-releases/raw/master/python-$(version).amd64.zip", {alias = "py2"}) add_versions("py2:2.7.15", "b9d8157fe2ca58f84d29a814bedf1d304d2277ad02f0930acd22e2ce7367b77e") else add_urls("https://gitlab.com/xmake-mirror/python-releases/raw/master/python-$(version).win32.zip", {alias = "py2"}) add_versions("py2:2.7.15", "f34e2555c4fde5d7d746e6a0bbfc9151435f3f5c3eaddfc046ec0993b7cc9660") end if winos.version():gt("winxp") then if os.arch() == "x64" then add_urls("https://www.python.org/ftp/python/$(version)/python-$(version)-embed-amd64.zip", {alias = "py3"}) add_versions("py3:3.7.0", "0cc08f3c74c0112abc2adafd16a534cde12fe7c7aafb42e936d59fd3ab08fcdb") else add_urls("https://www.python.org/ftp/python/$(version)/python-$(version)-embed-win32.zip", {alias = "py3"}) add_versions("py3:3.7.0", "9596b23a8db1f945c2e26fe0dc1743e33f3700b4b708c68ea202cf2ac761a736") end else if os.arch() == "x64" then add_urls("https://gitlab.com/xmake-mirror/python-releases/raw/master/python-$(version).amd64.zip", {alias = "py3"}) add_versions("py3:3.3.4", "a83bf90b28f8b44b99c3524a34ab18f21a59999e07c107da19b031869fb42af1") else add_urls("https://gitlab.com/xmake-mirror/python-releases/raw/master/python-$(version).win32.zip", {alias = "py3"}) add_versions("py3:3.3.4", "c9843d585e30da1c7c85663543b2f6a1f68621e02d288abc5b5e54361d93ccd6") end end else set_urls("https://www.python.org/ftp/python/$(version)/Python-$(version).tgz", "https://github.com/xmake-mirror/cpython/releases/download/v$(version)/Python-$(version).tgz") add_versions("2.7.15", "18617d1f15a380a919d517630a9cd85ce17ea602f9bbdc58ddc672df4b0239db") add_versions("3.7.0", "85bb9feb6863e04fb1700b018d9d42d1caac178559ffa453d7e6a436e259fd0d") end if is_host("macosx", "linux") then add_deps("openssl", {host = true}) end on_load(function (package) package:data_set("install_resources", function() -- imports import("net.http") import("utils.archive") import("lib.detect.find_file") -- set python environments local version = package:version() local envs = {} if is_host("windows") and package:version():ge("3.0") then envs.PYTHONPATH = package:installdir("Lib", "site-packages") else envs.PYTHONPATH = package:installdir("lib", "python" .. version:major() .. "." .. version:minor(), "site-packages") end package:addenv("PYTHONPATH", envs.PYTHONPATH) -- install resources local resources = { setuptools = { url = "https://files.pythonhosted.org/packages/c2/f7/c7b501b783e5a74cf1768bc174ee4fb0a8a6ee5af6afa92274ff964703e0/setuptools-40.8.0.zip", sha256 = "6e4eec90337e849ade7103723b9a99631c1f0d19990d6e8412dc42f5ae8b304d" }, pip = { url = "https://files.pythonhosted.org/packages/36/fa/51ca4d57392e2f69397cd6e5af23da2a8d37884a605f9e3f2d3bfdc48397/pip-19.0.3.tar.gz", sha256 = "6e6f197a1abfb45118dbb878b5c859a0edbdd33fd250100bc015b67fded4b9f2" }, wheel = { url = "https://files.pythonhosted.org/packages/b7/cf/1ea0f5b3ce55cacde1e84cdde6cee1ebaff51bd9a3e6c7ba4082199af6f6/wheel-0.33.1.tar.gz", sha256 = "66a8fd76f28977bb664b098372daef2b27f60dc4d1688cfab7b37a09448f0e9d" } } local python = path.join(package:installdir("bin"), "python" .. (is_host("windows") and ".exe" or "")) for name, resource in pairs(resources) do local resourcefile = path.join(os.curdir(), path.filename(resource.url)) local resourcedir = resourcefile .. ".dir" http.download(resource.url, resourcefile) assert(resource.sha256 == hash.sha256(resourcefile), "resource(%s): unmatched checksum!", name) assert(archive.extract(resourcefile, resourcedir), "resource(%s): extract failed!", name) local setupfile = assert(find_file("setup.py", path.join(resourcedir, "*")), "resource(%s): setup.py not found!", name) local oldir = os.cd(path.directory(setupfile)) os.vrunv(python, {"setup.py", "install", "--prefix=" .. package:installdir()}, {envs = envs}) os.cd(oldir) end end) end) on_install("@windows", function (package) if package:version():ge("3.0") then os.cp("python.exe", path.join(package:installdir("bin"), "python3.exe")) else os.cp("python.exe", path.join(package:installdir("bin"), "python2.exe")) end os.mv("*.exe", package:installdir("bin")) os.mv("*.dll", package:installdir("bin")) os.cp("*", package:installdir()) package:data("install_resources")() end) on_install("@macosx", "@linux", function (package) -- init configs local configs = {"--enable-ipv6", "--without-ensurepip"} table.insert(configs, "--datadir=" .. package:installdir("share")) table.insert(configs, "--datarootdir=" .. package:installdir("share")) -- add openssl libs path for detecting local openssl_dir = package:dep("openssl"):installdir() if package:version():ge("3.0") then table.insert(configs, "--with-openssl=" .. openssl_dir) else io.gsub("setup.py", "/usr/local/ssl", openssl_dir) end -- allow python modules to use ctypes.find_library to find xmake's stuff if is_host("macosx") then io.gsub("Lib/ctypes/macholib/dyld.py", "DEFAULT_LIBRARY_FALLBACK = %[", format("DEFAULT_LIBRARY_FALLBACK = [ '%s/lib',", package:installdir())) end -- unset these so that installing pip and setuptools puts them where we want -- and not into some other Python the user has installed. import("package.tools.autoconf").configure(package, configs, {envs = {PYTHONHOME = "", PYTHONPATH = ""}}) os.vrunv("make", {"install", "-j4", "PYTHONAPPSDIR=" .. package:installdir()}) if package:version():ge("3.0") then os.cp(path.join(package:installdir("bin"), "python3"), path.join(package:installdir("bin"), "python")) os.cp(path.join(package:installdir("bin"), "python3-config"), path.join(package:installdir("bin"), "python-config")) end package:data("install_resources")() end) on_test(function (package) os.vrun("python --version") os.vrun("python -c \"import pip\"") os.vrun("python -c \"import setuptools\"") os.vrun("python -c \"import wheel\"") end)
apache-2.0
Fatalerror66/ffxi-a
scripts/zones/Windurst_Walls/npcs/Moan-Maon.lua
5
1038
----------------------------------- -- Area: Windurst Walls -- NPC: Moan-Maon -- Type: Standard NPC -- @zone: 239 -- @pos: 88.244 -6.32 148.912 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0133); 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
Fatalerror66/ffxi-a
scripts/zones/Metalworks/npcs/Glarociquet_TK.lua
5
1067
----------------------------------- -- Area: Metalworks -- NPC: Glarociquet, T.K. -- Type: Conquest Overseer -- @zone: 237 -- @pos: 17.057 -17 -28.755 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, GLAROCIQUET_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
Fatalerror66/ffxi-a
scripts/globals/weaponskills/shoulder_tackle.lua
6
1415
----------------------------------- -- Shoulder Tackle -- Hand-to-Hand weapon skill -- Skill Level: 40 -- Stuns target. Chance of stunning varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Aqua Gorget & Thunder Gorget. -- Aligned with the Aqua Belt & Thunder Belt. -- Element: None -- Modifiers: VIT:30% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); local chance = player:getTP()-100 > math.random()*150; if(damage > 0 and target:hasStatusEffect(EFFECT_STUN) == false) then target:addStatusEffect(EFFECT_STUN, 1, 0, 4); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Port_San_dOria/npcs/_6g7.lua
20
1144
----------------------------------- -- 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
kidaa/FFXIOrgins
scripts/zones/Windurst_Waters/npcs/Moreno-Toeno.lua
4
6645
----------------------------------- -- Area: Windurst Waters -- NPC: Morno-Toeno -- Starts and Finishes Quest: Teacher's Pet -- @pos 169 -2 159 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(WINDURST,TEACHER_S_PET) >= 1 and trade:hasItemQty(847,1) == true and trade:hasItemQty(4368,1) == true and trade:getGil() == 0 and trade:getItemCount() == 2) then player:startEvent(0x01b8,250,847,4368); -- -- Quest Finish end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) teacherstatus = player:getQuestStatus(WINDURST,TEACHER_S_PET); if(player:getCurrentMission(WINDURST) == A_TESTING_TIME) then MissionStatus = player:getVar("MissionStatus"); alreadyCompleted = player:hasCompletedMission(WINDURST,A_TESTING_TIME); if(MissionStatus == 0) then if(alreadyCompleted == false) then player:startEvent(0x00B6); -- First start at tahrongi else player:startEvent(0x02AF); -- Repeat at buburimu end elseif(MissionStatus == 1) then start_time = player:getVar("testingTime_start_time"); seconds_passed = os.time() - start_time; -- one Vana'diel Day is 3456 seconds (2 day for repeat) if((alreadyCompleted == false and seconds_passed > 3456) or (alreadyCompleted and seconds_passed > 6912)) then player:startEvent(0x00CA); -- are we in the last game hour of the Vana'diel Day? elseif(alreadyCompleted == false and seconds_passed >= 3312) then killcount = player:getVar("testingTime_crea_count"); if(killcount >= 35) then event = 0x00C9; elseif(killcount >= 30) then event = 0x00C8; elseif(killcount >= 19) then event = 0x00C7; else event = 0x00C6; end; player:startEvent(event,0,VanadielHour(),1,killcount); -- are we in the last game hour of the Vana'diel Day? REPEAT elseif(alreadyCompleted and seconds_passed >= 6768) then killcount = player:getVar("testingTime_crea_count"); if(killcount >= 35) then event = 0x00CE; elseif(killcount >= 30) then event = 0x00D1; else event = 0x00D0; end; player:startEvent(event,0,VanadielHour(),1,killcount); else start_day = player:getVar("testingTime_start_day"); start_hour = player:getVar("testingTime_start_hour"); if(VanadielDayOfTheYear() == start_day) then hours_passed = VanadielHour() - start_hour; elseif(VanadielDayOfTheYear() == start_day + 1) then hours_passed = VanadielHour() - start_hour + 24; else if(alreadyCompleted) then hours_passed = (24 - start_hour) + VanadielHour() + 24; else hours_passed = (24 - start_hour) + VanadielHour(); end end; if(alreadyCompleted) then player:startEvent(0x00CC,0,0,0,0,0,VanadielHour(),48 - hours_passed,0); else player:startEvent(0x00B7,0,VanadielHour(),24 - hours_passed); end; end; end elseif(teacherstatus == QUEST_AVAILABLE) then prog = player:getVar("QuestTeachersPet_prog") if(prog == 0) then player:startEvent(0x01b5); -- Before Quest player:setVar("QuestTeachersPet_prog",1); elseif(prog == 1) then player:startEvent(0x01b6,0,847,4368); -- Quest Start end elseif(teacherstatus == QUEST_ACCEPTED) then player:startEvent(0x01b7,0,847,4368); -- Quest Reminder elseif(player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(0x01bc); -- During Making the GRADE else -- Will run through these iffame is not high enough for other quests rand = math.random(1,2); if(rand == 1) then player:startEvent(0x01b9); -- Standard Conversation 1 else player:startEvent(0x01d5); -- Standard Conversation 2 end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x01b6 and option == 0) then player:addQuest(WINDURST,TEACHER_S_PET); elseif(csid == 0x01b6 and option == 1) then player:setVar("QuestTeachersPet_prog",0); elseif(csid == 0x01b8) then player:addGil(GIL_RATE*250); player:setVar("QuestTeachersPet_prog",0); player:tradeComplete(trade); if(player:getQuestStatus(WINDURST,TEACHER_S_PET) == QUEST_ACCEPTED) then player:completeQuest(WINDURST,TEACHER_S_PET); player:addFame(WINDURST,WIN_FAME*75); else player:addFame(WINDURST,WIN_FAME*8); end elseif(csid == 0x00B6 or csid == 0x02AF) and option ~= 1 then -- start player:addKeyItem(CREATURE_COUNTER_MAGIC_DOLL); player:messageSpecial(KEYITEM_OBTAINED,CREATURE_COUNTER_MAGIC_DOLL); player:setVar("MissionStatus",1); player:setVar("testingTime_start_day",VanadielDayOfTheYear()); player:setVar("testingTime_start_hour",VanadielHour()); player:setVar("testingTime_start_time",os.time()); elseif(csid == 0x00C6 or csid == 0x00C7 or csid == 0x00CA or csid == 0x00D0) then -- failed testing time player:delKeyItem(CREATURE_COUNTER_MAGIC_DOLL); player:messageSpecial(KEYITEM_OBTAINED + 1,CREATURE_COUNTER_MAGIC_DOLL); player:setVar("MissionStatus",0); player:setVar("testingTime_crea_count",0); player:setVar("testingTime_start_day",0); player:setVar("testingTime_start_hour",0); player:setVar("testingTime_start_time",0); player:delMission(WINDURST,A_TESTING_TIME); elseif (csid == 0x00C8 or csid == 0x00C9) then -- first time win finishMissionTimeline(player,1,csid,option); player:setVar("testingTime_crea_count",0); player:setVar("testingTime_start_day",0); player:setVar("testingTime_start_hour",0); player:setVar("testingTime_start_time",0); elseif (csid == 0x00D1 or csid == 0x00CE) then -- succesfull repeat attempt (Buburimu). finishMissionTimeline(player,1,csid,option); player:setVar("testingTime_crea_count",0); player:setVar("testingTime_start_day",0); player:setVar("testingTime_start_hour",0); player:setVar("testingTime_start_time",0); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/items/bowl_of_pebble_soup.lua
36
1103
----------------------------------------- -- ID: 4455 -- Item: Bowl of Pebble Soup -- Food Effect: 3 Hr, All Races ----------------------------------------- -- MP Recovered while healing 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4455); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Upper_Jeuno/npcs/Rouliette.lua
2
2142
----------------------------------- -- Area: Upper Jeuno -- NPC: Rouliette -- Starts and Finishes Quest: Candle-making -- @zone 244 -- @pos -24 -2 11 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,CANDLE_MAKING) == QUEST_ACCEPTED and trade:hasItemQty(531,1) == true and trade:getItemCount() == 1) then player:startEvent(0x0025); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --Prerequisites for this quest : A_CANDLELIGHT_VIGIL ACCEPTED if(player:getQuestStatus(JEUNO,CANDLE_MAKING) ~= QUEST_COMPLETED and player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL) == QUEST_ACCEPTED) then player:startEvent(0x0024); -- Start Quest Candle-making else player:startEvent(0x001e); --Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0024 and player:getQuestStatus(JEUNO,CANDLE_MAKING) == QUEST_AVAILABLE) then player:addQuest(JEUNO,CANDLE_MAKING); elseif(csid == 0x0025) then player:addTitle(BELIEVER_OF_ALTANA); player:addKeyItem(HOLY_CANDLE); player:messageSpecial(KEYITEM_OBTAINED,HOLY_CANDLE); player:addFame(JEUNO,30); player:tradeComplete(trade); player:completeQuest(JEUNO,CANDLE_MAKING); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/The_Sanctuary_of_ZiTah/npcs/Limion_RK.lua
8
2996
----------------------------------- -- Area: The Sanctuary of Zi'Tah -- NPC: Limion, R.K. -- Border Conquest Guards -- @pos -252.454 -1.958 624.366 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/conquest"); require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = LITELOR; local csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Giddeus/Zone.lua
4
1265
----------------------------------- -- -- Zone: Giddeus (145) -- ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-135.904,-5.788,-300.668,2); 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
kidaa/FFXIOrgins
scripts/zones/Southern_San_dOria/npcs/Ailevia.lua
5
1831
----------------------------------- -- Area: Southern San d'Oria -- NPC: Ailevia -- Adventurer's Assistant -- Only recieving Adv.Coupon and simple talk event are scripted -- This NPC participates in Quests and Missions -- @zone 230 -- @pos -8 1 1 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --Adventurer coupon if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then player:startEvent(0x028f); end -- "Flyers for Regine" conditional script count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0267); -- i know a thing or 2 about these streets 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 == 0x028f) then player:addGil(GIL_RATE*50); player:tradeComplete(); player:messageSpecial(GIL_OBTAINED,GIL_RATE*50); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Gusgen_Mines/Zone.lua
2
1281
----------------------------------- -- -- Zone: Gusgen_Mines (196) -- ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(100.007,-61.63,-237.441,187); 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
kidaa/FFXIOrgins
scripts/globals/items/jar_of_remedy_ointment.lua
4
1628
----------------------------------------- -- ID: 5356 -- Item: Remedy Ointment -- Item Effect: This potion remedies status ailments. -- Works on paralysis, silence, blindness, poison, and plague. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if(target:hasStatusEffect(EFFECT_SILENCE) or target:hasStatusEffect(EFFECT_BLINDNESS) or target:hasStatusEffect(EFFECT_POISON) or target:hasStatusEffect(EFFECT_PARALYSIS) or target:hasStatusEffect(EFFECT_PLAGUE)) then local effectRemoved = 0; while effectRemoved == 0 do num = math.random(1,5); if(num == 1 and target:hasStatusEffect(EFFECT_SILENCE)) then effectRemoved = effectRemoved + 1; target:delStatusEffect(EFFECT_SILENCE); elseif(num == 2 and target:hasStatusEffect(EFFECT_BLINDNESS)) then effectRemoved = effectRemoved + 1; target:delStatusEffect(EFFECT_BLINDNESS); elseif(num == 3 and target:hasStatusEffect(EFFECT_POISON)) then effectRemoved = effectRemoved + 1; target:delStatusEffect(EFFECT_POISON); elseif(num == 4 and target:hasStatusEffect(EFFECT_PARALYSIS)) then effectRemoved = effectRemoved + 1; target:delStatusEffect(EFFECT_PARALYSIS); elseif(num == 5 and target:hasStatusEffect(EFFECT_PLAGUE)) then effectRemoved = effectRemoved + 1; target:delStatusEffect(EFFECT_PLAGUE); end end end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/items/serving_of_bass_meuniere.lua
1
1499
----------------------------------------- -- ID: 4582 -- Item: serving_of_bass_meuniere -- Food Effect: 180Min, All Races ----------------------------------------- -- Health % 3 -- Dexterity 3 -- Agility 3 -- Mind -3 -- Ranged ACC % 6 -- Ranged ACC Cap 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4582); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPP, 3); target:addMod(MOD_DEX, 3); target:addMod(MOD_AGI, 3); target:addMod(MOD_MND, -3); target:addMod(MOD_FOOD_RACCP, 6); target:addMod(MOD_FOOD_RACC_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPP, 3); target:delMod(MOD_DEX, 3); target:delMod(MOD_AGI, 3); target:delMod(MOD_MND, -3); target:delMod(MOD_FOOD_RACCP, 6); target:delMod(MOD_FOOD_RACC_CAP, 15); end;
gpl-3.0
RockySeven3161/Unknown.
plugins/domaintools.lua
359
1494
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function check(name) local api = "https://domainsearch.p.mashape.com/index.php?" local param = "name="..name local url = api..param local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "application/json" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) local body = json:decode(body) --vardump(body) local domains = "List of domains for '"..name.."':\n" for k,v in pairs(body) do print(k) local status = " ❌ " if v == "Available" then status = " ✔ " end domains = domains..k..status.."\n" end return domains end local function run(msg, matches) if matches[1] == "check" then local name = matches[2] return check(name) end end return { description = "Domain tools", usage = {"!domain check [domain] : Check domain name availability.", }, patterns = { "^!domain (check) (.*)$", }, run = run }
gpl-2.0
kidaa/FFXIOrgins
scripts/globals/items/piscators_skewer.lua
36
1339
----------------------------------------- -- ID: 5983 -- Item: Piscator's Skewer -- Food Effect: 60 Mins, All Races ----------------------------------------- -- Dexterity 3 -- Vitality 4 -- Defense % 26 Cap 155 ----------------------------------------- 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,5983); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_VIT, 4); target:addMod(MOD_FOOD_DEFP, 26); target:addMod(MOD_FOOD_DEF_CAP, 155); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_VIT, 4); target:delMod(MOD_FOOD_DEFP, 26); target:delMod(MOD_FOOD_DEF_CAP, 155); end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/spells/bluemagic/spinal_cleave.lua
6
1065
require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; 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_ACC; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_SCISSION; params.scattr2 = SC_DETONATION; params.numhits = 1; params.multiplier = 3.0; params.tp150 = 3.0; params.tp300 = 3.0; params.azuretp = 3.0; params.duppercap = 75; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
Maxsteam/3mer
bot/utils.lua
28
14994
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(user_id) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end -- user has admins privileges function is_admin(user_id, chat_id) local var = false local data = load_data(_config.moderation.data) if data[tostring('admins')] then if data[tostring('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 -- user has moderator privileges function is_mod(user_id, chat_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(chat_id)] then if data[tostring(chat_id)]['moderators'] then if data[tostring(chat_id)]['moderators'][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 function is_banned(user_id, chat_id) return redis:get('banned:'..chat_id..':'..user_id) or false end function is_super_banned(user_id) return redis:get('superbanned:'..user_id) or false 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 plugins moderated = true if plugin.moderated and not is_mod(msg.from.id, msg.to.id) then -- Check if user is a mod if plugin.moderated and not is_admin(msg.from.id, msg.to.id) then -- Check if user is an admin if plugin.moderated and not is_sudo(msg.from.id) then -- Check if user is a sudoer return false end end end -- If plugins privileged = true if plugin.privileged and not is_sudo(msg.from.id) 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
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/Lower_Jeuno/npcs/Home_Point.lua
3
1187
----------------------------------- -- Area: Lower Jeuno -- NPC: Home Point ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (HOMEPOINT_HEAL == 1) then player:addHP(player:getMaxHP()); player:addMP(player:getMaxMP()); end player:startEvent(0x2711); 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 (option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/lamiabane.lua
2
1144
----------------------------------------- -- ID: 18693 -- Equip: Lamiabane -- Latent effect: Enhances Magic Atk Bonus +2 -- Enchantment: Adds "Refresh" -- Durration: 60 Mins -- Active while in Mamook, Arrapago Reef, or Halvung ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) zone = target:getZone(); ranged = target:getEquipID(SLOT_RANGED); if (ranged == 18693) then if (zone == 65 or zone == 54 or zone == 62) then target:addMod(MOD_MATT, 2); elseif (zone ~= 65 or zone ~= 54 or zone ~= 62) then target:delMod(MOD_MATT, 2); end elseif (ranged ~= 18693 and zone == 65 or zone == 54 or zone == 62) then target:delMod(MOD_MATT, 2); end end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) duration = 3600; target:delStatusEffect(EFFECT_REFRESH); target:addStatusEffect(EFFECT_REFRESH,3,1,duration); end;
gpl-3.0
WACcCKER/Anti_Wacccker
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
Puccio7/bot-telegram
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
apache-2.0
mosy210/G-H-O-S-T-BOT
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
alikineh/ali_kineh
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
mys007/nn
SpatialDivisiveNormalization.lua
39
5171
local SpatialDivisiveNormalization, parent = torch.class('nn.SpatialDivisiveNormalization','nn.Module') function SpatialDivisiveNormalization:__init(nInputPlane, kernel, threshold, thresval) parent.__init(self) -- get args self.nInputPlane = nInputPlane or 1 self.kernel = kernel or torch.Tensor(9,9):fill(1) self.threshold = threshold or 1e-4 self.thresval = thresval or threshold or 1e-4 local kdim = self.kernel:nDimension() -- check args if kdim ~= 2 and kdim ~= 1 then error('<SpatialDivisiveNormalization> averaging kernel must be 2D or 1D') end if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then error('<SpatialDivisiveNormalization> averaging kernel must have ODD dimensions') end -- padding values local padH = math.floor(self.kernel:size(1)/2) local padW = padH if kdim == 2 then padW = math.floor(self.kernel:size(2)/2) end -- create convolutional mean estimator self.meanestimator = nn.Sequential() self.meanestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH)) if kdim == 2 then self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1))) else self.meanestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1)) self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1))) end self.meanestimator:add(nn.Replicate(self.nInputPlane,1,3)) -- create convolutional std estimator self.stdestimator = nn.Sequential() self.stdestimator:add(nn.Square()) self.stdestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH)) if kdim == 2 then self.stdestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1))) else self.stdestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1)) self.stdestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1))) end self.stdestimator:add(nn.Replicate(self.nInputPlane,1,3)) self.stdestimator:add(nn.Sqrt()) -- set kernel and bias if kdim == 2 then self.kernel:div(self.kernel:sum() * self.nInputPlane) for i = 1,self.nInputPlane do self.meanestimator.modules[2].weight[1][i] = self.kernel self.stdestimator.modules[3].weight[1][i] = self.kernel end self.meanestimator.modules[2].bias:zero() self.stdestimator.modules[3].bias:zero() else self.kernel:div(self.kernel:sum() * math.sqrt(self.nInputPlane)) for i = 1,self.nInputPlane do self.meanestimator.modules[2].weight[i]:copy(self.kernel) self.meanestimator.modules[3].weight[1][i]:copy(self.kernel) self.stdestimator.modules[3].weight[i]:copy(self.kernel) self.stdestimator.modules[4].weight[1][i]:copy(self.kernel) end self.meanestimator.modules[2].bias:zero() self.meanestimator.modules[3].bias:zero() self.stdestimator.modules[3].bias:zero() self.stdestimator.modules[4].bias:zero() end -- other operation self.normalizer = nn.CDivTable() self.divider = nn.CDivTable() self.thresholder = nn.Threshold(self.threshold, self.thresval) -- coefficient array, to adjust side effects self.coef = torch.Tensor(1,1,1) end function SpatialDivisiveNormalization:updateOutput(input) self.localstds = self.stdestimator:updateOutput(input) -- compute side coefficients local dim = input:dim() if self.localstds:dim() ~= self.coef:dim() or (input:size(dim) ~= self.coef:size(dim)) or (input:size(dim-1) ~= self.coef:size(dim-1)) then self.ones = self.ones or input.new() if dim == 4 then -- batch mode self.ones:resizeAs(input[1]):fill(1) local coef = self.meanestimator:updateOutput(self.ones) self._coef = self._coef or input.new() self._coef:resizeAs(coef):copy(coef) -- make contiguous for view self.coef = self._coef:view(1,table.unpack(self._coef:size():totable())):expandAs(self.localstds) else self.ones:resizeAs(input):fill(1) self.coef = self.meanestimator:updateOutput(self.ones) end end -- normalize std dev self.adjustedstds = self.divider:updateOutput{self.localstds, self.coef} self.thresholdedstds = self.thresholder:updateOutput(self.adjustedstds) self.output = self.normalizer:updateOutput{input, self.thresholdedstds} -- done return self.output end function SpatialDivisiveNormalization:updateGradInput(input, gradOutput) -- resize grad self.gradInput:resizeAs(input):zero() -- backprop through all modules local gradnorm = self.normalizer:updateGradInput({input, self.thresholdedstds}, gradOutput) local gradadj = self.thresholder:updateGradInput(self.adjustedstds, gradnorm[2]) local graddiv = self.divider:updateGradInput({self.localstds, self.coef}, gradadj) self.gradInput:add(self.stdestimator:updateGradInput(input, graddiv[1])) self.gradInput:add(gradnorm[1]) -- done return self.gradInput end
bsd-3-clause
BTAxis/naev
dat/factions/equip/thurion.lua
1
4654
include("dat/factions/equip/generic.lua") equip_typeOutfits_weapons["Perspicacity"] = { { "Energy Dart", "Ripper Cannon" } } equip_typeOutfits_weapons["Ingenuity"] = { { varied = true; "Energy Dart", "Ripper Cannon", "Ion Cannon", "Laser Cannon MK3" } } equip_typeOutfits_weapons["Scintillation"] = { { varied = true; "Convulsion Launcher", "Energy Missile", "Unicorp Medusa Launcher" } } equip_typeOutfits_weapons["Virtuosity"] = { { num = 1; "Convulsion Launcher", "Energy Missile" }, { num = 1; "Energy Dart", "Ripper Cannon" }, { varied = true; "Energy Dart", "Ripper Cannon", "Ion Cannon", "Laser Cannon MK3" } } equip_typeOutfits_weapons["Taciturnity"] = { { num = 2, varied = true; "Turreted Convulsion Launcher", "EMP Grenade", "Laser Turret MK1" }, { varied = true; "Turreted Gauss Gun", "Laser PD MK1" } } equip_typeOutfits_weapons["Apprehension"] = { { varied = true; "Laser Turret MK3", "Railgun", "Energy Torpedo", "Turreted Convulsion Launcher" } } equip_typeOutfits_weapons["Certitude"] = { { varied = true; "Railgun", "Energy Torpedo", "Turreted Convulsion Launcher" } } equip_typeOutfits_utilities["Perspicacity"] = { { varied = true; "Unicorp Scrambler", "Sensor Array", "Jump Scanner", "Thurion Reactor Class I", "Small Shield Booster", "Generic Afterburner" } } equip_typeOutfits_utilities["Ingenuity"] = { { num = 1; "Droid Repair Crew", "Boarding Androids MKI", "Thurion Reactor Class II", "Medium Shield Booster" }, { varied = true; "Sensor Array", "Unicorp Scrambler", "Thurion Reactor Class I", "Small Shield Booster", "Hellburner" } } equip_typeOutfits_utilities["Scintillation"] = { { varied = true; "Sensor Array", "Unicorp Scrambler", "Thurion Reactor Class I", "Small Shield Booster", "Hellburner" } } equip_typeOutfits_utilities["Virtuosity"] = { { varied = true; "Droid Repair Crew", "Boarding Androids MKI", "Thurion Reactor Class II", "Medium Shield Booster" }, { varied = true; "Sensor Array", "Milspec Scrambler", "Thurion Reactor Class I", "Small Shield Booster", "Hellburner" } } equip_typeOutfits_utilities["Taciturnity"] = { { varied = true; "Droid Repair Crew", "Boarding Androids MKI", "Thurion Reactor Class II", "Medium Shield Booster" }, { varied = true; "Sensor Array", "Milspec Scrambler", "Thurion Reactor Class I", "Small Shield Booster", "Hellburner" } } equip_typeOutfits_utilities["Apprehension"] = { { varied = true; "Boarding Androids MKII", "Thurion Reactor Class II", "Medium Shield Booster", "Droid Repair Crew", "Sensor Array", "Milspec Scrambler" } } equip_typeOutfits_utilities["Certitude"] = { { varied = true; "Boarding Androids MKII", "Thurion Reactor Class III", "Large Shield Booster", "Droid Repair Crew", "Sensor Array", "Milspec Scrambler" } } equip_typeOutfits_structurals["Perspicacity"] = { { varied = true; "Adaptive Stealth Plating", "Fuel Pod", "Thurion Engine Reroute", "Steering Thrusters", "Shield Capacitor" } } equip_typeOutfits_structurals["Ingenuity"] = { { varied = true; "Adaptive Stealth Plating", "Fuel Pod", "Thurion Engine Reroute", "Steering Thrusters", "Shield Capacitor" } } equip_typeOutfits_structurals["Scintillation"] = { { varied = true; "Adaptive Stealth Plating", "Fuel Pod", "Thurion Engine Reroute", "Steering Thrusters", "Shield Capacitor" } } equip_typeOutfits_structurals["Virtuosity"] = { { varied = true; "Active Plating", "Medium Fuel Pod", "Battery II", "Shield Capacitor II", "Adaptive Stealth Plating" } } equip_typeOutfits_structurals["Taciturnity"] = { { varied = true; "Active Plating", "Medium Fuel Pod", "Battery II", "Shield Capacitor II", "Adaptive Stealth Plating", "Cargo Pod" } } equip_typeOutfits_structurals["Apprehension"] = { { varied = true; "Active Plating", "Nanobond Plating", "Medium Fuel Pod", "Battery II", "Shield Capacitor III" } } equip_typeOutfits_structurals["Certitude"] = { { varied = true; "Biometal Armour", "Nanobond Plating", "Large Fuel Pod", "Battery III", "Shield Capacitor IV" } } --[[ -- @brief Does thurion pilot equipping -- -- @param p Pilot to equip --]] function equip( p ) equip_generic( p ) end
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/West_Sarutabaruta/npcs/Darumomo_WW.lua
8
2956
----------------------------------- -- Area: West Sarutabaruta -- NPC: Darumomo, W.W. -- Type: Border Conquest Guards -- @pos 399.450 -25.858 727.545 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Sarutabaruta/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = SARUTABARUTA; local csid = 0x7ff6; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Port_Windurst/npcs/Yujuju.lua
2
2533
----------------------------------- -- Area: Port Windurst -- NPC: Yujuju -- Involved In Quest: Making Headlines -- @pos 201.523 -4.785 138.978 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,19) == false) then player:startEvent(0x026d); elseif (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==9)then player:startEvent(0x0250);--COP event elseif (MakingHeadlines == 1) then local prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),2) == false) then player:startEvent(0x013a); -- Get Scoop else player:startEvent(0x013b); -- After receiving scoop end else player:startEvent(0x0154); -- Standard Conversation 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 == 0x013a) then prog = player:getVar("QuestMakingHeadlines_var"); player:addKeyItem(PORT_WINDURST_SCOOP); player:messageSpecial(KEYITEM_OBTAINED,PORT_WINDURST_SCOOP); player:setVar("QuestMakingHeadlines_var",prog+2); elseif (csid == 0x0250) then player:setVar("MEMORIES_OF_A_MAIDEN_Status",10); elseif (csid == 0x026d) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",19,true); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Windurst_Woods/npcs/Anillah.lua
12
1765
----------------------------------- -- Area: Windurst Woods -- NPC: Anillah -- Type: Clothcraft Image Support -- @pos -34.800 -2.25 -119.950 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/status"); require("scripts/globals/crafting"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,3); local SkillCap = getCraftSkillCap(player,8); local SkillLevel = player:getSkillLevel(8); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == false) then player:startEvent(0x271F,SkillCap,SkillLevel,2,511,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(0x271F,SkillCap,SkillLevel,2,511,player:getGil(),7108,0,0); end else player:startEvent(0x271F); -- Standard Dialogue 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 == 0x271F and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,4,2); player:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,1,0,120); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Windurst_Waters/npcs/Ajen-Myoojen.lua
38
1044
----------------------------------- -- Area: Windurst Waters -- NPC: Ajen-Myoojen -- Type: Standard NPC -- @zone: 238 -- @pos -44.542 -5.999 238.996 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x010e); 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
Fatalerror66/ffxi-a
scripts/zones/Hall_of_Transference/npcs/_0e1.lua
2
1721
----------------------------------- -- 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 and (player:getVar("PH") <= 1 and player:getVar("PD") <= 1 and player:getVar("PM") <= 1) and player:getVar("PromathiaStatus") == 2)then player:startEvent(0x00A0); elseif(player:getCurrentMission(COP) >= BELOW_THE_ARKS and player:getVar("PD") <= 3 and and player:getVar("PH") ~= 2 and player:getVar("PM") ~= 2)then player:startEvent(0x0096); else player:messageSpecial(DOOR_IS_CLOSED); 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 == 0x00A0) then player:setVar("PD",2); player:setPos(152,0 ,-70 ,81 ,18); -- tp to promy dem end if(csid == 0x0096 and option == 1) then player:setPos(152,0 ,-70 ,81 ,18); -- tp to promy dem end end;
gpl-3.0
3RaGaming/3Ra-Enhanced-Vanilla
config.lua
1
1035
-- A 3Ra Gaming compilation Event.register(-1, function() global.scenario = {} global.scenario.config = {} global.scenario.config.announcements_enabled = true -- if true announcements will be shown global.scenario.config.announcement_delay = 595 -- number of seconds between each announcement global.scenario.config.score_delay = 8 -- delay in seconds before hiding rocket score window (0 = never show) global.scenario.config.autolaunch_default = false -- default autolaunch option global.scenario.config.logistic_research_enabled = false -- if true then research for requesters and active providers will be enabled. global.scenario.config.mapsettings = global.scenario.config.mapsettings or {} global.scenario.config.mapsettings.cross_width = 200 -- total width of cross global.scenario.config.mapsettings.spiral_land_width = 70 -- width of land in spiral global.scenario.config.mapsettings.spiral_water_width = 70 -- width of water in spiral global.scenario.custom_functions = {} end)
gpl-3.0
MOSAVI17/Security1
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
WACcCKER/Anti_Wacccker
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
emadni/emadoso
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
nenau/naev
dat/missions/empire/collective/ec04.lua
2
9013
--[[ Collective Extraction Author: bobbens minor edits by Infiltrator Fifth mission in the collective mini campaign. You must go rescue a team of commandos after being attacked by collective forces on a surveillance mission. ]]-- include "dat/scripts/nextjump.lua" include "proximity.lua" misn_title = _("Collective Extraction") misn_reward = _("None") misn_desc = {} misn_desc[1] = _("Check for survivors on %s in %s.") misn_desc[2] = _("Travel back to %s in %s.") title = {} title[1] = _("Collective Extraction") title[2] = _("Planet %s") title[3] = _("Mission Accomplished") text = {} text[1] = _([[As soon as you exit the landing pad you see Lt. Commander Dimitri waiting for you. He seems a bit more nervous then usual. "The commando team has sent us an SOS. They were discovered by the Collective, and now they're under heavy fire. We need you to go and get them out of there. Would you be willing to embark on another dangerous mission?"]]) text[2] = _([["We'll send extra forces to %s to try to give you a chance to break through the blockade. You'll have to land on %s and extract our team. Be very careful. This is going to be no walk in the park."]]) text[3] = _([[The atmosphere once again starts giving your shields a workout as you land. You spend a while flying low until your sensors pick up a reading of possible life forms. The silhouette of the transport ship is barely visible. As you fly closer, it becomes apparent that you arrived too late. Everyone is already dead. You see if you can salvage the readings from their equipment, but it seems like it's completely toasted.]]) text[4] = _([[You notice you won't have enough fuel to get back so you salvage some from the wrecked transport ship. Stealing from the dead isn't pleasant business, but if it gets you out alive, you figure it's good enough.]]) text[5] = _([[You spend a while searching until you find a datapad on one of the corpses. Ignoring the stench of burnt flesh you grab it, just as you hear the sirens go off in your ship. Enemy reinforcements! Time to hit the afterburner. You've got one, right?]]) text[6] = _([[Lt. Commander Dimitri's face cannot hide his sadness as he sees you approach with no commando members. "No survivors, eh? I had that gut feeling. At least you were able to salvage something? Good, at least it'll mean they didn't die in vain. Meet me in the bar in a while. We're going to try to process this datapad. It'll hopefully have the final results."]]) escort_msg1 = _("Okay, %s, we'll flank the Collective force around the planet and try to draw their fire. You punch right through and land on that planet!") escort_msg2 = _("There's too many of them! Fall back! Everyone to the jump point!") land_msg = _("You can't land now! Get to the jump point!") markername = _("Empire flanking maneuver") osd_msg = {} osd_msg[1] = _("Fly to %s") osd_msg[2] = _("Land on %s") osd_msg[3] = _("Return to %s") osd_msg["__save"] = true function create () misn_target, misn_target_sys = planet.get("Eiroik") local missys = {misn_target} if not misn.claim(missys) then abort() end -- Intro text if tk.yesno( title[1], string.format(text[1], misn_target:name()) ) then misn.accept() misn_stage = 0 misn_base, misn_base_sys = planet.get("Omega Station") misn_marker = misn.markerAdd( misn_target_sys, "low" ) -- Mission details misn.setTitle(misn_title) misn.setReward( misn_reward ) misn.setDesc( string.format(misn_desc[1], misn_target:name(), misn_target_sys:name() )) tk.msg( title[1], string.format(text[2], misn_target_sys:name(), misn_target:name()) ) osd_msg[1] = osd_msg[1]:format(misn_target_sys:name()) osd_msg[2] = osd_msg[2]:format(misn_target:name()) osd_msg[3] = osd_msg[3]:format(misn_base:name()) misn.osdCreate(misn_title, osd_msg) hook.enter("enter") hook.land("land") end end -- Handles the Collective encounters. function enter() player.allowSave() -- This mission disables saving, which is dangerous. Should be turned back on ASAP. if system.cur() == misn_target_sys and misn_stage == 0 then -- Case jumped in before landing pilot.clear() pilot.toggleSpawn(false) local fleetpos1 = vec2.new(20500, 2300) local fleetpos2 = vec2.new(20500, 1700) local waypoint1 = vec2.new(7500, 9500) local waypoint2 = vec2.new(7500, -5500) local waypoint12 = vec2.new(1500, 3000) local waypoint22 = vec2.new(1500, -500) fleet1 = pilot.add("Empire Flanking Fleet", "empire_norun", fleetpos1) fleet2 = pilot.add("Empire Flanking Fleet", "empire_norun", fleetpos2) empireAttack(fleet1) empireAttack(fleet2) fleet1[1]:comm(escort_msg1:format(player.name())) fleet1[1]:taskClear() fleet1[1]:goto(waypoint1, false, false) fleet1[1]:goto(waypoint12, false, false) fleet2[1]:taskClear() fleet2[1]:goto(waypoint2, false, false) fleet2[1]:goto(waypoint22, false, false) hook.pilot(fleet1[1], "idle", "idle") hook.pilot(fleet2[1], "idle", "idle") system.mrkAdd(markername, waypoint1) system.mrkAdd(markername, waypoint2) swarm1 = pilot.add("Collective Lge Swarm", nil, misn_target:pos()) swarm2 = pilot.add("Collective Lge Swarm", nil, misn_target:pos()) for _, j in ipairs(swarm2) do swarm1[#swarm1 + 1] = j -- Combine the swarms into one swarm, for convenience. end for _, j in ipairs(swarm1) do if j:exists() then j:control() j:setVisplayer() end end hook.timer(500, "proximity", {location = misn_target:pos(), radius = 3000, funcname = "idle"}) misn_stage = 1 misn.osdActive(2) elseif system.cur() == misn_target_sys and misn_stage == 2 then -- Case taken off from the planet pilot.clear() pilot.toggleSpawn(false) local pv = player.pilot():pos() fleet1 = pilot.add("Empire Flanking Fleet", nil, pv + vec2.new(-150, 500)) fleet2 = pilot.add("Empire Flanking Fleet", nil, pv + vec2.new(-150, -500)) empireRetreat(fleet1) empireRetreat(fleet2) fleet1[1]:comm(escort_msg2) -- TODO: Use heavier Collective ships here swarm1 = pilot.add("Collective Lge Swarm", nil, pv + vec2.new(-3000, 500)) swarm2 = pilot.add("Collective Lge Swarm", nil, pv + vec2.new(-3000, 0)) swarm3 = pilot.add("Collective Lge Swarm", nil, pv + vec2.new(-3000, -500)) for i, _ in ipairs(swarm1) do -- Let's be lazy. swarm1[i]:setVisplayer() swarm2[i]:setVisplayer() swarm3[i]:setVisplayer() end player.allowLand(false, land_msg) misn.osdActive(3) elseif misn_stage == 1 then -- Case jumped back out without landing misn_stage = 0 misn.osdActive(1) elseif misn_stage == 2 then -- Case jumped out after landing misn_stage = 3 end end -- Preps the Empire ships for attack. function empireAttack(fleet) for _, j in ipairs(fleet) do if j:exists() then j:control() j:setVisplayer() j:follow(fleet[1]) end end end -- Makes the Empire ships run away. function empireRetreat(fleet) for _, j in ipairs(fleet) do if j:exists() then j:control() j:setVisplayer() j:hyperspace(getNextSystem(system.cur(), misn_base_sys)) end end end -- Triggered when either Empire fleet is in attack range. function idle() for _, j in ipairs(swarm1) do if j:exists() then j:control(false) end end for _, j in ipairs(fleet1) do if j:exists() then j:control(false) end end for _, j in ipairs(fleet2) do if j:exists() then j:control(false) end end end -- Handles arrival back to base function land () -- Just landing if misn_stage == 1 and planet.cur() == misn_target then player.allowSave(false) -- This prevents the player from starting on Eiroik if he dies after taking off. player.takeoff() -- Some flavour text title[2] = title[2]:format(misn_target:name()) tk.msg( title[2], text[3] ) -- Add fuel if needed if player.jumps() < 2 then local fuel, consumption = player.fuel() player.refuel(2 * consumption) tk.msg( title[2], text[4] ) end tk.msg( title[2], text[5] ) -- Add goods misn_cargo = misn.cargoAdd( "Datapad", 0 ) misn_stage = 2 elseif misn_stage == 3 and planet.cur() == misn_base then tk.msg( title[3], text[6] ) misn.cargoRm( misn_cargo ) var.pop("emp_commando") -- Rewards faction.modPlayerSingle("Empire",5) misn.finish(true) end end
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Port_Windurst/npcs/Nine_of_Clubs.lua
5
1039
----------------------------------- -- Area: Port Windurst -- NPC: Nine of Clubs -- Type: Standard NPC -- @zone: 240 -- @pos: -229.699 -9 185.686 -- -- 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(0x004a); 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
Wedge009/wesnoth
data/ai/micro_ais/cas/ca_simple_attack.lua
6
1940
local AH = wesnoth.require "ai/lua/ai_helper.lua" local BC = wesnoth.require "ai/lua/battle_calcs.lua" local LS = wesnoth.require "location_set" local ca_simple_attack, best_attack = {}, nil function ca_simple_attack:evaluation(cfg) local units = AH.get_units_with_attacks { side = wesnoth.current.side, { "and", wml.get_child(cfg, "filter") } } if (not units[1]) then return 0 end -- If cfg.filter_second is set, set up a map (location set) -- of enemies that it is okay to attack local enemy_filter = wml.get_child(cfg, "filter_second") local enemy_map if enemy_filter then local enemies = AH.get_attackable_enemies(enemy_filter) if (not enemies[1]) then return 0 end enemy_map = LS.create() for _,enemy in ipairs(enemies) do enemy_map:insert(enemy.x, enemy.y) end end -- Now find the best of the possible attacks local attacks = AH.get_attacks(units, { include_occupied = true }) if (not attacks[1]) then return 0 end local max_rating = - math.huge for _, att in ipairs(attacks) do local valid_target = true if enemy_filter and (not enemy_map:get(att.target.x, att.target.y)) then valid_target = false end if valid_target then local attacker = wesnoth.units.get(att.src.x, att.src.y) local enemy = wesnoth.units.get(att.target.x, att.target.y) local dst = { att.dst.x, att.dst.y } local rating = BC.attack_rating(attacker, enemy, dst) if (rating > max_rating) then max_rating, best_attack = rating, att end end end if best_attack then return cfg.ca_score end return 0 end function ca_simple_attack:execution(cfg) AH.robust_move_and_attack(ai, best_attack.src, best_attack.dst, best_attack.target, cfg) best_attack = nil end return ca_simple_attack
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/Windurst_Waters/npcs/Chyuk-Kochak.lua
4
1049
----------------------------------- -- Area: Windurst Waters -- NPC: Chyuk-Kochak -- Type: Standard NPC -- @zone: 238 -- @pos: -252.162 -6.319 -307.011 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0298); 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
Fatalerror66/ffxi-a
scripts/zones/Windurst_Woods/npcs/Erpolant.lua
5
1039
----------------------------------- -- Area: Windurst Woods -- NPC: Erpolant -- Type: Standard NPC -- @zone: 241 -- @pos: -63.224 -0.749 -33.424 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01bc); 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
shahryar1989/ShahryarAntiSpam
plugins/stats.lua
866
4001
do -- 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 = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(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 = 'users in this chat \n' 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 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..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/Davoi/npcs/_45d.lua
4
1459
----------------------------------- -- Area: Davoi -- NPC: Wall of Banishing -- Used In Quest: Whence Blows the Wind -- @zone 149 -- @pos 181 0 -218 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(CRIMSON_ORB)) then player:startEvent(0x002a); else player:messageSpecial(CAVE_HAS_BEEN_SEALED_OFF); player:messageSpecial(MAY_BE_SOME_WAY_TO_BREAK); player:setVar("miniQuestForORB_CS",99); 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 == 0x002a and option == 0) then player:messageSpecial(POWER_OF_THE_ORB_ALLOW_PASS); GetNPCByID(17387982):openDoor(); end end;
gpl-3.0
KevinGuarnati/controllore
plugins/eur.lua
3
1241
do -- TODO: More currencies -- See http://webrates.truefx.com/rates/connect.html local function getEURUSD(usd, eur) local url = 'http://webrates.truefx.com/rates/connect.html?c=EUR/USD&f=csv&s=n' local res,code = http.request(url) local rates = res:split(", ") local symbol = rates[1] local timestamp = rates[2] local sell = rates[3]..rates[4] local buy = rates[5]..rates[6] local text = symbol..'\n'..'Buy: '..buy..'\n'..'Sell: '..sell if usd then local eur = tonumber(usd) / tonumber(buy) text = text.."\n "..usd.."USD = "..eur.."EUR" end if eur then local usd = tonumber(eur) * tonumber(sell) text = text.."\n "..eur.."EUR = "..usd.."USD" end return text end local function run(msg, matches) if matches[1] == "!eurusd" then return getEURUSD(nil) end if matches[2] == "USD" then return getEURUSD(matches[1], nil) end if matches[2] == "EUR" then return getEURUSD(nil, matches[1]) end end return { description = "Real-time EURUSD market price", usage = { "!eurusd [value EUR/USD]", }, patterns = { "^!eurusd$", "^!eurusd (%d+[%d%.]*) (.*)$", }, run = run } end
mit
Yhgenomics/premake-core
src/base/detoken.lua
6
4091
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, environ) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, environ) -- run it and get the result local result = func() or "" -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then result = varMap[token] if type(result) == "function" then result = result(environ) end isAbs = path.isabsolute(result) end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if isAbs and field.paths then result = "\0" .. result end return result end function expandvalue(value) if type(value) ~= "string" then return value end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), environ) if not result then error(err, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value) if type(value) == "table" then local res_table = {} for k, v in pairs(value) do if tonumber(k) ~= nil then res_table[k] = recurse(v, e) else local nk = recurse(k, e); res_table[nk] = recurse(v, e) end end return res_table else return expandvalue(value) end end return recurse(value) end
bsd-3-clause
RockySeven3161/Unknown.
plugins/moderation.lua
336
9979
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as moderator for this group.') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminprom' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end local message = 'List for Bot admins:\n' for k,v in pairs(data['admins']) do message = message .. '- ' .. v ..' ['..k..'] \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only works on group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return "Only moderator can promote" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return "Only moderator can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminprom' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'Admin only!' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Moderation plugin", usage = { moderator = { "!promote <username> : Promote user as moderator", "!demote <username> : Demote user from moderator", "!modlist : List of moderators", }, admin = { "!modadd : Add group to moderation list", "!modrem : Remove group from moderation list", }, sudo = { "!adminprom <username> : Promote user as admin (must be done from a group)", "!admindem <username> : Demote user from admin (must be done from a group)", }, }, patterns = { "^!(modadd)$", "^!(modrem)$", "^!(promote) (.*)$", "^!(demote) (.*)$", "^!(modlist)$", "^!(adminprom) (.*)$", -- sudoers only "^!(admindem) (.*)$", -- sudoers only "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
kidaa/FFXIOrgins
scripts/zones/Abyssea-Altepa/Zone.lua
33
1470
----------------------------------- -- -- Zone: Abyssea - Altepa -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Altepa/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(435 ,0 ,320 ,136) end if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED and player:getVar("1stTimeAyssea") == 0) then player:setVar("1stTimeAyssea",1); 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
emadni/emadoso
plugins/moderation.lua
336
9979
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as moderator for this group.') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminprom' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end local message = 'List for Bot admins:\n' for k,v in pairs(data['admins']) do message = message .. '- ' .. v ..' ['..k..'] \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only works on group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return "Only moderator can promote" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return "Only moderator can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminprom' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'Admin only!' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Moderation plugin", usage = { moderator = { "!promote <username> : Promote user as moderator", "!demote <username> : Demote user from moderator", "!modlist : List of moderators", }, admin = { "!modadd : Add group to moderation list", "!modrem : Remove group from moderation list", }, sudo = { "!adminprom <username> : Promote user as admin (must be done from a group)", "!admindem <username> : Demote user from admin (must be done from a group)", }, }, patterns = { "^!(modadd)$", "^!(modrem)$", "^!(promote) (.*)$", "^!(demote) (.*)$", "^!(modlist)$", "^!(adminprom) (.*)$", -- sudoers only "^!(admindem) (.*)$", -- sudoers only "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
meshr-net/meshr_win32
usr/lib/lua/luci/model/cbi/coovachilli_network.lua
11
1695
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> 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: coovachilli_network.lua 3943 2008-12-23 21:57:34Z jow $ ]]-- require("luci.sys") require("luci.ip") m = Map("coovachilli") -- tun s1 = m:section(TypedSection, "tun") s1.anonymous = true s1:option( Flag, "usetap" ) s1:option( Value, "tundev" ).optional = true s1:option( Value, "txqlen" ).optional = true net = s1:option( Value, "net" ) for _, route in ipairs(luci.sys.net.routes()) do if route.device ~= "lo" and route.dest:prefix() < 32 then net:value( route.dest:string() ) end end s1:option( Value, "dynip" ).optional = true s1:option( Value, "statip" ).optional = true s1:option( Value, "dns1" ).optional = true s1:option( Value, "dns2" ).optional = true s1:option( Value, "domain" ).optional = true s1:option( Value, "ipup" ).optional = true s1:option( Value, "ipdown" ).optional = true s1:option( Value, "conup" ).optional = true s1:option( Value, "condown" ).optional = true -- dhcp config s2 = m:section(TypedSection, "dhcp") s2.anonymous = true dif = s2:option( Value, "dhcpif" ) for _, nif in ipairs(luci.sys.net.devices()) do if nif ~= "lo" then dif:value(nif) end end s2:option( Value, "dhcpmac" ).optional = true s2:option( Value, "lease" ).optional = true s2:option( Value, "dhcpstart" ).optional = true s2:option( Value, "dhcpend" ).optional = true s2:option( Flag, "eapolenable" ) return m
apache-2.0
Fatalerror66/ffxi-a
scripts/zones/Upper_Delkfutts_Tower/npcs/qm3.lua
2
1107
----------------------------------- -- Area: Upper Delkfutt's Tower -- NPC: ??? -- ??? at the bottom of the great spiral staircase. Takes you to the 10th floor. -- @pos 261 19 20 158 ----------------------------------- package.loaded["scripts/zones/Upper_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Upper_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0011); 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
actionless/awesome
tests/examples/wibox/container/arcchart/bg.lua
5
1062
--DOC_HIDE_ALL --DOC_GEN_IMAGE local parent = ... local wibox = require( "wibox" ) local beautiful = require( "beautiful" ) local l = wibox.layout.fixed.horizontal() l.spacing = 10 parent:add(l) for _, v in ipairs {"", "#00ff00", "#0000ff"} do l:add(wibox.widget { { text = v~="" and v or "nil", align = "center", valign = "center", widget = wibox.widget.textbox, }, colors = { beautiful.bg_normal, beautiful.bg_highlight, beautiful.border_color, }, values = { 1, 2, 3, }, max_value = 10, min_value = 0, rounded_edge = false, bg = v~="" and v or nil, border_width = 0.5, border_color = "#000000", widget = wibox.container.arcchart }) end return nil, 60 --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
actionless/awesome
lib/naughty/widget/title.lua
3
2581
---------------------------------------------------------------------------- --- A notification title. -- -- This widget is a specialized `wibox.widget.textbox` with the following extra -- features: -- -- * Honor the `beautiful` notification variables. -- * React to the `naughty.notification` object title changes. -- --@DOC_wibox_nwidget_title_simple_EXAMPLE@ -- -- @author Emmanuel Lepage Vallee &lt;elv1313@gmail.com&gt; -- @copyright 2017 Emmanuel Lepage Vallee -- @widgetmod naughty.widget.title -- @see wibox.widget.textbox ---------------------------------------------------------------------------- local textbox = require("wibox.widget.textbox") local gtable = require("gears.table") local beautiful = require("beautiful") local markup = require("naughty.widget._markup").set_markup local title = {} --- The attached notification. -- @property notification -- @tparam naughty.notification notification -- @propemits true false function title:set_notification(notif) if self._private.notification == notif then return end if self._private.notification then self._private.notification:disconnect_signal("property::message", self._private.title_changed_callback) self._private.notification:disconnect_signal("property::fg", self._private.title_changed_callback) end markup(self, notif.title, notif.fg, notif.font) self._private.notification = notif self._private.title_changed_callback() notif:connect_signal("property::title", self._private.title_changed_callback) notif:connect_signal("property::fg" , self._private.title_changed_callback) self:emit_signal("property::notification", notif) end --- Create a new naughty.widget.title. -- @tparam table args -- @tparam naughty.notification args.notification The notification. -- @constructorfct naughty.widget.title -- @usebeautiful beautiful.notification_fg -- @usebeautiful beautiful.notification_font local function new(args) args = args or {} local tb = textbox() tb:set_wrap("word") tb:set_font(beautiful.notification_font) gtable.crush(tb, title, true) function tb._private.title_changed_callback() markup( tb, tb._private.notification.title, tb._private.notification.fg, tb._private.notification.font ) end if args.notification then tb:set_notification(args.notification) end return tb end --@DOC_widget_COMMON@ --@DOC_object_COMMON@ return setmetatable(title, {__call = function(_, ...) return new(...) end})
gpl-2.0
Fatalerror66/ffxi-a
scripts/globals/mobskills/Fulmination.lua
8
1235
--------------------------------------------- -- Fulmination -- -- Description: Deals heavy magical damage in an area of effect. Additional effect: Paralysis + Stun -- Type: Magical -- Wipes Shadows -- Range: 30 yalms --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function OnMobSkillCheck(target,mob,skill) local family = mob:getFamily(); local mobhp = mob:getHPP(); if (family == 168 and mobhp <= 35) then -- Khimera < 35% return 0; elseif (family == 315 and mobhp <= 50) then -- Tyger < 50% return 0; end return 1; end; function OnMobWeaponSkill(target, mob, skill) -- TODO: Hits all players near Khimaira, not just alliance. local dmgmod = 3; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 4,ELE_LIGHTNING,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS); MobStatusEffectMove(mob,target,EFFECT_PARALYSIS, 40, 0, 60); MobStatusEffectMove(mob,target,EFFECT_STUN, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Temenos/mobs/Thrym.lua
2
1148
----------------------------------- -- Area: Temenos N T -- NPC: Thrym ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16928781):updateEnmity(target); GetMobByID(16928783):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(IsMobDead(16928781)==true and IsMobDead(16928782)==true and IsMobDead(16928783)==true )then GetNPCByID(16928768+19):setPos(200,-82,495); GetNPCByID(16928768+19):setStatus(STATUS_NORMAL); GetNPCByID(16928768+153):setPos(206,-82,495); GetNPCByID(16928768+153):setStatus(STATUS_NORMAL); GetNPCByID(16928768+210):setPos(196,-82,495); GetNPCByID(16928768+210):setStatus(STATUS_NORMAL); end end;
gpl-3.0
bygreencn/DIGITS
digits/tools/torch/main.lua
3
35289
-- Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. require 'torch' require 'xlua' require 'optim' require 'pl' require 'trepl' require 'lfs' require 'nn' local dir_path = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] if dir_path ~= nil then package.path = dir_path .."?.lua;".. package.path end require 'Optimizer' require 'LRPolicy' require 'logmessage' -- load utils local utils = require 'utils' ---------------------------------------------------------------------- opt = lapp[[ Usage details: -a,--threads (default 8) number of threads -b,--batchSize (default 0) batch size -c,--learningRateDecay (default 1e-6) learning rate decay (in # samples) -e,--epoch (default 1) number of epochs to train -1 for unbounded -f,--shuffle (default no) shuffle records before train -i,--interval (default 1) number of train epochs to complete, to perform one validation -k,--crop (default no) If this option is 'yes', all the images are randomly cropped into square image. And croplength is provided as --croplen parameter -l,--croplen (default 0) crop length. This is required parameter when crop option is provided -m,--momentum (default 0.9) momentum -n,--network (string) Model - must return valid network. Available - {lenet, googlenet, alexnet} -o,--optimization (default sgd) optimization method -p,--type (default cuda) float or cuda -r,--learningRate (default 0.001) learning rate -s,--save (default results) save directory -t,--train (default '') location in which train db exists. This parameter may be omitted only if visualizeModel is 'yes'. -v,--validation (default '') location in which validation db exists. -w,--weightDecay (default 1e-4) L2 penalty on the weights --augFlip (default none) options {none, fliplr, flipud, fliplrud} as random pre-processing augmentation --augQuadRot (default none) options {none, rot90, rot180, rotall} as random pre-processing augmentation --augRot (default 0.0) min and max rotation (degrees) of arbitrary uniform-rotation as pre-processing augmentation --augScale (default 0.0) stddev of Scale as pre-processing augmentation --augNoise (default 0.0) stddev of Noise in AWGN as pre-processing augmentation --augHSVh (default 0.0) stddev of HSV's Hue shift as pre-processing augmentation --augHSVs (default 0.0) stddev of HSV's Saturation shift as pre-processing augmentation --augHSVv (default 0.0) stddev of HSV's Value shift as pre-processing augmentation --train_labels (default '') location in which train labels db exists. Optional, use this if train db does not contain target labels. --validation_labels (default '') location in which validation labels db exists. Optional, use this if validation db does not contain target labels. --dbbackend (default 'lmdb') Specifies which DB backend was used to create datasets. Valid backends: hdf5, lmdb --seed (default '') fixed input seed for repeatable experiments --weights (default '') filename for weights of a model to use for fine-tuning --retrain (default '') Specifies path to model to retrain with --optimState (default '') Specifies path to an optimState to reload from --randomState (default '') Specifies path to a random number state to reload from --lrpolicyState (default '') Specifies path to a lrpolicy state to reload from --networkDirectory (default '') directory in which network exists --mean (default '') mean image file. --subtractMean (default 'image') Select mean subtraction method. Possible values are 'image', 'pixel' or 'none'. --labels (default '') file contains label definitions --snapshotPrefix (default '') prefix of the weights/snapshots --snapshotInterval (default 1) specifies the training epochs to be completed before taking a snapshot --visualizeModel (default 'no') Visualize model. If this options is set to 'yes' no model will be trained. -q,--policy (default torch_sgd) Learning Rate Policy. Valid policies : fixed, step, exp, inv, multistep, poly, sigmoid and torch_sgd. Note: when power value is -1, then "inv" policy with "gamma" is similar to "torch_sgd" with "learningRateDecay". -h,--gamma (default -1) Required to calculate learning rate, when any of the following learning rate policies are used: step, exp, inv, multistep & sigmoid -j,--power (default inf) Required to calculate learning rate, when any of the following learning rate policies are used: inv & poly -x,--stepvalues (default '') Required to calculate stepsize for the following learning rate policies: step, multistep & sigmoid. Note: if it is 'step' or 'sigmoid' policy, then this parameter expects single value, if it is 'multistep' policy, then this parameter expects a string which has all the step values delimited by comma (ex: "10,25,45,80") ]] ----------------------------------------------------------------------------------------------------------------------------- --Note: At present DIGITS supports only fine tuning, which means copying only the weights from pretrained model. -- --To include "crash recovery" feature, we may need to save the below torch elements for every fixed duration (or) for every fixed epochs (for instance 30 minutes or 10 epochs). -- -- trained model -- SGD optim state -- LRPolicy - this module helps in implementing caffe learning policies in Torch -- Random number state -- --And if the job was crashed, provide the saved backups using the command options (--retrain, --optimState, --randomState, --lrpolicyState) while restarting the job. -- --Please refer to below links for more information about "crash recovery" feature: -- 1) https://groups.google.com/forum/#!searchin/torch7/optimstate/torch7/uNxnrH-7C-4/pgIBdAFVaOYJ -- 2) https://groups.google.com/forum/#!topic/torch7/fcy0-5v6M08 -- 3) https://groups.google.com/forum/#!searchin/torch7/optimstate/torch7/Gv1BiQoaIVA/HRnjRoegR38J -- --Almost all the required routines are already implemented. Below are some remaining tasks, -- 1) while recovering from crash, we should only consider the below options and discard all other inputs like epoch -- --retrain, --optimState, --randomState, --lrpolicyState, --networkDirectory, --network, --save, --train, --validation, --mean, --labels, --snapshotPrefix -- 2) We should also save and restore some information like epoch, batch size, snapshot interval, subtractMean, shuffle, mirror, crop, croplen -- Precautions should be taken while restoring these options. ----------------------------------------------------------------------------------------------------------------------------- COMPUTE_TRAIN_ACCURACY = false ---------------------------------------------------------------------- -- Initial parameter checks -- Convert boolean options opt.crop = opt.crop == 'yes' or false opt.shuffle = opt.shuffle == 'yes' or false opt.visualizeModel = opt.visualizeModel == 'yes' or false -- Set the seed of the random number generator to the given number. if opt.seed ~= '' then torch.manualSeed(tonumber(opt.seed)) end -- validate options if opt.crop and opt.croplen == 0 then logmessage.display(2,'crop length is missing') os.exit(-1) end local stepvalues_list = {} -- verify whether required learning rate parameters are provided to calculate learning rate when caffe-like learning rate policies are used if opt.policy == 'fixed' or opt.policy == 'step' or opt.policy == 'exp' or opt.policy == 'inv' or opt.policy == 'multistep' or opt.policy == 'poly' or opt.policy == 'sigmoid' then if opt.policy == 'step' or opt.policy == 'exp' or opt.policy == 'inv' or opt.policy == 'multistep' or opt.policy == 'sigmoid' then if opt.gamma ==-1 then logmessage.display(2,'gamma parameter missing and is required to calculate learning rate when ' .. opt.policy .. ' learning rate policy is used') os.exit(-1) end end if opt.policy == 'inv' or opt.policy == 'poly' then if opt.power == math.huge then logmessage.display(2,'power parameter missing and is required to calculate learning rate when ' .. opt.policy .. ' learning rate policy is used') os.exit(-1) end end if opt.policy == 'step' or opt.policy == 'multistep' or opt.policy == 'sigmoid' then if opt.stepvalues =='' then logmessage.display(2,'step parameter missing and is required to calculate learning rate when ' .. opt.policy .. ' learning rate policy is used') os.exit(-1) else for i in string.gmatch(opt.stepvalues, '([^,]+)') do if tonumber(i) ~= nil then table.insert(stepvalues_list, tonumber(i)) else logmessage.display(2,'invalid step parameter value : ' .. opt.stepvalues .. '. step parameter should contain only number. if there are more than one value, then the values should be delimited by comma. ex: "10" or "10,25,45,80"') os.exit(-1) end end end end elseif opt.policy ~= 'torch_sgd' then logmessage.display(2,'invalid learning rate policy - '.. opt.policy .. '. Valid policies : fixed, step, exp, inv, multistep, poly, sigmoid and torch_sgd') os.exit(-1) end if opt.retrain ~= '' and opt.weights ~= '' then logmessage.display(2,"Both '--retrain' and '--weights' options cannot be used at the same time.") os.exit(-1) end if opt.randomState ~= '' and opt.seed ~= '' then logmessage.display(2,"Both '--randomState' and '--seed' options cannot be used at the same time.") os.exit(-1) end torch.setnumthreads(opt.threads) ---------------------------------------------------------------------- -- Open Data sources: -- mean tensor, -- training database and optionally: labels, -- optionally: validation database and labels. local data = require 'data' local meanTensor if opt.subtractMean ~= 'none' then assert(opt.mean ~= '', 'subtractMean parameter not set to "none" yet mean image path is unset') logmessage.display(0,'Loading mean tensor from '.. opt.mean ..' file') meanTensor = data.loadMean(opt.mean, opt.subtractMean == 'pixel') end local classes local trainConfusion local valConfusion if opt.labels ~= '' then logmessage.display(0,'Loading label definitions from '.. opt.labels ..' file') -- classes classes = data.loadLabels(opt.labels) if classes == nil then logmessage.display(2,'labels file '.. opt.labels ..' not found') os.exit(-1) end -- This matrix records the current confusion across classes trainConfusion = optim.ConfusionMatrix(classes) -- separate validation matrix for validation data valConfusion = nil if opt.validation ~= '' then valConfusion = optim.ConfusionMatrix(classes) end logmessage.display(0,'found ' .. #classes .. ' categories') end logmessage.display(0,'creating data readers') -- DataLoader objects take care of loading data from -- databases. Data loading and tensor manipulations -- (e.g. cropping, mean subtraction, mirroring) are -- performed from separate threads local trainDataLoader, trainSize, inputTensorShape local valDataLoader, valSize local num_threads_data_loader = 4 if opt.train ~= '' then -- create data loader for training dataset trainDataLoader = DataLoader:new( num_threads_data_loader, -- num threads package.path, opt.dbbackend, opt.train, opt.train_labels, meanTensor, true, -- train opt.shuffle, classes ~= nil -- whether this is a classification task ) -- retrieve info from train DB (number of records and shape of input tensors) trainSize, inputTensorShape = trainDataLoader:getInfo() logmessage.display(0,'found ' .. trainSize .. ' images in train db' .. opt.train) if opt.validation ~= '' then local shape valDataLoader = DataLoader:new( num_threads_data_loader, -- num threads package.path, opt.dbbackend, opt.validation, opt.validation_labels, meanTensor, false, -- train false, -- shuffle classes ~= nil -- whether this is a classification task ) valSize, shape = valDataLoader:getInfo() logmessage.display(0,'found ' .. valSize .. ' images in train db' .. opt.validation) end else assert(opt.visualizeModel, 'Train DB should be specified') end -- update inputTensorShape if crop length specified -- this is necessary as the inputTensorShape is provided -- below to the user-defined function that defines the network if opt.crop and inputTensorShape then inputTensorShape[2] = opt.croplen inputTensorShape[3] = opt.croplen end local nGpus = 0 if opt.type =='cuda' then require 'cunn' require 'cutorch' nGpus = cutorch.getDeviceCount() end ---------------------------------------------------------------------- -- Model + Loss: -- this is where we retrieve the network definition -- from the user-defined function package.path = paths.concat(opt.networkDirectory, "?.lua") ..";".. package.path logmessage.display(0,'Loading network definition from ' .. paths.concat(opt.networkDirectory, opt.network)) local network_func = require (opt.network) assert(type(network_func)=='function', "Network definition should return a Lua function - see documentation") local parameters = { nclasses = (classes ~= nil) and #classes or nil, ngpus = nGpus, inputShape = inputTensorShape } network = network_func(parameters) local model = network.model -- embed model in parallel table unless explicitly disallowed in user-defined description if nGpus > 1 and not network.disableAutoDataParallelism then local gpus = torch.range(1, nGpus):totable() model = nn.DataParallelTable(1, true, true):add(model, gpus) end -- if the loss criterion was not defined in the network -- use nn.ClassNLLCriterion() by default local loss = network.loss or nn.ClassNLLCriterion() -- if the crop length was not defined on command line then -- check if the network defined a preferred crop length if not opt.crop and network.croplen then opt.crop = true opt.croplen = network.croplen end -- if batch size was not specified on command line then check -- whether the network defined a preferred batch size (there -- can be separate batch sizes for the training and validation -- sets) local trainBatchSize local valBatchSize if opt.batchSize==0 then local defaultBatchSize = 16 trainBatchSize = network.trainBatchSize or defaultBatchSize valBatchSize = network.validationBatchSize or defaultBatchSize else trainBatchSize = opt.batchSize valBatchSize = opt.batchSize end logmessage.display(0,'Train batch size is '.. trainBatchSize .. ' and validation batch size is ' .. valBatchSize) -- if we were instructed to print a visualization of the model, -- do it now and return immediately if opt.visualizeModel then logmessage.display(0,'Network definition:') print('\nModel: \n' .. model:__tostring()) print('\nCriterion: \n' .. loss:__tostring()) logmessage.display(0,'Network definition ends') os.exit(-1) end -- NOTE: currently randomState option wasn't used in DIGITS. This option was provided to be used from command line, if required. -- load random number state from backup if opt.randomState ~= '' then if paths.filep(opt.randomState) then logmessage.display(0,'Loading random number state - ' .. opt.randomState) torch.setRNGState(torch.load(opt.randomState)) else logmessage.display(2,'random number state not found: ' .. opt.randomState) os.exit(-1) end end ---------------------------------------------------------------------- -- NOTE: currently retrain option wasn't used in DIGITS. This option was provided to be used from command line, if required. -- If preloading option is set, preload existing models appropriately if opt.retrain ~= '' then if paths.filep(opt.retrain) then logmessage.display(0,'Loading pretrained model - ' .. opt.retrain) model = torch.load(opt.retrain) else logmessage.display(2,'Pretrained model not found: ' .. opt.retrain) os.exit(-1) end end logmessage.display(0,'Network definition: \n' .. model:__tostring()) logmessage.display(0,'Network definition ends') local function saveModel(model, directory, prefix, epoch) local filename local modelObjectToSave if model.clearState then -- save the full model filename = paths.concat(directory, prefix .. '_' .. epoch .. '_Model.t7') modelObjectToSave = model:clearState() else -- this version of Torch doesn't support clearing the model state => save only the weights local Weights,Gradients = model:getParameters() filename = paths.concat(directory, prefix .. '_' .. epoch .. '_Weights.t7') modelObjectToSave = Weights end logmessage.display(0,'Snapshotting to ' .. filename) torch.save(filename, modelObjectToSave) logmessage.display(0,'Snapshot saved - ' .. filename) end local function switchType(newType, model, loss) if newType == 'float' then logmessage.display(0,'switching to floats') torch.setdefaulttensortype('torch.FloatTensor') model:float() loss = loss:float() elseif newType =='cuda' then cutorch.setDevice(1) logmessage.display(0,'switching to CUDA') model:cuda() loss = loss:cuda() end return loss end -- If weights option is set, preload weights from existing models appropriately if opt.weights ~= '' then if paths.filep(opt.weights) then logmessage.display(0,'Loading weights from pretrained model - ' .. opt.weights) if (string.find(opt.weights, '_Weights')) then local w, grad = model:getParameters() w:copy(torch.load(opt.weights)) else -- the full model was saved assert(string.find(opt.weights, '_Model')) if nn.DataParallelTable then -- set number of GPUs to use when deserializing model nn.DataParallelTable.deserializeNGPUs = nGpus end model = torch.load(opt.weights) network.model = model end else logmessage.display(2,'Weight file for pretrained model not found: ' .. opt.weights) os.exit(-1) end end -- allow user to fine tune model (this needs to be done *after* we have loaded the snapshot) if network.fineTuneHook then logmessage.display(0,'Calling user-defined fine tuning hook...') model = network.fineTuneHook(model) logmessage.display(0,'Network definition: \n' .. model:__tostring()) logmessage.display(0,'Network definition ends') end -- switch to float or cuda loss = switchType(opt.type, model, loss) -- get model parameters local Weights,Gradients = model:getParameters() -- create a directory, if not exists, to save all the snapshots -- os.execute('mkdir -p ' .. paths.concat(opt.save)) -- commented this line, as os.execute command is not portable if lfs.mkdir(paths.concat(opt.save)) then logmessage.display(0,'created a directory ' .. paths.concat(opt.save) .. ' to save all the snapshots') end -- validate "crop length" input parameter if opt.crop and inputTensorShape then assert(opt.croplen <= math.min(inputTensorShape[2], inputTensorShape[3]), 'croplen parameter is bigger than input image size') end -- Set up augmentation options augOpt = { augFlip = opt.augFlip, augQuadRot = opt.augQuadRot, augRot = opt.augRot, augScale = opt.augScale, augNoise = opt.augNoise, augHSV = {H=opt.augHSVh, S=opt.augHSVs, V=opt.augHSVv}, crop = {use=opt.crop, Y=-1, X=-1, len=opt.croplen}, } logmessage.display(0, 'augOpt:' .. table.concat(augOpt)) trainDataLoader:setDataAugmentation(augOpt) if valDataLoader then -- Note the valDataLoader will automatically nullify certain augmentation options because it knows it is the validation loader due to the test parameter valDataLoader:setDataAugmentation(augOpt) end --modifying total sizes of train and validation dbs to be the exact multiple of 32, when cc2 is used if ccn2 ~= nil then if (trainSize % 32) ~= 0 then logmessage.display(1,'when ccn2 is used, total images should be the exact multiple of 32. In train db, as the total images are ' .. trainSize .. ', skipped the last ' .. trainSize % 32 .. ' images from train db') trainSize = trainSize - (trainSize % 32) end if opt.validation ~= '' and (valSize % 32) ~=0 then logmessage.display(1,'when ccn2 is used, total images should be the exact multiple of 32. In validation db, as the total images are ' .. valSize .. ', skipped the last ' .. valSize % 32 .. ' images from validation db') valSize = valSize - (valSize % 32) end end --initializing learning rate policy logmessage.display(0,'initializing the parameters for learning rate policy: ' .. opt.policy) local lrpolicy = {} if opt.policy ~= 'torch_sgd' then local max_iterations = (math.ceil(trainSize/trainBatchSize))*opt.epoch --local stepsize = math.floor((max_iterations*opt.step/100)+0.5) --adding 0.5 to round the value if max_iterations < #stepvalues_list then logmessage.display(1,'maximum iterations (i.e., ' .. max_iterations .. ') is less than provided step values count (i.e, ' .. #stepvalues_list .. '), so learning rate policy is reset to "step" policy with the step value 1.') opt.policy = 'step' stepvalues_list[1] = 1 else -- converting stepsize percentages into values for i=1,#stepvalues_list do stepvalues_list[i] = utils.round(max_iterations*stepvalues_list[i]/100) -- avoids 'nan' values during learning rate calculation if stepvalues_list[i] == 0 then stepvalues_list[i] = 1 end end end lrpolicy = LRPolicy{ policy = opt.policy, baselr = opt.learningRate, gamma = opt.gamma, power = opt.power, max_iter = max_iterations, step_values = stepvalues_list } else lrpolicy = LRPolicy{ policy = opt.policy, baselr = opt.learningRate } end -- NOTE: currently lrpolicyState option wasn't used in DIGITS. This option was provided to be used from command line, if required. if opt.lrpolicyState ~= '' then if paths.filep(opt.lrpolicyState) then logmessage.display(0,'Loading lrpolicy state from file: ' .. opt.lrpolicyState) lrpolicy = torch.load(opt.lrpolicyState) else logmessage.display(2,'lrpolicy state file not found: ' .. opt.lrpolicyState) os.exit(-1) end end --resetting "learningRateDecay = 0", so that sgd.lua won't recalculates the learning rate if lrpolicy.policy ~= 'torch_sgd' then opt.learningRateDecay = 0 end local optimState = { learningRate = opt.learningRate, momentum = opt.momentum, weightDecay = opt.weightDecay, learningRateDecay = opt.learningRateDecay } -- NOTE: currently optimState option wasn't used in DIGITS. This option was provided to be used from command line, if required. if opt.optimState ~= '' then if paths.filep(opt.optimState) then logmessage.display(0,'Loading optimState from file: ' .. opt.optimState) optimState = torch.load(opt.optimState) -- this makes sure that sgd.lua won't recalculates the learning rate while using learning rate policy if lrpolicy.policy ~= 'torch_sgd' then optimState.learningRateDecay = 0 end else logmessage.display(1,'Optim state file not found: ' .. opt.optimState) -- if optim state file isn't found, notify user and continue training end end local function updateConfusion(y,yt) if trainConfusion ~= nil then trainConfusion:batchAdd(y,yt) end end local labelFunction = network.labelHook or function (input, dblabel) return dblabel end -- Optimization configuration logmessage.display(0,'initializing the parameters for Optimizer') local optimizer = Optimizer{ Model = model, Loss = loss, --OptFunction = optim.sgd, OptFunction = _G.optim[opt.optimization], OptState = optimState, Parameters = {Weights, Gradients}, HookFunction = COMPUTE_TRAIN_ACCURACY and updateConfusion or nil, lrPolicy = lrpolicy, LabelFunction = labelFunction, } -- During training, loss rate should be displayed at max 8 times or for every 5000 images, whichever lower. local logging_check = 0 if (math.ceil(trainSize/8)<5000) then logging_check = math.ceil(trainSize/8) else logging_check = 5000 end logmessage.display(0,'During training. details will be logged after every ' .. logging_check .. ' images') -- This variable keeps track of next epoch, when to perform validation. local next_validation = opt.interval logmessage.display(0,'Training epochs to be completed for each validation : ' .. opt.interval) local last_validation_epoch = 0 -- This variable keeps track of next epoch, when to save model weights. local next_snapshot_save = opt.snapshotInterval logmessage.display(0,'Training epochs to be completed before taking a snapshot : ' .. opt.snapshotInterval) local last_snapshot_save_epoch = 0 local snapshot_prefix = '' if opt.snapshotPrefix ~= '' then snapshot_prefix = opt.snapshotPrefix else snapshot_prefix = opt.network end -- epoch value will be calculated for every batch size. To maintain unique epoch value between batches, it needs to be rounded to the required number of significant digits. local epoch_round = 0 -- holds the required number of significant digits for round function. local tmp_batchsize = trainBatchSize while tmp_batchsize <= trainSize do tmp_batchsize = tmp_batchsize * 10 epoch_round = epoch_round + 1 end logmessage.display(0,'While logging, epoch value will be rounded to ' .. epoch_round .. ' significant digits') --[[ -- NOTE: uncomment this block when "crash recovery" feature was implemented logmessage.display(0,'model, lrpolicy, optim state and random number states will be saved for recovery from crash') logmessage.display(0,'model will be saved as ' .. snapshot_prefix .. '_<EPOCH>_model.t7') logmessage.display(0,'optim state will be saved as optimState_<EPOCH>.t7') logmessage.display(0,'random number state will be saved as randomState_<EPOCH>.t7') logmessage.display(0,'LRPolicy state will be saved as lrpolicy_<EPOCH>.t7') --]] -- NOTE: currently this routine wasn't used in DIGITS. -- This routine takes backup of model, optim state, LRPolicy and random number state local function backupforrecovery(backup_epoch) -- save model local filename = paths.concat(opt.save, snapshot_prefix .. '_' .. backup_epoch .. '_model.t7') logmessage.display(0,'Saving model to ' .. filename) utils.cleanupModel(model) torch.save(filename, model) logmessage.display(0,'Model saved - ' .. filename) --save optim state filename = paths.concat(opt.save, 'optimState_' .. backup_epoch .. '.t7') logmessage.display(0,'optim state saving to ' .. filename) torch.save(filename, optimState) logmessage.display(0,'optim state saved - ' .. filename) --save random number state filename = paths.concat(opt.save, 'randomState_' .. backup_epoch .. '.t7') logmessage.display(0,'random number state saving to ' .. filename) torch.save(filename, torch.getRNGState()) logmessage.display(0,'random number state saved - ' .. filename) --save lrPolicy state filename = paths.concat(opt.save, 'lrpolicy_' .. backup_epoch .. '.t7') logmessage.display(0,'lrpolicy state saving to ' .. filename) torch.save(filename, optimizer.lrPolicy) logmessage.display(0,'lrpolicy state saved - ' .. filename) end -- Validation function local function Validation(model, loss, epoch, data_loader, data_size, batch_size, confusion, label_function) -- switch model to evaluation mode model:evaluate() local batch_count = 0 local loss_sum = 0 local data_index = 1 local data = {} if confusion ~= nil then confusion:zero() end local count = 1 while count <= data_size do -- create mini batch while data_loader:acceptsjob() do local curr_batch_size = math.min(data_size - data_index + 1, batch_size) if curr_batch_size > 0 then data_loader:scheduleNextBatch(curr_batch_size, data_index, data, true) data_index = data_index + curr_batch_size else break end end -- wait for next data loader job to complete data_loader:waitNext() -- get data from last load job local data_batch_size = data.batchSize local inputs = data.inputs local targets = data.outputs if inputs ~= nil then if opt.type == 'cuda' then inputs = inputs:cuda() targets = targets:cuda() else inputs = inputs:float() targets = targets:float() end local y = model:forward(inputs) local labels = label_function(inputs, targets) local err = loss:forward(y, labels) loss_sum = loss_sum + err if confusion ~= nil then confusion:batchAdd(y, labels) end batch_count = batch_count + 1 if math.fmod(batch_count, 50) == 0 then collectgarbage() end count = count + data_batch_size else -- failed to read from database (possibly due to disabled thread) data_index = data_index - data_batch_size end end local avg_loss = batch_count > 0 and loss_sum / batch_count or 0 if confusion ~= nil then confusion:updateValids() logmessage.display(0, 'Validation (epoch ' .. epoch .. '): loss = ' .. avg_loss .. ', accuracy = ' .. confusion.totalValid) else logmessage.display(0, 'Validation (epoch ' .. epoch .. '): loss = ' .. avg_loss) end end -- Train function local function Train(epoch, dataLoader) model:training() local NumBatches = 0 local curr_images_cnt = 0 local loss_sum = 0 local loss_batches_cnt = 0 local learningrate = 0 local inputs, targets local dataLoaderIdx = 1 local data = {} local t = 1 while t <= trainSize do while dataLoader:acceptsjob() do local dataBatchSize = math.min(trainSize-dataLoaderIdx+1,trainBatchSize) if dataBatchSize > 0 then dataLoader:scheduleNextBatch(dataBatchSize, dataLoaderIdx, data, true) dataLoaderIdx = dataLoaderIdx + dataBatchSize else break end end NumBatches = NumBatches + 1 -- wait for next data loader job to complete dataLoader:waitNext() -- get data from last load job local thisBatchSize = data.batchSize inputs = data.inputs targets = data.outputs if inputs then --[=[ -- print some statistics, show input in iTorch if t%1024==1 then print(string.format("input mean=%f std=%f",inputs:mean(),inputs:std())) for idx=1,thisBatchSize do print(classes[targets[idx]]) end if itorch then itorch.image(inputs) end end --]=] if opt.type =='cuda' then inputs = inputs:cuda() targets = targets:cuda() else inputs = inputs:float() targets = targets:float() end _,learningrate,_,trainerr = optimizer:optimize(inputs, targets) -- adding the loss values of each mini batch and also maintaining the counter for number of batches, so that average loss value can be found at the time of logging details loss_sum = loss_sum + trainerr[1] loss_batches_cnt = loss_batches_cnt + 1 if math.fmod(NumBatches,50)==0 then collectgarbage() end local current_epoch = (epoch-1)+utils.round((math.min(t+trainBatchSize-1,trainSize))/trainSize, epoch_round) -- log details on first iteration, or when required number of images are processed curr_images_cnt = curr_images_cnt + thisBatchSize if (epoch==1 and t==1) or curr_images_cnt >= logging_check then logmessage.display(0, 'Training (epoch ' .. current_epoch .. '): loss = ' .. (loss_sum/loss_batches_cnt) .. ', lr = ' .. learningrate) curr_images_cnt = 0 -- For accurate values we may assign curr_images_cnt % logging_check to curr_images_cnt, instead of 0 loss_sum = 0 loss_batches_cnt = 0 end if opt.validation ~= '' and current_epoch >= next_validation then Validation(model, loss, current_epoch, valDataLoader, valSize, valBatchSize, valConfusion, labelFunction) next_validation = (utils.round(current_epoch/opt.interval) + 1) * opt.interval -- To find next nearest epoch value that exactly divisible by opt.interval last_validation_epoch = current_epoch model:training() -- to reset model to training end if current_epoch >= next_snapshot_save then saveModel(model, opt.save, snapshot_prefix, current_epoch) next_snapshot_save = (utils.round(current_epoch/opt.snapshotInterval) + 1) * opt.snapshotInterval -- To find next nearest epoch value that exactly divisible by opt.snapshotInterval last_snapshot_save_epoch = current_epoch end t = t + thisBatchSize else -- failed to read from database (possibly due to disabled thread) dataLoaderIdx = dataLoaderIdx - data.batchSize end end --xlua.progress(trainSize, trainSize) end ------------------------------ local epoch = 1 logmessage.display(0,'started training the model') -- run an initial validation before the first train epoch if opt.validation ~= '' then Validation(model, loss, 0, valDataLoader, valSize, valBatchSize, valConfusion, labelFunction) end while epoch<=opt.epoch do local ErrTrain = 0 if trainConfusion ~= nil then trainConfusion:zero() end Train(epoch, trainDataLoader) if trainConfusion ~= nil then trainConfusion:updateValids() --print(trainConfusion) ErrTrain = (1-trainConfusion.totalValid) end epoch = epoch+1 end -- if required, perform validation at the end if opt.validation ~= '' and opt.epoch > last_validation_epoch then Validation(model, loss, opt.epoch, valDataLoader, valSize, valBatchSize, valConfusion, labelFunction) end -- if required, save snapshot at the end if opt.epoch > last_snapshot_save_epoch then saveModel(model, opt.save, snapshot_prefix, opt.epoch) end -- close databases trainDataLoader:close() if opt.validation ~= '' then valDataLoader:close() end -- enforce clean exit os.exit(0)
bsd-3-clause
simon-wh/PAYDAY-2-BeardLib-Editor
mods/BeardLib-Editor/Classes/Map/Elements/coreinstance.lua
1
13635
EditorInstanceInput = EditorInstanceInput or class(MissionScriptEditor) EditorInstanceInput.SAVE_UNIT_POSITION = false EditorInstanceInput.SAVE_UNIT_ROTATION = false function EditorInstanceInput:create_element() EditorInstanceInput.super.create_element(self) self._element.class = "ElementInstanceInput" self._element.module = "CoreElementInstance" self._element.values.event = "none" end function EditorInstanceInput:_build_panel() self:_create_panel() self:StringCtrl("event") end EditorInstanceOutput = EditorInstanceOutput or class(EditorInstanceInput) function EditorInstanceOutput:create_element(...) EditorInstanceOutput.super.create_element(self, ...) self._element.class = "ElementInstanceOutput" self._element.module = "CoreElementInstance" end EditorInstanceInputEvent = EditorInstanceInputEvent or class(MissionScriptEditor) EditorInstanceInputEvent.SAVE_UNIT_POSITION = false EditorInstanceInputEvent.SAVE_UNIT_ROTATION = false function EditorInstanceInputEvent:init(...) local unit = EditorInstanceInputEvent.super.init(self, ...) self._type = "input" return unit end function EditorInstanceInputEvent:create_element() EditorInstanceInputEvent.super.create_element(self) self._element.class = "ElementInstanceInputEvent" self._element.module = "CoreElementInstance" self._element.values.event_list = {} end function EditorInstanceInputEvent:_draw_instance_link(instance_name) local instance = managers.world_instance:get_instance_data_by_name(instance_name) if type(instance) ~= "table" then return false end if self._type == "input" then Application:draw_arrow(self._unit:position(), instance.position, r, g, b, 0.2) else Application:draw_arrow(instance.position, self._unit:position(), r, g, b, 0.2) end return true end function EditorInstanceInputEvent:update(t, dt, instance_name) local r, g, b = self._unit:mission_element()._color:unpack() for i, data in ipairs(self._element.values.event_list) do if not self:_draw_instance_link(data.instance) then table.remove(self._element.values.event_list, i) end end EditorInstanceInputEvent.super.update(self, t, dt) end function EditorInstanceInputEvent:_get_events(instance_name) if self._type == "input" then return managers.world_instance:get_mission_inputs_by_name(instance_name) else return managers.world_instance:get_mission_outputs_by_name(instance_name) end end function EditorInstanceInputEvent:_build_panel() self:_create_panel() self:BuildInstancesManage("event_list", {values_name = "Event", value_key = "event", default_value = "none", key = "instance", orig = {instance = "", event = "none"}, combo_items_func = function(name) return self:_get_events(name) end}) end EditorInstanceOutputEvent = EditorInstanceOutputEvent or class(EditorInstanceInputEvent) function EditorInstanceOutputEvent:init(...) local unit = EditorInstanceOutputEvent.super.init(self, ...) self._type = "output" return unit end function EditorInstanceOutputEvent:create_element() EditorInstanceOutputEvent.super.create_element(self) self._element.class = "ElementInstanceOutputEvent" self._element.module = "CoreElementInstance" end EditorInstancePoint = EditorInstancePoint or class(MissionScriptEditor) function EditorInstancePoint:create_element() EditorInstancePoint.super.create_element(self) self._element.class = "ElementInstancePoint" self._element.module = "CoreElementInstance" end function EditorInstancePoint:update(t, dt) if self._element.values.instance then if not EditorInstanceInputEvent._draw_instance_link(self, self._element.values.instance) then self._element.values.instance = nil end end EditorInstancePoint.super.update(self, t, dt) end function EditorInstancePoint:external_change_instance(instance) self._element.values.instance = instance end function EditorInstancePoint:_build_panel() self:_create_panel() local names = {} for _, name in ipairs(managers.world_instance:instance_names_by_script(self._element.script)) do if managers.world_instance:get_instance_data_by_name(name).mission_placed then table.insert(names, name) end end self:ComboCtrl("instance", names) end EditorInstanceSetParams = EditorInstanceSetParams or class(MissionScriptEditor) function EditorInstanceSetParams:create_element() EditorInstanceSetParams.super.create_element(self) self._element.class = "ElementInstanceSetParams" self._element.module = "CoreElementInstance" self._element.values.params = {} end function EditorInstanceSetParams:update(t, dt) if self._element.values.instance then if not EditorInstanceInputEvent._draw_instance_link(self, self._element.values.instance) then self._element.values.instance = nil end end EditorInstanceSetParams.super.update(self, t, dt) end function EditorInstanceSetParams:_check_change_instance(new_instance) if not self._element.values.instance or not next(self._element.values.params) then self._element.values.instance = new_instance return end local new_folder = managers.world_instance:get_instance_data_by_name(new_instance).folder local folder = managers.world_instance:get_instance_data_by_name(self._element.values.instance).folder if new_folder == folder then self._element.values.instance = new_instance return end BeardLibEditor.Utils:YesNoQuestion("This will change the instance from " .. self._element.values.instance .. " to " .. new_instance .. "and will reset the params", function() self._element.values.params = {} self._element.values.instance = new_instance self:_build_from_params() end, function() self:GetItem("instance"):SetSelectedItem(self._element.values.instance) end) end function EditorInstanceSetParams:_build_from_params() self._instance_menu:ClearItems() if not self._element.values.instance then self:Divider("No instance selected", {color = false, group = self._instance_menu}) return end local params = managers.world_instance:get_instance_params_by_name(self._element.values.instance) for _, data in ipairs(params) do local value_ctrlr local name = data.var_name local opt = {data = self._element.values.params, group = self._instance_menu} if data.type == "number" then value_ctrlr = self:NumberCtrl(name, opt) elseif data.type == "enemy" then value_ctrlr = self:PathCtrl(name, "unit", 12) elseif data.type == "civilian" then value_ctrlr = self:PathCtrl(name, "unit", 21) elseif data.type == "objective" then value_ctrlr = self:ComboCtrl(name, managers.objectives:objectives_by_name(), opt) elseif data.type == "enemy_spawn_action" then value_ctrlr = self:ComboCtrl(name, clone(CopActionAct._act_redirects.enemy_spawn), opt) elseif data.type == "civilian_spawn_state" then value_ctrlr = self:ComboCtrl(name, clone(CopActionAct._act_redirects.civilian_spawn), opt) elseif data.type == "special_objective_action" then value_ctrlr = self:ComboCtrl(name, clone(CopActionAct._act_redirects.SO), opt) end local use = self:Toggle("use_"..name, ClassClbk(self, "_on_gui_toggle_use"), self._element.values.params[name] and true or false, { text = "Using Variable", value_ctrlr = value_ctrlr, var_name = name, help = "Toggle use of variable on/off", group = self._instance_menu }) value_ctrlr:SetEnabled(use:Value()) end if #self._instance_menu._my_items == 0 then self:Divider("No parameters", {color = false, group = self._instance_menu}) end end function EditorInstanceSetParams:_on_gui_toggle_use(item) local use = item:Value() item.value_ctrlr:SetEnabled(use) local orig_value = item.value_ctrlr:Value() self._element.values.params[item.var_name] = use and (tonumber(orig_value) or orig_value) or nil end function EditorInstanceSetParams:_build_panel() self:_create_panel() local names = {} for _, name in ipairs(managers.world_instance:instance_names_by_script(self._element.script)) do table.insert(names, name) end table.insert(names, "none") table.sort(names) self:ComboCtrl("instance", names) self:BooleanCtrl("apply_on_execute") self._instance_menu = self:DivGroup("Instance Params") self:_build_from_params() end function EditorInstanceSetParams:set_element_data(item, ...) if item.name == "instance" then if item:SelectedItem() == "none" then item:SetSelectedItem() end self:_check_change_instance(item:SelectedItem()) self:_build_from_params() return end EditorInstanceSetParams.super.set_element_data(self, item, ...) end EditorInstanceParams = EditorInstanceParams or class(MissionScriptEditor) EditorInstanceParams.TYPES = {"number","enemy","objective","civilian","enemy_spawn_action","civilian_spawn_state","special_objective_action"} function EditorInstanceParams:create_element(...) EditorInstanceParams.super.create_element(self) self._element.class = "ElementInstanceParams" self._element.module = "CoreElementInstance" self._element.values.params = {} end function EditorInstanceParams:_add_var_dialog(text) local typ BLE.InputDialog:Show( { title = "Add Variable", text = text or "", create_items = function(menu) typ = menu:combobox("Type", nil, self.TYPES) end, callback = function(name) if not name or name == "" then BLE.Dialog:Show({title = "ERROR!", message = "Variable name cannot be empty!", callback = ClassClbk(self, "_add_var_dialog", name)}) return end for _, data in ipairs(self._element.values.params) do if data.var_name == name then BLE.Dialog:Show({title = "ERROR!", message = "Variable name already exists!", callback = ClassClbk(self, "_add_var_dialog", name)}) return end end local type = typ:SelectedItem() if not type then BLE.Dialog:Show({title = "ERROR!", message = "Variables must have a type!", callback = ClassClbk(self, "_add_var_dialog", name)}) return end local default_value = nil if type == "number" then default_value = 0 elseif type == "enemy" then default_value = "units/payday2/characters/ene_swat_1/ene_swat_1" elseif type == "civilian" then default_value = "" elseif type == "objective" then default_value = managers.objectives:objectives_by_name()[1] elseif type == "enemy_spawn_action" then default_value = clone(CopActionAct._act_redirects.enemy_spawn)[1] elseif type == "civilian_spawn_state" then default_value = CopActionAct._act_redirects.civilian_spawn[1] elseif type == "special_objective_action" then default_value = CopActionAct._act_redirects.SO[1] end local data = { var_name = name, type = type, default_value = default_value } table.insert(self._element.values.params, data) self:_build_var_panel(data) end } ) end function EditorInstanceParams:_remove_var_name(var_name, item) for i, data in ipairs(self._element.values.params) do if data.var_name == var_name then table.remove(self._element.values.params, i) if self._panels[i] then local rem_data = table.remove(self._panels, i) rem_data.item:Destroy() item:Destroy() end return end end end function EditorInstanceParams:_build_var_panel(data) self._panels = self._panels or {} if data.type == "number" then self:_build_number(data) elseif data.type == "enemy" then self:_build_pathbox(data, 12) elseif data.type == "civilian" then self:_build_pathbox(data, 21) elseif data.type == "objective" then self:_build_combobox(data, managers.objectives:objectives_by_name()) elseif data.type == "enemy_spawn_action" then self:_build_combobox(data, clone(CopActionAct._act_redirects.enemy_spawn)) elseif data.type == "civilian_spawn_state" then self:_build_combobox(data, clone(CopActionAct._act_redirects.civilian_spawn)) elseif data.type == "special_objective_action" then self:_build_combobox(data, clone(CopActionAct._act_redirects.SO)) end end function EditorInstanceParams:_build_remove_var(item) self._pan:ImgButton("RemoveVariable", ClassClbk(self, "_remove_var_name", item.name), nil, BLE.Utils:GetIcon("cross"), { offset = item.offset, size = 22 }) table.insert(self._panels, {var_name = item.var_name, item = item}) end function EditorInstanceParams:_build_number(data) self:_build_remove_var(self._pan:numberbox(data.var_name, ClassClbk(self, "_set_default_var_name", data), data.default_value, { floats = 0, help = "Set a default number variable.", shrink_width = 0.91 })) end function EditorInstanceParams:_build_combobox(data, options) self:_build_remove_var(self._pan:combobox(data.var_name, ClassClbk(self, "_set_default_var_name", data), options, data.default_value, { shrink_width = 0.91, control_slice = 0.65 })) end function EditorInstanceParams:_build_pathbox(data, slot) self:_build_remove_var(self._pan:pathbox(data.var_name, ClassClbk(self, "_set_default_var_name", data), data.default_value, "unit", { slot = slot, shrink_width = 0.91 })) end function EditorInstanceParams:_set_default_var_name(data, item) local value = item:Value() data.default_value = tonumber(value) or value end function EditorInstanceParams:_build_panel() self:_create_panel() self._class_group:button("AddVariable", ClassClbk(self, "_add_var_dialog", false), nil, BLE.Utils:GetIcon("plus")) self._pan = self._class_group:pan("Params", {align_method = "grid"}) for _, data in ipairs(self._element.values.params) do self:_build_var_panel(data) end end
mit
kidaa/FFXIOrgins
scripts/zones/Qufim_Island/npcs/Trodden_Snow.lua
3
2454
----------------------------------- -- Area: Qufim Island -- NPC: Trodden Snow -- Mission: ASA - THAT_WHICH_CURDLES_BLOOD -- @zone 126 -- @pos -19 -17 104 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Qufim_Island/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) -- Trade Enfeebling Kit if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if(asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end if(trade:getItemCount() == 1 and trade:hasItemQty(item,1)) then player:tradeComplete(); player:startEvent(0x002c); end end end; ----------------------------------- -- onTrigger ----------------------------------- 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==0x002c) then player:addKeyItem(DOMINAS_SCARLET_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_SCARLET_SEAL); player:addKeyItem(DOMINAS_CERULEAN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_CERULEAN_SEAL); player:addKeyItem(DOMINAS_EMERALD_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_EMERALD_SEAL); player:addKeyItem(DOMINAS_AMBER_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AMBER_SEAL); player:addKeyItem(DOMINAS_VIOLET_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_VIOLET_SEAL); player:addKeyItem(DOMINAS_AZURE_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AZURE_SEAL); player:completeMission(ASA,THAT_WHICH_CURDLES_BLOOD); player:addMission(ASA,SUGAR_COATED_DIRECTIVE); player:setVar("ASA_Status",0); end end;
gpl-3.0
flyzjhz/openwrt-bb
feeds/luci/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo.lua
141
1038
--[[ 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("SIP Device 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", false, debug) luci.controller.luci_diag.smap_common.action_links(m, false) return m
gpl-2.0
kidaa/FFXIOrgins
scripts/zones/Metalworks/npcs/Hungry_Wolf.lua
19
2040
----------------------------------- -- Area: Metalworks -- NPC: Hungry Wolf -- Type: Quest Giver -- @pos -25.861 -11 -30.172 237 -- -- Auto-Script: Requires Verification (Verified by Brawndo) -- Updated for "Smoke on the Mountain" by EccentricAnata 03.22.13 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN) ~= QUEST_AVAILABLE and trade:hasItemQty(4395,1) and trade:getItemCount() == 1) then player:startEvent(0x01ad); end --]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SmokeOnTheMountain = player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN); if (SmokeOnTheMountain == QUEST_AVAILABLE) then player:startEvent(0x01ac); else player:startEvent(0x01a5); 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 == 0x01ac) then player:addQuest(BASTOK,SMOKE_ON_THE_MOUNTAIN); elseif(csid == 0x01ad) then player:tradeComplete(); player:addGil(GIL_RATE*300) player:messageSpecial(GIL_OBTAINED,GIL_RATE*300); player:addTitle(HOT_DOG); if(player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN) == QUEST_ACCEPTED) then player:addFame(BASTOK,BAS_FAME*30); player:completeQuest(BASTOK,SMOKE_ON_THE_MOUNTAIN); else player:addFame(BASTOK,BAS_FAME*5); end end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/spells/moogle_rhapsody.lua
2
1096
----------------------------------------- -- Spell: Moogle Rhapsody -- Increases Confusion Resistance to -- Party Members within target AoE ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Mostly Guestimate ?? local duration = 120; local power = 20; duration = duration + (duration * (caster:getMod(MOD_SONG_DURATION)/100)); duration = duration + (duration * ((caster:getMod(MOD_ALL_SONGS) * 10)/100)); power = power + (caster:getMod(MOD_ALL_SONGS) * 4); -- Until someone finds a way to delete Effects by tier we should not allow bard spells to stack. -- Since all the tiers use the same effect buff it is hard to delete a specific one. target:delStatusEffect(EFFECT_RHAPSODY); target:addStatusEffect(EFFECT_RHAPSODY,power,0,duration); spell:setMsg(230); return EFFECT_RHAPSODY; end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Southern_San_dOria/npcs/Glenne.lua
2
3817
------------------------------------- -- Area: Southern San d'Oria -- NPC: Glenne -- Starts and Finishes Quest: A Sentry's Peril -- @zone 230 -- @pos -122 -2 15 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/pathfind"); path = { -121.512833, -2.000000, 14.492509, -122.600044, -2.000000, 14.535807, -123.697128, -2.000000, 14.615446, -124.696846, -2.000000, 14.707844, -123.606018, -2.000000, 14.601295, -124.720863, -2.000000, 14.709210, -123.677681, -2.000000, 14.608237, -124.752579, -2.000000, 14.712106, -123.669525, -2.000000, 14.607473, -124.788277, -2.000000, 14.715488, -123.792847, -2.000000, 14.619405, -124.871826, -2.000000, 14.723736 }; function onSpawn(npc) npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end elseif(player:getQuestStatus(SANDORIA,A_SENTRY_S_PERIL) == QUEST_ACCEPTED) then if(trade:hasItemQty(601,1) and trade:getItemCount() == 1) then player:startEvent(0x0201); npc:wait(-1); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) aSentrysPeril = player:getQuestStatus(SANDORIA,A_SENTRY_S_PERIL); npc:wait(-1); if(aSentrysPeril == QUEST_AVAILABLE) then player:startEvent(0x01fe); elseif(aSentrysPeril == QUEST_ACCEPTED) then if (player:hasItem(600) == true or player:hasItem(601) == true) then player:startEvent(0x0208); else player:startEvent(0x0284); end elseif(aSentrysPeril == QUEST_COMPLETED) then player:startEvent(0x0209); else npc:wait(0); 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); GetNPCByID(17719328):wait(5000); if (csid == 0x01fe and option == 0) then if (player:getFreeSlotsCount() > 0) then player:addQuest(SANDORIA,A_SENTRY_S_PERIL); player:addItem(600); player:messageSpecial(ITEM_OBTAINED,600); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,600); -- Dose of ointment end elseif (csid == 0x0284) then if(player:getFreeSlotsCount() > 0) then player:addItem(600); player:messageSpecial(ITEM_OBTAINED,600); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,600); -- Dose of ointment end elseif(csid == 0x0201) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12832); -- Bronze Subligar else player:tradeComplete(); player:addTitle(RONFAURIAN_RESCUER); player:addItem(12832); player:messageSpecial(ITEM_OBTAINED,12832); -- Bronze Subligar player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,A_SENTRY_S_PERIL); end else GetNPCByID(17719328):wait(0); end end;
gpl-3.0
xia-lixun/libvsthostm
Trunk/hetero/Debug/host.lua
1
2954
--#!/bin/lua --configurations for simple vst host NumInputWavLocations = 0 NumOutputWavLocations = 0 NumVstPluginLocations = 0 InputWavLocations = {} OutputWavLocations = {} VstPluginLocations = {} ModuleCount = 0 ModuleNumInputs = {} --length ModuleCount ModuleNumOutputs = {} --length ModuleCount ConnectionCount = 0; FromModule = {} ToModule = {} FromPin = {} ToPin = {} PluginParams = {} --{{...}, {...}, {...}} function TableLength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function Module(t) --case of input module if t.numInputs == 0 then for i,v in ipairs(t) do table.insert(InputWavLocations, v) NumInputWavLocations = NumInputWavLocations + 1 end --case of output module elseif t.numOutputs == 0 then for i,v in ipairs(t) do table.insert(OutputWavLocations, v) NumOutputWavLocations = NumOutputWavLocations + 1 end --case of vst plugin module else table.insert(VstPluginLocations,t.location) NumVstPluginLocations = NumVstPluginLocations + 1 --collect vst plugin parameters table.insert(PluginParams, t.params) end table.insert(ModuleNumInputs, t.numInputs) table.insert(ModuleNumOutputs, t.numOutputs) ModuleCount = ModuleCount + 1 end function Map(t) for i,v in ipairs(t) do table.insert(FromModule, v[1][1]) table.insert(ToModule, v[2][1]) table.insert(FromPin, v[1][2]) table.insert(ToPin, v[2][2]) ConnectionCount = ConnectionCount + 1 end end --[1] plugin 1 is always the input --[2] plugin[#plugin] is always the output --[3] the rest plugins are arranged in sequence Host={ HostSampleRate = 44100, BlockSize = 64 } --plugin 1 Module{ numInputs = 0, numOutputs = 7, --put all input vectors here "D:/Git/libvsthostm/Trunk/hetero/Debug/quiet_2m_short.wav" } --plugin 2 Module{ location = "FixedBeamFormer.dll", numInputs = 7, numOutputs = 8, params = {0.0, 0.968, 0.458} } --plugin 3 Module{ location = "BeamSteering.dll", numInputs = 9, numOutputs = 9, params = {0.0, 0.226, 0.9, 0.73, 0.072, 0.488, 0.3333, 0.5, 0.3, 0.103, 0.5} } --plugin 4 Module{ location = "AdaptiveBeamFormer.dll", numInputs = 2, numOutputs = 2, params = {0.0, 1.0, 0.01, 0.5, 0.891, 0.869, 0.829, 0.7} } --plugin 5 Module{ numInputs = 2, numOutputs = 0, --put all resultant files here "D:/Git/libvsthostm/Trunk/hetero/Debug/quiet_2m_result.wav" } Map{ --{[module] = portout, [module] = portin} {{1,1}, {2,1}}, {{1,2}, {2,2}}, {{1,3}, {2,3}}, {{1,4}, {2,4}}, {{1,5}, {2,5}}, {{1,6}, {2,6}}, {{1,7}, {2,7}}, {{2,1}, {3,1}}, {{2,2}, {3,2}}, {{2,3}, {3,3}}, {{2,4}, {3,4}}, {{2,5}, {3,5}}, {{2,6}, {3,6}}, {{2,7}, {3,7}}, {{2,8}, {3,8}}, {{3,3}, {4,1}}, {{3,4}, {4,2}}, {{4,1}, {5,1}}, {{4,2}, {5,2}} }
mit
Yhgenomics/premake-core
src/base/option.lua
16
3399
-- -- option.lua -- Work with the list of registered options. -- Copyright (c) 2002-2014 Jason Perkins and the Premake project -- premake.option = {} local m = premake.option -- -- We can't control how people will type in the command line arguments, or how -- project scripts will define their custom options, so case becomes an issue. -- To mimimize issues, set up the _OPTIONS table to always use lowercase keys. -- local _OPTIONS_metatable = { __index = function(tbl, key) if type(key) == "string" then key = key:lower() end return rawget(tbl, key) end, __newindex = function(tbl, key, value) if type(key) == "string" then key = key:lower() end rawset(tbl, key, value) end } _OPTIONS = {} setmetatable(_OPTIONS, _OPTIONS_metatable) -- -- Process the raw command line arguments from _ARGV to populate -- the _OPTIONS table -- for i, arg in ipairs(_ARGV) do local key, value local i = arg:find("=", 1, true) if i then key = arg:sub(1, i - 1) value = arg:sub(i + 1) else key = arg value = "" end if key:startswith("/") then _OPTIONS[key:sub(2)] = value elseif key:startswith("--") then _OPTIONS[key:sub(3)] = value end end -- -- The list of registered options. Calls to newoption() will add -- new entries here. -- m.list = {} -- -- Register a new option. -- -- @param opt -- The new option object. -- function m.add(opt) -- some sanity checking local missing for _, field in ipairs({ "description", "trigger" }) do if (not opt[field]) then missing = field end end if (missing) then error("option needs a " .. missing, 3) end -- add it to the master list premake.option.list[opt.trigger:lower()] = opt -- if it has a default value, set it. if opt.default and not _OPTIONS[opt.trigger] then _OPTIONS[opt.trigger] = opt.default end end -- -- Retrieve an option by name. -- -- @param name -- The name of the option to retrieve. -- @returns -- The requested option, or nil if the option does not exist. -- function m.get(name) return premake.option.list[name] end -- -- Iterator for the list of options. -- function m.each() -- sort the list by trigger local keys = { } for _, option in pairs(premake.option.list) do table.insert(keys, option.trigger) end table.sort(keys) local i = 0 return function() i = i + 1 return premake.option.list[keys[i]] end end -- -- Validate a list of user supplied key/value pairs against the list of registered options. -- -- @param values -- The list of user supplied key/value pairs. -- @returns --- True if the list of pairs are valid, false and an error message otherwise. -- function m.validate(values) for key, value in pairs(values) do -- does this option exist local opt = premake.option.get(key) if (not opt) then return false, "invalid option '" .. key .. "'" end -- does it need a value? if (opt.value and value == "") then return false, "no value specified for option '" .. key .. "'" end -- is the value allowed? if opt.allowed then local found = false for _, match in ipairs(opt.allowed) do if match[1] == value then found = true break end end if not found then return false, string.format("invalid value '%s' for option '%s'", value, key) end end end return true end
bsd-3-clause
kidaa/FFXIOrgins
scripts/zones/Apollyon/mobs/Water_Elemental.lua
14
2337
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if(mobID==16932913 or mobID==16932921 or mobID==16932929)then correctelement=true; end end , [1] = function (x) if(mobID==16932912 or mobID==16932920 or mobID==16932928 )then correctelement=true; end end , [2] = function (x) if(mobID==16932916 or mobID==16932924 or mobID==16932932 )then correctelement=true; end end , [3] = function (x) if(mobID==16932910 or mobID==16932918 or mobID==16932926 )then correctelement=true; end end , [4] = function (x) if(mobID==16932914 or mobID==16932922 or mobID==16932930 )then correctelement=true; end end , [5] = function (x) if(mobID==16932917 or mobID==16932925 or mobID==16932933 )then correctelement=true; end end , [6] = function (x) if(mobID==16932931 or mobID==16932915 or mobID==16932923 )then correctelement=true; end end , [7] = function (x) if(mobID==16932911 or mobID==16932919 or mobID==16932927 )then correctelement=true; end end , }; if(correctelement==true and IselementalDayAreDead()==true)then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Selbina/npcs/Gabwaleid.lua
2
1452
----------------------------------- -- Area: Selbina -- NPC: Gabwaleid -- Involved in Quest: Riding on the Clouds -- @pos -17 -7 11 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 4) then if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0258); 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
LingJiJian/uLui
build/luajit-2.1.0/src/jit/v.lua
1
5925
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif ltype == "stitch" then out:write(format("[TRACE %3s %s%s %s %s]\n", tr, startex, startloc, ltype, fmtfunc(func, pc))) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon -- For -j command line option. }
mit
Fatalerror66/ffxi-a
scripts/zones/Upper_Jeuno/npcs/Baudin.lua
2
4526
----------------------------------- -- Area: Upper Jeuno -- NPC: Baudin -- Starts and Finishes Quest: Crest of Davoi, Save My Sister -- Involved in Quests: Save the Clock Tower -- @zone 244 -- @pos -75 0 80 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(555,1) and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz2"); -- NPC Zone2 if(a == 0 or (a ~= 32 and a ~= 96 and a ~= 160 and a ~= 288 and a ~= 544 and a ~= 224 and a ~= 800 and a ~= 352 and a ~= 672 and a ~= 416 and a ~= 608 and a ~= 480 and a ~= 736 and a ~= 864 and a ~= 928 and a ~= 992)) then player:startEvent(0x00b1,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end elseif(player:getQuestStatus(JEUNO,CREST_OF_DAVOI) == QUEST_ACCEPTED and trade:hasItemQty(4377,1) and trade:getItemCount() == 1) then player:startEvent(0x00AB); -- Finish Quest "Crest of Davoi" Start Quest "Save my Sister" with var, not addquest() end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CrestOfDavoi = player:getQuestStatus(JEUNO,CREST_OF_DAVOI); SaveMySister = player:getQuestStatus(JEUNO,SAVE_MY_SISTER); -- You need to talk to Aldo before you can obtain the Crest of Davoi or Yagudo Torch if(player:hasKeyItem(SILVER_BELL) and CrestOfDavoi == QUEST_AVAILABLE) then player:startEvent(0x00AE); -- Start Quest "Crest of Davoi" elseif(CrestOfDavoi == QUEST_ACCEPTED) then player:startEvent(0x00AF); -- During Quest "Crest of Davoi" elseif(CrestOfDavoi == QUEST_COMPLETED and SaveMySister == QUEST_AVAILABLE and player:getVar("saveMySisterVar") == 1) then player:startEvent(0x00AC); -- During Quest "Save my Sister" (before speak with Mailloquetat) elseif(CrestOfDavoi == QUEST_COMPLETED and player:getVar("saveMySisterVar") == 2) then player:startEvent(0x0069); -- During Quest "Save my Sister" (after speak with Mailloquetat) elseif(SaveMySister == QUEST_ACCEPTED and player:getVar("saveMySisterFireLantern") < 4) then player:startEvent(0x001b); -- During Quest "Save my Sister" (after speak with Neraf-Najiruf) elseif(SaveMySister == QUEST_ACCEPTED and player:getVar("saveMySisterFireLantern") == 4) then player:startEvent(0x006b); -- Ending Quest "Save my Sister" elseif(SaveMySister == QUEST_COMPLETED) then player:startEvent(0x00B0); -- New standard dialog after "Save my Sister" else player:startEvent(0x007a); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x00b1) then --1 player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz2",player:getVar("saveTheClockTowerNPCz2") + 32); elseif(csid == 0x00AE and option == 1) then player:addQuest(JEUNO,CREST_OF_DAVOI); elseif(csid == 0x00AB) then player:tradeComplete(); player:setVar("saveMySisterVar",1); player:addKeyItem(CREST_OF_DAVOI_KI); player:messageSpecial(KEYITEM_OBTAINED,CREST_OF_DAVOI_KI); player:addFame(JEUNO,30); player:completeQuest(JEUNO,CREST_OF_DAVOI); elseif(csid == 0x0069) then player:setVar("saveMySisterVar",3); elseif(csid == 0x006b) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17041); else player:addTitle(EXORCIST_IN_TRAINING); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); player:addItem(17041); player:messageSpecial(ITEM_OBTAINED,17041); player:tradeComplete(); player:addFame(JEUNO,30); player:completeQuest(JEUNO,SAVE_MY_SISTER); end end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/weaponskills/tachi_rana.lua
2
4439
----------------------------------- -- Tachi Rana -- Great Katana weapon skill -- Skill Level: N/A -- Delivers a three-fold attack. params.accuracy varies with TP. Aftermath effect varies with TP. See Kogarasumaru. -- In order to obtain Tachi: Rana, the Unlocking a Myth (Samurai) quest must be completed. -- Will stack with Sneak Attack (first hit only). -- Aligned with the Shadow Gorget, Soil Gorget & Snow Gorget. -- Aligned with the Shadow Belt, Soil Belt & Snow Belt. -- Element: None -- Modifiers: STR:35% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 3; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if((player:getEquipID(SLOT_MAIN) == 19002) and (player:getMainJob() == JOB_SAM)) then if(damage > 0) then -- AFTERMATH LV1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1); -- AFTERMATH LV2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1); -- AFTERMATH LV3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
wizardbottttt/Speed_Bot
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
Fatalerror66/ffxi-a
scripts/globals/spells/foe_requiem_vii.lua
2
1713
----------------------------------------- -- Spell: Foe Requiem VII ----------------------------------------- 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 = 160; local power = 8; local bonus = AffinityBonus(caster, spell:getElement()); 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,bonus); if(resm < 0.5) then spell:setMsg(85);--resist message return 1; end local sItem = caster:getEquipID(2); -- flute +1 if(sItem == 17372) then power = power + 1; end if(sItem == 17844) then power = power + 1; end if(sItem == 17346) then power = power + 2; end if(sItem == 17379) then power = power + 2; end if(sItem == 17362) then power = power + 2; end if(sItem == 17832) then power = power + 3; end if(sItem == 17852) then power = power + 4; end if(sItem == 18342) then power = power + 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
Fatalerror66/ffxi-a
scripts/zones/Toraimarai_Canal/npcs/qm4.lua
2
1644
----------------------------------- -- Area: Toraimarai Canal -- NPC: ??? (BLM AF6 Final ???) -- @zone 169 ----------------------------------- package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Toraimarai_Canal/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(WINDURST,THE_ROOT_OF_THE_PROBLEM) == QUEST_ACCEPTED and player:getVar("windurstTheRootOfTheProblem") == 5) then player:startEvent(0x0030); elseif(player:getQuestStatus(WINDURST,THE_ROOT_OF_THE_PROBLEM) == QUEST_ACCEPTED and player:getVar("windurstTheRootOfTheProblem") == 7) then player:startEvent(0x0037); else player:messageSpecial(11); 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 == 0x0030) then if(option == 1) then SpawnMob(17469516,8832); player:setVar("windurstTheRootOfTheProblem",6) end end end;
gpl-3.0
nenau/naev
dat/missions/pirate/pir_cargo.lua
1
6189
--[[ Handles the randomly generated Pirate cargo missions. Most of the code taken from Empire Shipping. ]]-- include "dat/scripts/cargo_common.lua" include "dat/scripts/numstring.lua" -- This is in cargo_common, but we need to increase the range… function cargo_selectMissionDistance () local seed = rnd.rnd() if seed < 0.20 then missdist = 3 elseif seed < 0.40 then missdist = 4 elseif seed < 0.60 then missdist = 5 elseif seed < 0.80 then missdist = 6 else missdist = 7 end return missdist end osd_title = _("Pirate Shipping") osd_msg = {} osd_msg[1] = _("Fly to %s in the %s system before %s.") osd_msg[2] = _("You have %s remaining.") osd_msg1 = _("Fly to %s in the %s system before %s.") osd_msg2 = _("You have %s remaining.") -- Need to reuse. misn_title = _("Pirate cargo transport (%d tonnes of %s)") misn_desc = _("%d tons of %s needs to be shipped to %s in the %s system by %s (%s left).") misn_reward = _("%s credits") title = {} title_p1 = _("Pirate: Cargo transport to %s in the %s system") title_p2 = _([[ Cargo: %s (%d tonnes) Jumps: %d Travel distance: %d Time limit: %s]]) full = {} full[1] = _("Ship is full") full[2] = _("Your ship is too full. You need to make room for %d more tons if you want to be able to accept the mission.") slow = {} slow[1] = _("Too slow") slow[2] = _([[This shipment must arrive within %s, but it will take at least %s for your ship to reach %s. Accept the mission anyway?]]) msg_title = {} msg_title[1] = _("Mission Accepted") msg_title[2] = _("Too many missions") msg_title[3] = _("Successful Delivery") msg_msg = {} msg_msg[1] = _("%d tons of %s are loaded onto your ship.") msg_msg[2] = _("You have too many active missions.") msg_msg[3] = _("The %s is unloaded at the docks.") msg_msg[4] = _("The %s is passed through the airlock.") miss = {} miss[1]= _("Cargo Missing") miss[2] = _("You are missing the %d tons of %s!.") miss[3] = _("MISSION FAILED: You have failed to deliver the goods on time!") --[[ -- Pirates shipping missions are always timed, but quite lax on the schedules -- and pays a lot more then the rush missions --]] -- Create the mission function create() -- Note: this mission does not make any system claims. origin_p, origin_s = planet.cur() local routesys = origin_s local routepos = origin_p:pos() -- target destination destplanet, destsys, numjumps, traveldist, cargo, tier = cargo_calculateRoute() if destplanet == nil then misn.finish(false) end -- We’re redefining the cargo local cargoes = { "Unmarked Boxes", "Weapons", "Drugs", "Exotic Animals", "Radioactive Materials", } cargo = cargoes[rnd.rnd(1, #cargoes)] -- It is my opinion that those cargos should come from Pirate worlds and be -- destined to any other worlds, for black markets and such. Besides, -- Pirate worlds are too far away from one another. --if destplanet:faction() ~= faction.get( "Pirate" ) then -- misn.finish(false) --end -- mission generics stuperpx = 0.3 - 0.015 * tier stuperjump = 11000 - 75 * tier stupertakeoff = 15000 timelimit = time.get() + time.create(0, 0, traveldist * stuperpx + numjumps * stuperjump + stupertakeoff + 480 * numjumps) -- Allow extra time for refuelling stops. local jumpsperstop = 3 + math.min(tier, 1) if numjumps > jumpsperstop then timelimit:add(time.create( 0, 0, math.floor((numjumps-1) / jumpsperstop) * stuperjump )) end -- Choose amount of cargo and mission reward. This depends on the mission tier. finished_mod = 2.0 -- Modifier that should tend towards 1.0 as naev is finished as a game amount = rnd.rnd(10 + 3 * tier, 20 + 4 * tier) jumpreward = 1500 distreward = 0.30 reward = 1.5^tier * (numjumps * jumpreward + traveldist * distreward) * finished_mod * (1. + 0.05*rnd.twosigma()) misn.setTitle( misn_title:format( amount, cargo ) ) misn.markerAdd(destsys, "computer") misn.setDesc(title_p1:format(destplanet:name(), destsys:name()) .. title_p2:format(cargo, amount, numjumps, traveldist, (timelimit - time.get()):str())) misn.setReward(misn_reward:format(numstring(reward))) end -- Mission is accepted function accept() local playerbest = cargoGetTransit( timelimit, numjumps, traveldist ) if timelimit < playerbest then if not tk.yesno( slow[1], slow[2]:format( (timelimit - time.get()):str(), (playerbest - time.get()):str(), destplanet:name()) ) then misn.finish() end end if player.pilot():cargoFree() < amount then tk.msg( full[1], string.format( full[2], amount-player.pilot():cargoFree() )) misn.finish() end if misn.accept() then -- able to accept the mission, hooks BREAK after accepting carg_id = misn.cargoAdd( cargo, amount ) tk.msg( msg_title[1], string.format( msg_msg[1], amount, cargo )) osd_msg[1] = osd_msg1:format(destplanet:name(), destsys:name(), timelimit:str()) osd_msg[2] = osd_msg2:format((timelimit - time.get()):str()) misn.osdCreate(osd_title, osd_msg) hook.land( "land" ) -- only hook after accepting hook.date(time.create(0, 0, 100), "tick") -- 100STU per tick else tk.msg( msg_title[2], msg_msg [2] ) misn.finish() end end -- Land hook function land() if planet.cur() == destplanet then tk.msg( msg_title[3], string.format( msg_msg[3], cargo )) player.pay(reward) n = var.peek("ps_misn") if n ~= nil then var.push("ps_misn", n+1) else var.push("ps_misn", 1) end -- increase faction faction.modPlayerSingle("Pirate", rnd.rnd(2, 4)) misn.finish(true) end end -- Date hook function tick() if timelimit >= time.get() then -- Case still in time osd_msg[1] = osd_msg1:format(destplanet:name(), destsys:name(), timelimit:str()) osd_msg[2] = osd_msg2:format((timelimit - time.get()):str()) misn.osdCreate(osd_title, osd_msg) elseif timelimit <= time.get() then -- Case missed deadline player.msg(miss[3]) abort() end end function abort () misn.finish(false) end
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/abilities/water_shot.lua
2
2217
----------------------------------- -- Ability: Water Shot ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- OnUseAbility ----------------------------------- function OnAbilityCheck(player,target,ability) --ranged weapon/ammo: You do not have an appropriate ranged weapon equipped. --no card: <name> cannot perform that action. if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then return 216,0; end if (player:hasItem(2181, 0) or player:hasItem(2974, 0)) then return 0,0; else return 71, 0; end end; function OnUseAbility(player, target, ability) local dmg = 2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG); dmg = addBonusesAbility(player, ELE_WATER, target, dmg); dmg = dmg * applyResistanceAbility(player,target,ELE_WATER,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY)); dmg = adjustForTarget(target,dmg,ELE_WATER); dmg = utils.stoneskin(target, dmg); target:delHP(dmg); target:updateEnmityFromDamage(player,dmg); local effects = {}; local counter = 1; local drown = target:getStatusEffect(EFFECT_DROWN); if (drown ~= nil) then effects[counter] = drown; counter = counter + 1; end local threnody = target:getStatusEffect(EFFECT_THRENODY); if (threnody ~= nil and threnody:getSubPower() == MOD_FIRERES) then effects[counter] = threnody; counter = counter + 1; end if counter > 1 then local effect = effects[math.random(1, counter-1)]; local duration = effect:getDuration(); local startTime = effect:getStartTime(); local tick = effect:getTick(); local power = effect:getPower(); local subpower = effect:getSubPower(); local tier = effect:getTier(); local effectId = effect:getType(); local subId = effect:getSubType(); power = power * 1.2; target:delStatusEffectSilent(effectId); target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier); local newEffect = target:getStatusEffect(effectId); newEffect:setStartTime(startTime); end return dmg; end;
gpl-3.0
brendangregg/bcc
src/lua/bcc/run.lua
9
2190
--[[ Copyright 2016 GitHub, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] return function() require("bcc.vendor.helpers") local standalone = rawget(_G, "BCC_STANDALONE") local progname = standalone or "bcc-probe" local function print_usage() io.stderr:write(string.format( "usage: %s [[--version|--verbose] --] path_to_script.lua [...]\n", progname)) os.exit(1) end local function print_version() local jit = require("jit") print(string.format("%s %s -- Running on %s (%s/%s)", progname, rawget(_G, "BCC_VERSION") or "HEAD", jit.version, jit.os, jit.arch)) os.exit(0) end while arg[1] and string.starts(arg[1], "-") do local k = table.remove(arg, 1) if k == "--" then break elseif standalone == nil and string.starts(k, "--so-path=") then rawset(_G, "LIBBCC_SO_PATH", string.lstrip(k, "--so-path=")) elseif k == "--llvm-debug" then rawset(_G, "LIBBCC_LLVM_DEBUG", 1) elseif k == "-V" or k == "--verbose" then log.enabled = true elseif k == "-v" or k == "--version" then print_version() else print_usage() end end local tracefile = table.remove(arg, 1) if not tracefile then print_usage() end local BPF = require("bcc.bpf") BPF.script_root(tracefile) local USDT = require("bcc.usdt") local utils = { argparse = require("bcc.vendor.argparse"), posix = require("bcc.vendor.posix"), USDT = USDT, } local command = dofile(tracefile) local res, err = xpcall(command, debug.traceback, BPF, utils) if not res and err ~= "interrupted!" then io.stderr:write("[ERROR] "..err.."\n") end BPF.cleanup() USDT.cleanup() return res, err end
apache-2.0