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
LipkeGu/OpenRA
mods/d2k/bits/scripts/campaign-global.lua
1
5899
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] Difficulty = Map.LobbyOption("difficulty") IdleHunt = function(actor) if actor.HasProperty("Hunt") and not actor.IsDead then Trigger.OnIdle(actor, actor.Hunt) end end InitObjectives = function(player) Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Lose") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Win") end) end) end SendCarryallReinforcements = function(player, currentWave, totalWaves, delay, pathFunction, unitTypes, customCondition, customHuntFunction) Trigger.AfterDelay(delay, function() if customCondition and customCondition() then return end currentWave = currentWave + 1 if currentWave > totalWaves then return end local path = pathFunction() local units = Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", unitTypes[currentWave], path, { path[1] })[2] if not customHuntFunction then customHuntFunction = IdleHunt end Utils.Do(units, customHuntFunction) SendCarryallReinforcements(player, currentWave, totalWaves, delay, pathFunction, unitTypes, customCondition, customHuntFunction) end) end TriggerCarryallReinforcements = function(triggeringPlayer, reinforcingPlayer, area, unitTypes, path, customCondition) local fired = false Trigger.OnEnteredFootprint(area, function(a, id) if customCondition and customCondition() then return end if not fired and a.Owner == triggeringPlayer and a.Type ~= "carryall" then fired = true Trigger.RemoveFootprintTrigger(id) local units = Reinforcements.ReinforceWithTransport(reinforcingPlayer, "carryall.reinforce", unitTypes, path, { path[1] })[2] Utils.Do(units, IdleHunt) end end) end -- Used for the AI: IdlingUnits = { } Attacking = { } HoldProduction = { } LastHarvesterEaten = { } SetupAttackGroup = function(owner, size) local units = { } for i = 0, size, 1 do if #IdlingUnits[owner] == 0 then return units end local number = Utils.RandomInteger(1, #IdlingUnits[owner] + 1) if IdlingUnits[owner][number] and not IdlingUnits[owner][number].IsDead then units[i] = IdlingUnits[owner][number] table.remove(IdlingUnits[owner], number) end end return units end SendAttack = function(owner, size) if Attacking[owner] then return end Attacking[owner] = true HoldProduction[owner] = true local units = SetupAttackGroup(owner, size) Utils.Do(units, IdleHunt) Trigger.OnAllRemovedFromWorld(units, function() Attacking[owner] = false HoldProduction[owner] = false end) end DefendActor = function(unit, defendingPlayer, defenderCount) Trigger.OnDamaged(unit, function(self, attacker) -- Don't try to attack spiceblooms if attacker and attacker.Type == "spicebloom" then return end if Attacking[defendingPlayer] then return end Attacking[defendingPlayer] = true local Guards = SetupAttackGroup(defendingPlayer, defenderCount) if #Guards <= 0 then Attacking[defendingPlayer] = false return end Utils.Do(Guards, function(unit) if not self.IsDead then unit.AttackMove(self.Location) end IdleHunt(unit) end) Trigger.OnAllRemovedFromWorld(Guards, function() Attacking[defendingPlayer] = false end) end) end ProtectHarvester = function(unit, owner, defenderCount) DefendActor(unit, owner, defenderCount) -- Worms don't kill the actor, but dispose it instead. -- If a worm kills the last harvester (hence we check for remaining ones), -- a new harvester is delivered by the harvester insurance. -- Otherwise, there's no need to check for new harvesters. local killed = false Trigger.OnKilled(unit, function() killed = true end) Trigger.OnRemovedFromWorld(unit, function() if not killed and #unit.Owner.GetActorsByType("harvester") == 0 then LastHarvesterEaten[owner] = true end end) end RepairBuilding = function(owner, actor, modifier) Trigger.OnDamaged(actor, function(building) if building.Owner == owner and building.Health < building.MaxHealth * modifier then building.StartBuildingRepairs() end end) end DefendAndRepairBase = function(owner, baseBuildings, modifier, defenderCount) Utils.Do(baseBuildings, function(actor) if actor.IsDead then return end DefendActor(actor, owner, defenderCount) RepairBuilding(owner, actor, modifier) end) end ProduceUnits = function(player, factory, delay, toBuild, attackSize, attackThresholdSize) if factory.IsDead or factory.Owner ~= player then return end if HoldProduction[player] then Trigger.AfterDelay(DateTime.Minutes(1), function() ProduceUnits(player, factory, delay, toBuild, attackSize, attackThresholdSize) end) return end player.Build(toBuild(), function(unit) IdlingUnits[player][#IdlingUnits[player] + 1] = unit[1] Trigger.AfterDelay(delay(), function() ProduceUnits(player, factory, delay, toBuild, attackSize, attackThresholdSize) end) if #IdlingUnits[player] >= attackThresholdSize then SendAttack(player, attackSize) end end) end
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/mobskills/Gate_of_Tartarus.lua
10
1071
--------------------------------------------- -- Gate of Tartarus -- -- Description: Lowers target's attack. Additional effect: Refresh -- Type: Physical -- Shadow per hit -- Range: Melee --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function OnMobSkillCheck(target,mob,skill) return 0; end; function OnMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20; if(mob:getTP() == 300) then duration = 60; elseif(mob:getTP() >= 200) then duration = 40; end MobBuffMove(mob, EFFECT_REFRESH, 8, 3, duration); MobStatusEffectMove(mob, target, EFFECT_ATTACK_DOWN, 20, 0, duration); target:delHP(dmg); return dmg; end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Mamook/npcs/qm2.lua
15
1163
----------------------------------- -- Area: Mamook -- NPC: ??? (Spawn Iriri Samariri(ZNM T2)) -- @pos -118 7 -80 65 ----------------------------------- package.loaded["scripts/zones/Mamook/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mamook/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(2579,1) and trade:getItemCount() == 1) then -- Trade Samariri Corpsehair player:tradeComplete(); SpawnMob(17043888,180):updateEnmity(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); 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
tltneon/nsplugins
plugins/talknpc/entities/entities/nut_talker.lua
2
4412
ENT.Type = "anim" ENT.PrintName = "Talker" ENT.Category = "NutScript" ENT.Spawnable = true ENT.AdminOnly = true function ENT:Initialize() if (SERVER) then self:SetModel("models/mossman.mdl") self:SetUseType(SIMPLE_USE) self:SetMoveType(MOVETYPE_NONE) self:DrawShadow(true) self:SetSolid(SOLID_BBOX) self:PhysicsInit(SOLID_BBOX) self.messages = {} self.factions = {} self.classes = {} self:setNetVar("name", "John Doe") self:setNetVar("desc", "") self.receivers = {} local physObj = self:GetPhysicsObject() if (IsValid(physObj)) then physObj:EnableMotion(false) physObj:Sleep() end end timer.Simple(1, function() if (IsValid(self)) then self:setAnim() end end) end function ENT:canAccess(client) if (client:IsAdmin()) then return true end local allowed = false local uniqueID = nut.faction.indices[client:Team()].uniqueID if (self.factions and table.Count(self.factions) > 0) then if (self.factions[uniqueID]) then allowed = true else return false end end if (allowed and self.classes and table.Count(self.classes) > 0) then local class = nut.class.list[client:getChar():getClass()] local uniqueID = class and class.uniqueID if (!self.classes[uniqueID]) then return false end end return true end function ENT:setAnim() for k, v in ipairs(self:GetSequenceList()) do if (v:lower():find("idle") and v != "idlenoise") then return self:ResetSequence(k) end end self:ResetSequence(4) end if (CLIENT) then function ENT:CreateBubble() self.bubble = ClientsideModel("models/extras/info_speech.mdl", RENDERGROUP_OPAQUE) self.bubble:SetPos(self:GetPos() + Vector(0, 0, 84)) self.bubble:SetModelScale(0.6, 0) end function ENT:Think() if (!IsValid(self.bubble)) then self:CreateBubble() end self:SetEyeTarget(LocalPlayer():GetPos()) end function ENT:Draw() local bubble = self.bubble if (IsValid(bubble)) then local realTime = RealTime() bubble:SetAngles(Angle(0, realTime * 120, 0)) bubble:SetRenderOrigin(self:GetPos() + Vector(0, 0, 84 + math.sin(realTime * 3) * 0.03)) end self:DrawModel() end function ENT:OnRemove() if (IsValid(self.bubble)) then self.bubble:Remove() end end netstream.Hook("nut_Dialogue", function(data) if (IsValid(nut.gui.dialogue)) then nut.gui.dialogue:Remove() return end nut.gui.dialogue = vgui.Create("Nut_Dialogue") nut.gui.dialogue:Center() nut.gui.dialogue:SetEntity(data) if LocalPlayer():IsAdmin() then if (IsValid(nut.gui.edialogue)) then nut.gui.dialogue:Remove() return end nut.gui.edialogue = vgui.Create("Nut_DialogueEditor") --nut.gui.edialogue:Center() nut.gui.edialogue:SetEntity(data) end end) local TEXT_OFFSET = Vector(0, 0, 20) local toScreen = FindMetaTable("Vector").ToScreen local colorAlpha = ColorAlpha local drawText = nut.util.drawText local configGet = nut.config.get ENT.DrawEntityInfo = true function ENT:onDrawEntityInfo(alpha) local position = toScreen(self.LocalToWorld(self, self.OBBCenter(self)) + TEXT_OFFSET) local x, y = position.x, position.y local desc = self.getNetVar(self, "desc") drawText(self.getNetVar(self, "name", "John Doe"), x, y, colorAlpha(configGet("color"), alpha), 1, 1, nil, alpha * 0.65) if (desc) then drawText(desc, x, y + 16, colorAlpha(color_white, alpha), 1, 1, "nutSmallFont", alpha * 0.65) end end else function ENT:Use(activator) local factionData = self:getNetVar("factiondata", {}) if !factionData[nut.faction.indices[activator:Team()].uniqueID] and !activator:IsSuperAdmin() then activator:ChatPrint( self:getNetVar( "name", "John Doe" )..": I don't want talk with you." ) return end netstream.Start(activator, "nut_Dialogue", self) end netstream.Hook("nut_DialogueData", function( client, data ) if (!client:IsSuperAdmin()) then return end local entity = data[1] local dialogue = data[2] local factionData = data[3] local classData = data[4] local name = data[5] local desc = data[6] local model = data[7] if (IsValid(entity)) then entity:setNetVar("dialogue", dialogue) entity:setNetVar("factiondata", factionData) entity:setNetVar("classdata", classData) entity:setNetVar("name", name) entity:setNetVar("desc", desc) entity:SetModel(model) entity:setAnim() client:notify("You have updated this talking npc's data.") end end) end
gpl-2.0
kidaa/FFXIOrgins
scripts/zones/Beadeaux/npcs/_43b.lua
2
1672
----------------------------------- -- Area: Beadeaux -- NPC: Jail Door -- Involved in Quests: The Rescue -- @pos 56 0.1 -23 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Beadeaux/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(OTHER_AREAS,THE_RESCUE) == QUEST_ACCEPTED and player:hasKeyItem(TRADERS_SACK) == false) then if(trade:hasItemQty(495,1) == true and trade:getItemCount() == 1) then player:startEvent(0x03e8); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(OTHER_AREAS,THE_RESCUE) == QUEST_ACCEPTED and player:hasKeyItem(TRADERS_SACK) == false) then player:messageSpecial(LOCKED_DOOR_QUADAV_HAS_KEY); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 0x03e8) then player:addKeyItem(TRADERS_SACK); player:messageSpecial(KEYITEM_OBTAINED,TRADERS_SACK); end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Temple_of_Uggalepih/npcs/_4fx.lua
2
1816
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Granite Door -- @pos 340 0.1 329 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(1143,1) and trade:getItemCount() == 1 and player:getZPos() < 332) then -- Trade cursed key if(player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 4) then player:startEvent(0x0019); else player:messageSpecial(NOTHING_HAPPENS); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getZPos() < 332) then player:messageSpecial(DOOR_LOCKED); else player:startEvent(0x001a); 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 == 0x0017) then player:tradeComplete(); player:messageSpecial(YOUR_KEY_BREAKS,0,1143); player:delKeyItem(BLANK_BOOK_OF_THE_GODS); player:addKeyItem(BOOK_OF_THE_GODS); player:messageSpecial(KEYITEM_OBTAINED,BOOK_OF_THE_GODS); player:setVar("MissionStatus",5); elseif(csid == 0x0019) then player:startEvent(0x0017); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/abilities/pets/water_iv.lua
6
1159
--------------------------------------------------- -- Aero 2 --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/magic"); --------------------------------------------------- function OnAbilityCheck(player, target, ability) return 0,0; end; function OnPetAbility(target, pet, skill) local spell = getSpell(172); --calculate raw damage local dmg = calculateMagicDamage(410,2,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,ELE_WATER); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = mobAddBonuses(pet,spell,target,dmg, 3); --add on TP bonuses local tp = pet:getTP(); if tp < 100 then tp = 100; end dmg = dmg * tp / 100; --add in final adjustments dmg = finalMagicAdjustments(pet,target,spell,dmg); return dmg; end
gpl-3.0
brendangregg/bcc
tools/biosnoop.lua
3
5032
#!/usr/bin/env bcc-lua --[[ 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. --]] local program = [[ #include <uapi/linux/ptrace.h> #include <linux/blkdev.h> struct val_t { u32 pid; char name[TASK_COMM_LEN]; }; struct data_t { u32 pid; u64 rwflag; u64 delta; u64 sector; u64 len; u64 ts; char disk_name[DISK_NAME_LEN]; char name[TASK_COMM_LEN]; }; BPF_HASH(start, struct request *); BPF_HASH(infobyreq, struct request *, struct val_t); BPF_PERF_OUTPUT(events); // cache PID and comm by-req int trace_pid_start(struct pt_regs *ctx, struct request *req) { struct val_t val = {}; if (bpf_get_current_comm(&val.name, sizeof(val.name)) == 0) { val.pid = bpf_get_current_pid_tgid(); infobyreq.update(&req, &val); } return 0; } // time block I/O int trace_req_start(struct pt_regs *ctx, struct request *req) { u64 ts; ts = bpf_ktime_get_ns(); start.update(&req, &ts); return 0; } // output int trace_req_completion(struct pt_regs *ctx, struct request *req) { u64 *tsp, delta; u32 *pidp = 0; struct val_t *valp; struct data_t data ={}; u64 ts; // fetch timestamp and calculate delta tsp = start.lookup(&req); if (tsp == 0) { // missed tracing issue return 0; } ts = bpf_ktime_get_ns(); data.delta = ts - *tsp; data.ts = ts / 1000; valp = infobyreq.lookup(&req); if (valp == 0) { data.len = req->__data_len; data.name[0] = '?'; data.name[1] = 0; } else { data.pid = valp->pid; data.len = req->__data_len; data.sector = req->__sector; bpf_probe_read_kernel(&data.name, sizeof(data.name), valp->name); bpf_probe_read_kernel(&data.disk_name, sizeof(data.disk_name), req->rq_disk->disk_name); } /* * The following deals with a kernel version change (in mainline 4.7, although * it may be backported to earlier kernels) with how block request write flags * are tested. We handle both pre- and post-change versions here. Please avoid * kernel version tests like this as much as possible: they inflate the code, * test, and maintenance burden. */ #ifdef REQ_WRITE data.rwflag = !!(req->cmd_flags & REQ_WRITE); #elif defined(REQ_OP_SHIFT) data.rwflag = !!((req->cmd_flags >> REQ_OP_SHIFT) == REQ_OP_WRITE); #else data.rwflag = !!((req->cmd_flags & REQ_OP_MASK) == REQ_OP_WRITE); #endif events.perf_submit(ctx,&data,sizeof(data)); start.delete(&req); infobyreq.delete(&req); return 0; } ]] local ffi = require("ffi") return function(BPF, utils) local bpf = BPF:new{text=program} bpf:attach_kprobe{event="blk_account_io_start", fn_name="trace_pid_start"} bpf:attach_kprobe{event="blk_start_request", fn_name="trace_req_start"} bpf:attach_kprobe{event="blk_mq_start_request", fn_name="trace_req_start"} bpf:attach_kprobe{event="blk_account_io_done", fn_name="trace_req_completion"} print("%-14s %-14s %-6s %-7s %-2s %-9s %-7s %7s" % {"TIME(s)", "COMM", "PID", "DISK", "T", "SECTOR", "BYTES", "LAT(ms)"}) local rwflg = "" local start_ts = 0 local prev_ts = 0 local delta = 0 local function print_event(cpu, event) local val = -1 local event_pid = event.pid local event_delta = tonumber(event.delta) local event_sector = tonumber(event.sector) local event_len = tonumber(event.len) local event_ts = tonumber(event.ts) local event_disk_name = ffi.string(event.disk_name) local event_name = ffi.string(event.name) if event.rwflag == 1 then rwflg = "W" end if event.rwflag == 0 then rwflg = "R" end if not event_name:match("%?") then val = event_sector end if start_ts == 0 then prev_ts = start_ts end if start_ts == 1 then delta = delta + (event_ts - prev_ts) end print("%-14.9f %-14.14s %-6s %-7s %-2s %-9s %-7s %7.2f" % { delta / 1000000, event_name, event_pid, event_disk_name, rwflg, val, event_len, event_delta / 1000000}) prev_ts = event_ts start_ts = 1 end local TASK_COMM_LEN = 16 -- linux/sched.h local DISK_NAME_LEN = 32 -- linux/genhd.h bpf:get_table("events"):open_perf_buffer(print_event, [[ struct { uint32_t pid; uint64_t rwflag; uint64_t delta; uint64_t sector; uint64_t len; uint64_t ts; char disk_name[$]; char name[$]; } ]], {DISK_NAME_LEN, TASK_COMM_LEN}, 64) bpf:perf_buffer_poll_loop() end
apache-2.0
newenclave/ferro-remote
lua-client/examples/grove-rgb-lcd.lua
1
2180
i2c = fr.client.smbus eq = fr.client.event_queue eqt = eq.timer grove_lcd_rgb = { RGB_ADDR = 0x62, TXT_ADDR = 0x3E } grove_lcd_rgb.new = function( ) inst = { } for k, v in pairs(grove_lcd_rgb) do inst[k] = v end inst.txt = assert(i2c.open( 1, grove_lcd_rgb.TXT_ADDR )) inst.rgb = assert(i2c.open( 1, grove_lcd_rgb.RGB_ADDR )) setmetatable( inst, grove_lcd_rgb ) return inst end grove_lcd_rgb.set_color = function( self, R, G, B ) assert(self.rgb:write_bytes( { [0]=0, [1]=0, [0x8]=0xAA, [4]=R, [3]=G, [2]=B })) end grove_lcd_rgb.clr = function( self ) assert(self.txt:write_bytes({[0x80] = 0x01})) end grove_lcd_rgb.control = function( self, byte ) assert(self.txt:write_bytes( {[0x80] = byte} )) end grove_lcd_rgb.write = function( self, txt ) local send_txt_cmd = function( byte ) self:control( byte ) end local send_txt = function( byte ) assert(self.txt:write_bytes( {[0x40] = byte} )) end send_txt_cmd( 0x01 ) send_txt_cmd( 0x08 | 0x04 ) send_txt_cmd( 0x28 ) for i = 1, string.len(txt) do local b = string.byte( txt, i ) if b == 0x0A then send_txt_cmd( 0xC0 ) else send_txt( b ) end end end function next_char( err, b, dev ) dev:clr( ) dev.txt:write_bytes( {[0x40] = b} ) if b > 0 then eqt.post( next_char, {milli=500}, b - 1, dev ) else next_char( nil, 255, dev ) end end function set_color( err, R, G, B, dev ) dev:set_color( R, G, B ) local changed = false if R > 0 then R = R - 1 changed = true elseif B > 0 then B = B - 1 changed = true elseif R > 0 then R = R - 1 changed = true end if changed then eqt.post( set_color, {milli=10}, R, G, B, dev ) else eqt.post( set_color, {milli=10}, 255, 255, 255, dev ) end end function main( ) fr.run( ) local i = grove_lcd_rgb.new( ) i:set_color( 0, 0, 0 ) i:write( "Hola\nAdelante" ) -- eqt.post( function( err, i ) -- i:set_color( 0, 0, 0 ) -- i:clr( ) -- fr.exit( ) -- end, -- {sec=5}, i ) -- next_char( nil, 255, i ) set_color( nil, 255, 255, 255, i ) end
gpl-3.0
SlySven/Mudlet
translations/translated/generate-translation-stats.lua
3
5910
-- Convert output from runs of Qt lrelease for each language into statistics --[[ ############################################################################ # Copyright (C) 2018-2019, 2022 by Vadim Peretokin - vperetokin@hey.com # # Copyright (C) 2018 by Florian Scheel - keneanung@googlemail.com # # Copyright (C) 2019-2020 by Stephen Lyons - slysven@virginmedia.com # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the # # Free Software Foundation, Inc., # # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################ ]] local status, result = pcall(require, 'yajl') if not status then print("warning: lua-yajl not available - translation statistics in settings won't be shown.\nError loading yajl was: ".. result) io.output("translation-stats.json") io.write("{}") return end local github_workspace = os.getenv("GITHUB_WORKSPACE") if github_workspace then -- the script struggles to load the load files relatively in CI loadfile(github_workspace.."/src/mudlet-lua/lua/TableUtils.lua")() else loadfile("../../src/mudlet-lua/lua/TableUtils.lua")() end local yajl = result -- see if the file exists function file_exists(file) local f = io.open(file, "rb") if f then f:close() end return f ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then return {} end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- tests the functions above local file = 'lrelease_output.txt' local lines = lines_from(file) local line = 1 local stats, keyvaluestats, statsindex = {}, {}, {} while line <= #lines do local currentLine = lines[line] local lang = currentLine:match("Updating '.*mudlet_([a-z]+_[A-Z]+)%.qm'...") line = line + 1 if lang then local translated = 0 local finished = 0 local unfinished = 0 repeat currentLine = lines[line] translated, finished, unfinished = currentLine:match("Generated (%d+) translation%(s%) %((%d+) finished and (%d+) unfinished%)") if translated ~= nil and finished ~= nil and unfinished ~= nil then translated = tonumber(translated) finished = tonumber(finished) unfinished = tonumber(unfinished) end line = line + 1 until translated ~= nil currentLine = lines[line] local untranslated = 0 if currentLine ~= nil then -- The untranslated line will not be present if translation is at 100%! untranslated = currentLine:match("Ignored (%d+) untranslated source text%(s%)") if untranslated ~= nil then untranslated = tonumber(untranslated) -- There IS an "Ignored..." line so increment the line counter past it, line = line + 1 else -- reset from the nil returned value to 0 (as that how many untranslated -- source text there are!) end -- Otherwise leave it unchanged for the next time around the outer loop end stats[#stats + 1] = { lang = lang, translated = translated, untranslated = untranslated or 0, finished = finished, unfinished = unfinished, total = translated + (untranslated or 0), translated_fraction = (100 * translated)/(translated + (untranslated or 0)) } stats[#stats].translated_percent = math.floor(stats[#stats].translated_fraction) keyvaluestats[lang] = { translated = stats[#stats].translated, untranslated = stats[#stats].untranslated, finished = stats[#stats].finished, unfinished = stats[#stats].unfinished, total = stats[#stats].total, translated_fraction = stats[#stats].translated_fraction, translated_percent = stats[#stats].translated_percent } statsindex[lang] = keyvaluestats[lang].translated_fraction end end print() print("We have statistics for " .. #stats .. " languages:") print() print(" lang_CNTRY trnsl utrnsl finish unfin total done") for lang, _ in spairs(statsindex, function(t,a,b) return t[a] > t[b] end) do local star = ' ' if keyvaluestats[lang].translated_percent > 94 then star = '*' end print(string.format("%1s %-10s %5d %5d %5d %5d %5d %3d%%", star, lang, keyvaluestats[lang].translated, keyvaluestats[lang].untranslated, keyvaluestats[lang].finished, keyvaluestats[lang].unfinished, keyvaluestats[lang].total, keyvaluestats[lang].translated_percent)) end print() serialise_stats = {} for _, stat in ipairs(stats) do serialise_stats[stat.lang] = { translated = stat.translated, untranslated = stat.untranslated, total = stat.total, translated_percent = stat.translated_percent } end io.output("translation-stats.json") io.write(yajl.to_string(serialise_stats))
gpl-2.0
kidaa/FFXIOrgins
scripts/zones/Abyssea-Uleguerand/Zone.lua
33
1487
----------------------------------- -- -- Zone: Abyssea - Uleguerand -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Uleguerand/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Uleguerand/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(-238, -40, -520.5, 0); 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
yanarsin/new1
plugins/banhammer.lua
2
12021
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "حذف" then if member_id == from_id then return send_large_msg(receiver, "شما نمیتوانید خود را حذف کنید") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "شما نمیتواند این فرد را حذف کنید") end return kick_user(member_id, chat_id) elseif get_cmd == 'بن' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "شما نمیتوانید این فرد را بن کنید") end send_large_msg(receiver, 'کاربر @'..member..' ['..member_id..'] بن شد') return ban_user(member_id, chat_id) elseif get_cmd == 'حذف بن' then send_large_msg(receiver, 'کاربر @'..member..' ['..member_id..'] آن بن شد') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'کاربر '..user_id..' آن بن شد' elseif get_cmd == 'سوپر بن' then send_large_msg(receiver, 'کاربر @'..member..' ['..member_id..'] از همه گروه ها بن شد') return banall_user(member_id, chat_id) elseif get_cmd == 'حذف سوپر بن' then send_large_msg(receiver, 'کاربر @'..member..' ['..member_id..'] از سوپر بن خارج شد') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'آیدی' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'ایدی' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "آیدی گروه " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'خروج' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] با استفاده از خروج خارج شوید ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "لیست بن" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'بن' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "شما نمیتوانید این فرد را بن کنید" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "شما نمیتوانید خود را بن کنید" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'بن', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'حذف بن' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'کاربر '..user_id..' آن بن شد' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'حذف بن', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'حذف' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "شما نمیتوانید این فرد را حذف کنید" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "شما نمیتوانید خود را حذف کنید" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'حذف', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'سوپر بن' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'کاربر ['..user_id..' ] از همه گروه ها بن شد' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'سوپر بن', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'حذف سوپر بن' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'کاربر ['..user_id..' ] از سوپر بن خارج شد' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'حذف سوپر بن', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "لیست سوپر بن" then -- Global ban list return banall_list() end end return { patterns = { "^(سوپر بن) (.*)$", "^(سوپر بن)$", "^(لیست بن) (.*)$", "^(لیست بن)$", "^(لیست سوپر بن)$", "^(بن) (.*)$", "^(اخراج)$", "^(حذف بن) (.*)$", "^(حذف سوپر بن) (.*)$", "^(حذف سوپر بن)$", "^(حذف) (.*)$", "^(خروج)$", "^(بن)$", "^(حذف بن)$", "^(ایدی)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
jiang42/Algorithm-Implementations
Derivative/Lua/Yonaba/derivative_test.lua
26
1356
-- Tests for derivative.lua local drv = require 'derivative' 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 local function fuzzyEqual(a, b, eps) local eps = eps or 1e-4 return (math.abs(a - b) < eps) end run('Testing left derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.left(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.left(f, 5), 3 * 5 * 5)) end) run('Testing right derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.right(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.right(f, 5), 3 * 5 * 5)) end) run('Testing mid derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.mid(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.mid(f, 5), 3 * 5 * 5)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
MOSAVI17/Security1
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
Puccio7/bot-telegram
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
apache-2.0
Fatalerror66/ffxi-a
scripts/zones/Middle_Delkfutts_Tower/npcs/qm1.lua
2
1568
----------------------------------- -- Area: Middle Delfutt's Tower -- NPC: ??? -- Involved In Quest: Blade of Evil -- @zone 157 -- @pos 84 -79 77 ----------------------------------- package.loaded["scripts/zones/Middle_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Middle_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(BASTOK,BLADE_OF_EVIL) == QUEST_ACCEPTED and player:getVar("bladeOfEvilCS") == 0) then if(trade:hasItemQty(1114,1) and trade:getItemCount() == 1) then -- Trade Quadav Mage Blood player:tradeComplete(); SpawnMob(17420629,300):updateEnmity(player); SpawnMob(17420630,180):updateEnmity(player); SpawnMob(17420631,180):updateEnmity(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
flyzjhz/openwrt-bb
feeds/luci/modules/freifunk/luasrc/model/cbi/freifunk/profile.lua
56
2755
--[[ LuCI - Lua Configuration Interface Copyright 2011-2012 Manuel Munz <freifunk at somakoma dot de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at httc://www.apache.org/licenses/LICENSE-2.0 ]]-- local uci = require "luci.model.uci".cursor() local ipkg = require "luci.model.ipkg" local community = uci:get("freifunk", "community", "name") if community == nil then luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "profile_error")) return else community = "profile_" .. community m = Map(community, translate("Community settings"), translate("These are the settings of your local community.")) c = m:section(NamedSection, "profile", "community") local name = c:option(Value, "name", "Name") name.rmempty = false local homepage = c:option(Value, "homepage", translate("Homepage")) local cc = c:option(Value, "country", translate("Country code")) function cc.cfgvalue(self, section) return uci:get(community, "wifi_device", "country") end function cc.write(self, sec, value) if value then uci:set(community, "wifi_device", "country", value) uci:save(community) end end local ssid = c:option(Value, "ssid", translate("ESSID")) ssid.rmempty = false local prefix = c:option(Value, "mesh_network", translate("Mesh prefix")) prefix.datatype = "ip4addr" prefix.rmempty = false local splash_net = c:option(Value, "splash_network", translate("Network for client DHCP addresses")) splash_net.datatype = "ip4addr" splash_net.rmempty = false local splash_prefix = c:option(Value, "splash_prefix", translate("Client network size")) splash_prefix.datatype = "range(0,32)" splash_prefix.rmempty = false local ipv6 = c:option(Flag, "ipv6", translate("Enable IPv6")) ipv6.rmempty = true local ipv6_config = c:option(ListValue, "ipv6_config", translate("IPv6 Config")) ipv6_config:depends("ipv6", 1) ipv6_config:value("static") if ipkg.installed ("auto-ipv6-ib") then ipv6_config:value("auto-ipv6-random") ipv6_config:value("auto-ipv6-fromv4") end ipv6_config.rmempty = true local ipv6_prefix = c:option(Value, "ipv6_prefix", translate("IPv6 Prefix"), translate("IPv6 network in CIDR notation.")) ipv6_prefix:depends("ipv6", 1) ipv6_prefix.datatype = "ip6addr" ipv6_prefix.rmempty = true local vap = c:option(Flag, "vap", translate("VAP"), translate("Enable a virtual access point (VAP) by default if possible.")) vap.rmempty = true local lat = c:option(Value, "latitude", translate("Latitude")) lat.datatype = "range(-180, 180)" lat.rmempty = false local lon = c:option(Value, "longitude", translate("Longitude")) lon.rmempty = false return m end
gpl-2.0
AntonioModer/Moses
moses_min.lua
6
17706
local daa='1.4.0'local _ba,aba,bba,cba,dba=next,type,unpack,select,pcall local _ca,aca=setmetatable,getmetatable;local bca,cca=table.insert,table.sort;local dca,_da=table.remove,table.concat local ada,bda,cda=math.randomseed,math.random,math.huge;local dda,__b,a_b=math.floor,math.max,math.min;local b_b=rawget;local c_b=bba local d_b,_ab=pairs,ipairs;local aab={}local function bab(bcb,ccb)return bcb>ccb end local function cab(bcb,ccb)return bcb<ccb end;local function dab(bcb,ccb,dcb) return(bcb<ccb)and ccb or(bcb>dcb and dcb or bcb)end local function _bb(bcb,ccb)return ccb and true end;local function abb(bcb)return not bcb end;local function bbb(bcb)local ccb=0 for dcb,_db in d_b(bcb)do ccb=ccb+1 end;return ccb end local function cbb(bcb,ccb,dcb,...)local _db local adb=dcb or aab.identity;for bdb,cdb in d_b(bcb)do if not _db then _db=adb(cdb,...)else local ddb=adb(cdb,...)_db= ccb(_db,ddb)and _db or ddb end end;return _db end local function dbb(bcb,ccb,dcb)for i=0,#bcb,ccb do local _db=aab.slice(bcb,i+1,i+ccb) if#_db>0 then dcb(_db)end end end local function _cb(bcb,ccb,dcb)if ccb==0 then dcb(bcb)end for i=1,ccb do bcb[ccb],bcb[i]=bcb[i],bcb[ccb]_cb(bcb,ccb- 1,dcb)bcb[ccb],bcb[i]=bcb[i],bcb[ccb]end end;local acb=-1 function aab.each(bcb,ccb,...)for dcb,_db in d_b(bcb)do ccb(dcb,_db,...)end end function aab.eachi(bcb,ccb,...) local dcb=aab.sort(aab.select(aab.keys(bcb),function(_db,adb)return aab.isInteger(adb)end))for _db,adb in _ab(dcb)do ccb(adb,bcb[adb],...)end end function aab.at(bcb,...)local ccb={}for dcb,_db in _ab({...})do if aab.has(bcb,_db)then ccb[#ccb+1]=bcb[_db]end end;return ccb end function aab.count(bcb,ccb)if aab.isNil(ccb)then return aab.size(bcb)end;local dcb=0 aab.each(bcb,function(_db,adb)if aab.isEqual(adb,ccb)then dcb=dcb+1 end end)return dcb end function aab.countf(bcb,ccb,...)return aab.count(aab.map(bcb,ccb,...),true)end function aab.cycle(bcb,ccb)ccb=ccb or 1;if ccb<=0 then return function()end end;local dcb,_db;local adb=0 while true do return function()dcb= dcb and _ba(bcb,dcb)or _ba(bcb)_db= not _db and dcb or _db;if ccb then adb=(dcb==_db)and adb+1 or adb;if adb>ccb then return end end return dcb,bcb[dcb]end end end;function aab.map(bcb,ccb,...)local dcb={} for _db,adb in d_b(bcb)do dcb[_db]=ccb(_db,adb,...)end;return dcb end;function aab.reduce(bcb,ccb,dcb) for _db,adb in d_b(bcb)do if dcb==nil then dcb=adb else dcb=ccb(dcb,adb)end end;return dcb end;function aab.reduceRight(bcb,ccb,dcb)return aab.reduce(aab.reverse(bcb),ccb,dcb)end function aab.mapReduce(bcb,ccb,dcb) local _db={}for adb,bdb in d_b(bcb)do _db[adb]=not dcb and bdb or ccb(dcb,bdb) dcb=_db[adb]end;return _db end;function aab.mapReduceRight(bcb,ccb,dcb) return aab.mapReduce(aab.reverse(bcb),ccb,dcb)end function aab.include(bcb,ccb)local dcb= aab.isFunction(ccb)and ccb or aab.isEqual;for _db,adb in d_b(bcb)do if dcb(adb,ccb)then return true end end;return false end function aab.detect(bcb,ccb) local dcb=aab.isFunction(ccb)and ccb or aab.isEqual;for _db,adb in d_b(bcb)do if dcb(adb,ccb)then return _db end end end function aab.contains(bcb,ccb)return aab.toBoolean(aab.detect(bcb,ccb))end function aab.findWhere(bcb,ccb) local dcb=aab.detect(bcb,function(_db)for adb in d_b(ccb)do if ccb[adb]~=_db[adb]then return false end end;return true end)return dcb and bcb[dcb]end function aab.select(bcb,ccb,...)local dcb=aab.map(bcb,ccb,...)local _db={}for adb,bdb in d_b(dcb)do if bdb then _db[#_db+1]=bcb[adb]end end;return _db end function aab.reject(bcb,ccb,...)local dcb=aab.map(bcb,ccb,...)local _db={}for adb,bdb in d_b(dcb)do if not bdb then _db[#_db+1]=bcb[adb]end end;return _db end;function aab.all(bcb,ccb,...)return ( (#aab.select(aab.map(bcb,ccb,...),_bb))== (#bcb))end function aab.invoke(bcb,ccb,...) local dcb={...} return aab.map(bcb,function(_db,adb) if aab.isTable(adb)then if aab.has(adb,ccb)then if aab.isCallable(adb[ccb])then return adb[ccb](adb,c_b(dcb))else return adb[ccb]end else if aab.isCallable(ccb)then return ccb(adb,c_b(dcb))end end elseif aab.isCallable(ccb)then return ccb(adb,c_b(dcb))end end)end function aab.pluck(bcb,ccb)return aab.reject(aab.map(bcb,function(dcb,_db)return _db[ccb]end),abb)end;function aab.max(bcb,ccb,...)return cbb(bcb,bab,ccb,...)end;function aab.min(bcb,ccb,...)return cbb(bcb,cab,ccb,...)end function aab.shuffle(bcb,ccb)if ccb then ada(ccb)end local dcb={} aab.each(bcb,function(_db,adb)local bdb=dda(bda()*_db)+1;dcb[_db]=dcb[bdb] dcb[bdb]=adb end)return dcb end function aab.same(bcb,ccb) return aab.all(bcb,function(dcb,_db)return aab.include(ccb,_db)end)and aab.all(ccb,function(dcb,_db)return aab.include(bcb,_db)end)end;function aab.sort(bcb,ccb)cca(bcb,ccb)return bcb end function aab.groupBy(bcb,ccb,...)local dcb={...} local _db={} local adb=aab.isFunction(ccb)and ccb or(aab.isString(ccb)and function(bdb,cdb)return cdb[ccb](cdb,c_b(dcb))end)if not adb then return end aab.each(bcb,function(bdb,cdb)local ddb=adb(bdb,cdb) if _db[ddb]then _db[ddb][#_db[ddb]+ 1]=cdb else _db[ddb]={cdb}end end)return _db end function aab.countBy(bcb,ccb,...)local dcb={...}local _db={} aab.each(bcb,function(adb,bdb)local cdb=ccb(adb,bdb,c_b(dcb))_db[cdb]=( _db[cdb]or 0)+1 end)return _db end function aab.size(...)local bcb={...}local ccb=bcb[1]if aab.isNil(ccb)then return 0 elseif aab.isTable(ccb)then return bbb(bcb[1])else return bbb(bcb)end end;function aab.containsKeys(bcb,ccb) for dcb in d_b(ccb)do if not bcb[dcb]then return false end end;return true end function aab.sameKeys(bcb,ccb) aab.each(bcb,function(dcb)if not ccb[dcb]then return false end end) aab.each(ccb,function(dcb)if not bcb[dcb]then return false end end)return true end;function aab.toArray(...)return{...}end function aab.find(bcb,ccb,dcb)for i=dcb or 1,#bcb do if aab.isEqual(bcb[i],ccb)then return i end end end function aab.reverse(bcb)local ccb={}for i=#bcb,1,-1 do ccb[#ccb+1]=bcb[i]end;return ccb end function aab.selectWhile(bcb,ccb,...)local dcb={}for _db,adb in _ab(bcb)do if ccb(_db,adb,...)then dcb[_db]=adb else break end end;return dcb end function aab.dropWhile(bcb,ccb,...)local dcb for _db,adb in _ab(bcb)do if not ccb(_db,adb,...)then dcb=_db;break end end;if aab.isNil(dcb)then return{}end;return aab.rest(bcb,dcb)end function aab.sortedIndex(bcb,ccb,dcb,_db)local adb=dcb or cab;if _db then aab.sort(bcb,adb)end;for i=1,#bcb do if not adb(bcb[i],ccb)then return i end end return#bcb+1 end function aab.indexOf(bcb,ccb)for k=1,#bcb do if bcb[k]==ccb then return k end end end function aab.lastIndexOf(bcb,ccb)local dcb=aab.indexOf(aab.reverse(bcb),ccb)if dcb then return #bcb-dcb+1 end end;function aab.addTop(bcb,...) aab.each({...},function(ccb,dcb)bca(bcb,1,dcb)end)return bcb end;function aab.push(bcb,...)aab.each({...},function(ccb,dcb) bcb[#bcb+1]=dcb end) return bcb end function aab.pop(bcb,ccb) ccb=a_b(ccb or 1,#bcb)local dcb={} for i=1,ccb do local _db=bcb[1]dcb[#dcb+1]=_db;dca(bcb,1)end;return c_b(dcb)end function aab.unshift(bcb,ccb)ccb=a_b(ccb or 1,#bcb)local dcb={}for i=1,ccb do local _db=bcb[#bcb] dcb[#dcb+1]=_db;dca(bcb)end;return c_b(dcb)end function aab.pull(bcb,...) for ccb,dcb in _ab({...})do for i=#bcb,1,-1 do if aab.isEqual(bcb[i],dcb)then dca(bcb,i)end end end;return bcb end function aab.removeRange(bcb,ccb,dcb)local _db=aab.clone(bcb)local adb,bdb=(_ba(_db)),#_db if bdb<1 then return _db end;ccb=dab(ccb or adb,adb,bdb) dcb=dab(dcb or bdb,adb,bdb)if dcb<ccb then return _db end;local cdb=dcb-ccb+1;local ddb=ccb;while cdb>0 do dca(_db,ddb)cdb=cdb-1 end;return _db end function aab.chunk(bcb,ccb,...)if not aab.isArray(bcb)then return bcb end;local dcb,_db,adb={},0 local bdb=aab.map(bcb,ccb,...) aab.each(bdb,function(cdb,ddb)adb=(adb==nil)and ddb or adb;_db=( (ddb~=adb)and(_db+1)or _db) if not dcb[_db]then dcb[_db]={bcb[cdb]}else dcb[_db][ #dcb[_db]+1]=bcb[cdb]end;adb=ddb end)return dcb end function aab.slice(bcb,ccb,dcb)return aab.select(bcb,function(_db)return (_db>= (ccb or _ba(bcb))and _db<= (dcb or#bcb))end)end;function aab.first(bcb,ccb)local dcb=ccb or 1 return aab.slice(bcb,1,a_b(dcb,#bcb))end function aab.initial(bcb,ccb) if ccb and ccb<0 then return end;return aab.slice(bcb,1,ccb and#bcb- (a_b(ccb,#bcb))or#bcb-1)end;function aab.last(bcb,ccb)if ccb and ccb<=0 then return end return aab.slice(bcb,ccb and #bcb-a_b(ccb-1,#bcb-1)or 2,#bcb)end;function aab.rest(bcb,ccb)if ccb and ccb>#bcb then return{}end return aab.slice(bcb, ccb and __b(1,a_b(ccb,#bcb))or 1,#bcb)end;function aab.compact(bcb) return aab.reject(bcb,function(ccb,dcb)return not dcb end)end function aab.flatten(bcb,ccb)local dcb=ccb or false local _db;local adb={} for bdb,cdb in d_b(bcb)do if aab.isTable(cdb)then _db=dcb and cdb or aab.flatten(cdb) aab.each(_db,function(ddb,__c)adb[#adb+1]=__c end)else adb[#adb+1]=cdb end end;return adb end function aab.difference(bcb,ccb)if not ccb then return aab.clone(bcb)end;return aab.select(bcb,function(dcb,_db)return not aab.include(ccb,_db)end)end function aab.union(...)return aab.uniq(aab.flatten({...}))end function aab.intersection(bcb,...)local ccb={...}local dcb={} for _db,adb in _ab(bcb)do if aab.all(ccb,function(bdb,cdb)return aab.include(cdb,adb)end)then bca(dcb,adb)end end;return dcb end function aab.symmetricDifference(bcb,ccb)return aab.difference(aab.union(bcb,ccb),aab.intersection(bcb,ccb))end function aab.unique(bcb)local ccb={}for i=1,#bcb do if not aab.find(ccb,bcb[i])then ccb[#ccb+1]=bcb[i]end end;return ccb end function aab.isunique(bcb)return aab.isEqual(bcb,aab.unique(bcb))end function aab.zip(...)local bcb={...} local ccb=aab.max(aab.map(bcb,function(_db,adb)return#adb end))local dcb={}for i=1,ccb do dcb[i]=aab.pluck(bcb,i)end;return dcb end function aab.append(bcb,ccb)local dcb={}for _db,adb in _ab(bcb)do dcb[_db]=adb end;for _db,adb in _ab(ccb)do dcb[#dcb+1]=adb end;return dcb end function aab.interleave(...)return aab.flatten(aab.zip(...))end;function aab.interpose(bcb,ccb)return aab.flatten(aab.zip(ccb,aab.rep(bcb,#ccb-1)))end function aab.range(...) local bcb={...}local ccb,dcb,_db if#bcb==0 then return{}elseif#bcb==1 then dcb,ccb,_db=bcb[1],0,1 elseif#bcb==2 then ccb,dcb,_db=bcb[1],bcb[2],1 elseif#bcb==3 then ccb,dcb,_db=bcb[1],bcb[2],bcb[3]end;if(_db and _db==0)then return{}end;local adb={} local bdb=__b(dda((dcb-ccb)/_db),0)for i=1,bdb do adb[#adb+1]=ccb+_db*i end;if#adb>0 then bca(adb,1,ccb)end;return adb end function aab.rep(bcb,ccb)local dcb={}for i=1,ccb do dcb[#dcb+1]=bcb end;return dcb end function aab.partition(bcb,ccb)return coroutine.wrap(function()dbb(bcb,ccb or 1,coroutine.yield)end)end function aab.permutation(bcb)return coroutine.wrap(function()_cb(bcb,#bcb,coroutine.yield)end)end;function aab.invert(bcb)local ccb={} aab.each(bcb,function(dcb,_db)ccb[_db]=dcb end)return ccb end function aab.concat(bcb,ccb,dcb,_db) local adb=aab.map(bcb,function(bdb,cdb)return tostring(cdb)end)return _da(adb,ccb,dcb or 1,_db or#bcb)end;function aab.identity(bcb)return bcb end function aab.once(bcb)local ccb=0;local dcb={}return function(...)ccb=ccb+1;if ccb<=1 then dcb={...}end;return bcb(c_b(dcb))end end function aab.memoize(bcb,ccb)local dcb=_ca({},{__mode='kv'}) local _db=ccb or aab.identity return function(...)local adb=_db(...)local bdb=dcb[adb] if not bdb then dcb[adb]=bcb(...)end;return dcb[adb]end end function aab.after(bcb,ccb)local dcb,_db=ccb,0;return function(...)_db=_db+1;if _db>=dcb then return bcb(...)end end end function aab.compose(...)local bcb=aab.reverse{...}return function(...)local ccb;for dcb,_db in _ab(bcb)do ccb=ccb and _db(ccb)or _db(...)end;return ccb end end function aab.pipe(bcb,...)return aab.compose(...)(bcb)end function aab.complement(bcb)return function(...)return not bcb(...)end end;function aab.juxtapose(bcb,...)local ccb={} aab.each({...},function(dcb,_db)ccb[#ccb+1]=_db(bcb)end)return c_b(ccb)end function aab.wrap(bcb,ccb)return function(...)return ccb(bcb,...)end end function aab.times(bcb,ccb,...)local dcb={}for i=1,bcb do dcb[i]=ccb(i,...)end;return dcb end function aab.bind(bcb,ccb)return function(...)return bcb(ccb,...)end end function aab.bindn(bcb,...)local ccb={...}return function(...) return bcb(c_b(aab.append(ccb,{...})))end end function aab.uniqueId(bcb,...)acb=acb+1 if bcb then if aab.isString(bcb)then return bcb:format(acb)elseif aab.isFunction(bcb)then return bcb(acb,...)end end;return acb end;function aab.keys(bcb)local ccb={} aab.each(bcb,function(dcb)ccb[#ccb+1]=dcb end)return ccb end;function aab.values(bcb)local ccb={} aab.each(bcb,function(dcb,_db)ccb[ #ccb+1]=_db end)return ccb end;function aab.toBoolean(bcb)return not not bcb end function aab.extend(bcb,...)local ccb={...} aab.each(ccb,function(dcb,_db) if aab.isTable(_db)then aab.each(_db,function(adb,bdb) bcb[adb]=bdb end)end end)return bcb end function aab.functions(bcb,ccb)bcb=bcb or aab;local dcb={} aab.each(bcb,function(adb,bdb)if aab.isFunction(bdb)then dcb[#dcb+1]=adb end end)if not ccb then return aab.sort(dcb)end;local _db=aca(bcb) if _db and _db.__index then local adb=aab.functions(_db.__index)aab.each(adb,function(bdb,cdb) dcb[#dcb+1]=cdb end)end;return aab.sort(dcb)end function aab.clone(bcb,ccb)if not aab.isTable(bcb)then return bcb end;local dcb={} aab.each(bcb,function(_db,adb)if aab.isTable(adb)then if not ccb then dcb[_db]=aab.clone(adb,ccb)else dcb[_db]=adb end else dcb[_db]=adb end end)return dcb end;function aab.tap(bcb,ccb,...)ccb(bcb,...)return bcb end;function aab.has(bcb,ccb)return bcb[ccb]~=nil end function aab.pick(bcb,...)local ccb=aab.flatten{...} local dcb={} aab.each(ccb,function(_db,adb) if not aab.isNil(bcb[adb])then dcb[adb]=bcb[adb]end end)return dcb end function aab.omit(bcb,...)local ccb=aab.flatten{...}local dcb={} aab.each(bcb,function(_db,adb)if not aab.include(ccb,_db)then dcb[_db]=adb end end)return dcb end;function aab.template(bcb,ccb) aab.each(ccb or{},function(dcb,_db)if not bcb[dcb]then bcb[dcb]=_db end end)return bcb end function aab.isEqual(bcb,ccb,dcb) local _db=aba(bcb)local adb=aba(ccb)if _db~=adb then return false end if _db~='table'then return(bcb==ccb)end;local bdb=aca(bcb)local cdb=aca(ccb) if dcb then if bdb or cdb and bdb.__eq or cdb.__eq then return(bcb==ccb)end end if aab.size(bcb)~=aab.size(ccb)then return false end for ddb,__c in d_b(bcb)do local a_c=ccb[ddb]if aab.isNil(a_c)or not aab.isEqual(__c,a_c,dcb)then return false end end for ddb,__c in d_b(ccb)do local a_c=bcb[ddb]if aab.isNil(a_c)then return false end end;return true end function aab.result(bcb,ccb,...) if bcb[ccb]then if aab.isCallable(bcb[ccb])then return bcb[ccb](bcb,...)else return bcb[ccb]end end;if aab.isCallable(ccb)then return ccb(bcb,...)end end;function aab.isTable(bcb)return aba(bcb)=='table'end function aab.isCallable(bcb)return ( aab.isFunction(bcb)or (aab.isTable(bcb)and aca(bcb)and aca(bcb).__call~=nil)or false)end function aab.isArray(bcb)if not aab.isTable(bcb)then return false end;local ccb=0 for dcb in d_b(bcb)do ccb=ccb+1;if aab.isNil(bcb[ccb])then return false end end;return true end function aab.isIterable(bcb)return aab.toBoolean((dba(d_b,bcb)))end function aab.isEmpty(bcb)if aab.isNil(bcb)then return true end;if aab.isString(bcb)then return#bcb==0 end if aab.isTable(bcb)then return _ba(bcb)==nil end;return true end;function aab.isString(bcb)return aba(bcb)=='string'end;function aab.isFunction(bcb)return aba(bcb)=='function'end;function aab.isNil(bcb) return bcb==nil end function aab.isNumber(bcb)return aba(bcb)=='number'end function aab.isNaN(bcb)return aab.isNumber(bcb)and bcb~=bcb end function aab.isFinite(bcb)if not aab.isNumber(bcb)then return false end;return bcb>-cda and bcb<cda end;function aab.isBoolean(bcb)return aba(bcb)=='boolean'end function aab.isInteger(bcb)return aab.isNumber(bcb)and dda(bcb)==bcb end do aab.forEach=aab.each;aab.forEachi=aab.eachi;aab.loop=aab.cycle aab.collect=aab.map;aab.inject=aab.reduce;aab.foldl=aab.reduce aab.injectr=aab.reduceRight;aab.foldr=aab.reduceRight;aab.mapr=aab.mapReduce aab.maprr=aab.mapReduceRight;aab.any=aab.include;aab.some=aab.include;aab.filter=aab.select aab.discard=aab.reject;aab.every=aab.all;aab.takeWhile=aab.selectWhile aab.rejectWhile=aab.dropWhile;aab.shift=aab.pop;aab.remove=aab.pull;aab.rmRange=aab.removeRange aab.chop=aab.removeRange;aab.sub=aab.slice;aab.head=aab.first;aab.take=aab.first aab.tail=aab.rest;aab.skip=aab.last;aab.without=aab.difference;aab.diff=aab.difference aab.symdiff=aab.symmetricDifference;aab.xor=aab.symmetricDifference;aab.uniq=aab.unique aab.isuniq=aab.isunique;aab.part=aab.partition;aab.perm=aab.permutation;aab.mirror=aab.invert aab.join=aab.concat;aab.cache=aab.memoize;aab.juxt=aab.juxtapose;aab.uid=aab.uniqueId aab.methods=aab.functions;aab.choose=aab.pick;aab.drop=aab.omit;aab.defaults=aab.template aab.compare=aab.isEqual end do local bcb={}local ccb={}ccb.__index=bcb;local function dcb(_db)local adb={_value=_db,_wrapped=true} return _ca(adb,ccb)end _ca(ccb,{__call=function(_db,adb)return dcb(adb)end,__index=function(_db,adb,...)return bcb[adb]end})function ccb.chain(_db)return dcb(_db)end function ccb:value()return self._value end;bcb.chain,bcb.value=ccb.chain,ccb.value for _db,adb in d_b(aab)do bcb[_db]=function(bdb,...)local cdb=aab.isTable(bdb)and bdb._wrapped or false if cdb then local ddb=bdb._value;local __c=adb(ddb,...)return dcb(__c)else return adb(bdb,...)end end end bcb.import=function(_db,adb)_db=_db or _G;local bdb=aab.functions() aab.each(bdb,function(cdb,ddb) if b_b(_db,ddb)then if not adb then _db[ddb]=aab[ddb]end else _db[ddb]=aab[ddb]end end)return _db end;ccb._VERSION='Moses v'..daa ccb._URL='http://github.com/Yonaba/Moses' ccb._LICENSE='MIT <http://raw.githubusercontent.com/Yonaba/Moses/master/LICENSE>'ccb._DESCRIPTION='utility-belt library for functional programming in Lua'return ccb end
mit
KevinGuarnati/controllore
plugins/rss.lua
3
5195
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if not is_sudo(msg) then return "Only sudo users can use the RSS." end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
mit
Fatalerror66/ffxi-a
scripts/zones/Eastern_Altepa_Desert/npcs/Daborn_IM.lua
4
2910
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Daborn, I.M. -- Border Conquest Guards -- @pos 226.493 -12.231 260.194 114 ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border region = KUZOTZ; csid = 0x7ff8; ----------------------------------- -- 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 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 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 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/globals/weaponskills/spinning_scythe.lua
4
1225
----------------------------------- -- Spinning Scythe -- Scythe weapon skill -- Skill Level: 125 -- Delivers an area of effect attack. Attack radius varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Aqua Gorget & Soil Gorget. -- Aligned with the Aqua Belt & Soil Belt. -- Element: None -- Modifiers: STR: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 = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; 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; 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); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
zhangshiqian1214/skynet
3rd/lua-cjson/lua/cjson/util.lua
170
6837
local json = require "cjson" -- Various common routines used by the Lua CJSON package -- -- Mark Pulford <mark@kyne.com.au> -- Determine with a Lua table can be treated as an array. -- Explicitly returns "not an array" for very sparse arrays. -- Returns: -- -1 Not an array -- 0 Empty table -- >0 Highest index in the array local function is_array(table) local max = 0 local count = 0 for k, v in pairs(table) do if type(k) == "number" then if k > max then max = k end count = count + 1 else return -1 end end if max > count * 2 then return -1 end return max end local serialise_value local function serialise_table(value, indent, depth) local spacing, spacing2, indent2 if indent then spacing = "\n" .. indent spacing2 = spacing .. " " indent2 = indent .. " " else spacing, spacing2, indent2 = " ", " ", false end depth = depth + 1 if depth > 50 then return "Cannot serialise any further: too many nested tables" end local max = is_array(value) local comma = false local fragment = { "{" .. spacing2 } if max > 0 then -- Serialise array for i = 1, max do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, serialise_value(value[i], indent2, depth)) comma = true end elseif max < 0 then -- Serialise table for k, v in pairs(value) do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, ("[%s] = %s"):format(serialise_value(k, indent2, depth), serialise_value(v, indent2, depth))) comma = true end end table.insert(fragment, spacing .. "}") return table.concat(fragment) end function serialise_value(value, indent, depth) if indent == nil then indent = "" end if depth == nil then depth = 0 end if value == json.null then return "json.null" elseif type(value) == "string" then return ("%q"):format(value) elseif type(value) == "nil" or type(value) == "number" or type(value) == "boolean" then return tostring(value) elseif type(value) == "table" then return serialise_table(value, indent, depth) else return "\"<" .. type(value) .. ">\"" end end local function file_load(filename) local file if filename == nil then file = io.stdin else local err file, err = io.open(filename, "rb") if file == nil then error(("Unable to read '%s': %s"):format(filename, err)) end end local data = file:read("*a") if filename ~= nil then file:close() end if data == nil then error("Failed to read " .. filename) end return data end local function file_save(filename, data) local file if filename == nil then file = io.stdout else local err file, err = io.open(filename, "wb") if file == nil then error(("Unable to write '%s': %s"):format(filename, err)) end end file:write(data) if filename ~= nil then file:close() end end local function compare_values(val1, val2) local type1 = type(val1) local type2 = type(val2) if type1 ~= type2 then return false end -- Check for NaN if type1 == "number" and val1 ~= val1 and val2 ~= val2 then return true end if type1 ~= "table" then return val1 == val2 end -- check_keys stores all the keys that must be checked in val2 local check_keys = {} for k, _ in pairs(val1) do check_keys[k] = true end for k, v in pairs(val2) do if not check_keys[k] then return false end if not compare_values(val1[k], val2[k]) then return false end check_keys[k] = nil end for k, _ in pairs(check_keys) do -- Not the same if any keys from val1 were not found in val2 return false end return true end local test_count_pass = 0 local test_count_total = 0 local function run_test_summary() return test_count_pass, test_count_total end local function run_test(testname, func, input, should_work, output) local function status_line(name, status, value) local statusmap = { [true] = ":success", [false] = ":error" } if status ~= nil then name = name .. statusmap[status] end print(("[%s] %s"):format(name, serialise_value(value, false))) end local result = { pcall(func, unpack(input)) } local success = table.remove(result, 1) local correct = false if success == should_work and compare_values(result, output) then correct = true test_count_pass = test_count_pass + 1 end test_count_total = test_count_total + 1 local teststatus = { [true] = "PASS", [false] = "FAIL" } print(("==> Test [%d] %s: %s"):format(test_count_total, testname, teststatus[correct])) status_line("Input", nil, input) if not correct then status_line("Expected", should_work, output) end status_line("Received", success, result) print() return correct, result end local function run_test_group(tests) local function run_helper(name, func, input) if type(name) == "string" and #name > 0 then print("==> " .. name) end -- Not a protected call, these functions should never generate errors. func(unpack(input or {})) print() end for _, v in ipairs(tests) do -- Run the helper if "should_work" is missing if v[4] == nil then run_helper(unpack(v)) else run_test(unpack(v)) end end end -- Run a Lua script in a separate environment local function run_script(script, env) local env = env or {} local func -- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists if _G.setfenv then func = loadstring(script) if func then setfenv(func, env) end else func = load(script, nil, nil, env) end if func == nil then error("Invalid syntax.") end func() return env end -- Export functions return { serialise_value = serialise_value, file_load = file_load, file_save = file_save, compare_values = compare_values, run_test_summary = run_test_summary, run_test = run_test, run_test_group = run_test_group, run_script = run_script } -- vi:ai et sw=4 ts=4:
mit
meshr-net/meshr_win32
usr/lib/lua/luci/model/cbi/luci_statistics/exec.lua
7
2838
--[[ Luci configuration model for statistics - collectd exec plugin configuration (c) 2008 Freifunk Leipzig / 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: exec.lua 7993 2011-11-28 15:19:11Z soma $ ]]-- m = Map("luci_statistics", translate("Exec Plugin Configuration"), translate( "The exec plugin starts external commands to read values " .. "from or to notify external processes when certain threshold " .. "values have been reached." )) -- collectd_exec config section s = m:section( NamedSection, "collectd_exec", "luci_statistics" ) -- collectd_exec.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_exec_input config section (Exec directives) exec = m:section( TypedSection, "collectd_exec_input", translate("Add command for reading values"), translate( "Here you can define external commands which will be " .. "started by collectd in order to read certain values. " .. "The values will be read from stdout." )) exec.addremove = true exec.anonymous = true -- collectd_exec_input.cmdline exec_cmdline = exec:option( Value, "cmdline", translate("Script") ) exec_cmdline.default = "/usr/bin/stat-dhcpusers" -- collectd_exec_input.cmdline exec_cmduser = exec:option( Value, "cmduser", translate("User") ) exec_cmduser.default = "nobody" exec_cmduser.rmempty = true exec_cmduser.optional = true -- collectd_exec_input.cmdline exec_cmdgroup = exec:option( Value, "cmdgroup", translate("Group") ) exec_cmdgroup.default = "nogroup" exec_cmdgroup.rmempty = true exec_cmdgroup.optional = true -- collectd_exec_notify config section (NotifyExec directives) notify = m:section( TypedSection, "collectd_exec_notify", translate("Add notification command"), translate( "Here you can define external commands which will be " .. "started by collectd when certain threshold values have " .. "been reached. The values leading to invokation will be " .. "feeded to the the called programs stdin." )) notify.addremove = true notify.anonymous = true -- collectd_notify_input.cmdline notify_cmdline = notify:option( Value, "cmdline", translate("Script") ) notify_cmdline.default = "/usr/bin/stat-dhcpusers" -- collectd_notify_input.cmdline notify_cmduser = notify:option( Value, "cmduser", translate("User") ) notify_cmduser.default = "nobody" notify_cmduser.rmempty = true notify_cmduser.optional = true -- collectd_notify_input.cmdline notify_cmdgroup = notify:option( Value, "cmdgroup", translate("Group") ) notify_cmdgroup.default = "nogroup" notify_cmdgroup.rmempty = true notify_cmdgroup.optional = true return m
apache-2.0
emoses/hammerspoon
extensions/messages/init.lua
22
1501
--- === hs.messages === --- --- Send messages via iMessage and SMS Relay (note, SMS Relay requires OS X 10.10 and an established SMS Relay pairing between your Mac and an iPhone running iOS8) --- --- Note: This extension works by controlling the OS X "Messages" app via AppleScript, so you will need that app to be signed into an iMessage account local messages = {} local as = require "hs.applescript" -- Internal function to pass a command to Applescript. local function tell(cmd) local _cmd = 'tell application "Messages" to ' .. cmd local _ok, result = as.applescript(_cmd) return result end --- hs.messages.iMessage(targetAddress, message) --- Function --- Sends an iMessage --- --- Parameters: --- * targetAddress - A string containing a phone number or email address registered with iMessage, to send the iMessage to --- * message - A string containing the message to send --- --- Returns: --- * None function messages.iMessage(targetAddress, message) tell('send "'..message..'" to buddy "'..targetAddress..'" of (service 1 whose service type is iMessage)') end -- --- hs.messages.SMS(targetNumber, message) --- Function --- Sends an SMS using SMS Relay --- --- Parameters: --- * targetNumber - A string containing a phone number to send an SMS to --- * message - A string containing the message to send --- --- Returns: --- * None function messages.SMS(targetNumber, message) tell('send "'..message..'" to buddy "'..targetNumber..'" of service "SMS"') end return messages
mit
Clavus/LD32
game/words/J Words.lua
1
10356
return [[jab jabbed jabber jabbered jabberer jabberers jabbering jabberings jabbers jabberwock jabbing jabble jabbled jabbles jabbling jabers jabiru jabirus jaborandi jabot jabots jabs jacamar jacamars jacana jacanas jacaranda jacarandas jacchus jacchuses jacent jacinth jacinths jack jackal jackals jackanapes jackaroo jackarooed jackaroos jackass jackasses jackboot jackboots jackdaw jackdaws jacked jackeen jackeroo jackerooed jackeroos jacket jacketed jacketing jackets jackfish jackhammer jacking jackman jackmen jackpot jackpots jacks jackshaft jacksie jacksies jacksy jacobus jacobuses jaconet jacquard jacquards jactation jactations jaculate jaculated jaculates jaculating jaculation jaculator jaculators jaculatory jade jaded jadedly jadeite jaderies jadery jades jading jadish jaeger jaegers jag j‰ger j‰gers jagged jaggedly jaggedness jagger jaggers jaggery jaggier jaggiest jagging jaggy jaghir jaghire jaghirs jagir jagirs jags jaguar jaguarondi jaguars jaguarundi jail jailed jailer jaileress jailers jailhouse jailing jailor jailors jails jake jakes jalap jalapeÒo jalapeÒos jalapic jalapin jalaps jalopies jaloppies jaloppy jalopy jalouse jalouses jalousie jalousied jalousies jam jamadar jamadars jamahiriya jamb jambalaya jambalayas jambe jambeau jambeaux jambee jambees jamber jambers jambes jambo jambok jambokked jambokking jamboks jambolan jambolana jambolanas jambolans jambone jambones jambool jambools jamboree jamborees jambos jambs jambu jambul jambuls jambus jamdani james jameses jamjar jamjars jammed jammer jammers jammier jammiest jamming jammy jampan jampani jampanis jampans jampot jampots jams jane janes jangle jangled jangler janglers jangles jangling janglings jangly janiform janissary janitor janitorial janitors janitress janitrix janitrixes janizarian janizaries janizary janker jankers jann jannock jannocks jansky janskys janties janty jap japan japanesy japanned japanner japanners japanning japans jape japed japer japers japes japing japonica japonicas japs jar jararaca jararacas jardiniËre jarful jarfuls jargon jargoned jargoneer jargoneers jargonelle jargoning jargonise jargonised jargonises jargonist jargonists jargonize jargonized jargonizes jargons jargoon jark jarkman jarkmen jarks jarl jarls jarool jarools jarosite jarrah jarrahs jarred jarring jarringly jarrings jars jarvey jarveys jarvie jarvies jasey jaseys jasmine jasmines jasp jaspe jasper jasperise jasperised jasperises jasperize jasperized jasperizes jaspers jasperware jaspery jaspidean jaspideous jaspis jaspises jass jataka jatakas jato jatos jaunce jaunced jaunces jauncing jaundice jaundiced jaundices jaundicing jaunt jaunted jauntie jauntier jaunties jauntiest jauntily jauntiness jaunting jaunts jaunty jaup jauped jauping jaups javel javelin javelins jaw jawan jawans jawbation jawbations jawbone jawbones jawboning jawbreaker jawed jawfall jawfalls jawing jawings jawohl jaws jay jays jaywalk jaywalked jaywalker jaywalkers jaywalking jaywalks jazerant jazz jazzed jazzer jazzers jazzes jazzier jazziest jazzily jazziness jazzing jazzman jazzmen jazzy jealous jealousies jealously jealousy jean jeanette jeanettes jeans jebel jebels jee jeed jeeing jeelie jeelies jeely jeep jeepney jeepneys jeeps jeer jeered jeerer jeerers jeering jeeringly jeerings jeers jees jeff jeffed jeffing jeffs jehad jehads jeistiecor jejune jejunely jejuneness jejunity jejunum jejunums jelab jell jellaba jellabas jelled jellied jellies jellified jellifies jellify jellifying jelling jello jellos jells jelly jellybean jellybeans jellyfish jellygraph jellying jelutong jelutongs jemadar jemadars jemidar jemidars jemima jemimas jemmied jemmies jemminess jemmy jemmying jennet jenneting jennetings jennets jennies jenny jeofail jeopard jeoparder jeoparders jeopardise jeopardize jeopardous jeopardy jequirity jerbil jerbils jerboa jerboas jereed jereeds jeremiad jeremiads jerfalcon jerfalcons jerid jerids jerk jerked jerker jerkers jerkier jerkiest jerkily jerkin jerkiness jerking jerkings jerkinhead jerkins jerks jerkwater jerkwaters jerky jeroboam jeroboams jerque jerqued jerquer jerquers jerques jerquing jerquings jerrican jerricans jerries jerry jerrycan jerrycans jersey jerseys jess jessamine jessamines jessamy jessant jessed jesses jessie jessies jest jestbook jestbooks jested jestee jestees jester jesters jestful jesting jestingly jestings jests jet jetfoil jetfoils jetliner jetliners jeton jetons jets jetsam jetsom jetted jettied jetties jettiness jetting jettison jettisoned jettisons jetton jettons jetty jettying jeu jeux jewel jeweler jewelers jewelfish jewelled jeweller jewellers jewellery jewelling jewelry jewels jewfish jewfishes jezail jezails jhala jiao jiaos jib jibbah jibbahs jibbed jibber jibbers jibbing jibbings jibe jibed jiber jibers jibes jibing jibs jiff jiffies jiffs jiffy jig jigamaree jigamarees jigged jigger jiggered jiggering jiggers jigging jiggings jiggish jiggle jiggled jiggles jiggling jiggly jiggumbob jiggumbobs jigjig jigot jigots jigs jigsaw jigsawed jigsawing jigsaws jihad jihads jill jillaroo jillarooed jillaroos jillet jillets jillflirt jillflirts jillion jillions jills jilt jilted jilting jilts jimcrack jimcracks jiminy jimjam jimjams jimmies jimmy jimp jimper jimpest jimply jimpness jimpy jingal jingals jingbang jingbangs jingle jingled jingler jinglers jingles jinglet jinglets jinglier jingliest jingling jingly jingo jingoes jingoish jingoism jingoist jingoistic jingoists jinjili jinjilis jink jinked jinker jinkers jinking jinks jinn jinnee jinni jinns jinricksha jinrikisha jinx jinxed jinxes jipyapa jipyapas jirga jirgas jirkinet jirkinets jism jissom jitney jitneys jitter jitterbug jitterbugs jittered jittering jitters jittery jive jived jiver jivers jives jiving jizz jizzes jnana jo joannes joanneses job jobation jobations jobbed jobber jobbers jobbery jobbing jobless jobs jobsworth jobsworths jock jockette jockettes jockey jockeyed jockeying jockeyism jockeys jockeyship jocko jockos jocks jockstrap jockstraps jockteleg jocktelegs jocose jocosely jocoseness jocosity jocular jocularity jocularly joculator joculators jocund jocundity jocundly jocundness jodel jodelled jodelling jodels jodhpurs joe joes joey joeys jog jogged jogger joggers jogging joggle joggled joggles joggling jogs johannes johanneses john johnnie johnnies johnny johns join joinder joinders joined joiner joiners joinery joining joinings joins joint jointed jointer jointers jointing jointless jointly jointress joints jointure jointured jointures jointuress jointuring joist joisted joisting joists jojoba jojobas joke joked joker jokers jokes jokesmith jokesmiths jokesome jokey jokier jokiest joking jokingly joky jole joled joles joling joliotium joll jolled jollied jollier jollies jolliest jollified jollifies jollify jollifying jollily jolliness jolling jollities jollity jolls jolly jollyboat jollyboats jollyer jollyers jollyhead jollying jolt jolted jolter jolterhead jolters jolthead joltheads joltier joltiest jolting joltingly jolts jolty jomo jomos joncanoe jongleur jongleurs jonquil jonquils jook jooked jooking jooks jor joram jorams jorum jorums joseph josephs josh joshed josher joshers joshes joshing joskin joskins joss josser jossers josses jostle jostled jostlement jostles jostling jostlings jot jota jotas jots jotted jotter jotters jotting jottings jotun jotunn jotunns jotuns joual jougs jouisance jouk jouked jouking jouks joule joules jounce jounced jounces jouncing jour journal journalese journalise journalism journalist journalize journals journey journeyed journeyer journeyers journeying journeyman journeymen journeys journo journos joust jousted jouster jousters jousting jousts jouysaunce jovial joviality jovially jovialness jow jowar jowari jowaris jowars jowed jowing jowl jowled jowler jowlers jowlier jowliest jowls jowly jows joy joyance joyances joyed joyful joyfully joyfulness joying joyless joylessly joyous joyously joyousness joypop joypopped joypopping joypops joys juba jubas jubate jubbah jubbahs jube jubes jubilance jubilances jubilancy jubilant jubilantly jubilate jubilated jubilates jubilating jubilation jubilee jubilees jud judaist judas judases judder juddered juddering judders judge judged judgement judgements judges judgeship judgeships judging judgment judgmental judgments judicable judication judicative judicator judicators judicatory judicature judicial judicially judiciary judicious judies judo judogi judogis judoist judoists judoka judokas juds judy jug juga jugal jugals jugate jugful jugfuls jugged juggernaut jugging juggins jugginses juggle juggled juggler juggleries jugglers jugglery juggles juggling jugglingly jugglings jughead jugheads jugs jugular jugulars jugulate jugulated jugulates jugulating jugum juice juiced juiceless juicer juicers juices juicier juiciest juiciness juicing juicy juju jujube jujubes jujus juke jukebox jukeboxes juked jukes juking jukskei julep juleps julienne juliennes jumar jumared jumaring jumars jumart jumarts jumbal jumbals jumble jumbled jumbler jumblers jumbles jumbling jumblingly jumbly jumbo jumboise jumboised jumboises jumboising jumboize jumboized jumboizes jumboizing jumbos jumbuck jumbucks jumby jumelle jumelles jump jumpable jumped jumper jumpers jumpier jumpiest jumpily jumpiness jumping jumps jumpy juncaceous junco juncoes juncos junction junctions juncture junctures juncus juncuses juneating jungle jungles jungli junglier jungliest jungly junior juniority juniors juniper junipers junk junkanoo junked junker junkerdom junkerdoms junkerism junkerisms junkers junket junketed junketeer junketeers junketing junketings junkets junkie junkies junking junkman junkmen junks junky junta juntas junto juntos jupati jupatis jupon jupons jura jural jurally jurant jurants jurat juratory jurats jure juridic juridical juries jurist juristic juristical jurists juror jurors jury juryman jurymast jurymasts jurymen jurywoman jurywomen jus jussive jussives just justed justice justicer justicers justices justiciar justiciars justiciary justified justifier justifiers justifies justify justifying justing justle justled justles justling justly justness justs jut jute jutes juts jutted juttied jutties jutting juttingly jutty juttying juve juvenal juvenile juvenilely juveniles juvenilia juvenility juves juxtapose juxtaposed juxtaposes jymold jynx jynxes]]
mit
Fatalerror66/ffxi-a
scripts/globals/items/coeurl_sub_+1.lua
2
1861
----------------------------------------- -- ID: 5167 -- Item: coeurl_sub_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Magic 15 -- Strength 6 -- Agility 1 -- Intelligence -2 -- Health Regen While Healing 1 -- Attack % 22 -- Attack Cap 80 -- Ranged ATT % 22 -- Ranged ATT Cap 80 -- Sleep Resist 5 ----------------------------------------- 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,5167); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 15); target:addMod(MOD_STR, 6); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 80); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 80); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 15); target:delMod(MOD_STR, 6); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 80); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 80); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
diezombies/MCGC
MCGC/c84130834.lua
3
2673
-- MC群的萌物 菜鸟 function c84130834.initial_effect(c) -- 召唤成功触发 local e1 = Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE + EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c84130834.target) e1:SetOperation(c84130834.operation) c:RegisterEffect(e1) end function c84130834.target(e, tp, eg, ep, ev, re, r, rp, chk, chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) end if chk == 0 then return Duel.GetMatchingGroupCount(Card.IsAbleToRemove, tp, LOCATION_GRAVE, 0, nil) > 0 end local g = Duel.SelectTarget(tp, Card.IsAbleToRemove, tp, LOCATION_GRAVE, 0, 1, 1, nil) Duel.SetOperationInfo(0, CATEGORY_REMOVE, g, g:GetCount(), nil, 0) end function c84130834.operation(e, tp, eg, ep, ev, re, r, rp) local g = Duel.GetChainInfo(0, CHAININFO_TARGET_CARDS) local c1 = g:GetFirst() -- 除外并且三回合回手 Duel.Remove(c1, POS_FACEUP, REASON_EFFECT + REASON_TEMPORARY) local e1 = Effect.CreateEffect(c1) e1:SetType(EFFECT_TYPE_FIELD + EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE + PHASE_STANDBY) e1:SetRange(LOCATION_REMOVED) e1:SetLabel(0) e1:SetCountLimit(1) e1:SetCondition(c84130834.thirdTriggerCondition) e1:SetOperation(c84130834.thirdTriggerOperation) c1:RegisterEffect(e1) -- 战破免疫三回合(参考棉花糖31305911) local c = e:GetHandler() local e2 = Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e2:SetValue(1) -- 并不知道这里的数值是什么意思,但是棉花糖里有 e2:SetReset(RESET_PHASE + PHASE_STANDBY + RESET_SELF_TURN, 3) c:RegisterEffect(e2) -- 送墓触发 local e3 = Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE + EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_TO_GRAVE) e3:SetReset(RESET_PHASE + PHASE_STANDBY + RESET_SELF_TURN, 3) e3:SetLabelObject(e1) e3:SetOperation(c84130834.toGraveTriggerOperation) c:RegisterEffect(e3) end function c84130834.thirdTriggerCondition(e, tp, eg, ep, ev, re, r, rp) return Duel.GetTurnPlayer() == tp end function c84130834.thirdTriggerOperation(e, tp, eg, ep, ev, re, r, rp) local count = e:GetLabel() if count == 2 then Duel.SendtoHand(e:GetHandler(), tp, REASON_EFFECT) e:Reset() else e:SetLabel(count + 1) end end function c84130834.toGraveTriggerOperation(e, tp, eg, ep, ev, re, r, rp) local te = e:GetLabelObject() Duel.SendtoDeck(te:GetHandler(), tp, nil, REASON_EFFECT) te:Reset() end
mit
pavouk/lgi
tests/glib.lua
2
3882
--[[-------------------------------------------------------------------------- LGI testsuite, GLib test suite. Copyright (c) 2013 Pavel Holejsovsky Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local lgi = require 'lgi' local check = testsuite.check -- Basic GLib testing local glib = testsuite.group.new('glib') function glib.timer() local Timer = lgi.GLib.Timer check(Timer.new) check(Timer.start) check(Timer.stop) check(Timer.continue) check(Timer.elapsed) check(Timer.reset) check(not Timer.destroy) local timer = Timer() check(Timer:is_type_of(timer)) timer = Timer.new() check(Timer:is_type_of(timer)) local el1, ms1 = timer:elapsed() check(type(el1) == 'number') check(type(ms1) == 'number') lgi.GLib.usleep(1000) -- wait one millisecond local el2, ms2 = timer:elapsed() check(el1 < el2) timer:stop() el2 = timer:elapsed() for i = 1, 1000000 do end check(timer:elapsed() == el2) end function glib.markup_base() local MarkupParser = lgi.GLib.MarkupParser local MarkupParseContext = lgi.GLib.MarkupParseContext local p = MarkupParser() local el, at = {}, {} function p.start_element(context, element_name, attrs) el[#el + 1] = element_name at[#at + 1] = attrs end function p.end_element(context) end function p.text(context, text, len) end function p.passthrough(context, text, len) end local pc = MarkupParseContext(p, {}) local ok, err = pc:parse([[ <map> <entry key='method' value='printf' /> </map> ]]) check(ok) check(#el == 2) check(el[1] == 'map') check(el[2] == 'entry') check(#at == 2) check(not next(at[1])) check(at[2].key == 'method') check(at[2].value == 'printf') end function glib.markup_error1() local MarkupParser = lgi.GLib.MarkupParser local MarkupParseContext = lgi.GLib.MarkupParseContext local saved_err local parser = MarkupParser { error = function(context, error) saved_err = error end, } local context = MarkupParseContext(parser, 0) local ok, err = context:parse('invalid>uh') check(not ok) check(err:matches(saved_err)) end function glib.markup_error2() local GLib = lgi.GLib local MarkupParser = GLib.MarkupParser local MarkupParseContext = GLib.MarkupParseContext local saved_err local parser = MarkupParser { error = function(context, error) saved_err = error end, start_element = function(context, element) error(GLib.MarkupError('UNKNOWN_ELEMENT', 'snafu %d', 1)) end, } local context = MarkupParseContext(parser, {}) local ok, err = context:parse('<e/>') check(not ok) check(err:matches(GLib.MarkupError, 'UNKNOWN_ELEMENT')) check(err.message == 'snafu 1') check(saved_err:matches(err)) end function glib.gsourcefuncs() local GLib = lgi.GLib local called local source_funcs = GLib.SourceFuncs { prepare = function(source, timeout) called = source return true, 42 end } local source = GLib.Source(source_funcs) local res, timeout = source_funcs.prepare(source) check(res == true) check(timeout == 42) check(called == source) end function glib.coroutine_related_crash() -- This test does not have a specific assert() or check() call. Instead it -- is a regression test: Once upon a time this caused a segmentation fault -- due to a use-after-free. local glib = require("lgi").GLib local mainloop = glib.MainLoop.new() coroutine.wrap(function() local co = coroutine.running() for i=1,100 do glib.timeout_add(glib.PRIORITY_DEFAULT, 0, function() coroutine.resume(co) return false end) coroutine.yield() end mainloop:quit() end)() mainloop:run() end
mit
kidaa/FFXIOrgins
scripts/globals/weaponskills/gust_slash.lua
4
1200
----------------------------------- -- Gust Slash -- Dagger weapon skill -- Skill level: 40 -- Deals wind elemental damage. Damage varies with TP. -- Will not stack with Sneak Attack. -- Aligned with the Breeze Gorget. -- Aligned with the Breeze Belt. -- Element: Wind -- Modifiers: DEX:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.0; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; 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); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/spells/bluemagic/frypan.lua
6
1057
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_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.78; params.tp150 = 1.78; params.tp300 = 1.78; params.azuretp = 1.78; params.duppercap = 75; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); -- Missing AOE STUN return damage; end;
gpl-3.0
jdgwartney/boundary-plugin-nginx
init.lua
1
3418
-- Copyright 2015 Boundary, 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. local framework = require('framework') local json = require('json') local url = require('url') local Plugin = framework.Plugin local WebRequestDataSource = framework.WebRequestDataSource local Accumulator = framework.Accumulator local auth = framework.util.auth local gsplit = framework.string.gsplit local isHttpSuccess = framework.util.isHttpSuccess local params = framework.params local options = url.parse(params.url) options.auth = auth(params.username, params.password) options.wait_for_end = true local ds = WebRequestDataSource:new(options) local acc = Accumulator:new() local plugin = Plugin:new(params, ds) local function parseText(body) local stats = {} for v in gsplit(body, "\n") do if v:find("Active connections:", 1, true) then local metric, connections = v:match('(%w+):%s*(%d+)') stats[metric:lower()] = tonumber(connections) elseif v:match("%s*(%d+)%s+(%d+)%s+(%d+)%s*$") then local accepts, handled, requests = v:match("%s*(%d+)%s+(%d+)%s+(%d+)%s*$") stats.accepts = tonumber(accepts) stats.handled = tonumber(handled) stats.requests = tonumber(requests) stats.not_handled = stats.accepts - stats.handled elseif v:match("(%w+):%s*(%d+)") then for metric, value in v:gmatch("(%w+):%s*(%d+)") do stats[metric:lower()] = tonumber(value) end end end return stats end local function parseJson(body) local parsed pcall(function () parsed = json.parse(body) end) return parsed end function plugin:onParseValues(data, extra) local metrics = {} if not isHttpSuccess(extra.status_code) then self:emitEvent('error', ('HTTP Request returned %d instead of OK. Please check NGINX Free stats endpoint.'):format(extra.status_code)) return end local stats = parseJson(data) if stats then self:emitEvent('info', 'You should install NGINX+ Plugin for non-free version of NGINX.') else stats = parseText(data) local function prepare () local handled = acc:accumulate('handled', stats.handled) local requests = acc:accumulate('requests', stats.requests) local reqs_per_connection = (handled > 0) and requests / handled or 0 metrics['NGINX_ACTIVE_CONNECTIONS'] = stats.connections metrics['NGINX_READING'] = stats.reading metrics['NGINX_WRITING'] = stats.writing metrics['NGINX_WAITING'] = stats.waiting metrics['NGINX_HANDLED'] = handled metrics['NGINX_NOT_HANDLED'] = stats.not_handled metrics['NGINX_REQUESTS'] = requests metrics['NGINX_REQUESTS_PER_CONNECTION'] = reqs_per_connection end if not pcall(prepare) then self:emitEvent('error', 'Can not parse metrics. Please check NGINX Free stats endpoint.') end end return metrics end plugin:run()
apache-2.0
kidaa/FFXIOrgins
scripts/zones/Windurst_Waters/npcs/Kipo-Opo.lua
12
1849
----------------------------------- -- Area: Windurst Waters -- NPC: Kipo-Opo -- Type: Cooking Adv. Image Support -- @pos -119.750 -5.239 64.500 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/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,4); local SkillLevel = player:getSkillLevel(16); local Cost = getAdvImageSupportCost(player,16); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_COOKING_IMAGERY) == false) then player:startEvent(0x271F,Cost,SkillLevel,0,495,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(0x271F,Cost,SkillLevel,0,495,player:getGil(),28589,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); local Cost = getAdvImageSupportCost(player,16); if (csid == 0x271F and option == 1) then player:delGil(Cost); player:messageSpecial(COOKING_SUPPORT,0,8,0); player:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,480); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Claymore.lua
2
1489
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Animated Claymore ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if(mob:AnimationSub() == 3) then SetDropRate(102,1574,100); else SetDropRate(102,1574,0); end target:showText(mob,ANIMATED_CLAYMORE_DIALOG); SpawnMob(17330365,120):updateEnmity(target); SpawnMob(17330366,120):updateEnmity(target); SpawnMob(17330367,120):updateEnmity(target); SpawnMob(17330372,120):updateEnmity(target); SpawnMob(17330373,120):updateEnmity(target); SpawnMob(17330374,120):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_CLAYMORE_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:showText(mob,ANIMATED_CLAYMORE_DIALOG+1); DespawnMob(17330365); DespawnMob(17330366); DespawnMob(17330367); DespawnMob(17330372); DespawnMob(17330373); DespawnMob(17330374); end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Giddeus/npcs/Treasure_Chest.lua
1
2660
----------------------------------- -- Area: Giddeus -- NPC: Treasure Chest -- -- @pos -158.563 0.999 -226.058 145 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Giddeus/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1026,1); -- Treasure Key --trade:hasItemQty(1115,1); -- Skeleton Key --trade:hasItemQty(1023,1); -- Living Key --trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1026,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZone(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1026); 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
smile-tmb/lua-mta-fairplay-roleplay
inventory/client/inventory.lua
1
14170
--[[ The MIT License (MIT) Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization) 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. ]] local screenWidth, screenHeight = guiGetScreenSize( ) local isInventoryShowing = false local categoryBoxScale = 80 local categoryBoxSpacing = 5 local categoryBoxSpaced = categoryBoxScale + categoryBoxSpacing local categoryBackgroundColor = tocolor( 5, 5, 5, 0.45 * 255 ) local categoryActiveColor = tocolor( 150, 150, 150, 0.5 * 255 ) local categoryHoverActiveColor = tocolor( 200, 200, 200, 0.5 * 255 ) local categoryHoverColor = tocolor( 5, 5, 5, 0.95 * 255 ) local categoryColor = tocolor( 5, 5, 5, 0.75 * 255 ) local categories = { { name = "Items", value = "All your miscellaneous items are here.", type = 1 }, { name = "Keys", value = "All your keys are in this keychain.", type = 2 }, { name = "Weapons", value = "All your weapons are in here.", type = 3 }, } local category = false local inventoryBoxScale = 60 local inventoryBoxSpacing = 4 local inventoryBoxSpaced = inventoryBoxScale + inventoryBoxSpacing local inventoryBackgroundColor = tocolor( 5, 5, 5, 0.55 * 255 ) local inventoryDeleteColor = tocolor( 100, 5, 5, 0.65 * 255 ) local inventoryShowColor = tocolor( 15, 15, 100, 0.65 * 255 ) local inventoryDropColor = tocolor( 5, 100, 5, 0.65 * 255 ) local inventoryColorEmpty = tocolor( 5, 5, 5, 0.45 * 255 ) local inventoryActiveColor = tocolor( 5, 5, 5, 0.85 * 255 ) local inventoryHoverColor = tocolor( 10, 10, 10, 0.8 * 255 ) local inventoryColor = tocolor( 5, 5, 5, 0.75 * 255 ) local inventoryDragAvailable = tocolor( 5, 100, 5, 0.65 * 255 ) local inventoryDragUnavailable = tocolor( 100, 5, 5, 0.65 * 255 ) local inventory = { } local inventoryRows = 4 local inventoryColumns = 0 local tooltipSpacing = 12 local tooltipColor = tocolor( 5, 5, 5, 0.75 * 255 ) local tooltipTextColor = tocolor( 250, 250, 250, 1.0 * 255 ) local maximumTriggerDistance = 12.725 local hoveringCategory = false local hoveringItem = false local hoveringWorldItem = false local dragTimer local function dxDrawTooltip( values, x, y ) local name = values.name or "[no title]" local value = values.value or false local output = name local width = dxGetTextWidth( output, 1, "clear" ) + ( tooltipSpacing * 2 ) if ( value ) then width = math.max( width, dxGetTextWidth( value, 1, "clear" ) + ( tooltipSpacing * 2 ) ) output = output .. "\n" .. value end local height = dxGetFontHeight( 1, "clear" ) height = ( value and 5 or 0 ) + height + tooltipSpacing * 2 local y = y + 15 local x = math.max( tooltipSpacing, math.min( x, screenWidth - width - tooltipSpacing ) ) local y = math.max( tooltipSpacing, math.min( y, screenHeight - height - tooltipSpacing ) ) dxDrawRectangle( x, y, width, height, tooltipColor ) dxDrawText( output, x, y, x + width, y + height, tooltipTextColor, 1, "clear", "center", "center", false, false, true ) end local function getWorldItemFromCursor( ) local cursorX, cursorY, worldX, worldY, worldZ = getCursorPosition( ) local cameraX, cameraY, cameraZ = getWorldFromScreenPosition( cursorX, cursorY, 0.1 ) local collision, hitX, hitY, hitZ, hitElement = processLineOfSight( cameraX, cameraY, cameraZ, worldX, worldY, worldZ, true, true, true, true, true, true, true, nil, false, true ) if ( hitElement ) and ( getElementParent( getElementParent( hitElement ) ) == getResourceRootElement( getResourceFromName( "items" ) ) ) and ( exports.common:getRealWorldItemID( hitElement ) ) then return hitElement elseif ( ( hitX ) and ( hitY ) and ( hitZ ) ) then hitElement = nil local x, y, z = nil local maxDistance = 0.35 for _, element in ipairs( getElementsByType( "object", getResourceRootElement( getResourceFromName( "items" ) ) ) ) do if ( exports.common:getRealWorldItemID( hitElement ) ) and ( isElementStreamedIn( element ) ) and ( isElementOnScreen( element ) ) then x, y, z = getElementPosition( element ) local distance = getDistanceBetweenPoints3D( x, y, z, hitX, hitY, hitZ ) if ( distance < maxDistance ) then hitElement = element maxDistance = distance end end end if ( hitElement ) then local x, y, z = getElementPosition( localPlayer ) return getDistanceBetweenPoints3D( x, y, z, getElementPosition( hitElement ) ) <= maximumTriggerDistance and hitElement end end return false end local function renderInventory( ) if ( not isInventoryShowing ) or ( not isCursorShowing( ) ) then return end inventory = { } local items = exports.items:getItems( localPlayer ) if ( items ) then for index, values in ipairs( items ) do if ( exports.items:getItemType( values.itemID ) == activeCategory ) then table.insert( inventory, values ) end end else return end inventoryColumns = math.ceil( #inventory / inventoryRows ) hoveringCategory = false hoveringItem = false local cursorX, cursorY, worldX, worldY, worldZ = getCursorPosition( ) cursorX, cursorY = cursorX * screenWidth, cursorY * screenHeight local x = screenWidth - categoryBoxSpaced - categoryBoxSpacing local y = ( screenHeight - #categories * categoryBoxSpaced - categoryBoxSpacing ) / 2 -- Category background rendering dxDrawRectangle( x, y, categoryBoxSpaced + categoryBoxSpacing, #categories * categoryBoxSpaced + categoryBoxSpacing, categoryBackgroundColor ) -- Category rendering for index, values in ipairs( categories ) do local x = x + categoryBoxSpacing local y = y + categoryBoxSpacing + categoryBoxSpaced * ( index - 1 ) local isHovering = exports.common:isWithin2DBounds( cursorX, cursorY, x, y, categoryBoxScale, categoryBoxScale ) local color = isHovering and ( activeCategory == index and categoryHoverActiveColor or categoryHoverColor ) or ( activeCategory == index and categoryActiveColor or categoryColor ) dxDrawRectangle( x, y, categoryBoxScale, categoryBoxScale, color ) dxDrawImage( x, y, categoryBoxScale, categoryBoxScale, "assets/-" .. index .. ".png" ) if ( isHovering ) then hoveringCategory = index end end local offsetX = categoryBoxSpaced + categoryBoxSpacing local bgX = screenWidth - offsetX - inventoryColumns * inventoryBoxSpaced - inventoryBoxSpacing local bgY = ( screenHeight - inventoryRows * inventoryBoxSpaced - inventoryBoxSpacing ) / 2 if ( activeCategory ) and ( inventoryColumns > 0 ) then if ( not draggingItem ) then -- Inventory background rendering dxDrawRectangle( bgX, bgY, inventoryColumns * inventoryBoxSpaced + inventoryBoxSpacing, inventoryRows * inventoryBoxSpaced + inventoryBoxSpacing, categoryBackgroundColor ) end -- Inventory items rendering for index = 1, inventoryColumns * inventoryRows do local column = math.floor( ( index - 1 ) / inventoryRows ) local row = ( index - 1 ) % inventoryRows local x = x - ( inventoryBoxSpaced + inventoryBoxSpacing ) - column * inventoryBoxSpaced + inventoryBoxSpacing local y = y + row * inventoryBoxSpaced + inventoryBoxSpacing local item = inventory[ index ] if ( item ) then local isHovering = exports.common:isWithin2DBounds( cursorX, cursorY, x, y, inventoryBoxScale, inventoryBoxScale ) local color = isHovering and ( getKeyState( "delete" ) and inventoryDeleteColor or ( ( ( getKeyState( "lctrl" ) ) or ( getKeyState( "rctrl" ) ) ) and inventoryDropColor or ( ( ( getKeyState( "lalt" ) ) or ( getKeyState( "ralt" ) ) ) and inventoryShowColor or inventoryHoverColor ) ) ) or inventoryColor if ( draggingItem == index ) then x, y = cursorX, cursorY local cameraX, cameraY, cameraZ = getWorldFromScreenPosition( cursorX, cursorY, 0.1 ) local collision, hitX, hitY, hitZ, hitElement = processLineOfSight( cameraX, cameraY, cameraZ, worldX, worldY, worldZ, true, true, true, true, true, false, true, false, localPlayer, false, true ) if ( collision ) and ( getDistanceBetweenPoints3D( hitX, hitY, hitZ, getElementPosition( localPlayer ) ) <= maximumTriggerDistance ) then color = inventoryDragAvailable else color = inventoryDragUnavailable end end dxDrawRectangle( x, y, inventoryBoxScale, inventoryBoxScale, color ) dxDrawImage( x, y, inventoryBoxScale, inventoryBoxScale, "assets/" .. item.itemID .. ( exports.items:getItemType( item.itemID ) == 3 and "_" .. exports.items:getWeaponID( item.itemValue ) or "" ) .. ".png" ) if ( isHovering ) then hoveringItem = index end if ( draggingItem == index ) then break end else dxDrawRectangle( x, y, inventoryBoxScale, inventoryBoxScale, inventoryColorEmpty ) end end end -- Hover tooltips if ( hoveringCategory ) then dxDrawTooltip( categories[ hoveringCategory ], cursorX, cursorY ) elseif ( hoveringItem ) then local item = inventory[ hoveringItem ] local name = exports.items:getItemName( item.itemID ) local value = tostring( item.itemValue ):len( ) > 0 and item.itemValue or false if ( exports.items:getItemType( item.itemID ) == 2 ) then if ( item.itemID == 6 ) then name = name .. " (PRN " .. ( value or "?" ) .. ")" elseif ( item.itemID == 7 ) then name = name .. " (VIN " .. ( value or "?" ) .. ")" end elseif ( exports.items:getItemType( item.itemID ) == 3 ) then local weaponName = exports.items:getWeaponName( value ) name = name .. " (" .. weaponName .. ")" end value = exports.items:getItemDescription( item.itemID ) dxDrawTooltip( { name = name, value = value }, cursorX, cursorY ) end end local function renderWorldItems( ) hoveringWorldItem = false if ( not isCursorShowing( ) ) or ( hoveringCategory ) or ( hoveringItem ) then return end local worldItem = getWorldItemFromCursor( ) if ( worldItem ) then hoveringWorldItem = worldItem local cursorX, cursorY = getCursorPosition( ) cursorX, cursorY = cursorX * screenWidth, cursorY * screenHeight local itemID = exports.common:getWorldItemID( worldItem ) local name = exports.items:getItemName( itemID ) local value = exports.common:getWorldItemValue( worldItem ) value = tostring( value ):len( ) > 0 and value or false if ( exports.items:getItemType( itemID ) == 2 ) then if ( itemID == 6 ) then name = name .. " (PRN " .. ( value or "?" ) .. ")" elseif ( itemID == 7 ) then name = name .. " (VIN " .. ( value or "?" ) .. ")" end elseif ( exports.items:getItemType( itemID ) == 3 ) then local weaponName = exports.items:getWeaponName( value ) name = name .. " (" .. weaponName .. ")" end value = exports.items:getItemDescription( itemID ) dxDrawTooltip( { name = name, value = value }, cursorX, cursorY ) end end function toggleInventory( ) local fn = isInventoryShowing and removeEventHandler or addEventHandler fn( "onClientHUDRender", root, renderInventory ) isInventoryShowing = not isInventoryShowing showCursor( isInventoryShowing ) draggingItem = false end addEventHandler( "onClientClick", root, function( button, state, cursorX, cursorY, worldX, worldY, worldZ, clickedElement ) if ( not isInventoryShowing ) then return end if ( button == "left" ) then if ( state == "down" ) then if ( hoveringItem ) then if ( isTimer( dragTimer ) ) then resetTimer( dragTimer ) else dragTimer = setTimer( function( hoveredItem ) if ( hoveringItem == hoveredItem ) then draggingItem = hoveringItem end end, 185, 1, hoveringItem ) end end else if ( isTimer( dragTimer ) ) then killTimer( dragTimer ) end if ( draggingItem ) then if ( getDistanceBetweenPoints3D( worldX, worldY, worldZ, getElementPosition( localPlayer ) ) <= maximumTriggerDistance ) then triggerServerEvent( "items:drop", localPlayer, inventory[ draggingItem ], worldX, worldY, worldZ ) end draggingItem = false elseif ( hoveringCategory ) then activeCategory = hoveringCategory elseif ( hoveringItem ) then local item = inventory[ hoveringItem ] if ( getKeyState( "delete" ) ) then triggerServerEvent( "items:delete", localPlayer, item ) elseif ( getKeyState( "lctrl" ) ) or ( getKeyState( "rctrl" ) ) then local x, y, z = getElementPosition( localPlayer ) z = getGroundPosition( x, y, z + 2 ) triggerServerEvent( "items:drop", localPlayer, item, x, y, z ) elseif ( getKeyState( "lalt" ) ) or ( getKeyState( "ralt" ) ) then triggerServerEvent( "items:show", localPlayer, item ) else triggerServerEvent( "items:use", localPlayer, item ) end elseif ( hoveringWorldItem ) then triggerServerEvent( "items:pickup", localPlayer, hoveringWorldItem ) end end elseif ( button == "right" ) then draggingItem = false end end ) addEventHandler( "onClientResourceStart", resourceRoot, function( ) bindKey( "I", "down", "inventory" ) addEventHandler( "onClientRender", root, renderWorldItems ) end ) addCommandHandler( "inventory", function( cmd ) if ( exports.common:isPlayerPlaying( localPlayer ) ) or ( isInventoryShowing ) then toggleInventory( ) end end )
mit
tboox/xmake-repo
packages/b/bzip2/xmake.lua
1
1161
package("bzip2") set_homepage("https://en.wikipedia.org/wiki/Bzip2") set_description("Freely available high-quality data compressor.") set_urls("https://ftp.osuosl.org/pub/clfs/conglomeration/bzip2/bzip2-$(version).tar.gz", "https://fossies.org/linux/misc/bzip2-$(version).tar.gz") add_versions("1.0.6", "a2848f34fcd5d6cf47def00461fcb528a0484d8edef8208d6d2e2909dc61d9cd") on_load("windows", function (package) package:addenv("PATH", "bin") package:add("links", "libbz2") end) on_install("windows", function (package) io.gsub("makefile.msc", "%-MD", "-" .. package:config("vs_runtime")) os.vrunv("nmake", {"-f", "makefile.msc"}) os.cp("libbz2.lib", package:installdir("lib")) os.cp("*.h", package:installdir("include")) os.cp("*.exe", package:installdir("bin")) end) on_install("macosx", "linux", function (package) os.vrunv("make", {"install", "PREFIX=" .. package:installdir()}) end) on_test(function (package) os.vrun("bzip2 --help") assert(package:has_cfuncs("BZ2_bzCompressInit", {includes = "bzlib.h"})) end)
apache-2.0
OmegaBolt/OpenRA
lua/stacktraceplus.lua
59
12006
-- tables local _G = _G local string, io, debug, coroutine = string, io, debug, coroutine -- functions local tostring, print, require = tostring, print, require local next, assert = next, assert local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs local error = error assert(debug, "debug table must be available at this point") local io_open = io.open local string_gmatch = string.gmatch local string_sub = string.sub local table_concat = table.concat local _M = { max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' } -- this tables should be weak so the elements in them won't become uncollectable local m_known_tables = { [_G] = "_G (global table)" } local function add_known_module(name, desc) local ok, mod = pcall(require, name) if ok then m_known_tables[mod] = desc end end add_known_module("string", "string module") add_known_module("io", "io module") add_known_module("os", "os module") add_known_module("table", "table module") add_known_module("math", "math module") add_known_module("package", "package module") add_known_module("debug", "debug module") add_known_module("coroutine", "coroutine module") -- lua5.2 add_known_module("bit32", "bit32 module") -- luajit add_known_module("bit", "bit module") add_known_module("jit", "jit module") local m_user_known_tables = {} local m_known_functions = {} for _, name in ipairs{ -- Lua 5.2, 5.1 "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", -- Lua 5.1 "gcinfo", "getfenv", "loadstring", "module", "newproxy", "setfenv", "unpack", -- TODO: add table.* etc functions } do if _G[name] then m_known_functions[_G[name]] = name end end local m_user_known_functions = {} local function safe_tostring (value) local ok, err = pcall(tostring, value) if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end end -- Private: -- Parses a line, looking for possible function definitions (in a very naïve way) -- Returns '(anonymous)' if no function name was found in the line local function ParseLine(line) assert(type(line) == "string") --print(line) local match = line:match("^%s*function%s+(%w+)") if match then --print("+++++++++++++function", match) return match end match = line:match("^%s*local%s+function%s+(%w+)") if match then --print("++++++++++++local", match) return match end match = line:match("^%s*local%s+(%w+)%s+=%s+function") if match then --print("++++++++++++local func", match) return match end match = line:match("%s*function%s*%(") -- this is an anonymous function if match then --print("+++++++++++++function2", match) return "(anonymous)" end return "(anonymous)" end -- Private: -- Tries to guess a function's name when the debug info structure does not have it. -- It parses either the file or the string where the function is defined. -- Returns '?' if the line where the function is defined is not found local function GuessFunctionName(info) --print("guessing function name") if type(info.source) == "string" and info.source:sub(1,1) == "@" then local file, err = io_open(info.source:sub(2), "r") if not file then print("file not found: "..tostring(err)) -- whoops! return "?" end local line for i = 1, info.linedefined do line = file:read("*l") end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) else local line local lineNumber = 0 for l in string_gmatch(info.source, "([^\n]+)\n-") do lineNumber = lineNumber + 1 if lineNumber == info.linedefined then line = l break end end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) end end --- -- Dumper instances are used to analyze stacks and collect its information. -- local Dumper = {} Dumper.new = function(thread) local t = { lines = {} } for k,v in pairs(Dumper) do t[k] = v end t.dumping_same_thread = (thread == coroutine.running()) -- if a thread was supplied, bind it to debug.info and debug.get -- we also need to skip this additional level we are introducing in the callstack (only if we are running -- in the same thread we're inspecting) if type(thread) == "thread" then t.getinfo = function(level, what) if t.dumping_same_thread and type(level) == "number" then level = level + 1 end return debug.getinfo(thread, level, what) end t.getlocal = function(level, loc) if t.dumping_same_thread then level = level + 1 end return debug.getlocal(thread, level, loc) end else t.getinfo = debug.getinfo t.getlocal = debug.getlocal end return t end -- helpers for collecting strings to be used when assembling the final trace function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table_concat(self.lines) end --- -- Private: -- Iterates over the local variables of a given function. -- -- @param level The stack level where the function is. -- function Dumper:DumpLocals (level) local prefix = "\t " local i = 1 if self.dumping_same_thread then level = level + 1 end local name, value = self.getlocal(level, i) if not name then return end self:add("\tLocal variables:\r\n") while name do if type(value) == "number" then self:add_f("%s%s = number: %g\r\n", prefix, name, value) elseif type(value) == "boolean" then self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) elseif type(value) == "string" then self:add_f("%s%s = string: %q\r\n", prefix, name, value) elseif type(value) == "userdata" then self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) elseif type(value) == "nil" then self:add_f("%s%s = nil\r\n", prefix, name) elseif type(value) == "table" then if m_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) elseif m_user_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) else local txt = "{" for k,v in pairs(value) do txt = txt..safe_tostring(k)..":"..safe_tostring(v) if #txt > _M.max_tb_output_len then txt = txt.." (more...)" break end if next(value, k) then txt = txt..", " end end self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") end elseif type(value) == "function" then local info = self.getinfo(value, "nS") local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] if info.what == "C" then self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) else local source = info.short_src if source:sub(2,7) == "string" then source = source:sub(9) end --for k,v in pairs(info) do print(k,v) end fun_name = fun_name or GuessFunctionName(info) self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) end elseif type(value) == "thread" then self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) end i = i + 1 name, value = self.getlocal(level, i) end end --- -- Public: -- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. -- This function is suitable to be used as an error handler with pcall or xpcall -- -- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) -- @param message An optional error string or object. -- @param level An optional number telling at which level to start the traceback (default is 1) -- -- Returns a string with the stack trace and a string with the original error. -- function _M.stacktrace(thread, message, level) if type(thread) ~= "thread" then -- shift parameters left thread, message, level = nil, thread, message end thread = thread or coroutine.running() level = level or 1 local dumper = Dumper.new(thread) local original_error if type(message) == "table" then dumper:add("an error object {\r\n") local first = true for k,v in pairs(message) do if first then dumper:add(" ") first = false else dumper:add(",\r\n ") end dumper:add(safe_tostring(k)) dumper:add(": ") dumper:add(safe_tostring(v)) end dumper:add("\r\n}") original_error = dumper:concat_lines() elseif type(message) == "string" then dumper:add(message) original_error = message end dumper:add("\r\n") dumper:add[[ Stack Traceback =============== ]] --print(error_message) local level_to_show = level if dumper.dumping_same_thread then level = level + 1 end local info = dumper.getinfo(level, "nSlf") while info do if info.what == "main" then if string_sub(info.source, 1, 1) == "@" then dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline) else dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline) end elseif info.what == "C" then --print(info.namewhat, info.name) --for k,v in pairs(info) do print(k,v, type(v)) end local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) elseif info.what == "tail" then --print("tail") --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) dumper:add_f("(%d) tail call\r\n", level_to_show) dumper:DumpLocals(level) elseif info.what == "Lua" then local source = info.short_src local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name if source:sub(2, 7) == "string" then source = source:sub(9) end local was_guessed = false if not function_name or function_name == "?" then --for k,v in pairs(info) do print(k,v, type(v)) end function_name = GuessFunctionName(info) was_guessed = true end -- test if we have a file name local function_type = (info.namewhat == "") and "function" or info.namewhat if info.source and info.source:sub(1, 1) == "@" then dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") elseif info.source and info.source:sub(1,1) == '#' then dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") else dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source) end dumper:DumpLocals(level) else dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) end level = level + 1 level_to_show = level_to_show + 1 info = dumper.getinfo(level, "nSlf") end return dumper:concat_lines(), original_error end -- -- Adds a table to the list of known tables function _M.add_known_table(tab, description) if m_known_tables[tab] then error("Cannot override an already known table") end m_user_known_tables[tab] = description end -- -- Adds a function to the list of known functions function _M.add_known_function(fun, description) if m_known_functions[fun] then error("Cannot override an already known function") end m_user_known_functions[fun] = description end return _M
gpl-3.0
Clavus/LD32
engine/lib/loveloader/love-loader.lua
7
6444
require "love.filesystem" require "love.image" require "love.audio" require "love.sound" local loader = { _VERSION = 'love-loader v2.0.2', _DESCRIPTION = 'Threaded resource loading for LÖVE', _URL = 'https://github.com/kikito/love-loader', _LICENSE = [[ MIT LICENSE Copyright (c) 2014 Enrique García Cota, Tanner Rogalsky 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. ]] } local resourceKinds = { image = { requestKey = "imagePath", resourceKey = "imageData", constructor = love.image.newImageData, postProcess = function(data) return love.graphics.newImage(data) end }, source = { requestKey = "sourcePath", resourceKey = "source", constructor = function(path) return love.audio.newSource(path) end }, font = { requestKey = "fontPath", resourceKey = "fontData", constructor = function(path) -- we don't use love.filesystem.newFileData directly here because there -- are actually two arguments passed to this constructor which in turn -- invokes the wrong love.filesystem.newFileData overload return love.filesystem.newFileData(path) end, postProcess = function(data, resource) local path, size = unpack(resource.requestParams) return love.graphics.newFont(data, size) end }, stream = { requestKey = "streamPath", resourceKey = "stream", constructor = function(path) return love.audio.newSource(path, "stream") end }, soundData = { requestKey = "soundDataPathOrDecoder", resourceKey = "soundData", constructor = love.sound.newSoundData }, imageData = { requestKey = "imageDataPath", resourceKey = "rawImageData", constructor = love.image.newImageData } } local CHANNEL_PREFIX = "loader_" local loaded = ... if loaded == true then local requestParams, resource local done = false local doneChannel = love.thread.getChannel(CHANNEL_PREFIX .. "is_done") while not done do for _,kind in pairs(resourceKinds) do local loader = love.thread.getChannel(CHANNEL_PREFIX .. kind.requestKey) requestParams = loader:pop() if requestParams then resource = kind.constructor(unpack(requestParams)) local producer = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey) producer:push(resource) end end done = doneChannel:pop() end else local pending = {} local callbacks = {} local resourceBeingLoaded local pathToThisFile = (...):gsub("%.", "/") .. ".lua" local function shift(t) return table.remove(t,1) end local function newResource(kind, holder, key, ...) pending[#pending + 1] = { kind = kind, holder = holder, key = key, requestParams = {...} } end local function getResourceFromThreadIfAvailable() local data, resource for name,kind in pairs(resourceKinds) do local channel = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey) data = channel:pop() if data then resource = kind.postProcess and kind.postProcess(data, resourceBeingLoaded) or data resourceBeingLoaded.holder[resourceBeingLoaded.key] = resource loader.loadedCount = loader.loadedCount + 1 callbacks.oneLoaded(resourceBeingLoaded.kind, resourceBeingLoaded.holder, resourceBeingLoaded.key) resourceBeingLoaded = nil end end end local function requestNewResourceToThread() resourceBeingLoaded = shift(pending) local requestKey = resourceKinds[resourceBeingLoaded.kind].requestKey local channel = love.thread.getChannel(CHANNEL_PREFIX .. requestKey) channel:push(resourceBeingLoaded.requestParams) end local function endThreadIfAllLoaded() if not resourceBeingLoaded and #pending == 0 then love.thread.getChannel(CHANNEL_PREFIX .. "is_done"):push(true) callbacks.allLoaded() end end ----------------------------------------------------- function loader.newImage(holder, key, path) newResource('image', holder, key, path) end function loader.newFont(holder, key, path, size) newResource('font', holder, key, path, size) end function loader.newSource(holder, key, path, sourceType) local kind = (sourceType == 'stream' and 'stream' or 'source') newResource(kind, holder, key, path) end function loader.newSoundData(holder, key, pathOrDecoder) newResource('soundData', holder, key, pathOrDecoder) end function loader.newImageData(holder, key, path) newResource('imageData', holder, key, path) end function loader.start(allLoadedCallback, oneLoadedCallback) callbacks.allLoaded = allLoadedCallback or function() end callbacks.oneLoaded = oneLoadedCallback or function() end local thread = love.thread.newThread(pathToThisFile) loader.loadedCount = 0 loader.resourceCount = #pending thread:start(true) loader.thread = thread end function loader.update() if loader.thread then if loader.thread:isRunning() then if resourceBeingLoaded then getResourceFromThreadIfAvailable() elseif #pending > 0 then requestNewResourceToThread() else endThreadIfAllLoaded() end else local errorMessage = loader.thread:getError() assert(not errorMessage, errorMessage) end end end return loader end
mit
mys007/nn
View.lua
41
2232
local View, parent = torch.class('nn.View', 'nn.Module') function View:__init(...) parent.__init(self) if select('#', ...) == 1 and torch.typename(select(1, ...)) == 'torch.LongStorage' then self.size = select(1, ...) else self.size = torch.LongStorage({...}) end self.numElements = 1 local inferdim = false for i = 1,#self.size do local szi = self.size[i] if szi >= 0 then self.numElements = self.numElements * self.size[i] else assert(szi == -1, 'size should be positive or -1') assert(not inferdim, 'only one dimension can be at -1') inferdim = true end end self.output = nil self.gradInput = nil self.numInputDims = nil end function View:setNumInputDims(numInputDims) self.numInputDims = numInputDims return self end local function batchsize(input, size, numInputDims, numElements) local ind = input:nDimension() local isz = input:size() local maxdim = numInputDims and numInputDims or ind local ine = 1 for i=ind,ind-maxdim+1,-1 do ine = ine * isz[i] end if ine % numElements ~= 0 then error(string.format( 'input view (%s) and desired view (%s) do not match', table.concat(input:size():totable(), 'x'), table.concat(size:totable(), 'x'))) end -- the remainder is either the batch... local bsz = ine / numElements -- ... or the missing size dim for i=1,size:size() do if size[i] == -1 then bsz = 1 break end end -- for dim over maxdim, it is definitively the batch for i=ind-maxdim,1,-1 do bsz = bsz * isz[i] end -- special card if bsz == 1 and (not numInputDims or input:nDimension() <= numInputDims) then return end return bsz end function View:updateOutput(input) local bsz = batchsize(input, self.size, self.numInputDims, self.numElements) if bsz then self.output = input:view(bsz, table.unpack(self.size:totable())) else self.output = input:view(self.size) end return self.output end function View:updateGradInput(input, gradOutput) self.gradInput = gradOutput:view(input:size()) return self.gradInput end
bsd-3-clause
kidaa/FFXIOrgins
scripts/zones/Lower_Jeuno/npcs/Tuh_Almobankha.lua
1
3746
----------------------------------- -- Area: Lower Jeuno -- NPC: Tuh Almobankha -- Title Change NPC -- @pos -14 0 -61 245 ----------------------------------- require("scripts/globals/titles"); local title2 = { BROWN_MAGE_GUINEA_PIG , BROWN_MAGIC_BYPRODUCT , RESEARCHER_OF_CLASSICS , TORCHBEARER , FORTUNETELLER_IN_TRAINING , CHOCOBO_TRAINER , CLOCK_TOWER_PRESERVATIONIST , LIFE_SAVER , CARD_COLLECTOR , TWOS_COMPANY , TRADER_OF_ANTIQUITIES , GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN , TENSHODO_MEMBER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { ACTIVIST_FOR_KINDNESS , ENVOY_TO_THE_NORTH , EXORCIST_IN_TRAINING , FOOLS_ERRAND_RUNNER , STREET_SWEEPER , MERCY_ERRAND_RUNNER , BELIEVER_OF_ALTANA , TRADER_OF_MYSTERIES , WANDERING_MINSTREL , ANIMAL_TRAINER , HAVE_WINGS_WILL_FLY , ROD_RETRIEVER , DESTINED_FELLOW , TROUPE_BRILIOTH_DANCER , PROMISING_DANCER , STARDUST_DANCER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { TIMEKEEPER , BRINGER_OF_BLISS , PROFESSIONAL_LOAFER , TRADER_OF_RENOWN , HORIZON_BREAKER , SUMMIT_BREAKER , BROWN_BELT , DUCAL_DUPE , CHOCOBO_LOVE_GURU , PICKUP_ARTIST , WORTHY_OF_TRUST , A_FRIEND_INDEED , CHOCOROOKIE , CRYSTAL_STAKES_CUPHOLDER , WINNING_OWNER , VICTORIOUS_OWNER , TRIUMPHANT_OWNER , HIGH_ROLLER , FORTUNES_FAVORITE , CHOCOCHAMPION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_BEASTMASTER_EXCELLENCE , PARAGON_OF_BARD_EXCELLENCE , SKY_BREAKER , BLACK_BELT , GREEDALOX , CLOUD_BREAKER , STAR_BREAKER , ULTIMATE_CHAMPION_OF_THE_WORLD , DYNAMISJEUNO_INTERLOPER , DYNAMISBEAUCEDINE_INTERLOPER , DYNAMISXARCABARD_INTERLOPER , DYNAMISQUFIM_INTERLOPER , CONQUEROR_OF_FATE , SUPERHERO , SUPERHEROINE , ELEGANT_DANCER , DAZZLING_DANCE_DIVA , GRIMOIRE_BEARER , FELLOW_FORTIFIER , BUSHIN_ASPIRANT , BUSHIN_RYU_INHERITOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { GRAND_GREEDALOX , SILENCER_OF_THE_ECHO , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x271E,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x271E) then if(option > 0 and option <29) then if (player:delGil(400)) then player:setTitle( title2[option] ) end elseif(option > 256 and option <285) then if (player:delGil(500)) then player:setTitle( title3[option - 256] ) end elseif(option > 512 and option < 541) then if (player:delGil(600)) then player:setTitle( title4[option - 512] ) end elseif(option > 768 and option <797) then if (player:delGil(700)) then player:setTitle( title5[option - 768] ) end elseif(option > 1024 and option < 1053) then if (player:delGil(800)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/death_chakram.lua
2
1043
----------------------------------------- -- ID: 18231 -- Item: Death Chakram -- Enchantment: MP +5% -- Durration: 30 Mins ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if(target:hasStatusEffect(EFFECT_ENCHANTMENT) == false) then target:addStatusEffect(EFFECT_ENCHANTMENT,0,0,1800,18231); end; end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MMP, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MMP, 5); end;
gpl-3.0
alikineh/ali_kineh
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- 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 request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) 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) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
kidaa/FFXIOrgins
scripts/zones/Temenos/mobs/Goblin_Slaughterman.lua
1
1026
----------------------------------- -- Area: Temenos N T -- NPC: Goblin_Slaughterman ----------------------------------- 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) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if(mobID ==16928773)then GetNPCByID(16928768+18):setPos(330,70,468); GetNPCByID(16928768+18):setStatus(STATUS_NORMAL); elseif(mobID ==16928772)then GetNPCByID(16928770+450):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Beadeaux/Zone.lua
4
3060
----------------------------------- -- -- Zone: Beadeaux (147) -- ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Beadeaux/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- The Afflictor System (RegionID, X, Radius, Z) zone:registerRegion(1, -163, 10, -137, 0,0,0); -- 17379798 The Afflictor zone:registerRegion(2, -209, 10, -131, 0,0,0); -- 17379799 The Afflictor zone:registerRegion(3, -140, 10, 20, 0,0,0); -- 17379800 The Afflictor zone:registerRegion(4, 261, 10, 140, 0,0,0); -- 17379801 The Afflictor zone:registerRegion(5, 340, 10, 100, 0,0,0); -- 17379802 The Afflictor zone:registerRegion(6, 380, 10, 60, 0,0,0); -- 17379803 The Afflictor end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(387.382,38.029,19.694,3); end if(prevZone == 109) then if(player:getQuestStatus(BASTOK, BLADE_OF_DARKNESS) == QUEST_ACCEPTED and player:getVar("ChaosbringerKills") >= 100) then cs = 0x0079; elseif(player:getCurrentMission(BASTOK) == THE_FOUR_MUSKETEERS and player:getVar("MissionStatus") == 1) then cs = 0x0078; elseif(player:getMainJob() == 8 and player:getQuestStatus(BASTOK,DARK_PUPPET) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,BLADE_OF_EVIL) == QUEST_AVAILABLE) then cs = 0x007a; end end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) if (region:GetRegionID() <= 6) then if (player:hasStatusEffect(EFFECT_CURSE_I) == false and player:hasStatusEffect(EFFECT_SILENCE) == false) then player:addStatusEffect(EFFECT_CURSE_I,50,0,300); end end end; function onRegionLeave(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 == 0x0079) then player:unlockJob(8); player:addTitle(DARK_SIDER); player:setVar("ZeruhnMines_Zeid_CS", 0); player:messageSpecial(YOU_CAN_NOW_BECOME_A_DARK_KNIGHT); player:completeQuest(BASTOK, BLADE_OF_DARKNESS); elseif(csid == 0x0078) then player:setVar("MissionStatus",2); player:setPos(-297, 1, 96, 1); elseif(csid == 0x007a) then player:addQuest(BASTOK,BLADE_OF_EVIL); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/weaponskills/stardiver.lua
6
1384
----------------------------------- -- Stardiver -- Polearm weapon skill -- Skill Level: MERIT -- Delivers a fourfold attack. Damage varies with TP. -- Will stack with Sneak Attack. reduces params.crit hit evasion by 5% -- Element: None -- Modifiers: STR:85% //actually 17~85% -- 100%TP 200%TP 300%TP -- 0.75 0.84375 0.9375 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 4; params.ftp100 = 0.75; params.ftp200 = 0.84375; params.ftp300 = 0.9375; params.str_wsc = 0.85; 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.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 and (target:hasStatusEffect(EFFECT_CRIT_HIT_EVASION_DOWN) == false) then target:addStatusEffect(EFFECT_CRIT_HIT_EVASION_DOWN, 5, 0, 60); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/bowl_of_tomato_soup.lua
2
1437
----------------------------------------- -- ID: 4420 -- Item: bowl_of_tomato_soup -- Food Effect: 3Hrs, All Races ----------------------------------------- -- Agility 3 -- Vitality -1 -- HP Recovered While Healing 5 -- Ranged Accuracy % 9 (cap 15) ----------------------------------------- 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,10800,4420); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -1); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_FOOD_RACCP, 9); target:addMod(MOD_FOOD_RACC_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -1); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_FOOD_RACCP, 9); target:delMod(MOD_FOOD_RACC_CAP, 15); end;
gpl-3.0
TeleMafia/mafia
libs/lua-redis.lua
1
35758
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) function get_text_msg() MSG = '\n🔖support: @'..string.reverse("AIFAMHCIR") return MSG end -- get_text_msg = '\n🔖support: @'..string.reverse("AIFAMHCIR") do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-3.0
nenau/naev
dat/missions/empire/longdistanceshipping/emp_longdistancecargo4.lua
2
3326
--[[ Fourth diplomatic mission to Frontier space that opens up the Empire long-distance cargo missions. Author: micahmumper ]]-- include "dat/scripts/numstring.lua" include "dat/scripts/jumpdist.lua" bar_desc = _("Lieutenant Czesc from the Empire Aramda Shipping Division is sitting at the bar.") misn_title = _("Frontier Long Distance Recruitment") misn_reward = _("50000 credits") misn_desc = _("Deliver a shipping diplomat for the Empire to The Frontier Council in Gilligan's Light system.") title = {} title[1] = _("Spaceport Bar") title[2] = _("Frontier Alliance Long Distance Recruitment") title[3] = _("Mission Accomplished") text = {} text[1] = _([["We have to stop running into each other like this." Lieutenant Czesc laughs at his joke. "Just kidding, you know I owe you for helping set up these contracts. So far, everything has been moving smoothly on our end. We're hoping to extend our relations to the Frontier Alliance. You know the drill by this point. Ready to help?"]]) text[2] = _([["I applaud your commitment," Lieutenant Czesc says, "and I know these aren't the most exciting missions, but they're most useful. The frontier can be a bit dangerous, so make sure you're prepared. You need to drop the bureaucrat off at The Frontier Council in Gilligan's Light system. After this, there should only be one more faction to bring into the fold. I expect to see you again soon."]]) text[3] = _([[You deliver the diplomat to The Frontier Council, and she hands you a credit chip. Thankfully, Lieutenant Czesc mentioned only needing your assistance again for one more mission. This last bureaucrat refused to stay in her quarters, preferring to hang out on the bridge and give you the ins and outs of Empire bureaucracy. Only your loyalty to the Empire stopped you from sending her out into the vacuum of space.]]) function create () -- Note: this mission does not make any system claims. -- Get the planet and system at which we currently are. startworld, startworld_sys = planet.cur() -- Set our target system and planet. targetworld_sys = system.get("Gilligan's Light") targetworld = planet.get("The Frontier Council") misn.setNPC( _("Lieutenant"), "empire/unique/czesc" ) misn.setDesc( bar_desc ) end function accept () -- Set marker to a system, visible in any mission computer and the onboard computer. misn.markerAdd( targetworld_sys, "low") ---Intro Text if not tk.yesno( title[1], text[1] ) then misn.finish() end -- Flavour text and mini-briefing tk.msg( title[2], text[2] ) ---Accept the mission misn.accept() -- Description is visible in OSD and the onboard computer, it shouldn't be too long either. reward = 50000 misn.setTitle(misn_title) misn.setReward(misn_reward) misn.setDesc( string.format( misn_desc, targetworld:name(), targetworld_sys:name() ) ) misn.osdCreate(title[2], {misn_desc}) -- Set up the goal hook.land("land") person = misn.cargoAdd( "Person" , 0 ) end function land() if planet.cur() == targetworld then misn.cargoRm( person ) player.pay( reward ) -- More flavour text tk.msg( title[3], text[3] ) faction.modPlayerSingle( "Empire",3 ); misn.finish(true) end end function abort() misn.finish(false) end
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/items/hard-boiled_egg.lua
1
1147
----------------------------------------- -- ID: 4409 -- Item: hard-boiled_egg -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 10 -- Magic 10 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4409); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); end;
gpl-3.0
nenau/naev
dat/missions/pirate/hitman3.lua
2
6225
--[[ Pirate Hitman 3 A one time random pirate hitman mission that gets you pirate landing permissions Author: nloewen --]] -- Bar information bar_desc = _("A well-dressed young businessman. He looks out of place, contrasting sharply with most of the bar's clientele") -- Mission details misn_title = _("Pirate Hitman 3") misn_reward = _("More easy money.") misn_desc = _("The Empire patrol vessel known as %s must be terminated. It was last seen near the %s system.") misn_desc2 = _("Return to %s to get your rewards.") -- Text title = {} text = {} title[1] = _("Spaceport Bar") title[2] = _("Mission Complete") text[1] = _([[As you approach, the man merely glances at you before pushing out a chair for you. "Hello. A certain trader associate of mine has recommended your services." You nod knowingly, and he continues, "A certain Empire pilot has been... consistent in refusing our bribes. We'd like to be rid of him as soon as possible. Are you up for it?]]) text[2] = _([["Excellent. If you're successful in removing him, you will of course be rewarded." His demeanour shifts slightly before he continues, "Of course, we are not the forgiving type. If you rat us out, we will find you. If you fail, well, I suppose you'll be sent to one of the Empire's penal colonies. That said, you've performed admirably for my associate, so I trust I'll see you again soon."]]) text[3] = _([[The businessman is waiting for you. "Ah, you've returned. I've already received the good news from my associates who monitor the Empire communications band. Here's your pay. There's always work for a competent pilot; I look forward to working with you again." With that, the man walks away, disappearing into a crowd. You wonder how much "business" this supposed businessman is involved in.]]) msg = {} msg[1] = _("Target destroyed. Mission objective updated") msg[2] = _("Target has jumped. Persue %s!") include("dat/missions/pirate/common.lua") -- Scripts we need include("pilot/empire.lua") include("dat/scripts/jumpdist.lua") function create () -- Note: this mission does not make any system claims. -- Create the target pirate emp_name, emp_ship, emp_outfits = emp_generate() -- Get target system near_sys = get_emp_system( system.cur() ) -- Spaceport bar stuff misn.setNPC( _("Young Businessman"), "neutral/unique/youngbusinessman") misn.setDesc( bar_desc ) --some other stuff misn_base, misn_base_sys = planet.cur() end function businessman_timer () hook.timer( 5000, "accept" ) end --[[ Mission entry point. --]] function accept () -- Mission details: if not tk.yesno( title[1], string.format( text[1], emp_name, credits, near_sys:name() ) ) then misn.finish() end misn.accept() -- Set mission details misn.setTitle( string.format( misn_title, near_sys:name()) ) misn.setReward( string.format( misn_reward, credits) ) misn.setDesc( string.format( misn_desc, emp_name, near_sys:name() ) ) misn_marker = misn.markerAdd( near_sys, "low" ) misn.osdCreate(misn_title, {misn_desc:format(emp_name, near_sys:name())}) -- Some flavour text tk.msg( title[1], text[2] ) -- Set hooks hook.enter("sys_enter") end -- Gets a empireish system function get_emp_system( sys ) local s = { } local dist = 1 local target = {} while #target == 0 do target = getsysatdistance( sys, dist, dist+1, emp_systems_filter, s ) dist = dist + 2 end return target[rnd.rnd(1,#target)] end function emp_systems_filter( sys, data ) -- Must have Empire if not sys:presences()["Empire"] then return false end -- Must not be safe if sys:presence("friendly") > 3.*sys:presence("hostile") then return false end -- Must not already be in list local found = false for k,v in ipairs(data) do if sys == v then return false end end return true end function misn_finished() player.msg( msg[1] ) misn.setDesc( string.format( misn_desc2, misn_base:name(), misn_base_sys:name() ) ) misn.markerRm( misn_marker ) misn_marker = misn.markerAdd( misn_base_sys, "low" ) misn.osdCreate(misn_title, {misn_desc2:format(misn_base:name())}) hook.land("landed") end -- Player won, gives rewards. function landed () if planet.cur() == misn_base then tk.msg(title[2], text[3]) -- Give rewards faction.modPlayerSingle( "Pirate", 5 ) player.pay( 100000 ) -- 100k pir_modDecayFloor( 5 ) -- Finish mission misn.finish(true) end end -- Entering a system function sys_enter () cur_sys = system.cur() -- Check to see if reaching target system if cur_sys == near_sys then -- Create the badass enemy p = pilot.add(emp_ship) emp = p[1] emp:rename(emp_name) emp:setHostile() emp:rmOutfit("all") -- Start naked pilot_outfitAddSet( emp, emp_outfits ) hook.pilot( emp, "death", "misn_finished" ) hook.pilot( emp, "jump", "emp_jump" ) end end -- Empire patrol jumped away function emp_jump () player.msg( string.format(msg[2], emp_name) ) -- Basically just swap the system near_sys = get_emp_system( near_sys ) end --[[ Functions to create Empire patrols based on difficulty more easily. --]] function emp_generate () -- Get the Empire ships's name emp_name = empire_name() -- Get the Empire patrol's details rating = player.getRating() if rating < 100 then emp_ship, emp_outfits = emp_easy() elseif rating < 200 then emp_ship, emp_outfits = emp_medium() else emp_ship, emp_outfits = emp_hard() end -- Make sure to save the outfits. emp_outfits["__save"] = true return emp_name, emp_ship, emp_outfits end function emp_easy () if rnd.rnd() < 0.5 then return empire_createShark(false) else return empire_createLancelot(false) end end function emp_medium () if rnd.rnd() < 0.5 then return empire_createAdmonisher(false) else return empire_createPacifier(false) end end function emp_hard () if rnd.rnd() < 0.5 then return empire_createHawking(false) else return empire_createPeacemaker(false) end end
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Southern_San_dOria/npcs/Katharina.lua
37
1095
----------------------------------- -- Area: Southern San d'Oria -- NPC: Katharina -- General Info NPC ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- require("scripts/globals/settings"); function onTrigger(player,npc) player:startEvent(0x377); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/fudgy-wudge.lua
3
1099
----------------------------------------- -- ID: 5920 -- Item: Fudgy-wudge -- Food Effect: 3 Min, All Races ----------------------------------------- -- Intelligence 1 -- Speed 12.5% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) 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,180,5920); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 1); target:addMod(MOD_MOVE, 13); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 1); target:delMod(MOD_MOVE, 13); end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Temenos/mobs/Pee_Qoho_the_Python.lua
2
1549
----------------------------------- -- Area: Temenos -- NPC: ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (IsMobDead(16929023)==true and IsMobDead(16929024)==true and IsMobDead(16929025)==true and IsMobDead(16929026)==true and IsMobDead(16929027)==true and IsMobDead(16929028)==true )then mob:setMod(MOD_SLASHRES,1400); mob:setMod(MOD_PIERCERES,1400); mob:setMod(MOD_IMPACTRES,1400); mob:setMod(MOD_HTHRES,1400); else mob:setMod(MOD_SLASHRES,300); mob:setMod(MOD_PIERCERES,300); mob:setMod(MOD_IMPACTRES,300); mob:setMod(MOD_HTHRES,300); end GetMobByID(16929005):updateEnmity(target); GetMobByID(16929006):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true)then GetNPCByID(16928768+78):setPos(-280,-161,-440); GetNPCByID(16928768+78):setStatus(STATUS_NORMAL); GetNPCByID(16928768+473):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/The_Sanctuary_of_ZiTah/npcs/mandau.lua
2
1770
----------------------------------- -- Area: The Sanctuary of Zitah -- NPC: ??? -- @zone 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if(player:getVar("relic") == 1) then if(trade:hasItemQty(18269,1) and trade:hasItemQty(1572,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1) and trade:getItemCount() == 4) then player:startEvent(0x00cf,18270); end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 0x00cf)then if(player:getFreeSlotsCount() == 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18270); player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,1456,30); else player:tradeComplete(); player:setVar("relic",0); player:addItem(18270); player:addItem(1456,30); player:messageSpecial(ITEM_OBTAINED,18270); player:messageSpecial(ITEM_OBTAINEDX,1456,30); end end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/LaLoff_Amphitheater/npcs/qm0_1.lua
35
1154
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: qm0 (warp player outside after they win fight) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ------------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0C); 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 == 0x0C and option == 1) then player:setPos(291.459,-42.088,-401.161,163,130); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/plate_of_vegan_sautee.lua
2
1340
----------------------------------------- -- ID: 5184 -- Item: plate_of_vegan_sautee -- Food Effect: 240Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -1 -- Ranged ACC % 7 -- Ranged ACC Cap 20 ----------------------------------------- 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,5184); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 20); end;
gpl-3.0
Wedge009/wesnoth
data/campaigns/World_Conquest/lua/map/postgeneration/3E_Coral.lua
7
1495
-- Coral function world_conquest_tek_map_repaint_3e() set_terrain { "Ur", f.terrain("U*^Tf,U*"), fraction = 8, } wct_reduce_wall_clusters("Uu,Uu^Tf,Uh,Uu^Tf,Uu,Uh,Ur,Uu,Ur,Uu,Ur") set_terrain { "Xu", f.all( f.adjacent(f.terrain("U*^*")), f.terrain("Mm^Xm") ), } set_terrain { "Gs", f.terrain("Wog"), } set_terrain { "Ds", f.terrain("Dd"), } set_terrain { "Hh^Ftp", f.terrain("Hh^Fp"), } set_terrain { "Gs^Vht", f.terrain("Gs^Vc"), fraction = 2, } set_terrain { "Ss", f.terrain("Gs"), fraction = 9, } set_terrain { "Gg", f.terrain("Hh,Hh^F*,Hh^Tf"), fraction = 4, } set_terrain { "Ds^Ftd", f.all( f.terrain("Ds"), f.adjacent(f.terrain("G*")) ), fraction = 4, } set_terrain { "Gg", f.terrain("Mm"), fraction = 3, } set_terrain { "*^Ft", f.terrain("G*"), fraction = 4, layer = "overlay", } set_terrain { "Hh,Hh,Hh,Hh^Ftp,Mm", f.terrain("G*"), fraction = 5, } -- fix water due to bug in generator creating rivers -- todo: what did tekelili mean by that? set_terrain { "Wot", f.terrain("Ww"), } end function wct_map_3e_post_bunus_decoration() wct_map_cave_path_to("Re") set_terrain { "Wwt", f.all( f.adjacent(f.terrain("!,W*^*")), f.terrain("Wot") ), } end local _ = wesnoth.textdomain 'wesnoth-wc' return function() set_map_name(_"made of^Coral") wct_enemy_castle_expansion() world_conquest_tek_map_repaint_3e() world_conquest_tek_bonus_points() wct_map_3e_post_bunus_decoration() end
gpl-2.0
BTAxis/naev
dat/gui/legacy.lua
11
10515
--[[ @brief Obligatory create function. Run when the GUI is loaded which is caused whenever the player gets in a different ship. --]] function create() -- Get the player pp = player.pilot() pfact = pp:faction() -- Get sizes screen_w, screen_h = gfx.dim() deffont_h = gfx.fontSize() smallfont_h = gfx.fontSize(true) -- FPS pos gui.fpsPos( 15, screen_h - 15 - deffont_h ); -- Some colours col_white = colour.new() col_warn = colour.new( "Red" ) col_gray = colour.new( "Grey70" ) col_neut = colour.new( 0.9, 1.0, 0.3, 1.0 ) col_console = colour.new( 0.1, 0.9, 0.1, 1.0 ) shield_col = colour.new( 0.2, 0.2, 0.8, 0.8 ) armour_col = colour.new( 0.5, 0.5, 0.5, 0.8 ) energy_col = colour.new( 0.2, 0.8, 0.2, 0.8 ) fuel_col = colour.new( 0.9, 0.1, 0.4, 0.8 ) -- Load graphics local base = "dat/gfx/gui/default/" frame = tex.open( base .. "minimal.png" ) energy = tex.open( base .. "minimal_energy.png" ) fuel = tex.open( base .. "minimal_fuel.png" ) gui.targetPlanetGFX( tex.open( base .. "minimal_planet.png" ) ) gui.targetPilotGFX( tex.open( base .. "minimal_pilot.png" ) ) -- OSD gui.osdInit( 30, screen_h-90, 150, 300 ) -- Messages gui.mesgInit( screen_w-400, 20, 30 ) -- Frame position frame_w, frame_h = frame:dim() frame_x = screen_w - frame_w - 15 frame_y = screen_h - frame_h - 15 -- Radar radar_r = 82 radar_x, radar_y = relativize( 83, 90 ) gui.radarInit( true, radar_r ) -- Health position shield_w = 128 shield_h = 7 shield_x, shield_y = relativize( 43, 192 ) armour_w = 128 armour_h = 7 armour_x, armour_y = relativize( 43, 206 ) -- Fuel/energy position energy_x, energy_y = relativize( 97, 177 ) energy_w, energy_h = energy:dim() fuel_x, fuel_y = relativize( 95, 78 ) fuel_w, fuel_h = fuel:dim() -- NAV position nav_w = 135 nav_h = 40 nav_x, nav_y = relativize( 35, 220 ) -- Weapon position weapon_w = 135 weapon_h = 32 weapon_x, weapon_y = relativize( 35, 294 ) -- Target position target_w = 128 target_h = 100 target_x, target_y = relativize( 40, 350 ) -- Misc position misc_w = 128 misc_h = 104 misc_x, misc_y = relativize( 40, 472 ) -- Bottom bar --gui.viewport( 0, 20, screen_w, screen_h-20 ) -- Update stuff update_cargo() update_nav() update_target() update_ship() update_system() end function relativize( x, y ) return frame_x + x, frame_y + frame_h - y end --[[ -- @brief This function is run whenever the player changes nav target (be in hyperspace or planet target). --]] function update_nav () nav_pnt, nav_hyp = pp:nav() end --[[ -- @brief This function is run whenever the player changes their pilot target. --]] function update_target () -- Set target ptarget = pp:target() if ptarget ~= nil then target_fact = ptarget:faction() target_gfx = ptarget:ship():gfxTarget() target_gfx_w, target_gfx_h = target_gfx:dim() target_gfxFact = target_fact:logoTiny() if target_gfxFact ~= nil then target_gf_w, target_gf_h = target_gfxFact:dim() target_gf_w = ( target_gf_w + 24 ) / 2 target_gf_h = ( target_gf_h + 24 ) / 2 end end end --[[ -- @brief This function is run whenever the player modifies their ship outfits (when the ship is changed the gui is recreated). --]] function update_ship () stats = pp:stats() fuel_max = stats.fuel end --[[ -- @brief This function is run whenever the player changes their cargo. --]] function update_cargo () cargol = pp:cargoList() misc_cargo = "" for _,v in ipairs(cargol) do if v.q == 0 then misc_cargo = misc_cargo .. v.name else misc_cargo = misc_cargo .. string.format( "%d" .. "t %s", v.q, v.name ) end if v.m then misc_cargo = misc_cargo .. "*" end misc_cargo = misc_cargo .. "\n" end end --[[ -- @brief This function is run whenever the player changes system (every enter). --]] function update_system () end --[[ @brief Obligatory render function. Run every frame. Note that the dt will be 0. if the game is paused. @param dt Current deltatick in seconds since last render. --]] function render( dt ) gfx.renderTex( frame, frame_x, frame_y ) gui.radarRender( radar_x, radar_y ) render_border() render_nav() render_health() render_weapon() render_target() render_misc() render_warnings() end function render_border () --gfx.renderRect( 0, 0, screen_w/2, 20, col_white ) end -- Renders the navigation computer function render_nav () if nav_pnt ~= nil or nav_hyp ~= nil then local y = nav_y - 3 - deffont_h local str gfx.print( nil, "Landing", nav_x, y, col_console, nav_w, true ) y = y - 5 - smallfont_h if nav_pnt ~= nil then str = nav_pnt:name() col = col_white else str = "Off" col = col_gray end gfx.print( true, str, nav_x, y, col, nav_w, true ) y = nav_y - 33 - deffont_h gfx.print( nil, "Hyperspace", nav_x, y, col_console, nav_w, true ) y = y - 5 - smallfont_h if nav_hyp ~= nil then if nav_hyp:known() then str = nav_hyp:name() else str = "Unknown" end col = col_white else str = "Off" col = col_gray end gfx.print( true, str, nav_x, y, col, nav_w, true ) else local y = nav_y - 20 - deffont_h gfx.print( nil, "Navigation", nav_x, y, col_console, nav_w, true ) y = y - 5 - smallfont_h gfx.print( true, "Off", nav_x, y, col_gray, nav_w, true ) end end function update_faction() end -- Renders the health bars function render_health () local arm, shi = pp:health() gfx.renderRect( shield_x, shield_y, shi/100.*shield_w, shield_h, shield_col ) gfx.renderRect( armour_x, armour_y, arm/100.*armour_w, armour_h, armour_col ) local ene = pp:energy() / 100 gfx.renderTexRaw( energy, energy_x, energy_y, ene*energy_w, energy_h, 1, 1, 0, 0, ene, 1, energy_col ) local fue = player.fuel() / fuel_max gfx.renderTexRaw( fuel, fuel_x, fuel_y, fue*fuel_w, fuel_h, 1, 1, 0, 0, fue, 1, fuel_col ) end -- Renders the weapon systems function render_weapon () col = col_console ws_name, ws = pp:weapset() gfx.print( nil, ws_name, weapon_x, weapon_y-25, col, weapon_w, true ) --[[ local sec, amm, rdy = pp:secondary() if sec ~= nil then local col if rdy then col = col_console else col = col_gray end if amm ~= nil then gfx.print( nil, sec, weapon_x, weapon_y-17, col, weapon_w, true ) gfx.print( true, string.format("%d", amm), weapon_x, weapon_y-32, col_gray, weapon_w, true ) else gfx.print( nil, sec, weapon_x, weapon_y-25, col, weapon_w, true ) end else gfx.print( nil, "Secondary", weapon_x, weapon_y-17, col_console, weapon_w, true ) gfx.print( true, "None", weapon_x, weapon_y-32, col_gray, weapon_w, true ) end --]] end -- Renders the pilot target function render_target () -- Target must exist if ptarget == nil then render_targetnone() return end local det, scan = pp:inrange(ptarget) -- Must be detected if not det then render_targetnone() return end local col, shi, arm, stress, dis arm, shi, stress, dis = ptarget:health() -- Get colour if dis or not scan then col = col_gray else col = ptarget:colour() end -- Render target graphic local x, y if not scan then str = "Unknown" w = gfx.printDim( true, str ) x = target_x + (target_w - w)/2 y = target_y - (target_h - smallfont_h)/2 gfx.print( true, str, x, y-smallfont_h, col_gray, w, true ) else x = target_x + (target_w - target_gfx_w)/2 y = target_y + (target_h - target_gfx_h)/2 gfx.renderTex( target_gfx, x, y-target_h ) end -- Display name local name if not scan then name = "Unknown" else name = ptarget:name() end local w = gfx.printDim( nil, name ) gfx.print( w > target_w, name, target_x, target_y-13, col, target_w ) -- Display faction if scan then local faction = target_fact:name() local w = gfx.printDim( nil, faction ) gfx.print( true, faction, target_x, target_y-26, col_white, target_w ) end -- Display health if scan then local str if dis then str = "Disabled" elseif shi < 5 then str = string.format( "Armour: %.0f%%", arm ) else str = string.format( "Shield: %.0f%%", shi ) end gfx.print( true, str, target_x, target_y-105, col_white, target_w ) end -- Render faction logo. if scan and target_gfxFact ~= nil then gfx.renderTex( target_gfxFact, target_x + target_w - target_gf_w - 3, target_y - target_gf_h + 3 ) end end function render_targetnone () gfx.print( false, "No Target", target_x, target_y-(target_h-deffont_h)/2-deffont_h, col_gray, target_w, true ) end -- Renders the miscellaneous stuff function render_misc () _, creds = player.credits(2) h = 5 + smallfont_h y = misc_y - h gfx.print( true, "Creds:", misc_x, y, col_console, misc_w, false ) w = gfx.printDim( true, creds ) gfx.print( true, creds, misc_x+misc_w-w-3, y, col_white, misc_w, false ) y = y - h gfx.print( true, "Cargo Free:", misc_x, y, col_console, misc_w, false ) local free = string.format("%d" .. "t", pp:cargoFree()) w = gfx.printDim( true, free ) gfx.print( true, free, misc_x+misc_w-w-3, y, col_white, misc_w, false ) y = y - 5 h = misc_h - 2*h - 8 gfx.printText( true, misc_cargo, misc_x+13., y-h, misc_w-15., h, col_white ) end -- Renders the warnings like system volatility function render_warnings () -- Render warnings local sys = system.cur() local nebu_dens, nebu_vol = sys:nebula() local y = screen_h - 50 - deffont_h if pp:lockon() > 0 then gfx.print( nil, "LOCK-ON DETECTED", 0, y, col_warn, screen_w, true ) y = y - deffont_h - 10 end if nebu_vol > 0 then gfx.print( nil, "VOLATILE ENVIRONMENT DETECTED", 0, y, col_warn, screen_w, true ) end end --[[ @brief Optional destroy function. Run when exitting the game on changing GUI. Graphics and stuff are cleaned up automatically. --]] function destroy() end
gpl-3.0
Yhgenomics/premake-core
src/actions/vstudio/vs2013.lua
17
1679
-- -- actions/vstudio/vs2013.lua -- Extend the existing exporters with support for Visual Studio 2013. -- Copyright (c) 2013-2014 Jason Perkins and the Premake project -- premake.vstudio.vc2013 = {} local p = premake local vstudio = p.vstudio local vc2010 = vstudio.vc2010 local m = vstudio.vc2013 --- -- Define the Visual Studio 2013 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2013", shortname = "Visual Studio 2013", description = "Generate Visual Studio 2013 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None", "Utility" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Workspace and project generation logic onWorkspace = function(wks) vstudio.vs2005.generateSolution(wks) end, onProject = function(prj) vstudio.vs2010.generateProject(prj) end, onRule = function(rule) vstudio.vs2010.generateRule(rule) end, onCleanWorkspace = function(wks) vstudio.cleanSolution(wks) end, onCleanProject = function(prj) vstudio.cleanProject(prj) end, onCleanTarget = function(prj) vstudio.cleanTarget(prj) end, pathVars = vstudio.pathVars, -- This stuff is specific to the Visual Studio exporters vstudio = { solutionVersion = "12", versionName = "2013", targetFramework = "4.5", toolsVersion = "12.0", filterToolsVersion = "4.0", platformToolset = "v120" } }
bsd-3-clause
meshr-net/meshr_win32
usr/lib/lua/nixioutil.lua
2
5844
--[[ nixio - Linux I/O library for lua Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local table = require "table" local nixio = require "nixio" local getmetatable, assert, pairs, type = getmetatable, assert, pairs, type local tostring = tostring module "nixio.util" local BUFFERSIZE = nixio.const.buffersize local ZIOBLKSIZE = 65536 local socket = nixio.meta_socket local tls_socket = nixio.meta_tls_socket local file = nixio.meta_file local uname = nixio.uname() local ZBUG = uname.sysname == "Linux" and uname.release:sub(1, 3) == "2.4" function consume(iter, append) local tbl = append or {} if iter then for obj in iter do tbl[#tbl+1] = obj end end return tbl end local meta = {} function meta.is_socket(self) return (getmetatable(self) == socket) end function meta.is_tls_socket(self) return (getmetatable(self) == tls_socket) end function meta.is_file(self) return (getmetatable(self) == file) end function meta.readall(self, len) local block, code, msg = self:read(len or BUFFERSIZE) if not block then return nil, code, msg, "" elseif #block == 0 then return "", nil, nil, "" end local data, total = {block}, #block while not len or len > total do block, code, msg = self:read(len and (len - total) or BUFFERSIZE) if not block then return nil, code, msg, table.concat(data) elseif #block == 0 then break end data[#data+1], total = block, total + #block end local data = #data > 1 and table.concat(data) or data[1] return data, nil, nil, data end meta.recvall = meta.readall function meta.writeall(self, data) data = tostring(data) local sent, code, msg = self:write(data) if not sent then return nil, code, msg, 0 end local total = sent while total < #data do sent, code, msg = self:write(data, total) if not sent then return nil, code, msg, total end total = total + sent end return total, nil, nil, total end meta.sendall = meta.writeall function meta.linesource(self, limit) limit = limit or BUFFERSIZE local buffer = "" local bpos = 0 return function(flush) local line, endp, _ if flush then line = buffer:sub(bpos + 1) buffer = type(flush) == "string" and flush or "" bpos = 0 return line end while not line do _, endp, line = buffer:find("(.-)\r?\n", bpos + 1) if line then bpos = endp return line elseif #buffer < limit + bpos then local newblock, code, msg = self:read(limit + bpos - #buffer) if not newblock or newblock == true then return nil, code, msg elseif #newblock == 0 then return nil end buffer = buffer:sub(bpos + 1) .. newblock bpos = 0 else return nil, 0 end end end end function meta.blocksource(self, bs, limit) bs = bs or BUFFERSIZE return function() local toread = bs if limit then if limit < 1 then return nil elseif limit < toread then toread = limit end end local block, code, msg = self:read(toread) if not block then return nil, code, msg elseif #block == 0 then return nil else if limit then limit = limit - #block end return block end end end function meta.sink(self, close) return function(chunk, src_err) if not chunk and not src_err and close then if self.shutdown then self:shutdown() end self:close() elseif chunk and #chunk > 0 then return self:writeall(chunk) end return true end end function meta.copy(self, fdout, size) local source = self:blocksource(nil, size) local sink = fdout:sink() local sent, chunk, code, msg = 0 repeat chunk, code, msg = source() sink(chunk, code, msg) sent = chunk and (sent + #chunk) or sent until not chunk return not code and sent or nil, code, msg, sent end function meta.copyz(self, fd, size) local sent, lsent, code, msg = 0 local splicable if not ZBUG and self:is_file() then local ftype = self:stat("type") if nixio.sendfile and fd:is_socket() and ftype == "reg" then repeat lsent, code, msg = nixio.sendfile(fd, self, size or ZIOBLKSIZE) if lsent then sent = sent + lsent size = size and (size - lsent) end until (not lsent or lsent == 0 or (size and size == 0)) if lsent or (not lsent and sent == 0 and code ~= nixio.const.ENOSYS and code ~= nixio.const.EINVAL) then return lsent and sent, code, msg, sent end elseif nixio.splice and not fd:is_tls_socket() and ftype == "fifo" then splicable = true end end if nixio.splice and fd:is_file() and not splicable then splicable = not self:is_tls_socket() and fd:stat("type") == "fifo" end if splicable then repeat lsent, code, msg = nixio.splice(self, fd, size or ZIOBLKSIZE) if lsent then sent = sent + lsent size = size and (size - lsent) end until (not lsent or lsent == 0 or (size and size == 0)) if lsent or (not lsent and sent == 0 and code ~= nixio.const.ENOSYS and code ~= nixio.const.EINVAL) then return lsent and sent, code, msg, sent end end return self:copy(fd, size) end if tls_socket then function tls_socket.close(self) return self.socket:close() end function tls_socket.getsockname(self) return self.socket:getsockname() end function tls_socket.getpeername(self) return self.socket:getpeername() end function tls_socket.getsockopt(self, ...) return self.socket:getsockopt(...) end tls_socket.getopt = tls_socket.getsockopt function tls_socket.setsockopt(self, ...) return self.socket:setsockopt(...) end tls_socket.setopt = tls_socket.setsockopt end for k, v in pairs(meta) do file[k] = v socket[k] = v if tls_socket then tls_socket[k] = v end end
apache-2.0
ForgedAddons/StayFocused_AutoShot
tekKonfig/tekKonfigButton.lua
6
1708
local lib, oldminor = LibStub:NewLibrary("tekKonfig-Button", 5) if not lib then return end oldminor = oldminor or 0 if oldminor < 5 then local GameTooltip = GameTooltip local function HideTooltip() GameTooltip:Hide() end local function ShowTooltip(self) if self.tiptext then GameTooltip:SetOwner(self, "ANCHOR_RIGHT") GameTooltip:SetText(self.tiptext, nil, nil, nil, nil, true) end end -- Create a button. -- All args optional, parent recommended function lib.new(parent, ...) local butt = CreateFrame("Button", nil, parent) if select("#", ...) > 0 then butt:SetPoint(...) end butt:SetWidth(80) butt:SetHeight(22) -- Fonts -- butt:SetDisabledFontObject(GameFontDisable) butt:SetHighlightFontObject(GameFontHighlight) butt:SetNormalFontObject(GameFontNormal) -- Textures -- butt:SetNormalTexture("Interface\\Buttons\\UI-Panel-Button-Up") butt:SetPushedTexture("Interface\\Buttons\\UI-Panel-Button-Down") butt:SetHighlightTexture("Interface\\Buttons\\UI-Panel-Button-Highlight") butt:SetDisabledTexture("Interface\\Buttons\\UI-Panel-Button-Disabled") butt:GetNormalTexture():SetTexCoord(0, 0.625, 0, 0.6875) butt:GetPushedTexture():SetTexCoord(0, 0.625, 0, 0.6875) butt:GetHighlightTexture():SetTexCoord(0, 0.625, 0, 0.6875) butt:GetDisabledTexture():SetTexCoord(0, 0.625, 0, 0.6875) butt:GetHighlightTexture():SetBlendMode("ADD") -- Tooltip bits butt:SetScript("OnEnter", ShowTooltip) butt:SetScript("OnLeave", HideTooltip) return butt end function lib.new_small(parent, ...) local butt = lib.new(parent, ...) butt:SetHighlightFontObject(GameFontHighlightSmall) butt:SetNormalFontObject(GameFontNormalSmall) return butt end end
apache-2.0
meshr-net/meshr_win32
usr/lib/lua/luci/model/cbi/admin_system/backupfiles.lua
8
2706
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: backupfiles.lua 7798 2011-10-26 23:43:04Z jow $ ]]-- if luci.http.formvalue("cbid.luci.1._list") then luci.http.redirect(luci.dispatcher.build_url("admin/system/flashops/backupfiles") .. "?display=list") elseif luci.http.formvalue("cbid.luci.1._edit") then luci.http.redirect(luci.dispatcher.build_url("admin/system/flashops/backupfiles") .. "?display=edit") return end m = SimpleForm("luci", translate("Backup file list")) m:append(Template("admin_system/backupfiles")) if luci.http.formvalue("display") ~= "list" then f = m:section(SimpleSection, nil, translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade. Modified files in /etc/config/ and certain other configurations are automatically preserved.")) l = f:option(Button, "_list", translate("Show current backup file list")) l.inputtitle = translate("Open list...") l.inputstyle = "apply" c = f:option(TextValue, "_custom") c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end else m.submit = false m.reset = false f = m:section(SimpleSection, nil, translate("Below is the determined list of files to backup. It consists of changed configuration files marked by opkg, essential base files and the user defined backup patterns.")) l = f:option(Button, "_edit", translate("Back to configuration")) l.inputtitle = translate("Close list...") l.inputstyle = "link" d = f:option(DummyValue, "_detected") d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end end return m
apache-2.0
kidaa/FFXIOrgins
scripts/globals/mobskills/Barbed_Crescent.lua
10
1034
--------------------------------------------------- -- Barbed Crescent -- Damage. Additional Effect: Accuracy Down. -- Area of Effect is centered around caster. -- The Additional Effect: Accuracy Down may not always process. -- Duration: Three minutes ? --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------------- function OnMobSkillCheck(target,mob,skill) return 0; end; function OnMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.7; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); local typeEffect = EFFECT_ACCURACY_DOWN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 50, 0, 120); target:delHP(dmg); return dmg; end;
gpl-3.0
BTAxis/naev
dat/missions/flf/flf_pre02.lua
1
17936
--[[ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -- This is the second "prelude" mission leading to the FLF campaign. 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 --]] include "fleethelper.lua" include "dat/missions/flf/flf_patrol.lua" title = {} text = {} DVtitle = {} DVtext = {} osd_desc = {} DVosd = {} refuelmsg = {} title[1] = _("A chance to prove yourself") text[1] = _([[The FLF officer doesn't seem at all surprised that you approached her. On the contrary, she looks like she expected you to do so all along. "Greetings," she says, nodding at you in curt greeting. "I am Corporal Benito. And you must be %s, the one who got Lt. Fletcher back here in one piece." Benito's expression becomes a little more severe. "I'm not here to exchange pleasantries, however. You probably noticed, but people here are a little uneasy about your presence. They don't know what to make of you, see. You helped us once, it is true, but that doesn't tell us much. We don't know you."]]) text[2] = _([[Indeed, you are constantly aware of the furtive glances the other people in this bar are giving you. They don't seem outright hostile, but you can tell that if you don't watch your step and choose your words carefully, things might quickly take a turn for the worse. Benito waves her hand to indicate you needn't pay them any heed. "That said, the upper ranks have decided that if you are truly sympathetic to our cause, you will be given an opportunity to prove yourself. Of course, if you'd rather not get involved in our struggle, that's understandable. But if you're in for greater things, if you stand for justice... Perhaps you'll consider joining with us?"]]) title[3] = _("Patrol-B-gone") text[3] = _([["I'm happy to hear that. It's good to know we still have the support from the common man. Anyway, let me fill you in on what it is we want you to do. As you may be aware, the Dvaered have committed a lot of resources to finding us and flushing us out lately. And while our base is well hidden, those constant patrols are certainly not doing anything to make us feel more secure! I think you can see where this is going. You will go out there and eliminate one of those patrols in the %s system." You object, asking the Corporal if all recruits have to undertake dangerous missions like this to be accepted into the FLF ranks. Benito chuckles, and makes a pacifying gesture. "Calm down, it's not as bad as it sounds. You only have to take out one small patrol; I don't think you will have to fight more than 3 ships, 4 if you're really unlucky. If you think that's too much for you, you can abort the mission for now and come to me again later. Otherwise, good luck!"]]) title[4] = _("Breaking the ice") text[4] = _([[When you left Sindbad Station, it was a cold, lonely place for you. The FLF soldiers on the station avoided you whenever they could, and basic services were harder to get than they should have been. But now that you have returned victorious over the Dvaered, the place has become considerably more hospitable. There are more smiles on people's faces, and some even tell you you did a fine job. Among them is Corporal Benito. She walks up to you and offers you her hand.]]) text[5] = _([["Welcome back, %s, and congratulations. I didn't expect the Dvaered to send reinforcements, much less a Vigilance. I certainly wouldn't have sent you alone if I did, and I might not have sent you at all. But then, you're still in one piece, so maybe I shouldn't worry so much, eh?"]]) text[6] = _([[Benito takes you to the station's bar, and buys you what for lack of a better word must be called a drink. "We will of course reward you for your service," she says once you are seated. "Though you must understand the FLF doesn't have that big a budget. Financial support is tricky, and the Frontier doesn't have that much to spare themselves to begin with. Nevertheless, we are willing to pay for good work, and your work is nothing but. What's more, you've ingratiated yourself with many of us, as you've undoubtedly noticed. Our top brass are among those you've impressed, so from today on, you can call yourself one of us! How about that, huh?"]]) text[7] = _([["Of course, our work is only just beginning. No rest for the weary; we must continue the fight against the oppressors. I'm sure the road is still long, but I'm encouraged by the fact that we gained another valuable ally today. Check the mission computer for more tasks you can help us with. I'm sure you'll play an important role in our eventual victory over the Dvaered!" That last part earns a cheer from the assembled FLF soldiers. You decide to raise your glass with them, making a toast to the fortune of battle in the upcoming campaign - and the sweet victory that lies beyond.]]) refusetitle = _("Some other time perhaps") refusetext = _([["I see. That's a fair answer, I'm sure you have your reasons. But if you ever change your mind, I'll be around on Sindbad. You won't have trouble finding me, I'm sure."]]) DVtitle[1] = _("A tempting offer") DVtext[1] = _([[Your viewscreen shows a Dvaered Colonel. He looks tense. Normally, a tense Dvaered would be bad news, but then this one bothered to hail you in the heat of battle, so perhaps there is more here than meets the eye.]]) DVtext[2] = _([["I am Colonel Urnus of the Dvaered Fleet, anti-terrorism division. I would normally never contact an enemy of House Dvaered, but my intelligence officer has looked through our records and found that you were recently a law-abiding citizen, doing honest freelance missions."]]) DVtext[3] = _([["I know your type, %s. You take jobs where profit is to be had, and you side with the highest bidder. There are many like you in the galaxy, though admittedly not so many with your talent. That's why I'm willing to make you this offer: you will provide us with information on their base of operations and their combat strength. In return, I will convince my superiors that you were working for me all along, so you won't face any repercussions for assaulting Dvaered ships. Furthermore, I will transfer a considerable amount of credits in your account, as well as put you into a position to make an ally out of House Dvaered. If you refuse, however, I guarantee you that you will never again be safe in Dvaered space. What say you? Surely this proposition beats anything that rabble can do for you?"]]) DVchoice1 = _("Accept the offer") DVchoice2 = _("Remain loyal to the FLF") DVtitle[4] = _("Opportunism is an art") DVtext[4] = _([[Colonel Urnus smiles broadly. "I knew you'd make the right choice, citizen!" He addresses someone on his bridge, out of the view of the camera. "Notify the flight group. This ship is now friendly. Cease fire." Then he turns back to you. "Proceed to %s in the %s system, citizen. I will personally meet you there."]]) DVtitle[5] = _("End of negotiations") DVtext[5] = _([[Colonel Urnus is visibly annoyed by your response. "Very well then," he bites at you. "In that case you will be destroyed along with the rest of that terrorist scum. Helm, full speed ahead! All batteries, fire at will!"]]) DVtitle[6] = _("A reward for a job well botched") DVtext[6] = _([[Soon after docking, you are picked up by a couple of soldiers, who escort you to Colonel Urnus' office. Urnus greets you warmly, and offers you a seat and a cigar. You take the former, not the latter. "I am most pleased with the outcome of this situation, citizen," Urnus begins. "To be absolutely frank with you, I was beginning to get frustrated. My superiors have been breathing down my neck, demanding results on those blasted FLF, but they are as slippery as eels. Just when you think you've cornered them, poof! They're gone, lost in that nebula. Thick as soup, that thing. I don't know how they can even find their own way home!"]]) DVtext[7] = _([[Urnus takes a puff of his cigar and blows out a ring of smoke. It doesn't take a genius to figure out you're the best thing that's happened to him in a long time. "Anyway. I promised you money, status and opportunities, and I intend to make good on those promises. Your money is already in your account. Check your balance sheet later. As for status, I can assure you that no Dvaered will find out what you've been up to. As far as the military machine is concerned, you have nothing to do with the FLF. In fact, you're known as an important ally in the fight against them! Finally, opportunities. We're analyzing the data from your flight recorder as we speak, and you'll be asked a few questions after we're done here. Based on that, we can form a new strategy against the FLF. Unless I miss my guess by a long shot, we'll be moving against them in force very soon, and I will make sure you'll be given the chance to be part of that. I'm sure it'll be worth your while."]]) DVtext[8] = _([[Urnus stands up, a sign that this meeting is drawing to a close. "Keep your eyes open for one of our liaisons, citizen. He'll be your ticket into the upcoming battle. Now, I'm a busy man so I'm going to have to ask you to leave. But I hope we'll meet again, and if you continue to build your career like you have today, I'm sure we will. Good day to you!" You leave the Colonel's office. You are then taken to an interrogation room, where Dvaered petty officers question you politely yet persistently about your brief stay with the FLF. Once their curiosity is satisfied, they let you go, and you are free to return to your ship.]]) flfcomm = {} flfcomm[1] = _("We have your back, %s!") flfcomm[2] = _("%s is selling us out! Eliminate the traitor!") flfcomm[3] = _("Let's get out of here, %s! We'll meet you back at the base.") misn_title = _("FLF: Small Dvaered Patrol in %s") misn_desc = _("To prove yourself to the FLF, you must take out one of the Dvaered security patrols.") misn_rwrd = _("A chance to make friends with the FLF.") osd_title = _("Dvaered Patrol") osd_desc[1] = _("Fly to the %s system") osd_desc[2] = _("Eliminate the Dvaered patrol") osd_desc[3] = _("Return to the FLF base") osd_desc["__save"] = true DVosd[1] = _("Fly to the %s system and land on %s") DVosd["__save"] = true npc_name = _("FLF petty officer") npc_desc = _("There is a low-ranking officer of the Frontier Liberation Front sitting at one of the tables. She seems somewhat more receptive than most people in the bar.") function create () missys = system.get( "Arcanis" ) if not misn.claim( missys ) then misn.finish( false ) end misn.setNPC( npc_name, "flf/unique/benito" ) misn.setDesc( npc_desc ) end function accept () tk.msg( title[1], text[1]:format( player.name() ) ) if tk.yesno( title[1], text[2] ) then tk.msg( title[3], text[3]:format( missys:name() ) ) osd_desc[1] = osd_desc[1]:format( missys:name() ) misn.accept() misn.osdCreate( osd_title, osd_desc ) misn.setDesc( misn_desc ) misn.setTitle( misn_title:format( missys:name() ) ) marker = misn.markerAdd( missys, "low" ) misn.setReward( misn_rwrd ) DVplanet = "Raelid Outpost" DVsys = "Raelid" reinforcements_arrived = false dv_ships_left = 0 job_done = false hook.enter( "enter" ) hook.jumpout( "leave" ) hook.land( "leave" ) else tk.msg( refusetitle, refusetext ) misn.finish( false ) end end function enter () if not job_done then if system.cur() == missys then misn.osdActive( 2 ) patrol_spawnDV( 3, nil ) else misn.osdActive( 1 ) end end end function leave () if spawner ~= nil then hook.rm( spawner ) end if hailer ~= nil then hook.rm( hailer ) end if rehailer ~= nil then hook.rm( rehailer ) end reinforcements_arrived = false dv_ships_left = 0 end function spawnDVReinforcements () reinforcements_arrived = true local dist = 1500 local x local y if rnd.rnd() < 0.5 then x = dist else x = -dist end if rnd.rnd() < 0.5 then y = dist else y = -dist end local pos = player.pos() + vec2.new( x, y ) local reinforcements = pilot.add( "Dvaered Big Patrol", "dvaered_norun", pos ) for i, j in ipairs( reinforcements ) do if j:ship():class() == "Destroyer" then boss = j end hook.pilot( j, "death", "pilot_death_dv" ) j:setHostile() j:setVisible( true ) j:setHilight( true ) fleetDV[ #fleetDV + 1 ] = j dv_ships_left = dv_ships_left + 1 end -- Check for defection possibility if faction.playerStanding( "Dvaered" ) >= -5 then hailer = hook.timer( 30000, "timer_hail" ) else spawner = hook.timer( 30000, "timer_spawnFLF" ) end end function timer_hail () if hailer ~= nil then hook.rm( hailer ) end if boss ~= nil and boss:exists() then timer_rehail() hailer = hook.pilot( boss, "hail", "hail" ) end end function timer_rehail () if rehailer ~= nil then hook.rm( rehailer ) end if boss ~= nil and boss:exists() then boss:hailPlayer() rehailer = hook.timer( 8000, "timer_rehail" ) end end function hail () if hailer ~= nil then hook.rm( hailer ) end if rehailer ~= nil then hook.rm( rehailer ) end player.commClose() tk.msg( DVtitle[1], DVtext[1] ) tk.msg( DVtitle[1], DVtext[2] ) choice = tk.choice( DVtitle[1], DVtext[3]:format( player.name() ), DVchoice1, DVchoice2 ) if choice == 1 then tk.msg( DVtitle[4], DVtext[4]:format( DVplanet, DVsys ) ) faction.get("FLF"):setPlayerStanding( -100 ) local standing = faction.get("Dvaered"):playerStanding() if standing < 0 then faction.get("Dvaered"):setPlayerStanding( 0 ) end for i, j in ipairs( fleetDV ) do if j:exists() then j:setFriendly() j:changeAI( "dvaered" ) end end job_done = true osd_desc[1] = DVosd[1]:format( DVsys, DVplanet ) osd_desc[2] = nil misn.osdActive( 1 ) misn.osdCreate( misn_title, osd_desc ) misn.markerRm( marker ) marker = misn.markerAdd( system.get(DVsys), "high" ) spawner = hook.timer( 3000, "timer_spawnHostileFLF" ) hook.land( "land_dv" ) else tk.msg( DVtitle[5], DVtext[5] ) timer_spawnFLF() end end function spawnFLF () local dist = 1500 local x local y if rnd.rnd() < 0.5 then x = dist else x = -dist end if rnd.rnd() < 0.5 then y = dist else y = -dist end local pos = player.pos() + vec2.new( x, y ) fleetFLF = addShips( { "FLF Vendetta", "FLF Lancelot" }, "flf_norun", pos, 8 ) end function timer_spawnFLF () if boss ~= nil and boss:exists() then spawnFLF() for i, j in ipairs( fleetFLF ) do j:setFriendly() j:setVisplayer( true ) end fleetFLF[1]:broadcast( flfcomm[1]:format( player.name() ) ) end end function timer_spawnHostileFLF () spawnFLF() for i, j in ipairs( fleetFLF ) do j:setHostile() j:control() j:attack( player.pilot() ) end hook.pilot( player.pilot(), "death", "returnFLFControl" ) fleetFLF[1]:broadcast( flfcomm[2]:format( player.name() ) ) end function returnFLFControl() for i, j in ipairs( fleetFLF ) do j:control( false ) end end function pilot_death_dv () dv_ships_left = dv_ships_left - 1 if dv_ships_left <= 0 then if spawner ~= nil then hook.rm( spawner ) end if hailer ~= nil then hook.rm( hailer ) end if rehailer ~= nil then hook.rm( rehailer ) end job_done = true local standing = faction.get("Dvaered"):playerStanding() if standing >= 0 then faction.get("Dvaered"):setPlayerStanding( -1 ) end misn.osdActive( 3 ) misn.markerRm( marker ) marker = misn.markerAdd( system.get( var.peek( "flfbase_sysname" ) ), "high" ) hook.land( "land_flf" ) pilot.toggleSpawn( true ) local hailed = false if fleetFLF ~= nil then for i, j in ipairs( fleetFLF ) do if j:exists() then j:control() j:hyperspace() if not hailed then hailed = true j:comm( player.pilot(), flfcomm[3]:format( player.name() ) ) end end end end elseif dv_ships_left <= 1 and not reinforcements_arrived then spawnDVReinforcements() end end function land_flf () leave() if planet.cur():faction() == faction.get("FLF") then tk.msg( title[4], text[4] ) tk.msg( title[4], text[5]:format( player.name() ) ) tk.msg( title[4], text[6] ) tk.msg( title[4], text[7] ) player.pay( 100000 ) flf_setReputation( 15 ) faction.get("FLF"):modPlayer( 5 ) var.pop( "flfbase_intro" ) misn.finish( true ) end end function land_dv () leave() if planet.cur():name() == DVplanet then tk.msg( DVtitle[6], DVtext[6] ) tk.msg( DVtitle[6], DVtext[7] ) tk.msg( DVtitle[6], DVtext[8] ) player.pay( 70000 ) var.push( "flfbase_intro", 3 ) if diff.isApplied( "FLF_base" ) then diff.remove( "FLF_base" ) end misn.finish( true ) end end
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Northern_San_dOria/npcs/Palguevion.lua
6
1734
----------------------------------- -- Area: Northern San d'Oria -- NPC: Palguevion -- Only sells when San d'Oria controlls Valdeaunia Region ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/conquest"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(VALDEAUNIA); if (RegionOwner ~= SANDORIA) then player:showText(npc,PALGUEVION_CLOSED_DIALOG); else player:showText(npc,PALGUEVION_OPEN_DIALOG); stock = {0x111e,29, -- Frost Turnip 0x027e,170} -- Sage showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/titles.lua
4
34682
----------------------------------- -- -- TITLES IDs -- ----------------------------------- FODDERCHIEF_FLAYER = 1; WARCHIEF_WRECKER = 2; DREAD_DRAGON_SLAYER = 3; OVERLORD_EXECUTIONER = 4; DARK_DRAGON_SLAYER = 5; ADAMANTKING_KILLER = 6; BLACK_DRAGON_SLAYER = 7; MANIFEST_MAULER = 8; BEHEMOTHS_BANE = 9; ARCHMAGE_ASSASSIN = 10; HELLSBANE = 11; GIANT_KILLER = 12; LICH_BANISHER = 13; JELLYBANE = 14; BOGEYDOWNER = 15; BEAKBENDER = 16; SKULLCRUSHER = 17; MORBOLBANE = 18; GOLIATH_KILLER = 19; MARYS_GUIDE = 20; SIMURGH_POACHER = 21; ROC_STAR = 22; SERKET_BREAKER = 23; CASSIENOVA = 24; THE_HORNSPLITTER = 25; TORTOISE_TORTURER = 26; MON_CHERRY = 27; BEHEMOTH_DETHRONER = 28; THE_VIVISECTOR = 29; DRAGON_ASHER = 30; EXPEDITIONARY_TROOPER = 31; BEARER_OF_THE_WISEWOMANS_HOPE = 32; BEARER_OF_THE_EIGHT_PRAYERS = 33; LIGHTWEAVER = 34; DESTROYER_OF_ANTIQUITY = 35; SEALER_OF_THE_PORTAL_OF_THE_GODS = 36; BURIER_OF_THE_ILLUSION = 37; FAMILY_COUNSELOR = 39; GREAT_GRAPPLER_SCORPIO = 41; BOND_FIXER = 42; VAMPIRE_HUNTER_DMINUS = 43; SHEEPS_MILK_DELIVERER = 44; BEAN_CUISINE_SALTER = 45; TOTAL_LOSER = 46; DOCTOR_SHANTOTTOS_FLAVOR_OF_THE_MONTH = 47; PILGRIM_TO_HOLLA = 48; PILGRIM_TO_DEM = 49; PILGRIM_TO_MEA = 50; DAYBREAK_GAMBLER = 51; THE_PIOUS_ONE = 52; A_MOSS_KIND_PERSON = 53; ENTRANCE_DENIED = 54; APIARIST = 55; RABBITER = 56; ROYAL_GRAVE_KEEPER = 57; COURIER_EXTRAORDINAIRE = 58; RONFAURIAN_RESCUER = 59; PICKPOCKET_PINCHER = 60; FANG_FINDER = 61; FAITH_LIKE_A_CANDLE = 62; THE_PURE_ONE = 63; LOST_CHILD_OFFICER = 64; SILENCER_OF_THE_LAMBS = 65; LOST_AMP_FOUND_OFFICER = 66; GREEN_GROCER = 67; THE_BENEVOLENT_ONE = 68; KNIGHT_IN_TRAINING = 69; LIZARD_SKINNER = 70; BUG_CATCHER = 71; SPELUNKER = 72; ARMS_TRADER = 73; TRAVELING_MEDICINE_MAN = 74; CAT_SKINNER = 75; CARP_DIEM = 76; ADVERTISING_EXECUTIVE = 77; THIRDRATE_ORGANIZER = 78; SECONDRATE_ORGANIZER = 79; FIRSTRATE_ORGANIZER = 80; BASTOK_WELCOMING_COMMITTEE = 81; SHELL_OUTER = 82; BUCKET_FISHER = 83; PURSUER_OF_THE_PAST = 84; PURSUER_OF_THE_TRUTH = 85; MOMMYS_HELPER = 86; HOT_DOG = 87; STAMPEDER = 88; QIJIS_FRIEND = 89; QIJIS_RIVAL = 90; CONTEST_RIGGER = 91; RINGBEARER = 92; KULATZ_BRIDGE_COMPANION = 93; BEADEAUX_SURVEYOR = 94; AVENGER = 95; TREASURE_SCAVENGER = 96; AIRSHIP_DENOUNCER = 97; ZERUHN_SWEEPER = 98; TEARJERKER = 99; CRAB_CRUSHER = 100; STAR_OF_IFRIT = 101; SORROW_DROWNER = 102; BRYGIDAPPROVED = 103; DRACHENFALL_ASCETIC = 104; STEAMING_SHEEP_REGULAR = 105; PURPLE_BELT = 106; GUSTABERG_TOURIST = 107; SAND_BLASTER = 108; BLACK_DEATH = 109; FRESH_NORTH_WINDS_RECRUIT = 111; NEW_BEST_OF_THE_WEST_RECRUIT = 112; NEW_BUUMAS_BOOMERS_RECRUIT = 113; HEAVENS_TOWER_GATEHOUSE_RECRUIT = 114; CAT_BURGLAR_GROUPIE = 115; CRAWLER_CULLER = 116; SAVIOR_OF_KNOWLEDGE = 117; STARORDAINED_WARRIOR = 118; LOWER_THAN_THE_LOWEST_TUNNEL_WORM = 119; STAR_ONION_BRIGADE_MEMBER = 120; STAR_ONION_BRIGADIER = 121; QUICK_FIXER = 122; FAKEMOUSTACHED_INVESTIGATOR = 123; HAKKURURINKURUS_BENEFACTOR = 124; SOB_SUPER_HERO = 125; EDITORS_HATCHET_MAN = 126; DOCTOR_SHANTOTTOS_GUINEA_PIG = 127; SPOILSPORT = 128; SUPER_MODEL = 129; GHOSTIE_BUSTER = 130; NIGHT_SKY_NAVIGATOR = 131; FAST_FOOD_DELIVERER = 132; CUPIDS_FLORIST = 133; TARUTARU_MURDER_SUSPECT = 134; HEXER_VEXER = 135; CARDIAN_TUTOR = 136; DELIVERER_OF_TEARFUL_NEWS = 137; FOSSILIZED_SEA_FARER = 138; DOWN_PIPER_PIPEUPPERER = 139; KISSER_MAKEUPPER = 140; TIMEKEEPER = 141; FORTUNETELLER_IN_TRAINING = 142; TORCHBEARER = 143; TENSHODO_MEMBER = 144; CHOCOBO_TRAINER = 145; BRINGER_OF_BLISS = 146; ACTIVIST_FOR_KINDNESS = 147; ENVOY_TO_THE_NORTH = 148; EXORCIST_IN_TRAINING = 149; PROFESSIONAL_LOAFER = 150; CLOCK_TOWER_PRESERVATIONIST = 151; LIFE_SAVER = 152; FOOLS_ERRAND_RUNNER = 153; CARD_COLLECTOR = 154; RESEARCHER_OF_CLASSICS = 155; STREET_SWEEPER = 156; MERCY_ERRAND_RUNNER = 157; TWOS_COMPANY = 158; BELIEVER_OF_ALTANA = 159; TRADER_OF_MYSTERIES = 160; TRADER_OF_ANTIQUITIES = 161; TRADER_OF_RENOWN = 162; BROWN_BELT = 163; HORIZON_BREAKER = 164; GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN = 165; SUMMIT_BREAKER = 166; SKY_BREAKER = 167; CLOUD_BREAKER = 168; STAR_BREAKER = 169; GREEDALOX = 170; CERTIFIED_RHINOSTERY_VENTURER = 171; CORDON_BLEU_FISHER = 172; ACE_ANGLER = 173; LU_SHANGLIKE_FISHER_KING = 174; MATCHMAKER = 175; ECOLOGIST = 176; LIL_CUPID = 177; THE_LOVE_DOCTOR = 178; SAVIOR_OF_LOVE = 179; HONORARY_CITIZEN_OF_SELBINA = 180; PURVEYOR_IN_TRAINING = 181; ONESTAR_PURVEYOR = 182; TWOSTAR_PURVEYOR = 183; THREESTAR_PURVEYOR = 184; FOURSTAR_PURVEYOR = 185; FIVESTAR_PURVEYOR = 186; DOCTOR_YORANORAN_SUPPORTER = 187; DOCTOR_SHANTOTTO_SUPPORTER = 188; PROFESSOR_KORUMORU_SUPPORTER = 189; RAINBOW_WEAVER = 190; SHADOW_WALKER = 191; HEIR_TO_THE_HOLY_CREST = 192; BUSHIDO_BLADE = 193; PARAGON_OF_PALADIN_EXCELLENCE = 195; PARAGON_OF_BEASTMASTER_EXCELLENCE = 196; PARAGON_OF_RANGER_EXCELLENCE = 197; PARAGON_OF_DARK_KNIGHT_EXCELLENCE = 198; PARAGON_OF_BARD_EXCELLENCE = 199; PARAGON_OF_SAMURAI_EXCELLENCE = 200; PARAGON_OF_DRAGOON_EXCELLENCE = 201; PARAGON_OF_NINJA_EXCELLENCE = 202; PARAGON_OF_SUMMONER_EXCELLENCE = 203; NEW_ADVENTURER = 206; CERTIFIED_ADVENTURER = 207; SHADOW_BANISHER = 208; TRIED_AND_TESTED_KNIGHT = 209; DARK_SIDER = 210; THE_FANGED_ONE = 211; HAVE_WINGS_WILL_FLY = 212; ANIMAL_TRAINER = 213; WANDERING_MINSTREL = 214; MOGS_MASTER = 215; MOGS_KIND_MASTER = 216; MOGS_EXCEPTIONALLY_KIND_MASTER = 217; PARAGON_OF_WARRIOR_EXCELLENCE = 218; PARAGON_OF_MONK_EXCELLENCE = 219; PARAGON_OF_RED_MAGE_EXCELLENCE = 220; PARAGON_OF_THIEF_EXCELLENCE = 221; PARAGON_OF_BLACK_MAGE_EXCELLENCE = 222; PARAGON_OF_WHITE_MAGE_EXCELLENCE = 223; MOGS_LOVING_MASTER = 224; ROYAL_ARCHER = 226; ROYAL_SPEARMAN = 227; ROYAL_SQUIRE = 228; ROYAL_SWORDSMAN = 229; ROYAL_CAVALIER = 230; ROYAL_GUARD = 231; GRAND_KNIGHT_OF_THE_REALM = 232; GRAND_TEMPLE_KNIGHT = 233; RESERVE_KNIGHT_CAPTAIN = 234; ELITE_ROYAL_GUARD = 235; LEGIONNAIRE = 236; DECURION = 237; CENTURION = 238; JUNIOR_MUSKETEER = 239; SENIOR_MUSKETEER = 240; MUSKETEER_COMMANDER = 241; GOLD_MUSKETEER = 242; PRAEFECTUS = 243; SENIOR_GOLD_MUSKETEER = 244; PRAEFECTUS_CASTRORUM = 245; FREESWORD = 246; MERCENARY = 247; MERCENARY_CAPTAIN = 248; COMBAT_CASTER = 249; TACTICIAN_MAGICIAN = 250; WISE_WIZARD = 251; PATRIARCH_PROTECTOR = 252; CASTER_CAPTAIN = 253; MASTER_CASTER = 254; MERCENARY_MAJOR = 255; FUGITIVE_MINISTER_BOUNTY_HUNTER = 256; KING_OF_THE_OPOOPOS = 257; EXCOMMUNICATE_OF_KAZHAM = 258; KAZHAM_CALLER = 259; DREAM_DWELLER = 260; APPRENTICE_SOMMELIER = 261; DESERT_HUNTER = 262; SEEKER_OF_TRUTH = 263; KUFTAL_TOURIST = 264; THE_IMMORTAL_FISHER_LU_SHANG = 265; LOOKS_SUBLIME_IN_A_SUBLIGAR = 266; LOOKS_GOOD_IN_LEGGINGS = 267; HONORARY_DOCTORATE_MAJORING_IN_TONBERRIES = 268; TREASUREHOUSE_RANSACKER = 269; CRACKER_OF_THE_SECRET_CODE = 270; BLACK_MARKETEER = 271; ACQUIRER_OF_ANCIENT_ARCANUM = 272; YA_DONE_GOOD = 273; HEIR_OF_THE_GREAT_FIRE = 274; HEIR_OF_THE_GREAT_EARTH = 275; HEIR_OF_THE_GREAT_WATER = 276; HEIR_OF_THE_GREAT_WIND = 277; HEIR_OF_THE_GREAT_ICE = 278; HEIR_OF_THE_GREAT_LIGHTNING = 279; GUIDER_OF_SOULS_TO_THE_SANCTUARY = 280; BEARER_OF_BONDS_BEYOND_TIME = 281; FRIEND_OF_THE_OPOOPOS = 282; HERO_ON_BEHALF_OF_WINDURST = 283; VICTOR_OF_THE_BALGA_CONTEST = 284; GULLIBLES_TRAVELS = 285; EVEN_MORE_GULLIBLES_TRAVELS = 286; HEIR_OF_THE_NEW_MOON = 287; ASSASSIN_REJECT = 288; BLACK_BELT = 289; VERMILLION_VENTURER = 290; CERULEAN_SOLDIER = 291; EMERALD_EXTERMINATOR = 292; GUIDING_STAR = 293; VESTAL_CHAMBERLAIN = 294; SAN_DORIAN_ROYAL_HEIR = 295; HERO_AMONG_HEROES = 296; DYNAMISSAN_DORIA_INTERLOPER = 297; DYNAMISBASTOK_INTERLOPER = 298; DYNAMISWINDURST_INTERLOPER = 299; DYNAMISJEUNO_INTERLOPER = 300; DYNAMISBEAUCEDINE_INTERLOPER = 301; DYNAMISXARCABARD_INTERLOPER = 302; DISCERNING_INDIVIDUAL = 303; VERY_DISCERNING_INDIVIDUAL = 304; EXTREMELY_DISCERNING_INDIVIDUAL = 305; ROYAL_WEDDING_PLANNER = 306; CONSORT_CANDIDATE = 307; OBSIDIAN_STORM = 308; PENTACIDE_PERPETRATOR = 309; WOOD_WORSHIPER = 310; LUMBER_LATHER = 311; ACCOMPLISHED_CARPENTER = 312; ANVIL_ADVOCATE = 313; FORGE_FANATIC = 314; ACCOMPLISHED_BLACKSMITH = 315; TRINKET_TURNER = 316; SILVER_SMELTER = 317; ACCOMPLISHED_GOLDSMITH = 318; KNITTING_KNOWITALL = 319; LOOM_LUNATIC = 320; ACCOMPLISHED_WEAVER = 321; FORMULA_FIDDLER = 322; POTION_POTENTATE = 323; ACCOMPLISHED_ALCHEMIST = 324; BONE_BEAUTIFIER = 325; SHELL_SCRIMSHANDER = 326; ACCOMPLISHED_BONEWORKER = 327; HIDE_HANDLER = 328; LEATHER_LAUDER = 329; ACCOMPLISHED_TANNER = 330; FASTRIVER_FISHER = 331; COASTLINE_CASTER = 332; ACCOMPLISHED_ANGLER = 333; GOURMAND_GRATIFIER = 334; BANQUET_BESTOWER = 335; ACCOMPLISHED_CHEF = 336; FINE_TUNER = 337; FRIEND_OF_THE_HELMED = 338; TAVNAZIAN_SQUIRE = 339; DUCAL_DUPE = 340; HYPER_ULTRA_SONIC_ADVENTURER = 341; ROD_RETRIEVER = 342; DEED_VERIFIER = 343; CHOCOBO_LOVE_GURU = 344; PICKUP_ARTIST = 345; TRASH_COLLECTOR = 346; ANCIENT_FLAME_FOLLOWER = 347; TAVNAZIAN_TRAVELER = 348; TRANSIENT_DREAMER = 349; THE_LOST_ONE = 350; TREADER_OF_AN_ICY_PAST = 351; BRANDED_BY_LIGHTNING = 352; SEEKER_OF_THE_LIGHT = 353; DEAD_BODY = 354; FROZEN_DEAD_BODY = 355; DREAMBREAKER = 356; MIST_MELTER = 357; DELTA_ENFORCER = 358; OMEGA_OSTRACIZER = 359; ULTIMA_UNDERTAKER = 360; ULMIAS_SOULMATE = 361; TENZENS_ALLY = 362; COMPANION_OF_LOUVERANCE = 363; TRUE_COMPANION_OF_LOUVERANCE = 364; PRISHES_BUDDY = 365; NAGMOLADAS_UNDERLING = 366; ESHANTARLS_COMRADE_IN_ARMS = 367; THE_CHEBUKKIS_WORST_NIGHTMARE = 368; BROWN_MAGE_GUINEA_PIG = 369; BROWN_MAGIC_BYPRODUCT = 370; BASTOKS_SECOND_BEST_DRESSED = 371; ROOKIE_HERO_INSTRUCTOR = 372; GOBLIN_IN_DISGUISE = 373; APOSTATE_FOR_HIRE = 374; TALKS_WITH_TONBERRIES = 375; ROOK_BUSTER = 376; BANNERET = 377; GOLD_BALLI_STAR = 378; MYTHRIL_BALLI_STAR = 379; SILVER_BALLI_STAR = 380; BRONZE_BALLI_STAR = 381; SEARING_STAR = 382; STRIKING_STAR = 383; SOOTHING_STAR = 384; SABLE_STAR = 385; SCARLET_STAR = 386; SONIC_STAR = 387; SAINTLY_STAR = 388; SHADOWY_STAR = 389; SAVAGE_STAR = 390; SINGING_STAR = 391; SNIPING_STAR = 392; SLICING_STAR = 393; SNEAKING_STAR = 394; SPEARING_STAR = 395; SUMMONING_STAR = 396; PUTRID_PURVEYOR_OF_PUNGENT_PETALS = 397; UNQUENCHABLE_LIGHT = 398; BALLISTAGER = 399; ULTIMATE_CHAMPION_OF_THE_WORLD = 400; WARRIOR_OF_THE_CRYSTAL = 401; INDOMITABLE_FISHER = 402; AVERTER_OF_THE_APOCALYPSE = 403; BANISHER_OF_EMPTINESS = 404; RANDOM_ADVENTURER = 405; IRRESPONSIBLE_ADVENTURER = 406; ODOROUS_ADVENTURER = 407; INSIGNIFICANT_ADVENTURER = 408; FINAL_BALLI_STAR = 409; BALLI_STAR_ROYALE = 410; DESTINED_FELLOW = 411; ORCISH_SERJEANT = 412; BRONZE_QUADAV = 413; YAGUDO_INITIATE = 414; MOBLIN_KINSMAN = 415; SIN_HUNTER_HUNTER = 416; DISCIPLE_OF_JUSTICE = 417; MONARCH_LINN_PATROL_GUARD = 418; TEAM_PLAYER = 419; WORTHY_OF_TRUST = 420; CONQUEROR_OF_FATE = 421; BREAKER_OF_THE_CHAINS = 422; A_FRIEND_INDEED = 423; HEIR_TO_THE_REALM_OF_DREAMS = 424; GOLD_HOOK = 425; MYTHRIL_HOOK = 426; SILVER_HOOK = 427; COPPER_HOOK = 428; DYNAMISVALKURM_INTERLOPER = 430; DYNAMISBUBURIMU_INTERLOPER = 431; DYNAMISQUFIM_INTERLOPER = 432; DYNAMISTAVNAZIA_INTERLOPER = 433; CONFRONTER_OF_NIGHTMARES = 434; DISTURBER_OF_SLUMBER = 435; INTERRUPTER_OF_DREAMS = 436; SAPPHIRE_STAR = 437; SURGING_STAR = 438; SWAYING_STAR = 439; DARK_RESISTANT = 440; BEARER_OF_THE_MARK_OF_ZAHAK = 441; SEAGULL_PHRATRIE_CREW_MEMBER = 442; PROUD_AUTOMATON_OWNER = 443; PRIVATE_SECOND_CLASS = 444; PRIVATE_FIRST_CLASS = 445; SUPERIOR_PRIVATE = 446; WILDCAT_PUBLICIST = 447; ADAMANTKING_USURPER = 448; OVERLORD_OVERTHROWER = 449; DEITY_DEBUNKER = 450; FAFNIR_SLAYER = 451; ASPIDOCHELONE_SINKER = 452; NIDHOGG_SLAYER = 453; MAAT_MASHER = 454; KIRIN_CAPTIVATOR = 455; CACTROT_DESACELERADOR = 456; LIFTER_OF_SHADOWS = 457; TIAMAT_TROUNCER = 458; VRTRA_VANQUISHER = 459; WORLD_SERPENT_SLAYER = 460; XOLOTL_XTRAPOLATOR = 461; BOROKA_BELEAGUERER = 462; OURYU_OVERWHELMER = 463; VINEGAR_EVAPORATOR = 464; VIRTUOUS_SAINT = 465; BYEBYE_TAISAI = 466; TEMENOS_LIBERATOR = 467; APOLLYON_RAVAGER = 468; WYRM_ASTONISHER = 469; NIGHTMARE_AWAKENER = 470; CERBERUS_MUZZLER = 471; HYDRA_HEADHUNTER = 472; SHINING_SCALE_RIFLER = 473; TROLL_SUBJUGATOR = 474; GORGONSTONE_SUNDERER = 475; KHIMAIRA_CARVER = 476; ELITE_EINHERJAR = 477; STAR_CHARIOTEER = 478; SUN_CHARIOTEER = 479; SUBDUER_OF_THE_MAMOOL_JA = 480; SUBDUER_OF_THE_TROLLS = 481; SUBDUER_OF_THE_UNDEAD_SWARM = 482; AGENT_OF_THE_ALLIED_FORCES = 483; SCENIC_SNAPSHOTTER = 484; BRANDED_BY_THE_FIVE_SERPENTS = 485; IMMORTAL_LION = 486; PARAGON_OF_BLUE_MAGE_EXCELLENCE = 487; PARAGON_OF_CORSAIR_EXCELLENCE = 488; PARAGON_OF_PUPPETMASTER_EXCELLENCE = 489; LANCE_CORPORAL = 490; CORPORAL = 491; MASTER_OF_AMBITION = 492; MASTER_OF_CHANCE = 493; MASTER_OF_MANIPULATION = 494; OVJANGS_ERRAND_RUNNER = 495; SERGEANT = 496; SERGEANT_MAJOR = 497; KARABABAS_TOUR_GUIDE = 498; KARABABAS_BODYGUARD = 499; KARABABAS_SECRET_AGENT = 500; SKYSERPENT_AGGRANDIZER = 501; CHIEF_SERGEANT = 502; APHMAUS_MERCENARY = 503; NASHMEIRAS_MERCENARY = 504; CHOCOROOKIE = 505; SECOND_LIEUTENANT = 506; GALESERPENT_GUARDIAN = 507; STONESERPENT_SHOCKTROOPER = 508; PHOTOPTICATOR_OPERATOR = 509; SALAHEEMS_RISK_ASSESSOR = 510; TREASURE_TROVE_TENDER = 511; GESSHOS_MERCY = 512; EMISSARY_OF_THE_EMPRESS = 513; ENDYMION_PARATROOPER = 514; NAJAS_COMRADEINARMS = 515; NASHMEIRAS_LOYALIST = 516; PREVENTER_OF_RAGNAROK = 517; CHAMPION_OF_AHT_URHGAN = 518; FIRST_LIEUTENANT = 519; CAPTAIN = 520; CRYSTAL_STAKES_CUPHOLDER = 521; WINNING_OWNER = 522; VICTORIOUS_OWNER = 523; TRIUMPHANT_OWNER = 524; HIGH_ROLLER = 525; FORTUNES_FAVORITE = 526; SUPERHERO = 527; SUPERHEROINE = 528; BLOODY_BERSERKER = 529; THE_SIXTH_SERPENT = 530; ETERNAL_MERCENARY = 531; SPRINGSERPENT_SENTRY = 532; SPRIGHTLY_STAR = 533; SAGACIOUS_STAR = 534; SCHULTZ_SCHOLAR = 535; KNIGHT_OF_THE_IRON_RAM = 536; FOURTH_DIVISION_SOLDIER = 537; COBRA_UNIT_MERCENARY = 538; WINDTALKER = 539; LADY_KILLER = 540; TROUPE_BRILIOTH_DANCER = 541; CAIT_SITHS_ASSISTANT = 542; AJIDOMARUJIDOS_MINDER = 543; COMET_CHARIOTEER = 544; MOON_CHARIOTEER = 545; SANDWORM_WRANGLER = 546; IXION_HORNBREAKER = 547; LAMBTON_WORM_DESEGMENTER = 548; PANDEMONIUM_QUELLER = 549; DEBASER_OF_DYNASTIES = 550; DISPERSER_OF_DARKNESS = 551; ENDER_OF_IDOLATRY = 552; LUGH_EXORCIST = 553; ELATHA_EXORCIST = 554; ETHNIU_EXORCIST = 555; TETHRA_EXORCIST = 556; BUARAINECH_EXORCIST = 557; OUPIRE_IMPALER = 558; SCYLLA_SKINNER = 559; ZIRNITRA_WINGCLIPPER = 560; DAWON_TRAPPER = 561; KRABKATOA_STEAMER = 562; ORCUS_TROPHY_HUNTER = 563; BLOBDINGNAG_BURSTER = 564; VERTHANDI_ENSNARER = 565; RUTHVEN_ENTOMBER = 566; YILBEGAN_HIDEFLAYER = 567; TORCHBEARER_OF_THE_1ST_WALK = 568; TORCHBEARER_OF_THE_2ND_WALK = 569; TORCHBEARER_OF_THE_3RD_WALK = 570; TORCHBEARER_OF_THE_4TH_WALK = 571; TORCHBEARER_OF_THE_5TH_WALK = 572; TORCHBEARER_OF_THE_8TH_WALK = 573; TORCHBEARER_OF_THE_6TH_WALK = 574; TORCHBEARER_OF_THE_7TH_WALK = 575; FURNITURE_STORE_OWNER = 576; ARMORY_OWNER = 577; JEWELRY_STORE_OWNER = 578; BOUTIQUE_OWNER = 579; APOTHECARY_OWNER = 580; CURIOSITY_SHOP_OWNER = 581; SHOESHOP_OWNER = 582; FISHMONGER_OWNER = 583; RESTAURANT_OWNER = 584; ASSISTANT_DETECTIVE = 585; PROMISING_DANCER = 586; STARDUST_DANCER = 587; ELEGANT_DANCER = 588; DAZZLING_DANCE_DIVA = 589; FRIEND_OF_LEHKO_HABHOKA = 590; SUMMA_CUM_LAUDE = 591; GRIMOIRE_BEARER = 592; SEASONING_CONNOISSEUR = 593; FINE_YOUNG_GRIFFON = 594; BABBANS_TRAVELING_COMPANION = 595; FELLOW_FORTIFIER = 596; CHOCOCHAMPION = 597; TRAVERSER_OF_TIME = 598; MYTHRIL_MUSKETEER_NO_6 = 599; JEWEL_OF_THE_COBRA_UNIT = 600; KNIGHT_OF_THE_SWIFTWING_GRIFFIN = 601; WYRMSWORN_PROTECTOR = 602; FLAMESERPENT_FACILITATOR = 603; MAZE_WANDERER = 604; MAZE_NAVIGATOR = 605; MAZE_SCHOLAR = 606; MAZE_ARTISAN = 607; MAZE_OVERLORD = 608; SWARMINATOR = 609; BATTLE_OF_JEUNO_VETERAN = 610; GRAND_GREEDALOX = 611; KARAHABARUHAS_RESEARCH_ASSISTANT = 612; HONORARY_KNIGHT_OF_THE_CARDINAL_STAG = 613; DETECTOR_OF_DECEPTION = 614; SILENCER_OF_THE_ECHO = 615; BESTRIDER_OF_FUTURES = 616; MOG_HOUSE_HANDYPERSON = 617; PRESIDENTIAL_PROTECTOR = 618; THE_MOONS_COMPANION = 619; ARRESTER_OF_THE_ASCENSION = 620; HOUSE_AURCHIAT_RETAINER = 621; WANDERER_OF_TIME = 622; SMITER_OF_THE_SHADOW = 623; HEIR_OF_THE_BLESSED_RADIANCE = 624; HEIR_OF_THE_BLIGHTED_GLOOM = 625; SWORN_TO_THE_DARK_DIVINITY = 626; TEMPERER_OF_MYTHRIL = 627; STAR_IN_THE_AZURE_SKY = 628; FANGMONGER_FORESTALLER = 629; VISITOR_TO_ABYSSEA = 630; FRIEND_OF_ABYSSEA = 631; WARRIOR_OF_ABYSSEA = 632; STORMER_OF_ABYSSEA = 633; DEVASTATOR_OF_ABYSSEA = 634; HERO_OF_ABYSSEA = 635; CHAMPION_OF_ABYSSEA = 636; CONQUEROR_OF_ABYSSEA = 637; SAVIOR_OF_ABYSSEA = 638; VANQUISHER_OF_SPITE = 639; HADHAYOSH_HALTERER = 640; BRIAREUS_FELLER = 641; KARKINOS_CLAWCRUSHER = 642; CARABOSSE_QUASHER = 643; OVNI_OBLITERATOR = 644; RUMINATOR_CONFOUNDER = 645; ECCENTRICITY_EXPUNGER = 646; FISTULE_DRAINER = 647; KUKULKAN_DEFANGER = 648; TURUL_GROUNDER = 649; BLOODEYE_BANISHER = 650; SATIATOR_DEPRIVER = 651; IRATHAM_CAPTURER = 652; LACOVIE_CAPSIZER = 653; CHLORIS_UPROOTER = 654; MYRMECOLEON_TAMER = 655; GLAVOID_STAMPEDER = 656; USURPER_DEPOSER = 657; YAANEI_CRASHER = 658; KUTHAREI_UNHORSER = 659; SIPPOY_CAPTURER = 660; TITLACAUAN_DISMEMBERER = 661; SMOK_DEFOGGER = 662; AMHULUK_INUNDATER = 663; PULVERIZER_DISMANTLER = 664; DURINN_DECEIVER = 665; KARKADANN_EXOCULATOR = 666; ULHUADSHI_DESICCATOR = 667; ITZPAPALOTL_DECLAWER = 668; SOBEK_MUMMIFIER = 669; CIREINCROIN_HARPOONER = 670; BUKHIS_TETHERER = 671; SEDNA_TUSKBREAKER = 672; CLEAVER_DISMANTLER = 673; EXECUTIONER_DISMANTLER = 674; SEVERER_DISMANTLER = 675; LUSCA_DEBUNKER = 676; TRISTITIA_DELIVERER = 677; KETEA_BEACHER = 678; RANI_DECROWNER = 679; ORTHRUS_DECAPITATOR = 680; DRAGUA_SLAYER = 681; BENNU_DEPLUMER = 682; HEDJEDJET_DESTINGER = 683; CUIJATENDER_DESICCATOR = 684; BRULO_EXTINGUISHER = 685; PANTOKRATOR_DISPROVER = 686; APADEMAK_ANNIHILATOR = 687; ISGEBIND_DEFROSTER = 688; RESHEPH_ERADICATOR = 689; EMPOUSA_EXPURGATOR = 690; INDRIK_IMMOLATOR = 691; OGOPOGO_OVERTURNER = 692; RAJA_REGICIDE = 693; ALFARD_DETOXIFIER = 694; AZDAJA_ABOLISHER = 695; AMPHITRITE_SHUCKER = 696; FUATH_PURIFIER = 697; KILLAKRIQ_EXCORIATOR = 698; MAERE_BESTIRRER = 699; WYRM_GOD_DEFIER = 700; MENDER_OF_WINGS = 736; CHAMPION_OF_THE_DAWN = 737; BUSHIN_ASPIRANT = 738; BUSHIN_RYU_INHERITOR = 739; TEMENOS_EMANCIPATOR = 740; APOLLYON_RAZER = 741; GOLDWING_SQUASHER = 742; SILAGILITH_DETONATOR = 743; SURTR_SMOTHERER = 744; DREYRUK_PREDOMINATOR = 745; SAMURSK_VITIATOR = 746; UMAGRHK_MANEMANGLER = 747; SUPERNAL_SAVANT = 748; SOLAR_SAGE = 749; BOLIDE_BARON = 750; MOON_MAVEN = 751;
gpl-3.0
actionless/awesome
tests/examples/wibox/widget/graph/scale1.lua
2
1714
--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 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 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 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 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 w1 = --DOC_HIDE wibox.widget { scale = false, forced_height = 20, --DOC_HIDE widget = wibox.widget.graph, } --DOC_NEWLINE local w2 = --DOC_HIDE wibox.widget { scale = true, forced_height = 20, --DOC_HIDE widget = wibox.widget.graph, } for _, v in ipairs(data) do --DOC_HIDE w1:add_value(v) --DOC_HIDE w2:add_value(v) --DOC_HIDE end --DOC_HIDE parent:add(wibox.layout {--DOC_HIDE {--DOC_HIDE {--DOC_HIDE markup = "<b>scale = false</b>",--DOC_HIDE widget = wibox.widget.textbox,--DOC_HIDE },--DOC_HIDE w1,--DOC_HIDE layout = wibox.layout.fixed.vertical,--DOC_HIDE },--DOC_HIDE {--DOC_HIDE {--DOC_HIDE markup = "<b>scale = true</b>",--DOC_HIDE widget = wibox.widget.textbox,--DOC_HIDE },--DOC_HIDE w2,--DOC_HIDE layout = wibox.layout.fixed.vertical,--DOC_HIDE },--DOC_HIDE forced_width = 210, --DOC_HIDE spacing = 5, --DOC_HIDE layout = wibox.layout.flex.horizontal --DOC_HIDE }) --DOC_HIDE --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
Wedge009/wesnoth
data/campaigns/World_Conquest/lua/game_mechanics/utils.lua
4
5161
local on_event = wesnoth.require "on_event" local wc2_utils = {} function wc2_utils.set_to_array(s, res) res = res or {} for k,v in pairs(s) do table.insert(res, k) end table.sort( res ) return res end function wc2_utils.remove_duplicates(t) local found = {} for i = #t, 1, -1 do local v = t[i] if found[v] then table.remove(t, i) else found[v] = true end end end --comma seperated list function wc2_utils.pick_random(str, generator) local s2 = wml.variables[str] if s2 ~= nil or generator then local array = s2 and stringx.split(s2) or {} if #array == 0 and generator then array = generator() end local index = mathx.random(#array) local res = array[index] table.remove(array, index) wml.variables[str] = table.concat(array, ",") return res end end local function filtered_from_array(array, filter) local possible_indicies = {} for i, v in ipairs(array) do if filter(v) then table.insert(possible_indicies, i) end end if #possible_indicies == 0 then return nil end local index = possible_indicies[mathx.random(#possible_indicies)] return index end function wc2_utils.pick_random_filtered(str, generator, filter) local s2 = wml.variables[str] if s2 == nil and generator == nil then return end local array = s2 and stringx.split(s2 or "") or {} if #array == 0 and generator then array = generator() end local index = filtered_from_array(array, filter) if index == nil then array = generator() index = filtered_from_array(array, filter) end local res = array[index] table.remove(array, index) wml.variables[str] = table.concat(array, ",") return res end --wml array function wc2_utils.pick_random_t(str) local size = wml.variables[str .. ".length"] if size ~= 0 then local index = mathx.random(size) - 1 local res = wml.variables[str .. "[" .. index .. "]"] wml.variables[str .. "[" .. index .. "]"] = nil return res end end --like table concat but for tstrings. function wc2_utils.concat(t, sep) local res = t[1] if not res then return "" end for i = 2, #t do -- uses .. so we dont hae to call tostring. so this function can still return a tstring. res = res .. sep .. t[i] end return res end function wc2_utils.range(a1,a2) if a2 == nil then a2 = a1 a1 = 1 end local res = {} for i = a1, a2 do res[i] = i end return res end function wc2_utils.facing_each_other(u1,u2) u1.facing = wesnoth.map.get_relative_dir(u1.x, u1.y, u2.x, u2.y) u2.facing = wesnoth.map.get_relative_dir(u2.x, u2.y, u1.x, u1.y) wesnoth.wml_actions.redraw {} end function wc2_utils.has_no_advances(u) return #u.advances_to == 0 end wc2_utils.global_vars = wesnoth.experimental.wml.global_vars.wc2 if rawget(_G, "wc2_menu_filters") == nil then wc2_menu_filters = {} end function wc2_utils.menu_item(t) local id_nospace = string.gsub(t.id, " ", "_") local cfg = {} on_event("start", function() wesnoth.wml_actions.set_menu_item { id = t.id, description = t.description, image = t.image, synced = t.synced, wml.tag.filter_location { lua_function="wc2_menu_filters." .. id_nospace, }, } end) if t.handler then on_event("menu_item_" .. t.id, t.handler) end wc2_menu_filters[id_nospace] = t.filter end function wc2_utils.get_fstring(t, key) local args = wml.get_child(t, key .. "_data") if args then args = wc2_utils.get_fstring_all(args) else args = {} end return stringx.vformat(t[key], args) end function wc2_utils.get_fstring_all(t) local res = {} for k,v in pairs(t) do res[k] = wc2_utils.get_fstring(t, k) end return res end -- populates wc2_utils.world_conquest_data, reads [world_conquest_data] from all [resource]s and [era] function wc2_utils.load_wc2_data() if wc2_utils.world_conquest_data == nil then local data_dict = {} local ignore_list = {} for i,resource in ipairs(wesnoth.scenario.resources) do local world_conquest_data = wml.get_child(resource, "world_conquest_data") if world_conquest_data then for ignore in wml.child_range(world_conquest_data, "ignore") do ignore_list[ignore.id] = true end table.insert(data_dict, {id=resource.id, data = world_conquest_data}) end end table.insert(data_dict, {id="era", data = wesnoth.scenario.era}) -- make sure the result does not depend on the order in which these addons are loaded. table.sort(data_dict, function(a,b) return a.id<b.id end) wc2_utils.world_conquest_data = {} for i, v in ipairs(data_dict) do if not ignore_list[v.id] then for i2, tag in ipairs(v.data) do local tagname = tag[1] wc2_utils.world_conquest_data[tagname] = wc2_utils.world_conquest_data[tagname] or {} table.insert( wc2_utils.world_conquest_data[tagname], tag ) end end end end end -- reads the tag @a tagnaem from [world_conquest_data] provided by any of the ressoucrs or eras used in the game. -- returns a wml table that contains only tagname subtags. function wc2_utils.get_wc2_data(tagname) wc2_utils.load_wc2_data() --todo: maybe we shoudl clear wc2_utils.world_conquest_data[tagname] afterwards ? return wc2_utils.world_conquest_data[tagname] end return wc2_utils
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/Northern_San_dOria/npcs/Beadurinc.lua
4
1052
----------------------------------- -- Area: Northern San d'Oria -- NPC: Beadurinc -- Type: Standard NPC -- @zone: 231 -- @pos: -182.300 10.999 146.650 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0276); 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_[S]/npcs/Loillie.lua
4
1398
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Loillie -- @zone 80 -- @pos 78 -8 -23 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 8) then if(trade:hasItemQty(2528,1) and trade:getItemCount() == 1) then player:startEvent(0x01F) -- Gifts of Griffon Trade end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0265); -- Default Dialogue 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 == 0x01F) then -- Gifts Of Griffon Trade player:tradeComplete(); player:setVar("GiftsOfGriffonProg",9); end end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/spells/fowl_aubade.lua
2
2743
----------------------------------------- -- Spell: Fowl Aubade -- Increases Sleep 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; local sItem = caster:getEquipID(SLOT_RANGED); local sLvl = caster:getSkillLevel(SINGING_SKILL); -- Gets skill level of Singing local weapon = caster:getEquipID(SLOT_MAIN); local weapon2 = caster:getEquipID(SLOT_SUB); if (caster:getEquipID(SLOT_BODY) == 11093) then -- Aoidos Hongreline +2 duration = duration * 1.1; elseif(caster:getEquipID(SLOT_BODY) == 11193) then -- Aoidos Hongreline +1 duration = duration * 1.05; end if (caster:getEquipID(SLOT_NECK) == 11618) then -- Aoidos Matinee duration = duration * 1.1; end if (caster:getEquipID(SLOT_LEGS) == 28074) then -- Marduks Shalwar +1 duration = duration * 1.1; end if (weapon == 19000 or weapon2 == 19000) then -- Carnwenhan Lvl 75 duration = duration * 1.1; elseif (weapon == 19069 or weapon2 == 19069) then -- Carnwenhan Lvl 80 duration = duration * 1.2; elseif (weapon == 19089 or weapon2 == 19089) then -- Carnwenhan Lvl 85 duration = duration * 1.3; elseif (weapon == 19089 or weapon2 == 19089) then -- Carnwenhan Lvl 90 duration = duration * 1.4; elseif (weapon == 19719 or weapon2 == 19719) then -- Carnwenhan Lvl 95 duration = duration * 1.4; elseif (weapon == 19828 or weapon2 == 19828) then -- Carnwenhan Lvl 99 duration = duration * 1.5; elseif (weapon == 19957 or weapon2 == 19957) then -- Carnwenhan Lvl 99 - 2 duration = duration * 1.4; end if(sItem == 18342 or sItem == 18577 or sItem == 18578) then -- Gjallarhorn Lvl 75 - 80 - 85 power = power + 4; elseif(sItem == 18579 or sItem == 18580) then -- Gjallarhorn Lvl 90 - 95 power = power + 6; elseif(sItem == 18840 or sItem == 18572) then -- Gjallarhorn Lvl 99 - 99-2 power = power + 8; end if (sItem == 18575) then -- Daurdabla Lvl 90 duration = duration * 1.25; elseif (sItem == 18576 or sItem == 18839 or sItem == 18571) then -- Daurdabla Lvl 95 - 99 - 99-2 duration = duration * 1.3; end -- 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_AUBADE); target:addStatusEffect(EFFECT_AUBADE,power,0,duration); spell:setMsg(230); return EFFECT_AUBADE; end;
gpl-3.0
nofishonfriday/ReaScripts
Loudness/nofish_Normalize take pan (Loudness based).lua
1
4470
--[[ * Version: 1.0.1 * ReaScript Name: Normalize take pan (Loudness based) (experimental) * Author: nofish * Provides: [main] nofish_Normalize take pan (Loudness based) - Set threshold.lua * About: * Request: https://forum.cockos.com/showthread.php?t=178277 * Thread: https://forum.cockos.com/showthread.php?t=229544 (thanks ashcat_lt!) * works via adjusting take pan (stereo takes only) * in the accompanying script "Normalize take pan (Loudness based) - Set threshold.lua" can be set a a difference threshold (Loudness difference between l/r) over which the script starts processing --]] --[[ * Changelog: * v1.00 - January 01 2020 + initial release * v1.0.1 - April 01 2022 # clarify it's experimental --]] -- USER CONFIG AREA ----------------------------------------------------------- SHOW_INFO = true -- true/false: display info / progress in cosole ------------------------------------------------------- END OF USER CONFIG AREA -- Check whether the required version of REAPER / SWS is available if not reaper.NF_AnalyzeTakeLoudness then reaper.ShowMessageBox("This script requires REAPER v5.21 / SWS v2.9.6 or above.", "ERROR", 0) return false end -- check if user has set threshold if not reaper.HasExtState("nofish", "normalizeTakePanLoudnessBased_threshold") then reaper.ShowMessageBox("Threshold not set. Please run script 'Normalize take pan (Loudness based) - Set threshold.lua'", "ERROR", 0) return false else DIFFERENCE_THRESHOLD = tonumber(reaper.GetExtState("nofish", "normalizeTakePanLoudnessBased_threshold")) end local function Msg(str) reaper.ShowConsoleMsg(tostring(str) .. "\n") end function DB2VAL(x) return math.exp(x*0.11512925464970228420089957273422) end function Round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end -------------- --- Main() --- -------------- function Main() reaper.PreventUIRefresh(1) local selItemsCount = reaper.CountSelectedMediaItems(0) for i = 0, selItemsCount-1 do local item = reaper.GetSelectedMediaItem(0, i) local take = reaper.GetActiveTake(item) if take ~= nil then local source = reaper.GetMediaItemTake_Source(take) local numChan = reaper.GetMediaSourceNumChannels( source ) if (SHOW_INFO) then Msg("Processing item " .. i+1 .. " of " .. selItemsCount .. "...") Msg((reaper.GetTakeName(take))) end if numChan == 2 then origChanMode = reaper.GetMediaItemTakeInfo_Value(take, "I_CHANMODE") reaper.SetMediaItemTakeInfo_Value( take, "I_CHANMODE", 3) -- left chan retVal, LUintegrLeft = reaper.NF_AnalyzeTakeLoudness_IntegratedOnly(take) reaper.SetMediaItemTakeInfo_Value( take, "I_CHANMODE", 4) -- right chan retVal, LUintegrRight = reaper.NF_AnalyzeTakeLoudness_IntegratedOnly(take) reaper.SetMediaItemTakeInfo_Value( take, "I_CHANMODE", origChanMode) -- set chan mode back to original difference = LUintegrLeft - LUintegrRight differenceAbs = math.abs(difference) -- not totally sure what I'm doing here :/ val = DB2VAL(difference) if (val > 1) then val = 1 - 1 / val else val = -val end if (val < 0) then val = -1 - val end if (SHOW_INFO) then Msg("Loudness left channel: " .. LUintegrLeft .. " LUFSi") Msg("Loudness right channel: " .. LUintegrRight .. " LUFSi") Msg("difference: " .. differenceAbs) end if val <= 1.0 and val >= -1.0 and differenceAbs > DIFFERENCE_THRESHOLD then if (SHOW_INFO) then if val < 0 then Msg("Adjusting take pan: " .. Round(val*100) .. "%" .."L\n") else Msg("Adjusting take pan: " .. Round(val*100) .. "%" .. "R\n") end end reaper.SetMediaItemTakeInfo_Value(take, "D_PAN", val) else Msg("nothing processed.\n") end else -- if numChan == 2 then Msg("Not a stereo take, skipping..\n") end end -- if take ~= nil then end -- for i = 0, selItemsCount-1 do -- Msg("") reaper.PreventUIRefresh(-1) reaper.Undo_OnStateChange("Script: Normalize take pan (Loudness based)") end -- main() Main() reaper.defer(function() end) -- don't create unnecessary undo point
gpl-2.0
Fatalerror66/ffxi-a
scripts/globals/items/leremieu_salad.lua
2
1616
----------------------------------------- -- ID: 5185 -- Item: leremieu_salad -- Food Effect: 240Min, All Races ----------------------------------------- -- Health 20 -- Magic 20 -- Dexterity 4 -- Agility 4 -- Vitality 6 -- Charisma 4 -- Defense % 25 -- Defense Cap 160 ----------------------------------------- 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,5185); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, 6); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 160); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, 6); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 160); end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/West_Ronfaure/npcs/qm2.lua
2
1509
----------------------------------- -- Area: West Ronfaure -- NPC: ??? -- @zone: 100 -- @pos: -550 -0 -542 -- -- Involved in Quest: The Dismayed Customer ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 2) then player:addKeyItem(GULEMONTS_DOCUMENT); player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT); player:setVar("theDismayedCustomer", 0); else player:messageSpecial(DISMAYED_CUSTOMER); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Yhgenomics/premake-core
src/actions/vstudio/vs2010_vcxproj.lua
2
43554
-- -- vs2010_vcxproj.lua -- Generate a Visual Studio 201x C/C++ project. -- Copyright (c) 2009-2015 Jason Perkins and the Premake project -- premake.vstudio.vc2010 = {} local p = premake local vstudio = p.vstudio local project = p.project local config = p.config local fileconfig = p.fileconfig local tree = p.tree local m = p.vstudio.vc2010 --- -- Add namespace for element definition lists for premake.callArray() --- m.elements = {} -- -- Generate a Visual Studio 201x C++ project, with support for the new platforms API. -- m.elements.project = function(prj) return { m.xmlDeclaration, m.project, m.projectConfigurations, m.globals, m.importDefaultProps, m.configurationPropertiesGroup, m.importLanguageSettings, m.importExtensionSettings, m.propertySheetGroup, m.userMacros, m.outputPropertiesGroup, m.itemDefinitionGroups, m.assemblyReferences, m.files, m.projectReferences, m.importLanguageTargets, m.importExtensionTargets, } end function m.generate(prj) p.utf8() p.callArray(m.elements.project, prj) p.out('</Project>') end -- -- Output the XML declaration and opening <Project> tag. -- function m.project(prj) local action = p.action.current() p.push('<Project DefaultTargets="Build" ToolsVersion="%s" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">', action.vstudio.toolsVersion) end -- -- Write out the list of project configurations, which pairs build -- configurations with architectures. -- function m.projectConfigurations(prj) -- build a list of all architectures used in this project local platforms = {} for cfg in project.eachconfig(prj) do local arch = vstudio.archFromConfig(cfg, true) if not table.contains(platforms, arch) then table.insert(platforms, arch) end end local configs = {} p.push('<ItemGroup Label="ProjectConfigurations">') for cfg in project.eachconfig(prj) do for _, arch in ipairs(platforms) do local prjcfg = vstudio.projectConfig(cfg, arch) if not configs[prjcfg] then configs[prjcfg] = prjcfg p.push('<ProjectConfiguration Include="%s">', vstudio.projectConfig(cfg, arch)) p.x('<Configuration>%s</Configuration>', vstudio.projectPlatform(cfg)) p.w('<Platform>%s</Platform>', arch) p.pop('</ProjectConfiguration>') end end end p.pop('</ItemGroup>') end -- -- Write out the TargetFrameworkVersion property. -- function m.targetFramework(prj) local action = p.action.current() local tools = string.format(' ToolsVersion="%s"', action.vstudio.toolsVersion) local framework = prj.framework or action.vstudio.targetFramework or "4.0" p.w('<TargetFrameworkVersion>v%s</TargetFrameworkVersion>', framework) end -- -- Write out the Globals property group. -- m.elements.globals = function(prj) return { m.projectGuid, m.ignoreWarnDuplicateFilename, m.keyword, m.projectName, } end function m.globals(prj) m.propertyGroup(nil, "Globals") p.callArray(m.elements.globals, prj) p.pop('</PropertyGroup>') end -- -- Write out the configuration property group: what kind of binary it -- produces, and some global settings. -- m.elements.configurationProperties = function(cfg) if cfg.kind == p.UTILITY then return { m.configurationType, m.platformToolset, } else return { m.configurationType, m.useDebugLibraries, m.useOfMfc, m.useOfAtl, m.clrSupport, m.characterSet, m.platformToolset, m.wholeProgramOptimization, m.nmakeOutDirs, } end end function m.configurationProperties(cfg) m.propertyGroup(cfg, "Configuration") p.callArray(m.elements.configurationProperties, cfg) p.pop('</PropertyGroup>') end function m.configurationPropertiesGroup(prj) for cfg in project.eachconfig(prj) do m.configurationProperties(cfg) end end -- -- Write the output property group, which includes the output and intermediate -- directories, manifest, etc. -- m.elements.outputProperties = function(cfg) if cfg.kind == p.UTILITY then return { m.outDir, m.intDir, m.extensionsToDeleteOnClean, } else return { m.linkIncremental, m.ignoreImportLibrary, m.outDir, m.outputFile, m.intDir, m.targetName, m.targetExt, m.includePath, m.libraryPath, m.imageXexOutput, m.generateManifest, m.extensionsToDeleteOnClean, m.executablePath, } end end function m.outputProperties(cfg) if not vstudio.isMakefile(cfg) then m.propertyGroup(cfg) p.callArray(m.elements.outputProperties, cfg) p.pop('</PropertyGroup>') end end function m.outputPropertiesGroup(prj) for cfg in project.eachconfig(prj) do m.outputProperties(cfg) m.nmakeProperties(cfg) end end -- -- Write the NMake property group for Makefile projects, which includes the custom -- build commands, output file location, etc. -- function m.nmakeProperties(cfg) if vstudio.isMakefile(cfg) then m.propertyGroup(cfg) m.nmakeOutput(cfg) m.nmakeCommandLine(cfg, cfg.buildcommands, "Build") m.nmakeCommandLine(cfg, cfg.rebuildcommands, "ReBuild") m.nmakeCommandLine(cfg, cfg.cleancommands, "Clean") p.pop('</PropertyGroup>') end end -- -- Write a configuration's item definition group, which contains all -- of the per-configuration compile and link settings. -- m.elements.itemDefinitionGroup = function(cfg) if cfg.kind == p.UTILITY then return { m.ruleVars, m.buildEvents, } else return { m.clCompile, m.resourceCompile, m.linker, m.manifest, m.buildEvents, m.imageXex, m.deploy, m.ruleVars, m.buildLog, } end end function m.itemDefinitionGroup(cfg) if not vstudio.isMakefile(cfg) then p.push('<ItemDefinitionGroup %s>', m.condition(cfg)) p.callArray(m.elements.itemDefinitionGroup, cfg) p.pop('</ItemDefinitionGroup>') else if cfg == project.getfirstconfig(cfg.project) then p.w('<ItemDefinitionGroup>') p.w('</ItemDefinitionGroup>') end end end function m.itemDefinitionGroups(prj) for cfg in project.eachconfig(prj) do m.itemDefinitionGroup(cfg) end end -- -- Write the the <ClCompile> compiler settings block. -- m.elements.clCompile = function(cfg) return { m.precompiledHeader, m.warningLevel, m.treatWarningAsError, m.disableSpecificWarnings, m.treatSpecificWarningsAsErrors, m.basicRuntimeChecks, m.clCompilePreprocessorDefinitions, m.clCompileUndefinePreprocessorDefinitions, m.clCompileAdditionalIncludeDirectories, m.clCompileAdditionalUsingDirectories, m.forceIncludes, m.debugInformationFormat, m.programDataBaseFileName, m.optimization, m.functionLevelLinking, m.intrinsicFunctions, m.minimalRebuild, m.omitFramePointers, m.stringPooling, m.runtimeLibrary, m.omitDefaultLib, m.exceptionHandling, m.runtimeTypeInfo, m.bufferSecurityCheck, m.treatWChar_tAsBuiltInType, m.floatingPointModel, m.inlineFunctionExpansion, m.enableEnhancedInstructionSet, m.multiProcessorCompilation, m.additionalCompileOptions, m.compileAs, m.callingConvention, } end function m.clCompile(cfg) p.push('<ClCompile>') p.callArray(m.elements.clCompile, cfg) p.pop('</ClCompile>') end -- -- Write out the resource compiler block. -- m.elements.resourceCompile = function(cfg) return { m.resourcePreprocessorDefinitions, m.resourceAdditionalIncludeDirectories, m.culture, } end function m.resourceCompile(cfg) if cfg.system ~= p.XBOX360 and p.config.hasFile(cfg, path.isresourcefile) then local contents = p.capture(function () p.push() p.callArray(m.elements.resourceCompile, cfg) p.pop() end) if #contents > 0 then p.push('<ResourceCompile>') p.outln(contents) p.pop('</ResourceCompile>') end end end -- -- Write out the linker tool block. -- m.elements.linker = function(cfg, explicit) return { m.link, m.lib, m.linkLibraryDependencies, } end function m.linker(cfg) local explicit = vstudio.needsExplicitLink(cfg) p.callArray(m.elements.linker, cfg, explicit) end m.elements.link = function(cfg, explicit) if cfg.kind == p.STATICLIB then return { m.subSystem, m.generateDebugInformation, m.optimizeReferences, } else return { m.subSystem, m.generateDebugInformation, m.optimizeReferences, m.additionalDependencies, m.additionalLibraryDirectories, m.importLibrary, m.entryPointSymbol, m.generateMapFile, m.moduleDefinitionFile, m.treatLinkerWarningAsErrors, m.ignoreDefaultLibraries, m.additionalLinkOptions, } end end function m.link(cfg, explicit) local contents = p.capture(function () p.push() p.callArray(m.elements.link, cfg, explicit) p.pop() end) if #contents > 0 then p.push('<Link>') p.outln(contents) p.pop('</Link>') end end m.elements.lib = function(cfg, explicit) if cfg.kind == p.STATICLIB then return { m.treatLinkerWarningAsErrors, m.additionalLinkOptions, } else return {} end end function m.lib(cfg, explicit) local contents = p.capture(function () p.push() p.callArray(m.elements.lib, cfg, explicit) p.pop() end) if #contents > 0 then p.push('<Lib>') p.outln(contents) p.pop('</Lib>') end end -- -- Write the manifest section. -- function m.manifest(cfg) if cfg.kind ~= p.STATICLIB then -- get the manifests files local manifests = {} for _, fname in ipairs(cfg.files) do if path.getextension(fname) == ".manifest" then table.insert(manifests, project.getrelative(cfg.project, fname)) end end if #manifests > 0 then p.push('<Manifest>') m.element("AdditionalManifestFiles", nil, "%s %%(AdditionalManifestFiles)", table.concat(manifests, " ")) p.pop('</Manifest>') end end end --- -- Write out the pre- and post-build event settings. --- function m.buildEvents(cfg) local write = function (event) local name = event .. "Event" local field = event:lower() local steps = cfg[field .. "commands"] local msg = cfg[field .. "message"] if #steps > 0 then steps = os.translateCommands(steps, p.WINDOWS) p.push('<%s>', name) p.x('<Command>%s</Command>', table.implode(steps, "", "", "\r\n")) if msg then p.x('<Message>%s</Message>', msg) end p.pop('</%s>', name) end end write("PreBuild") write("PreLink") write("PostBuild") end --- -- Write out project-level custom rule variables. --- function m.ruleVars(cfg) for i = 1, #cfg.rules do local rule = p.global.getRule(cfg.rules[i]) local contents = p.capture(function () p.push() for prop in p.rule.eachProperty(rule) do local fld = p.rule.getPropertyField(rule, prop) local value = cfg[fld.name] if value ~= nil then if fld.kind == "path" then value = vstudio.path(cfg, value) else value = p.rule.getPropertyString(rule, prop, value) end if value ~= nil and #value > 0 then m.element(prop.name, nil, '%s', value) end end end p.pop() end) if #contents > 0 then p.push('<%s>', rule.name) p.outln(contents) p.pop('</%s>', rule.name) end end end -- -- Reference any managed assemblies listed in the links() -- function m.assemblyReferences(prj) -- Visual Studio doesn't support per-config references; use -- whatever is contained in the first configuration local cfg = project.getfirstconfig(prj) local refs = config.getlinks(cfg, "system", "fullpath", "managed") if #refs > 0 then p.push('<ItemGroup>') for i = 1, #refs do local value = refs[i] -- If the link contains a '/' then it is a relative path to -- a local assembly. Otherwise treat it as a system assembly. if value:find('/', 1, true) then p.push('<Reference Include="%s">', path.getbasename(value)) p.x('<HintPath>%s</HintPath>', path.translate(value)) p.pop('</Reference>') else p.x('<Reference Include="%s" />', path.getbasename(value)) end end p.pop('</ItemGroup>') end end --- -- Write out the list of source code files, and any associated configuration. --- m.elements.files = function(prj, groups) return { m.clIncludeFiles, m.clCompileFiles, m.noneFiles, m.resourceCompileFiles, m.customBuildFiles, m.customRuleFiles, m.midlFiles } end function m.files(prj) local groups = m.categorizeSources(prj) p.callArray(m.elements.files, prj, groups) end m.elements.ClCompileFile = function(cfg, file) return {} end m.elements.ClCompileFileCfg = function(fcfg, condition) if fcfg then return { m.excludedFromBuild, m.objectFileName, m.clCompilePreprocessorDefinitions, m.clCompileUndefinePreprocessorDefinitions, m.optimization, m.forceIncludes, m.precompiledHeader, m.enableEnhancedInstructionSet, m.additionalCompileOptions, m.disableSpecificWarnings, m.treatSpecificWarningsAsErrors } else return { m.excludedFromBuild } end end function m.clCompileFiles(prj, groups) m.emitFiles(prj, groups, "ClCompile") end m.elements.ClIncludeFile = function(cfg, file) return {} end m.elements.ClIncludeFileCfg = function(fcfg, condition) return {} end function m.clIncludeFiles(prj, groups) m.emitFiles(prj, groups, "ClInclude") end m.elements.CustomBuildFile = function(cfg, file) return { m.fileType } end m.elements.CustomBuildFileCfg = function(fcfg, condition) return { m.excludedFromBuild, m.buildCommands, m.buildOutputs, m.buildMessage, m.buildAdditionalInputs } end function m.customBuildFiles(prj, groups) m.emitFiles(prj, groups, "CustomBuild", function (cfg, fcfg) return fileconfig.hasCustomBuildRule(fcfg) end) end function m.customRuleFiles(prj, groups) for i = 1, #prj.rules do local rule = p.global.getRule(prj.rules[i]) local files = groups[rule.name] if files and #files > 0 then p.push('<ItemGroup>') for _, file in ipairs(files) do local contents = p.capture(function() p.push() for prop in p.rule.eachProperty(rule) do local fld = p.rule.getPropertyField(rule, prop) for cfg in project.eachconfig(prj) do local fcfg = fileconfig.getconfig(file, cfg) if fcfg and fcfg[fld.name] then local value = p.rule.getPropertyString(rule, prop, fcfg[fld.name]) if value and #value > 0 then m.element(prop.name, m.condition(cfg), '%s', value) end end end end p.pop() end) if #contents > 0 then p.push('<%s Include=\"%s\">', rule.name, path.translate(file.relpath)) p.outln(contents) p.pop('</%s>', rule.name) else p.x('<%s Include=\"%s\" />', rule.name, path.translate(file.relpath)) end end p.pop('</ItemGroup>') end end end m.elements.NoneFile = function(cfg, file) return {} end m.elements.NoneFileCfg = function(fcfg, condition) return {} end function m.noneFiles(prj, groups) m.emitFiles(prj, groups, "None") end m.elements.ResourceCompileFile = function(cfg, file) return {} end m.elements.ResourceCompileFileCfg = function(fcfg, condition) return { m.excludedFromBuild } end function m.resourceCompileFiles(prj, groups) m.emitFiles(prj, groups, "ResourceCompile", function(cfg) return cfg.system == p.WINDOWS end) end m.elements.MidlFile = function(cfg, file) return {} end m.elements.MidlFileCfg = function(fcfg, condition) return { m.excludedFromBuild } end function m.midlFiles(prj, groups) m.emitFiles(prj, groups, "Midl", function(cfg) return cfg.system == p.WINDOWS end) end function m.categorizeSources(prj) local groups = prj._vc2010_sources if groups then return groups end groups = {} prj._vc2010_sources = groups local tr = project.getsourcetree(prj) tree.traverse(tr, { onleaf = function(node) local cat = m.categorizeFile(prj, node) groups[cat] = groups[cat] or {} table.insert(groups[cat], node) end }) -- sort by relative-to path; otherwise VS will reorder the files for group, files in pairs(groups) do table.sort(files, function (a, b) return a.relpath < b.relpath end) end return groups end function m.categorizeFile(prj, file) -- If any configuration for this file uses a custom build step, -- that's the category to use for cfg in project.eachconfig(prj) do local fcfg = fileconfig.getconfig(file, cfg) if fileconfig.hasCustomBuildRule(fcfg) then return "CustomBuild" end end -- If there is a custom rule associated with it, use that local rule = p.global.getRuleForFile(file.name, prj.rules) if rule then return rule.name end -- Otherwise use the file extension to deduce a category if path.iscppfile(file.name) then return "ClCompile" elseif path.iscppheader(file.name) then return "ClInclude" elseif path.isresourcefile(file.name) then return "ResourceCompile" elseif path.isidlfile(file.name) then return "Midl" else return "None" end end function m.emitFiles(prj, groups, group, check) local files = groups[group] if files and #files > 0 then p.push('<ItemGroup>') for _, file in ipairs(files) do local contents = p.capture(function () p.push() p.callArray(m.elements[group .. "File"], cfg, file) for cfg in project.eachconfig(prj) do local fcfg = fileconfig.getconfig(file, cfg) if not check or check(cfg, fcfg) then p.callArray(m.elements[group .. "FileCfg"], fcfg, m.condition(cfg)) end end p.pop() end) local rel = path.translate(file.relpath) if #contents > 0 then p.push('<%s Include="%s">', group, rel) p.outln(contents) p.pop('</%s>', group) else p.x('<%s Include="%s" />', group, rel) end end p.pop('</ItemGroup>') end end -- -- Generate the list of project dependencies. -- m.elements.projectReferences = function(prj, ref) if prj.clr ~= p.OFF then return { m.referenceProject, m.referencePrivate, m.referenceOutputAssembly, m.referenceCopyLocalSatelliteAssemblies, m.referenceLinkLibraryDependencies, m.referenceUseLibraryDependences, } else return { m.referenceProject, } end end function m.projectReferences(prj) local refs = project.getdependencies(prj, 'linkOnly') if #refs > 0 then -- sort dependencies by uuid. table.sort(refs, function(a,b) return a.uuid < b.uuid end) p.push('<ItemGroup>') for _, ref in ipairs(refs) do local relpath = vstudio.path(prj, vstudio.projectfile(ref)) p.push('<ProjectReference Include=\"%s\">', relpath) p.callArray(m.elements.projectReferences, prj, ref) p.pop('</ProjectReference>') end p.pop('</ItemGroup>') end end --------------------------------------------------------------------------- -- -- Handlers for individual project elements -- --------------------------------------------------------------------------- function m.additionalDependencies(cfg, explicit) local links -- check to see if this project uses an external toolset. If so, let the -- toolset define the format of the links local toolset = config.toolset(cfg) if toolset then links = toolset.getlinks(cfg, not explicit) else links = vstudio.getLinks(cfg, explicit) end if #links > 0 then links = path.translate(table.concat(links, ";")) m.element("AdditionalDependencies", nil, "%s;%%(AdditionalDependencies)", links) end end function m.additionalIncludeDirectories(cfg, includedirs) if #includedirs > 0 then local dirs = vstudio.path(cfg, includedirs) if #dirs > 0 then m.element("AdditionalIncludeDirectories", nil, "%s;%%(AdditionalIncludeDirectories)", table.concat(dirs, ";")) end end end function m.additionalLibraryDirectories(cfg) if #cfg.libdirs > 0 then local dirs = table.concat(vstudio.path(cfg, cfg.libdirs), ";") m.element("AdditionalLibraryDirectories", nil, "%s;%%(AdditionalLibraryDirectories)", dirs) end end function m.additionalUsingDirectories(cfg) if #cfg.usingdirs > 0 then local dirs = table.concat(vstudio.path(cfg, cfg.usingdirs), ";") m.element("AdditionalUsingDirectories", nil, "%s;%%(AdditionalUsingDirectories)", dirs) end end function m.additionalCompileOptions(cfg, condition) if #cfg.buildoptions > 0 then local opts = table.concat(cfg.buildoptions, " ") m.element("AdditionalOptions", condition, '%s %%(AdditionalOptions)', opts) end end function m.additionalLinkOptions(cfg) if #cfg.linkoptions > 0 then local opts = table.concat(cfg.linkoptions, " ") m.element("AdditionalOptions", nil, "%s %%(AdditionalOptions)", opts) end end function m.basicRuntimeChecks(cfg) local runtime = config.getruntime(cfg) if cfg.flags.NoRuntimeChecks or (config.isOptimizedBuild(cfg) and runtime:endswith("Debug")) then m.element("BasicRuntimeChecks", nil, "Default") end end function m.buildAdditionalInputs(fcfg, condition) if fcfg.buildinputs and #fcfg.buildinputs > 0 then local inputs = project.getrelative(fcfg.project, fcfg.buildinputs) m.element("AdditionalInputs", condition, '%s', table.concat(inputs, ";")) end end function m.buildCommands(fcfg, condition) local commands = os.translateCommands(fcfg.buildcommands, p.WINDOWS) commands = table.concat(commands,'\r\n') m.element("Command", condition, '%s', commands) end function m.buildLog(cfg) if cfg.buildlog and #cfg.buildlog > 0 then p.push('<BuildLog>') m.element("Path", nil, "%s", vstudio.path(cfg, cfg.buildlog)) p.pop('</BuildLog>') end end function m.buildMessage(fcfg, condition) if fcfg.buildmessage then m.element("Message", condition, '%s', fcfg.buildmessage) end end function m.buildOutputs(fcfg, condition) local outputs = project.getrelative(fcfg.project, fcfg.buildoutputs) m.element("Outputs", condition, '%s', table.concat(outputs, ";")) end function m.characterSet(cfg) if not vstudio.isMakefile(cfg) then m.element("CharacterSet", nil, iif(cfg.flags.Unicode, "Unicode", "MultiByte")) end end function m.wholeProgramOptimization(cfg) if cfg.flags.LinkTimeOptimization then m.element("WholeProgramOptimization", nil, "true") end end function m.clCompileAdditionalIncludeDirectories(cfg) m.additionalIncludeDirectories(cfg, cfg.includedirs) end function m.clCompileAdditionalUsingDirectories(cfg) m.additionalUsingDirectories(cfg, cfg.usingdirs) end function m.clCompilePreprocessorDefinitions(cfg, condition) m.preprocessorDefinitions(cfg, cfg.defines, false, condition) end function m.clCompileUndefinePreprocessorDefinitions(cfg, condition) m.undefinePreprocessorDefinitions(cfg, cfg.undefines, false, condition) end function m.clrSupport(cfg) local value if cfg.clr == "On" or cfg.clr == "Unsafe" then value = "true" elseif cfg.clr ~= p.OFF then value = cfg.clr end if value then m.element("CLRSupport", nil, value) end end function m.compileAs(cfg) if cfg.project.language == "C" then m.element("CompileAs", nil, "CompileAsC") end end function m.configurationType(cfg) local types = { SharedLib = "DynamicLibrary", StaticLib = "StaticLibrary", ConsoleApp = "Application", WindowedApp = "Application", Makefile = "Makefile", None = "Makefile", Utility = "Utility", } m.element("ConfigurationType", nil, types[cfg.kind]) end function m.culture(cfg) local value = vstudio.cultureForLocale(cfg.locale) if value then m.element("Culture", nil, "0x%04x", tostring(value)) end end function m.debugInformationFormat(cfg) local value local tool, toolVersion = p.config.toolset(cfg) if cfg.flags.Symbols then if cfg.debugformat == "c7" then value = "OldStyle" elseif cfg.architecture == "x86_64" or cfg.clr ~= p.OFF or config.isOptimizedBuild(cfg) or cfg.editandcontinue == p.OFF or (toolVersion and toolVersion:startswith("LLVM-vs")) then value = "ProgramDatabase" else value = "EditAndContinue" end end if value then m.element("DebugInformationFormat", nil, value) end end function m.deploy(cfg) if cfg.system == p.XBOX360 then p.push('<Deploy>') m.element("DeploymentType", nil, "CopyToHardDrive") m.element("DvdEmulationType", nil, "ZeroSeekTimes") m.element("DeploymentFiles", nil, "$(RemoteRoot)=$(ImagePath);") p.pop('</Deploy>') end end function m.enableEnhancedInstructionSet(cfg, condition) local v local x = cfg.vectorextensions if x == "AVX" and _ACTION > "vs2010" then v = "AdvancedVectorExtensions" elseif x == "AVX2" and _ACTION > "vs2012" then v = "AdvancedVectorExtensions2" elseif cfg.architecture ~= "x86_64" then if x == "SSE2" or x == "SSE3" or x == "SSSE3" or x == "SSE4.1" then v = "StreamingSIMDExtensions2" elseif x == "SSE" then v = "StreamingSIMDExtensions" end end if v then m.element('EnableEnhancedInstructionSet', condition, v) end end function m.entryPointSymbol(cfg) if cfg.entrypoint then m.element("EntryPointSymbol", nil, cfg.entrypoint) else if (cfg.kind == premake.CONSOLEAPP or cfg.kind == premake.WINDOWEDAPP) and not cfg.flags.WinMain and cfg.clr == p.OFF and cfg.system ~= p.XBOX360 then m.element("EntryPointSymbol", nil, "mainCRTStartup") end end end function m.exceptionHandling(cfg) local value if cfg.exceptionhandling == p.OFF then m.element("ExceptionHandling", nil, "false") elseif cfg.exceptionhandling == "SEH" then m.element("ExceptionHandling", nil, "Async") end end function m.excludedFromBuild(filecfg, condition) if not filecfg or filecfg.flags.ExcludeFromBuild then m.element("ExcludedFromBuild", condition, "true") end end function m.extensionsToDeleteOnClean(cfg) if #cfg.cleanextensions > 0 then local value = table.implode(cfg.cleanextensions, "*", ";", "") m.element("ExtensionsToDeleteOnClean", nil, value .. "$(ExtensionsToDeleteOnClean)") end end function m.fileType(cfg, file) m.element("FileType", nil, "Document") end function m.floatingPointModel(cfg) if cfg.floatingpoint then m.element("FloatingPointModel", nil, cfg.floatingpoint) end end function m.inlineFunctionExpansion(cfg) if cfg.inlining then local types = { Default = "Default", Disabled = "Disabled", Explicit = "OnlyExplicitInline", Auto = "AnySuitable", } m.element("InlineFunctionExpansion", nil, types[cfg.inlining]) end end function m.forceIncludes(cfg, condition) if #cfg.forceincludes > 0 then local includes = vstudio.path(cfg, cfg.forceincludes) if #includes > 0 then m.element("ForcedIncludeFiles", condition, table.concat(includes, ';')) end end if #cfg.forceusings > 0 then local usings = vstudio.path(cfg, cfg.forceusings) if #usings > 0 then m.element("ForcedUsingFiles", condition, table.concat(usings, ';')) end end end function m.functionLevelLinking(cfg) if config.isOptimizedBuild(cfg) then m.element("FunctionLevelLinking", nil, "true") end end function m.generateDebugInformation(cfg) m.element("GenerateDebugInformation", nil, tostring(cfg.flags.Symbols ~= nil)) end function m.generateManifest(cfg) if cfg.flags.NoManifest then m.element("GenerateManifest", nil, "false") end end function m.generateMapFile(cfg) if cfg.flags.Maps then m.element("GenerateMapFile", nil, "true") end end function m.ignoreDefaultLibraries(cfg) if #cfg.ignoredefaultlibraries > 0 then local ignored = cfg.ignoredefaultlibraries for i = 1, #ignored do -- Add extension if required if not p.tools.msc.getLibraryExtensions()[ignored[i]:match("[^.]+$")] then ignored[i] = path.appendextension(ignored[i], ".lib") end end m.element("IgnoreSpecificDefaultLibraries", condition, table.concat(ignored, ';')) end end function m.ignoreWarnDuplicateFilename(prj) -- VS 2013 warns on duplicate file names, even those files which are -- contained in different, mututally exclusive configurations. See: -- http://connect.microsoft.com/VisualStudio/feedback/details/797460/incorrect-warning-msb8027-reported-for-files-excluded-from-build -- Premake already adds unique object names to conflicting file names, so -- just go ahead and disable that warning. if _ACTION > "vs2012" then m.element("IgnoreWarnCompileDuplicatedFilename", nil, "true") end end function m.ignoreImportLibrary(cfg) if cfg.kind == p.SHAREDLIB and cfg.flags.NoImportLib then m.element("IgnoreImportLibrary", nil, "true") end end function m.imageXex(cfg) if cfg.system == p.XBOX360 then p.push('<ImageXex>') if cfg.configfile then m.element("ConfigurationFile", nil, "%s", cfg.configfile) else p.w('<ConfigurationFile>') p.w('</ConfigurationFile>') end p.w('<AdditionalSections>') p.w('</AdditionalSections>') p.pop('</ImageXex>') end end function m.imageXexOutput(cfg) if cfg.system == p.XBOX360 then m.element("ImageXexOutput", nil, "%s", "$(OutDir)$(TargetName).xex") end end function m.importLanguageTargets(prj) p.w('<Import Project="$(VCTargetsPath)\\Microsoft.Cpp.targets" />') end m.elements.importExtensionTargets = function(prj) return { m.importRuleTargets, } end function m.importExtensionTargets(prj) p.push('<ImportGroup Label="ExtensionTargets">') p.callArray(m.elements.importExtensionTargets, prj) p.pop('</ImportGroup>') end function m.importRuleTargets(prj) for i = 1, #prj.rules do local rule = p.global.getRule(prj.rules[i]) local loc = vstudio.path(prj, p.filename(rule, ".targets")) p.x('<Import Project="%s" />', loc) end end function m.importDefaultProps(prj) p.w('<Import Project="$(VCTargetsPath)\\Microsoft.Cpp.Default.props" />') end function m.importLanguageSettings(prj) p.w('<Import Project="$(VCTargetsPath)\\Microsoft.Cpp.props" />') end m.elements.importExtensionSettings = function(prj) return { m.importRuleSettings, } end function m.importExtensionSettings(prj) p.push('<ImportGroup Label="ExtensionSettings">') p.callArray(m.elements.importExtensionSettings, prj) p.pop('</ImportGroup>') end function m.importRuleSettings(prj) for i = 1, #prj.rules do local rule = p.global.getRule(prj.rules[i]) local loc = vstudio.path(prj, p.filename(rule, ".props")) p.x('<Import Project="%s" />', loc) end end function m.importLibrary(cfg) if cfg.kind == p.SHAREDLIB then m.element("ImportLibrary", nil, "%s", path.translate(cfg.linktarget.relpath)) end end function m.includePath(cfg) local dirs = vstudio.path(cfg, cfg.sysincludedirs) if #dirs > 0 then m.element("IncludePath", nil, "%s;$(IncludePath)", table.concat(dirs, ";")) end end function m.intDir(cfg) local objdir = vstudio.path(cfg, cfg.objdir) m.element("IntDir", nil, "%s\\", objdir) end function m.intrinsicFunctions(cfg) if config.isOptimizedBuild(cfg) then m.element("IntrinsicFunctions", nil, "true") end end function m.keyword(prj) -- try to determine what kind of targets we're building here local isWin, isManaged, isMakefile for cfg in project.eachconfig(prj) do if cfg.system == p.WINDOWS then isWin = true end if cfg.clr ~= p.OFF then isManaged = true end if vstudio.isMakefile(cfg) then isMakefile = true end end if isWin then if isMakefile then m.element("Keyword", nil, "MakeFileProj") else if isManaged then m.targetFramework(prj) m.element("Keyword", nil, "ManagedCProj") else m.element("Keyword", nil, "Win32Proj") end m.element("RootNamespace", nil, "%s", prj.name) end end end function m.libraryPath(cfg) local dirs = vstudio.path(cfg, cfg.syslibdirs) if #dirs > 0 then m.element("LibraryPath", nil, "%s;$(LibraryPath)", table.concat(dirs, ";")) end end function m.linkIncremental(cfg) if cfg.kind ~= p.STATICLIB then m.element("LinkIncremental", nil, "%s", tostring(config.canLinkIncremental(cfg))) end end function m.linkLibraryDependencies(cfg, explicit) -- Left to its own devices, VS will happily link against a project dependency -- that has been excluded from the build. As a workaround, disable dependency -- linking and list all siblings explicitly if explicit then p.push('<ProjectReference>') m.element("LinkLibraryDependencies", nil, "false") p.pop('</ProjectReference>') end end function m.minimalRebuild(cfg) if config.isOptimizedBuild(cfg) or cfg.flags.NoMinimalRebuild or cfg.flags.MultiProcessorCompile or cfg.debugformat == p.C7 then m.element("MinimalRebuild", nil, "false") end end function m.moduleDefinitionFile(cfg) local df = config.findfile(cfg, ".def") if df then m.element("ModuleDefinitionFile", nil, "%s", df) end end function m.multiProcessorCompilation(cfg) if cfg.flags.MultiProcessorCompile then m.element("MultiProcessorCompilation", nil, "true") end end function m.nmakeCommandLine(cfg, commands, phase) if #commands > 0 then commands = os.translateCommands(commands, p.WINDOWS) commands = table.concat(p.esc(commands), p.eol()) p.w('<NMake%sCommandLine>%s</NMake%sCommandLine>', phase, commands, phase) end end function m.nmakeOutDirs(cfg) if vstudio.isMakefile(cfg) then m.outDir(cfg) m.intDir(cfg) end end function m.nmakeOutput(cfg) m.element("NMakeOutput", nil, "$(OutDir)%s", cfg.buildtarget.name) end function m.objectFileName(fcfg) if fcfg.objname ~= fcfg.basename then m.element("ObjectFileName", m.condition(fcfg.config), "$(IntDir)\\%s.obj", fcfg.objname) end end function m.omitDefaultLib(cfg) if cfg.flags.OmitDefaultLibrary then m.element("OmitDefaultLibName", nil, "true") end end function m.omitFramePointers(cfg) if cfg.flags.NoFramePointer then m.element("OmitFramePointers", nil, "true") end end function m.optimizeReferences(cfg) if config.isOptimizedBuild(cfg) then m.element("EnableCOMDATFolding", nil, "true") m.element("OptimizeReferences", nil, "true") end end function m.optimization(cfg, condition) local map = { Off="Disabled", On="Full", Debug="Disabled", Full="Full", Size="MinSpace", Speed="MaxSpeed" } local value = map[cfg.optimize] if value or not condition then m.element('Optimization', condition, value or "Disabled") end end function m.outDir(cfg) local outdir = vstudio.path(cfg, cfg.buildtarget.directory) m.element("OutDir", nil, "%s\\", outdir) end function m.outputFile(cfg) if cfg.system == p.XBOX360 then m.element("OutputFile", nil, "$(OutDir)%s", cfg.buildtarget.name) end end function m.executablePath(cfg) local dirs = vstudio.path(cfg, cfg.bindirs) if #dirs > 0 then m.element("ExecutablePath", nil, "%s;$(ExecutablePath)", table.concat(dirs, ";")) end end function m.platformToolset(cfg) local tool, version = p.config.toolset(cfg) if not version then local action = p.action.current() version = action.vstudio.platformToolset end if version then if cfg.kind == p.NONE or cfg.kind == p.MAKEFILE then if p.config.hasFile(cfg, path.iscppfile) then m.element("PlatformToolset", nil, version) end else m.element("PlatformToolset", nil, version) end end end function m.precompiledHeader(cfg, condition) prjcfg, filecfg = p.config.normalize(cfg) if filecfg then if prjcfg.pchsource == filecfg.abspath and not prjcfg.flags.NoPCH then m.element('PrecompiledHeader', condition, 'Create') elseif filecfg.flags.NoPCH then m.element('PrecompiledHeader', condition, 'NotUsing') end else if not prjcfg.flags.NoPCH and prjcfg.pchheader then m.element("PrecompiledHeader", nil, "Use") m.element("PrecompiledHeaderFile", nil, "%s", prjcfg.pchheader) else m.element("PrecompiledHeader", nil, "NotUsing") end end end function m.preprocessorDefinitions(cfg, defines, escapeQuotes, condition) if #defines > 0 then defines = table.concat(defines, ";") if escapeQuotes then defines = defines:gsub('"', '\\"') end defines = p.esc(defines) .. ";%%(PreprocessorDefinitions)" m.element('PreprocessorDefinitions', condition, defines) end end function m.undefinePreprocessorDefinitions(cfg, undefines, escapeQuotes, condition) if #undefines > 0 then undefines = table.concat(undefines, ";") if escapeQuotes then undefines = undefines:gsub('"', '\\"') end undefines = p.esc(undefines) .. ";%%(UndefinePreprocessorDefinitions)" m.element('UndefinePreprocessorDefinitions', condition, undefines) end end function m.programDataBaseFileName(cfg) -- just a placeholder for overriding; will use the default VS name -- for changes, see https://github.com/premake/premake-core/issues/151 end function m.projectGuid(prj) m.element("ProjectGuid", nil, "{%s}", prj.uuid) end function m.projectName(prj) if prj.name ~= prj.filename then m.element("ProjectName", nil, "%s", prj.name) end end function m.propertyGroup(cfg, label) local cond if cfg then cond = string.format(' %s', m.condition(cfg)) end if label then label = string.format(' Label="%s"', label) end p.push('<PropertyGroup%s%s>', cond or "", label or "") end function m.propertySheets(cfg) p.push('<ImportGroup Label="PropertySheets" %s>', m.condition(cfg)) p.w('<Import Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props" Condition="exists(\'$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\')" Label="LocalAppDataPlatform" />') p.pop('</ImportGroup>') end function m.propertySheetGroup(prj) for cfg in project.eachconfig(prj) do m.propertySheets(cfg) end end function m.referenceCopyLocalSatelliteAssemblies(prj, ref) m.element("CopyLocalSatelliteAssemblies", nil, "false") end function m.referenceLinkLibraryDependencies(prj, ref) m.element("LinkLibraryDependencies", nil, "true") end function m.referenceOutputAssembly(prj, ref) m.element("ReferenceOutputAssembly", nil, "true") end function m.referencePrivate(prj, ref) m.element("Private", nil, "true") end function m.referenceProject(prj, ref) m.element("Project", nil, "{%s}", ref.uuid) end function m.referenceUseLibraryDependences(prj, ref) m.element("UseLibraryDependencyInputs", nil, "false") end function m.resourceAdditionalIncludeDirectories(cfg) m.additionalIncludeDirectories(cfg, table.join(cfg.includedirs, cfg.resincludedirs)) end function m.resourcePreprocessorDefinitions(cfg) m.preprocessorDefinitions(cfg, table.join(cfg.defines, cfg.resdefines), true) end function m.runtimeLibrary(cfg) local runtimes = { StaticDebug = "MultiThreadedDebug", StaticRelease = "MultiThreaded", } local runtime = runtimes[config.getruntime(cfg)] if runtime then m.element("RuntimeLibrary", nil, runtime) end end function m.callingConvention(cfg) if cfg.callingconvention then m.element("CallingConvention", nil, cfg.callingconvention) end end function m.runtimeTypeInfo(cfg) if cfg.rtti == p.OFF and cfg.clr == p.OFF then m.element("RuntimeTypeInfo", nil, "false") elseif cfg.rtti == p.ON then m.element("RuntimeTypeInfo", nil, "true") end end function m.bufferSecurityCheck(cfg) local tool, toolVersion = p.config.toolset(cfg) if cfg.flags.NoBufferSecurityCheck or (toolVersion and toolVersion:startswith("LLVM-vs")) then m.element("BufferSecurityCheck", nil, "false") end end function m.stringPooling(cfg) if config.isOptimizedBuild(cfg) then m.element("StringPooling", nil, "true") end end function m.subSystem(cfg) if cfg.system ~= p.XBOX360 then local subsystem = iif(cfg.kind == p.CONSOLEAPP, "Console", "Windows") m.element("SubSystem", nil, subsystem) end end function m.targetExt(cfg) local ext = cfg.buildtarget.extension if ext ~= "" then m.element("TargetExt", nil, "%s", ext) else p.w('<TargetExt>') p.w('</TargetExt>') end end function m.targetName(cfg) m.element("TargetName", nil, "%s%s", cfg.buildtarget.prefix, cfg.buildtarget.basename) end function m.treatLinkerWarningAsErrors(cfg) if cfg.flags.FatalLinkWarnings then local el = iif(cfg.kind == p.STATICLIB, "Lib", "Linker") m.element("Treat" .. el .. "WarningAsErrors", nil, "true") end end function m.treatWChar_tAsBuiltInType(cfg) local map = { On = "true", Off = "false" } local value = map[cfg.nativewchar] if value then m.element("TreatWChar_tAsBuiltInType", nil, value) end end function m.treatWarningAsError(cfg) if cfg.flags.FatalCompileWarnings and cfg.warnings ~= p.OFF then m.element("TreatWarningAsError", nil, "true") end end function m.disableSpecificWarnings(cfg, condition) if #cfg.disablewarnings > 0 then local warnings = table.concat(cfg.disablewarnings, ";") warnings = p.esc(warnings) .. ";%%(DisableSpecificWarnings)" m.element('DisableSpecificWarnings', condition, warnings) end end function m.treatSpecificWarningsAsErrors(cfg, condition) if #cfg.fatalwarnings > 0 then local fatal = table.concat(cfg.fatalwarnings, ";") fatal = p.esc(fatal) .. ";%%(TreatSpecificWarningsAsErrors)" m.element('TreatSpecificWarningsAsErrors', condition, fatal) end end function m.useDebugLibraries(cfg) local runtime = config.getruntime(cfg) m.element("UseDebugLibraries", nil, tostring(runtime:endswith("Debug"))) end function m.useOfMfc(cfg) if cfg.flags.MFC then m.element("UseOfMfc", nil, iif(cfg.flags.StaticRuntime, "Static", "Dynamic")) end end function m.useOfAtl(cfg) if cfg.atl then m.element("UseOfATL", nil, cfg.atl) end end function m.userMacros(cfg) p.w('<PropertyGroup Label="UserMacros" />') end function m.warningLevel(cfg) local map = { Off = "TurnOffAllWarnings", Extra = "Level4" } m.element("WarningLevel", nil, "%s", map[cfg.warnings] or "Level3") end function m.xmlDeclaration() p.xmlUtf8() end --------------------------------------------------------------------------- -- -- Support functions -- --------------------------------------------------------------------------- -- -- Format and return a Visual Studio Condition attribute. -- function m.condition(cfg) return string.format('Condition="\'$(Configuration)|$(Platform)\'==\'%s\'"', p.esc(vstudio.projectConfig(cfg))) end -- -- Output an individual project XML element, with an optional configuration -- condition. -- -- @param depth -- How much to indent the element. -- @param name -- The element name. -- @param condition -- An optional configuration condition, formatted with vc2010.condition(). -- @param value -- The element value, which may contain printf formatting tokens. -- @param ... -- Optional additional arguments to satisfy any tokens in the value. -- function m.element(name, condition, value, ...) if select('#',...) == 0 then value = p.esc(value) end local format if condition then format = string.format('<%s %s>%s</%s>', name, condition, value, name) else format = string.format('<%s>%s</%s>', name, value, name) end p.x(format, ...) end
bsd-3-clause
mys007/nn
SpatialContrastiveNormalization.lua
63
1444
local SpatialContrastiveNormalization, parent = torch.class('nn.SpatialContrastiveNormalization','nn.Module') function SpatialContrastiveNormalization:__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('<SpatialContrastiveNormalization> 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('<SpatialContrastiveNormalization> averaging kernel must have ODD dimensions') end -- instantiate sub+div normalization self.normalizer = nn.Sequential() self.normalizer:add(nn.SpatialSubtractiveNormalization(self.nInputPlane, self.kernel)) self.normalizer:add(nn.SpatialDivisiveNormalization(self.nInputPlane, self.kernel, self.threshold, self.thresval)) end function SpatialContrastiveNormalization:updateOutput(input) self.output = self.normalizer:forward(input) return self.output end function SpatialContrastiveNormalization:updateGradInput(input, gradOutput) self.gradInput = self.normalizer:backward(input, gradOutput) return self.gradInput end
bsd-3-clause
nenau/naev
dat/missions/neutral/trader_escort.lua
2
17408
--Escort a convoy of traders to a destination-- include "dat/scripts/nextjump.lua" include "dat/scripts/cargo_common.lua" include "dat/scripts/numstring.lua" misn_title = _("Escort a %s convoy to %s in %s.") misn_reward = _("%s credits") convoysizestr = {} convoysizestr[1] = _("tiny") convoysizestr[2] = _("small") convoysizestr[3] = _("medium") convoysizestr[4] = _("large") convoysizestr[5] = _("huge") title_p1 = _("A %s convoy of traders needs protection to %s in %s. You must stick with the convoy at all times, waiting to jump or land until the entire convoy has done so.") -- Note: please leave the trailing space on the line below! Needed to make the newline show up. title_p2 = _([[ Cargo: %s Jumps: %d Travel distance: %d Piracy Risk: %s]]) piracyrisk = {} piracyrisk[1] = _("None") piracyrisk[2] = _("Low") piracyrisk[3] = _("Medium") piracyrisk[4] = _("High") accept_title = _("Mission Accepted") osd_title = _("Convey Escort") osd_msg = _("Escort a convoy of traders to %s in the %s system.") slow = {} slow[1] = _("Not enough fuel") slow[2] = _([[The destination is %s jumps away, but you only have enough fuel for %s jumps. You cannot stop to refuel. Accept the mission anyway?]]) landsuccesstitle = _("Success!") landsuccesstext = _("You successfully escorted the trading convoy to the destination. There wasn't a single casualty, and you are rewarded the full amount.") landcasualtytitle = _("Success with Casualities") landcasualtytext = {} landcasualtytext[1] = _("You've arrived with the trading convoy more or less intact. Your pay is docked slightly to provide compensation for the families of the lost crew members.") landcasualtytext[2] = _("You arrive with what's left of the convoy. It's not much, but it's better than nothing. After a moment of silence of the lost crew members, you are paid a steeply discounted amount.") wrongsystitle = _("You diverged!") wrongsystext = _([[You have jumped to the wrong system! You are no longer part of the mission to escort the traders.]]) convoydeathtitle = _("The convoy has been destroyed!") convoydeathtext = _([[All of the traders have been killed. You are a terrible escort.]]) landfailtitle = _("You abandoned your mission!") landfailtext = _("You have landed, but you were supposed to escort the trading convoy. Your mission is a failure!") convoynoruntitle = _("You have left your convoy behind!") convoynoruntext = _([[You jumped before the rest of your convoy and the remaining ships scatter to find cover. You have abandoned your duties, and failed your mission.]]) convoynolandtitle = _("You landed before the convoy!") convoynolandtext = _([[You landed at the planet before ensuring that the rest of your convoy was safe. You have abandoned your duties, and failed your mission.]]) traderdistress = _("Convoy ships under attack! Requesting immediate assistance!") function create() --This mission does not make any system claims destplanet, destsys, numjumps, traveldist, cargo, avgrisk, tier = cargo_calculateRoute() if destplanet == nil then misn.finish(false) elseif numjumps == 0 then misn.finish(false) -- have to escort them at least one jump! elseif avgrisk <= 25 then misn.finish(false) -- needs to be a little bit of piracy possible along route end if avgrisk > 25 and avgrisk <= 100 then piracyrisk = piracyrisk[3] riskreward = 25 else piracyrisk = piracyrisk[4] riskreward = 50 end --Select size of convoy. Must have enough combat exp to get large convoys. if player.getRating() >= 5000 then convoysize = rnd.rnd(1,5) elseif player.getRating() >= 2000 then convoysize = rnd.rnd(1,4) elseif player.getRating() >= 1000 then convoysize = rnd.rnd(1,3) elseif player.getRating() >= 500 then convoysize = rnd.rnd(1,2) else convoysize = 1 end -- Choose mission reward. This depends on the mission tier. -- Reward depends on type of cargo hauled. Hauling expensive commodities gives a better deal. finished_mod = 2.0 -- Modifier that should tend towards 1.0 as naev is finished as a game if convoysize == 1 then tier = 1 jumpreward = commodity.price(cargo) distreward = math.log(100*commodity.price(cargo))/100 elseif convoysize == 2 then tier = 2 jumpreward = commodity.price(cargo) distreward = math.log(250*commodity.price(cargo))/100 elseif convoysize == 3 then tier = 3 jumpreward = commodity.price(cargo) distreward = math.log(500*commodity.price(cargo))/100 elseif convoysize == 4 then tier = 4 jumpreward = commodity.price(cargo) distreward = math.log(1000*commodity.price(cargo))/100 elseif convoysize == 5 then tier = 5 jumpreward = commodity.price(cargo) distreward = math.log(2000*commodity.price(cargo))/100 end reward = 2.0^tier * (avgrisk * riskreward + numjumps * jumpreward + traveldist * distreward) * finished_mod * (1. + 0.05*rnd.twosigma()) misn.setTitle( misn_title:format( convoysizestr[convoysize], destplanet:name(), destsys:name() ) ) misn.setDesc(title_p1:format(convoysizestr[convoysize], destplanet:name(), destsys:name()) .. title_p2:format(cargo, numjumps, traveldist, piracyrisk)) misn.markerAdd(destsys, "computer") misn.setReward(misn_reward:format(numstring(reward))) end function accept() if convoysize == 1 then convoyname = "Trader Convoy 3" alive = {true, true, true} -- Keep track of the traders. Update this when they die. alive["__save"] = true elseif convoysize == 2 then convoyname = "Trader Convoy 4" alive = {true, true, true, true} alive["__save"] = true elseif convoysize == 3 then convoyname = "Trader Convoy 5" alive = {true, true, true, true, true} alive["__save"] = true elseif convoysize == 4 then convoyname = "Trader Convoy 6" alive = {true, true, true, true, true, true} alive["__save"] = true elseif convoysize == 5 then convoyname = "Trader Convoy 8" alive = {true, true, true, true, true, true, true, true} alive["__save"] = true end if player.jumps() < numjumps then if not tk.yesno( slow[1], slow[2]:format( numjumps, player.jumps())) then misn.finish() end end nextsys = getNextSystem(system.cur(), destsys) -- This variable holds the system the player is supposed to jump to NEXT. origin = planet.cur() -- The place where the AI ships spawn from. misnfail = false misn.accept() misn.osdCreate(osd_title, {osd_msg:format(destplanet:name(), destsys:name())}) hook.takeoff("takeoff") hook.jumpin("jumpin") hook.jumpout("jumpout") hook.land("land") end function takeoff() --Make it interesting if convoysize == 1 then ambush = pilot.add("Trader Ambush 1", "baddie_norun", vec2.new(0, 0)) elseif convoysize == 2 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(1,2)), "baddie_norun", vec2.new(0, 0)) elseif convoysize == 3 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(2,3)), "baddie_norun", vec2.new(0, 0)) elseif convoysize == 4 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(2,4)), "baddie_norun", vec2.new(0, 0)) else ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(3,5)), "baddie_norun", vec2.new(0, 0)) end --Spawn the convoy convoy = pilot.add(convoyname, nil, origin) for i, j in ipairs(convoy) do if not alive[i] then j:rm() end -- Dead trader stays dead. if j:exists() then j:control() j:setHilight(true) j:setInvincPlayer() j:hyperspace(getNextSystem(system.cur(), destsys)) n = pilot.cargoFree(j) c = pilot.cargoAdd(j, cargo, n) convoyJump = false hook.pilot(j, "death", "traderDeath") hook.pilot(j, "jump", "traderJump") hook.pilot(j, "attacked", "traderAttacked", j) end end end function jumpin() if system.cur() ~= nextsys then -- player jumped to somewhere other than the next system tk.msg(wrongsystitle, wrongsystext) abort() elseif system.cur() == destsys and misnfail == false then -- player has reached the destination system --Make it interesting if convoysize == 1 then ambush = pilot.add("Trader Ambush 1", "baddie_norun", vec2.new(0, 0)) elseif convoysize == 2 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(1,2)), "baddie_norun", vec2.new(0, 0)) elseif convoysize == 3 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(2,3)), "baddie_norun", vec2.new(0, 0)) elseif convoysize == 4 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(2,4)), "baddie_norun", vec2.new(0, 0)) else ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(3,5)), "baddie_norun", vec2.new(0, 0)) end --Spawn the convoy convoy = pilot.add(convoyname, nil, origin) for i, j in ipairs(convoy) do if not alive[i] then j:rm() end -- Dead traders stay dead. if j:exists() then j:control() j:setHilight(true) j:setInvincPlayer() j:land(destplanet) n = pilot.cargoFree(j) c = pilot.cargoAdd(j, cargo, n) convoyLand = false hook.pilot(j, "death", "traderDeath") hook.pilot(j, "land", "traderLand") hook.pilot(j, "attacked", "traderAttacked", j) end end elseif misnfail == false then -- Not yet at destination, so traders continue to next system. --Make it interesting if convoysize == 1 then ambush = pilot.add("Trader Ambush 1", "baddie_norun", vec2.new(0, 0)) elseif convoysize == 2 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(1,2)), "baddie_norun", vec2.new(0, 0)) elseif convoysize == 3 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(2,3)), "baddie_norun", vec2.new(0, 0)) elseif convoysize == 4 then ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(2,4)), "baddie_norun", vec2.new(0, 0)) else ambush = pilot.add(string.format("Trader Ambush %i", rnd.rnd(3,5)), "baddie_norun", vec2.new(0, 0)) end --Spawn the convoy convoy = pilot.add(convoyname, nil, origin) for i, j in ipairs(convoy) do if not alive[i] then j:rm() end -- Dead traders stay dead. if j:exists() then j:control() j:setHilight(true) j:setInvincPlayer() j:hyperspace(getNextSystem(system.cur(), destsys)) convoyJump = false n = pilot.cargoFree(j) c = pilot.cargoAdd(j, cargo, n) hook.pilot(j, "death", "traderDeath") hook.pilot(j, "jump", "traderJump") hook.pilot(j, "attacked", "traderAttacked", j) end end elseif misnfail == true then -- Jumped ahead of traders. Convoy appears in next system, but reverts to AI hook.timer(4000, "convoyContinues") -- waits 4 secs then has them follow. end end function jumpout() if not convoyJump then tk.msg(convoynoruntitle, convoynoruntext) misnfail = true end origin = system.cur() nextsys = getNextSystem(system.cur(), destsys) end function land() dead = 0 for k,v in pairs(alive) do if v ~= true then dead = dead + 1 end end if planet.cur() ~= destplanet then tk.msg(landfailtitle, landfailtext) misn.finish(false) elseif planet.cur() == destplanet and convoyLand == false then tk.msg(convoynolandtitle, convoynolandtext) misn.finish(false) elseif planet.cur() == destplanet and convoyLand == true and convoysize == 1 then if dead == 0 then tk.msg(landsuccesstitle, landsuccesstext) player.pay(reward) misn.finish(true) elseif dead == 1 then tk.msg(landcasualtytitle, landcasualtytext[1]) player.pay(reward/2) misn.finish(true) elseif dead == 2 then tk.msg(landcasualtytitle, landcasualtytext[2]) player.pay(reward/4) misn.finish(true) end elseif planet.cur() == destplanet and convoyLand == true and convoysize == 2 then if dead == 0 then tk.msg(landsuccesstitle, landsuccesstext) player.pay(reward) misn.finish(true) elseif dead > 0 and dead < 3 then tk.msg(landcasualtytitle, landcasualtytext[1]) player.pay(reward/2) misn.finish(true) elseif dead == 3 then tk.msg(landcasualtytitle, landcasualtytext[2]) player.pay(reward/4) misn.finish(true) end elseif planet.cur() == destplanet and convoyLand == true and convoysize == 3 then if dead == 0 then tk.msg(landsuccesstitle, landsuccesstext) player.pay(reward) misn.finish(true) elseif dead > 0 and dead < 3 then tk.msg(landcasualtytitle, landcasualtytext[1]) player.pay(reward/2) misn.finish(true) elseif dead >= 3 then tk.msg(landcasualtytitle, landcasualtytext[2]) player.pay(reward/4) misn.finish(true) end elseif planet.cur() == destplanet and convoyLand == true and convoysize == 4 then if dead == 0 then tk.msg(landsuccesstitle, landsuccesstext) player.pay(reward) misn.finish(true) elseif dead <= 3 then tk.msg(landcasualtytitle, landcasualtytext[1]) player.pay(reward/2) misn.finish(true) elseif dead > 3 then tk.msg(landcasualtytitle, landcasualtytext[2]) player.pay(reward/4) misn.finish(true) end elseif planet.cur() == destplanet and convoyLand == true and convoysize == 5 then if dead == 0 then tk.msg(landsuccesstitle, landsuccesstext) player.pay(reward) misn.finish(true) elseif dead <= 4 then tk.msg(landcasualtytitle, landcasualtytext[1]) player.pay(reward/2) misn.finish(true) elseif dead > 4 then tk.msg(landcasualtytitle, landcasualtytext[2]) player.pay(reward/4) misn.finish(true) end end end function traderDeath() if convoysize == 1 then if alive[3] then alive[3] = false elseif alive[2] then alive[2] = false else -- all convoy dead tk.msg(convoydeathtitle, convoydeathtext) abort() end elseif convoysize == 2 then if alive[4] then alive[4] = false elseif alive[3] then alive[3] = false elseif alive[2] then alive[2] = false else -- all convoy dead tk.msg(convoydeathtitle, convoydeathtext) abort() end elseif convoysize == 3 then if alive[5] then alive[5] = false elseif alive[4] then alive[4] = false elseif alive[3] then alive[3] = false elseif alive[2] then alive[2] = false elseif alive[1] then alive[1] = false else -- all convoy dead tk.msg(convoydeathtitle, convoydeathtext) abort() end elseif convoysize == 4 then if alive[6] then alive[6] = false elseif alive[5] then alive[5] = false elseif alive[4] then alive[4] = false elseif alive[3] then alive[3] = false elseif alive[2] then alive[2] = false else -- all convoy dead tk.msg(convoydeathtitle, convoydeathtext) abort() end elseif convoysize == 5 then if alive[8] then alive[8] = false elseif alive[7] then alive[7] = false elseif alive[6] then alive[6] = false elseif alive[5] then alive[5] = false elseif alive[4] then alive[4] = false elseif alive[3] then alive[3] = false elseif alive[2] then alive[2] = false else -- all convoy dead tk.msg(convoydeathtitle, convoydeathtext) abort() end end end -- Handle the jumps of convoy. function traderJump() convoyJump = true local broadcast = false for i, j in pairs(convoy) do if j:exists() and broadcast == false then player.msg(string.format("%s has jumped to %s.", j:name(),getNextSystem(system.cur(), destsys):name())) broadcast = true end end end --Handle landing of convoy function traderLand() convoyLand = true local broadcast = false for i, j in pairs(convoy) do if j:exists() and broadcast == false then player.msg(string.format("%s has landed on %s.", j:name(),destplanet:name())) broadcast = true end end end -- Handle the convoy getting attacked. function traderAttacked(j) if shuttingup == true then return else shuttingup = true j:comm(player.pilot(),traderdistress) hook.timer(5000, "traderShutup") -- Shuts him up for at least 5s. end end function traderShutup() shuttingup = false end function convoyContinues() convoy = pilot.add(convoyname, nil, origin) for i, j in ipairs(convoy) do if not alive[i] then j:rm() end -- Dead traders stay dead. if j:exists() then j:changeAI( "trader" ) j:control(false) end end misn.finish(false) end
gpl-3.0
kidaa/FFXIOrgins
scripts/globals/spells/choke.lua
2
1594
----------------------------------------- -- Spell: Choke -- Deals wind damage that lowers an enemy's vitality and gradually reduces its HP. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if(target:getStatusEffect(EFFECT_FROST) ~= nil) then spell:setMsg(75); -- no effect else local bonus = AffinityBonus(caster, spell:getElement()); local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT); local resist = applyResistance(caster,spell,target,dINT,36,bonus); if(resist <= 0.125) then spell:setMsg(85); else if(target:getStatusEffect(EFFECT_RASP) ~= nil) then target:delStatusEffect(EFFECT_RASP); end; local sINT = caster:getStat(MOD_INT); local DOT = getElementalDebuffDOT(sINT); local effect = target:getStatusEffect(EFFECT_CHOKE); local noeffect = false; if(effect ~= nil) then if(effect:getPower() >= DOT) then noeffect = true; end; end; if(noeffect) then spell:setMsg(75); -- no effect else if(effect ~= nil) then target:delStatusEffect(EFFECT_CHOKE); end; spell:setMsg(237); local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist); target:addStatusEffect(EFFECT_CHOKE,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASBLE); end; end; end; return EFFECT_CHOKE; end;
gpl-3.0
LipkeGu/OpenRA
mods/ra/maps/soviet-06b/soviet06b.lua
7
4629
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] IntroAttackers = { IntroEnemy1, IntroEnemy2, IntroEnemy3 } Trucks = { Truck1, Truck2 } InfAttack = { } ArmorAttack = { } AttackPaths = { { AttackWaypoint1 }, { AttackWaypoint2 } } AlliedInfantryTypes = { "e1", "e1", "e3" } AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "2tnk", "2tnk", "arty" } SovietReinforcements1 = { "e6", "e6", "e6", "e6", "e6" } SovietReinforcements2 = { "e4", "e4", "e2", "e2", "e2" } SovietReinforcements1Waypoints = { McvWaypoint.Location, APCWaypoint1.Location } SovietReinforcements2Waypoints = { McvWaypoint.Location, APCWaypoint2.Location } TruckGoalTrigger = { CPos.New(85, 10), CPos.New(85, 11), CPos.New(85, 12), CPos.New(86, 13), CPos.New(87, 13), CPos.New(88, 13), CPos.New(88, 14), CPos.New(89, 14), CPos.New(90, 14), CPos.New(90, 15), CPos.New(91, 15), CPos.New(91, 16), CPos.New(91, 17), CPos.New(92, 17), CPos.New(93, 17), CPos.New(94, 17), CPos.New(94, 18), CPos.New(95, 18), CPos.New(96, 18), CPos.New(96, 19), CPos.New(97, 19), CPos.New(98, 19)} Trigger.OnEnteredFootprint(TruckGoalTrigger, function(a, id) if not truckGoalTrigger and a.Owner == player and a.Type == "truk" then truckGoalTrigger = true player.MarkCompletedObjective(sovietObjective) player.MarkCompletedObjective(SaveAllTrucks) end end) Trigger.OnAllKilled(Trucks, function() enemy.MarkCompletedObjective(alliedObjective) end) Trigger.OnAnyKilled(Trucks, function() player.MarkFailedObjective(SaveAllTrucks) end) Trigger.OnKilled(Apwr, function(building) BaseApwr.exists = false end) Trigger.OnKilled(Barr, function(building) BaseTent.exists = false end) Trigger.OnKilled(Proc, function(building) BaseProc.exists = false end) Trigger.OnKilled(Weap, function(building) BaseWeap.exists = false end) Trigger.OnKilled(Apwr2, function(building) BaseApwr2.exists = false end) Trigger.OnKilled(Dome, function() player.MarkCompletedObjective(sovietObjective2) Media.PlaySpeechNotification(player, "ObjectiveMet") end) Trigger.OnRemovedFromWorld(Mcv, function() if not mcvDeployed then mcvDeployed = true BuildBase() SendEnemies() Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry) Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor) end end) WorldLoaded = function() player = Player.GetPlayer("USSR") enemy = Player.GetPlayer("Greece") Camera.Position = CameraStart.CenterPosition Mcv.Move(McvWaypoint.Location) Harvester.FindResources() Utils.Do(IntroAttackers, function(actor) IdleHunt(actor) end) Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements1, SovietReinforcements1Waypoints) Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements2, SovietReinforcements2Waypoints) 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) Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) alliedObjective = enemy.AddPrimaryObjective("Destroy all Soviet troops.") sovietObjective = player.AddPrimaryObjective("Escort the Convoy.") sovietObjective2 = player.AddSecondaryObjective("Destroy the Allied radar dome to stop enemy\nreinforcements.") SaveAllTrucks = player.AddSecondaryObjective("Keep all trucks alive.") end Tick = function() if player.HasNoRequiredUnits() then enemy.MarkCompletedObjective(alliedObjective) end if enemy.Resources >= enemy.ResourceCapacity * 0.75 then enemy.Cash = enemy.Cash + enemy.Resources - enemy.ResourceCapacity * 0.25 enemy.Resources = enemy.ResourceCapacity * 0.25 end end
gpl-3.0
wizardbottttt/Speed_Bot
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
roboxt/ss
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
Puccio7/bot-telegram
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
apache-2.0
alikineh/ali_kineh
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
actionless/awesome
lib/wibox/widget/init.lua
3
3216
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2010 Uli Schlachter -- @module wibox.widget --------------------------------------------------------------------------- local cairo = require("lgi").cairo local hierarchy = require("wibox.hierarchy") local widget = { base = require("wibox.widget.base"); textbox = require("wibox.widget.textbox"); imagebox = require("wibox.widget.imagebox"); background = require("wibox.widget.background"); systray = require("wibox.widget.systray"); textclock = require("wibox.widget.textclock"); progressbar = require("wibox.widget.progressbar"); graph = require("wibox.widget.graph"); checkbox = require("wibox.widget.checkbox"); piechart = require("wibox.widget.piechart"); slider = require("wibox.widget.slider"); calendar = require("wibox.widget.calendar"); separator = require("wibox.widget.separator"); } setmetatable(widget, { __call = function(_, args) return widget.base.make_widget_declarative(args) end }) --- Draw a widget directly to a given cairo context. -- This function creates a temporary `wibox.hierarchy` instance and uses that to -- draw the given widget once to the given cairo context. -- @tparam widget wdg A widget to draw -- @tparam cairo_context cr The cairo context to draw the widget on -- @tparam number width The width of the widget -- @tparam number height The height of the widget -- @tparam[opt={dpi=96}] table context The context information to give to the widget. -- @staticfct wibox.widget.draw_to_cairo_context function widget.draw_to_cairo_context(wdg, cr, width, height, context) local function no_op() end context = context or {dpi=96} local h = hierarchy.new(context, wdg, width, height, no_op, no_op, {}) h:draw(context, cr) end --- Create an SVG file showing this widget. -- @tparam widget wdg A widget -- @tparam string path The output file path -- @tparam number width The surface width -- @tparam number height The surface height -- @tparam[opt={dpi=96}] table context The context information to give to the widget. -- @staticfct wibox.widget.draw_to_svg_file function widget.draw_to_svg_file(wdg, path, width, height, context) local img = cairo.SvgSurface.create(path, width, height) local cr = cairo.Context(img) widget.draw_to_cairo_context(wdg, cr, width, height, context) img:finish() end --- Create a cairo image surface showing this widget. -- @tparam widget wdg A widget -- @tparam number width The surface width -- @tparam number height The surface height -- @param[opt=cairo.Format.ARGB32] format The surface format -- @tparam[opt={dpi=96}] table context The context information to give to the widget. -- @return The cairo surface -- @staticfct wibox.widget.draw_to_image_surface function widget.draw_to_image_surface(wdg, width, height, format, context) local img = cairo.ImageSurface(format or cairo.Format.ARGB32, width, height) local cr = cairo.Context(img) widget.draw_to_cairo_context(wdg, cr, width, height, context) return img end return widget -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/West_Ronfaure/npcs/qm4.lua
2
1631
----------------------------------- -- Area: West Ronfaure -- NPC: ??? -- Involved in Quest: The Dismayed Customer -- @pos -399 -10 -438 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE) and player:getVar("MissionStatus") == 1)then if(GetMobAction(17187273) == 0) then if(player:getVar("Mission7-1MobKilled") == 1) then player:addKeyItem(ANCIENT_SANDORIAN_TABLET); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_SANDORIAN_TABLET); player:setVar("Mission7-1MobKilled",0); player:setVar("MissionStatus",2); else SpawnMob(17187273):updateEnmity(player); end end end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
meshr-net/meshr_win32
usr/lib/lua/luci/model/cbi/asterisk.lua
11
5378
--[[ 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: asterisk.lua 3618 2008-10-23 02:25:26Z jow $ ]]-- cbimap = Map("asterisk", "asterisk", "") asterisk = cbimap:section(TypedSection, "asterisk", "Asterisk General Options", "") asterisk.anonymous = true agidir = asterisk:option(Value, "agidir", "AGI directory", "") agidir.rmempty = true cache_record_files = asterisk:option(Flag, "cache_record_files", "Cache recorded sound files during recording", "") cache_record_files.rmempty = true debug = asterisk:option(Value, "debug", "Debug Level", "") debug.rmempty = true dontwarn = asterisk:option(Flag, "dontwarn", "Disable some warnings", "") dontwarn.rmempty = true dumpcore = asterisk:option(Flag, "dumpcore", "Dump core on crash", "") dumpcore.rmempty = true highpriority = asterisk:option(Flag, "highpriority", "High Priority", "") highpriority.rmempty = true initcrypto = asterisk:option(Flag, "initcrypto", "Initialise Crypto", "") initcrypto.rmempty = true internal_timing = asterisk:option(Flag, "internal_timing", "Use Internal Timing", "") internal_timing.rmempty = true logdir = asterisk:option(Value, "logdir", "Log directory", "") logdir.rmempty = true maxcalls = asterisk:option(Value, "maxcalls", "Maximum number of calls allowed", "") maxcalls.rmempty = true maxload = asterisk:option(Value, "maxload", "Maximum load to stop accepting new calls", "") maxload.rmempty = true nocolor = asterisk:option(Flag, "nocolor", "Disable console colors", "") nocolor.rmempty = true record_cache_dir = asterisk:option(Value, "record_cache_dir", "Sound files Cache directory", "") record_cache_dir.rmempty = true record_cache_dir:depends({ ["cache_record_files"] = "true" }) rungroup = asterisk:option(Flag, "rungroup", "The Group to run as", "") rungroup.rmempty = true runuser = asterisk:option(Flag, "runuser", "The User to run as", "") runuser.rmempty = true spooldir = asterisk:option(Value, "spooldir", "Voicemail Spool directory", "") spooldir.rmempty = true systemname = asterisk:option(Value, "systemname", "Prefix UniquID with system name", "") systemname.rmempty = true transcode_via_sln = asterisk:option(Flag, "transcode_via_sln", "Build transcode paths via SLINEAR, not directly", "") transcode_via_sln.rmempty = true transmit_silence_during_record = asterisk:option(Flag, "transmit_silence_during_record", "Transmit SLINEAR silence while recording a channel", "") transmit_silence_during_record.rmempty = true verbose = asterisk:option(Value, "verbose", "Verbose Level", "") verbose.rmempty = true zone = asterisk:option(Value, "zone", "Time Zone", "") zone.rmempty = true hardwarereboot = cbimap:section(TypedSection, "hardwarereboot", "Reload Hardware Config", "") method = hardwarereboot:option(ListValue, "method", "Reboot Method", "") method:value("web", "Web URL (wget)") method:value("system", "program to run") method.rmempty = true param = hardwarereboot:option(Value, "param", "Parameter", "") param.rmempty = true iaxgeneral = cbimap:section(TypedSection, "iaxgeneral", "IAX General Options", "") iaxgeneral.anonymous = true iaxgeneral.addremove = true allow = iaxgeneral:option(MultiValue, "allow", "Allow Codecs", "") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true canreinvite = iaxgeneral:option(ListValue, "canreinvite", "Reinvite/redirect media connections", "") canreinvite:value("yes", "Yes") canreinvite:value("nonat", "Yes when not behind NAT") canreinvite:value("update", "Use UPDATE rather than INVITE for path redirection") canreinvite:value("no", "No") canreinvite.rmempty = true static = iaxgeneral:option(Flag, "static", "Static", "") static.rmempty = true writeprotect = iaxgeneral:option(Flag, "writeprotect", "Write Protect", "") writeprotect.rmempty = true sipgeneral = cbimap:section(TypedSection, "sipgeneral", "Section sipgeneral", "") sipgeneral.anonymous = true sipgeneral.addremove = true allow = sipgeneral:option(MultiValue, "allow", "Allow codecs", "") allow:value("ulaw", "ulaw") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true port = sipgeneral:option(Value, "port", "SIP Port", "") port.rmempty = true realm = sipgeneral:option(Value, "realm", "SIP realm", "") realm.rmempty = true moh = cbimap:section(TypedSection, "moh", "Music On Hold", "") application = moh:option(Value, "application", "Application", "") application.rmempty = true application:depends({ ["asterisk.moh.mode"] = "custom" }) directory = moh:option(Value, "directory", "Directory of Music", "") directory.rmempty = true mode = moh:option(ListValue, "mode", "Option mode", "") mode:value("system", "program to run") mode:value("files", "Read files from directory") mode:value("quietmp3", "Quite MP3") mode:value("mp3", "Loud MP3") mode:value("mp3nb", "unbuffered MP3") mode:value("quietmp3nb", "Quiet Unbuffered MP3") mode:value("custom", "Run a custom application") mode.rmempty = true random = moh:option(Flag, "random", "Random Play", "") random.rmempty = true return cbimap
apache-2.0
tangzx/IntelliJ-EmmyLua
src/main/resources/std/Lua52/debug.lua
6
9495
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com) -- -- 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. debug = {} --- --- Enters an interactive mode with the user, running each string that the user --- enters. Using simple commands and other debug facilities, the user can --- inspect global and local variables, change their values, evaluate --- expressions, and so on. A line containing only the word `cont` finishes this --- function, so that the caller continues its execution. --- --- Note that commands for `debug.debug` are not lexically nested within any --- function, and so have no direct access to local variables. function debug.debug() end --- --- Returns the current hook settings of the thread, as three values: the --- current hook function, the current hook mask, and the current hook count --- (as set by the `debug.sethook` function). ---@overload fun():thread ---@param thread thread ---@return thread function debug.gethook(thread) end ---@class DebugInfo ---@field linedefined number ---@field lastlinedefined number ---@field currentline number ---@field func function ---@field isvararg boolean ---@field namewhat string ---@field source string ---@field nups number ---@field what string ---@field nparams number ---@field short_src string --- --- Returns a table with information about a function. You can give the --- function directly, or you can give a number as the value of `f`, --- which means the function running at level `f` of the call stack --- of the given thread: level 0 is the current function (`getinfo` itself); --- level 1 is the function that called `getinfo` (except for tail calls, which --- do not count on the stack); and so on. If `f` is a number larger than --- the number of active functions, then `getinfo` returns **nil**. --- --- The returned table can contain all the fields returned by `lua_getinfo`, --- with the string `what` describing which fields to fill in. The default for --- `what` is to get all information available, except the table of valid --- lines. If present, the option '`f`' adds a field named `func` with the --- function itself. If present, the option '`L`' adds a field named --- `activelines` with the table of valid lines. --- --- For instance, the expression `debug.getinfo(1,"n").name` returns a table --- with a name for the current function, if a reasonable name can be found, --- and the expression `debug.getinfo(print)` returns a table with all available --- information about the `print` function. ---@overload fun(f:function):DebugInfo ---@param thread thread ---@param f function ---@param what string ---@return DebugInfo function debug.getinfo(thread, f, what) end --- --- This function returns the name and the value of the local variable with --- index `local` of the function at level `level f` of the stack. This function --- accesses not only explicit local variables, but also parameters, --- temporaries, etc. --- --- The first parameter or local variable has index 1, and so on, following the --- order that they are declared in the code, counting only the variables that --- are active in the current scope of the function. Negative indices refer to --- vararg parameters; -1 is the first vararg parameter. The function returns --- **nil** if there is no variable with the given index, and raises an error --- when called with a level out of range. (You can call `debug.getinfo` to --- check whether the level is valid.) --- --- Variable names starting with '(' (open parenthesis) represent variables with --- no known names (internal variables such as loop control variables, and --- variables from chunks saved without debug information). --- --- The parameter `f` may also be a function. In that case, `getlocal` returns --- only the name of function parameters. ---@overload fun(f:table, var:string):table ---@param thread thread ---@param f table ---@param var string ---@return table function debug.getlocal(thread, f, var) end --- --- Returns the metatable of the given `value` or **nil** if it does not have --- a metatable. ---@param value table ---@return table function debug.getmetatable(value) end --- --- Returns the registry table. ---@return table function debug.getregistry() end --- --- This function returns the name and the value of the upvalue with index --- `up` of the function `f`. The function returns **nil** if there is no --- upvalue with the given index. --- --- Variable names starting with '(' (open parenthesis) represent variables with --- no known names (variables from chunks saved without debug information). ---@param f number ---@param up number ---@return table function debug.getupvalue(f, up) end --- --- Returns the `n`-th user value associated to the userdata `u` plus a boolean, --- **false** if the userdata does not have that value. ---@param u userdata ---@param n number ---@return boolean function debug.getuservalue(u, n) end --- --- Sets the given function as a hook. The string `mask` and the number `count` --- describe when the hook will be called. The string mask may have any --- combination of the following characters, with the given meaning: --- --- * `"c"`: the hook is called every time Lua calls a function; --- * `"r"`: the hook is called every time Lua returns from a function; --- * `"l"`: the hook is called every time Lua enters a new line of code. --- --- Moreover, with a `count` different from zero, the hook is called after every --- `count` instructions. --- --- When called without arguments, `debug.sethook` turns off the hook. --- --- When the hook is called, its first parameter is a string describing --- the event that has triggered its call: `"call"`, (or `"tail --- call"`), `"return"`, `"line"`, and `"count"`. For line events, the hook also --- gets the new line number as its second parameter. Inside a hook, you can --- call `getinfo` with level 2 to get more information about the running --- function (level 0 is the `getinfo` function, and level 1 is the hook --- function) ---@overload fun(hook:(fun():any), mask:any) ---@param thread thread ---@param hook fun():any ---@param mask string ---@param count number function debug.sethook(thread, hook, mask, count) end --- --- This function assigns the value `value` to the local variable with --- index `local` of the function at level `level` of the stack. The function --- returns **nil** if there is no local variable with the given index, and --- raises an error when called with a `level` out of range. (You can call --- `getinfo` to check whether the level is valid.) Otherwise, it returns the --- name of the local variable. ---@overload fun(level:number, var:string, value:any):string ---@param thread thread ---@param level number ---@param var string ---@param value any ---@return string function debug.setlocal(thread, level, var, value) end --- --- Sets the metatable for the given `object` to the given `table` (which --- can be **nil**). Returns value. ---@param value any ---@param table table ---@return boolean function debug.setmetatable(value, table) end --- --- This function assigns the value `value` to the upvalue with index `up` --- of the function `f`. The function returns **nil** if there is no upvalue --- with the given index. Otherwise, it returns the name of the upvalue. ---@param f fun():any ---@param up number ---@param value any ---@return string function debug.setupvalue(f, up, value) end --- Sets the given `value` as the `n`-th associated to the given `udata`. --- `udata` must be a full userdata. --- --- Returns `udata`, or **nil** if the userdata does not have that value. ---@param udata userdata ---@param value any ---@param n number ---@return userdata function debug.setuservalue(udata, value, n) end --- If `message` is present but is neither a string nor **nil**, this function --- returns `message` without further processing. Otherwise, it returns a string --- with a traceback of the call stack. The optional `message` string is --- appended at the beginning of the traceback. An optional level number --- `tells` at which level to start the traceback (default is 1, the function --- c alling `traceback`). ---@overload fun():string ---@param thread thread ---@param message string ---@param level number ---@return string function debug.traceback(thread, message, level) end --- Returns a unique identifier (as a light userdata) for the upvalue numbered --- `n` from the given function. --- --- These unique identifiers allow a program to check whether different --- closures share upvalues. Lua closures that share an upvalue (that is, that --- access a same external local variable) will return identical ids for those --- upvalue indices. ---@param f fun():number ---@param n number ---@return number function debug.upvalueid(f, n) end --- --- Make the `n1`-th upvalue of the Lua closure f1 refer to the `n2`-th upvalue --- of the Lua closure f2. ---@param f1 fun():any ---@param n1 number ---@param f2 fun():any ---@param n2 number function debug.upvaluejoin(f1, n1, f2, n2) end
apache-2.0
kidaa/FFXIOrgins
scripts/zones/Bhaflau_Thickets/mobs/Sea_Puk.lua
12
1223
----------------------------------- -- Area: Bhaflau Thickets -- MOB: Sea Puk -- Note: Place holder Nis Puk ----------------------------------- require("/scripts/zones/Bhaflau_Thickets/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) -- Get Sea Puk ID and check if it is a PH of NP mob = mob:getID(); -- Check if Sea Puk is within the Nis_Puk_PH table if (Nis_Puk_PH[mob] ~= nil) then -- printf("%u is a PH",mob); -- Get NP's previous ToD NP_ToD = GetServerVariable("[POP]Nis_Puk"); -- Check if NP window is open, and there is not an NP popped already(ACTION_NONE = 0) if (NP_ToD <= os.time(t) and GetMobAction(Nis_Puk) == 0) then -- printf("NP window open"); -- Give Sea Puk 5 percent chance to pop NP if (math.random(1,20) >= 1) then -- printf("NP will pop"); UpdateNMSpawnPoint(Nis_Puk); GetMobByID(Nis_Puk):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Nis_Puk", mob); DeterMob(mob, true); end end end end;
gpl-3.0
kidaa/FFXIOrgins
scripts/zones/Chocobo_Circuit/Zone.lua
17
1068
----------------------------------- -- -- Zone: Chocobo_Circuit -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Chocobo_Circuit/TextIDs"] = nil; require("scripts/zones/Chocobo_Circuit/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; 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
mythzeal/tos_addon
Unbreakable/unbreakable.lua
1
4239
mzDlgTalk = mzDlgTalk or {}; mzDlgTalk.__talks = mzDlgTalk.__talks or {}; local __talks = mzDlgTalk.__talks; local talkNames = {"rein1", "rein2", "rein3"}; talkNames[#talkNames + 1] = talkNames[#talkNames]; __talks[talkNames[1]] = { [1] = {img = "hauberk", title = "魔将ホーバーク", text = "待つのだ、啓示者よ。"}, [2] = {img = "hauberk", title = "魔将ホーバーク", text = "その武具のポテンシャルは\"0\"だぞ。"}, [3] = {img = "hauberk", title = "魔将ホーバーク", text = "どうしても叩きたくば、\"黄金の金床\"を用意することだ。"}, }; __talks[talkNames[2]] = { [1] = {img = "raima", title = "女神ライマ", text = "待つのです、救済者よ。"}, [2] = {img = "raima", title = "女神ライマ", text = "その武具のポテンシャルはすでに\"0\"。"}, [3] = {img = "raima", title = "女神ライマ", text = "どうしても叩きたければ、\"黄金の金床\"を使うのです。"}, }; __talks[talkNames[3]] = { [1] = {img = "gesti", title = "魔王ジェスティ", text = "・・・。"}, [2] = {img = "gesti", title = "魔王ジェスティ", text = "おや、ポテンシャルが\"0\"だぞ?"}, [3] = {img = "gesti", title = "魔王ジェスティ", text = "どうした、叩かぬのか?臆病者め。"}, }; -- Hooked function function REINFORCE_131014_MSGBOX(frame) local fromItem, fromMoru = UPGRADE2_GET_ITEM(frame); local fromItemObj = GetIES(fromItem:GetObject()); local curReinforce = fromItemObj.Reinforce_2; local moruObj = GetIES(fromMoru:GetObject()); local price = GET_REINFORCE_131014_PRICE(fromItemObj, moruObj) local hadmoney = GET_TOTAL_MONEY(); if hadmoney < price then ui.AddText("SystemMsgFrame", ScpArgMsg('NotEnoughMoney')); return; end local classType = TryGetProp(fromItemObj,"ClassType"); local talkName = talkNames[math.floor(math.random(#talkNames))]; if moruObj.ClassName ~= "Moru_Potential" and moruObj.ClassName ~= "Moru_Potential14d" then if fromItemObj.GroupName == 'Weapon' or (fromItemObj.GroupName == 'SubWeapon' and classType ~='Shield') then if curReinforce >= 5 then if moruObj.ClassName == "Moru_Premium" or moruObj.ClassName == "Moru_Gold" or moruObj.ClassName == "Moru_Gold_14d" or moruObj.ClassName == "Moru_Gold_TA" then ui.MsgBox(ScpArgMsg("GOLDMORUdontbrokenitemProcessReinforce?", "Auto_1", 3), "REINFORCE_131014_EXEC", "None"); return; else if fromItemObj.PR > 0 then ui.MsgBox(ScpArgMsg("WeaponWarningMSG", "Auto_1", 5), "REINFORCE_131014_EXEC", "None"); else frame:ShowWindow(0); if DLGTALK_SHOW ~= nil then DLGTALK_SHOW(talkName); else ui.MsgBox("ポテンシャルが0だよ", "None", "None"); end end return; end end else if curReinforce >= 3 then if moruObj.ClassName == "Moru_Premium" or moruObj.ClassName == "Moru_Gold" or moruObj.ClassName == "Moru_Gold_14d" or moruObj.ClassName == "Moru_Gold_TA" then ui.MsgBox(ScpArgMsg("GOLDMORUdontbrokenitemProcessReinforce?", "Auto_1", 3), "REINFORCE_131014_EXEC", "None"); return; else if fromItemObj.PR > 0 then ui.MsgBox(ScpArgMsg("Over_+{Auto_1}_ReinforceItemCanBeBroken_ProcessReinforce?", "Auto_1", 3), "REINFORCE_131014_EXEC", "None"); else frame:ShowWindow(0); if DLGTALK_SHOW ~= nil then DLGTALK_SHOW(talkName); else ui.MsgBox("ポテンシャルが0だよ", "None", "None"); end end return; end end end end REINFORCE_131014_EXEC(); end math.randomseed(os.time()); CHAT_SYSTEM("reinforce loaded.");
agpl-3.0
actionless/awesome
tests/examples/awful/wibar/default.lua
4
1324
--DOC_NO_USAGE --DOC_GEN_IMAGE local awful = require("awful") --DOC_HIDE local wibox = require("wibox") --DOC_HIDE screen[1]._resize {width = 480, height = 200} --DOC_HIDE local wb = awful.wibar { position = "top" } --DOC_HIDE Create the same number of tags as the default config awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, screen[1], awful.layout.layouts[1]) --DOC_HIDE --DOC_HIDE Only bother with widgets that are visible by default local mykeyboardlayout = awful.widget.keyboardlayout() --DOC_HIDE local mytextclock = wibox.widget.textclock() --DOC_HIDE local mytaglist = awful.widget.taglist(screen[1], awful.widget.taglist.filter.all, {}) --DOC_HIDE local mytasklist = awful.widget.tasklist(screen[1], awful.widget.tasklist.filter.currenttags, {}) --DOC_HIDE local month_calendar = awful.widget.calendar_popup.month() --DOC_HIDE month_calendar:attach( mytextclock, "tr" ) --DOC_HIDE wb:setup { layout = wibox.layout.align.horizontal, { mytaglist, layout = wibox.layout.fixed.horizontal, }, mytasklist, { layout = wibox.layout.fixed.horizontal, mykeyboardlayout, mytextclock, }, } --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
Fatalerror66/ffxi-a
scripts/zones/Northern_San_dOria/npcs/Doggomehr.lua
2
1139
----------------------------------- -- Area: Northern San d'Oria -- NPC: Doggomehr -- Guild Merchant NPC: Blacksmithing Guild -- @zone: 231 -- @pos: -193.920 3.999 162.027 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:sendGuild(526,8,23,2)) then player:showText(npc,DOGGOMEHR_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kazupon/kyotocabinet-lua
docrefine.lua
1
1067
-- -- refine the documents -- INDEXFILE = "doc/index.html" MODULEFILE = "doc/modules/kyotocabinet.html" CSSFILE = "doc/luadoc.css" TMPFILE = INDEXFILE .. "~" OVERVIEWFILE = "overview.html" ofd = io.open(TMPFILE, "wb") first = true for line in io.lines(INDEXFILE) do if first and string.match(line, "<h2> *Modules *</h2>") then for tline in io.lines(OVERVIEWFILE) do ofd:write(tline .. "\n") end first = false end ofd:write(line .. "\n") end ofd:close() os.remove(INDEXFILE) os.rename(TMPFILE, INDEXFILE) ofd = io.open(TMPFILE, "wb") first = true for line in io.lines(MODULEFILE) do if string.match(line, "<em>Fields</em>") then ofd:write("<br/>\n") end ofd:write(line .. "\n") end ofd:close() os.remove(MODULEFILE) os.rename(TMPFILE, MODULEFILE) ofd = io.open(TMPFILE, "wb") for line in io.lines(CSSFILE) do if not string.match(line, "#TODO:") then ofd:write(line .. "\n") end end ofd:write("table.function_list td.name { width: 20em; }\n") ofd:close() os.remove(CSSFILE) os.rename(TMPFILE, CSSFILE)
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Aht_Urhgan_Whitegate/npcs/Asrahd.lua
2
2780
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Asrahd -- Type: Imperial Gate Guard -- @pos 0.011 -1 10.587 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; package.loaded["scripts/globals/besieged"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/besieged"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) merc_rank = getMercenaryRank(player); if(merc_rank == 0) then player:startEvent(0x0277,npc); else maps = getMapBitmask(player); if(getAstralCandescence() == 1) then maps = maps + 0x80000000; end; x,y,z,w = getImperialDefenseStats(); player:startEvent(0x0276,player:getPoint(IS),maps,merc_rank,0,x,y,z,w); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x0276 and option >= 1 and option <= 2049) then itemid = getISPItem(option); player:updateEvent(0,0,0,canEquip(player,itemid)); end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x276) then if(option == 0 or option == 16 or option == 32 or option == 48) then -- player chose sanction. if(option ~= 0) then player:delPoint(IS,100); end; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); duration = getSanctionDuration(player); if(option == 16 or option == 32) then -- refresh and regen sanction tick = 3; else tick = 0; end; player:addStatusEffect(EFFECT_SANCTION,option / 16,tick,duration); -- effect size 1 = regen, 2 = refresh, 3 = food. player:messageSpecial(SANCTION); elseif(option % 256 == 17) then -- player bought one of the maps id = 1862 + (option - 17) / 256; player:addKeyItem(id); player:messageSpecial(KEYITEM_OBTAINED,id); player:delPoint(IS,1000); elseif(option <= 2049) then -- player bought item item, price = getISPItem(option) if(player:getFreeSlotsCount() > 0) then player:delPoint(IS,price); player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); end; end; end; end;
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Mhaura/npcs/Celestina.lua
2
2472
----------------------------------- -- Area: Mhaura -- NPC: Celestina -- Finish Quest: The Sand Charm -- Involved in Quest: Riding on the Clouds -- Guild Merchant NPC: Goldsmithing Guild -- @zone 249 -- @pos -36 -16 72 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(OTHER_AREAS,THE_SAND_CHARM) == QUEST_ACCEPTED) then if(trade:hasItemQty(13095,1) and trade:getItemCount() == 1) then player:startEvent(0x007f); -- Finish quest "The Sand Charm" end end if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 5) 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) if(player:getVar("theSandCharmVar") == 3) then player:startEvent(0x007e,13095); -- During quest "The Sand Charm" - 3rd dialog elseif(player:sendGuild(523,8,23,4)) then player:showText(npc,GOLDSMITHING_GUILD); 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 == 0x007e and option == 70) then player:setVar("theSandCharmVar",4); elseif(csid == 0x007f) then player:tradeComplete(); player:setVar("theSandCharmVar",0); player:setVar("SmallDialogByBlandine",1); player:addKeyItem(MAP_OF_BOSTAUNIEUX_OUBLIETTE); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_BOSTAUNIEUX_OUBLIETTE); player:addFame(OTHER_AREAS,30); player:completeQuest(OTHER_AREAS,THE_SAND_CHARM); end end;
gpl-3.0
mys007/nn
LookupTable.lua
3
2360
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module') LookupTable.__version = 4 function LookupTable:__init(nIndex, nOutput) parent.__init(self) self.weight = torch.Tensor(nIndex, nOutput) self.gradWeight = torch.Tensor(nIndex, nOutput):zero() self._count = torch.IntTensor() self._input = torch.LongTensor() self.shouldScaleGradByFreq = false self:reset() end function LookupTable:accUpdateOnly() self.gradWeight = nil return self end function LookupTable:scaleGradByFreq() self.shouldScaleGradByFreq = true return self end function LookupTable:reset(stdv) stdv = stdv or 1 self.weight:normal(0, stdv) end function LookupTable:makeInputContiguous(input) -- make sure input is a contiguous torch.LongTensor if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then self.copiedInput = true self._input:resize(input:size()):copy(input) return self._input end self.copiedInput = false return input end function LookupTable:updateOutput(input) input = self:makeInputContiguous(input) if input:dim() == 1 then self.output:index(self.weight, 1, input) elseif input:dim() == 2 then self.output:index(self.weight, 1, input:view(-1)) self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2)) else error("input must be a vector or matrix") end return self.output end function LookupTable:accGradParameters(input, gradOutput, scale) input = self.copiedInput and self._input or input if input:dim() == 2 then input = input:view(-1) elseif input:dim() ~= 1 then error("input must be a vector or matrix") end self.gradWeight.nn.LookupTable_accGradParameters(self, input, gradOutput, scale) end function LookupTable:type(type) parent.type(self, type) if type == 'torch.CudaTensor' then -- CUDA uses _sorted and _indices temporary tensors self._sorted = self.weight.new() self._indices = self.weight.new() else -- self._count and self._input should only be converted if using Cuda self._count = torch.IntTensor() self._input = torch.LongTensor() end return self end -- we do not need to accumulate parameters when sharing LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
bsd-3-clause
nenau/naev
dat/ai/tpl/scout.lua
5
2375
include("dat/ai/include/basic.lua") -- Variables planet_dist = 1500 -- distance to keep from planets enemy_dist = 800 -- distance to keep from enemies -- Required control rate control_rate = 2 -- Required "control" function function control () task = ai.taskname() if task == nil or task == "idle" then enemy = ai.getenemy() -- There is an enemy if enemy ~= nil then if ai.dist(enemy) < enemy_dist or ai.haslockon() then ai.pushtask("runaway", enemy) return end end -- nothing to do so check if we are too far form the planet (if there is one) if mem.approach == nil then local planet = ai.rndplanet() if planet ~= nil then mem.approach = planet:pos() end end planet = mem.approach if planet ~= nil then if ai.dist(planet) > planet_dist then ai.pushtask("approach") return end end -- Go idle if no task if task == nil then ai.pushtask("idle") return end -- Check if we are near enough elseif task == "approach" then planet = mem.approach if ai.dist( planet ) < planet_dist + ai.minbrakedist() then ai.poptask() ai.pushtask("idle") return end -- Check if we need to run more elseif task == "runaway" then enemy = ai.target() if ai.dist(enemy) > enemy_dist and ai.haslockon() == false then ai.poptask() return end end end -- Required "attacked" function function attacked ( attacker ) task = ai.taskname() -- Start running away if task ~= "runaway" then ai.pushtask("runaway", attacker) elseif task == "runaway" then if ai.target() ~= attacker then -- Runaway from the new guy ai.poptask() ai.pushtask("runaway", attacker) end end end -- Required "create" function function create () end -- Effectively does nothing function idle () if ai.isstopped() == false then ai.brake() end end -- Approaches the target function approach () target = mem.approach dir = ai.face(target) dist = ai.dist(target) -- See if should accel or brake if dist > planet_dist then ai.accel() else ai.poptask() ai.pushtask("idle") end end
gpl-3.0
brendangregg/bcc
examples/lua/strlen_count.lua
3
1305
#!/usr/bin/env bcc-lua --[[ 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. ]] assert(arg[1], "usage: strlen_count PID") local program = string.gsub([[ #include <uapi/linux/ptrace.h> int printarg(struct pt_regs *ctx) { if (!PT_REGS_PARM1(ctx)) return 0; u32 pid = bpf_get_current_pid_tgid(); if (pid != PID) return 0; char str[128] = {}; bpf_probe_read_user(&str, sizeof(str), (void *)PT_REGS_PARM1(ctx)); bpf_trace_printk("strlen(\"%s\")\n", &str); return 0; }; ]], "PID", arg[1]) return function(BPF) local b = BPF:new{text=program, debug=0} b:attach_uprobe{name="c", sym="strlen", fn_name="printarg"} local pipe = b:pipe() while true do local task, pid, cpu, flags, ts, msg = pipe:trace_fields() print("%-18.9f %-16s %-6d %s" % {ts, task, pid, msg}) end end
apache-2.0
mys007/nn
SpatialConvolution.lua
27
4452
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padW = padW or 0 self.padH = padH or self.padW self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() if self.padding then self.padW = self.padding self.padH = self.padding self.padding = nil else self.padW = self.padW or 0 self.padH = self.padH or 0 end if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end function SpatialConvolution:updateOutput(input) backCompatibility(self) viewWeight(self) input = makeContiguous(self, input) local out = input.nn.SpatialConvolutionMM_updateOutput(self, input) unviewWeight(self) return out end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then backCompatibility(self) viewWeight(self) input, gradOutput = makeContiguous(self, input, gradOutput) local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) unviewWeight(self) return out end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) viewWeight(self) local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) unviewWeight(self) return out end function SpatialConvolution:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end function SpatialConvolution:__tostring__() local s = string.format('%s(%d -> %d, %dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.kW, self.kH) if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d', self.dW, self.dH) end if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padW .. ',' .. self.padH end return s .. ')' end
bsd-3-clause
Fatalerror66/ffxi-a
scripts/globals/items/bowl_of_dhalmel_stew.lua
2
1688
----------------------------------------- -- ID: 4433 -- Item: Bowl of Dhalmel Stew -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 4 -- Agility 1 -- Vitality 2 -- Intelligence -2 -- Attack % 25 -- Attack Cap 45 -- Ranged ATT % 25 -- Ranged ATT Cap 45 ----------------------------------------- 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,10800,4433); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 4); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 45); target:addMod(MOD_FOOD_RATTP, 25); target:addMod(MOD_FOOD_RATT_CAP, 45); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 4); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 45); target:delMod(MOD_FOOD_RATTP, 25); target:delMod(MOD_FOOD_RATT_CAP, 45); end;
gpl-3.0