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
RebootRevival/FFXI_Test
scripts/zones/Batallia_Downs/npcs/qm2.lua
17
1515
----------------------------------- -- Area: Batallia Downs -- NPC: qm2 (???) -- Pop for the quest "Chasing Quotas" ----------------------------------- package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Batallia_Downs/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Sturmtiger = player:getVar("SturmtigerKilled"); if (player:getVar("ChasingQuotas_Progress") == 5 and Sturmtiger == 0) then SpawnMob(17207696,300):updateClaim(player); elseif (Sturmtiger == 1) then player:addKeyItem(RANCHURIOMES_LEGACY); player:messageSpecial(KEYITEM_OBTAINED,RANCHURIOMES_LEGACY); player:setVar("ChasingQuotas_Progress",6); player:setVar("SturmtigerKilled",0); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) 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
djianq/Game
lualib/sharemap.lua
78
1496
local stm = require "stm" local sprotoloader = require "sprotoloader" local sproto = require "sproto" local setmetatable = setmetatable local sharemap = {} function sharemap.register(protofile) -- use global slot 0 for type define sprotoloader.register(protofile, 0) end local sprotoobj local function loadsp() if sprotoobj == nil then sprotoobj = sprotoloader.load(0) end return sprotoobj end function sharemap:commit() self.__obj(sprotoobj:encode(self.__typename, self.__data)) end function sharemap:copy() return stm.copy(self.__obj) end function sharemap.writer(typename, obj) local sp = loadsp() obj = obj or {} local stmobj = stm.new(sp:encode(typename,obj)) local ret = { __typename = typename, __obj = stmobj, __data = obj, commit = sharemap.commit, copy = sharemap.copy, } return setmetatable(ret, { __index = obj, __newindex = obj }) end local function decode(msg, sz, self) local data = self.__data for k in pairs(data) do data[k] = nil end return sprotoobj:decode(self.__typename, msg, sz, data) end function sharemap:update() return self.__obj(decode, self) end function sharemap.reader(typename, stmcpy) local sp = loadsp() local stmobj = stm.newcopy(stmcpy) local _, data = stmobj(function(msg, sz) return sp:decode(typename, msg, sz) end) local obj = { __typename = typename, __obj = stmobj, __data = data, update = sharemap.update, } return setmetatable(obj, { __index = data, __newindex = error }) end return sharemap
mit
gowadbd/DevDroid
plugins/hello.lua
1
2628
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY BAKURY ▀▄ ▄▀ ▀▄ ▄▀ BY sadik (@illOlli) ▀▄ ▄▀ ▀▄ ▄ JUST WRITED BY BAKURY ▀▄ ▄▀ ▀▄ ▄▀ wolcom : ترحيب ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function run(msg,matches) if matches[1] == "chat_add_user" then local text = ' اهلا بك في المجموعه كبد حياتي 🙈💋'..'\n'..'\n' ..'🦁 اسمـ☆ـك : '..msg.action.user.print_name..'\n' ..'🦁 معـ☆ـرفك : @'..(msg.action.user.username or "لا يوجد")..'\n' ..'🦁 الايـ❃ـدي : '..msg.action.user.id..'\n' ..'🦁 رقـم هاتـ❅ـفك : '..(msg.action.user.phone or "لا يوجد")..'\n' ..'🦁 الـي ضـ❉ـافك : '..msg.from.print_name..'\n' ..'🦁 معـ☆ـرف الـي ضـافك : @'..(msg.from.username or "لا يوجد")..'\n' ..'📆 الـتاريخ : '..os.date('!%A, %B %d, %Y*\n', timestamp) ..'🕧 الوقـت : '..os.date(' %T*', os.time())..'\n' return reply_msg(msg.id, text, ok_cb, false) end if matches[1] == "chat_add_user_link" then local text = ' اهلا بك في المجموعه كبد حياتي 🙈💋'..'\n'..'\n' ..'🦁 اسـ☆ـمك : '..msg.from.print_name..'\n' ..'🦁 معـ☆ـرفك : @'..(msg.from.username or "لا يوجد")..'\n' ..'🦁 الايـ❃ـدي : '..msg.from.id..'\n' ..'🦁رقـم هاتـ❆ـفك : '..(msg.from.phone or "لا يوجد")..'\n' ..'🦁 اسـم المجـ❆ـموعة : '..msg.to.title..'\n' ..'🦁 ايـدي المجـ❈ـموعة : '..msg.to.id..'\n' ..'📆 الـتاريخ : '..os.date('!%A, %B %d, %Y*\n', timestamp) ..'🕧 الوقـت : '..os.date(' %T*', os.time())..'\n' return reply_msg(msg.id, text, ok_cb, false) end if matches[1] == "chat_del_user" then return " 🔸 الله وياك/ج كبد عمري 😍🙈 لتنسه الباب مفتوح 🌚"..msg.action.user.first_name end end return { patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$" }, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/LaLoff_Amphitheater/npcs/qm0_1.lua
17
1165
----------------------------------- -- 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
tommo/mock
mock/ai/ScriptedFSMController.lua
1
2942
module 'mock' CLASS: ScriptedFSMController ( FSMController ) :MODEL{ Field 'script' :asset( 'com_script' ) :getset( 'Script' ); } registerComponent( 'ScriptedFSMController', ScriptedFSMController ) function ScriptedFSMController:__init() self.scriptPath = false self.delegate = false self.dataInstance = false end function ScriptedFSMController:getScript() return self.scriptPath end function ScriptedFSMController:setScript( path ) self.scriptPath = path self:updateComponentScript() end function ScriptedFSMController:updateComponentScript() local path = self.scriptPath local scriptObj = loadAsset( path ) local delegate, dataInstance for k, v in pairs( self ) do --clear collected method if k:startwith( '_FSM_' ) then self[ k ] = false end end if scriptObj then local fsmCollector = FSMController.__createStateMethodCollector( self ) delegate, dataInstance = scriptObj:buildInstance( self, { fsm = fsmCollector } ) end local prevInstance = self.dataInstance self.delegate = delegate or false self.dataInstance = dataInstance or false if prevInstance and dataInstance then _cloneObject( prevInstance, dataInstance ) end end function ScriptedFSMController:onStart( ent ) --Update delegate local delegate = self.delegate if delegate then --insert global variables delegate.entity = ent -- delegate.scene = ent:getScene() local onStart = delegate.onStart if onStart then onStart() end self.onThread = delegate.onThread local onMsg = delegate.onMsg if onMsg then self.msgListener = onMsg ent:addMsgListener( self.msgListener ) end if delegate.onUpdate then ent.scene:addUpdateListener( self ) end end return FSMController.onStart( self, ent ) end function ScriptedFSMController:onUpdate( dt ) return self.delegate.onUpdate( dt ) end function ScriptedFSMController:onDetach( ent ) if self.delegate then local onDetach = self.delegate.onDetach if onDetach then onDetach( ent ) end if self.msgListener then ent:removeMsgListener( self.msgListener ) end ent.scene:removeUpdateListener( self ) end end function ScriptedFSMController:installInputListener( option ) return installInputListener( self.delegate, option ) end function ScriptedFSMController:uninstallInputListener() return uninstallInputListener( self.delegate ) end function ScriptedFSMController:__serialize( objMap ) local dataInstance = self.dataInstance if not dataInstance then return end return _serializeObject( dataInstance, objMap ) end function ScriptedFSMController:__deserialize( data, objMap ) if not data then return end local dataInstance = self.dataInstance if not dataInstance then return end return _deserializeObject( dataInstance, data, objMap ) end function ScriptedFSMController:__clone( src, objMap ) local dataInstance = self.dataInstance if not dataInstance then return end return _cloneObject( src, dataInstance, objMap ) end
mit
onpon4/naev
dat/missions/empire/emp_cargo00.lua
1
4062
--[[ <?xml version='1.0' encoding='utf8'?> <mission name="Empire Recruitment"> <flags> <unique /> </flags> <avail> <priority>70</priority> <chance>40</chance> <location>Bar</location> <faction>Empire</faction> </avail> </mission> --]] --[[ Simple cargo mission that opens up the Empire cargo missions. Author: bobbens minor edits by Infiltrator ]]-- require "numstring" require "jumpdist" require "missions/empire/common" bar_desc = _("You see an Empire Lieutenant who seems to be looking at you.") misn_title = _("Empire Recruitment") misn_desc = _("Land on %s (%s system) to deliver some parcels for the Empire") text = {} text[1] = _([[You approach the Empire Lieutenant. "Hello, I'm Lieutenant Czesc from the Empire Armada Shipping Division. We're having another recruitment operation and would be interested in having another pilot among us. Would you be interested in working for the Empire?"]]) text[2] = _([["Welcome aboard," says Czesc before giving you a firm handshake. "At first you'll just be tested with cargo missions while we gather data on your flying skills. Later on, you could get called upon for more important missions. Who knows? You could be the next Yao Pternov, greatest pilot we ever had in the armada." He hits a couple buttons on his wrist computer, which springs into action. "It looks like we already have a simple task for you. Deliver these parcels to %s. The best pilots started delivering papers and ended up flying into combat against gigantic warships with the Interception Division."]]) text[3] = _([[You deliver the parcels to the Empire Shipping station at the %s spaceport. Afterwards, they make you do some paperwork to formalise your participation with the Empire. They tell you to keep an eye out for missions labeled ES, which stands for Empire Shipping, in the mission computer, to which you now have access. You aren't too sure of what to make of your encounter with the Empire. Only time will tell...]]) log_text = _([[You were recruited into the Empire's shipping division and can now do missions labeled ES, which stands for Empire Shipping. You aren't too sure of what to make of your encounter with the Empire. Only time will tell...]]) function create () -- Note: this mission does not make any system claims. local landed, landed_sys = planet.cur() -- target destination local planets = {} getsysatdistance(system.cur(), 1, 6, function(s) for i, v in ipairs(s:planets()) do if v:faction() == faction.get("Empire") and v:canLand() then planets[#planets + 1] = {v, s} end end return false end) if #planets == 0 then abort() end -- In case no suitable planets are in range. local index = rnd.rnd(1, #planets) dest = planets[index][1] sys = planets[index][2] misn.setNPC(_("Lieutenant"), "empire/unique/czesc.png", bar_desc) end function accept () -- Intro text if not tk.yesno("", text[1]) then misn.finish() end misn.markerAdd(sys, "low") -- Accept the mission misn.accept() -- Mission details reward = 30000 misn.setTitle(misn_title) misn.setReward(creditstring(reward)) misn.setDesc(misn_desc:format(dest:name(), sys:name())) -- Flavour text and mini-briefing tk.msg("", string.format(text[2], dest:name())) misn.osdCreate(misn_title, {misn_desc:format(dest:name(), sys:name())}) -- Set up the goal local c = misn.cargoNew(N_("Parcels"), N_("A bunch of boring Empire parcels.")) parcels = misn.cargoAdd(c, 0) hook.land("land") end function land() local landed = planet.cur() if landed == dest then if misn.cargoRm(parcels) then player.pay(reward) -- More flavour text tk.msg("", string.format(text[3], dest:name())) var.push("es_cargo", true) faction.modPlayerSingle("Empire",3); emp_addShippingLog(log_text) misn.finish(true) end end end function abort() misn.finish(false) end
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Lower_Jeuno/npcs/_l00.lua
3
2852
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- !pos -107 0 -158 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/NPCIDs"); require("scripts/zones/Lower_Jeuno/TextIDs"); -- lamp id vary from 17780881 to 17780892 -- lamp cs vary from 0x0078 to 0x0083 (120 to 131) local lampNum = 0; local lampId = lampIdOffset + lampNum; local cs = lampCsOffset + lampNum; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); local playerOnQuest = GetServerVariable("[JEUNO]CommService"); -- player is on the quest if playerOnQuest == player:getID() then if hour >= 20 and hour < 21 then player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock. elseif hour >= 21 or hour < 1 then if npc:getAnimation() == ANIMATION_OPEN_DOOR then player:startEvent(cs,2); -- The lamp is already lit. else player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No end else player:startEvent(cs,3); -- You have failed to light the lamps in time. end -- player is not on the quest else if npc:getAnimation() == ANIMATION_OPEN_DOOR then player:startEvent(cs,5); -- The lamp is lit. else player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually. end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if csid == cs and option == 1 then -- lamp is now lit GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR); -- tell player how many remain local lampsRemaining = 12; for i=0,11 do local lamp = GetNPCByID(lampIdOffset + i); if lamp:getAnimation() == ANIMATION_OPEN_DOOR then lampsRemaining = lampsRemaining - 1; end end if lampsRemaining == 0 then player:messageSpecial(LAMP_MSG_OFFSET); else player:messageSpecial(LAMP_MSG_OFFSET+1,lampsRemaining); end end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Sacrificial_Chamber/bcnms/amphibian_assault.lua
19
1761
----------------------------------- -- Area: Sacrificial Chamber -- Name: Amphibian Assualt -- BCNM60 ----------------------------------- package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Sacrificial_Chamber/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); end;
gpl-3.0
openwrt-es/openwrt-luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/wifi.lua
7
11101
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wireless"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) bssid.datatype = "macaddr" local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
apache-2.0
tommo/mock
mock/extra/ScreenAnchor.lua
2
1181
module 'mock' EnumScreenAnchorTypeV = _ENUM_V { 'top', 'center', 'bottom', } EnumScreenAnchorTypeH = _ENUM_V { 'left', 'center', 'right', } CLASS: ScreenAnchor ( Component ) :MODEL{ Field 'targetCamera' :type( Camera ); Field 'alignH' :enum( EnumScreenAnchorTypeV ); Field 'alignV' :enum( EnumScreenAnchorTypeH ); Field 'offset' :type('vec2') :tuple_getset() :onset( 'updateLoc' ); } function ScreenAnchor:__init() self.targetCamera = false self.alignH = 'center' self.alignV = 'center' self.offset = { 0, 0 } end function ScreenAnchor:onAttach( ent ) self:updateLoc() end function ScreenAnchor:updateLoc() local ent = self._entity local camera = self:getTargetCamera() local w, h = camera:getViewportSize() local ah, av = self.alignH, self.alignV local x, y x = ( ah == 'left' and -w/2 ) or ( ah == 'right' and w/2 ) or 0 y = ( av == 'top' and h/2 ) or ( av == 'bottom' and -h/2 ) or 0 local ox, oy = unpack( self.offset ) ent:setWorldLoc( x + ox, y + oy ) print( x, y, w,h, av, ah ) end function ScreenAnchor:getTargetCamera() if self.targetCamera then return self.targetCamera end end function ScreenAnchor:drawGizmo() end
mit
tommo/mock
mock/effect/EffectEmitter.lua
1
5026
module 'mock' EnumActionOnStop = _ENUM_V{ 'default', --inherit from effect 'detach', 'destroy', 'none' } -------------------------------------------------------------------- CLASS: EffectEmitter ( Component ) :MODEL{ Field 'effect' :asset('effect') :set('setEffect'); Field 'autoPlay' :boolean(); Field 'actionOnStop' :enum( EnumActionOnStop ); Field 'delay' :number(); '----'; Field 'transformRole' :string(); } :META{ category = 'FX' } mock.registerComponent( 'EffectEmitter', EffectEmitter ) -------------------------------------------------------------------- function EffectEmitter:__init() self.duration = false self.effect = false self.autoPlay = true self.effectConfig = false self.hasActiveState = false self.prop = MOAIProp.new() self.activeStates = {} self.mirrorX = false self.mirrorY = false self.actionOnStop = 'default' self.delay = 0 self.transformRole = 'render' self.defaultState = false end function EffectEmitter:onAttach( entity ) entity:_attachProp( self.prop, self.transformRole or 'render' ) end function EffectEmitter:onDetach( entity ) self:stop() entity:_detachProp( self.prop ) end function EffectEmitter:onStart() if self.autoPlay then if self.delay > 0 then self:addCoroutine( function () self:wait( self.delay ) self:start() end) else self:start() end end end function EffectEmitter:restart() self:stop() self:start() end function EffectEmitter:loadEffect( effectConfig ) if type( effectConfig ) == 'string' then effectConfig = loadAsset( effectConfig ) end if not effectConfig then _error( 'nil effectConfig' ) return false end local state = EffectState( self, effectConfig ) self.activeStates[ state ] = true state:load() if not self.hasActiveState then self._entity.scene:addUpdateListener( self ) self.hasActiveState = true end return state end function EffectEmitter:start() if self.defaultState then return end local effect = self.effect or self.effectConfig if not effect then return end local state = self:loadEffect( effect ) self.defaultState = state if self.duration then state:setDuration( self.duration ) end state:start() return state end function EffectEmitter:stop( actionOnStop ) if not self.hasActiveState then return end self._entity.scene:removeUpdateListener( self ) for state in pairs( self.activeStates ) do state:stop() end self.defaultState = false self.activeStates = {} self.hasActiveState = false local actionOnStop = actionOnStop or self.actionOnStop if actionOnStop == 'default' then if self.effectConfig then actionOnStop = self.effectConfig:getRootNode().actionOnStop end end if actionOnStop == 'detach' then self._entity:detach( self ) elseif actionOnStop == 'destroy' then self._entity:destroy() else -- do nothing end end function EffectEmitter:onUpdate( dt ) local stoppedStates = false for state in pairs( self.activeStates ) do state:update( dt ) if not state:isPlaying() then stoppedStates = stoppedStates or {} stoppedStates[ state ] = true end end local activeStates = self.activeStates if stoppedStates then for s in pairs( stoppedStates ) do if s == self.defaultState then self.defaultState = false end activeStates[ s ] = nil end if not next( activeStates ) then self:stop() return end end end function EffectEmitter:setEffect( e ) local tt = type( e ) if tt == 'string' then --path self.effect = e self.effectConfig = mock.loadAsset( e ) else self.effect = false self.effectConfig = e end end function EffectEmitter:setActionOnStop( f ) self.actionOnStop = f or 'default' end function EffectEmitter:setDuration( d ) self.duration = d if self.defaultEffectState then self.defaultEffectState:setDuration( d ) end end function EffectEmitter:setMirrorX( mirror ) self.mirrorX = mirror setSclX( self.prop, (mirror and -1) or 1 ) end function EffectEmitter:setMirrorY( mirror ) self.mirrorY = mirror setSclY( self.prop, (mirror and -1) or 1 ) end -------------------------------------------------------------------- --EDITOR Support if mock_edit then function EffectEmitter:onBuildGizmo() local giz = mock_edit.IconGizmo( 'effect.png' ) return giz end function EffectEmitter:onBuildPreviewer() return EffectEmitterPreviewer( self ) end -------------------------------------------------------------------- CLASS: EffectEmitterPreviewer ( ComponentPreviewer ) :MODEL{} function EffectEmitterPreviewer:__init( emitter ) self.targetEmitter = emitter end function EffectEmitterPreviewer:onStart() self.targetState = self.targetEmitter:start() end function EffectEmitterPreviewer:onUpdate( dt ) -- self.targetState:update( dt ) end function EffectEmitterPreviewer:onDestroy() if self.targetState then self.targetEmitter:stop( 'skip' ) self.targetState = false end end function EffectEmitterPreviewer:onReset() self:onDestroy() self:onStart() end end
mit
RebootRevival/FFXI_Test
scripts/globals/items/nopales_salad.lua
12
1358
----------------------------------------- -- ID: 5701 -- Item: nopales_salad -- Food Effect: 3Hrs, All Races ----------------------------------------- -- Strength 1 -- Agility 6 -- Ranged Accuracy +20 -- Ranged Attack +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,10800,5701); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 1); target:addMod(MOD_AGI, 6); target:addMod(MOD_RACC, 20); target:addMod(MOD_RATT, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 1); target:delMod(MOD_AGI, 6); target:delMod(MOD_RACC, 20); target:delMod(MOD_RATT, 10); end;
gpl-3.0
akavel/svgmath
svgmath/fonts/glyphlist.lua
1
1600
local math, string, table, arg = math, string, table, arg local pairs, ipairs, require, tonumber, error = pairs, ipairs, require, tonumber, error local _ENV = {package=package} local PYLUA = require('PYLUA') local os = require('os') GlyphList = PYLUA.class(dict) { __init__ = function(self, f) while true do local line = f:readline() if #line==0 then break end line = PYLUA.strip(line) if #line==0 or PYLUA.startswith(line, '#') then goto continue end local pair = PYLUA.split(line, ';') if #pair~=2 then goto continue end local glyph = PYLUA.strip(pair[1]) local codelist = PYLUA.split(pair[2]) if #codelist~=1 then goto continue -- no support for compounds end local codepoint = tonumber(codelist[1], 16) or error('cannot convert '..codelist[1]..' to codepoint') if self[glyph] then table.insert(self[glyph], codepoint) else self[glyph] = {codepoint} end ::continue:: end end ; lookup = function(self, glyphname) return self[glyphname] or defaultGlyphList[glyphname] end ; } local glyphListName = PYLUA.dirname(arg[0]) .. 'svgmath/fonts/default.glyphs' defaultGlyphList = GlyphList(PYLUA.open(glyphListName, 'r')) main = function() if #arg>0 then local glyphList = parseGlyphList(PYLUA.open(arg[1], 'r')) else glyphList = defaultGlyphList end for entry, value in pairs(glyphList) do PYLUA.print(entry, ' => ', value, '\n') end end if arg and arg[1]==... then main() end return _ENV
mit
RebootRevival/FFXI_Test
scripts/globals/items/plate_of_felicifruit_gelatin.lua
12
1387
----------------------------------------- -- ID: 5978 -- Item: Plate of Felicifruit Gelatin -- Food Effect: 180 Min, All Races ----------------------------------------- -- MP % 5 Cap 100 -- Intelligence +7 -- MP Healing +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5978); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 5); target:addMod(MOD_FOOD_MP_CAP, 100); target:addMod(MOD_INT, 7); target:addMod(MOD_MPHEAL, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 5); target:delMod(MOD_FOOD_MP_CAP, 100); target:delMod(MOD_INT, 7); target:delMod(MOD_MPHEAL, 3); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/shrimp_cracker_+1.lua
12
1497
----------------------------------------- -- ID: 5636 -- Item: shrimp_cracker_+1 -- Food Effect: 5Min, All Races ----------------------------------------- -- Vitality 2 -- Defense +10 -- Amorph Killer 12 -- Resist Virus 12 -- HP Recovered While Healing 9 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5636); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 2); target:addMod(MOD_DEF, 10); target:addMod(MOD_AMORPH_KILLER, 12); target:addMod(MOD_VIRUSRES, 12); target:addMod(MOD_HPHEAL, 9); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 2); target:delMod(MOD_DEF, 10); target:delMod(MOD_AMORPH_KILLER, 12); target:delMod(MOD_VIRUSRES, 12); target:delMod(MOD_HPHEAL, 9); end;
gpl-3.0
lzyzsd/ABTestingGateway
admin/runtime/set.lua
22
4799
local runtimeModule = require('abtesting.adapter.runtime') local policyModule = require('abtesting.adapter.policy') local redisModule = require('abtesting.utils.redis') local systemConf = require('abtesting.utils.init') local handler = require('abtesting.error.handler').handler local utils = require('abtesting.utils.utils') local ERRORINFO = require('abtesting.error.errcode').info local cjson = require('cjson.safe') local redisConf = systemConf.redisConf local prefixConf = systemConf.prefixConf local runtimeLib = prefixConf.runtimeInfoPrefix local policyLib = prefixConf.policyLibPrefix local domain_name = prefixConf.domainname local divtypes = systemConf.divtypes local separator = ':' local fields = {} fields.divtype = 'divtype' fields.divdata = 'divdata' fields.idCount = 'idCount' local doresp = utils.doresp local dolog = utils.dolog local domainName = domain_name if not domainName or domainName == ngx.null or string.len(domainName) < 1 then local info = ERRORINFO.PARAMETER_NONE local desc = "domainName is blank and please set it in nginx.conf" local response = doresp(info, desc) dolog(info, desc) ngx.say(response) return end local policyID = ngx.var.arg_policyid if policyID then policyID = tonumber(ngx.var.arg_policyid) if not policyID or policyID < 0 then local info = ERRORINFO.PARAMETER_TYPE_ERROR local desc = "policyID should be a positive Integer" local response = doresp(info, desc) dolog(info, desc) ngx.say(response) return end end if not policyID then local request_body = ngx.var.request_body local postData = cjson.decode(request_body) if not request_body then -- ERRORCODE.PARAMETER_NONE local info = ERRORINFO.PARAMETER_NONE local desc = 'request_body or post data to get policyID' local response = doresp(info, desc) dolog(info, desc) ngx.say(response) return end if not postData then -- ERRORCODE.PARAMETER_ERROR local info = ERRORINFO.PARAMETER_ERROR local desc = 'postData is not a json string' local response = doresp(info, desc) dolog(info, desc) ngx.say(response) return end policyID = postData.policyid if not policyID then local info = ERRORINFO.PARAMETER_ERROR local desc = "policyID is needed" local response = doresp(info, desc) dolog(info, desc) ngx.say(response) return end policyID = tonumber(postData.policyid) if not policyID or policyID < 0 then local info = ERRORINFO.PARAMETER_TYPE_ERROR local desc = "policyID should be a positive Integer" local response = doresp(info, desc) dolog(info, desc) ngx.say(response) return end end local red = redisModule:new(redisConf) local ok, err = red:connectdb() if not ok then local errinfo = ERRORINFO.REDIS_CONNECT_ERROR local response = doresp(errinfo, err) dolog(errinfo, err) ngx.say(response) return end local pfunc = function() local policyMod = policyModule:new(red.redis, policyLib) return policyMod:get(policyID) end local status, info = xpcall(pfunc, handler) if not status then local errinfo = info[1] local errstack = info[2] local err, desc = errinfo[1], errinfo[2] local response = doresp(err, desc) dolog(err, desc, nil, errstack) ngx.say(response) return end local divtype = info.divtype local divdata = info.divdata if divtype == ngx.null or divdata == ngx.null then local err = ERRORINFO.POLICY_BLANK_ERROR local desc = 'policy NO.'..policyID local response = doresp(err, desc) dolog(err, desc) ngx.say(response) return end if not divtypes[divtype] then -- unsupported divtype end local pfunc = function() local divModulename = table.concat({'abtesting', 'diversion', divtype}, '.') local divDataKey = table.concat({policyLib, policyID, fields.divdata}, ':') local userInfoModulename= table.concat({'abtesting', 'userinfo', divtypes[divtype]}, '.') local runtimeMod = runtimeModule:new(red.redis, runtimeLib) return runtimeMod:set(domainName, divModulename, divDataKey, userInfoModulename) end local status, info = xpcall(pfunc, handler) if not status then local errinfo = info[1] local errstack = info[2] local err, desc = errinfo[1], errinfo[2] local response = doresp(err, desc) dolog(err, desc, nil, errstack) ngx.say(response) return end local response = doresp(ERRORINFO.SUCCESS) ngx.say(response)
mit
RebootRevival/FFXI_Test
scripts/zones/Riverne-Site_A01/npcs/_0u1.lua
17
1367
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x6); else player:messageSpecial(SD_VERY_SMALL); end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Xarcabard/mobs/Biast.lua
3
1302
----------------------------------- -- Area: Xarcabard -- NM: Biast -- ID: 17235988 ----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Set Biast's ToD SetServerVariable("[POP]Biast", os.time() + 75600); -- 21 hour DisallowRespawn(mob:getID()-1, false); GetMobByID(mob:getID()-1):setRespawnTime(GetMobRespawnTime(mob:getID()-1)); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) if ((math.random(1,15) ~= 5) or (target:hasStatusEffect(EFFECT_TERROR) == true)) then return 0,0,0; else local duration = 5; target:addStatusEffect(EFFECT_TERROR,1,0,duration); mob:resetEnmity(target); return SUBEFFECT_NONE,0,EFFECT_TERROR; end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/abilities/pets/magic_mortar.lua
4
1313
--------------------------------------------------- -- Magic Mortar --------------------------------------------------- require("scripts/globals/status") require("scripts/globals/settings") require("scripts/globals/automatonweaponskills") --------------------------------------------------- function onMobSkillCheck(target, automaton, skill) local master = automaton:getMaster() return master:countEffect(EFFECT_LIGHT_MANEUVER) end function onPetAbility(target, automaton, skill, master, action) local ftp local tp = skill:getTP() if not USE_ADOULIN_WEAPON_SKILL_CHANGES then ftp = 0.5 + ((0.5/3000) * tp) else -- Might be wrong, it may only use max hp in its new form, also it may be able to miss and take defense into account as well if tp >= 3000 then ftp = 2.5 elseif tp >= 2000 then ftp = 1.75 + ((0.75/3000) * tp) else ftp = 1.5 + ((0.25/3000) * tp) end end local hpdamage = (automaton:getMaxHP() - automaton:getHP()) * ftp local skilldamage = automaton:getSkillLevel(22) * ftp local damage = (hpdamage > skilldamage) and hpdamage or skilldamage if damage > 0 then target:addTP(20) automaton:addTP(80) end target:delHP(damage) return damage end
gpl-3.0
MRAHS/SuperGpSupporter
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
RebootRevival/FFXI_Test
scripts/globals/spells/cure_vi.lua
1
4297
----------------------------------------- -- Spell: Cure VI -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- 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) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 600; power = getCurePower(caster); if (power < 210) then divisor = 1.5; constant = 600; basepower = 90; elseif (power < 300) then divisor = 0.9; constant = 680; basepower = 210; elseif (power < 400) then divisor = 10/7; constant = 780; basepower = 300; elseif (power < 500) then divisor = 2.5; constant = 850; basepower = 400; elseif (power < 700) then divisor = 5/3; constant = 890; basepower = 500; else divisor = 999999; constant = 1010; basepower = 0; end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then basecure = getBaseCure(power,divisor,constant,basepower); final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:restoreHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else if (target:isUndead()) then spell:setMsg(2); local params = {}; params.dmg = minCure; params.multiplier = 1; params.skillType = HEALING_MAGIC_SKILL; params.attribute = MOD_MND; params.hasMultipleTargetReduction = false; local dmg = calculateMagicDamage(caster, target, spell, params)*0.5; local params = {}; params.diff = caster:getStat(MOD_MND)-target:getStat(MOD_MND); params.attribute = MOD_MND; params.skillType = HEALING_MAGIC_SKILL; params.bonus = 1.0; resist = applyResistance(caster, target, spell, params); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/bowl_of_adoulinian_soup.lua
12
1563
----------------------------------------- -- ID: 5998 -- Item: Bowl of Adoulin Soup -- Food Effect: 180 Min, All Races ----------------------------------------- -- HP % 3 Cap 40 -- Vitality 3 -- Defense % 15 Cap 70 -- HP Healing 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5998); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 3); target:addMod(MOD_FOOD_HP_CAP, 40); target:addMod(MOD_VIT, 3); target:addMod(MOD_FOOD_DEFP, 15); target:addMod(MOD_FOOD_DEF_CAP, 70); target:addMod(MOD_HPHEAL, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 3); target:delMod(MOD_FOOD_HP_CAP, 40); target:delMod(MOD_VIT, 3); target:delMod(MOD_FOOD_DEFP, 15); target:delMod(MOD_FOOD_DEF_CAP, 70); target:delMod(MOD_HPHEAL, 6); end;
gpl-3.0
Goodzilam/Goodzila-bot_v1.5
libs/mimetype.lua
28
2924
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
petoju/awesome
tests/examples/wibox/awidget/prompt/keypress.lua
6
1312
--DOC_GEN_IMAGE --DOC_HIDE local parent = ... --DOC_NO_USAGE --DOC_HIDE local wibox = require( "wibox" ) --DOC_HIDE local awful = { prompt = require("awful.prompt"),--DOC_HIDE util = require("awful.util"),--DOC_HIDE screen = require("awful.screen")}--DOC_HIDE local beautiful = require( "beautiful" ) --DOC_HIDE local gfs = require("gears.filesystem") --DOC_HIDE local naughty = {} --DOC_HIDE local atextbox = wibox.widget.textbox() local notif = nil awful.prompt.run { prompt = "<b>Run: </b>", keypressed_callback = function(mod, key, cmd) --luacheck: no unused args if key == "Shift_L" then notif = naughty.notification { message = "Shift pressed" } end end, keyreleased_callback = function(mod, key, cmd) --luacheck: no unused args if notif then naughty.destroy(notif) notif = nil end end, textbox = atextbox, history_path = gfs.get_cache_dir() .. "/history", } parent:add( wibox.widget { --DOC_HIDE atextbox, --DOC_HIDE bg = beautiful.bg_normal, --DOC_HIDE widget = wibox.container.background --DOC_HIDE }) --DOC_HIDE
gpl-2.0
rudolfmleziva/AdministratorTeritorial
cocos2d/cocos/scripting/lua-bindings/auto/api/WavesTiles3D.lua
10
1459
-------------------------------- -- @module WavesTiles3D -- @extend TiledGrid3DAction -- @parent_module cc -------------------------------- -- waves amplitude rate -- @function [parent=#WavesTiles3D] getAmplitudeRate -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#WavesTiles3D] setAmplitude -- @param self -- @param #float amplitude -------------------------------- -- -- @function [parent=#WavesTiles3D] setAmplitudeRate -- @param self -- @param #float amplitudeRate -------------------------------- -- waves amplitude -- @function [parent=#WavesTiles3D] getAmplitude -- @param self -- @return float#float ret (return value: float) -------------------------------- -- creates the action with a number of waves, the waves amplitude, the grid size and the duration -- @function [parent=#WavesTiles3D] create -- @param self -- @param #float duration -- @param #size_table gridSize -- @param #unsigned int waves -- @param #float amplitude -- @return WavesTiles3D#WavesTiles3D ret (return value: cc.WavesTiles3D) -------------------------------- -- -- @function [parent=#WavesTiles3D] clone -- @param self -- @return WavesTiles3D#WavesTiles3D ret (return value: cc.WavesTiles3D) -------------------------------- -- -- @function [parent=#WavesTiles3D] update -- @param self -- @param #float time return nil
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Northern_San_dOria/npcs/Maloquedil.lua
3
3650
----------------------------------- -- Area: Northern San d'Oria -- NPC: Maloquedil -- Involved in Quest : Warding Vampires, Riding on the Clouds, Lure of the Wildcat (San d'Oria) -- !pos 35 0.1 60 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(SANDORIA,WARDING_VAMPIRES) ~= QUEST_AVAILABLE) then if (trade:hasItemQty(1018,2) and trade:getItemCount() == 2) then -- Trade Shaman Garlic player:startEvent(0x0017); end end if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 4) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_1",0); player:tradeComplete(); player:addKeyItem(SCOWLING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local warding = player:getQuestStatus(SANDORIA,WARDING_VAMPIRES); local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,7) == false) then player:startEvent(0x0327); elseif (warding == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then --Quest available for fame superior or equal to 3 player:startEvent(0x0018); elseif (warding == QUEST_ACCEPTED) then --Quest accepted, and he just tell me where to get item. player:startEvent(0x0016); elseif (warding == QUEST_COMPLETED) then --Since the quest is repeatable, he tells me where to find (again) the items. player:startEvent(0x0016); else player:startEvent(0x0015); 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 == 0x0018 and option == 1) then player:addQuest(SANDORIA,WARDING_VAMPIRES); elseif (csid == 0x0017) then player:tradeComplete(); player:addTitle(VAMPIRE_HUNTER_DMINUS); player:addGil(GIL_RATE*900); player:messageSpecial(GIL_OBTAINED,GIL_RATE*900); if (player:getQuestStatus(SANDORIA,WARDING_VAMPIRES) == QUEST_ACCEPTED) then player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,WARDING_VAMPIRES); else player:addFame(SANDORIA,5); end elseif (csid == 0x0327) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",7,true); end end;
gpl-3.0
openwrt-es/openwrt-luci
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_6rd.lua
72
2039
-- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, peeraddr, ip6addr, tunnelid, username, password local defaultroute, metric, ttl, mtu ipaddr = s:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" peeraddr = s:taboption("general", Value, "peeraddr", translate("Remote IPv4 address"), translate("This IPv4 address of the relay")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6prefix", translate("IPv6 prefix"), translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>")) ip6addr.rmempty = false ip6addr.datatype = "ip6addr" ip6prefixlen = s:taboption("general", Value, "ip6prefixlen", translate("IPv6 prefix length"), translate("The length of the IPv6 prefix in bits")) ip6prefixlen.placeholder = "16" ip6prefixlen.datatype = "range(0,128)" ip6prefixlen = s:taboption("general", Value, "ip4prefixlen", translate("IPv4 prefix length"), translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses.")) ip6prefixlen.placeholder = "0" ip6prefixlen.datatype = "range(0,32)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
apache-2.0
bmichalo/MoonGen
lua/include/proto/vxlan.lua
3
6680
------------------------------------------------------------------------ --- @file vxlan.lua --- @brief VXLAN utility. --- Utility functions for the vxlan_header struct --- defined in \ref headers.lua . \n --- Includes: --- - VXLAN constants --- - VXLAN header utility --- - Definition of VXLAN packets ------------------------------------------------------------------------ local ffi = require "ffi" local pkt = require "packet" require "headers" local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift local format = string.format --------------------------------------------------------------------------- ---- vxlan constants --------------------------------------------------------------------------- local vxlan = {} --------------------------------------------------------------------------- ---- vxlan header --------------------------------------------------------------------------- --- Module for vxlan_header struct (see \ref headers.lua). local vxlanHeader = {} vxlanHeader.__index = vxlanHeader --- Set the flags. --- @param int VXLAN header flags as 8 bit integer. function vxlanHeader:setFlags(int) int = int or 8 -- '00001000' self.flags = int end --- Retrieve the flags. --- @return Flags as 8 bit integer. function vxlanHeader:getFlags() return self.flags end --- Retrieve the flags. --- @return Flags as string. function vxlanHeader:getFlagsString() return format("0x%02x", self:getFlags()) end --- Set the first reserved field. --- @param int VXLAN header first reserved field as 24 bit integer. function vxlanHeader:setReserved(int) int = int or 0 -- X 3 2 1 -> 1 2 3 self.reserved[0] = rshift(band(int, 0xFF0000), 16) self.reserved[1] = rshift(band(int, 0x00FF00), 8) self.reserved[2] = band(int, 0x0000FF) end --- Retrieve the first reserved field. --- @return First reserved field as 24 bit integer. function vxlanHeader:getReserved() return bor(lshift(self.reserved[0], 16), bor(lshift(self.reserved[1], 8), self.reserved[2])) end --- Retrieve the first reserved field. --- @return First reserved field as string. function vxlanHeader:getReservedString() return format("0x%06x", self:getReserved()) end --- Set the VXLAN network identifier (VNI). --- @param int VXLAN header VNI as 24 bit integer. function vxlanHeader:setVNI(int) int = int or 0 -- X 3 2 1 -> 1 2 3 self.vni[0] = rshift(band(int, 0xFF0000), 16) self.vni[1] = rshift(band(int, 0x00FF00), 8) self.vni[2] = band(int, 0x0000FF) end --- Retrieve the VXLAN network identifier (VNI). --- @return VNI as 24 bit integer. function vxlanHeader:getVNI() return bor(lshift(self.vni[0], 16), bor(lshift(self.vni[1], 8), self.vni[2])) end --- Retrieve the VXLAN network identifier (VNI). --- @return VNI as string. function vxlanHeader:getVNIString() return format("0x%06x", self:getVNI()) end --- Set the second reserved field. --- @param int VXLAN header second reserved field as 8 bit integer. function vxlanHeader:setReserved2(int) int = int or 0 self.reserved2 = int end --- Retrieve the second reserved field. --- @return Second reserved field as 8 bit integer. function vxlanHeader:getReserved2() return self.reserved2 end --- Retrieve the second reserved field. --- @return Second reserved field as string. function vxlanHeader:getReserved2String() return format("0x%02x", self:getReserved2()) end --- Set all members of the ip header. --- Per default, all members are set to default values specified in the respective set function. --- Optional named arguments can be used to set a member to a user-provided value. --- @param args Table of named arguments. Available arguments: Flags, Reserved, VNI, Reserved2 --- @param pre prefix for namedArgs. Default 'vxlan'. --- @code --- fill() --- only default values --- fill{ vxlanFlags=1 } --- all members are set to default values with the exception of vxlanFlags --- @endcode function vxlanHeader:fill(args, pre) args = args or {} pre = pre or "vxlan" self:setFlags(args[pre .. "Flags"]) self:setReserved(args[pre .. "Reserved"]) self:setVNI(args[pre .. "VNI"]) self:setReserved2(args[pre .. "Reserved2"]) end --- Retrieve the values of all members. --- @param pre prefix for namedArgs. Default 'vxlan'. --- @return Table of named arguments. For a list of arguments see "See also". --- @see vxlanHeader:fill function vxlanHeader:get(pre) pre = pre or "vxlan" local args = {} args[pre .. "Flags"] = self:getFlags() args[pre .. "Reserved"] = self:getReserved() args[pre .. "VNI"] = self:getVNI() args[pre .. "Reserved2"] = self:getReserved2() return args end --- Retrieve the values of all members. --- @return Values in string format. function vxlanHeader:getString() return "VXLAN flags " .. self:getFlagsString() .. " res " .. self:getReservedString() .. " vni " .. self:getVNIString() .. " res " .. self:getReserved2String() end --- Resolve which header comes after this one (in a packet). --- For instance: in tcp/udp based on the ports. --- This function must exist and is only used when get/dump is executed on --- an unknown (mbuf not yet casted to e.g. tcpv6 packet) packet (mbuf) --- @return String next header (e.g. 'udp', 'icmp', nil) function vxlanHeader:resolveNextHeader() return 'eth' end --- Change the default values for namedArguments (for fill/get). --- This can be used to for instance calculate a length value based on the total packet length. --- See proto/ip4.setDefaultNamedArgs as an example. --- This function must exist and is only used by packet.fill. --- @param pre The prefix used for the namedArgs, e.g. 'ip4' --- @param namedArgs Table of named arguments (see See Also) --- @param nextHeader The header following after this header in a packet --- @param accumulatedLength The so far accumulated length for previous headers in a packet --- @return Table of namedArgs --- @see ip4Header:fill function vxlanHeader:setDefaultNamedArgs(pre, namedArgs, nextHeader, accumulatedLength) return namedArgs end ---------------------------------------------------------------------------------- ---- Packets ---------------------------------------------------------------------------------- -- the raw version (only the encapsulating headers, everything else is payload) pkt.getVxlanPacket = packetCreate("eth", "ip4", "udp", "vxlan") -- Vxlan packet with an inner Ethernet header pkt.getVxlanEthernetPacket = packetCreate("eth", "ip4", "udp", "vxlan", { "eth", "innerEth" }) ------------------------------------------------------------------------ ---- Metatypes ------------------------------------------------------------------------ ffi.metatype("struct vxlan_header", vxlanHeader) return vxlan
mit
rudolfmleziva/AdministratorTeritorial
cocos2d/cocos/scripting/lua-bindings/script/cocostudio/DeprecatedCocoStudioFunc.lua
39
3421
--tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --functions of GUIReader will be deprecated begin local GUIReaderDeprecated = { } function GUIReaderDeprecated.shareReader() deprecatedTip("GUIReader:shareReader","ccs.GUIReader:getInstance") return ccs.GUIReader:getInstance() end GUIReader.shareReader = GUIReaderDeprecated.shareReader function GUIReaderDeprecated.purgeGUIReader() deprecatedTip("GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end GUIReader.purgeGUIReader = GUIReaderDeprecated.purgeGUIReader --functions of GUIReader will be deprecated end --functions of SceneReader will be deprecated begin local SceneReaderDeprecated = { } function SceneReaderDeprecated.sharedSceneReader() deprecatedTip("SceneReader:sharedSceneReader","ccs.SceneReader:getInstance") return ccs.SceneReader:getInstance() end SceneReader.sharedSceneReader = SceneReaderDeprecated.sharedSceneReader function SceneReaderDeprecated.purgeSceneReader(self) deprecatedTip("SceneReader:purgeSceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end SceneReader.purgeSceneReader = SceneReaderDeprecated.purgeSceneReader --functions of SceneReader will be deprecated end --functions of ccs.GUIReader will be deprecated begin local CCSGUIReaderDeprecated = { } function CCSGUIReaderDeprecated.purgeGUIReader() deprecatedTip("ccs.GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end ccs.GUIReader.purgeGUIReader = CCSGUIReaderDeprecated.purgeGUIReader --functions of ccs.GUIReader will be deprecated end --functions of ccs.ActionManagerEx will be deprecated begin local CCSActionManagerExDeprecated = { } function CCSActionManagerExDeprecated.destroyActionManager() deprecatedTip("ccs.ActionManagerEx:destroyActionManager","ccs.ActionManagerEx:destroyInstance") return ccs.ActionManagerEx:destroyInstance() end ccs.ActionManagerEx.destroyActionManager = CCSActionManagerExDeprecated.destroyActionManager --functions of ccs.ActionManagerEx will be deprecated end --functions of ccs.SceneReader will be deprecated begin local CCSSceneReaderDeprecated = { } function CCSSceneReaderDeprecated.destroySceneReader(self) deprecatedTip("ccs.SceneReader:destroySceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end ccs.SceneReader.destroySceneReader = CCSSceneReaderDeprecated.destroySceneReader --functions of ccs.SceneReader will be deprecated end --functions of CCArmatureDataManager will be deprecated begin local CCArmatureDataManagerDeprecated = { } function CCArmatureDataManagerDeprecated.sharedArmatureDataManager() deprecatedTip("CCArmatureDataManager:sharedArmatureDataManager","ccs.ArmatureDataManager:getInstance") return ccs.ArmatureDataManager:getInstance() end CCArmatureDataManager.sharedArmatureDataManager = CCArmatureDataManagerDeprecated.sharedArmatureDataManager function CCArmatureDataManagerDeprecated.purge() deprecatedTip("CCArmatureDataManager:purge","ccs.ArmatureDataManager:destoryInstance") return ccs.ArmatureDataManager:destoryInstance() end CCArmatureDataManager.purge = CCArmatureDataManagerDeprecated.purge --functions of CCArmatureDataManager will be deprecated end
gpl-3.0
petoju/awesome
spec/awful/screen_spec.lua
5
4832
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2016 Uli Schlachter --------------------------------------------------------------------------- local fake_screens = {} _G.screen = setmetatable({ connect_signal = function() end, set_index_miss_handler = function() end, set_newindex_miss_handler = function() end, }, { __call = function(_, _, prev) if not prev then return fake_screens[1] end for k, v in ipairs(fake_screens) do if v == prev then return fake_screens[k+1] end end end, __index = function(_, arg) if arg == "primary" then return fake_screens[1] end if type(arg) == "number" then return fake_screens[arg] end for _, v in ipairs(fake_screens) do if v == arg then return arg end end end, __newindex = error, }) local ascreen = require("awful.screen") describe("awful.screen", function() describe("two screens each 1x1", function() before_each(function() fake_screens = { { geometry = { x = 0, y = 0, width = 1, height = 1 }, index = 1 }, { geometry = { x = 0, y = 1, width = 1, height = 1 }, index = 2 }, } end) it("get_square_distance", function() assert.is.equal(0, ascreen.object.get_square_distance(fake_screens[1], 0, 0)) assert.is.equal(1, ascreen.object.get_square_distance(fake_screens[1], 0, 1)) assert.is.equal(2, ascreen.object.get_square_distance(fake_screens[1], 1, 1)) assert.is.equal(5, ascreen.object.get_square_distance(fake_screens[1], 2, 1)) assert.is.equal(2, ascreen.object.get_square_distance(fake_screens[1], -1, 1)) assert.is.equal(1, ascreen.object.get_square_distance(fake_screens[2], 0, 0)) assert.is.equal(0, ascreen.object.get_square_distance(fake_screens[2], 0, 1)) assert.is.equal(1, ascreen.object.get_square_distance(fake_screens[2], 1, 1)) assert.is.equal(4, ascreen.object.get_square_distance(fake_screens[2], 2, 1)) assert.is.equal(1, ascreen.object.get_square_distance(fake_screens[2], -1, 1)) end) it("getbycoord", function() -- Some exact matches assert.is.equal(1, ascreen.getbycoord(0, 0)) assert.is.equal(2, ascreen.getbycoord(0, 1)) -- Some "find the closest screen"-cases assert.is.equal(1, ascreen.getbycoord(-1, -1)) assert.is.equal(1, ascreen.getbycoord(-1, 0)) assert.is.equal(2, ascreen.getbycoord(-1, 1)) assert.is.equal(2, ascreen.getbycoord(-1, 2)) assert.is.equal(2, ascreen.getbycoord(1, 1)) end) end) describe("get_next_in_direction", function() before_each(function() fake_screens = { { geometry = { x = 0, y = 0, width = 1, height = 1 }, index = 1 }, { geometry = { x = 1, y = 0, width = 1, height = 1 }, index = 2 }, { geometry = { x = 0, y = 1, width = 1, height = 1 }, index = 3 }, { geometry = { x = 1, y = 1, width = 1, height = 1 }, index = 4 }, } end) it("gets screens to the left", function() assert.is.equal(fake_screens[1], ascreen.object.get_next_in_direction(fake_screens[2], "left")) end) it("gets screens to the right", function() assert.is.equal(fake_screens[2], ascreen.object.get_next_in_direction(fake_screens[1], "right")) end) it("gets screens to the top", function() assert.is.equal(fake_screens[2], ascreen.object.get_next_in_direction(fake_screens[4], "up")) end) it("gets screens to the bottom", function() assert.is.equal(fake_screens[4], ascreen.object.get_next_in_direction(fake_screens[2], "down")) end) it("gets no screens if none exist in the direction", function() assert.is_nil(ascreen.object.get_next_in_direction(fake_screens[2], "up")) assert.is_nil(ascreen.object.get_next_in_direction(fake_screens[4], "down")) assert.is_nil(ascreen.object.get_next_in_direction(fake_screens[2], "right")) assert.is_nil(ascreen.object.get_next_in_direction(fake_screens[1], "left")) end) end) describe("no screens", function() before_each(function() fake_screens = {} end) it("getbycoord", function() assert.is_nil(ascreen.getbycoord(0, 0)) end) end) end) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
blackzw/openwrt_sdk_dev1
staging_dir/target-mips_r2_uClibc-0.9.33.2/root-ar71xx/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
gpl-2.0
Afforess/Factorio-Stdlib
stdlib/misc/logger.lua
1
5802
--- For logging debug information to files. -- @module Misc.Logger -- @usage -- local Logger = require('__stdlib__/stdlib/misc/logger') -- -- or to create a new logger directly: -- local Log = require('__stdlib__/stdlib/misc/logger').new() -- -- log files are saved to script-output/modname/log.log by default local Logger = { __class = 'Logger', _loggers = {}, __call = function(self, ...) return self.get(...) end, __index = require('__stdlib__/stdlib/core') } setmetatable(Logger, Logger) local table = require('__stdlib__/stdlib/utils/table') -- Set on the individual log object, either logs a message or writes immediatly if nil. local _Log_mt = { __call = function(self, msg) if msg then return self, self.log(msg) else return self, self.write() end end } local format = string.format --- Get a saved log or create a new one if there is no saved log. function Logger.get(...) local log_name = (...) or 'log' return Logger._loggers[log_name] or Logger.new(...) end --- Creates a new logger object. -- In debug mode, the logger writes to file immediately, otherwise the logger buffers the lines. -- <p>The logger flushes the logged messages every 60 seconds since the last message. -- <p>A table of @{options} may be specified when creating a logger. -- @usage --Log = Logger.new() --Log("this msg will be logged in /script-output/YourModName/log.log!") -- -- Immediately Write everything buffered in the log file -- Log() -- -- @usage --Log = Logger.new('test', true) --Log("this msg will be logged and written immediately in /script-output/YourModName/test.log!") -- -- @usage --Log = Logger.new('cool_mod_name', 'test', true, { file_extension = data }) --Log("this msg will be logged and written immediately in /script-output/YourModName/test.data!") -- -- @tparam[opt='log'] string log_name the name of the logger -- @tparam[opt=false] boolean debug_mode toggles the debug state of logger -- @tparam[opt={...}] options options a table with optional arguments -- @return (<span class="types">@{Logger}</span>) the logger instance function Logger.new(log_name, debug_mode, options) local mod_name = script and script.mod_name or 'Data' log_name = log_name or 'log' Logger._loggers[log_name] = nil options = options or {} local Log = { __class = 'Log', mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false, } --- -- Used in the @{new} function for logging game ticks, specifying logfile extension, or forcing the logs to append to the end of the logfile. -- @tfield[opt=false] boolean log_ticks whether to include the game tick timestamp in the logs -- @tfield[opt="log"] string file_extension a string that overrides the default logfile extension -- @tfield[opt=false] boolean force_append if true, every new message appends to the current logfile instead of creating a new one -- @table Log.options Log.options = { log_ticks = options.log_ticks or false, file_extension = options.file_extension or 'log', force_append = options.force_append or false } Log.file_name = mod_name .. '/' .. log_name .. (log_name:find('%.') and '' or '.' .. Log.options.file_extension) Log.ever_written = Log.options.force_append --- Logs a message. -- @tparam string|table msg the message to log. @{table}s will be dumped using [serpent](https://github.com/pkulchenko/serpent) -- which is included in the official Factorio Lualib -- @return (<span class="types">@{Logger}</span>) the logger instance -- @see https://forums.factorio.com/viewtopic.php?f=25&t=23844 Debugging utilities built in to Factorio function Log.log(msg) if type(msg) ~= 'string' then msg = serpent.block(msg, { comment = false, nocode = true, sparse = true }) end if _G.game then local tick = game.tick local floor = math.floor local time_s = floor(tick / 60) local time_minutes = floor(time_s / 60) local time_hours = floor(time_minutes / 60) if Log.options.log_ticks then table.insert(Log.buffer, format('%02d:%02d:%02d.%02d: %s\n', time_hours, time_minutes % 60, time_s % 60, tick - time_s * 60, msg)) else table.insert(Log.buffer, format('%02d:%02d:%02d: %s\n', time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Log.debug_mode or (tick - Log.last_written) > 3600) then return Log.write() end else if _G.script then --buffer when a save is loaded but _G.game isn't available if Log.options.log_ticks then table.insert(Log.buffer, format('00:00:00:00: %s\n', msg)) else table.insert(Log.buffer, format('00:00:00: %s\n', msg)) end else --log in data stage log(format('%s/%s: %s', Log.mod_name, Log.log_name, msg)) end end return Log end --- Writes out all buffered messages immediately. -- @return (<span class="types">@{Logger}</span>) the logger instance function Log.write() if _G.game and table.size(Log.buffer) > 0 then Log.last_written = game.tick game.write_file(Log.file_name, table.concat(Log.buffer), Log.ever_written) Log.buffer = {} Log.ever_written = true end return Log end setmetatable(Log, _Log_mt) Logger._loggers[log_name] = Log return Log end return Logger
isc
mzguanglin/LuCI
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-codec.lua
80
2172
--[[ 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$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true codec_a_mu = module:option(ListValue, "codec_a_mu", "A-law and Mulaw direct Coder/Decoder", "") codec_a_mu:value("yes", "Load") codec_a_mu:value("no", "Do Not Load") codec_a_mu:value("auto", "Load as Required") codec_a_mu.rmempty = true codec_adpcm = module:option(ListValue, "codec_adpcm", "Adaptive Differential PCM Coder/Decoder", "") codec_adpcm:value("yes", "Load") codec_adpcm:value("no", "Do Not Load") codec_adpcm:value("auto", "Load as Required") codec_adpcm.rmempty = true codec_alaw = module:option(ListValue, "codec_alaw", "A-law Coder/Decoder", "") codec_alaw:value("yes", "Load") codec_alaw:value("no", "Do Not Load") codec_alaw:value("auto", "Load as Required") codec_alaw.rmempty = true codec_g726 = module:option(ListValue, "codec_g726", "ITU G.726-32kbps G726 Transcoder", "") codec_g726:value("yes", "Load") codec_g726:value("no", "Do Not Load") codec_g726:value("auto", "Load as Required") codec_g726.rmempty = true codec_gsm = module:option(ListValue, "codec_gsm", "GSM/PCM16 (signed linear) Codec Translation", "") codec_gsm:value("yes", "Load") codec_gsm:value("no", "Do Not Load") codec_gsm:value("auto", "Load as Required") codec_gsm.rmempty = true codec_speex = module:option(ListValue, "codec_speex", "Speex/PCM16 (signed linear) Codec Translator", "") codec_speex:value("yes", "Load") codec_speex:value("no", "Do Not Load") codec_speex:value("auto", "Load as Required") codec_speex.rmempty = true codec_ulaw = module:option(ListValue, "codec_ulaw", "Mu-law Coder/Decoder", "") codec_ulaw:value("yes", "Load") codec_ulaw:value("no", "Do Not Load") codec_ulaw:value("auto", "Load as Required") codec_ulaw.rmempty = true return cbimap
apache-2.0
RebootRevival/FFXI_Test
scripts/globals/spells/frost.lua
1
2020
----------------------------------------- -- Spell: Frost -- Deals ice damage that lowers an enemy's agility 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_BURN) ~= nil) then spell:setMsg(75); -- no effect else local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = 36; params.bonus = 0; params.effect = nil; resist = applyResistance(caster, target, spell, params); if (resist <= 0.125) then spell:setMsg(85); else if (target:getStatusEffect(EFFECT_CHOKE) ~= nil) then target:delStatusEffect(EFFECT_CHOKE); end; local sINT = caster:getStat(MOD_INT); local DOT = getElementalDebuffDOT(sINT); local effect = target:getStatusEffect(EFFECT_FROST); 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_FROST); end; spell:setMsg(237); local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist); target:addStatusEffect(EFFECT_FROST,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE); end; end; end; return EFFECT_FROST; end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Rabao/npcs/Guinavie.lua
5
1719
----------------------------------- -- Area: Rabao -- NPC: Guinavie -- Chocobo Vendor ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/chocobo"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 20) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); player:startEvent(0x004F,price,gil); else player:startEvent(0x0050); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x004F and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,duration,true); player:setPos(420,8,360,0x40,0x7D); end end end;
gpl-3.0
chen0031/sysdig
userspace/sysdig/chisels/subsecoffset.lua
18
4462
--[[ Copyright (C) 2013-2014 Draios inc. Copyright (C) 2015 Brendan Gregg. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 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. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] -- Chisel description description = "This visualizes the subsecond offset time of system call execution. This allows repetitive patterns to be identified, which are lost when averaging at a one second granularity. The Y axis (vertical) shows the passage of time. The X axis (horizontal) shows the passage of time within whole or fractions of a second. By default, the X axis range is 1000 milliseconds; this can be specified as an argument (try 100). Each bucket of the heat map, or spectrogram, is shown as a colored rectangle. The color shows how many syscalls fell into that time and subsecond offset range. It can be black (no calls), green (tens of calls/s), yellow (hundreds of calls/s) or red (Thousands of calls/s). Use this chisel in conjunction with filters to visualize latencies for certain processes, types of I/O activity, file systems, etc." short_description = "Visualize subsecond offset execution time." category = "CPU Usage" -- Chisel argument list args = { { name = "refresh_time", description = "chart refresh time in milliseconds", argtype = "int", optional = true }, } require "common" terminal = require "ansiterminal" terminal.enable_color(true) refresh_time = 1000 * 1000 * 1000 refresh_per_sec = 1 * 1000 * 1000 * 1000 / refresh_time max_label_len = 0 frequencies = {} colpalette = {22, 28, 64, 34, 2, 76, 46, 118, 154, 191, 227, 226, 11, 220, 209, 208, 202, 197, 9, 1} -- Argument initialization function on_set_arg(name, val) if name == "refresh_time" then refresh_time = parse_numeric_input(val, name) * 1 * 1000 * 1000 refresh_per_sec = 1 * 1000 * 1000 * 1000 / refresh_time return true end return false end -- Initialization callback function on_init() is_tty = sysdig.is_tty() if not is_tty then print("This chisel only works on ANSI terminals. Aborting.") return false end tinfo = sysdig.get_terminal_info() w = tinfo.width h = tinfo.height max_label_len = string.len("|" .. (0.9 * refresh_time / 10000000) .. "ms") -- trace syscall entry chisel.set_filter("evt.dir=>") rawtime = chisel.request_field("evt.rawtime") terminal.hidecursor() print("Tracing syscalls... red (hot) == high frequency <-> green == low frequency.\n") return true end -- Final chisel initialization function on_capture_start() chisel.set_interval_ns(refresh_time) return true end -- Event parsing callback function on_event() local subsec = evt.field(rawtime) -- subsec is normalized to terminal column location subsec = math.floor((((subsec * 1000 / refresh_time) % 1000) / 1000) * w) if frequencies[subsec] == nil then frequencies[subsec] = 1 else frequencies[subsec] = frequencies[subsec] + 1 end return true end function mkcol(n) local col = math.floor(math.log10(n * refresh_per_sec + 1) / math.log10(1.6)) if col < 1 then col = 1 end if col > #colpalette then col = #colpalette end return colpalette[col] end -- Periodic timeout callback function on_interval(ts_s, ts_ns, delta) terminal.moveup(1) for x = 1, w do local fr = frequencies[x] if fr == nil or fr == 0 then terminal.setbgcol(0) else terminal.setbgcol(mkcol(fr)) end io.write(" ") end io.write(terminal.reset .. "\n") local x = 0 while true do if x >= w then break end local curtime = math.floor(x * 10 / w) local prevtime = math.floor((x - 1) * 10 / w) if curtime ~= prevtime then if (x <= w - max_label_len) then local tstr = "|" .. (math.floor(10 * x / w) * refresh_time / 10000000) .. "ms" io.write(tstr) x = x + string.len(tstr) else io.write(" ") x = x + 1 end else io.write(" ") x = x + 1 end end io.write("\n") frequencies = {} return true end function on_capture_end(ts_s, ts_ns, delta) if is_tty then print(terminal.reset) terminal.showcursor() end return true end
gpl-2.0
rw/flatbuffers
tests/namespace_test/NamespaceC/TableInC.lua
12
1513
-- automatically generated by the FlatBuffers compiler, do not modify -- namespace: NamespaceC local flatbuffers = require('flatbuffers') local TableInC = {} -- the module local TableInC_mt = {} -- the class metatable function TableInC.New() local o = {} setmetatable(o, {__index = TableInC_mt}) return o end function TableInC.GetRootAsTableInC(buf, offset) local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) local o = TableInC.New() o:Init(buf, n + offset) return o end function TableInC_mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function TableInC_mt:ReferToA1() local o = self.view:Offset(4) if o ~= 0 then local x = self.view:Indirect(o + self.view.pos) local obj = require('NamespaceA.TableInFirstNS').New() obj:Init(self.view.bytes, x) return obj end end function TableInC_mt:ReferToA2() local o = self.view:Offset(6) if o ~= 0 then local x = self.view:Indirect(o + self.view.pos) local obj = require('NamespaceA.SecondTableInA').New() obj:Init(self.view.bytes, x) return obj end end function TableInC.Start(builder) builder:StartObject(2) end function TableInC.AddReferToA1(builder, referToA1) builder:PrependUOffsetTRelativeSlot(0, referToA1, 0) end function TableInC.AddReferToA2(builder, referToA2) builder:PrependUOffsetTRelativeSlot(1, referToA2, 0) end function TableInC.End(builder) return builder:EndObject() end return TableInC -- return the module
apache-2.0
RebootRevival/FFXI_Test
scripts/globals/abilities/pets/earthen_fury.lua
34
1118
--------------------------------------------------- -- Earthen Fury --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) local level = player:getMainLvl() * 2; if(player:getMP()<level) then return 87,0; end return 0,0; end; function onPetAbility(target, pet, skill, master) local dINT = math.floor(pet:getStat(MOD_INT) - target:getStat(MOD_INT)); local level = pet:getMainLvl() local damage = 48 + (level * 8); damage = damage + (dINT * 1.5); damage = MobMagicalMove(pet,target,skill,damage,ELE_EARTH,1,TP_NO_EFFECT,0); damage = mobAddBonuses(pet, nil, target, damage.dmg, ELE_EARTH); damage = AvatarFinalAdjustments(damage,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1); master:setMP(0); target:delHP(damage); target:updateEnmityFromDamage(pet,damage); return damage; end
gpl-3.0
GlennS/card-draft
game/dota_addons/card-draft/scripts/vscripts/inputs.lua
1
4528
-- TODO: we'd prefer not to have to distribute the npc_heroes.txt and npc_abilities.txt files ourselves - is there some better way? function loadHeroes() -- Returns a list of all the heroes in Dota 2. local heroes = LoadKeyValues("scripts/data/npc_heroes.txt") -- See Unavailable Heroes in http://dota2.gamepedia.com/Game_modes#Ability_Draft forbiddenHeroes = { "npc_dota_hero_base", "Version", "npc_dota_hero_beastmaster", "npc_dota_hero_chen", "npc_dota_hero_doom_bringer", "npc_dota_hero_earth_spirit", "npc_dota_hero_ember_spirit", "npc_dota_hero_keeper_of_the_light", "npc_dota_hero_morphling", "npc_dota_hero_phoenix", "npc_dota_hero_puck", "npc_dota_hero_rubick", "npc_dota_hero_nevermore", "npc_dota_hero_spectre", "npc_dota_hero_shadow_demon", "npc_dota_hero_techies", "npc_dota_hero_templar_assassin", "npc_dota_hero_shredder", "npc_dota_hero_troll_warlord", "npc_dota_hero_tusk", "npc_dota_hero_invoker", "npc_dota_hero_abyssal_underlord", "npc_dota_hero_lone_druid", "npc_dota_hero_ogre_magi", "npc_dota_hero_meepo", "npc_dota_hero_elder_titan" } local heroNames = {} for name, _ in pairs(heroes) do local ok = true for i, badName in ipairs(forbiddenHeroes) do if name == badName then ok = false break end end if ok then table.insert(heroNames, name) end end return heroNames end function loadAbilities(heroNames) -- Returns a list of all the abilities in Dota 2, divided up by whether they are an ultimate or normal skill. local normal = {} local ultimates = {} local abilities = LoadKeyValues("scripts/data/npc_abilities.txt") local heroForAbility = {} for name, ability in pairs(abilities) do if isPickableAbility(name, ability) then local hero = getHeroForAbility(name, heroNames) if hero ~= nil then heroForAbility[name] = hero if (ability["AbilityType"] == "DOTA_ABILITY_TYPE_ULTIMATE") then table.insert(ultimates, name) else table.insert(normal, name) end end end end return {normal = normal, ultimates = ultimates, heroForAbility = heroForAbility} end function isPickableAbility(name, ability) local forbiddenBehaviours = {"DOTA_ABILITY_BEHAVIOR_HIDDEN", "DOTA_ABILITY_BEHAVIOR_NOT_LEARNABLE", "DOTA_ABILITY_BEHAVIOR_ITEM"} local forbiddenNames = { "Version", "ability_base", -- Brewmaster primal split elemental abilities "brewmaster_earth_hurl_boulder", "brewmaster_earth_spell_immunity", "brewmaster_earth_pulverize", "brewmaster_storm_dispel_magic", "brewmaster_storm_cyclone", "brewmaster_storm_wind_walk", "brewmaster_fire_permanent_immolation", -- Lycan's wolves' abilities "lycan_summon_wolves_critical_strike", "lycan_summon_wolves_invisibility", -- Warlock's golem's abilities "warlock_golem_flaming_fists", "warlock_golem_permanent_immolation", -- Transformed dragon knight ability "dragon_knight_frost_breath", -- This slipts though because it's prefixed by the hero name 'centaur'. "centaur_khan_war_stomp", -- Needs to be paired with ancient_apparaition_ice_blast_release - I haven't been able to make this work well. "ancient_apparition_ice_blast" } for _, forbidden in pairs(forbiddenNames) do if (name == forbidden) then return false end end if ability["MaxLevel"] == "1" then return false end local behaviour = ability["AbilityBehavior"] if (behaviour == nil) then return true end for _, forbidden in pairs(forbiddenBehaviours) do if string.find(behaviour, forbidden) then return false end end return true end local heroNamePrefix = "npc_dota_hero_" local heroNamePrefixLength = string.len(heroNamePrefix) -- Tests whether an ability belongs to a hero. -- Does this by checking whether it contains that hero's name. function getHeroForAbility(abilityName, heroNames) for _, heroName in ipairs(heroNames) do heroName = string.sub(heroName, heroNamePrefixLength + 1) if string.starts(abilityName, heroName) then return heroName end end return nil end -- See http://lua-users.org/wiki/StringRecipes function string.starts(str, start) return string.sub( str, 1, string.len(start) ) == start end
mit
jpmac26/PGE-Project
Content/configs/SMBX/script/npcs/huge_piranha_plant_turned.lua
1
5009
------------------------------------------------------------------------------------- -- Trace of Huge Piranha Plant NPC of SMBX Engine ------------------------------------------------------------------------------------- -- AI1:0 AI2:0 AI3:0 AI4:0 AI5:0 --INITIAL -- AI1:71 AI2:4 AI3:0 AI4:0 AI5:0 --HIDDEN -- AI1:74 AI2:4 AI3:0 AI4:0 AI5:0 -- AI1:0 AI2:1 AI3:0 AI4:0 AI5:0 -- SHOWING UP -- AI1:84 AI2:1 AI3:0 AI4:0 AI5:0 -- AI1:0 AI2:2 AI3:0 AI4:0 AI5:0 --Shown, wait something and breath air... -- AI1:0 AI2:2 AI3:0 AI4:0 AI5:0 -- AI1:50 AI2:2 AI3:10 AI4:0 AI5:0 -- OUCH! That was painful! -- AI1:0 AI2:3 AI3:9 AI4:0 AI5:0 -- Hidding away! -- AI1:84 AI2:3 AI3:0 AI4:0 AI5:0 -- AI1:0 AI2:4 AI3:0 AI4:0 AI5:0 --Wait in hidden -- AI1:74 AI2:4 AI3:0 AI4:0 AI5:0 -- AI1:0 AI2:1 AI3:0 AI4:0 AI5:0 -- Showing again! -- AI1:84 AI2:1 AI3:0 AI4:0 AI5:0 -- AI1:0 AI2:2 AI3:0 AI4:0 AI5:0 --Shown, wait something and breath air... ------------------------------------------------------------------------------------- class 'huge_piranha_plant_turned' local AI_SHOWING_UP = 0 local AI_SHOWING_IDLE = 1 local AI_HIDING_DOWN = 2 local AI_HIDING_IDLE = 3 function huge_piranha_plant_turned:hideSprite() self.npc_obj:setSpriteWarp(1.0, 1, true) end function huge_piranha_plant_turned:updateWarp() self.npc_obj:setSpriteWarp(1.0-(math.abs(self.npc_obj.top-self.npc_obj.bottom)/self.def_height), 1, true) end function huge_piranha_plant_turned:initProps() -- Animation properties -- Top position (reset size to initial) self.npc_obj.bottom = self.def_bottom self.npc_obj.top = self.def_top self.npc_obj.bottom = self.npc_obj.top -- Currents self.cur_mode = AI_HIDING_IDLE -- if physics are paused, than iterations and collisions are disabled. Paused objects will NOT be detected by other self.npc_obj.paused_physics = true -- FOR AI_SHOWING_UP self.cur_showingUpTicks = 0 -- FOR AI_SHOWING_IDLE -- self.cur_showingIdleTicks = 0 self.cur_keep_showing = true -- FOR AI_HIDING_DOWN self.cur_hidingDownTicks = 0 -- FOR AI_HIDING_IDLE self.cur_hidingIdleTicks = smbx_utils.ticksToTime(70) -- Initial wait time is 70 ticks! self:updateWarp() end function huge_piranha_plant_turned:__init(npc_obj) self.npc_obj = npc_obj -- Config self.def_top = npc_obj.top self.def_height = npc_obj.height self.def_bottom = npc_obj.bottom self.speed = 1.5 -- Detector of player -- self.plr_detector = self.npc_obj:installInAreaDetector(-44, -600, 44, 600, {4}) -- FOR AI_SHOWING_UP self.def_showingUpTicks = smbx_utils.ticksToTime(self.npc_obj.height/self.speed) -- FOR AI_SHOWING_IDLE -- self.def_showingIdleTicks = smbx_utils.ticksToTime(50) -- FOR AI_HIDING_DOWN self.def_hidingDownTicks = smbx_utils.ticksToTime(self.npc_obj.height/self.speed) -- FOR AI_HIDING_IDLE self.def_hidingIdleTicks = smbx_utils.ticksToTime(85) npc_obj.gravity = 0 self:initProps() end function huge_piranha_plant_turned:onActivated() self:initProps() end function huge_piranha_plant_turned:onLoop(tickTime) if(self.cur_mode == AI_SHOWING_UP)then if(self.def_showingUpTicks > self.cur_showingUpTicks)then self.cur_showingUpTicks = self.cur_showingUpTicks + tickTime self.npc_obj.bottom = self.npc_obj.bottom + smbx_utils.speedConv(self.speed, tickTime) self:updateWarp() else self.cur_mode = AI_SHOWING_IDLE self.npc_obj.top = self.def_top self.npc_obj:resetSpriteWarp() self.cur_showingUpTicks = 0 self.cur_keep_showing = true end elseif(self.cur_mode == AI_SHOWING_IDLE)then if(not self.cur_keep_showing)then self.cur_mode = AI_HIDING_DOWN -- self.cur_showingIdleTicks = 0 end elseif(self.cur_mode == AI_HIDING_DOWN)then if(self.def_hidingDownTicks > self.cur_hidingDownTicks)then self.cur_hidingDownTicks = self.cur_hidingDownTicks + tickTime self.npc_obj.bottom = self.npc_obj.bottom - smbx_utils.speedConv(self.speed, tickTime) self:updateWarp() else self.cur_mode = AI_HIDING_IDLE self:hideSprite() self.cur_hidingDownTicks = 0 self.npc_obj.paused_physics=true end elseif(self.cur_mode == AI_HIDING_IDLE)then if(self.def_hidingIdleTicks >= self.cur_hidingIdleTicks)then self.cur_hidingIdleTicks = self.cur_hidingIdleTicks + tickTime else self.cur_mode = AI_SHOWING_UP self.npc_obj.paused_physics = false self.cur_hidingIdleTicks = 0 end end end function huge_piranha_plant_turned:onHarm(harmEvent) self.cur_keep_showing = false end return huge_piranha_plant_turned
gpl-3.0
naader1380/Dragon1
plugins/linkpv.lua
66
30275
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, '') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, '') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'linkpv' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, 'Group link for ('..string.gsub(msg.to.print_name, "_", " ")..'):\n'..group_link) end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 50 then return "Wrong number,range is [2-50]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { usage = { "linkpv: Send Link In Private Chat.", }, patterns = { "^([Ll]inkpv)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Port_Bastok/npcs/Fo_Mocorho.lua
59
1038
----------------------------------- -- Area: Port Bastok -- NPC: Fo Mocorho -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0074,0,0,0,0,0,0,0,VanadielTime()); 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
RebootRevival/FFXI_Test
scripts/globals/mobskills/lethe_arrows.lua
29
1094
--------------------------------------------- -- Lethe Arrows -- -- Description: Deals a ranged attack to target. Additional effect: Knockback, Bind, and Amnesia -- Type: Ranged -- Utsusemi/Blink absorb: Ignores Utsusemi -- Range: Unknown -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_BIND; MobStatusEffectMove(mob, target, typeEffect, 1, 0, 120); typeEffect = EFFECT_AMNESIA; MobStatusEffectMove(mob, target, typeEffect, 1, 0, 120); local numhits = 1; local accmod = 3; local dmgmod = 4; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
MRAHS/SuperGpSupporter
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Port_Bastok/npcs/Evi.lua
17
2244
----------------------------------- -- Area: Port Bastok -- NPC: Evi -- Starts Quests: Past Perfect (100%) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT); if (PastPerfect == QUEST_ACCEPTED and player:hasKeyItem(TATTERED_MISSION_ORDERS)) then player:startEvent(0x0083); elseif (player:getFameLevel(BASTOK) >= 2 and player:getVar("PastPerfectVar") == 2) then player:startEvent(0x0082); elseif (PastPerfect == QUEST_AVAILABLE) then player:startEvent(0x0068); else player:startEvent(0x0015); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0068 and player:getVar("PastPerfectVar") == 0) then player:setVar("PastPerfectVar",1); elseif (csid == 0x0082) then player:addQuest(BASTOK,PAST_PERFECT); elseif (csid == 0x0083) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12560); else if (player:addItem(12560)) then player:delKeyItem(TATTERED_MISSION_ORDERS); player:setVar("PastPerfectVar",0); player:messageSpecial(ITEM_OBTAINED,12560); player:addFame(BASTOK,110); player:completeQuest(BASTOK,PAST_PERFECT); end end end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/bowl_of_zesty_zoni.lua
12
2081
----------------------------------------- -- ID: 5619 -- Item: Bowl of Zesti Zoni -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- HP 12 -- MP 12 -- Strength 2 -- Dexterity 2 -- Vitality 2 -- Agility 2 -- Accuracy +2 -- Ranged Accuracy +2 -- Attack +2 -- Ranged Attack +2 -- Evasion +2 -- MP Recovered while healing 1 -- HP Recovered while healing 1 ----------------------------------------- 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,14400,5619); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 12); target:addMod(MOD_MP, 12); target:addMod(MOD_STR, 2); target:addMod(MOD_DEX, 2); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, 2); target:addMod(MOD_ACC, 2); target:addMod(MOD_RACC, 2); target:addMod(MOD_ATT, 2); target:addMod(MOD_RATT, 2); target:addMod(MOD_EVA, 2); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 12); target:delMod(MOD_MP, 12); target:delMod(MOD_STR, 2); target:delMod(MOD_DEX, 2); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, 2); target:delMod(MOD_ACC, 2); target:delMod(MOD_RACC, 2); target:delMod(MOD_ATT, 2); target:delMod(MOD_RATT, 2); target:delMod(MOD_EVA, 2); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
hfjgjfg/jjjn
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
petoju/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
RebootRevival/FFXI_Test
scripts/globals/spells/addle.lua
1
1670
----------------------------------------- -- Spell: Addle -- Increases the casting time of the target -- Exact formula is unknown. -- -- Raw Value is said to be 30% -- It is said to increase to 50% w/ Saboteur ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND)); -- Power: Cast Time Modifier local power = 30; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then power = 50; end -- Sub Power: Magic Accuracy Modifier local targetMagicAccuracy = target:getMod(MOD_MACC); local subPower = math.floor( targetMagicAccuracy * (power / 100) ); --Duration, including resistance. local duration = 180; local params = {}; params.diff = nil; params.attribute = MOD_MND; params.skillType = 35; params.bonus = 0; params.effect = EFFECT_ADDLE; duration = duration * applyResistanceEffect(caster, target, spell, params); if (duration >= 60) then -- Do it! if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; caster:delStatusEffect(EFFECT_SABOTEUR); end if (target:addStatusEffect(EFFECT_ADDLE, power, 0, duration, 0, subPower)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end return EFFECT_ADDLE; end;
gpl-3.0
mzguanglin/LuCI
applications/luci-ntpc/luasrc/model/cbi/ntpc/ntpc.lua
11
1310
--[[ 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$ ]]-- m = Map("ntpclient", translate("Time Synchronisation"), translate("Synchronizes the system time")) s = m:section(TypedSection, "ntpclient", translate("General")) s.anonymous = true s.addremove = false s:option(DummyValue, "_time", translate("Current system time")).value = os.date("%c") s:option(Value, "interval", translate("Update interval (in seconds)")).rmempty = true s:option(Value, "count", translate("Count of time measurements"), translate("empty = infinite")).rmempty = true s2 = m:section(TypedSection, "ntpdrift", translate("Clock Adjustment")) s2.anonymous = true s2.addremove = false s2:option(Value, "freq", translate("Offset frequency")).rmempty = true s3 = m:section(TypedSection, "ntpserver", translate("Time Servers")) s3.anonymous = true s3.addremove = true s3.template = "cbi/tblsection" s3:option(Value, "hostname", translate("Hostname")) s3:option(Value, "port", translate("Port")).rmempty = true return m
apache-2.0
mujiansu/arangodb
3rdParty/V8-4.3.61/tools/gcmole/gcmole.lua
26
13876
-- Copyright 2011 the V8 project authors. All rights reserved. -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are -- met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above -- copyright notice, this list of conditions and the following -- disclaimer in the documentation and/or other materials provided -- with the distribution. -- * Neither the name of Google Inc. nor the names of its -- contributors may be used to endorse or promote products derived -- from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- This is main driver for gcmole tool. See README for more details. -- Usage: CLANG_BIN=clang-bin-dir lua tools/gcmole/gcmole.lua [arm|ia32|x64] local DIR = arg[0]:match("^(.+)/[^/]+$") local FLAGS = { -- Do not build gcsuspects file and reuse previously generated one. reuse_gcsuspects = false; -- Don't use parallel python runner. sequential = false; -- Print commands to console before executing them. verbose = false; -- Perform dead variable analysis (generates many false positives). -- TODO add some sort of whiteliste to filter out false positives. dead_vars = false; -- When building gcsuspects whitelist certain functions as if they -- can be causing GC. Currently used to reduce number of false -- positives in dead variables analysis. See TODO for WHITELIST -- below. whitelist = true; } local ARGS = {} for i = 1, #arg do local flag = arg[i]:match "^%-%-([%w_-]+)$" if flag then local no, real_flag = flag:match "^(no)([%w_-]+)$" if real_flag then flag = real_flag end flag = flag:gsub("%-", "_") if FLAGS[flag] ~= nil then FLAGS[flag] = (no ~= "no") else error("Unknown flag: " .. flag) end else table.insert(ARGS, arg[i]) end end local ARCHS = ARGS[1] and { ARGS[1] } or { 'ia32', 'arm', 'x64', 'arm64' } local io = require "io" local os = require "os" function log(...) io.stderr:write(string.format(...)) io.stderr:write "\n" end ------------------------------------------------------------------------------- -- Clang invocation local CLANG_BIN = os.getenv "CLANG_BIN" local CLANG_PLUGINS = os.getenv "CLANG_PLUGINS" if not CLANG_BIN or CLANG_BIN == "" then error "CLANG_BIN not set" end if not CLANG_PLUGINS or CLANG_PLUGINS == "" then CLANG_PLUGINS = DIR end local function MakeClangCommandLine( plugin, plugin_args, triple, arch_define, arch_options) if plugin_args then for i = 1, #plugin_args do plugin_args[i] = "-Xclang -plugin-arg-" .. plugin .. " -Xclang " .. plugin_args[i] end plugin_args = " " .. table.concat(plugin_args, " ") end return CLANG_BIN .. "/clang++ -std=c++11 -c " .. " -Xclang -load -Xclang " .. CLANG_PLUGINS .. "/libgcmole.so" .. " -Xclang -plugin -Xclang " .. plugin .. (plugin_args or "") .. " -Xclang -triple -Xclang " .. triple .. " -D" .. arch_define .. " -DENABLE_DEBUGGER_SUPPORT" .. " -DV8_I18N_SUPPORT" .. " -I./" .. " -Ithird_party/icu/source/common" .. " -Ithird_party/icu/source/i18n" .. " " .. arch_options end local function IterTable(t) return coroutine.wrap(function () for i, v in ipairs(t) do coroutine.yield(v) end end) end local function SplitResults(lines, func) -- Splits the output of parallel.py and calls func on each result. -- Bails out in case of an error in one of the executions. local current = {} local filename = "" for line in lines do local new_file = line:match "^______________ (.*)$" local code = line:match "^______________ finish (%d+) ______________$" if code then if tonumber(code) > 0 then log(table.concat(current, "\n")) log("Failed to examine " .. filename) return false end log("-- %s", filename) func(filename, IterTable(current)) elseif new_file then filename = new_file current = {} else table.insert(current, line) end end return true end function InvokeClangPluginForEachFile(filenames, cfg, func) local cmd_line = MakeClangCommandLine(cfg.plugin, cfg.plugin_args, cfg.triple, cfg.arch_define, cfg.arch_options) if FLAGS.sequential then log("** Sequential execution.") for _, filename in ipairs(filenames) do log("-- %s", filename) local action = cmd_line .. " " .. filename .. " 2>&1" if FLAGS.verbose then print('popen ', action) end local pipe = io.popen(action) func(filename, pipe:lines()) local success = pipe:close() if not success then error("Failed to run: " .. action) end end else log("** Parallel execution.") local action = "python tools/gcmole/parallel.py \"" .. cmd_line .. "\" " .. table.concat(filenames, " ") if FLAGS.verbose then print('popen ', action) end local pipe = io.popen(action) local success = SplitResults(pipe:lines(), func) local closed = pipe:close() if not (success and closed) then error("Failed to run: " .. action) end end end ------------------------------------------------------------------------------- -- GYP file parsing local function ParseGYPFile() local gyp = "" local gyp_files = { "tools/gyp/v8.gyp", "test/cctest/cctest.gyp" } for i = 1, #gyp_files do local f = assert(io.open(gyp_files[i]), "failed to open GYP file") local t = f:read('*a') gyp = gyp .. t f:close() end local result = {} for condition, sources in gyp:gmatch "'sources': %[.-### gcmole%((.-)%) ###(.-)%]" do if result[condition] == nil then result[condition] = {} end for file in sources:gmatch "'%.%./%.%./src/([^']-%.cc)'" do table.insert(result[condition], "src/" .. file) end for file in sources:gmatch "'(test-[^']-%.cc)'" do table.insert(result[condition], "test/cctest/" .. file) end end return result end local function EvaluateCondition(cond, props) if cond == 'all' then return true end local p, v = cond:match "(%w+):(%w+)" assert(p and v, "failed to parse condition: " .. cond) assert(props[p] ~= nil, "undefined configuration property: " .. p) return props[p] == v end local function BuildFileList(sources, props) local list = {} for condition, files in pairs(sources) do if EvaluateCondition(condition, props) then for i = 1, #files do table.insert(list, files[i]) end end end return list end local sources = ParseGYPFile() local function FilesForArch(arch) return BuildFileList(sources, { os = 'linux', arch = arch, mode = 'debug', simulator = ''}) end local mtConfig = {} mtConfig.__index = mtConfig local function config (t) return setmetatable(t, mtConfig) end function mtConfig:extend(t) local e = {} for k, v in pairs(self) do e[k] = v end for k, v in pairs(t) do e[k] = v end return config(e) end local ARCHITECTURES = { ia32 = config { triple = "i586-unknown-linux", arch_define = "V8_TARGET_ARCH_IA32", arch_options = "-m32" }, arm = config { triple = "i586-unknown-linux", arch_define = "V8_TARGET_ARCH_ARM", arch_options = "-m32" }, x64 = config { triple = "x86_64-unknown-linux", arch_define = "V8_TARGET_ARCH_X64", arch_options = "" }, arm64 = config { triple = "x86_64-unknown-linux", arch_define = "V8_TARGET_ARCH_ARM64", arch_options = "" }, } ------------------------------------------------------------------------------- -- GCSuspects Generation local gc, gc_caused, funcs local WHITELIST = { -- The following functions call CEntryStub which is always present. "MacroAssembler.*CallExternalReference", "MacroAssembler.*CallRuntime", "CompileCallLoadPropertyWithInterceptor", "CallIC.*GenerateMiss", -- DirectCEntryStub is a special stub used on ARM. -- It is pinned and always present. "DirectCEntryStub.*GenerateCall", -- TODO GCMole currently is sensitive enough to understand that certain -- functions only cause GC and return Failure simulataneously. -- Callsites of such functions are safe as long as they are properly -- check return value and propagate the Failure to the caller. -- It should be possible to extend GCMole to understand this. "Heap.*AllocateFunctionPrototype", -- Ignore all StateTag methods. "StateTag", -- Ignore printing of elements transition. "PrintElementsTransition" }; local function AddCause(name, cause) local t = gc_caused[name] if not t then t = {} gc_caused[name] = t end table.insert(t, cause) end local function resolve(name) local f = funcs[name] if not f then f = {} funcs[name] = f if name:match "Collect.*Garbage" then gc[name] = true AddCause(name, "<GC>") end if FLAGS.whitelist then for i = 1, #WHITELIST do if name:match(WHITELIST[i]) then gc[name] = false end end end end return f end local function parse (filename, lines) local scope for funcname in lines do if funcname:sub(1, 1) ~= '\t' then resolve(funcname) scope = funcname else local name = funcname:sub(2) resolve(name)[scope] = true end end end local function propagate () log "** Propagating GC information" local function mark(from, callers) for caller, _ in pairs(callers) do if gc[caller] == nil then gc[caller] = true mark(caller, funcs[caller]) end AddCause(caller, from) end end for funcname, callers in pairs(funcs) do if gc[funcname] then mark(funcname, callers) end end end local function GenerateGCSuspects(arch, files, cfg) -- Reset the global state. gc, gc_caused, funcs = {}, {}, {} log ("** Building GC Suspects for %s", arch) InvokeClangPluginForEachFile (files, cfg:extend { plugin = "dump-callees" }, parse) propagate() local out = assert(io.open("gcsuspects", "w")) for name, value in pairs(gc) do if value then out:write (name, '\n') end end out:close() local out = assert(io.open("gccauses", "w")) out:write "GC = {" for name, causes in pairs(gc_caused) do out:write("['", name, "'] = {") for i = 1, #causes do out:write ("'", causes[i], "';") end out:write("};\n") end out:write "}" out:close() log ("** GCSuspects generated for %s", arch) end -------------------------------------------------------------------------------- -- Analysis local function CheckCorrectnessForArch(arch) local files = FilesForArch(arch) local cfg = ARCHITECTURES[arch] if not FLAGS.reuse_gcsuspects then GenerateGCSuspects(arch, files, cfg) end local processed_files = 0 local errors_found = false local function SearchForErrors(filename, lines) processed_files = processed_files + 1 for l in lines do errors_found = errors_found or l:match "^[^:]+:%d+:%d+:" or l:match "error" or l:match "warning" print(l) end end log("** Searching for evaluation order problems%s for %s", FLAGS.dead_vars and " and dead variables" or "", arch) local plugin_args if FLAGS.dead_vars then plugin_args = { "--dead-vars" } end InvokeClangPluginForEachFile(files, cfg:extend { plugin = "find-problems", plugin_args = plugin_args }, SearchForErrors) log("** Done processing %d files. %s", processed_files, errors_found and "Errors found" or "No errors found") return errors_found end local function SafeCheckCorrectnessForArch(arch) local status, errors = pcall(CheckCorrectnessForArch, arch) if not status then print(string.format("There was an error: %s", errors)) errors = true end return errors end local errors = false for _, arch in ipairs(ARCHS) do if not ARCHITECTURES[arch] then error ("Unknown arch: " .. arch) end errors = SafeCheckCorrectnessForArch(arch, report) or errors end os.exit(errors and 1 or 0)
apache-2.0
RebootRevival/FFXI_Test
scripts/zones/Mount_Zhayolm/npcs/qm1.lua
3
1334
----------------------------------- -- Area: Mount Zhayolm -- NPC: ??? (Spawn Brass Borer(ZNM T1)) -- !pos 399 -27 120 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17027471; if (trade:hasItemQty(2590,1) and trade:getItemCount() == 1) then -- Trade Shadeleaves if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end 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
petoju/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
tgserver2018/Tarfand.farsi
libs/XMLElement.lua
1
3981
local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error local table, string = table, string local XMLElement={} local mt XMLElement.new = function(lom) return setmetatable({lom=lom or {}}, mt) end local function filter(filtery_thing, lom) filtery_thing=filtery_thing or '*' for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do if thing == "text()" then if type(lom)=='string' then return true end elseif thing == '*' then if type(lom)=='table' then return true end else if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end end end return nil end mt ={ __index = { getAttr = function(self, attribute) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end return self.lom.attr[attribute] end, setAttr = function(self, attribute, value) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if value == nil then return self:removeAttr(attribute) end self.lom.attr[attribute]=tostring(value) return self end, removeAttr = function(self, attribute) local lom = self.lom if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if not lom.attr[attribute] then return self end for i,v in ipairs(lom.attr) do if v == attribute then table.remove(lom.attr, i) break end end lom.attr[attribute]=nil end, removeAllAttributes = function(self) local attr = self.lom.attr for i, v in pairs(self.lom.attr) do attr[i]=nil end return self end, getAttributes = function(self) local attr = {} for i, v in ipairs(self.lom.attr) do table.insert(attr,v) end return attr end, getXML = function(self) local function getXML(lom) local attr, inner = {}, {} for i, attribute in ipairs(lom.attr) do table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute])) end for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getXML(v)) else error("oh shit") end end local tagcontents = table.concat(inner) local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or "" if #tagcontents>0 then return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag) else return string.format("<%s%s />", lom.tag, attrstring) end end return getXML(self.lom) end, getText = function(self) local function getText(lom) local inner = {} for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getText(v)) end end return table.concat(inner) end return getText(self.lom) end, getChildren = function(self, filter_thing) local res = {} for i, node in ipairs(self.lom) do if filter(filter_thing, node) then table.insert(res, type(node)=='table' and XMLElement.new(node) or node) end end return res end, getDescendants = function(self, filter_thing) local res = {} local function descendants(lom) for i, child in ipairs(lom) do if filter(filter_thing, child) then table.insert(res, type(child)=='table' and XMLElement.new(child) or child) if type(child)=='table' then descendants(child) end end end end descendants(self.lom) return res end, getChild = function(self, filter_thing) for i, node in ipairs(self.lom) do if filter(filter_thing, node) then return type(node)=='table' and XMLElement.new(node) or node end end end, getTag = function(self) return self.lom.tag end }} return XMLElement -- کد های پایین در ربات نشان داده نمیشوند — https://t.me/SaMaN_SaNstar2017 — @MeGaNet_sbot — @SaMaN_SaNtori — @SaMaN_SaNstar2017
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/abilities/dark_arts.lua
4
1587
----------------------------------- -- Ability: Dark Arts -- Optimizes black magic capability while lowering white magic proficiency. Grants a bonus to enfeebling, elemental, and dark magic. Also grants access to Stratagems. -- Obtained: Scholar Level 10 -- Recast Time: 1:00 -- Duration: 2:00:00 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_DARK_ARTS) or player:hasStatusEffect(EFFECT_ADDENDUM_BLACK) then return msgBasic.EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:delStatusEffectSilent(EFFECT_LIGHT_ARTS); player:delStatusEffect(EFFECT_ADDENDUM_WHITE); player:delStatusEffect(EFFECT_PENURY); player:delStatusEffect(EFFECT_CELERITY); player:delStatusEffect(EFFECT_ACCESSION); player:delStatusEffect(EFFECT_RAPTURE); player:delStatusEffect(EFFECT_ALTRUISM); player:delStatusEffect(EFFECT_TRANQUILITY); player:delStatusEffect(EFFECT_PERPETUANCE); local helixbonus = 0; if (player:getMainJob() == JOBS.SCH and player:getMainLvl() >= 20) then helixbonus = math.floor(player:getMainLvl() / 4); end player:addStatusEffect(EFFECT_DARK_ARTS,1,0,7200,0,helixbonus); return EFFECT_DARK_ARTS; end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/flask_of_panacea.lua
70
1742
----------------------------------------- -- ID: 4163 -- Item: Panacea -- Item Effect: Removes any number of status effects ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:delStatusEffect(EFFECT_PARALYSIS); target:delStatusEffect(EFFECT_BIND); target:delStatusEffect(EFFECT_WEIGHT); target:delStatusEffect(EFFECT_ADDLE); target:delStatusEffect(EFFECT_BURN); target:delStatusEffect(EFFECT_FROST); target:delStatusEffect(EFFECT_CHOKE); target:delStatusEffect(EFFECT_RASP); target:delStatusEffect(EFFECT_SHOCK); target:delStatusEffect(EFFECT_DROWN); target:delStatusEffect(EFFECT_DIA); target:delStatusEffect(EFFECT_BIO); target:delStatusEffect(EFFECT_STR_DOWN); target:delStatusEffect(EFFECT_DEX_DOWN); target:delStatusEffect(EFFECT_VIT_DOWN); target:delStatusEffect(EFFECT_AGI_DOWN); target:delStatusEffect(EFFECT_INT_DOWN); target:delStatusEffect(EFFECT_MND_DOWN); target:delStatusEffect(EFFECT_CHR_DOWN); target:delStatusEffect(EFFECT_MAX_HP_DOWN); target:delStatusEffect(EFFECT_MAX_MP_DOWN); target:delStatusEffect(EFFECT_ATTACK_DOWN); target:delStatusEffect(EFFECT_EVASION_DOWN); target:delStatusEffect(EFFECT_DEFENSE_DOWN); target:delStatusEffect(EFFECT_MAGIC_DEF_DOWN); target:delStatusEffect(EFFECT_INHIBIT_TP); target:delStatusEffect(EFFECT_MAGIC_ACC_DOWN); target:delStatusEffect(EFFECT_MAGIC_ATK_DOWN); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/porcupine_pie.lua
12
2061
----------------------------------------- -- ID: 5156 -- Item: porcupine_pie -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 55 -- Strength 6 -- Vitality 2 -- Intelligence -3 -- Mind 3 -- HP recovered while healing 2 -- MP recovered while healing 2 -- Accuracy 5 -- Attack % 18 (cap 95) -- Ranged Attack % 18 (cap 95) ----------------------------------------- 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,14400,5156); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 55); target:addMod(MOD_STR, 6); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -3); target:addMod(MOD_MND, 3); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 2); target:addMod(MOD_ACC, 5); target:addMod(MOD_FOOD_ATTP, 18); target:addMod(MOD_FOOD_ATT_CAP, 95); target:addMod(MOD_FOOD_RATTP, 18); target:addMod(MOD_FOOD_RATT_CAP, 95); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 55); target:delMod(MOD_STR, 6); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -3); target:delMod(MOD_MND, 3); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 2); target:delMod(MOD_ACC, 5); target:delMod(MOD_FOOD_ATTP, 18); target:delMod(MOD_FOOD_ATT_CAP, 95); target:delMod(MOD_FOOD_RATTP, 18); target:delMod(MOD_FOOD_RATT_CAP, 95); end;
gpl-3.0
mickours/lsyncd
tests/exclude-rsyncssh.lua
13
2934
#!/usr/bin/lua require("posix") dofile("tests/testlib.lua") cwriteln("****************************************************************"); cwriteln(" Testing excludes "); cwriteln("****************************************************************"); cwriteln(" (this test needs passwordless ssh localhost access "); cwriteln(" for current user)"); local tdir, srcdir, trgdir = mktemps() local logfile = tdir .. "log" local cfgfile = tdir .. "config.lua" local range = 5 local log = {} log = {"-log", "all"} writefile(cfgfile, [[ settings = { logfile = "]]..logfile..[[", nodaemon = true, delay = 3, } sync { default.rsyncssh, host = "localhost", source = "]]..srcdir..[[", targetdir = "]]..trgdir..[[", exclude = { "erf", "/eaf", "erd/", "/ead/", }, }]]); -- writes all files local function writefiles() posix.mkdir(srcdir .. "d"); writefile(srcdir .. "erf", "erf"); writefile(srcdir .. "eaf", "erf"); writefile(srcdir .. "erd", "erd"); writefile(srcdir .. "ead", "ead"); writefile(srcdir .. "d/erf", "erf"); writefile(srcdir .. "d/eaf", "erf"); writefile(srcdir .. "d/erd", "erd"); writefile(srcdir .. "d/ead", "ead"); end -- test if the filename exists, fails if this is different to expect local function testfile(filename, expect) local stat, err = posix.stat(filename) if stat and not expect then cwriteln("failure: ",filename," should be excluded"); os.exit(1); end if not stat and expect then cwriteln("failure: ",filename," should not be excluded"); os.exit(1); end end -- test all files local function testfiles() testfile(trgdir .. "erf", false); testfile(trgdir .. "eaf", false); testfile(trgdir .. "erd", true); testfile(trgdir .. "ead", true); testfile(trgdir .. "d/erf", false); testfile(trgdir .. "d/eaf", true); testfile(trgdir .. "d/erd", true); testfile(trgdir .. "d/ead", true); end cwriteln("testing startup excludes"); writefiles(); cwriteln("starting Lsyncd"); local pid = spawn("./lsyncd", cfgfile, unpack(log)); cwriteln("waiting for Lsyncd to start"); posix.sleep(3) cwriteln("testing excludes after startup"); testfiles(); cwriteln("ok, removing sources"); if srcdir:sub(1,4) ~= "/tmp" then -- just to make sure before rm -rf cwriteln("exist before drama, srcdir is '", srcdir, "'"); os.exit(1); end os.execute("rm -rf "..srcdir.."/*"); cwriteln("waiting for Lsyncd to remove destination"); posix.sleep(5); if os.execute("diff -urN "..srcdir.." "..trgdir) ~= 0 then cwriteln("fail, target directory not empty!"); os.exit(1); end cwriteln("writing files after startup"); writefiles(); cwriteln("waiting for Lsyncd to transmit changes"); posix.sleep(5); testfiles(); cwriteln("killing started Lsyncd"); posix.kill(pid); local _, exitmsg, lexitcode = posix.wait(lpid); cwriteln("Exitcode of Lsyncd = ", exitmsg, " ", lexitcode); posix.sleep(1); if lexitcode == 0 then cwriteln("OK"); end os.exit(lexitcode); -- TODO remove temp
gpl-2.0
iovisor/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
sajadaltaie/sejobot
plugins/settings.lua
1
30740
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -------------------------------------------------- do local function remove_message(extra, success, result) msg = backward_msg_format(result) delete_msg(msg.id, ok_cb, false) end local function set_group_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo (receiver, file, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'photoSaved') else print('Error downloading: '..msg.id) return 'ℹ️ '..lang_text(msg.to.id, 'photoSaved') end end local function pre_process(msg) local hash = 'flood:max:'..msg.to.id if not redis:get(hash) then floodMax = 5 else floodMax = tonumber(redis:get(hash)) end local hash = 'flood:time:'..msg.to.id if not redis:get(hash) then floodTime = 3 else floodTime = tonumber(redis:get(hash)) end --Checking flood local hashse = 'anti-flood:'..msg.to.id if not redis:get(hashse) then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then if not permissions(msg.from.id, msg.to.id, "no_flood_ban") then -- Increase the number of messages from the user on the chat local hash = 'flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > floodMax then local receiver = get_receiver(msg) local user = msg.from.id local chat = msg.to.id local channel = msg.to.id local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, lang_text(chat, 'user')..' @'..msg.from.username..' ('..msg.from.id..') '..lang_text(chat, 'isFlooding'), ok_cb, true) chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, lang_text(chat, 'user')..' @'..msg.from.username..' ('..msg.from.id..') '..lang_text(chat, 'isFlooding'), ok_cb, true) channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) end end redis:setex(hash, floodTime, msgs+1) end end end --Checking stickers if not msg.media then webp = 'nothing' else webp = msg.media.caption end if webp == 'sticker.webp' then hash = 'stickers:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end if not msg.media then mp4 = 'nothing' else if msg.media.type == 'document' then mp4 = msg.media.caption or 'audio' end end --Checking GIFs and MP4 files if mp4 == 'giphy.mp4' then hash = 'gifs:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else if msg.media then if msg.media.type == 'document' then gifytpe = string.find(mp4, 'gif.mp4') or 'audio' if gifytpe == 'audio' then hash = 'audio:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else hash = 'gifs:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end end end end --Checking photos if msg.media then if msg.media.type == 'photo' then local hash = 'setphoto:'..msg.to.id..':'..msg.from.id if redis:get(hash) then redis:del(hash) load_photo(msg.id, set_group_photo, msg) delete_msg(msg.id, ok_cb, false) end local hash = 'photo:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end end return msg end local function run(msg, matches) if matches[1] == 'settings' then if permissions(msg.from.id, msg.to.id, "settings") then if matches[2] ~= nil then if matches[2] == 'stickers' then if matches[3] == 'enable' then hash = 'stickers:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'stickersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'stickersL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'stickers:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noStickersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noStickersL'), ok_cb, false) end end return elseif matches[2] == 'gifs' then if matches[3] == 'enable' then hash = 'gifs:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'gifsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'gifsL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'gifs:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noGifsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noGifsL'), ok_cb, false) end end return elseif matches[2] == 'photos' then if matches[3] == 'enable' then hash = 'photo:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'photosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'photosL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'photo:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noPhotosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noPhotosL'), ok_cb, false) end end return elseif matches[2] == 'arabic' then if matches[3] == 'enable' then hash = 'arabic:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'arabicT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'arabicL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'arabic:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noArabicT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noArabicL'), ok_cb, false) end end return elseif matches[2] == 'audios' then if matches[3] == 'enable' then hash = 'audio:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'audiosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'audiosL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'audio:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noAudiosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noAudiosL'), ok_cb, false) end end return elseif matches[2] == 'kickme' then if matches[3] == 'enable' then hash = 'kickme:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'kickmeT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'kickmeL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'kickme:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noKickmeT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noKickmeL'), ok_cb, false) end end return elseif matches[2] == 'flood' then if matches[3] == 'enable' then hash = 'anti-flood:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'anti-flood:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noFloodT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noFloodL'), ok_cb, false) end end return elseif matches[2] == 'spam' then if matches[3] == 'enable' then local hash = 'spam:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'allowedSpamT'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'allowedSpamL'), ok_cb, true) end elseif matches[3] == 'disable' then local hash = 'spam:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notAllowedSpamT'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notAllowedSpamL'), ok_cb, true) end end elseif matches[2] == 'lockmember' then hash = 'lockmember:'..msg.to.id if matches[3] == 'enable' then redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'lockMembersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'lockMembersL'), ok_cb, false) end elseif matches[3] == 'disable' then redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notLockMembersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notLockMembersT'), ok_cb, false) end end return elseif matches[2] == 'floodtime' then if not matches[3] then else hash = 'flood:time:'..msg.to.id redis:set(hash, matches[3]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodTime')..matches[3], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodTime')..matches[3], ok_cb, false) end end return elseif matches[2] == 'maxflood' then if not matches[3] then else hash = 'flood:max:'..msg.to.id redis:set(hash, matches[3]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodMax')..matches[3], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodMax')..matches[3], ok_cb, false) end end return elseif matches[2] == 'setname' then if matches[3] == 'enable' then local hash = 'name:enabled:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'chatRename'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'channelRename'), ok_cb, false) end elseif matches[3] == 'disable' then local hash = 'name:enabled:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChatRename'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChannelRename'), ok_cb, false) end end end else if msg.to.type == 'chat' then text = '⚙ '..lang_text(msg.to.id, 'gSettings')..':\n' elseif msg.to.type == 'channel' then text = '⚙ '..lang_text(msg.to.id, 'sSettings')..':\n' end local allowed = lang_text(msg.to.id, 'allowed') local noAllowed = lang_text(msg.to.id, 'noAllowed') --Enable/disable Stickers local hash = 'stickers:'..msg.to.id if redis:get(hash) then sStickers = noAllowed sStickersD = '🔹' else sStickers = allowed sStickersD = '🔸' end text = text..sStickersD..' '..lang_text(msg.to.id, 'stickers')..': '..sStickers..'\n' --Enable/disable Links local hash = 'antilink:'..msg.to.id if redis:get(hash) then sLink = noAllowed sLinkD = '🔹' else sLink = allowed sLinkD = '🔸' end text = text..sLinkD..' '..lang_text(msg.to.id, 'links')..': '..sLink..'\n' --Enable/disable arabic messages local hash = 'arabic:'..msg.to.id if redis:get(hash) then sArabe = allowed sArabeD = '🔸' else sArabe = noAllowed sArabeD = '🔹' end text = text..sArabeD..' '..lang_text(msg.to.id, 'arabic')..': '..sArabe..'\n' --Enable/disable bots local hash = 'antibot:'..msg.to.id if redis:get(hash) then sBots = allowed sBotsD = '🔸' else sBots = noAllowed sBotsD = '🔹' end text = text..sBotsD..' '..lang_text(msg.to.id, 'bots')..': '..sBots..'\n' --Enable/disable gifs local hash = 'gifs:'..msg.to.id if redis:get(hash) then sGif = noAllowed sGifD = '🔹' else sGif = allowed sGifD = '🔸' end text = text..sGifD..' '..lang_text(msg.to.id, 'gifs')..': '..sGif..'\n' --Enable/disable send photos local hash = 'photo:'..msg.to.id if redis:get(hash) then sPhoto = noAllowed sPhotoD = '🔹' else sPhoto = allowed sPhotoD = '🔸' end text = text..sPhotoD..' '..lang_text(msg.to.id, 'photos')..': '..sPhoto..'\n' --Enable/disable send audios local hash = 'audio:'..msg.to.id if redis:get(hash) then sAudio = noAllowed sAudioD = '🔹' else sAudio = allowed sAudioD = '🔸' end text = text..sAudioD..' '..lang_text(msg.to.id, 'audios')..': '..sAudio..'\n' --Enable/disable kickme local hash = 'kickme:'..msg.to.id if redis:get(hash) then sKickme = allowed sKickmeD = '🔸' else sKickme = noAllowed sKickmeD = '🔹' end text = text..sKickmeD..' '..lang_text(msg.to.id, 'kickme')..': '..sKickme..'\n' --Enable/disable spam local hash = 'spam:'..msg.to.id if redis:get(hash) then sSpam = noAllowed sSpamD = '🔹' else sSpam = allowed sSpamD = '🔸' end text = text..sSpamD..' '..lang_text(msg.to.id, 'spam')..': '..sSpam..'\n' --Enable/disable setphoto local hash = 'setphoto:'..msg.to.id..':'..msg.from.id if redis:get(hash) then sSPhoto = allowed sSPhotoD = '🔸' else sSPhoto = noAllowed sSPhotoD = '🔹' end text = text..sSPhotoD..' '..lang_text(msg.to.id, 'setphoto')..': '..sSPhoto..'\n' --Enable/disable changing group name local hash = 'name:enabled:'..msg.to.id if redis:get(hash) then sName = allowed sNameD = '🔸' else sName = noAllowed sNameD = '🔹' end text = text..sNameD..' '..lang_text(msg.to.id, 'gName')..': '..sName..'\n' --Lock/unlock numbers of channel members local hash = 'lockmember:'..msg.to.id if redis:get(hash) then sLock = noAllowed sLockD = '🔹' else sLock = allowed sLockD = '🔸' end text = text..sLockD..' lockmembers: '..sLock..'\n' --Enable/disable Flood local hash = 'anti-flood:'..msg.to.id if redis:get(hash) then sFlood = allowed sFloodD = '🔸' else sFlood = noAllowed sFloodD = '🔹' end text = text..sFloodD..' '..lang_text(msg.to.id, 'flood')..': '..sFlood..'\n' local hash = 'langset:'..msg.to.id if redis:get(hash) then sLang = redis:get(hash) sLangD = '🔸' else sLang = lang_text(msg.to.id, 'noSet') sLangD = '🔹' end text = text..sLangD..' '..lang_text(msg.to.id, 'language')..': '..string.upper(sLang)..'\n' local hash = 'flood:max:'..msg.to.id if not redis:get(hash) then floodMax = 5 else floodMax = redis:get(hash) end local hash = 'flood:time:'..msg.to.id if not redis:get(hash) then floodTime = 3 else floodTime = redis:get(hash) end text = text..'🔺 '..lang_text(msg.to.id, 'mFlood')..': '..floodMax..'\n🔺 '..lang_text(msg.to.id, 'tFlood')..': '..floodTime..'\n' --Send settings to group or supergroup if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, text, ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, text, ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'rem' then if permissions(msg.from.id, msg.to.id, "settings") then if msg.reply_id then get_message(msg.reply_id, remove_message, false) end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'lang' then if permissions(msg.from.id, msg.to.id, "set_lang") then hash = 'langset:'..msg.to.id redis:set(hash, matches[2]) return lang_text(msg.to.id, 'langUpdated')..string.upper(matches[2]) else return '🚫 '..lang_text(msg.to.id, 'require_sudo') end elseif matches[1] == 'setname' then if permissions(msg.from.id, msg.to.id, "settings") then local hash = 'name:enabled:'..msg.to.id if redis:get(hash) then if msg.to.type == 'chat' then rename_chat(msg.to.peer_id, matches[2], ok_cb, false) elseif msg.to.type == 'channel' then rename_channel(msg.to.peer_id, matches[2], ok_cb, false) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'setlink' then if permissions(msg.from.id, msg.to.id, "settings") then hash = 'link:'..msg.to.id redis:set(hash, matches[2]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'link' then if permissions(msg.from.id, msg.to.id, "settings") then hash = 'link:'..msg.to.id local linktext = redis:get(hash) if linktext then if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, '🌐 '..lang_text(msg.to.id, 'groupLink')..': '..linktext, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, '🌐 '..lang_text(msg.to.id, 'sGroupLink')..': '..linktext, ok_cb, true) end else if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinkSet'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinkSet'), ok_cb, true) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'setphoto' then if permissions(msg.from.id, msg.to.id, "settings") then if matches[2] == 'stop' then hash = 'setphoto:'..msg.to.id..':'..msg.from.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'setPhotoAborted'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'setPhotoAborted'), ok_cb, true) end else hash = 'setphoto:'..msg.to.id..':'..msg.from.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'sendPhoto'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'sendPhoto'), ok_cb, true) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end end local hash = 'arabic:'..msg.to.id if not redis:get(hash) then delete_msg(msg.id, ok_cb, false) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, lang_text(msg.to.id, 'noArabicT'), ok_cb, true) chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, lang_text(msg.to.id, 'noArabicL'), ok_cb, true) channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) end return end end return { patterns = { '^#(settings)$', '^#(settings) (.*) (.*)$', '^#(rem)$', '^#(setname) (.*)$', '^#(setphoto)$', '^#(setphoto) (.*)$', '^#(link)$', '^#(setlink) (.*)$', '^#(lang) (.*)$', '([\216-\219][\128-\191])' }, pre_process = pre_process, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Metalworks/npcs/Unlucky_Rat.lua
16
2248
----------------------------------- -- Area: Metalworks -- NPC: Unlucky Rat -- Starts & Finishes Quest: Mean Machine ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local MeanMachine = player:getQuestStatus(BASTOK,MEAN_MACHINE); if (MeanMachine == QUEST_ACCEPTED) then local FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then count = trade:getItemCount(); SlimeOil = trade:hasItemQty(637,1); if (SlimeOil == true and count == 1) then player:startEvent(0x022d); end else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE, 4731); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local MeanMachine = player:getQuestStatus(BASTOK,MEAN_MACHINE); local Fame = player:getFameLevel(BASTOK); if (MeanMachine == QUEST_AVAILABLE and Fame >= 2) then player:startEvent(0x022c); elseif (MeanMachine == QUEST_ACCEPTED) then player:startEvent(0x022f); else player:startEvent(0x0226); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x022c) then player:addQuest(BASTOK,MEAN_MACHINE); elseif (csid == 0x022d) then player:completeQuest(BASTOK,MEAN_MACHINE); player:addFame(BASTOK,120); player:tradeComplete(); player:addItem(4869); player:messageSpecial(ITEM_OBTAINED,4869); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Labyrinth_of_Onzozo/mobs/Goblin_Bandit.lua
3
1214
----------------------------------- -- Area: Labyrinth of Onzozo -- MOB: Goblin Bandit -- Note: Place holder Soulstealer Skullnix ----------------------------------- require("scripts/globals/groundsofvalor"); require("scripts/zones/Labyrinth_of_Onzozo/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkGoVregime(player,mob,771,2); checkGoVregime(player,mob,772,2); checkGoVregime(player,mob,774,2); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Soulstealer_Skullnix_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Soulstealer_Skullnix"); if (ToD <= os.time() and GetMobAction(Soulstealer_Skullnix) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Soulstealer_Skullnix); GetMobByID(Soulstealer_Skullnix):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Soulstealer_Skullnix", mobID); DisallowRespawn(mobID, true); end end end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Yuhtunga_Jungle/npcs/Luck_Rune.lua
3
1060
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Luck Rune -- Involved in Quest: Mhaura Fortune -- !pos -95.486 11.188 418.153 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Yuhtunga_Jungle/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_THE_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
TheRikyHUN/fooniks
resources/phoenix_Infospots/infospots-client.lua
2
2115
local player = getLocalPlayer( ); function SetMyPos( x, y, z ) setElementPosition( player, x, y, z ); local newZ = getGroundPosition( x, y, z ) + math.abs( getElementDistanceFromCentreOfMassToBaseOfModel( player ) ); setElementPosition( player, x, y, newZ ); end addEvent( "onInteriorPosRequest", true ); addEventHandler( "onInteriorPosRequest", getRootElement( ), SetMyPos ); function getIntByID( id ) if( type( id ) == "number" ) then id = tostring( id); end if( type( id ) ~= "string" ) then return false, -1; end local ints = getElementsByType( "sInterior" ); for k, v in ipairs( ints ) do local myId = getElementData( v, "infoId" ); if( id == tostring( myId ) ) then return true, v; end end return false, -2; end addEvent( "onInfospotClicked", false ); addEventHandler( "onClientClick", getRootElement( ), function ( button, state, absoluteX, absoluteY, worldX, worldY, worldZ, clickedElement ) if( clickedElement == false ) then local myX, myY, myZ = getElementPosition( player ); local markers = getElementsByType( "marker" ); for k,v in ipairs( markers ) do local markerX, markerY, markerZ = getElementPosition( v ); local dist1 = getDistanceBetweenPoints3D( myX, myY, myZ, markerX, markerY, markerZ ); if( dist1 < 15 ) then local freeView = processLineOfSight( myX, myY, myZ, markerX, markerY, markerZ ); if( freeView == false ) then local msX, msY = getScreenFromWorldPosition( markerX, markerY, markerZ ); if( msX ~= false and msY ~= false ) then local dist = getDistanceBetweenPoints2D( absoluteX, absoluteY, msX, msY ); if( dist < 60 ) then local id = getElementData( v, "infoId" ); if( id ~= false ) then triggerEvent( "onInfospotClicked", player, v, id, button, state, msX, msY ); end end end end end end end end , true);
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/AlTaieu/mobs/Absolute_Virtue.lua
21
2312
----------------------------------- -- Area: Al'Taieu -- HNM: Absolute Virtue ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGEN, 500); local JoL = GetMobByID(16912848); -- Special check for regen modification by JoL pets killed if (JoL:getLocalVar("JoL_Qn_xzomit_Killed") == 9) then mob:addMod(MOD_REGEN, -130) end if (JoL:getLocalVar("JoL_Qn_hpemde_Killed") == 9) then mob:addMod(MOD_REGEN, -130) end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) end; ------------------------------------ -- onSpellPrecast ------------------------------------ function onSpellPrecast(mob, spell) if (spell:getID() == 218) then -- Meteor spell:setAoE(SPELLAOE_RADIAL); spell:setFlag(SPELLFLAG_HIT_ALL); spell:setRadius(30); spell:setAnimation(280); -- AoE Meteor Animation spell:setMPCost(1); end end; ------------------------------------ -- onMonsterMagicPrepare ------------------------------------ function onMonsterMagicPrepare(caster, target) end; ----------------------------------- -- onMagicHit ----------------------------------- function onMagicHit(caster, target, spell) local REGEN = target:getMod(MOD_REGEN); local DAY = VanadielDayElement(); local ELEM = spell:getElement(); if (GetServerVariable("AV_Regen_Reduction") < 60) then -- Had to serverVar the regen instead of localVar because localVar reset on claim loss. if (ELEM == DAY and (caster:isPC() or caster:isPet())) then SetServerVariable("AV_Regen_Reduction", 1+GetServerVariable("AV_Regen_Reduction")); target:addMod(MOD_REGEN, -2); end end return 1; end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(VIRTUOUS_SAINT); end;
gpl-3.0
openwrt-es/openwrt-luci
applications/luci-app-upnp/luasrc/model/cbi/upnp/upnp.lua
9
3907
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("upnpd", luci.util.pcdata(translate("Universal Plug & Play")), translate("UPnP allows clients in the local network to automatically configure the router.")) m:section(SimpleSection).template = "upnp_status" s = m:section(NamedSection, "config", "upnpd", translate("MiniUPnP settings")) s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) e = s:taboption("general", Flag, "enabled", translate("Start UPnP and NAT-PMP service")) e.rmempty = false --function e.cfgvalue(self, section) -- return luci.sys.init.enabled("miniupnpd") and self.enabled or self.disabled --end function e.write(self, section, value) if value == "1" then luci.sys.call("/etc/init.d/miniupnpd start >/dev/null") else luci.sys.call("/etc/init.d/miniupnpd stop >/dev/null") end return Flag.write(self, section, value) end s:taboption("general", Flag, "enable_upnp", translate("Enable UPnP functionality")).default = "1" s:taboption("general", Flag, "enable_natpmp", translate("Enable NAT-PMP functionality")).default = "1" s:taboption("general", Flag, "secure_mode", translate("Enable secure mode"), translate("Allow adding forwards only to requesting ip addresses")).default = "1" s:taboption("general", Flag, "igdv1", translate("Enable IGDv1 mode"), translate("Advertise as IGDv1 device instead of IGDv2")).default = "0" s:taboption("general", Flag, "log_output", translate("Enable additional logging"), translate("Puts extra debugging information into the system log")) s:taboption("general", Value, "download", translate("Downlink"), translate("Value in KByte/s, informational only")).rmempty = true s:taboption("general", Value, "upload", translate("Uplink"), translate("Value in KByte/s, informational only")).rmempty = true port = s:taboption("general", Value, "port", translate("Port")) port.datatype = "port" port.default = 5000 s:taboption("advanced", Flag, "system_uptime", translate("Report system instead of daemon uptime")).default = "1" s:taboption("advanced", Value, "uuid", translate("Device UUID")) s:taboption("advanced", Value, "serial_number", translate("Announced serial number")) s:taboption("advanced", Value, "model_number", translate("Announced model number")) ni = s:taboption("advanced", Value, "notify_interval", translate("Notify interval")) ni.datatype = "uinteger" ni.placeholder = 30 ct = s:taboption("advanced", Value, "clean_ruleset_threshold", translate("Clean rules threshold")) ct.datatype = "uinteger" ct.placeholder = 20 ci = s:taboption("advanced", Value, "clean_ruleset_interval", translate("Clean rules interval")) ci.datatype = "uinteger" ci.placeholder = 600 pu = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL")) pu.placeholder = "http://192.168.1.1/" lf = s:taboption("advanced", Value, "upnp_lease_file", translate("UPnP lease file")) lf.placeholder = "/var/run/miniupnpd.leases" s2 = m:section(TypedSection, "perm_rule", translate("MiniUPnP ACLs"), translate("ACLs specify which external ports may be redirected to which internal addresses and ports")) s2.template = "cbi/tblsection" s2.sortable = true s2.anonymous = true s2.addremove = true s2:option(Value, "comment", translate("Comment")) ep = s2:option(Value, "ext_ports", translate("External ports")) ep.datatype = "portrange" ep.placeholder = "0-65535" ia = s2:option(Value, "int_addr", translate("Internal addresses")) ia.datatype = "ip4addr" ia.placeholder = "0.0.0.0/0" ip = s2:option(Value, "int_ports", translate("Internal ports")) ip.datatype = "portrange" ip.placeholder = "0-65535" ac = s2:option(ListValue, "action", translate("Action")) ac:value("allow") ac:value("deny") return m
apache-2.0
RebootRevival/FFXI_Test
scripts/zones/Aht_Urhgan_Whitegate/TextIDs.lua
3
5010
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 219; -- You cannot obtain the item. Come back after sorting your inventory.?Prompt? ITEM_CANNOT_BE_OBTAINEDX = 221; -- You cannot obtain the ?Possible Special Code: 01??Possible Special Code: 05?#?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?. Try trading again after sorting your inventory.?Prompt? ITEM_OBTAINED = 223; -- Obtained: <item> ITEM_OBTAINEDX = 232; -- You obtain ?Numeric Parameter 1? ?Possible Special Code: 01??Speaker Name?)??BAD CHAR: 80??BAD CHAR: 80??BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?!?Prompt? GIL_OBTAINED = 224; -- Obtained <number> gil KEYITEM_OBTAINED = 226; -- Obtained key item: <keyitem> NOT_HAVE_ENOUGH_GIL = 228; -- You do not have enough gil FISHING_MESSAGE_OFFSET = 884; -- You can't fish here HOMEPOINT_SET = 1364; -- Home point set! IMAGE_SUPPORT = 1405; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ?Multiple Choice (Parameter 2)?[a little/ever so slightly/ever so slightly].?Prompt? -- Conquest system SANCTION = 9799; -- You have received the Empire's Sanction. -- Quest dialogs ZASSHAL_DIALOG = 10993; -- 'ang about. Looks like the permit you got was the last one I 'ad, so it might take me a bit o' time to scrounge up some more. 'ere, don't gimme that look. I'll be restocked before you know it. MUSHAYRA_DIALOG = 4962; -- Sorry for all the trouble. Please ignore Hadahda the next time he asks you to do something. HADAHDA_DIALOG = 4913; -- Hey, think you could help me out? PAY_DIVINATION = 8765; -- You pay 1000 gil for the divination. -- Other Dialogs ITEM_DELIVERY_DIALOG = 9349; -- You have something you want delivered? RUNIC_PORTAL = 4582; -- You cannot use the runic portal without the Empire's authorization. IMAGE_SUPPORT_ACTIVE = 1403; -- You have to wait a bit longer before asking for synthesis image support again. -- Shop Texts UGRIHD_PURCHASE_DIALOGUE = 4643; -- Salaheem's Sentinels values your contribution to the success of the company. Please come again! GAVRIE_SHOP_DIALOG = 9263; -- Remember to take your medicine in small doses... Sometimes you can get a little too much of a good thing! MALFUD_SHOP_DIALOG = 9264; -- Welcome, welcome! Flavor your meals with Malfud's ingredients! RUBAHAH_SHOP_DIALOG = 9265; -- Flour! Flooour! Corn! Rice and beans! Get your rice and beans here! If you're looking for grain, you've come to the right place! MULNITH_SHOP_DIALOG = 9266; -- Drawn in by my shop's irresistible aroma, were you? How would you like some of the Near East's famous skewers to enjoy during your journeys? SALUHWA_SHOP_DIALOG = 9267; -- Looking for undentable shields? This shop's got the best of 'em! These are absolute must-haves for a mercenary's dangerous work! DWAGO_SHOP_DIALOG = 9268; -- Buy your goods here...or you'll regret it! KULHAMARIYO_SHOP_DIALOG = 9269; -- Some fish to savorrr while you enjoy the sights of Aht Urhgan? KHAFJHIFANM_SHOP_DIALOG = 9270; -- How about a souvenir for back home? There's nothing like dried dates to remind you of good times in Al Zahbi! HAGAKOFF_SHOP_DIALOG = 9271; -- Welcome! Fill all your destructive needs with my superb weaponry! No good mercenary goes without a good weapon! BAJAHB_SHOP_DIALOG = 9272; -- Good day! If you want to live long, you'll buy your armor here. MAZWEEN_SHOP_DIALOG = 9273; -- Magic scrolls! Get your magic scrolls here! FAYEEWAH_SHOP_DIALOG = 9274; -- Why not sit back a spell and enjoy the rich aroma and taste of a cup of chai? YAFAAF_SHOP_DIALOG = 9275; -- There's nothing like the mature taste and luxurious aroma of coffee... Would you like a cup WAHNID_SHOP_DIALOG = 9276; -- All the fishing gear you'll ever need, here in one place! WAHRAGA_SHOP_DIALOG = 9277; -- Welcome to the Alchemists' Guild. -- Automaton AUTOMATON_RENAME = 5828; -- Your automaton has a new name. AUTOMATON_VALOREDGE_UNLOCK = 9587; -- You obtain the Valoredge X-900 head and frame! AUTOMATON_SHARPSHOT_UNLOCK = 9592; -- You obtain the Sharpshot Z-500 head and frame! AUTOMATON_STORMWAKER_UNLOCK = 9597; -- You obtain the Stormwaker Y-700 head and frame! AUTOMATON_SOULSOOTHER_UNLOCK = 9629; -- You obtain the Soulsoother C-1000 head! AUTOMATON_SPIRITREAVER_UNLOCK = 9630; -- You obtain the Spiritreaver M-400 head! AUTOMATON_ATTACHMENT_UNLOCK = 9646; -- You can now equip your automaton with -- Assault RYTAAL_MISSION_COMPLETE = 5650; -- Congratulations. You have been awarded Assault Points for the successful completion of your mission. RYTAAL_MISSION_FAILED = 5651; -- Your mission was not successful; however, the Empire recognizes your contribution and has awarded you Assault Points. -- Porter Moogle RETRIEVE_DIALOG_ID = 13512; -- You retrieve$ from the porter moogle's care.
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/zone.lua
11
3195
------------------------------------ -- -- Contains global functions and variables -- related to area specific things -- ------------------------------------ ------------------------------------ -- zone related IDs ------------------------------------ -- Zone Types ZONETYPE_NONE = 0 ZONETYPE_CITY = 1 ZONETYPE_OUTDOORS = 2 ZONETYPE_DUNGEON = 3 ZONETYPE_BATTLEFIELD = 4 ZONETYPE_DYNAMIS = 5 ZONETYPE_INSTANCED = 6 -- Continent Type THE_MIDDLE_LANDS = 1 THE_ARADJIAH_CONTINENT = 2 THE_SHADOWREIGN_ERA = 3 OTHER_AREAS = 4 -- Region Types REGION_RONFAURE = 0 REGION_ZULKHEIM = 1 REGION_NORVALLEN = 2 REGION_GUSTABERG = 3 REGION_DERFLAND = 4 REGION_SARUTABARUTA = 5 REGION_KOLSHUSHU = 6 REGION_ARAGONEU = 7 REGION_FAUREGANDI = 8 REGION_VALDEAUNIA = 9 REGION_QUFIMISLAND = 10 REGION_LITELOR = 11 REGION_KUZOTZ = 12 REGION_VOLLBOW = 13 REGION_ELSHIMOLOWLANDS = 14 REGION_ELSHIMOUPLANDS = 15 REGION_TULIA = 16 REGION_MOVALPOLOS = 17 REGION_TAVNAZIA = 18 REGION_SANDORIA = 19 REGION_BASTOK = 20 REGION_WINDURST = 21 REGION_JEUNO = 22 REGION_DYNAMIS = 23 REGION_TAVNAZIAN_MARQ = 24 REGION_PROMYVION = 25 REGION_LUMORIA = 26 REGION_LIMBUS = 27 REGION_WEST_AHT_URHGAN = 28 REGION_MAMOOL_JA_SAVAGE = 29 REGION_HALVUNG = 30 REGION_ARRAPAGO = 31 REGION_ALZADAAL = 32 REGION_RONFAURE_FRONT = 33 REGION_NORVALLEN_FRONT = 34 REGION_GUSTABERG_FRONT = 35 REGION_DERFLAND_FRONT = 36 REGION_SARUTA_FRONT = 37 REGION_ARAGONEAU_FRONT = 38 REGION_FAUREGANDI_FRONT = 39 REGION_VALDEAUNIA_FRONT = 40 REGION_ABYSSEA = 41 REGION_THE_THRESHOLD = 42 REGION_ABDHALJS = 43 REGION_ADOULIN_ISLANDS = 44 REGION_EAST_ULBUKA = 45 REGION_UNKNOWN = 255 ----------------------------------- -- SetExplorerMoogles ---------------------------------- function SetExplorerMoogles(moogle) if (EXPLORER_MOOGLE == 1) then local npc = GetNPCByID(moogle); if (npc == nil) then printf("'SetExplorerMoogles' Error trying to load undefined npc (%d)", moogle); else npc:setStatus(0); end end end; ----------------------------------- -- SetRespawnTime ---------------------------------- function SetRespawnTime(id, minTime, maxTime) -- This function is redundant should place the mob:setRespawnTime() and UpdateNMSpawnPoint back in the individual zones. -- Having this global just uses 3 functions where only 2 were needed. local mob = GetMobByID(id); if (mob == nil) then printf("'SetTimedSpawns' Error trying to load undefined mob (%d)", id); else UpdateNMSpawnPoint(id); mob:setRespawnTime(math.random((minTime),(maxTime))); end end
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/spells/bluemagic/body_slam.lua
35
1710
----------------------------------------- -- Spell: Body Slam -- Delivers an area attack. Damage varies with TP -- Spell cost: 74 MP -- Monster Type: Dragon -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: VIT+1, MP+5 -- Level: 62 -- Casting Time: 1 seconds -- Recast Time: 27.75 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: Max HP Boost ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.5; params.tp150 = 1.5; params.tp300 = 1.5; params.azuretp = 1.5; params.duppercap = 75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
wskplho/sl4a
lua/luasocket/samples/lpr.lua
59
1574
local lp = require("socket.lp") local function usage() print('\nUsage: lua lpr.lua [filename] [keyword=val...]\n') print('Valid keywords are :') print( ' host=remote host or IP address (default "localhost")\n' .. ' queue=remote queue or printer name (default "printer")\n' .. ' port=remote port number (default 515)\n' .. ' user=sending user name\n' .. ' format=["binary" | "text" | "ps" | "pr" | "fortran"] (default "binary")\n' .. ' banner=true|false\n' .. ' indent=number of columns to indent\n' .. ' mail=email of address to notify when print is complete\n' .. ' title=title to use for "pr" format\n' .. ' width=width for "text" or "pr" formats\n' .. ' class=\n' .. ' job=\n' .. ' name=\n' .. ' localbind=true|false\n' ) return nil end if not arg or not arg[1] then return usage() end do local opt = {} local pat = "[%s%c%p]*([%w]*)=([\"]?[%w%s_!@#$%%^&*()<>:;]+[\"]\?\.?)" for i = 2, table.getn(arg), 1 do string.gsub(arg[i], pat, function(name, value) opt[name] = value end) end if not arg[2] then return usage() end if arg[1] ~= "query" then opt.file = arg[1] r,e=lp.send(opt) io.stdout:write(tostring(r or e),'\n') else r,e=lp.query(opt) io.stdout:write(tostring(r or e), '\n') end end -- trivial tests --lua lp.lua lp.lua queue=default host=localhost --lua lp.lua lp.lua queue=default host=localhost format=binary localbind=1 --lua lp.lua query queue=default host=localhost
apache-2.0
ld-test/many2one
test/many2one.lua
2
3948
-- many2one lua program to combine many lua files (linked by require) to one lua file for easy distribution -- Written by Milind Gupta -- For usage and questions visit http://milindsweb.amved.com/Many2One.html -- The way it does is to read all files and convert them to strings and to replace the require for each file with a special -- require that uses loadstring rather than loadfile function fileTitle(path) -- Find the name of the file without extension (that would be in Lua) local strVar local intVar1 = -1 for intVar = #path,1,-1 do if string.sub(path, intVar, intVar) == "." then intVar1 = intVar end if string.sub(path, intVar, intVar) == "\\" or string.sub(path, intVar, intVar) == "/" then strVar = string.sub(path, intVar + 1, intVar1-1) break end end if not strVar then if intVar1 ~= -1 then strVar = path:sub(1,intVar1-1) else strVar = path end end return strVar end local luaCode = {} local args = {...} local configFile = args[1] or "Config.lua" local f=io.open(configFile,"r") if f~=nil then f:close() -- load the configuration file dofile(configFile) if not fileList then print("No fileList table defined by the configuration file. Exiting") else local mf = mainFile or fileList[1] for i = 1,#fileList do -- Convert all files except the main file to strings if fileList[i] ~= mf then f = io.open(fileList[i],"r") if f ~=nil then local fileStr = f:read("*a") luaCode[fileTitle(fileList[i])] = fileStr f:close() end end end -- for i = 1,#fileList do -- Add the files in the begining of the main file local mainFilePre if loadstring then mainFilePre = [[__MANY2ONEFILES={} function requireLuaString(str) if not package.loaded[str] then package.loaded[str] = true local res = loadstring(__MANY2ONEFILES[str]) res = res(str) if res ~= nil then package.loaded[str] = res _G[str] = str end end return package.loaded[str] end ]] else mainFilePre = [[__MANY2ONEFILES={} function requireLuaString(str) if not package.loaded[str] then package.loaded[str] = true local res = load(__MANY2ONEFILES[str]) res = res(str) if res ~= nil then package.loaded[str] = res end end return package.loaded[str] end ]] end local addedFiles = {} -- Now find and replace require in all the read files with the custom code for k,v in pairs(luaCode) do local added = nil for k1,v1 in pairs(luaCode) do local pre,post = v:find("require%([%\"%']"..k1.."[%\"%']%)") if pre and not added then luaCode[k] = "local requireLuaString = requireLuaString\n"..v end if pre then luaCode[k] = luaCode[k]:gsub("require%([%\"%']"..k1.."[%\"%']%)","requireLuaString('"..k1.."')") if not addedFiles[k1] then addedFiles[k1] = true end end end end -- Add all the required files in the beginning of Main file in MailFilePre for k,v in pairs(addedFiles) do mainFilePre = mainFilePre.."__MANY2ONEFILES['"..k.."']="..string.format("%q",luaCode[k]).."\n" end -- Now write the main code output file local of = outputFile or "output.lua" local fo = io.open(of,"w+") f = io.open(mf,"r") local mainFileStr = f:read("*a") f:close() -- Replace all require in main file with custom code for k,v in pairs(luaCode) do local pre,post = mainFileStr:find("require%([%\"%']"..k.."[%\"%']%)") if pre then mainFileStr = mainFileStr:gsub("require%([%\"%']"..k.."[%\"%']%)","requireLuaString('"..k.."')") if not addedFiles[k] then mainFilePre = mainFilePre.."__MANY2ONEFILES['"..k.."']="..string.format("%q",v).."\n" addedFiles[k] = true end end end mainFileStr = mainFilePre..mainFileStr fo:write(mainFileStr) fo:close() end -- if not fileList then ends else print("No Configuration file found. Exiting.") end -- if f~=nil then ends
mit
pedrus/dota-ra2
game/dota_addons/ra2/scripts/vscripts/builder.lua
1
6303
-- A build ability is used (not yet confirmed) function Build( event ) local caster = event.caster local ability = event.ability local ability_name = ability:GetAbilityName() local building_name = ability:GetAbilityKeyValues()['UnitName'] local gold_cost = ability:GetGoldCost(1) local hero = caster:IsRealHero() and caster or caster:GetOwner() local playerID = hero:GetPlayerID() print(ability.unit) -- If the ability has an AbilityGoldCost, it's impossible to not have enough gold the first time it's cast -- Always refund the gold here, as the building hasn't been placed yet hero:ModifyGold(gold_cost, false, 0) -- Makes a building dummy and starts panorama ghosting BuildingHelper:AddBuilding(event) -- Additional checks to confirm a valid building position can be performed here event:OnPreConstruction(function(vPos) -- Check for minimum height if defined if not BuildingHelper:MeetsHeightCondition(vPos) then BuildingHelper:print("Failed placement of " .. building_name .." - Placement is below the min height required") SendErrorMessage(playerID, "#error_invalid_build_position") return false end -- If not enough resources to queue, stop if PlayerResource:GetGold(playerID) < gold_cost then BuildingHelper:print("Failed placement of " .. building_name .." - Not enough gold!") SendErrorMessage(playerID, "#error_not_enough_gold") return false end return true end) -- Position for a building was confirmed and valid event:OnBuildingPosChosen(function(vPos) -- Spend resources hero:ModifyGold(-gold_cost, false, 0) -- Play a sound EmitSoundOnClient("DOTA_Item.ObserverWard.Activate", PlayerResource:GetPlayer(playerID)) end) -- The construction failed and was never confirmed due to the gridnav being blocked in the attempted area event:OnConstructionFailed(function() local playerTable = BuildingHelper:GetPlayerTable(playerID) local building_name = playerTable.activeBuilding BuildingHelper:print("Failed placement of " .. building_name) end) -- Cancelled due to ClearQueue event:OnConstructionCancelled(function(work) local building_name = work.name BuildingHelper:print("Cancelled construction of " .. building_name) -- Refund resources for this cancelled work if work.refund then hero:ModifyGold(gold_cost, false, 0) end end) -- A building unit was created event:OnConstructionStarted(function(unit) BuildingHelper:print("Started construction of " .. unit:GetUnitName() .. " " .. unit:GetEntityIndex()) -- Play construction sound -- If it's an item-ability and has charges, remove a charge or remove the item if no charges left if ability.GetCurrentCharges and not ability:IsPermanent() then local charges = ability:GetCurrentCharges() charges = charges-1 if charges == 0 then ability:RemoveSelf() else ability:SetCurrentCharges(charges) end end -- Units can't attack while building unit.original_attack = unit:GetAttackCapability() unit:SetAttackCapability(DOTA_UNIT_CAP_NO_ATTACK) -- Give item to cancel unit.item_building_cancel = CreateItem("item_building_cancel", hero, hero) if unit.item_building_cancel then unit:AddItem(unit.item_building_cancel) unit.gold_cost = gold_cost end -- FindClearSpace for the builder FindClearSpaceForUnit(caster, caster:GetAbsOrigin(), true) caster:AddNewModifier(caster, nil, "modifier_phased", {duration=0.03}) -- Remove invulnerability on npc_dota_building baseclass unit:RemoveModifierByName("modifier_invulnerable") end) -- A building finished construction event:OnConstructionCompleted(function(unit) BuildingHelper:print("Completed construction of " .. unit:GetUnitName() .. " " .. unit:GetEntityIndex()) local player = PlayerResource:GetPlayer(playerID) player:OnBuildingPlaced(unit) -- Play construction complete sound -- Remove the item if unit.item_building_cancel then UTIL_Remove(unit.item_building_cancel) end -- Give the unit their original attack capability unit:SetAttackCapability(unit.original_attack) local location = unit:GetAbsOrigin() local grid = unit:GetKeyValue("Grid") if grid and grid["Allowed"] then local size = grid["Allowed"]["Square"] or 0 BuildingHelper:AddGridType(size, location, "ALLOWED") unit:AddNewModifier(unit, nil, "modifier_grid_allowed", {}) end end) -- These callbacks will only fire when the state between below half health/above half health changes. -- i.e. it won't fire multiple times unnecessarily. event:OnBelowHalfHealth(function(unit) BuildingHelper:print(unit:GetUnitName() .. " is below half health.") end) event:OnAboveHalfHealth(function(unit) BuildingHelper:print(unit:GetUnitName().. " is above half health.") end) end -- Called when the Cancel ability-item is used function CancelBuilding( keys ) local building = keys.unit local hero = building:GetOwner() local playerID = building:GetPlayerOwnerID() BuildingHelper:print("CancelBuilding "..building:GetUnitName().." "..building:GetEntityIndex()) -- Refund here if building.gold_cost then hero:ModifyGold(building.gold_cost, false, 0) end -- Eject builder local builder = building.builder_inside if builder then BuildingHelper:ShowBuilder(builder) end building:ForceKill(true) --This will call RemoveBuilding end -- Requires notifications library from bmddota/barebones function SendErrorMessage( pID, string ) Notifications:ClearBottom(pID) Notifications:Bottom(pID, {text=string, style={color='#E62020'}, duration=2}) EmitSoundOnClient("General.Cancel", PlayerResource:GetPlayer(pID)) end
mit
jthomasbarry/aafmt
archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/control/Distances.lua
3
11636
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/control/Distances.lua,v 1.5 2013/05/23 20:01:25 tantau Exp $ local declare = require "pgf.gd.interface.InterfaceToAlgorithms".declare local lib = require "pgf.gd.lib" --- -- @section subsection {Padding and Node Distances} -- -- \label{subsection-gd-dist-pad} -- -- In many drawings, you may wish to specify how ``near'' two nodes should -- be placed by a graph drawing algorithm. Naturally, this depends -- strongly on the specifics of the algorithm, but there are a number of -- general keys that will be used by many algorithms. -- -- There are different kinds of objects for which you can specify -- distances and paddings: -- -- \begin{itemize} -- \item You specify the ``natural'' distance between nodes -- connected by an edge using |node distance|, which is also available in -- normal \tikzname\ albeit for a slightly different purpose. However, -- not every algorithm will (or can) honour the key; see the description -- of each algorithm what it will ``make of this option''. -- \item A number of graph drawing algorithms arrange nodes in layers -- (or levels); we refer -- to the nodes on the same layer as siblings (although, in a tree, -- siblings are only nodes with the same parent; nevertheless we use -- ``sibling'' loosely also for nodes that are more like ``cousins''). -- \item When a graph consists of several connected component, many graph -- drawing algorithms will layout these components individually. The -- different components will then be arranged next to each other, see -- Section~\ref{section-gd-packing} for the details, such that between -- the nodes of any two components a padding is avaiable. -- \end{itemize} -- -- @end --- declare { key = "node distance", type = "length", initial = "1cm", summary = [[" This is minimum distance that the centers of nodes connected by an edge should have. It will not always be possible to satisfy this desired distance, for instance in case the nodes are too big. In this case, the \meta{length} is just considered as a lower bound. "]], examples = [[" \begin{tikzpicture} \graph [simple necklace layout, node distance=1cm, node sep=0pt, nodes={draw,circle,as=.}] { 1 -- 2 [minimum size=2cm] -- 3 -- 4 -- 5 -- 6 -- 7 --[orient=up] 8 }; \draw [red,|-|] (1.center) -- ++(0:1cm); \draw [red,|-|] (5.center) -- ++(180:1cm); \end{tikzpicture} "]] } --- declare { key = "node pre sep", type = "length", initial = ".333em", summary = [[" This is a minimum ``padding'' or ``separation'' between the border of nodes connected by an edge. Thus, if nodes are so big that nodes with a distance of |node distance| would overlap (or just come with \meta{dimension} distance of one another), their distance is enlarged so that this distance is still satisfied. The |pre| means that the padding is added to the node ``at the front.'' This make sense only for some algorithms, like for a simple necklace layout. "]], examples = { [[" \tikz \graph [simple necklace layout, node distance=0cm, nodes={circle,draw}] { 1--2--3--4--5--1 }; "]], [[" \tikz \graph [simple necklace layout, node distance=0cm, node sep=0mm, nodes={circle,draw}] { 1--2--3[node pre sep=5mm]--4--5[node pre sep=1mm]--1 }; "]] } } --- declare { key = "node post sep", type = "length", initial = ".333em", summary = [[" Works like |node pre sep|. "]] } --- -- @param length A length. declare { key = "node sep", type = "length", use = { { key = "node pre sep", value = function(v) return v/2 end }, { key = "node post sep", value = function(v) return v/2 end }, }, summary = [[" A shorthand for setting both |node pre sep| and |node post sep| to $\meta{length}/2$. "]] } --- declare { key = "level distance", type = "length", initial = "1cm", summary = [[" This is minimum distance that the centers of nodes on one level should have from the centers of nodes on the next level. It will not always be possible to satisfy this desired distance, for instance in case the nodes are too big. In this case, the \meta{length} is just considered as a lower bound. "]], examples = [[" \begin{tikzpicture}[inner sep=2pt] \draw [help lines] (0,0) grid (3.5,2); \graph [layered layout, level distance=1cm, level sep=0] { 1 [x=1,y=2] -- 2 -- 3 -- 1 }; \graph [layered layout, level distance=5mm, level sep=0] { 1 [x=3,y=2] -- 2 -- 3 -- 1, 3 -- {4,5} -- 6 -- 3 }; \end{tikzpicture} "]] } --- declare { key = "layer distance", type = "length", use = { { key = "level distance", value = lib.id }, }, summary = "An alias for |level distance|" } --- declare { key = "level pre sep", type = "length", initial = ".333em", summary = [[" This is a minimum ``padding'' or ``separation'' between the border of the nodes on a level to any nodes on the previous level. Thus, if nodes are so big that nodes on consecutive levels would overlap (or just come with \meta{lrngth} distance of one another), their distance is enlarged so that this distance is still satisfied. If a node on the previous level also has a |level post sep|, this post padding and the \meta{dimension} add up. Thus, these keys behave like the ``padding'' keys rather than the ``margin'' key of cascading style sheets. "]], examples = [[" \begin{tikzpicture}[inner sep=2pt, level sep=0pt, sibling distance=0pt] \draw [help lines] (0,0) grid (3.5,2); \graph [layered layout, level distance=0cm, nodes=draw] { 1 [x=1,y=2] -- {2,3[level pre sep=1mm],4[level pre sep=5mm]} -- 5 }; \graph [layered layout, level distance=0cm, nodes=draw] { 1 [x=3,y=2] -- {2,3,4} -- 5[level pre sep=5mm] }; \end{tikzpicture} "]] } --- declare { key = "level post sep", type = "length", initial = ".333em", summary = [[" Works like |level pre sep|. "]] } --- declare { key = "layer pre sep", type = "length", use = { { key = "level pre sep", value = lib.id }, }, summary = "An alias for |level pre sep|." } --- declare { key = "layer post sep", type = "length", use = { { key = "level post sep", value = lib.id }, }, summary = "An alias for |level post sep|." } --- -- @param length A length declare { key = "level sep", type = "length", use = { { key = "level pre sep", value = function (v) return v/2 end }, { key = "level post sep", value = function (v) return v/2 end }, }, summary = [[" A shorthand for setting both |level pre sep| and |level post sep| to $\meta{length}/2$. Note that if you set |level distance=0| and |level sep=1em|, you get a layout where any two consecutive layers are ``spaced apart'' by |1em|. "]] } --- declare { key = "layer sep", type = "number", use = { { key = "level sep", value = lib.id }, }, summary = "An alias for |level sep|." } --- declare { key = "sibling distance", type = "length", initial = "1cm", summary = [[" This is minimum distance that the centers of node should have to the center of the next node on the same level. As for levels, this is just a lower bound. For some layouts, like a simple necklace layout, the \meta{length} is measured as the distance on the circle. "]], examples = { [[" \tikz \graph [tree layout, sibling distance=1cm, nodes={circle,draw}] { 1--{2,3,4,5} }; "]], [[" \tikz \graph [tree layout, sibling distance=0cm, sibling sep=0pt, nodes={circle,draw}] { 1--{2,3,4,5} }; "]], [[" \tikz \graph [tree layout, sibling distance=0cm, sibling sep=0pt, nodes={circle,draw}] { 1--{2,3[sibling distance=1cm],4,5} }; "]] } } --- declare { key = "sibling pre sep", type = "length", initial = ".333em", summary = [[" Works like |level pre sep|, only for siblings. "]], examples = [[" \tikz \graph [tree layout, sibling distance=0cm, nodes={circle,draw}, sibling sep=0pt] { 1--{2,3[sibling pre sep=1cm],4,5} }; "]] } --- declare { key = "sibling post sep", type = "length", initial = ".333em", summary = [[" Works like |sibling pre sep|. "]] } --- -- @param length A length declare { key = "sibling sep", type = "length", use = { { key = "sibling pre sep", value = function(v) return v/2 end }, { key = "sibling post sep", value = function(v) return v/2 end }, }, summary = [[" A shorthand for setting both |sibling pre sep| and |sibling post sep| to $\meta{length}/2$. "]] } --- declare { key = "part distance", type = "length", initial = "1.5cm", summary = [[" This is minimum distance between the centers of ``parts'' of a graph. What a ``part'' is depends on the algorithm. "]] } --- declare { key = "part pre sep", type = "length", initial = "1em", summary = "A pre-padding for parts." } --- declare { key = "part post sep", type = "length", initial = "1em", summary = "A post-padding for pars." } --- -- @param length A length declare { key = "part sep", type = "length", use = { { key = "part pre sep", value = function(v) return v/2 end }, { key = "part post sep", value = function(v) return v/2 end }, }, summary = [[" A shorthand for setting both |part pre sep| and |part post sep| to $\meta{length}/2$. "]] } --- declare { key = "component sep", type = "length", initial = "1.5em", summary = [[" This is pading between the bounding boxes that nodes of different connected components will have when they are placed next to each other. "]], examples = { [[" \tikz \graph [binary tree layout, sibling distance=4mm, level distance=8mm, components go right top aligned, component sep=1pt, nodes=draw] { 1 -> 2 -> {3->4[second]->5,6,7}; a -> b[second] -> c[second] -> d -> e; x -> y[second] -> z -> u[second] -> v; }; "]], [[" \tikz \graph [binary tree layout, sibling distance=4mm, level distance=8mm, components go right top aligned, component sep=1em, nodes=draw] { 1 -> 2 -> {3->4[second]->5,6,7}; a -> b[second] -> c[second] -> d -> e; x -> y[second] -> z -> u[second] -> v; }; "]] } } --- declare { key = "component distance", type = "length", initial = "2cm", summary = [[" This is the minimum distance between the centers of bounding boxes of connected components when they are placed next to each other. (Not used, currently.) "]] } return Distances
gpl-2.0
samijon/s
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
shahabsaf1/fucker
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/globals/items/plate_of_urchin_sushi.lua
12
1640
----------------------------------------- -- ID: 5151 -- Item: plate_of_urchin_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 40 -- Strength 1 -- Vitality 5 -- Accuracy % 15 (cap 72) -- Ranged ACC % 15 (cap 72) ----------------------------------------- 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,5151); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 40); target:addMod(MOD_STR, 1); target:addMod(MOD_VIT, 5); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 72); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 72); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 40); target:delMod(MOD_STR, 1); target:delMod(MOD_VIT, 5); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 72); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 72); end;
gpl-3.0
rafradek/wire
lua/wire/timedpairs.lua
17
3271
-- Timedpairs by Grocel. (Rewrite by Divran) -- It allows you to go through long tables, but without game freezing. -- Its like a for-pairs loop. -- -- How to use: -- WireLib.Timedpairs(string unique name, table, number ticks done at once, function tickcallback[, function endcallback, ...]) -- -- tickcallback is called every tick, it ticks for each KeyValue of the table. -- Its arguments are the current key and value. -- Return false in the tickcallback function to break the loop. -- tickcallback(key, value, ...) -- -- endcallback is called after the last tickcallback has been called. -- Its arguments are the same as the last arguments of WireLib.Timedpairs -- endcallback(lastkey, lastvalue, ...) if (!WireLib) then return end local next = next local pairs = pairs local unpack = unpack local pcall = pcall local functions = {} function WireLib.TimedpairsGetTable() return functions end function WireLib.TimedpairsStop(name) functions[name] = nil end local function copy( t ) -- custom table copy function to convert to numerically indexed table local ret = {} for k,v in pairs( t ) do ret[#ret+1] = { key = k, value = v } end return ret end local function Timedpairs() if not next(functions) then return end local toremove = {} for name, data in pairs( functions ) do for i=1,data.step do data.currentindex = data.currentindex + 1 -- increment index counter local lookup = data.lookup or {} if data.currentindex <= #lookup then -- If there are any more values.. local kv = lookup[data.currentindex] or {} -- Get the current key and value local ok, err = xpcall( data.callback, debug.traceback, kv.key, kv.value, unpack(data.args) ) -- DO EET if not ok then -- oh noes WireLib.ErrorNoHalt( "Error in Timedpairs '" .. name .. "': " .. err ) toremove[#toremove+1] = name break elseif err == false then -- They returned false inside the function toremove[#toremove+1] = name break end else -- Out of keys. Entire table looped if data.endcallback then -- If we had any end callback function local kv = lookup[data.currentindex-1] or {} -- get previous key & value local ok, err = xpcall( data.endcallback, debug.traceback, kv.key, kv.value, unpack(data.args) ) if not ok then WireLib.ErrorNoHalt( "Error in Timedpairs '" .. name .. "' (in end function): " .. err ) end end toremove[#toremove+1] = name break end end end for i=1,#toremove do -- Remove all that were flagged for removal functions[toremove[i]] = nil end end if (CLIENT) then hook.Add("PostRenderVGUI", "WireLib_Timedpairs", Timedpairs) // Doesn't get paused in single player. Can be important for vguis. else hook.Add("Think", "WireLib_Timedpairs", Timedpairs) // Servers still uses Think. end function WireLib.Timedpairs(name,tab,step,callback,endcallback,...) functions[name] = { lookup = copy(tab), step = step, currentindex = 0, callback = callback, endcallback = endcallback, args = {...} } end function WireLib.Timedcall(callback,...) // calls the given function like simple timer, but isn't affected by game pausing. local dummytab = {true} WireLib.Timedpairs("Timedcall_"..tostring(dummytab),dummytab,1,function(k, v, ...) callback(...) end,nil,...) end
apache-2.0
rafradek/wire
lua/wire/gates/memory.lua
17
11088
--[[ Memory Gates ]] GateActions("Memory") GateActions["latch"] = { name = "Latch (Edge triggered)", inputs = { "Data", "Clk" }, output = function(gate, Data, Clk) local clk = (Clk > 0) if (gate.PrevValue ~= clk) then gate.PrevValue = clk if (clk) then gate.LatchStore = Data end end return gate.LatchStore or 0 end, reset = function(gate) gate.LatchStore = 0 gate.PrevValue = nil end, label = function(Out, Data, Clk) return "Latch Data:"..Data.." Clock:"..Clk.." = "..Out end } GateActions["dlatch"] = { name = "D-Latch", inputs = { "Data", "Clk" }, output = function(gate, Data, Clk) if (Clk > 0) then gate.LatchStore = Data end return gate.LatchStore or 0 end, reset = function(gate) gate.LatchStore = 0 end, label = function(Out, Data, Clk) return "D-Latch Data:"..Data.." Clock:"..Clk.." = "..Out end } GateActions["srlatch"] = { name = "SR-Latch", inputs = { "S", "R" }, output = function(gate, S, R) if (S > 0) and (R <= 0) then gate.LatchStore = 1 elseif (S <= 0) and (R > 0) then gate.LatchStore = 0 end return gate.LatchStore end, reset = function(gate) gate.LatchStore = 0 end, label = function(Out, S, R) return "S:"..S.." R:"..R.." == "..Out end } GateActions["rslatch"] = { name = "RS-Latch", inputs = { "S", "R" }, output = function(gate, S, R) if (S > 0) and (R < 1) then gate.LatchStore = 1 elseif (R > 0) then gate.LatchStore = 0 end return gate.LatchStore end, reset = function(gate) gate.LatchStore = 0 end, label = function(Out, S, R) return "S:"..S.." R:"..R.." == "..Out end } GateActions["toggle"] = { name = "Toggle (Edge triggered)", inputs = { "Clk", "OnValue", "OffValue" }, output = function(gate, Clk, OnValue, OffValue) local clk = (Clk > 0) if (gate.PrevValue ~= clk) then gate.PrevValue = clk if (clk) then gate.LatchStore = (not gate.LatchStore) end end if (gate.LatchStore) then return OnValue end return OffValue end, reset = function(gate) gate.LatchStore = false gate.PrevValue = nil end, label = function(Out, Clk, OnValue, OffValue) return "Off:"..OffValue.." On:"..OnValue.." Clock:"..Clk.." = "..Out end } GateActions["wom4"] = { name = "Write Only Memory(4 store)", inputs = { "Clk", "AddrWrite", "Data" }, output = function( gate, Clk, AddrWrite, Data ) AddrWrite = math.floor(tonumber(AddrWrite)) if ( Clk > 0 ) then if ( AddrWrite >= 0 ) and ( AddrWrite < 4 ) then gate.LatchStore[AddrWrite] = Data end end return 0 end, reset = function( gate ) gate.LatchStore = {} for i = 0, 3 do gate.LatchStore[i] = 0 end end, label = function() return "Write Only Memory - 4 store" end } GateActions["ram8"] = { name = "RAM(8 store)", inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" }, output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset ) if (Reset > 0) then gate.LatchStore = {} end AddrRead = math.floor(tonumber(AddrRead)) AddrWrite = math.floor(tonumber(AddrWrite)) if (Clk > 0) then if (AddrWrite >= 0) and (AddrWrite < 8) then gate.LatchStore[AddrWrite] = Data end end if (AddrRead < 0) or (AddrRead >= 8) then return 0 end return gate.LatchStore[AddrRead] or 0 end, reset = function(gate) gate.LatchStore = {} end, label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset) return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset.. "\nReadAddr:"..AddrRead.." = "..Out end, ReadCell = function(dummy,gate,Address) if (Address < 0) || (Address >= 8) then return 0 else return gate.LatchStore[Address] or 0 end end, WriteCell = function(dummy,gate,Address,value) if (Address < 0) || (Address >= 8) then return false else gate.LatchStore[Address] = value return true end end } GateActions["ram64"] = { name = "RAM(64 store)", inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" }, output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset ) if (Reset > 0) then gate.LatchStore = {} end AddrRead = math.floor(tonumber(AddrRead)) AddrWrite = math.floor(tonumber(AddrWrite)) if (Clk > 0) then if (AddrWrite < 64) then gate.LatchStore[AddrWrite] = Data end end return gate.LatchStore[AddrRead] or 0 end, reset = function(gate) gate.LatchStore = {} end, label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset) return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset.. "\nReadAddr:"..AddrRead.." = "..Out end, ReadCell = function(dummy,gate,Address) if (Address < 0) || (Address >= 64) then return 0 else return gate.LatchStore[Address] or 0 end end, WriteCell = function(dummy,gate,Address,value) if (Address < 0) || (Address >= 64) then return false else gate.LatchStore[Address] = value return true end end } GateActions["ram1k"] = { name = "RAM(1kb)", inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" }, output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset ) if (Reset > 0) then gate.LatchStore = {} end AddrRead = math.floor(tonumber(AddrRead)) AddrWrite = math.floor(tonumber(AddrWrite)) if (Clk > 0) then if (AddrWrite < 1024) then gate.LatchStore[AddrWrite] = Data end end return gate.LatchStore[AddrRead] or 0 end, reset = function(gate) gate.LatchStore = {} end, label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset ) return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset.. "\nReadAddr:"..AddrRead.." = "..Out end, ReadCell = function(dummy,gate,Address) if (Address < 0) || (Address >= 1024) then return 0 else return gate.LatchStore[Address] or 0 end end, WriteCell = function(dummy,gate,Address,value) if (Address < 0) || (Address >= 1024) then return false else gate.LatchStore[Address] = value return true end end } GateActions["ram32k"] = { name = "RAM(32kb)", inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" }, output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset ) if (Reset > 0) then gate.LatchStore = {} end AddrRead = math.floor(tonumber(AddrRead)) AddrWrite = math.floor(tonumber(AddrWrite)) if (Clk > 0) then if (AddrWrite < 32768) then gate.LatchStore[AddrWrite] = Data end end return gate.LatchStore[AddrRead] or 0 end, reset = function(gate) gate.LatchStore = {} end, label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset ) return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset.. "\nReadAddr:"..AddrRead.." = "..Out end, ReadCell = function(dummy,gate,Address) if (Address < 0) || (Address >= 32768) then return 0 else return gate.LatchStore[Address] or 0 end end, WriteCell = function(dummy,gate,Address,value) if (Address < 0) || (Address >= 32768) then return false else gate.LatchStore[Address] = value return true end end } GateActions["ram128k"] = { name = "RAM(128kb)", inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" }, output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset ) if (Reset > 0) then gate.LatchStore = {} end AddrRead = math.floor(tonumber(AddrRead)) AddrWrite = math.floor(tonumber(AddrWrite)) if (Clk > 0) then if (AddrWrite < 131072) then gate.LatchStore[AddrWrite] = Data end end return gate.LatchStore[AddrRead] or 0 end, reset = function(gate) gate.LatchStore = {} end, label = function(Out, Clk, AddrRead, AddrWrite, Data) return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.. "\nReadAddr:"..AddrRead.." = "..Out end, ReadCell = function(dummy,gate,Address) if (Address < 0) || (Address >= 131072) then return 0 else return gate.LatchStore[Address] or 0 end end, WriteCell = function(dummy,gate,Address,value) if (Address < 0) || (Address >= 131072) then return false else gate.LatchStore[Address] = value return true end end } GateActions["ram64x64"] = { name = "RAM(64x64 store)", inputs = { "Clk", "AddrReadX", "AddrReadY", "AddrWriteX", "AddrWriteY", "Data", "Reset" }, output = function(gate, Clk, AddrReadX, AddrReadY, AddrWriteX, AddrWriteY, Data, Reset ) if (Reset > 0) then gate.LatchStore = {} end AddrReadX = math.floor(tonumber(AddrReadX)) AddrReadY = math.floor(tonumber(AddrReadY)) AddrWriteX = math.floor(tonumber(AddrWriteX)) AddrWriteY = math.floor(tonumber(AddrWriteY)) if (Clk > 0) then if (AddrWriteX >= 0) and (AddrWriteX < 64) or (AddrWriteY >= 0) and (AddrWriteY < 64) then gate.LatchStore[AddrWriteX + AddrWriteY*64] = Data end end if (AddrReadX < 0) or (AddrReadX >= 64) or (AddrReadY < 0) or (AddrReadY >= 64) then return 0 end return gate.LatchStore[AddrReadX + AddrReadY*64] or 0 end, reset = function(gate) gate.LatchStore = {} end, label = function(Out, Clk, AddrReadX, AddrReadY, AddrWriteX, AddrWriteY, Data, Reset) return "WriteAddr:"..AddrWriteX..", "..AddrWriteY.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset.. "\nReadAddr:"..AddrReadX..", "..AddrReadY.." = "..Out end, ReadCell = function(dummy,gate,Address) if (Address < 0) || (Address >= 4096) then return 0 else return gate.LatchStore[Address] or 0 end end, WriteCell = function(dummy,gate,Address,value) if (Address < 0) || (Address >= 4096) then return false else gate.LatchStore[Address] = value return true end end } GateActions["udcounter"] = { name = "Up/Down Counter", inputs = { "Increment", "Decrement", "Clk", "Reset"}, output = function(gate, Inc, Dec, Clk, Reset) local lInc = (Inc > 0) local lDec = (Dec > 0) local lClk = (Clk > 0) local lReset = (Reset > 0) if ((gate.PrevInc ~= lInc || gate.PrevDec ~= lDec || gate.PrevClk ~= lClk) && lClk) then if (lInc) and (!lDec) and (!lReset) then gate.countStore = (gate.countStore or 0) + 1 elseif (!lInc) and (lDec) and (!lReset) then gate.countStore = (gate.countStore or 0) - 1 end gate.PrevInc = lInc gate.PrevDec = lDec gate.PrevClk = lClk end if (lReset) then gate.countStore = 0 end return gate.countStore end, label = function(Out, Inc, Dec, Clk, Reset) return "Increment:"..Inc.." Decrement:"..Dec.." Clk:"..Clk.." Reset:"..Reset.." = "..Out end } GateActions["togglewhile"] = { name = "Toggle While(Edge triggered)", inputs = { "Clk", "OnValue", "OffValue", "While" }, output = function(gate, Clk, OnValue, OffValue, While) local clk = (Clk > 0) if (While <= 0) then clk = false gate.LatchStore = false end if (gate.PrevValue ~= clk) then gate.PrevValue = clk if (clk) then gate.LatchStore = (not gate.LatchStore) end end if (gate.LatchStore) then return OnValue end return OffValue end, reset = function(gate) gate.LatchStore = 0 gate.PrevValue = nil end, label = function(Out, Clk, OnValue, OffValue, While) return "Off:"..OffValue.." On:"..OnValue.." Clock:"..Clk.." While:"..While.." = "..Out end } GateActions()
apache-2.0
pecio/PetHealth-Broker
Common/AceConfig-3.0/AceConfigRegistry-3.0/AceConfigRegistry-3.0.lua
2
12516
--- AceConfigRegistry-3.0 handles central registration of options tables in use by addons and modules.\\ -- Options tables can be registered as raw tables, OR as function refs that return a table.\\ -- Such functions receive three arguments: "uiType", "uiName", "appName". \\ -- * Valid **uiTypes**: "cmd", "dropdown", "dialog". This is verified by the library at call time. \\ -- * The **uiName** field is expected to contain the full name of the calling addon, including version, e.g. "FooBar-1.0". This is verified by the library at call time.\\ -- * The **appName** field is the options table name as given at registration time \\ -- -- :IterateOptionsTables() (and :GetOptionsTable() if only given one argument) return a function reference that the requesting config handling addon must call with valid "uiType", "uiName". -- @class file -- @name AceConfigRegistry-3.0 -- @release $Id: AceConfigRegistry-3.0.lua 1161 2017-08-12 14:30:16Z funkydude $ local CallbackHandler = LibStub("CallbackHandler-1.0") local MAJOR, MINOR = "AceConfigRegistry-3.0", 17 local AceConfigRegistry = LibStub:NewLibrary(MAJOR, MINOR) if not AceConfigRegistry then return end AceConfigRegistry.tables = AceConfigRegistry.tables or {} if not AceConfigRegistry.callbacks then AceConfigRegistry.callbacks = CallbackHandler:New(AceConfigRegistry) end -- Lua APIs local tinsert, tconcat = table.insert, table.concat local strfind, strmatch = string.find, string.match local type, tostring, select, pairs = type, tostring, select, pairs local error, assert = error, assert ----------------------------------------------------------------------- -- Validating options table consistency: AceConfigRegistry.validated = { -- list of options table names ran through :ValidateOptionsTable automatically. -- CLEARED ON PURPOSE, since newer versions may have newer validators cmd = {}, dropdown = {}, dialog = {}, } local function err(msg, errlvl, ...) local t = {} for i=select("#",...),1,-1 do tinsert(t, (select(i, ...))) end error(MAJOR..":ValidateOptionsTable(): "..tconcat(t,".")..msg, errlvl+2) end local isstring={["string"]=true, _="string"} local isstringfunc={["string"]=true,["function"]=true, _="string or funcref"} local istable={["table"]=true, _="table"} local ismethodtable={["table"]=true,["string"]=true,["function"]=true, _="methodname, funcref or table"} local optstring={["nil"]=true,["string"]=true, _="string"} local optstringfunc={["nil"]=true,["string"]=true,["function"]=true, _="string or funcref"} local optstringnumberfunc={["nil"]=true,["string"]=true,["number"]=true,["function"]=true, _="string, number or funcref"} local optnumber={["nil"]=true,["number"]=true, _="number"} local optmethod={["nil"]=true,["string"]=true,["function"]=true, _="methodname or funcref"} local optmethodfalse={["nil"]=true,["string"]=true,["function"]=true,["boolean"]={[false]=true}, _="methodname, funcref or false"} local optmethodnumber={["nil"]=true,["string"]=true,["function"]=true,["number"]=true, _="methodname, funcref or number"} local optmethodtable={["nil"]=true,["string"]=true,["function"]=true,["table"]=true, _="methodname, funcref or table"} local optmethodbool={["nil"]=true,["string"]=true,["function"]=true,["boolean"]=true, _="methodname, funcref or boolean"} local opttable={["nil"]=true,["table"]=true, _="table"} local optbool={["nil"]=true,["boolean"]=true, _="boolean"} local optboolnumber={["nil"]=true,["boolean"]=true,["number"]=true, _="boolean or number"} local basekeys={ type=isstring, name=isstringfunc, desc=optstringfunc, descStyle=optstring, order=optmethodnumber, validate=optmethodfalse, confirm=optmethodbool, confirmText=optstring, disabled=optmethodbool, hidden=optmethodbool, guiHidden=optmethodbool, dialogHidden=optmethodbool, dropdownHidden=optmethodbool, cmdHidden=optmethodbool, icon=optstringnumberfunc, iconCoords=optmethodtable, handler=opttable, get=optmethodfalse, set=optmethodfalse, func=optmethodfalse, arg={["*"]=true}, width=optstring, } local typedkeys={ header={}, description={ image=optstringnumberfunc, imageCoords=optmethodtable, imageHeight=optnumber, imageWidth=optnumber, fontSize=optstringfunc, }, group={ args=istable, plugins=opttable, inline=optbool, cmdInline=optbool, guiInline=optbool, dropdownInline=optbool, dialogInline=optbool, childGroups=optstring, }, execute={ image=optstringnumberfunc, imageCoords=optmethodtable, imageHeight=optnumber, imageWidth=optnumber, }, input={ pattern=optstring, usage=optstring, control=optstring, dialogControl=optstring, dropdownControl=optstring, multiline=optboolnumber, }, toggle={ tristate=optbool, image=optstringnumberfunc, imageCoords=optmethodtable, }, tristate={ }, range={ min=optnumber, softMin=optnumber, max=optnumber, softMax=optnumber, step=optnumber, bigStep=optnumber, isPercent=optbool, }, select={ values=ismethodtable, style={ ["nil"]=true, ["string"]={dropdown=true,radio=true}, _="string: 'dropdown' or 'radio'" }, control=optstring, dialogControl=optstring, dropdownControl=optstring, itemControl=optstring, }, multiselect={ values=ismethodtable, style=optstring, tristate=optbool, control=optstring, dialogControl=optstring, dropdownControl=optstring, }, color={ hasAlpha=optmethodbool, }, keybinding={ -- TODO }, } local function validateKey(k,errlvl,...) errlvl=(errlvl or 0)+1 if type(k)~="string" then err("["..tostring(k).."] - key is not a string", errlvl,...) end if strfind(k, "[%c\127]") then err("["..tostring(k).."] - key name contained control characters", errlvl,...) end end local function validateVal(v, oktypes, errlvl,...) errlvl=(errlvl or 0)+1 local isok=oktypes[type(v)] or oktypes["*"] if not isok then err(": expected a "..oktypes._..", got '"..tostring(v).."'", errlvl,...) end if type(isok)=="table" then -- isok was a table containing specific values to be tested for! if not isok[v] then err(": did not expect "..type(v).." value '"..tostring(v).."'", errlvl,...) end end end local function validate(options,errlvl,...) errlvl=(errlvl or 0)+1 -- basic consistency if type(options)~="table" then err(": expected a table, got a "..type(options), errlvl,...) end if type(options.type)~="string" then err(".type: expected a string, got a "..type(options.type), errlvl,...) end -- get type and 'typedkeys' member local tk = typedkeys[options.type] if not tk then err(".type: unknown type '"..options.type.."'", errlvl,...) end -- make sure that all options[] are known parameters for k,v in pairs(options) do if not (tk[k] or basekeys[k]) then err(": unknown parameter", errlvl,tostring(k),...) end end -- verify that required params are there, and that everything is the right type for k,oktypes in pairs(basekeys) do validateVal(options[k], oktypes, errlvl,k,...) end for k,oktypes in pairs(tk) do validateVal(options[k], oktypes, errlvl,k,...) end -- extra logic for groups if options.type=="group" then for k,v in pairs(options.args) do validateKey(k,errlvl,"args",...) validate(v, errlvl,k,"args",...) end if options.plugins then for plugname,plugin in pairs(options.plugins) do if type(plugin)~="table" then err(": expected a table, got '"..tostring(plugin).."'", errlvl,tostring(plugname),"plugins",...) end for k,v in pairs(plugin) do validateKey(k,errlvl,tostring(plugname),"plugins",...) validate(v, errlvl,k,tostring(plugname),"plugins",...) end end end end end --- Validates basic structure and integrity of an options table \\ -- Does NOT verify that get/set etc actually exist, since they can be defined at any depth -- @param options The table to be validated -- @param name The name of the table to be validated (shown in any error message) -- @param errlvl (optional number) error level offset, default 0 (=errors point to the function calling :ValidateOptionsTable) function AceConfigRegistry:ValidateOptionsTable(options,name,errlvl) errlvl=(errlvl or 0)+1 name = name or "Optionstable" if not options.name then options.name=name -- bit of a hack, the root level doesn't really need a .name :-/ end validate(options,errlvl,name) end --- Fires a "ConfigTableChange" callback for those listening in on it, allowing config GUIs to refresh. -- You should call this function if your options table changed from any outside event, like a game event -- or a timer. -- @param appName The application name as given to `:RegisterOptionsTable()` function AceConfigRegistry:NotifyChange(appName) if not AceConfigRegistry.tables[appName] then return end AceConfigRegistry.callbacks:Fire("ConfigTableChange", appName) end -- ------------------------------------------------------------------- -- Registering and retreiving options tables: -- validateGetterArgs: helper function for :GetOptionsTable (or, rather, the getter functions returned by it) local function validateGetterArgs(uiType, uiName, errlvl) errlvl=(errlvl or 0)+2 if uiType~="cmd" and uiType~="dropdown" and uiType~="dialog" then error(MAJOR..": Requesting options table: 'uiType' - invalid configuration UI type, expected 'cmd', 'dropdown' or 'dialog'", errlvl) end if not strmatch(uiName, "[A-Za-z]%-[0-9]") then -- Expecting e.g. "MyLib-1.2" error(MAJOR..": Requesting options table: 'uiName' - badly formatted or missing version number. Expected e.g. 'MyLib-1.2'", errlvl) end end --- Register an options table with the config registry. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param options The options table, OR a function reference that generates it on demand. \\ -- See the top of the page for info on arguments passed to such functions. -- @param skipValidation Skip options table validation (primarily useful for extremely huge options, with a noticeable slowdown) function AceConfigRegistry:RegisterOptionsTable(appName, options, skipValidation) if type(options)=="table" then if options.type~="group" then -- quick sanity checker error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - missing type='group' member in root group", 2) end AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl) errlvl=(errlvl or 0)+1 validateGetterArgs(uiType, uiName, errlvl) if not AceConfigRegistry.validated[uiType][appName] and not skipValidation then AceConfigRegistry:ValidateOptionsTable(options, appName, errlvl) -- upgradable AceConfigRegistry.validated[uiType][appName] = true end return options end elseif type(options)=="function" then AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl) errlvl=(errlvl or 0)+1 validateGetterArgs(uiType, uiName, errlvl) local tab = assert(options(uiType, uiName, appName)) if not AceConfigRegistry.validated[uiType][appName] and not skipValidation then AceConfigRegistry:ValidateOptionsTable(tab, appName, errlvl) -- upgradable AceConfigRegistry.validated[uiType][appName] = true end return tab end else error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - expected table or function reference", 2) end end --- Returns an iterator of ["appName"]=funcref pairs function AceConfigRegistry:IterateOptionsTables() return pairs(AceConfigRegistry.tables) end --- Query the registry for a specific options table. -- If only appName is given, a function is returned which you -- can call with (uiType,uiName) to get the table.\\ -- If uiType&uiName are given, the table is returned. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param uiType The type of UI to get the table for, one of "cmd", "dropdown", "dialog" -- @param uiName The name of the library/addon querying for the table, e.g. "MyLib-1.0" function AceConfigRegistry:GetOptionsTable(appName, uiType, uiName) local f = AceConfigRegistry.tables[appName] if not f then return nil end if uiType then return f(uiType,uiName,1) -- get the table for us else return f -- return the function end end
gpl-3.0
Afforess/Factorio-Stdlib
stdlib/event/modules/event_filters.lua
1
1341
--- Event Filters -- Predefined event filter functions -- @module Event.Filters local Filters = { entity = {}, player = {}, } function Filters.on_key(event_key, pattern) return function(event) local key = event and event[event_key] return key and key:match(pattern) end end function Filters.entity.name(event, pattern) local entity = event and (event.created_entity or event.entity) return entity.name:match(pattern) end function Filters.entity.type(event, pattern) local entity = event and (event.created_entity or event.entity) return entity.type:match(pattern) end function Filters.player.cursor_stack(event, pattern) local player = game.get_player(event.player_index) local stack = player.cursor_stack return stack and stack.valid_for_read and stack.name:match(pattern) end function Filters.gui(event, pattern) if event.element and event.element.valid then local match_str = event.element.name:match(pattern) if match_str then event.match = match_str event.state = event.name == defines.events.on_gui_checked_state_changed and event.element.state or nil event.text = event.name == defines.events.on_gui_text_changed and event.element.text or nil return match_str end end end return Filters
isc
bmichalo/MoonGen
examples/timestamping-tests/timestamps-software.lua
2
2527
--- Software timestamping precision test. local mg = require "dpdk" local ts = require "timestamping" local device = require "device" local hist = require "histogram" local memory = require "memory" local stats = require "stats" local timer = require "timer" local ffi = require "ffi" local PKT_SIZE = 60 local NUM_PKTS = 10^6 function master(txPort, rxPort, load) if not txPort or not rxPort or type(load) ~= "number" then errorf("usage: txPort rxPort load") end local txDev = device.config{port = txPort, rxQueues = 2, txQueues = 2} local rxDev = device.config{port = rxPort, rxQueues = 2, txQueues = 2} device.waitForLinks() txDev:getTxQueue(0):setRate(load) if load > 0 then mg.launchLua("loadSlave", txDev:getTxQueue(0)) end mg.launchLua("txTimestamper", txDev:getTxQueue(1)) mg.launchLua("rxTimestamper", rxDev:getRxQueue(1)) mg.waitForSlaves() end function loadSlave(queue) local mem = memory.createMemPool(function(buf) buf:getEthPacket():fill{ } end) local bufs = mem:bufArray() local ctr = stats:newDevTxCounter("Load Traffic", queue.dev, "plain") while mg.running() do bufs:alloc(PKT_SIZE) queue:send(bufs) ctr:update() end ctr:finalize() end function txTimestamper(queue) local mem = memory.createMemPool(function(buf) -- just to use the default filter here -- you can use whatever packet type you want buf:getUdpPtpPacket():fill{ } end) mg.sleepMillis(1000) -- ensure that the load task is running local bufs = mem:bufArray(1) local rateLimit = timer:new(0.0001) -- 10kpps timestamped packets local i = 0 while i < NUM_PKTS and mg.running() do bufs:alloc(PKT_SIZE) queue:sendWithTimestamp(bufs) rateLimit:wait() rateLimit:reset() i = i + 1 end mg.sleepMillis(500) mg.stop() end -- FIXME: the API should be nicer function rxTimestamper(queue) local tscFreq = mg.getCyclesFrequency() local timestamps = ffi.new("uint64_t[64]") local bufs = memory.bufArray(64) -- use whatever filter appropriate for your packet type queue.dev:filterTimestamps(queue) local results = {} local rxts = {} while mg.running() do local numPkts = queue:recvWithTimestamps(bufs, timestamps) for i = 1, numPkts do local rxTs = timestamps[i - 1] local txTs = bufs[i]:getSoftwareTxTimestamp() results[#results + 1] = tonumber(rxTs - txTs) / tscFreq * 10^9 -- to nanoseconds rxts[#rxts + 1] = tonumber(rxTs) end bufs:free(numPkts) end local f = io.open("pings.txt", "w+") for i, v in ipairs(results) do f:write(v .. "\n") end f:close() end
mit
djianq/Game
examples/client.lua
1
2108
package.cpath = "luaclib/?.so" package.path = "lualib/?.lua;examples/?.lua" if _VERSION ~= "Lua 5.3" then error "Use lua 5.3" end local socket = require "clientsocket" local proto = require "proto" local sproto = require "sproto" local host = sproto.new(proto.s2c):host "package" local request = host:attach(sproto.new(proto.c2s)) local fd = assert(socket.connect("127.0.0.1", 1920)) local function send_package(fd, pack) local package = string.pack(">s2", pack) socket.send(fd, package) end local function unpack_package(text) local size = #text if size < 2 then return nil, text end local s = text:byte(1) * 256 + text:byte(2) if size < s + 2 then return nil, text end return text:sub(3, 2 + s), text:sub(3 + s) end local function recv_package(last) local result result, last = unpack_package(last) if result then return result, last end local r = socket.recv(fd) if not r then return nil, last end if r == "" then error "Server closed" end return unpack_package(last .. r) end local session = 0 local function send_request(name, args) session = session + 1 local str = request(name, args, session) send_package(fd, str) print("Request:", session) end local last = "" local function print_request(name, args) print("REQUEST", name) if args then for k, v in pairs(args) do print(k, v) end end end local function print_response(session, args) print("RESPONSE", session) if args then for k, v in pairs(args) do print(k, v) end end end local function print_package(t, ...) if t == "REQUEST" then print_request(...) else assert(t == "RESPONSE") print_response(...) end end local function dispatch_package() while true do local v v, last = recv_package(last) if not v then break end print_package(host:dispatch(v)) end end send_request("handshake") send_request("set", {what = "hello", value = "world"}) while true do dispatch_package() local cmd = socket.readstdin() if cmd then if cmd == "quit" then send_request("quit") else send_request("get", {what = cmd}) end else socket.usleep(100) end end
mit
RebootRevival/FFXI_Test
scripts/globals/items/venom_bolt.lua
1
1029
----------------------------------------- -- ID: 18152 -- Item: Venom Bolt -- Additional Effect: Poison ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 95; if (target:getMainLvl() > player:getMainLvl()) then chance = chance - 5 * (target:getMainLvl() - player:getMainLvl()) chance = utils.clamp(chance, 5, 95); end if (target:hasImmunity(256)) then spell:setMsg(75); elseif (math.random(0,99) >= chance or applyResistanceAddEffect(player,target,ELE_WATER,0) <= 0.5) then return 0,0,0; else if (not target:hasStatusEffect(EFFECT_POISON)) then target:addStatusEffect(EFFECT_POISON, 4, 3, 30); end return SUBEFFECT_POISON, msgBasic.ADD_EFFECT_STATUS, EFFECT_POISON; end end;
gpl-3.0
tommo/mock
mock/core/DebugHelper.lua
1
6812
--[[ * MOCK framework for Moai * Copyright (C) 2012 Tommo Zhou(tommo.zhou@gmail.com). All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local os=MOAIEnvironment.osBrand DebugHelper = {} function DebugHelper:startCrittercism( k1, k2, k3 ) --TODO: support android if os=='iOS' then MOAICrittercism.init( k1, k2, k3 ) self.crittercism = true end end function DebugHelper:setCodeMark( s, ... ) if self.crittercism then MOAICrittercism.leaveBreadcrumb( string.format( s, ... ) ) end end function DebugHelper:reportUsage() print'---------' print('FPS:',MOAISim.getPerformance()) print('Objects:',MOAISim.getLuaObjectCount()) print('Memory:') table.foreach(MOAISim.getMemoryUsage(),print) print('--------') if game.scenes then for k,s in pairs( game.scenes ) do local count=table.len(s.objects) if count>0 then printf('Object in scene "%s": %d',s.name,count) end end end print('--------') -- print(MOAISim.reportHistogram()) end function DebugHelper:showDebugLines(show) show=show~=false for i, l in pairs(moailayers) do l:showDebugLines(show) end end function DebugHelper:setDebugEnabled(d) self.debugEnabled=d or false if not self.debugger then require("clidebugger") self.debugger=clidebugger end MOAIDebugLines.setStyle ( MOAIDebugLines.PARTITION_CELLS, 2, 1, 1, 1 ) MOAIDebugLines.setStyle ( MOAIDebugLines.PARTITION_PADDED_CELLS, 1, 0.5, 0.5, 0.5 ) MOAIDebugLines.setStyle ( MOAIDebugLines.PROP_WORLD_BOUNDS, 2, 0.75, 0.75, 0.75 ) end function DebugHelper:pause(msg) if self.debugger then return self.debugger.pause(msg) end end function DebugHelper:exitOnError( enabled ) enabled = enabled~=false if enabled then MOAISim.setTraceback( function(msg) print( debug.traceback(msg, 2) ) os.exit() end) end end -------------------------------------------------------------------- --Profiler ( using ProFi ) Profiler = { coroWrapped = false } function Profiler:start( time, reportPath ) local ProFi=require 'ProFi' self.ProFi = ProFi --wrap moai coroutine if not self.coroWrapped then self.coroWrapped = true local MOAICoroutineIT = MOAICoroutine.getInterfaceTable() local _run = MOAICoroutineIT.run MOAICoroutineIT.run = function(self, func,...) return _run(self, function(...) ProFi:start() return func(...) end,...) end end --auto stop settings if time then laterCall( time, function() self:stop() if reportPath then self:writeReport( reportPath ) end end) end --start -- ProFi:setGetTimeMethod( MOAISim.getDeviceTime ) _stat 'start profiler...' ProFi:start() end function Profiler:stop() self.ProFi:stop() _stat 'stop profiler...' end function Profiler:writeReport( path ) _statf( 'writing profiler report to : %s', path ) self.ProFi:writeReport( path ) end -------------------------------------------------------------------- local tracingCoroutines = setmetatable( {}, { __mode = 'k' } ) function _reportTracingCoroutines() local count = {} local countActive = {} for coro, tb in pairs( tracingCoroutines ) do count[ tb ] = ( count[ tb ] or 0 ) + 1 print( tb ) if coro:isBusy() then countActive[ tb ] = ( countActive[ tb ] or 0 ) + 1 else -- print( 'inactive coro' ) -- print( tb ) end end -- for tb, c in pairs( count ) do -- if c > 1 then -- print( '------CORO COUNT:', c, countActive[ tb ] ) -- print( tb ) -- end -- end end local oldNew = MOAICoroutine.new MOAICoroutine.new = function( f, ... ) local coro = oldNew( f, ... ) -- print( 'CREATE COROUTINE', coro ) -- print( debug.traceback() ) -- local funcinfo = debug.getinfo( f, 'nSl' ) -- local infoString string.format( -- '%s:%d', funcinfo.source, funcinfo.currentline -- ) tracingCoroutines[ coro ] = debug.traceback( 3 ) return coro end -------------------------------------------------------------------- --dump calltree -------------------------------------------------------------------- --command CLASS: DebugCommand () :MODEL{} function DebugCommand:onExec() end function DebugCommand:finish() end function DebugCommand:fail() end -------------------------------------------------------------------- function enableInfiniteLoopChecking() local function _callback( funcInfo ) local funcInfo = debug.getinfo( 2, 'Sl' ) return print( '>>', funcInfo.source, funcInfo.currentline ) end local MOAICoroutineIT = MOAICoroutine.getInterfaceTable() local _run = MOAICoroutineIT.run MOAICoroutineIT.run = function(self, func,...) return _run(self, function(...) debug.sethook( _callback, 'l' ) return func(...) end,...) end debug.sethook( _callback, 'l' ) end local function defaultErrorHandler ( status ) print( 'ERROR:', status ) print( debug.traceback( 2 ) ) end local function _innerTry( errFunc, ok, ... ) -- print( errFunc, ok, ... ) if ok then return ... end local status = ... errFunc = errFunc or defaultErrorHandler errFunc( status ) return nil end function try( func, errFunc ) return _innerTry( errFunc, pcall( func ) ) end function singletraceback( level ) local info = debug.getinfo( ( level or 2 ) + 1, 'nSl' ) return string.format( '%s:%d', info.source, info.currentline ) end local trackingMOAIObjects = {} function trackMOAIObject( clas ) local oldNew = clas.new local t = table.weak_k() trackingMOAIObjects[ clas ] = t clas.new = function( ... ) local obj = oldNew( ... ) t[ obj ] = debug.traceback( 3 ) return obj end end function reportTrackingMOAIObject( clas ) local t = trackingMOAIObjects[ clas ] if not t then _log( 'not tracking', clas ) return false end _log( 'allocated moai object:', clas ) for obj, trace in pairs( t ) do _log( obj ) _log( trace ) end _log( '----' ) end
mit
RebootRevival/FFXI_Test
scripts/zones/Southern_San_dOria/npcs/Fulchia.lua
17
1048
----------------------------------- -- Area: Southern San d'Oria -- NPC: Fulchia -- 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 ----------------------------------- function onTrigger(player,npc) player:startEvent(0x24b); 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
RebootRevival/FFXI_Test
scripts/globals/items/head_of_isleracea.lua
12
1189
----------------------------------------- -- ID: 5965 -- Item: Head of Isleracea -- Food Effect: 5 Min, All Races ----------------------------------------- -- Agility 2 -- Vitality -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5965); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 2); target:addMod(MOD_VIT, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 2); target:delMod(MOD_VIT, -4); end;
gpl-3.0
tommo/mock
mock/gfx/asset/ParticleHelper.lua
1
9972
--[[ * Particle Script Helper for MOAI * Copyright (C) 2012 Tommo Zhou(tommo.zhou@gmail.com). All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local CONST=MOAIParticleScript.packConst local REG=MOAIParticleScript.packReg local M=MOAIParticleScript local function getScript() return getfenv(3).script end local symbolMT,namespaceMT local function newNode(m) return setmetatable(m,symbolMT) end local function newBNode(m) m.id='node' return newNode(m) end local function newNamespace(t) return setmetatable({ __ITEMS=t },namespaceMT) end local MAXREG=32 local function getReg(script,name) local regs=script.regs local r local tmpflag=regs.tmpflag local list=regs.list local size=#list local named=regs.named if name then r=named[name] if not r then for i=1,size do local item=list[i] if not item.name and item.flag~=tmpflag then --collectable register r=item r.name=name r.number=i r.defined=script r.flag=nil break end end if not r then size=size+1 if size>MAXREG then error('too many registers..:'..name) end r=newNode{id='reg', idx=REG(size), name=name, number=size, defined=script} list[size]=r end named[name]=r else r.referred=r.defined~=script end else for i=1,size do local item=list[i] if not item.name and item.flag~=tmpflag then --collectable register r=item r.flag=tmpflag break end end if not r then size=size+1 if size>MAXREG then error('too many registers..') end r=newNode{id='reg', idx=REG(size), flag=tmpflag} list[size]=r end end return r end local function solve(script,v,reg) local vt=type(v) assert(vt=='table' or vt=='number') if vt=='number' then v = CONST(v) if not reg then return v else local a,b=reg.idx,v script:set(a,b) return reg.idx end end local vid=v.id if not reg then if vid=='reg' or vid=='node' then return v.idx end reg=getReg(script) end if vid=='rand' then local a,b,c=reg.idx, solve(script,v.a),solve(script,v.b) script:rand(a,b,c) elseif vid=='node' or vid=='reg' then --set local a,b=reg.idx,solve(script,v) script:set(a,b) elseif vid=='add' then script:add(reg.idx, solve(script,v.a),solve(script,v.b)) elseif vid=='sub' then script:sub(reg.idx, solve(script,v.a),solve(script,v.b)) elseif vid=='mul' then script:mul(reg.idx, solve(script,v.a),solve(script,v.b)) elseif vid=='div' then script:div(reg.idx, solve(script,v.a),solve(script,v.b)) elseif vid=='vecAngle' then script:vecAngle(reg.idx, solve(script,v.a),solve(script,v.b)) elseif vid=='cycle' then script:cycle(reg.idx, solve(script,v.a),solve(script,v.b),solve(script,v.c)) elseif vid=='wrap' then script:wrap(reg.idx, solve(script,v.a),solve(script,v.b),solve(script,v.c)) elseif vid=='clamp' then script:clamp(reg.idx, solve(script,v.a),solve(script,v.b),solve(script,v.c)) elseif vid=='randSign' then script:randSign(reg.idx) elseif vid=='time' then script:time(reg.idx) elseif vid=='age' then script:time(reg.idx) elseif vid=='ease' then script:ease(reg.idx,solve(script,v.a),solve(script,v.b),v.easeType) elseif vid=='easeDelta' then script:easeDelta(reg.idx,solve(script,v.a),solve(script,v.b),v.easeType) elseif vid=='sign' then script:sign(reg.idx,solve(script,v.a)) elseif vid=='sin' then script:sin(reg.idx,solve(script,v.a)) elseif vid=='cos' then script:cos(reg.idx,solve(script,v.a)) elseif vid=='tan' then script:tan(reg.idx,solve(script,v.a)) elseif vid=='pow' then script:pow(reg.idx, solve(script,v.a),solve(script,v.b) ) -- elseif vid=='atan2rot' then -- script:atan2rot(reg.idx,solve(script,v.a),solve(script,v.b)) else error('todo node type:'..vid) end return reg.idx end symbolMT={ __add=function(a,b) return newNode{id='add',a=a,b=b} end, __sub=function(a,b) return newNode{id='sub',a=a,b=b} end, __div=function(a,b) return newNode{id='div',a=a,b=b} end, __mul=function(a,b) return newNode{id='mul',a=a,b=b} end, __neg=function(a) return newNode{id='sub',a=CONST(0),b=a} end } namespaceMT={ __index=function(t,k) local r=t.__ITEMS[k] if not r then return error('unkown script node name:'..k) end return r end, __newindex=function(t,k,v) local r=t.__ITEMS[k] if not r then return error('unkown script node name:'..k) end local script=getScript() solve(script,v,r) script.regs.tmpflag={} --new tmp flag end } local builtinSymbol={ p = newNamespace{ x = newBNode { idx = M.PARTICLE_X }, y = newBNode { idx = M.PARTICLE_Y }, z = newBNode { idx = M.PARTICLE_Z }, dx = newBNode { idx = M.PARTICLE_DX }, dy = newBNode { idx = M.PARTICLE_DY }, dz = newBNode { idx = M.PARTICLE_DZ }, }, sp = newNamespace{ x = newBNode { idx = M.SPRITE_X_LOC }, y = newBNode { idx = M.SPRITE_Y_LOC }, z = newBNode { idx = M.SPRITE_Z_LOC }, rx = newBNode { idx = M.SPRITE_X_ROT }, ry = newBNode { idx = M.SPRITE_Y_ROT }, rz = newBNode { idx = M.SPRITE_Z_ROT }, sx = newBNode { idx = M.SPRITE_X_SCL }, sy = newBNode { idx = M.SPRITE_Y_SCL }, sz = newBNode { idx = M.SPRITE_Z_SCL }, rot = newBNode { idx = M.SPRITE_ROT }, r = newBNode { idx = M.SPRITE_RED }, g = newBNode { idx = M.SPRITE_GREEN }, b = newBNode { idx = M.SPRITE_BLUE }, glow = newBNode { idx = M.SPRITE_GLOW }, idx = newBNode { idx = M.SPRITE_IDX }, opacity = newBNode { idx = M.SPRITE_OPACITY }, }, time=newNode{id='time'}, age =newNode{id='age'}, rand=function(a,b) return newNode{id='rand',a=a,b=b} end, randSign=function() return newNode{id='randSign'} end, randVec=function(r1,r2,a,b) local script=getScript() return script:randVec(r1,r2,solve(script,a),solve(script,b)) end, vecAngle=function(a,b) return newNode{id='vecAngle',a=a,b=b} end, cycle=function(a,b,c) return newNode{id='cycle',a=a,b=b,c=c} end, wrap=function(a,b,c) return newNode{id='wrap',a=a,b=b,c=c} end, clamp=function(a,b,c) return newNode{id='clamp',a=a,b=b,c=c} end, ease=function(a,b,c) return newNode{id='ease',a=a,b=b,easeType=c or MOAIEaseType.LINEAR} end, easeDelta=function(a,b,c) return newNode{id='easeDelta',a=a,b=b,easeType=c or MOAIEaseType.LINEAR} end, sprite=function() getScript():sprite() end, -- atan2rot=function(a,b) -- return newNode{id='atan2rot',a=a,b=b} -- end, pow=function(a,b) return newNode{id='pow',a=a,b=b} end, cos=function(a) return newNode{id='cos',a=a} end, sin=function(a) return newNode{id='sin',a=a} end, tan=function(a) return newNode{id='tan',a=a} end, sign=function(a) return newNode{id='sign',a=a} end, EaseType={ EASE_IN = MOAIEaseType. EASE_IN, EASE_OUT = MOAIEaseType. EASE_OUT, FLAT = MOAIEaseType. FLAT, LINEAR = MOAIEaseType. LINEAR, SHARP_EASE_IN = MOAIEaseType. SHARP_EASE_IN, SHARP_EASE_OUT = MOAIEaseType. SHARP_EASE_OUT, SHARP_SMOOTH = MOAIEaseType. SHARP_SMOOTH, SMOOTH = MOAIEaseType. SMOOTH, SOFT_EASE_IN = MOAIEaseType. SOFT_EASE_IN, SOFT_EASE_OUT = MOAIEaseType. SOFT_EASE_OUT, SOFT_SMOOTH = MOAIEaseType. SOFT_SMOOTH, BACK_IN = MOAIEaseType. BACK_IN, BACK_OUT = MOAIEaseType. BACK_OUT, BACK_SMOOTH = MOAIEaseType. BACK_SMOOTH, ELASTIC_IN = MOAIEaseType. ELASTIC_IN, ELASTIC_OUT = MOAIEaseType. ELASTIC_OUT, ELASTIC_SMOOTH = MOAIEaseType. ELASTIC_SMOOTH, BOUNCE_IN = MOAIEaseType. BOUNCE_IN, BOUNCE_OUT = MOAIEaseType. BOUNCE_OUT, BOUNCE_SMOOTH = MOAIEaseType. BOUNCE_SMOOTH, } } for k, v in pairs( builtinSymbol.EaseType ) do builtinSymbol[ k ] = v end local scriptEnvMT={ __index=function(t,k) local script=getScript() return builtinSymbol[k] or getReg(script,k) end, __newindex=function(t,k,v) local script=getScript() local r=builtinSymbol[k] or getReg(script,k) solve(script,v,r) script.regs.tmpflag={} end } function makeParticleScript( f, regs, ... ) local script=MOAIParticleScript.new() regs = regs or {} script.regs = regs if not regs.list then regs.list={} end if not regs.named then regs.named={} end regs.tmpflag={} local scriptEnv=setmetatable({ script=script },scriptEnvMT) setfenv(f,scriptEnv) if not pcall( f, ... ) then return nil end return script end function addParticleScriptBuiltinSymbol(k,v) builtinSymbol[k]=v end
mit
RebootRevival/FFXI_Test
scripts/zones/QuBia_Arena/TextIDs.lua
3
1428
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6386; -- Obtained: <item>. GIL_OBTAINED = 6387; -- Obtained <number> gil. KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>. -- Maat dialog YOU_DECIDED_TO_SHOW_UP = 7625; -- So, you decided to show up. LOOKS_LIKE_YOU_WERENT_READY = 7626; -- Looks like you weren't ready for me, were you? YOUVE_COME_A_LONG_WAY = 7627; -- Hm. That was a mighty fine display of skill there, Player Name. You've come a long way... TEACH_YOU_TO_RESPECT_ELDERS = 7628; -- I'll teach you to respect your elders! TAKE_THAT_YOU_WHIPPERSNAPPER = 7629; -- Take that, you whippersnapper! THAT_LL_HURT_IN_THE_MORNING = 7631; -- Ungh... That'll hurt in the morning... -- trion dialog FLAT_PREPARE = 7619; -- I am Trion, of San d'Oria FLAT_LAND = 7620; -- Feel the fire of my forefathers RLB_PREPARE = 7621; -- The darkness before me that shrouds the light of good... RLB_LAND = 7622; -- ...Return to the hell you crawled out from SAVAGE_PREPARE = 7623; -- The anger, the pain, and the will to survive... Let the spirit of San d'Oria converge within this blade SAVAGE_LAND = 7624; -- And with this blade I will return the glory to my kingdom's people -- conquest Base CONQUEST_BASE = 7047; -- Tallying conquest results...
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Aht_Urhgan_Whitegate/npcs/Yahsra.lua
3
3585
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Yahsra -- Type: Assault Mission Giver -- !pos 120.967 0.161 -44.002 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/besieged"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local rank = getMercenaryRank(player); local haveimperialIDtag; local assaultPoints = player:getAssaultPoint(LEUJAOAM_ASSAULT_POINT); if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then haveimperialIDtag = 1; else haveimperialIDtag = 0; end --[[if (rank > 0) then player:startEvent(273,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault()); else]] player:startEvent(279); -- no rank --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 == 273) then local selectiontype = bit.band(option, 0xF); if (selectiontype == 1) then -- taken assault mission player:addAssault(bit.rshift(option,4)); player:delKeyItem(IMPERIAL_ARMY_ID_TAG); player:addKeyItem(LEUJAOAM_ASSAULT_ORDERS); player:messageSpecial(KEYITEM_OBTAINED,LEUJAOAM_ASSAULT_ORDERS); elseif (selectiontype == 2) then -- purchased an item local item = bit.rshift(option,14); local itemID = 0; local price = 0; -- Copy/pasted from Famad, TODO: fill in the actual IDs/prices for Yahsra --[[if (item == 1) then itemID = 15972; price = 3000; elseif (item == 2) then itemID = 15777; price = 5000; elseif (item == 3) then itemID = 15523; price = 8000; elseif (item == 4) then itemID = 15886; price = 10000; elseif (item == 5) then itemID = 15492; price = 10000; elseif (item == 6) then itemID = 18583; price = 10000; elseif (item == 7) then itemID = 18388; price = 15000; elseif (item == 8) then itemID = 18417; price = 15000; elseif (item == 9) then itemID = 14940; price = 15000; elseif (item == 10) then itemID = 15690; price = 20000; elseif (item == 11) then itemID = 14525; price = 20000; else return; end player:addItem(itemID); player:messageSpecial(ITEM_OBTAINED,itemID); player:delAssaultPoint(LEBROS_ASSAULT_POINT,price);]] end end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Abyssea-Konschtat/npcs/Cavernous_Maw.lua
3
1200
----------------------------------- -- Area: Abyssea - Konschatat -- NPC: Cavernous Maw -- !pos 159.943 -72.109 -839.986 15 -- Teleports Players to Konschatat Highlands ----------------------------------- package.loaded["scripts/zones/Abyssea-Konschtat/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Abyssea-Konschtat/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8); 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 == 0x00C8 and option == 1) then player:setPos(91,-68,-582,237,108); end end;
gpl-3.0
sehraf/Lua4RS
scripts/buryTheDead.lua
2
3451
-- script to move long time offline peers to a seperated group -- !!! this may cause a GUI lag !!! -- enter the group name local groupName = "Graveyard" -- days offline local limit = 30 -- rs.clear() -- remove group for offline peers function removeGroup() local grpList = peers.getGroupInfoList() for i = 1, #grpList do if grpList[i]["name"] == groupName then rs.print("removing " .. grpList[i]["name"] .. " (" .. grpList[i]["id"] .. ")") peers.removeGroup(grpList[i]["id"]) end end end -- add group for offline peers function addGroup() local grpInfo = {} grpInfo["flag"] = 0 grpInfo["id"] = "0" grpInfo["name"] = groupName grpInfo["peerIds"] = nil peers.addGroup(grpInfo) end -- check whether the group exists function checkGroup() local grpList = peers.getGroupInfoList() for i = 1, #grpList do if grpList[i]["name"] == groupName then return true end end -- didn't fing anything return false end function contains(a, array) for i = 1, #array do if array[i] == a then return true end end return false end function getGroupId() local grpList = peers.getGroupInfoList() for i = 1, #grpList do if grpList[i]["name"] == groupName then return grpList[i]["id"] end end end function getDays(details) local now = os.time() local diff = now - details["lastUsed"] -- how long in days local days = diff / 60 / 60 / 24 return math.ceil(days) end -- function to combine everything function run() -- create group if needed if checkGroup() ~= true then addGroup() end local grpInfo = peers.getGroupInfo( getGroupId() ) -- get infos local friends = peers.getFriendList() for i = 1, #friends do local details = peers.getPeerDetails(friends[i]) -- get gpg id for groups local id = peers.getGPGId(details["id"]) local days = getDays(details) -- peer offline for too long? if days >= limit then if not contains(id, grpInfo["peerIds"]) then rs.print("burrying " .. details["name"] .. " (offline for " .. days .. " days)") peers.assignPeerToGroup(grpInfo["id"], id, true) end end end for i = 1, #friends do local details = peers.getPeerDetails(friends[i]) -- get gpg id for groups local id = peers.getGPGId(details["id"]) local days = getDays(details) -- peer offline for too long? if days < limit then if contains(id, grpInfo["peerIds"]) then rs.print("removing " .. details["name"]) peers.assignPeerToGroup(grpInfo["id"], id, false) end end end end -- use removeGroup() to cleanup your groups (will remove the group for offline peers) -- go! run() rs.print('buryTheDead done')
lgpl-3.0
onpon4/naev
dat/events/neutral/baron_comm.lua
1
1225
--[[ <?xml version='1.0' encoding='utf8'?> <event name="Baroncomm_baron"> <trigger>enter</trigger> <chance>4</chance> <cond> not var.peek("baron_hated") and not player.misnDone("Baron") and not player.misnActive("Baron") and ( system.cur():faction() == faction.get("Empire") or system.cur():faction() == faction.get("Dvaered") or system.cur():faction() == faction.get("Sirius") ) </cond> <flags> </flags> <notes> <campaign>Baron Sauterfeldt</campaign> </notes> </event> --]] --[[ -- Comm Event for the Baron mission string --]] function create () if not evt.claim(system.cur()) then evt.finish() end hyena = pilot.add( "Hyena", "Civilian", true, _("Civilian Hyena") ) hook.pilot(hyena, "jump", "finish") hook.pilot(hyena, "death", "finish") hook.land("finish") hook.jumpout("finish") hailie = hook.timer( 3.0, "hailme" ); end -- Make the ship hail the player function hailme() hyena:hailPlayer() hook.pilot(hyena, "hail", "hail") end -- Triggered when the player hails the ship function hail() naev.missionStart("Baron") player.commClose() evt.finish(true) end function finish() hook.rm(hailie) evt.finish() end
gpl-3.0
ciufciuf57/nodemcu-firmware
lua_modules/ds3231/ds3231-web.lua
84
1338
require('ds3231') port = 80 -- ESP-01 GPIO Mapping gpio0, gpio2 = 3, 4 days = { [1] = "Sunday", [2] = "Monday", [3] = "Tuesday", [4] = "Wednesday", [5] = "Thursday", [6] = "Friday", [7] = "Saturday" } months = { [1] = "January", [2] = "Febuary", [3] = "March", [4] = "April", [5] = "May", [6] = "June", [7] = "July", [8] = "August", [9] = "September", [10] = "October", [11] = "November", [12] = "December" } ds3231.init(gpio0, gpio2) srv=net.createServer(net.TCP) srv:listen(port, function(conn) second, minute, hour, day, date, month, year = ds3231.getTime() prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second) conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" .. "<!DOCTYPE HTML>" .. "<html><body>" .. "<b>ESP8266</b></br>" .. "Time and Date: " .. prettyTime .. "<br>" .. "Node ChipID : " .. node.chipid() .. "<br>" .. "Node MAC : " .. wifi.sta.getmac() .. "<br>" .. "Node Heap : " .. node.heap() .. "<br>" .. "Timer Ticks : " .. tmr.now() .. "<br>" .. "</html></body>") conn:on("sent",function(conn) conn:close() end) end )
mit
RebootRevival/FFXI_Test
scripts/globals/weaponskills/steel_cyclone.lua
26
1617
----------------------------------- -- Steel Cyclone -- Great Axe weapon skill -- Skill level: 240 -- Delivers a single-hit attack. Damage varies with TP. -- In order to obtain Steel Cyclone, the quest The Weight of Your Limits must be completed. -- Will stack with Sneak Attack. -- Aligned with the Breeze Gorget, Aqua Gorget & Snow Gorget. -- Aligned with the Breeze Belt, Aqua Belt & Snow Belt. -- Element: None -- Modifiers: STR:60% ; VIT:60% -- 100%TP 200%TP 300%TP -- 1.50 2.5 4.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1.5; params.ftp200 = 1.75; params.ftp300 = 3; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; 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.66; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 2.5; params.ftp300 = 4; params.str_wsc = 0.6; params.vit_wsc = 0.6; params.atkmulti = 1.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Aydeewa_Subterrane/npcs/qm3.lua
3
1271
----------------------------------- -- Area: Aydeewa Subterrane -- NPC: ??? (Spawn Chigre(ZNM T1)) -- !pos -217 35 12 68 ----------------------------------- package.loaded["scripts/zones/Aydeewa_Subterrane/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aydeewa_Subterrane/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17056186; if (trade:hasItemQty(2602,1) and trade:getItemCount() == 1) then -- Trade Spoilt Blood player:tradeComplete(); SpawnMob(mobID):updateClaim(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
RebootRevival/FFXI_Test
scripts/globals/items/flame_sword.lua
1
1101
----------------------------------------- -- ID: 16621 -- Item: Flame Sword -- Additional Effect: Fire Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0); dmg = adjustForTarget(target,dmg,ELE_FIRE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg); local message = msgBasic.ADD_EFFECT_DMG; if (dmg < 0) then message = msgBasic.ADD_EFFECT_HEAL; end return SUBEFFECT_FIRE_DAMAGE,message,dmg; end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/PsoXja/npcs/_094.lua
3
2852
----------------------------------- -- Area: Pso'Xja -- NPC: _094 (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- !pos 310.000 -1.925 -101.600 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == JOBS.THF) then local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z >= -101) then if (GetMobAction(16814085) == 0) then local Rand = math.random(1,2); -- estimated 50% success as per the wiki if (Rand == 1) then -- Spawn Gargoyle player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814085):updateClaim(player); -- Gargoyle else player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end player:tradeComplete(); else player:messageSpecial(DOOR_LOCKED); end end end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z >= -101) then if (GetMobAction(16814085) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814085):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif (Z <= -102) then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/weaponskills/metatron_torment.lua
19
2291
----------------------------------- -- Metatron Torment -- Hand-to-Hand Skill level: 5 Description: Delivers a threefold attack. Damage varies wit weapon skill -- Great Axe Weapon Skill -- Skill Level: N/A -- Lowers target's defense. Additional effect: temporarily lowers damage taken from enemies. -- Defense Down effect is 18.5%, 1 minute duration. -- Damage reduced is 20.4% or 52/256. -- Lasts 20 seconds at 100TP, 40 seconds at 200TP and 60 seconds at 300TP. -- Available only when equipped with the Relic Weapons Abaddon Killer (Dynamis use only) or Bravura. -- Also available as a Latent effect on Barbarus Bhuj -- Since these Relic Weapons are only available to Warriors, only Warriors may use this Weapon Skill. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:60% -- 100%TP 200%TP 300%TP -- 2.75 2.75 2.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75; params.str_wsc = 0.6; 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; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); -- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect. if (damage > 0) then local amDuration = 20 * math.floor(tp/1000); player:addStatusEffect(EFFECT_AFTERMATH, -21, 0, amDuration, 0, 5); target:addStatusEffect(EFFECT_DEFENSE_DOWN, 19, 0, 120); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Lower_Delkfutts_Tower/npcs/_542.lua
3
2219
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Cermet Door for Basty Ambassador -- Bastok Mission 3.3 "Appointment to Jeuno" -- !pos 596 16 -19 184 ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(BASTOK) == JEUNO_MISSION and player:getVar("MissionStatus") == 2) then if (trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key player:startEvent(0x0001); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(BASTOK); if (currentMission == JEUNO_MISSION and player:getVar("MissionStatus") == 2 and player:hasKeyItem(DELKFUTT_KEY) == false) then player:messageSpecial(THE_DOOR_IS_FIRMLY_SHUT_OPEN_KEY); elseif (currentMission == JEUNO_MISSION and player:getVar("MissionStatus") == 2 and player:hasKeyItem(DELKFUTT_KEY)) then player:startEvent(0x0001); else player:messageSpecial(DOOR_FIRMLY_SHUT); 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) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0001) then if (player:hasKeyItem(DELKFUTT_KEY) == false) then player:tradeComplete(); player:addKeyItem(DELKFUTT_KEY); player:messageSpecial(KEYITEM_OBTAINED,DELKFUTT_KEY); end player:setVar("MissionStatus",3); end end;
gpl-3.0
blackzw/openwrt_sdk_dev1
staging_dir/target-mips_r2_uClibc-0.9.33.2/root-ar71xx/usr/lib/lua/luci/webapi/common.lua
1
6984
module("luci.webapi.common", package.seeall) ReturnCode = { "RILD_ERRID_SUCCESS", -- 0 "RILD_ERRID_FAILED", -- 1 "RILD_ERRID_BAD_PARAMETER", -- 2 "RILD_ERRID_DEVICE_NOT_READY", -- 3 "RILD_ERRID_COMM_OPEN_FAILED", -- 4 "RILD_ERRID_AT_INIT_ERROR", -- 5 "RILD_ERRID_RPC_WRITE_FAILED",-- 6 "RILD_ERRID_RPC_DISCONNECTED", -- 7 "RILD_ERRID_AT_ERROR_TIMEOUT", -- 8 "RILD_ERRID_AT_ERROR_NOT_ENOUGH_MEMORY", -- 9 "RILD_ERRID_AT_ERROR_CALLBACK_FUNC_IS_NOT_READY", -- 10 "RILD_ERRID_AT_ERROR_PHSIM_PIN_REQUIRED", -- 11 "RILD_ERRID_AT_ERROR_PHFSIM_PIN_REQUIRED", -- 12 "RILD_ERRID_AT_ERROR_PHFSIM_PUK_REQUIRED", -- 13 "RILD_ERRID_AT_ERROR_SIM_NOT_INSERTED", -- 14 "RILD_ERRID_AT_ERROR_SIM_PIN_REQUIRED", -- 15 "RILD_ERRID_AT_ERROR_SIM_PUK_REQUIRED", -- 16 "RILD_ERRID_AT_ERROR_SIM_FAILURE", -- 17 "RILD_ERRID_AT_ERROR_SIM_BUSY", -- 18 "RILD_ERRID_AT_ERROR_SIM_WRONG", -- 19 "RILD_ERRID_AT_ERROR_INCORRECT_PASSWORD", -- 20 "RILD_ERRID_AT_ERROR_SIM_PIN2_REQUIRED", -- 21 "RILD_ERRID_AT_ERROR_SIM_PUK2_REQUIRED", -- 22 "RILD_ERRID_AT_ERROR_PHNET_PIN_REQUIRED", -- 23 "RILD_ERRID_AT_ERROR_PHNET_PUK_REQUIRED", -- 24 "RILD_ERRID_AT_ERROR_PHNETSUB_PIN_REQUIRED", -- 25 "RILD_ERRID_AT_ERROR_PHNETSUB_PUK_REQUIRED", -- 26 "RILD_ERRID_AT_ERROR_PHSP_PIN_REQUIRED", -- 27 "RILD_ERRID_AT_ERROR_PHSP_PUK_REQUIRED", -- 28 "RILD_ERRID_AT_ERROR_PHCORP_PIN_REQUIRED", -- 29 "RILD_ERRID_AT_ERROR_PHCORP_PUK_REQUIRED", -- 30 "RILD_ERRID_AT_ERROR_PIN_VERIFY_OK_BUT_FAIL_TO_DISABLE_PIN", -- 31 "RILD_ERRID_AT_ERROR_CALL_NO_CARRIER", -- 32 "RILD_ERRID_AT_ERROR_CALL_NO_ANSWER", -- 33 "RILD_ERRID_AT_ERROR_CALL_BUSY", -- 34 "RILD_ERRID_AT_ERROR_CALL_NO_DIAL_TONE", -- 35 "RILD_ERRID_AT_ERROR_CALL_INVALID_NUMBER", -- 36 "RILD_ERRID_AT_ERROR_CALL_AUDIO_INVALID", -- 37 "RILD_ERRID_AT_ERROR_PB_STORAGE_IS_FULL", -- 38 "RILD_ERRID_AT_ERROR_PB_NO_NEED_TO_MOVE", -- 39 "RILD_ERRID_AT_ERROR_PB_ITEM_SAVED_BUT_OLD_ONE_REMAINED", -- 40 "RILD_ERRID_CANCELED_MANUALLY", -- 41 "RILD_ERRID_NO_MESSAGE", -- 42 "RILD_ERRID_ERROR_USER_DEFINE_ERROR", -- 43 "RILD_ERRID_SOCKET_ERROR", -- 44 "RILD_ERRID_PROFILE_STORAGE_IS_FULL", -- 45 "RILD_ERRID_PROFILE_NO_ACTIVE", -- 46 "RILD_ERRID_SMS_STORAGE_IS_FULL", -- 47 "RILD_ERRID_SMS_SENDING_LAST_MESSAGE", -- 48 "RILD_ERRID_TOO_MANY_REQUEST", -- 49 "RILD_ERRID_AT_BUSY", -- 50 "RILD_ERRID_USSD_SENDING_LAST", -- 51, "RILD_ERRID_USAGE_HISTORY_OVERFLOW", -- 52 } function CreateEnumTable(tbl, index) local enumtbl = {} local enumindex = index or 0 for i, v in ipairs(tbl) do enumtbl[v] = enumindex + i - 1 end return enumtbl end ReturnCode = CreateEnumTable(ReturnCode, 0) function LoadRildClientLibrary() rild_client_lib = assert(package.loadlib("/usr/lib/librild_client.so", "luaopen_rild_client")) rild_client_lib() end --LoadRildClientLibrary() function GetCommonErrorObject(ret_code) if ret_code == ReturnCode.RILD_ERRID_SUCCESS then return nil elseif ret_code == ReturnCode.RILD_ERRID_BAD_PARAMETER then return {code=7, message="Bad parameter"} elseif ret_code == ReturnCode.RILD_ERRID_DEVICE_NOT_READY then return {code=1, message="Device not ready"} elseif ret_code == ReturnCode.RILD_ERRID_COMM_OPEN_FAILED or ret_code == ReturnCode.RILD_ERRID_AT_INIT_ERROR then return {code=2, message="AT port not ready"} elseif ret_code == ReturnCode.RILD_ERRID_AT_ERROR_TIMEOUT then return {code=3, message="AT timeout"} elseif ret_code == ReturnCode.RILD_ERRID_AT_ERROR_SIM_NOT_INSERTED then return {code=4, message="No SIM"} elseif ret_code == ReturnCode.RILD_ERRID_NO_MESSAGE then return {code=5, message="No message"} elseif ret_code == ReturnCode.RILD_ERRID_SOCKET_ERROR then return {code=6, message="Access ril service error"} elseif ret_code == ReturnCode.RILD_ERRID_PROFILE_NO_ACTIVE then return {code=8, message="No default profile"} elseif ret_code == ReturnCode.RILD_ERRID_TOO_MANY_REQUEST then return {code=9, message="RIL service is busy"} elseif ret_code == ReturnCode.RILD_ERRID_AT_BUSY then return {code=10, message="AT port is busy"} elseif ret_code == ReturnCode.RILD_ERRID_SMS_SENDING_LAST_MESSAGE then return {code=60302, message="Fail still sending last message"} elseif ret_code == ReturnCode.RILD_ERRID_SMS_STORAGE_IS_FULL then return {code=60303, message="Fail with memory full"} elseif ret_code == ReturnCode.RILD_ERRID_USAGE_HISTORY_OVERFLOW then return {code=80204, message="Usage history Overflow"} else return nil end end StatisticsReturnCode = { "STATISTICS_ERROR_SUCCESS", -- 0 "STATISTICS_ERROR_FAILED", -- 1 "STATISTICS_ERROR_PARAMETER_ERROR", -- 2 "STATISTICS_ERROR_REMOVE_SOCKET", -- 3 "STATISTICS_ERROR_NO_SPECIAL_MESSAGE", -- 4 "STATISTICS_ERROR_NO_MESSAGE", --5 "STATISTICS_ERROR_DATABASE_FAILED", -- 6 "STATISTICS_ERROR_BUFFER_SMALL", -- 7 "STATISTICS_ERROR_OPENDATABASE_ERROR", -- 8 "STATISTICS_ERROR_NO_RECORD", -- 9 "STATISTICS_ERROR_NOT_SET_IMSI", -- 10 "STATISTICS_ERROR_POFILE_NO_ACTIVE", -- 11 } StatisticsReturnCode = CreateEnumTable(StatisticsReturnCode, 0) function GetCommonErrorObjectForStatistics(ret_code) if ret_code == ReturnCode.STATISTICS_ERROR_SUCCESS then return nil elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_PARAMETER_ERROR then return {code=7, message="Bad parameter"} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_OPENDATABASE_ERROR then return {code=13, message="Open database file failed"} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_DATABASE_FAILED then return {code=11, message="Failed to get or set database data."} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_BUFFER_SMALL then return {code=12, message="Return buffer is smaller."} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_NO_RECORD then return {code=14, message="No special record."} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_NO_MESSAGE then return {code=5, message="No message"} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_REMOVE_SOCKET then return {code=10, message="Access connect manager service error"} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_NOT_SET_IMSI then return {code=15, message="Imsi is not ready."} elseif ret_code == StatisticsReturnCode.STATISTICS_ERROR_POFILE_NO_ACTIVE then return {code=8, message="No default profile"} else return nil end end function LoadConnectManagerClient() local connect_manager = assert(package.loadlib("/usr/lib/libconnect_manager_client.so", "luaopen_connect_manager_client")) connect_manager() end --LoadConnectManagerClient()
gpl-2.0