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
keplerproject/luarocks
src/luarocks/core/vers.lua
1
6925
local vers = {} local util = require("luarocks.core.util") local require = nil -------------------------------------------------------------------------------- local deltas = { dev = 120000000, scm = 110000000, cvs = 100000000, rc = -1000, pre = -10000, beta = -100000, alpha = -1000000 } local version_mt = { --- Equality comparison for versions. -- All version numbers must be equal. -- If both versions have revision numbers, they must be equal; -- otherwise the revision number is ignored. -- @param v1 table: version table to compare. -- @param v2 table: version table to compare. -- @return boolean: true if they are considered equivalent. __eq = function(v1, v2) if #v1 ~= #v2 then return false end for i = 1, #v1 do if v1[i] ~= v2[i] then return false end end if v1.revision and v2.revision then return (v1.revision == v2.revision) end return true end, --- Size comparison for versions. -- All version numbers are compared. -- If both versions have revision numbers, they are compared; -- otherwise the revision number is ignored. -- @param v1 table: version table to compare. -- @param v2 table: version table to compare. -- @return boolean: true if v1 is considered lower than v2. __lt = function(v1, v2) for i = 1, math.max(#v1, #v2) do local v1i, v2i = v1[i] or 0, v2[i] or 0 if v1i ~= v2i then return (v1i < v2i) end end if v1.revision and v2.revision then return (v1.revision < v2.revision) end return false end, -- @param v1 table: version table to compare. -- @param v2 table: version table to compare. -- @return boolean: true if v1 is considered lower than or equal to v2. __le = function(v1, v2) return not (v2 < v1) end, --- Return version as a string. -- @param v The version table. -- @return The string representation. __tostring = function(v) return v.string end, } local version_cache = {} setmetatable(version_cache, { __mode = "kv" }) --- Parse a version string, converting to table format. -- A version table contains all components of the version string -- converted to numeric format, stored in the array part of the table. -- If the version contains a revision, it is stored numerically -- in the 'revision' field. The original string representation of -- the string is preserved in the 'string' field. -- Returned version tables use a metatable -- allowing later comparison through relational operators. -- @param vstring string: A version number in string format. -- @return table or nil: A version table or nil -- if the input string contains invalid characters. function vers.parse_version(vstring) if not vstring then return nil end assert(type(vstring) == "string") local cached = version_cache[vstring] if cached then return cached end local version = {} local i = 1 local function add_token(number) version[i] = version[i] and version[i] + number/100000 or number i = i + 1 end -- trim leading and trailing spaces local v = vstring:match("^%s*(.*)%s*$") version.string = v -- store revision separately if any local main, revision = v:match("(.*)%-(%d+)$") if revision then v = main version.revision = tonumber(revision) end while #v > 0 do -- extract a number local token, rest = v:match("^(%d+)[%.%-%_]*(.*)") if token then add_token(tonumber(token)) else -- extract a word token, rest = v:match("^(%a+)[%.%-%_]*(.*)") if not token then util.warning("version number '"..v.."' could not be parsed.") version[i] = 0 break end version[i] = deltas[token] or (token:byte() / 1000) end v = rest end setmetatable(version, version_mt) version_cache[vstring] = version return version end --- Utility function to compare version numbers given as strings. -- @param a string: one version. -- @param b string: another version. -- @return boolean: True if a > b. function vers.compare_versions(a, b) if a == b then return false end return vers.parse_version(a) > vers.parse_version(b) end --- A more lenient check for equivalence between versions. -- This returns true if the requested components of a version -- match and ignore the ones that were not given. For example, -- when requesting "2", then "2", "2.1", "2.3.5-9"... all match. -- When requesting "2.1", then "2.1", "2.1.3" match, but "2.2" -- doesn't. -- @param version string or table: Version to be tested; may be -- in string format or already parsed into a table. -- @param requested string or table: Version requested; may be -- in string format or already parsed into a table. -- @return boolean: True if the tested version matches the requested -- version, false otherwise. local function partial_match(version, requested) assert(type(version) == "string" or type(version) == "table") assert(type(requested) == "string" or type(version) == "table") if type(version) ~= "table" then version = vers.parse_version(version) end if type(requested) ~= "table" then requested = vers.parse_version(requested) end if not version or not requested then return false end for i, ri in ipairs(requested) do local vi = version[i] or 0 if ri ~= vi then return false end end if requested.revision then return requested.revision == version.revision end return true end --- Check if a version satisfies a set of constraints. -- @param version table: A version in table format -- @param constraints table: An array of constraints in table format. -- @return boolean: True if version satisfies all constraints, -- false otherwise. function vers.match_constraints(version, constraints) assert(type(version) == "table") assert(type(constraints) == "table") local ok = true setmetatable(version, version_mt) for _, constr in pairs(constraints) do if type(constr.version) == "string" then constr.version = vers.parse_version(constr.version) end local constr_version, constr_op = constr.version, constr.op setmetatable(constr_version, version_mt) if constr_op == "==" then ok = version == constr_version elseif constr_op == "~=" then ok = version ~= constr_version elseif constr_op == ">" then ok = version > constr_version elseif constr_op == "<" then ok = version < constr_version elseif constr_op == ">=" then ok = version >= constr_version elseif constr_op == "<=" then ok = version <= constr_version elseif constr_op == "~>" then ok = partial_match(version, constr_version) end if not ok then break end end return ok end return vers
mit
Craige/prosody-modules
mod_s2s_auth_monkeysphere/mod_s2s_auth_monkeysphere.lua
32
1870
module:set_global(); local http_request = require"socket.http".request; local ltn12 = require"ltn12"; local json = require"util.json"; local json_encode, json_decode = json.encode, json.decode; local gettime = require"socket".gettime; local serialize = require"util.serialization".serialize; local msva_url = assert(os.getenv"MONKEYSPHERE_VALIDATION_AGENT_SOCKET", "MONKEYSPHERE_VALIDATION_AGENT_SOCKET is unset, please set it").."/reviewcert"; local function check_with_monkeysphere(event) local session, host, cert = event.session, event.host, event.cert; local result = {}; local post_body = json_encode { peer = { name = host; type = "peer"; }; context = "https"; -- context = "xmpp"; -- Monkeysphere needs to be extended to understand this pkc = { type = "x509pem"; data = cert:pem(); }; } local req = { method = "POST"; url = msva_url; headers = { ["Content-Type"] = "application/json"; ["Content-Length"] = tostring(#post_body); }; sink = ltn12.sink.table(result); source = ltn12.source.string(post_body); }; session.log("debug", "Asking what Monkeysphere thinks about this certificate"); local starttime = gettime(); local ok, code = http_request(req); module:log("debug", "Request took %fs", gettime() - starttime); local body = table.concat(result); if ok and code == 200 and body then body = json_decode(body); if body then session.log(body.valid and "info" or "warn", "Monkeysphere thinks the cert is %salid: %s", body.valid and "V" or "Inv", body.message); if body.valid then session.cert_chain_status = "valid"; session.cert_identity_status = "valid"; return true; end end else module:log("warn", "Request failed: %s, %s", tostring(code), tostring(body)); module:log("debug", serialize(req)); end end module:hook("s2s-check-certificate", check_with_monkeysphere);
mit
p00ria/RedStorm
plugins/rules.lua
28
2270
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -- Created by @Josepdal & @A7F -- -- -- -------------------------------------------------- local function set_rules_channel(msg, text) local rules = text local hash = 'channel:id:'..msg.to.id..':rules' redis:set(hash, rules) end local function del_rules_channel(chat_id) local hash = 'channel:id:'..chat_id..':rules' redis:del(hash) end local function init_def_rules(chat_id) local rules = 'ℹ️ Rules:\n' ..'1⃣ No Flood.\n' ..'2⃣ No Spam.\n' ..'3⃣ Try to stay on topic.\n' ..'4⃣ Forbidden any racist, sexual, homophobic or gore content.\n' ..'➡️ Repeated failure to comply with these rules will cause ban.' local hash='channel:id:'..chat_id..':rules' redis:set(hash, rules) end local function ret_rules_channel(msg) local chat_id = msg.to.id local hash = 'channel:id:'..msg.to.id..':rules' if redis:get(hash) then return redis:get(hash) else init_def_rules(chat_id) return redis:get(hash) end end local function run(msg, matches) if matches[1] == 'rules' then return ret_rules_channel(msg) elseif matches[1] == 'setrules' then if permissions(msg.from.id, msg.to.id, 'rules') then set_rules_channel(msg, matches[2]) return 'ℹ️ '..lang_text(msg.to.id, 'setRules') end elseif matches[1] == 'remrules' then if permissions(msg.from.id, msg.to.id, 'rules') then del_rules_channel(msg.to.id) return 'ℹ️ '..lang_text(msg.to.id, 'remRules') end end end return { patterns = { '^#(rules)$', '^#(setrules) (.+)$', '^#(remrules)$' }, run = run }
gpl-2.0
starlightknight/darkstar
scripts/globals/spells/absorb-vit.lua
12
1565
-------------------------------------- -- Spell: Absorb-VIT -- Steals an enemy's vitality. -------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) if (target:hasStatusEffect(dsp.effect.VIT_DOWN) or caster:hasStatusEffect(dsp.effect.VIT_BOOST)) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) -- no effect else local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) local params = {} params.diff = nil params.attribute = dsp.mod.INT params.skillType = 37 params.bonus = 0 params.effect = nil local resist = applyResistance(caster, target, spell, params) if (resist <= 0.125) then spell:setMsg(dsp.msg.basic.MAGIC_RESIST) else spell:setMsg(dsp.msg.basic.MAGIC_ABSORB_VIT) caster:addStatusEffect(dsp.effect.VIT_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(dsp.mod.AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK) -- caster gains VIT target:addStatusEffect(dsp.effect.VIT_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(dsp.mod.AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK) -- target loses VIT end end return dsp.effect.VIT_DOWN end
gpl-3.0
starlightknight/darkstar
scripts/globals/spells/virus.lua
12
1184
----------------------------------------- -- Spell: Virus ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local effect = dsp.effect.PLAGUE local duration = 60 local pINT = caster:getStat(dsp.mod.INT) local mINT = target:getStat(dsp.mod.INT) local dINT = (pINT - mINT) local params = {} params.diff = nil params.attribute = dsp.mod.INT params.skillType = dsp.skill.ENFEEBLING_MAGIC params.bonus = 0 params.effect = effect local resist = applyResistanceEffect(caster, target, spell, params) if (resist >= 0.5) then -- effect taken duration = duration * resist if (target:addStatusEffect(effect,5,3,duration)) then spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end else -- resist entirely. spell:setMsg(dsp.msg.basic.MAGIC_RESIST) end return effect end
gpl-3.0
starlightknight/darkstar
scripts/globals/spells/regen.lua
12
1129
----------------------------------------- -- Spell: Regen -- Gradually restores target's HP. ----------------------------------------- require("scripts/globals/magic") require("scripts/globals/msg") require("scripts/globals/status") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) local hp = math.ceil(5 * (1 + 0.01 * caster:getMod(dsp.mod.REGEN_MULTIPLIER))) -- spell base times gear multipliers hp = hp + caster:getMerit(dsp.merit.REGEN_EFFECT) -- bonus hp from merits hp = hp + caster:getMod(dsp.mod.LIGHT_ARTS_REGEN) -- bonus hp from light arts local duration = calculateDuration(75 + caster:getMod(dsp.mod.REGEN_DURATION), spell:getSkillType(), spell:getSpellGroup(), caster, target) duration = calculateDurationForLvl(duration, 21, target:getMainLvl()) if target:addStatusEffect(dsp.effect.REGEN, hp, 0, duration) then spell:setMsg(dsp.msg.basic.MAGIC_GAIN_EFFECT) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) -- no effect end return dsp.effect.REGEN end
gpl-3.0
noname007/vanilla
spec/helper.lua
2
1065
package.loaded['config.routes'] = { } package.loaded['config.application'] = {} _G['ngx'] = { HTTP_NOT_FOUND = 404, exit = function(code) return end, print = function(print) return end, status = 200, location = {}, say = print, eof = os.exit, header = {}, req = { read_body = function() return end, get_body_data = function() return end, get_headers = function() return end, get_uri_args = function() return {} end, get_post_args = function() return {busted = 'busted'} end, }, var = { uri = "/users", request_method = 'GET' } } local config={} config.name = 'bluebird' config.route='vanilla.v.routes.simple' config.bootstrap='application.bootstrap' config.app={} config.app.root='./' config.controller={} config.controller.path=config.app.root .. 'application/controllers/' config.view={} config.view.path=config.app.root .. 'application/views/' config.view.suffix='.html' config.view.auto_render=true _G['config'] = config require 'vanilla.spec.runner'
mit
gedads/Neodynamis
scripts/globals/weaponskills/tachi_shoha.lua
22
1782
----------------------------------- -- Tachi: Shoha -- Great Katana weapon skill -- Skill Level: 357 -- Delivers a two-hit attack. Damage varies with TP. -- To obtain Tachi: Shoha, the quest Martial Mastery must be completed and it must be purchased from the Merit Points menu. -- Suspected to have an Attack Bonus similar to Tachi: Yukikaze, Tachi: Gekko, and Tachi: Kasha, but only on the first hit. -- Aligned with the Breeze Gorget, Thunder Gorget & Shadow Gorget. -- Aligned with the Breeze Belt, Thunder Belt & Shadow Belt. -- Element: None -- Modifiers: STR:73~85%, depending on merit points upgrades. -- 100%TP 200%TP 300%TP -- 1.375 2.1875 2.6875 ----------------------------------- 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 = 2; params.ftp100 = 1.375; params.ftp200 = 2.1875; params.ftp300 = 2.6875; params.str_wsc = 0.85 + (player:getMerit(MERIT_TACHI_SHOHA) / 100); 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.375; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.7 + (player:getMerit(MERIT_TACHI_SHOHA) / 100); end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
gedads/Neodynamis
scripts/globals/mobskills/typhoon.lua
34
1116
--------------------------------------------- -- Typhoon -- -- Description: Spins around dealing damage to targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: 2-4 shadows -- Range: 10' radial -- 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 numhits = 4; local accmod = 1; local dmgmod = 0.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); if (mob:getName() == "Faust") then if (mob:getLocalVar("Typhoon") == 0) then mob:useMobAbility(539); mob:setLocalVar("Typhoon", 1); else mob:setLocalVar("Typhoon", 0); end end return dmg; end;
gpl-3.0
mishin/Algorithm-Implementations
Breadth_First_Search/Lua/Yonaba/bfs_test.lua
26
2339
-- Tests for bfs.lua local BFS = require 'bfs' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function same(t, p, comp) for k,v in ipairs(t) do if not comp(v, p[k]) then return false end end return true end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Testing linear graph', function() local comp = function(a, b) return a.value == b end local ln_handler = require 'handlers.linear_handler' ln_handler.init(-2,5) local bfs = BFS(ln_handler) local start, goal = ln_handler.getNode(0), ln_handler.getNode(5) assert(same(bfs:findPath(start, goal), {0,1,2,3,4,5}, comp)) start, goal = ln_handler.getNode(-2), ln_handler.getNode(2) assert(same(bfs:findPath(start, goal), {-2,-1,0,1,2}, comp)) end) run('Testing grid graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local gm_handler = require 'handlers.gridmap_handler' local bfs = BFS(gm_handler) local map = {{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}} gm_handler.init(map) gm_handler.diagonal = false local start, goal = gm_handler.getNode(1,1), gm_handler.getNode(5,3) assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{1,3},{2,3},{3,3},{4,3},{5,3}}, comp)) gm_handler.diagonal = true assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{2,3},{3,3},{4,3},{5,3}}, comp)) end) run('Testing point graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local pg_handler = require 'handlers.point_graph_handler' local bfs = BFS(pg_handler) pg_handler.addNode('a') pg_handler.addNode('b') pg_handler.addNode('c') pg_handler.addNode('d') pg_handler.addEdge('a', 'b') pg_handler.addEdge('a', 'c') pg_handler.addEdge('b', 'd') local comp = function(a, b) return a.name == b end local start, goal = pg_handler.getNode('a'), pg_handler.getNode('d') assert(same(bfs:findPath(start, goal), {'a','b','d'}, comp)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
pravsingh/Algorithm-Implementations
Breadth_First_Search/Lua/Yonaba/bfs_test.lua
26
2339
-- Tests for bfs.lua local BFS = require 'bfs' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function same(t, p, comp) for k,v in ipairs(t) do if not comp(v, p[k]) then return false end end return true end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Testing linear graph', function() local comp = function(a, b) return a.value == b end local ln_handler = require 'handlers.linear_handler' ln_handler.init(-2,5) local bfs = BFS(ln_handler) local start, goal = ln_handler.getNode(0), ln_handler.getNode(5) assert(same(bfs:findPath(start, goal), {0,1,2,3,4,5}, comp)) start, goal = ln_handler.getNode(-2), ln_handler.getNode(2) assert(same(bfs:findPath(start, goal), {-2,-1,0,1,2}, comp)) end) run('Testing grid graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local gm_handler = require 'handlers.gridmap_handler' local bfs = BFS(gm_handler) local map = {{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}} gm_handler.init(map) gm_handler.diagonal = false local start, goal = gm_handler.getNode(1,1), gm_handler.getNode(5,3) assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{1,3},{2,3},{3,3},{4,3},{5,3}}, comp)) gm_handler.diagonal = true assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{2,3},{3,3},{4,3},{5,3}}, comp)) end) run('Testing point graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local pg_handler = require 'handlers.point_graph_handler' local bfs = BFS(pg_handler) pg_handler.addNode('a') pg_handler.addNode('b') pg_handler.addNode('c') pg_handler.addNode('d') pg_handler.addEdge('a', 'b') pg_handler.addEdge('a', 'c') pg_handler.addEdge('b', 'd') local comp = function(a, b) return a.name == b end local start, goal = pg_handler.getNode('a'), pg_handler.getNode('d') assert(same(bfs:findPath(start, goal), {'a','b','d'}, comp)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
telergybot/zspam
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
focusworld/ghost-bot
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
uziins/uzzbot
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
gedads/Neodynamis
scripts/zones/Temple_of_Uggalepih/npcs/Stone_Picture_Frame.lua
3
3762
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Stone Picture Frame -- Notes: Opens door to Den of Rancor using Painbrush of Souls -- !pos -52.239 -2.089 10.000 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); local DoorToRancor = 17428989; if (X < -60) then if (Z < -6) then -- SW frame if (player:hasKeyItem(FINAL_FANTASY)) then player:startEvent(0x0032,FINAL_FANTASY); else player:messageSpecial(PAINTBRUSH_OFFSET + 31); -- This is a frame for a painting. end elseif (Z < 5) then player:messageSpecial(PAINTBRUSH_OFFSET + 14); -- It is a picture of an old mage carrying a staff. else player:messageSpecial(PAINTBRUSH_OFFSET + 13); -- It is a picture of a small group of three men and women. end else if (Z <-5) then -- SE picture player:messageSpecial(PAINTBRUSH_OFFSET + 12); -- It is a painting of a beautiful landscape. elseif (Z > -5 and Z < 5) then if (GetNPCByID(DoorToRancor):getAnimation() == 8) then player:messageSpecial(PAINTBRUSH_OFFSET + 23,PAINTBRUSH_OF_SOULS); -- The <KEY_ITEM> begins to twitch. The canvas is graced with the image from your soul. elseif (player:hasKeyItem(PAINTBRUSH_OF_SOULS) and X >= -53.2 and Z <= 0.1 and Z >= -0.1) then -- has paintbrush of souls + close enough player:messageSpecial(PAINTBRUSH_OFFSET + 17,PAINTBRUSH_OF_SOULS); player:setVar("started_painting",os.time()); player:startEvent(0x003C,PAINTBRUSH_OF_SOULS); elseif (player:hasKeyItem(PAINTBRUSH_OF_SOULS)) then player:messageSpecial(PAINTBRUSH_OFFSET + 15,PAINTBRUSH_OF_SOULS); else player:messageSpecial(PAINTBRUSH_OFFSET, PAINTBRUSH_OF_SOULS); -- When the paintbrush of souls projects the deepest, darkest corner of your soul... end else player:messageSpecial(PAINTBRUSH_OFFSET + 11); -- It is a painting of a sublime-looking woman. end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local DoorToRancor = 17428989; if (csid == 0x0032) then -- Soon ! elseif (csid == 0x003C) then time_elapsed = os.time() - player:getVar("started_painting"); if (time_elapsed >= 30) then player:messageSpecial(PAINTBRUSH_OFFSET + 22); -- You succeeded in projecting the image in your soul to the blank canvas. The door to the Rancor Den has opened!<Prompt> GetNPCByID(DoorToRancor):openDoor(45); -- Open the door to Den of Rancor for 45 sec else player:messageSpecial(PAINTBRUSH_OFFSET + 21); -- You were unable to fill the canvas with an image from your soul. end player:setVar("started_painting",0); end end;
gpl-3.0
tommy3/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/function.lua
25
14265
-- tolua: function class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Function class -- Represents a function or a class method. -- The following fields are stored: -- mod = type modifiers -- type = type -- ptr = "*" or "&", if representing a pointer or a reference -- name = name -- lname = lua name -- args = list of argument declarations -- const = if it is a method receiving a const "this". classFunction = { mod = '', type = '', ptr = '', name = '', args = {n=0}, const = '', } classFunction.__index = classFunction setmetatable(classFunction,classFeature) -- declare tags function classFunction:decltype () self.type = typevar(self.type) if strfind(self.mod,'const') then self.type = 'const '..self.type self.mod = gsub(self.mod,'const','') end local i=1 while self.args[i] do self.args[i]:decltype() i = i+1 end end -- Write binding function -- Outputs C/C++ binding function. function classFunction:supcode (local_constructor) local overload = strsub(self.cname,-2,-1) - 1 -- indicate overloaded func local nret = 0 -- number of returned values local class = self:inclass() local _,_,static = strfind(self.mod,'^%s*(static)') if class then if self.name == 'new' and self.parent.flags.pure_virtual then -- no constructor for classes with pure virtual methods return end if local_constructor then output("/* method: new_local of class ",class," */") else output("/* method:",self.name," of class ",class," */") end else output("/* function:",self.name," */") end if local_constructor then output("#ifndef TOLUA_DISABLE_"..self.cname.."_local") output("\nstatic int",self.cname.."_local","(lua_State* tolua_S)") else output("#ifndef TOLUA_DISABLE_"..self.cname) output("\nstatic int",self.cname,"(lua_State* tolua_S)") end output("{") -- check types if overload < 0 then output('#ifndef TOLUA_RELEASE\n') end output(' tolua_Error tolua_err;') output(' if (\n') -- check self local narg if class then narg=2 else narg=1 end if class then local func = get_is_function(self.parent.type) local type = self.parent.type if self.name=='new' or static~=nil then func = 'tolua_isusertable' type = self.parent.type end if self.const ~= '' then type = "const "..type end output(' !'..func..'(tolua_S,1,"'..type..'",0,&tolua_err) ||\n') end -- check args if self.args[1].type ~= 'void' then local i=1 while self.args[i] do local btype = isbasic(self.args[i].type) if btype ~= 'value' and btype ~= 'state' then output(' '..self.args[i]:outchecktype(narg)..' ||\n') end if btype ~= 'state' then narg = narg+1 end i = i+1 end end -- check end of list output(' !tolua_isnoobj(tolua_S,'..narg..',&tolua_err)\n )') output(' goto tolua_lerror;') output(' else\n') if overload < 0 then output('#endif\n') end output(' {') -- declare self, if the case local narg if class then narg=2 else narg=1 end if class and self.name~='new' and static==nil then output(' ',self.const,self.parent.type,'*','self = ') output('(',self.const,self.parent.type,'*) ') local to_func = get_to_function(self.parent.type) output(to_func,'(tolua_S,1,0);') elseif static then _,_,self.mod = strfind(self.mod,'^%s*static%s%s*(.*)') end -- declare parameters if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:declare(narg) if isbasic(self.args[i].type) ~= "state" then narg = narg+1 end i = i+1 end end -- check self if class and self.name~='new' and static==nil then output('#ifndef TOLUA_RELEASE\n') output(' if (!self) tolua_error(tolua_S,"'..output_error_hook("invalid \'self\' in function \'%s\'", self.name)..'", NULL);'); output('#endif\n') end -- get array element values if class then narg=2 else narg=1 end if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:getarray(narg) narg = narg+1 i = i+1 end end pre_call_hook(self) local out = string.find(self.mod, "tolua_outside") -- call function if class and self.name=='delete' then output(' Mtolua_delete(self);') elseif class and self.name == 'operator&[]' then if flags['1'] then -- for compatibility with tolua5 ? output(' self->operator[](',self.args[1].name,'-1) = ',self.args[2].name,';') else output(' self->operator[](',self.args[1].name,') = ',self.args[2].name,';') end else output(' {') if self.type ~= '' and self.type ~= 'void' then output(' ',self.mod,self.type,self.ptr,'tolua_ret = ') output('(',self.mod,self.type,self.ptr,') ') else output(' ') end if class and self.name=='new' then output('Mtolua_new((',self.type,')(') elseif class and static then if out then output(self.name,'(') else output(class..'::'..self.name,'(') end elseif class then if out then output(self.name,'(') else if self.cast_operator then --output('static_cast<',self.mod,self.type,self.ptr,' >(*self') output('self->operator ',self.mod,self.type,'(') else output('self->'..self.name,'(') end end else output(self.name,'(') end if out and not static then output('self') if self.args[1] and self.args[1].name ~= '' then output(',') end end -- write parameters local i=1 while self.args[i] do self.args[i]:passpar() i = i+1 if self.args[i] then output(',') end end if class and self.name == 'operator[]' and flags['1'] then output('-1);') else if class and self.name=='new' then output('));') -- close Mtolua_new( else output(');') end end -- return values if self.type ~= '' and self.type ~= 'void' then nret = nret + 1 local t,ct = isbasic(self.type) if t and self.name ~= "new" then if self.cast_operator and _basic_raw_push[t] then output(' ',_basic_raw_push[t],'(tolua_S,(',ct,')tolua_ret);') else output(' tolua_push'..t..'(tolua_S,(',ct,')tolua_ret);') end else t = self.type new_t = string.gsub(t, "const%s+", "") local owned = false if string.find(self.mod, "tolua_owned") then owned = true end local push_func = get_push_function(t) if self.ptr == '' then output(' {') output('#ifdef __cplusplus\n') output(' void* tolua_obj = Mtolua_new((',new_t,')(tolua_ret));') output(' ',push_func,'(tolua_S,tolua_obj,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') output('#else\n') output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(',t,'));') output(' ',push_func,'(tolua_S,tolua_obj,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') output('#endif\n') output(' }') elseif self.ptr == '&' then output(' ',push_func,'(tolua_S,(void*)&tolua_ret,"',t,'");') else output(' ',push_func,'(tolua_S,(void*)tolua_ret,"',t,'");') if owned or local_constructor then output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') end end end end local i=1 while self.args[i] do nret = nret + self.args[i]:retvalue() i = i+1 end output(' }') -- set array element values if class then narg=2 else narg=1 end if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:setarray(narg) narg = narg+1 i = i+1 end end -- free dynamically allocated array if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:freearray() i = i+1 end end end post_call_hook(self) output(' }') output(' return '..nret..';') -- call overloaded function or generate error if overload < 0 then output('#ifndef TOLUA_RELEASE\n') output('tolua_lerror:\n') output(' tolua_error(tolua_S,"'..output_error_hook("#ferror in function \'%s\'.", self.lname)..'",&tolua_err);') output(' return 0;') output('#endif\n') else local _local = "" if local_constructor then _local = "_local" end output('tolua_lerror:\n') output(' return '..strsub(self.cname,1,-3)..format("%02d",overload).._local..'(tolua_S);') end output('}') output('#endif //#ifndef TOLUA_DISABLE\n') output('\n') -- recursive call to write local constructor if class and self.name=='new' and not local_constructor then self:supcode(1) end end -- register function function classFunction:register (pre) if not self:check_public_access() then return end if self.name == 'new' and self.parent.flags.pure_virtual then -- no constructor for classes with pure virtual methods return end output(pre..'tolua_function(tolua_S,"'..self.lname..'",'..self.cname..');') if self.name == 'new' then output(pre..'tolua_function(tolua_S,"new_local",'..self.cname..'_local);') output(pre..'tolua_function(tolua_S,".call",'..self.cname..'_local);') --output(' tolua_set_call_event(tolua_S,'..self.cname..'_local, "'..self.parent.type..'");') end end -- Print method function classFunction:print (ident,close) print(ident.."Function{") print(ident.." mod = '"..self.mod.."',") print(ident.." type = '"..self.type.."',") print(ident.." ptr = '"..self.ptr.."',") print(ident.." name = '"..self.name.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." const = '"..self.const.."',") print(ident.." cname = '"..self.cname.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." args = {") local i=1 while self.args[i] do self.args[i]:print(ident.." ",",") i = i+1 end print(ident.." }") print(ident.."}"..close) end -- check if it returns an object by value function classFunction:requirecollection (t) local r = false if self.type ~= '' and not isbasic(self.type) and self.ptr=='' then local type = gsub(self.type,"%s*const%s+","") t[type] = "tolua_collect_" .. clean_template(type) r = true end local i=1 while self.args[i] do r = self.args[i]:requirecollection(t) or r i = i+1 end return r end -- determine lua function name overload function classFunction:overload () return self.parent:overload(self.lname) end function param_object(par) -- returns true if the parameter has an object as its default value if not string.find(par, '=') then return false end -- it has no default value local _,_,def = string.find(par, "=(.*)$") if string.find(par, "|") then -- a list of flags return true end if string.find(par, "%*") then -- it's a pointer with a default value if string.find(par, '=%s*new') or string.find(par, "%(") then -- it's a pointer with an instance as default parameter.. is that valid? return true end return false -- default value is 'NULL' or something end if string.find(par, "[%(&]") then return true end -- default value is a constructor call (most likely for a const reference) --if string.find(par, "&") then -- if string.find(def, ":") or string.find(def, "^%s*new%s+") then -- -- it's a reference with default to something like Class::member, or 'new Class' -- return true -- end --end return false -- ? end function strip_last_arg(all_args, last_arg) -- strips the default value from the last argument local _,_,s_arg = string.find(last_arg, "^([^=]+)") last_arg = string.gsub(last_arg, "([%%%(%)])", "%%%1"); all_args = string.gsub(all_args, "%s*,%s*"..last_arg.."%s*%)%s*$", ")") return all_args, s_arg end -- Internal constructor function _Function (t) setmetatable(t,classFunction) if t.const ~= 'const' and t.const ~= '' then error("#invalid 'const' specification") end append(t) if t:inclass() then --print ('t.name is '..t.name..', parent.name is '..t.parent.name) if string.gsub(t.name, "%b<>", "") == string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then t.name = 'new' t.lname = 'new' t.parent._new = true t.type = t.parent.name t.ptr = '*' elseif string.gsub(t.name, "%b<>", "") == '~'..string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then t.name = 'delete' t.lname = 'delete' t.parent._delete = true end end t.cname = t:cfuncname("tolua")..t:overload(t) return t end -- Constructor -- Expects three strings: one representing the function declaration, -- another representing the argument list, and the third representing -- the "const" or empty string. function Function (d,a,c) --local t = split(strsub(a,2,-2),',') -- eliminate braces --local t = split_params(strsub(a,2,-2)) if not flags['W'] and string.find(a, "%.%.%.%s*%)") then warning("Functions with variable arguments (`...') are not supported. Ignoring "..d..a..c) return nil end local i=1 local l = {n=0} a = string.gsub(a, "%s*([%(%)])%s*", "%1") local t,strip,last = strip_pars(strsub(a,2,-2)); if strip then --local ns = string.sub(strsub(a,1,-2), 1, -(string.len(last)+1)) local ns = join(t, ",", 1, last-1) ns = "("..string.gsub(ns, "%s*,%s*$", "")..')' --ns = strip_defaults(ns) local f = Function(d, ns, c) for i=1,last do t[i] = string.gsub(t[i], "=.*$", "") end end while t[i] do l.n = l.n+1 l[l.n] = Declaration(t[i],'var',true) i = i+1 end local f = Declaration(d,'func') f.args = l f.const = c return _Function(f) end function join(t, sep, first, last) first = first or 1 last = last or table.getn(t) local lsep = "" local ret = "" local loop = false for i = first,last do ret = ret..lsep..t[i] lsep = sep loop = true end if not loop then return "" end return ret end function strip_pars(s) local t = split_c_tokens(s, ',') local strip = false local last for i=t.n,1,-1 do if not strip and param_object(t[i]) then last = i strip = true end --if strip then -- t[i] = string.gsub(t[i], "=.*$", "") --end end return t,strip,last end function strip_defaults(s) s = string.gsub(s, "^%(", "") s = string.gsub(s, "%)$", "") local t = split_c_tokens(s, ",") local sep, ret = "","" for i=1,t.n do t[i] = string.gsub(t[i], "=.*$", "") ret = ret..sep..t[i] sep = "," end return "("..ret..")" end
mit
gedads/Neodynamis
scripts/zones/Windurst_Waters_[S]/npcs/Ranna-Brunna.lua
3
1065
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ranna-Brunna -- Type: Standard NPC -- @zone 94 -- !pos 123.085 -8.874 223.734 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01a8); 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
gedads/Neodynamis
scripts/globals/items/moon_carrot.lua
12
1181
----------------------------------------- -- ID: 4567 -- Item: moon_carrot -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -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,300,4567); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Open_sea_route_to_Mhaura/npcs/Sheadon.lua
3
1144
----------------------------------- -- Area: Open_sea_route_to_Mhaura -- NPC: Sheadon -- Notes: Tells ship ETA time -- !pos 0.340 -12.232 -4.120 47 ----------------------------------- package.loaded["scripts/zones/Open_sea_route_to_Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Open_sea_route_to_Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(ON_WAY_TO_MHAURA,0,0); -- Earth Time, Vana Hours. Needs a get-time function for boat? 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
tst2005/lua-penlight
tests/test-xml.lua
8
10800
local xml = require 'pl.xml' local asserteq = require 'pl.test'.asserteq local dump = require 'pl.pretty'.dump -- Prosody stanza.lua style XML building d = xml.new 'top' : addtag 'child' : text 'alice' : up() : addtag 'child' : text 'bob' d = xml.new 'children' : addtag 'child' : addtag 'name' : text 'alice' : up() : addtag 'age' : text '5' : up() : addtag('toy',{type='fluffy'}) : up() : up() : addtag 'child': addtag 'name' : text 'bob' : up() : addtag 'age' : text '6' : up() : addtag('toy',{type='squeaky'}) asserteq( xml.tostring(d,'',' '), [[ <children> <child> <name>alice</name> <age>5</age> <toy type='fluffy'/> </child> <child> <name>bob</name> <age>6</age> <toy type='squeaky'/> </child> </children>]]) -- Orbit-style 'xmlification' local children,child,toy,name,age = xml.tags 'children, child, toy, name, age' d1 = children { child {name 'alice', age '5', toy {type='fluffy'}}, child {name 'bob', age '6', toy {type='squeaky'}} } assert(xml.compare(d,d1)) -- or we can use a template document to convert Lua data to LOM templ = child {name '$name', age '$age', toy{type='$toy'}} d2 = children(templ:subst{ {name='alice',age='5',toy='fluffy'}, {name='bob',age='6',toy='squeaky'} }) assert(xml.compare(d1,d2)) -- Parsing Google Weather service results -- local joburg = [[ <?xml version="1.0"?> <xml_api_reply version='1'> <weather module_id='0' tab_id='0' mobile_zipped='1' section='0' row='0' mobile_row='0'> <forecast_information> <city data='Johannesburg, Gauteng'/> <postal_code data='Johannesburg,ZA'/> <latitude_e6 data=''/> <longitude_e6 data=''/> <forecast_date data='2010-10-02'/> <current_date_time data='2010-10-02 18:30:00 +0000'/> <unit_system data='US'/> </forecast_information> <current_conditions> <condition data='Clear'/> <temp_f data='75'/> <temp_c data='24'/> <humidity data='Humidity: 19%'/> <icon data='/ig/images/weather/sunny.gif'/> <wind_condition data='Wind: NW at 7 mph'/> </current_conditions> <forecast_conditions> <day_of_week data='Sat'/> <low data='60'/> <high data='89'/> <icon data='/ig/images/weather/sunny.gif'/> <condition data='Clear'/> </forecast_conditions> <forecast_conditions> <day_of_week data='Sun'/> <low data='53'/> <high data='86'/> <icon data='/ig/images/weather/sunny.gif'/> <condition data='Clear'/> </forecast_conditions> <forecast_conditions> <day_of_week data='Mon'/> <low data='57'/> <high data='87'/> <icon data='/ig/images/weather/sunny.gif'/> <condition data='Clear'/> </forecast_conditions> <forecast_conditions> <day_of_week data='Tue'/> <low data='60'/> <high data='84'/> <icon data='/ig/images/weather/sunny.gif'/> <condition data='Clear'/> </forecast_conditions> </weather> </xml_api_reply> ]] -- we particularly want to test the built-in XML parser here, not lxp.lom local function parse (str) return xml.parse(str,false,true) end local d = parse(joburg) function match(t,xpect) local res,ret = d:match(t) asserteq(res,xpect,0,1) ---> note extra level, so we report on calls to this function! end t1 = [[ <weather> <current_conditions> <condition data='$condition'/> <temp_c data='$temp'/> </current_conditions> </weather> ]] match(t1,{ condition = "Clear", temp = "24", } ) t2 = [[ <weather> {{<forecast_conditions> <day_of_week data='$day'/> <low data='$low'/> <high data='$high'/> <condition data='$condition'/> </forecast_conditions>}} </weather> ]] local conditions = { { low = "60", high = "89", day = "Sat", condition = "Clear", }, { low = "53", high = "86", day = "Sun", condition = "Clear", }, { low = "57", high = "87", day = "Mon", condition = "Clear", }, { low = "60", high = "84", day = "Tue", condition = "Clear", } } match(t2,conditions) config = [[ <config> <alpha>1.3</alpha> <beta>10</beta> <name>bozo</name> </config> ]] d,err = parse(config) if not d then print(err); os.exit(1) end -- can match against wildcard tag names (end with -) -- can be names match([[ <config> {{<key->$value</key->}} </config> ]],{ {key="alpha", value = "1.3"}, {key="beta", value = "10"}, {key="name",value = "bozo"}, }) -- can be numerical indices match([[ <config> {{<1->$2</1->}} </config> ]],{ {"alpha","1.3"}, {"beta","10"}, {"name","bozo"}, }) -- _ is special; means 'this value is key of captured table' match([[ <config> {{<_->$1</_->}} </config> ]],{ alpha = {"1.3"}, beta = {"10"}, name = {"bozo"}, }) -- the numerical index 0 is special: a capture of {[0]=val} becomes simply the value val match([[ <config> {{<_->$0</_->}} </config> ]],{ alpha = "1.3", name = "bozo", beta = "10" }) -- this can of course also work with attributes, but then we don't want to collapse! config = [[ <config> <alpha type='number'>1.3</alpha> <beta type='number'>10</beta> <name type='string'>bozo</name> </config> ]] d,err = parse(config) if not d then print(err); os.exit(1) end match([[ <config> {{<_- type='$1'>$2</_->}} </config> ]],{ alpha = {"number","1.3"}, beta = {"number","10"}, name = {"string","bozo"}, }) d,err = parse [[ <configuremap> <configure name="NAME" value="ImageMagick"/> <configure name="LIB_VERSION" value="0x651"/> <configure name="LIB_VERSION_NUMBER" value="6,5,1,3"/> <configure name="RELEASE_DATE" value="2009-05-01"/> <configure name="VERSION" value="6.5.1"/> <configure name="CC" value="vs7"/> <configure name="HOST" value="windows-unknown-linux-gnu"/> <configure name="DELEGATES" value="bzlib freetype jpeg jp2 lcms png tiff x11 xml wmf zlib"/> <configure name="COPYRIGHT" value="Copyright (C) 1999-2009 ImageMagick Studio LLC"/> <configure name="WEBSITE" value="http://www.imagemagick.org"/> </configuremap> ]] if not d then print(err); os.exit(1) end --xml.debug = true res,err = d:match [[ <configuremap> {{<configure name="$_" value="$0"/>}} </configuremap> ]] asserteq(res,{ HOST = "windows-unknown-linux-gnu", COPYRIGHT = "Copyright (C) 1999-2009 ImageMagick Studio LLC", NAME = "ImageMagick", LIB_VERSION = "0x651", VERSION = "6.5.1", RELEASE_DATE = "2009-05-01", WEBSITE = "http://www.imagemagick.org", LIB_VERSION_NUMBER = "6,5,1,3", CC = "vs7", DELEGATES = "bzlib freetype jpeg jp2 lcms png tiff x11 xml wmf zlib" }) -- short excerpt from -- /usr/share/mobile-broadband-provider-info/serviceproviders.xml d = parse [[ <serviceproviders format="2.0"> <country code="za"> <provider> <name>Cell-c</name> <gsm> <network-id mcc="655" mnc="07"/> <apn value="internet"> <username>Cellcis</username> <dns>196.7.0.138</dns> <dns>196.7.142.132</dns> </apn> </gsm> </provider> <provider> <name>MTN</name> <gsm> <network-id mcc="655" mnc="10"/> <apn value="internet"> <dns>196.11.240.241</dns> <dns>209.212.97.1</dns> </apn> </gsm> </provider> <provider> <name>Vodacom</name> <gsm> <network-id mcc="655" mnc="01"/> <apn value="internet"> <dns>196.207.40.165</dns> <dns>196.43.46.190</dns> </apn> <apn value="unrestricted"> <name>Unrestricted</name> <dns>196.207.32.69</dns> <dns>196.43.45.190</dns> </apn> </gsm> </provider> <provider> <name>Virgin Mobile</name> <gsm> <apn value="vdata"> <dns>196.7.0.138</dns> <dns>196.7.142.132</dns> </apn> </gsm> </provider> </country> </serviceproviders> ]] res = d:match [[ <serviceproviders> {{<country code="$_"> {{<provider> <name>$0</name> </provider>}} </country>}} </serviceproviders> ]] asserteq(res,{ za = { "Cell-c", "MTN", "Vodacom", "Virgin Mobile" } }) res = d:match [[ <serviceproviders> <country code="$country"> <provider> <name>$name</name> <gsm> <apn value="$apn"> <dns>196.43.46.190</dns> </apn> </gsm> </provider> </country> </serviceproviders> ]] asserteq(res,{ name = "Vodacom", country = "za", apn = "internet" }) d = parse[[ <!DOCTYPE xml> <params> <param> <name>XXX</name> <value></value> </param> <param> <name>YYY</name> <value>1</value> </param> </params> ]] match([[ <params> {{<param> <name>$_</name> <value>$0</value> </param>}} </params> ]],{XXX = '',YYY = '1'}) -- can always use xmlification to generate your templates... local SP, country, provider, gsm, apn, dns = xml.tags 'serviceprovider, country, provider, gsm, apn, dns' t = SP{country{code="$country",provider{ name '$name', gsm{apn {value="$apn",dns '196.43.46.190'}} }}} out = xml.tostring(t,' ',' ') asserteq(out,[[ <serviceprovider> <country code='$country'> <provider> <name>$name</name> <gsm> <apn value='$apn'> <dns>196.43.46.190</dns> </apn> </gsm> </provider> </country> </serviceprovider>]]) ----- HTML is a degenerate form of XML ;) -- attribute values don't need to be quoted, tags are case insensitive, -- and some are treated as self-closing doc = xml.parsehtml [[ <BODY a=1> Hello dolly<br> HTML is <b>slack</b><br> </BODY> ]] asserteq(xml.tostring(doc),[[ <body a='1'> Hello dolly<br/> HTML is <b>slack</b><br/></body>]]) doc = xml.parsehtml [[ <!DOCTYPE html> <html lang=en> <head><!--head man--> </head> <body> </body> </html> ]] asserteq(xml.tostring(doc),"<html lang='en'><head/><body/></html>") -- note that HTML mode currently barfs if there isn't whitespace around things -- like '<' and '>' in scripts. doc = xml.parsehtml [[ <html> <head> <script>function less(a,b) { return a < b; }</script> </head> <body> <h2>hello dammit</h2> </body> </html> ]] script = doc:get_elements_with_name 'script' asserteq(script[1]:get_text(), 'function less(a,b) { return a < b; }') -- test attribute order local test_attrlist = xml.new('AttrList',{ Attr3="Value3", ['Attr1'] = "Value1", ['Attr2'] = "Value2", [1] = 'Attr1', [2] = 'Attr2', [3] = 'Attr3' }) asserteq( xml.tostring(test_attrlist), "<AttrList Attr1='Value1' Attr2='Value2' Attr3='Value3'/>" ) -- commments str = [[ <hello> <!-- any <i>momentous</i> stuff here --> dolly </hello> ]] doc = parse(str) asserteq(xml.tostring(doc),[[ <hello> dolly </hello>]]) -- underscores and dashes in attributes str = [[ <hello> <tag my_attribute='my_value'>dolly</tag> </hello> ]] doc = parse(str) print(doc) print(xml.tostring(doc)) asserteq(xml.tostring(doc),[[ <hello><tag my_attribute='my_value'>dolly</tag></hello>]])
mit
starlightknight/darkstar
scripts/globals/mobskills/head_butt_turtle.lua
11
1053
--------------------------------------------------- -- Head Butt (Adamantoise) -- Deals damage to single target. Additional effects: Accuracy Down and large knockback --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 3 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,info.hitslanded) -- Large Knockdown ---------------------------- local typeEffect = dsp.effect.ACCURACY_DOWN MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 50, 0, 120) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT) return dmg end
gpl-3.0
zzzaaiidd/TCHUKY
plugins/zzaiddd6.lua
2
1076
do function run(msg, matches) return [[ ▫️الـبـوت الـذي يـعـمـل عـلـى مـجـمـوعـات الـسـوبـر ▫️يـعـمـل الـبـوت عـلـى مـجـمـوعـات سـوبـر تـصـل الـى 5 K عـضـو ≪ تـم صـنـع الـبـوت بـواسـطـه الـمـطـور ≫ 『 @zzaiddd 』 ▫️الـمـطـور : زيـــــد > @zzaiddd ▫️كـل مـا هـو جـديـد عـلـى قـنـاه الـسـورس [ @zzzaiddd ] ▫️للاسـتفـسـار راسـل الـمـطـور : @zzaiddd Programmable bot : @zzaiddd▫️ Bot continues coder : @zzaiddd_bot ▫️ ]] end return { description = "Shows bot q", usage = "spam Shows bot q", patterns = { "^(المطور)$", }, run = run } end
gpl-2.0
sudosurootdev/external_skia
tools/lua/bitmap_statistics.lua
207
1862
function string.startsWith(String,Start) return string.sub(String,1,string.len(Start))==Start end function string.endsWith(String,End) return End=='' or string.sub(String,-string.len(End))==End end local canvas = nil local num_perspective_bitmaps = 0 local num_affine_bitmaps = 0 local num_scaled_bitmaps = 0 local num_translated_bitmaps = 0 local num_identity_bitmaps = 0 local num_scaled_up = 0 local num_scaled_down = 0 function sk_scrape_startcanvas(c, fileName) canvas = c end function sk_scrape_endcanvas(c, fileName) canvas = nil end function sk_scrape_accumulate(t) -- dump the params in t, specifically showing the verb first, which we -- then nil out so it doesn't appear in tostr() if (string.startsWith(t.verb,"drawBitmap")) then matrix = canvas:getTotalMatrix() matrixType = matrix:getType() if matrixType.perspective then num_perspective_bitmaps = num_perspective_bitmaps + 1 elseif matrixType.affine then num_affine_bitmaps = num_affine_bitmaps + 1 elseif matrixType.scale then num_scaled_bitmaps = num_scaled_bitmaps + 1 if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then num_scaled_up = num_scaled_up + 1 else num_scaled_down = num_scaled_down + 1 end elseif matrixType.translate then num_translated_bitmaps = num_translated_bitmaps + 1 else num_identity_bitmaps = num_identity_bitmaps + 1 end end end function sk_scrape_summarize() io.write( "identity = ", num_identity_bitmaps, ", translated = ", num_translated_bitmaps, ", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")", ", affine = ", num_affine_bitmaps, ", perspective = ", num_perspective_bitmaps, "\n") end
bsd-3-clause
starlightknight/darkstar
scripts/zones/Windurst_Waters/npcs/Fuepepe.lua
9
3465
----------------------------------- -- Area: Windurst Waters -- NPC: Fuepepe -- Starts and Finishes Quest: Teacher's Pet -- Involved in Quest: Making the grade, Class Reunion -- !pos 161 -2 161 238 ----------------------------------- local ID = require("scripts/zones/Windurst_Waters/IDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.MAKING_THE_GRADE) == QUEST_ACCEPTED and player:getCharVar("QuestMakingTheGrade_prog") == 0) then if (trade:hasItemQty(544,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then player:startEvent(455); -- Quest Progress: Test Papers Shown and told to deliver them to principal end end end; function onTrigger(player,npc) local gradestatus = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.MAKING_THE_GRADE); local prog = player:getCharVar("QuestMakingTheGrade_prog"); -- 1 = answers found -- 2 = gave test answers to principle -- 3 = spoke to chomoro if (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.TEACHER_S_PET) == QUEST_COMPLETED and gradestatus == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >=3 and player:getQuestStatus(WINDURST,dsp.quest.id.windurst.LET_SLEEPING_DOGS_LIE) ~= QUEST_ACCEPTED) then player:startEvent(442); -- Quest Start elseif (gradestatus == QUEST_ACCEPTED) then if (prog == 0) then player:startEvent(443); -- Get Test Sheets Reminder elseif (prog == 1) then player:startEvent(456); -- Deliver Test Sheets Reminder elseif (prog == 2 or prog == 3) then player:startEvent(458); -- Quest Finish end elseif (gradestatus == QUEST_COMPLETED and player:needToZone() == true) then player:startEvent(459); -- After Quest ------------------------------------------------------- -- Class Reunion elseif (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.CLASS_REUNION) == QUEST_ACCEPTED and player:getCharVar("ClassReunionProgress") >= 3 and player:getCharVar("ClassReunion_TalkedToFupepe") ~= 1) then player:startEvent(817); -- he tells you about Uran-Mafran ------------------------------------------------------- else player:startEvent(423); -- Standard Conversation end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 442 and option == 1) then -- Quest Start player:addQuest(WINDURST,dsp.quest.id.windurst.MAKING_THE_GRADE); elseif (csid == 455) then -- Quest Progress: Test Papers Shown and told to deliver them to principal player:setCharVar("QuestMakingTheGrade_prog",1); elseif (csid == 458) then -- Quest Finish if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,4855); else player:tradeComplete(); player:completeQuest(WINDURST,dsp.quest.id.windurst.MAKING_THE_GRADE); player:addFame(WINDURST,75); player:addItem(4855); player:messageSpecial(ID.text.ITEM_OBTAINED,4855); player:setCharVar("QuestMakingTheGrade_prog",0); player:needToZone(true); end elseif (csid == 817) then player:setCharVar("ClassReunion_TalkedToFupepe",1); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Abyssea-Misareaux/npcs/qm3.lua
3
1352
----------------------------------- -- Zone: Abyssea-Misareaux -- NPC: qm3 (???) -- Spawns Funeral Apkallu -- !pos ? ? ? 216 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3087,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17662466) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17662466):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3087); -- Inform player what items they need. 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
starlightknight/darkstar
scripts/zones/Bastok_Mines/npcs/Titus.lua
12
1194
----------------------------------- -- Area: Bastok Mines -- NPC: Titus -- Alchemy Synthesis Image Support ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); local ID = require("scripts/zones/Bastok_Mines/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,1); local SkillCap = getCraftSkillCap(player,dsp.skill.ALCHEMY); local SkillLevel = player:getSkillLevel(dsp.skill.ALCHEMY); if (guildMember == 1) then if (player:hasStatusEffect(dsp.effect.ALCHEMY_IMAGERY) == false) then player:startEvent(123,SkillCap,SkillLevel,1,137,player:getGil(),0,0,0); else player:startEvent(123,SkillCap,SkillLevel,1,137,player:getGil(),6758,0,0); end else player:startEvent(123); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 123 and option == 1) then player:messageSpecial(ID.text.ALCHEMY_SUPPORT,0,7,1); player:addStatusEffect(dsp.effect.ALCHEMY_IMAGERY,1,0,120); end end;
gpl-3.0
soulgame/slua
build/luajit-2.1.0-beta3/src/jit/p.lua
55
9135
---------------------------------------------------------------------------- -- LuaJIT profiler. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module is a simple command line interface to the built-in -- low-overhead profiler of LuaJIT. -- -- The lower-level API of the profiler is accessible via the "jit.profile" -- module or the luaJIT_profile_* C API. -- -- Example usage: -- -- luajit -jp myapp.lua -- luajit -jp=s myapp.lua -- luajit -jp=-s myapp.lua -- luajit -jp=vl myapp.lua -- luajit -jp=G,profile.txt myapp.lua -- -- The following dump features are available: -- -- f Stack dump: function name, otherwise module:line. Default mode. -- F Stack dump: ditto, but always prepend module. -- l Stack dump: module:line. -- <number> stack dump depth (callee < caller). Default: 1. -- -<number> Inverse stack dump depth (caller > callee). -- s Split stack dump after first stack level. Implies abs(depth) >= 2. -- p Show full path for module names. -- v Show VM states. Can be combined with stack dumps, e.g. vf or fv. -- z Show zones. Can be combined with stack dumps, e.g. zf or fz. -- r Show raw sample counts. Default: show percentages. -- a Annotate excerpts from source code files. -- A Annotate complete source code files. -- G Produce raw output suitable for graphical tools (e.g. flame graphs). -- m<number> Minimum sample percentage to be shown. Default: 3. -- i<number> Sampling interval in milliseconds. Default: 10. -- ---------------------------------------------------------------------------- -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local profile = require("jit.profile") local vmdef = require("jit.vmdef") local math = math local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor local sort, format = table.sort, string.format local stdout = io.stdout local zone -- Load jit.zone module on demand. -- Output file handle. local out ------------------------------------------------------------------------------ local prof_ud local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth local prof_ann, prof_count1, prof_count2, prof_samples local map_vmmode = { N = "Compiled", I = "Interpreted", C = "C code", G = "Garbage Collector", J = "JIT Compiler", } -- Profiler callback. local function prof_cb(th, samples, vmmode) prof_samples = prof_samples + samples local key_stack, key_stack2, key_state -- Collect keys for sample. if prof_states then if prof_states == "v" then key_state = map_vmmode[vmmode] or vmmode else key_state = zone:get() or "(none)" end end if prof_fmt then key_stack = profile.dumpstack(th, prof_fmt, prof_depth) key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x) return vmdef.ffnames[tonumber(x)] end) if prof_split == 2 then local k1, k2 = key_stack:match("(.-) [<>] (.*)") if k2 then key_stack, key_stack2 = k1, k2 end elseif prof_split == 3 then key_stack2 = profile.dumpstack(th, "l", 1) end end -- Order keys. local k1, k2 if prof_split == 1 then if key_state then k1 = key_state if key_stack then k2 = key_stack end end elseif key_stack then k1 = key_stack if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end end -- Coalesce samples in one or two levels. if k1 then local t1 = prof_count1 t1[k1] = (t1[k1] or 0) + samples if k2 then local t2 = prof_count2 local t3 = t2[k1] if not t3 then t3 = {}; t2[k1] = t3 end t3[k2] = (t3[k2] or 0) + samples end end end ------------------------------------------------------------------------------ -- Show top N list. local function prof_top(count1, count2, samples, indent) local t, n = {}, 0 for k in pairs(count1) do n = n + 1 t[n] = k end sort(t, function(a, b) return count1[a] > count1[b] end) for i=1,n do local k = t[i] local v = count1[k] local pct = floor(v*100/samples + 0.5) if pct < prof_min then break end if not prof_raw then out:write(format("%s%2d%% %s\n", indent, pct, k)) elseif prof_raw == "r" then out:write(format("%s%5d %s\n", indent, v, k)) else out:write(format("%s %d\n", k, v)) end if count2 then local r = count2[k] if r then prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or (prof_depth < 0 and " -> " or " <- ")) end end end end -- Annotate source code local function prof_annotate(count1, samples) local files = {} local ms = 0 for k, v in pairs(count1) do local pct = floor(v*100/samples + 0.5) ms = math.max(ms, v) if pct >= prof_min then local file, line = k:match("^(.*):(%d+)$") if not file then file = k; line = 0 end local fl = files[file] if not fl then fl = {}; files[file] = fl; files[#files+1] = file end line = tonumber(line) fl[line] = prof_raw and v or pct end end sort(files) local fmtv, fmtn = " %3d%% | %s\n", " | %s\n" if prof_raw then local n = math.max(5, math.ceil(math.log10(ms))) fmtv = "%"..n.."d | %s\n" fmtn = (" "):rep(n).." | %s\n" end local ann = prof_ann for _, file in ipairs(files) do local f0 = file:byte() if f0 == 40 or f0 == 91 then out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file)) break end local fp, err = io.open(file) if not fp then out:write(format("====== ERROR: %s: %s\n", file, err)) break end out:write(format("\n====== %s ======\n", file)) local fl = files[file] local n, show = 1, false if ann ~= 0 then for i=1,ann do if fl[i] then show = true; out:write("@@ 1 @@\n"); break end end end for line in fp:lines() do if line:byte() == 27 then out:write("[Cannot annotate bytecode file]\n") break end local v = fl[n] if ann ~= 0 then local v2 = fl[n+ann] if show then if v2 then show = n+ann elseif v then show = n elseif show+ann < n then show = false end elseif v2 then show = n+ann out:write(format("@@ %d @@\n", n)) end if not show then goto next end end if v then out:write(format(fmtv, v, line)) else out:write(format(fmtn, line)) end ::next:: n = n + 1 end fp:close() end end ------------------------------------------------------------------------------ -- Finish profiling and dump result. local function prof_finish() if prof_ud then profile.stop() local samples = prof_samples if samples == 0 then if prof_raw ~= true then out:write("[No samples collected]\n") end return end if prof_ann then prof_annotate(prof_count1, samples) else prof_top(prof_count1, prof_count2, samples, "") end prof_count1 = nil prof_count2 = nil prof_ud = nil end end -- Start profiling. local function prof_start(mode) local interval = "" mode = mode:gsub("i%d*", function(s) interval = s; return "" end) prof_min = 3 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end) prof_depth = 1 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end) local m = {} for c in mode:gmatch(".") do m[c] = c end prof_states = m.z or m.v if prof_states == "z" then zone = require("jit.zone") end local scope = m.l or m.f or m.F or (prof_states and "" or "f") local flags = (m.p or "") prof_raw = m.r if m.s then prof_split = 2 if prof_depth == -1 or m["-"] then prof_depth = -2 elseif prof_depth == 1 then prof_depth = 2 end elseif mode:find("[fF].*l") then scope = "l" prof_split = 3 else prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0 end prof_ann = m.A and 0 or (m.a and 3) if prof_ann then scope = "l" prof_fmt = "pl" prof_split = 0 prof_depth = 1 elseif m.G and scope ~= "" then prof_fmt = flags..scope.."Z;" prof_depth = -100 prof_raw = true prof_min = 0 elseif scope == "" then prof_fmt = false else local sc = prof_split == 3 and m.f or m.F or scope prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ") end prof_count1 = {} prof_count2 = {} prof_samples = 0 profile.start(scope:lower()..interval, prof_cb) prof_ud = newproxy(true) getmetatable(prof_ud).__gc = prof_finish end ------------------------------------------------------------------------------ local function start(mode, outfile) if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end prof_start(mode or "f") end -- Public module functions. return { start = start, -- For -j command line option. stop = prof_finish }
mit
devnexen/h2o
deps/klib/lua/klib.lua
42
20155
--[[ The MIT License Copyright (c) 2011, Attractive Chaos <attractor@live.co.uk> 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. ]]-- --[[ This is a Lua library, more exactly a collection of Lua snippets, covering utilities (e.g. getopt), string operations (e.g. split), statistics (e.g. Fisher's exact test), special functions (e.g. logarithm gamma) and matrix operations (e.g. Gauss-Jordan elimination). The routines are designed to be as independent as possible, such that one can copy-paste relevant pieces of code without worrying about additional library dependencies. If you use routines from this library, please include the licensing information above where appropriate. ]]-- --[[ Library functions and dependencies. "a>b" means "a is required by b"; "b<a" means "b depends on a". os.getopt() string:split() io.xopen() table.ksmall() table.shuffle() math.lgamma() >math.lbinom() >math.igamma() math.igamma() <math.lgamma() >matrix.chi2() math.erfc() math.lbinom() <math.lgamma() >math.fisher_exact() math.bernstein_poly() <math.lbinom() math.fisher_exact() <math.lbinom() math.jackknife() math.pearson() math.spearman() math.fmin() matrix matrix.add() matrix.T() >matrix.mul() matrix.mul() <matrix.T() matrix.tostring() matrix.chi2() <math.igamma() matrix.solve() ]]-- -- Description: getopt() translated from the BSD getopt(); compatible with the default Unix getopt() --[[ Example: for o, a in os.getopt(arg, 'a:b') do print(o, a) end ]]-- function os.getopt(args, ostr) local arg, place = nil, 0; return function () if place == 0 then -- update scanning pointer place = 1 if #args == 0 or args[1]:sub(1, 1) ~= '-' then place = 0; return nil end if #args[1] >= 2 then place = place + 1 if args[1]:sub(2, 2) == '-' then -- found "--" place = 0 table.remove(args, 1); return nil; end end end local optopt = args[1]:sub(place, place); place = place + 1; local oli = ostr:find(optopt); if optopt == ':' or oli == nil then -- unknown option if optopt == '-' then return nil end if place > #args[1] then table.remove(args, 1); place = 0; end return '?'; end oli = oli + 1; if ostr:sub(oli, oli) ~= ':' then -- do not need argument arg = nil; if place > #args[1] then table.remove(args, 1); place = 0; end else -- need an argument if place <= #args[1] then -- no white space arg = args[1]:sub(place); else table.remove(args, 1); if #args == 0 then -- an option requiring argument is the last one place = 0; if ostr:sub(1, 1) == ':' then return ':' end return '?'; else arg = args[1] end end table.remove(args, 1); place = 0; end return optopt, arg; end end -- Description: string split function string:split(sep, n) local a, start = {}, 1; sep = sep or "%s+"; repeat local b, e = self:find(sep, start); if b == nil then table.insert(a, self:sub(start)); break end a[#a+1] = self:sub(start, b - 1); start = e + 1; if n and #a == n then table.insert(a, self:sub(start)); break end until start > #self; return a; end -- Description: smart file open function io.xopen(fn, mode) mode = mode or 'r'; if fn == nil then return io.stdin; elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout; elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w'); elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w'); else return io.open(fn, mode) end end -- Description: find the k-th smallest element in an array (Ref. http://ndevilla.free.fr/median/) function table.ksmall(arr, k) local low, high = 1, #arr; while true do if high <= low then return arr[k] end if high == low + 1 then if arr[high] < arr[low] then arr[high], arr[low] = arr[low], arr[high] end; return arr[k]; end local mid = math.floor((high + low) / 2); if arr[high] < arr[mid] then arr[mid], arr[high] = arr[high], arr[mid] end if arr[high] < arr[low] then arr[low], arr[high] = arr[high], arr[low] end if arr[low] < arr[mid] then arr[low], arr[mid] = arr[mid], arr[low] end arr[mid], arr[low+1] = arr[low+1], arr[mid]; local ll, hh = low + 1, high; while true do repeat ll = ll + 1 until arr[ll] >= arr[low] repeat hh = hh - 1 until arr[low] >= arr[hh] if hh < ll then break end arr[ll], arr[hh] = arr[hh], arr[ll]; end arr[low], arr[hh] = arr[hh], arr[low]; if hh <= k then low = ll end if hh >= k then high = hh - 1 end end end -- Description: shuffle/permutate an array function table.shuffle(a) for i = #a, 1, -1 do local j = math.random(i) a[j], a[i] = a[i], a[j] end end -- -- Mathematics -- -- Description: log gamma function -- Required by: math.lbinom() -- Reference: AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245 function math.lgamma(z) local x; x = 0.1659470187408462e-06 / (z+7); x = x + 0.9934937113930748e-05 / (z+6); x = x - 0.1385710331296526 / (z+5); x = x + 12.50734324009056 / (z+4); x = x - 176.6150291498386 / (z+3); x = x + 771.3234287757674 / (z+2); x = x - 1259.139216722289 / (z+1); x = x + 676.5203681218835 / z; x = x + 0.9999999999995183; return math.log(x) - 5.58106146679532777 - z + (z-0.5) * math.log(z+6.5); end -- Description: regularized incomplete gamma function -- Dependent on: math.lgamma() --[[ Formulas are taken from Wiki, with additional input from Numerical Recipes in C (for modified Lentz's algorithm) and AS245 (http://lib.stat.cmu.edu/apstat/245). A good online calculator is available at: http://www.danielsoper.com/statcalc/calc23.aspx It calculates upper incomplete gamma function, which equals math.igamma(s,z,true)*math.exp(math.lgamma(s)) ]]-- function math.igamma(s, z, complement) local function _kf_gammap(s, z) local sum, x = 1, 1; for k = 1, 100 do x = x * z / (s + k); sum = sum + x; if x / sum < 1e-14 then break end end return math.exp(s * math.log(z) - z - math.lgamma(s + 1.) + math.log(sum)); end local function _kf_gammaq(s, z) local C, D, f, TINY; f = 1. + z - s; C = f; D = 0.; TINY = 1e-290; -- Modified Lentz's algorithm for computing continued fraction. See Numerical Recipes in C, 2nd edition, section 5.2 for j = 1, 100 do local d; local a, b = j * (s - j), j*2 + 1 + z - s; D = b + a * D; if D < TINY then D = TINY end C = b + a / C; if C < TINY then C = TINY end D = 1. / D; d = C * D; f = f * d; if math.abs(d - 1) < 1e-14 then break end end return math.exp(s * math.log(z) - z - math.lgamma(s) - math.log(f)); end if complement then return ((z <= 1 or z < s) and 1 - _kf_gammap(s, z)) or _kf_gammaq(s, z); else return ((z <= 1 or z < s) and _kf_gammap(s, z)) or (1 - _kf_gammaq(s, z)); end end math.M_SQRT2 = 1.41421356237309504880 -- sqrt(2) math.M_SQRT1_2 = 0.70710678118654752440 -- 1/sqrt(2) -- Description: complement error function erfc(x): \Phi(x) = 0.5 * erfc(-x/M_SQRT2) function math.erfc(x) local z = math.abs(x) * math.M_SQRT2 if z > 37 then return (x > 0 and 0) or 2 end local expntl = math.exp(-0.5 * z * z) local p if z < 10. / math.M_SQRT2 then -- for small z p = expntl * ((((((.03526249659989109 * z + .7003830644436881) * z + 6.37396220353165) * z + 33.912866078383) * z + 112.0792914978709) * z + 221.2135961699311) * z + 220.2068679123761) / (((((((.08838834764831844 * z + 1.755667163182642) * z + 16.06417757920695) * z + 86.78073220294608) * z + 296.5642487796737) * z + 637.3336333788311) * z + 793.8265125199484) * z + 440.4137358247522); else p = expntl / 2.506628274631001 / (z + 1. / (z + 2. / (z + 3. / (z + 4. / (z + .65))))) end return (x > 0 and 2 * p) or 2 * (1 - p) end -- Description: log binomial coefficient -- Dependent on: math.lgamma() -- Required by: math.fisher_exact() function math.lbinom(n, m) if m == nil then local a = {}; a[0], a[n] = 0, 0; local t = math.lgamma(n+1); for m = 1, n-1 do a[m] = t - math.lgamma(m+1) - math.lgamma(n-m+1) end return a; else return math.lgamma(n+1) - math.lgamma(m+1) - math.lgamma(n-m+1) end end -- Description: Berstein polynomials (mainly for Bezier curves) -- Dependent on: math.lbinom() -- Note: to compute derivative: let beta_new[i]=beta[i+1]-beta[i] function math.bernstein_poly(beta) local n = #beta - 1; local lbc = math.lbinom(n); -- log binomial coefficients return function (t) assert(t >= 0 and t <= 1); if t == 0 then return beta[1] end if t == 1 then return beta[n+1] end local sum, logt, logt1 = 0, math.log(t), math.log(1-t); for i = 0, n do sum = sum + beta[i+1] * math.exp(lbc[i] + i * logt + (n-i) * logt1) end return sum; end end -- Description: Fisher's exact test -- Dependent on: math.lbinom() -- Return: left-, right- and two-tail P-values --[[ Fisher's exact test for 2x2 congintency tables: n11 n12 | n1_ n21 n22 | n2_ -----------+---- n_1 n_2 | n Reference: http://www.langsrud.com/fisher.htm ]]-- function math.fisher_exact(n11, n12, n21, n22) local aux; -- keep the states of n* for acceleration -- Description: hypergeometric function local function hypergeo(n11, n1_, n_1, n) return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1)); end -- Description: incremental hypergeometric function -- Note: aux = {n11, n1_, n_1, n, p} local function hypergeo_inc(n11, n1_, n_1, n) if n1_ ~= 0 or n_1 ~= 0 or n ~= 0 then aux = {n11, n1_, n_1, n, 1}; else -- then only n11 is changed local mod; _, mod = math.modf(n11 / 11); if mod ~= 0 and n11 + aux[4] - aux[2] - aux[3] ~= 0 then if n11 == aux[1] + 1 then -- increase by 1 aux[5] = aux[5] * (aux[2] - aux[1]) / n11 * (aux[3] - aux[1]) / (n11 + aux[4] - aux[2] - aux[3]); aux[1] = n11; return aux[5]; end if n11 == aux[1] - 1 then -- descrease by 1 aux[5] = aux[5] * aux[1] / (aux[2] - n11) * (aux[1] + aux[4] - aux[2] - aux[3]) / (aux[3] - n11); aux[1] = n11; return aux[5]; end end aux[1] = n11; end aux[5] = hypergeo(aux[1], aux[2], aux[3], aux[4]); return aux[5]; end -- Description: computing the P-value by Fisher's exact test local max, min, left, right, n1_, n_1, n, two, p, q, i, j; n1_, n_1, n = n11 + n12, n11 + n21, n11 + n12 + n21 + n22; max = (n_1 < n1_ and n_1) or n1_; -- max n11, for the right tail min = n1_ + n_1 - n; if min < 0 then min = 0 end -- min n11, for the left tail two, left, right = 1, 1, 1; if min == max then return 1 end -- no need to do test q = hypergeo_inc(n11, n1_, n_1, n); -- the probability of the current table -- left tail i, left, p = min + 1, 0, hypergeo_inc(min, 0, 0, 0); while p < 0.99999999 * q do left, p, i = left + p, hypergeo_inc(i, 0, 0, 0), i + 1; end i = i - 1; if p < 1.00000001 * q then left = left + p; else i = i - 1 end -- right tail j, right, p = max - 1, 0, hypergeo_inc(max, 0, 0, 0); while p < 0.99999999 * q do right, p, j = right + p, hypergeo_inc(j, 0, 0, 0), j - 1; end j = j + 1; if p < 1.00000001 * q then right = right + p; else j = j + 1 end -- two-tail two = left + right; if two > 1 then two = 1 end -- adjust left and right if math.abs(i - n11) < math.abs(j - n11) then right = 1 - left + q; else left = 1 - right + q end return left, right, two; end -- Description: Delete-m Jackknife --[[ Given g groups of values with a statistics estimated from m[i] samples in i-th group being t[i], compute the mean and the variance. t0 below is the estimate from all samples. Reference: Busing et al. (1999) Delete-m Jackknife for unequal m. Statistics and Computing, 9:3-8. ]]-- function math.jackknife(g, m, t, t0) local h, n, sum = {}, 0, 0; for j = 1, g do n = n + m[j] end if t0 == nil then -- When t0 is absent, estimate it in a naive way t0 = 0; for j = 1, g do t0 = t0 + m[j] * t[j] end t0 = t0 / n; end local mean, var = 0, 0; for j = 1, g do h[j] = n / m[j]; mean = mean + (1 - m[j] / n) * t[j]; end mean = g * t0 - mean; -- Eq. (8) for j = 1, g do local x = h[j] * t0 - (h[j] - 1) * t[j] - mean; var = var + 1 / (h[j] - 1) * x * x; end var = var / g; return mean, var; end -- Description: Pearson correlation coefficient -- Input: a is an n*2 table function math.pearson(a) -- compute the mean local x1, y1 = 0, 0 for _, v in pairs(a) do x1, y1 = x1 + v[1], y1 + v[2] end -- compute the coefficient x1, y1 = x1 / #a, y1 / #a local x2, y2, xy = 0, 0, 0 for _, v in pairs(a) do local tx, ty = v[1] - x1, v[2] - y1 xy, x2, y2 = xy + tx * ty, x2 + tx * tx, y2 + ty * ty end return xy / math.sqrt(x2) / math.sqrt(y2) end -- Description: Spearman correlation coefficient function math.spearman(a) local function aux_func(t) -- auxiliary function return (t == 1 and 0) or (t*t - 1) * t / 12 end for _, v in pairs(a) do v.r = {} end local T, S = {}, {} -- compute the rank for k = 1, 2 do table.sort(a, function(u,v) return u[k]<v[k] end) local same = 1 T[k] = 0 for i = 2, #a + 1 do if i <= #a and a[i-1][k] == a[i][k] then same = same + 1 else local rank = (i-1) * 2 - same + 1 for j = i - same, i - 1 do a[j].r[k] = rank end if same > 1 then T[k], same = T[k] + aux_func(same), 1 end end end S[k] = aux_func(#a) - T[k] end -- compute the coefficient local sum = 0 for _, v in pairs(a) do -- TODO: use nested loops to reduce loss of precision local t = (v.r[1] - v.r[2]) / 2 sum = sum + t * t end return (S[1] + S[2] - sum) / 2 / math.sqrt(S[1] * S[2]) end -- Description: Hooke-Jeeves derivative-free optimization function math.fmin(func, x, data, r, eps, max_calls) local n, n_calls = #x, 0; r = r or 0.5; eps = eps or 1e-7; max_calls = max_calls or 50000 function fmin_aux(x1, data, fx1, dx) -- auxiliary function local ftmp; for k = 1, n do x1[k] = x1[k] + dx[k]; local ftmp = func(x1, data); n_calls = n_calls + 1; if ftmp < fx1 then fx1 = ftmp; else -- search the opposite direction dx[k] = -dx[k]; x1[k] = x1[k] + dx[k] + dx[k]; ftmp = func(x1, data); n_calls = n_calls + 1; if ftmp < fx1 then fx1 = ftmp else x1[k] = x1[k] - dx[k] end -- back to the original x[k] end end return fx1; -- here: fx1=f(n,x1) end local dx, x1 = {}, {}; for k = 1, n do -- initial directions, based on MGJ dx[k] = math.abs(x[k]) * r; if dx[k] == 0 then dx[k] = r end; end local radius = r; local fx1, fx; fx = func(x, data); fx1 = fx; n_calls = n_calls + 1; while true do for i = 1, n do x1[i] = x[i] end; -- x1 = x fx1 = fmin_aux(x1, data, fx, dx); while fx1 < fx do for k = 1, n do local t = x[k]; dx[k] = (x1[k] > x[k] and math.abs(dx[k])) or -math.abs(dx[k]); x[k] = x1[k]; x1[k] = x1[k] + x1[k] - t; end fx = fx1; if n_calls >= max_calls then break end fx1 = func(x1, data); n_calls = n_calls + 1; fx1 = fmin_aux(x1, data, fx1, dx); if fx1 >= fx then break end local kk = n; for k = 1, n do if math.abs(x1[k] - x[k]) > .5 * math.abs(dx[k]) then kk = k; break; end end if kk == n then break end end if radius >= eps then if n_calls >= max_calls then break end radius = radius * r; for k = 1, n do dx[k] = dx[k] * r end else break end end return fx1, n_calls; end -- -- Matrix -- matrix = {} -- Description: matrix transpose -- Required by: matrix.mul() function matrix.T(a) local m, n, x = #a, #a[1], {}; for i = 1, n do x[i] = {}; for j = 1, m do x[i][j] = a[j][i] end end return x; end -- Description: matrix add function matrix.add(a, b) assert(#a == #b and #a[1] == #b[1]); local m, n, x = #a, #a[1], {}; for i = 1, m do x[i] = {}; local ai, bi, xi = a[i], b[i], x[i]; for j = 1, n do xi[j] = ai[j] + bi[j] end end return x; end -- Description: matrix mul -- Dependent on: matrix.T() -- Note: much slower without transpose function matrix.mul(a, b) assert(#a[1] == #b); local m, n, p, x = #a, #a[1], #b[1], {}; local c = matrix.T(b); -- transpose for efficiency for i = 1, m do x[i] = {} local xi = x[i]; for j = 1, p do local sum, ai, cj = 0, a[i], c[j]; for k = 1, n do sum = sum + ai[k] * cj[k] end xi[j] = sum; end end return x; end -- Description: matrix print function matrix.tostring(a) local z = {}; for i = 1, #a do z[i] = table.concat(a[i], "\t"); end return table.concat(z, "\n"); end -- Description: chi^2 test for contingency tables -- Dependent on: math.igamma() function matrix.chi2(a) if #a == 2 and #a[1] == 2 then -- 2x2 table local x, z x = (a[1][1] + a[1][2]) * (a[2][1] + a[2][2]) * (a[1][1] + a[2][1]) * (a[1][2] + a[2][2]) if x == 0 then return 0, 1, false end z = a[1][1] * a[2][2] - a[1][2] * a[2][1] z = (a[1][1] + a[1][2] + a[2][1] + a[2][2]) * z * z / x return z, math.igamma(.5, .5 * z, true), true else -- generic table local rs, cs, n, m, N, z = {}, {}, #a, #a[1], 0, 0 for i = 1, n do rs[i] = 0 end for j = 1, m do cs[j] = 0 end for i = 1, n do -- compute column sum and row sum for j = 1, m do cs[j], rs[i] = cs[j] + a[i][j], rs[i] + a[i][j] end end for i = 1, n do N = N + rs[i] end for i = 1, n do -- compute the chi^2 statistics for j = 1, m do local E = rs[i] * cs[j] / N; z = z + (a[i][j] - E) * (a[i][j] - E) / E end end return z, math.igamma(.5 * (n-1) * (m-1), .5 * z, true), true; end end -- Description: Gauss-Jordan elimination (solving equations; computing inverse) -- Note: on return, a[n][n] is the inverse; b[n][m] is the solution -- Reference: Section 2.1, Numerical Recipes in C, 2nd edition function matrix.solve(a, b) assert(#a == #a[1]); local n, m = #a, (b and #b[1]) or 0; local xc, xr, ipiv = {}, {}, {}; local ic, ir; for j = 1, n do ipiv[j] = 0 end for i = 1, n do local big = 0; for j = 1, n do local aj = a[j]; if ipiv[j] ~= 1 then for k = 1, n do if ipiv[k] == 0 then if math.abs(aj[k]) >= big then big = math.abs(aj[k]); ir, ic = j, k; end elseif ipiv[k] > 1 then return -2 end -- singular matrix end end end ipiv[ic] = ipiv[ic] + 1; if ir ~= ic then for l = 1, n do a[ir][l], a[ic][l] = a[ic][l], a[ir][l] end if b then for l = 1, m do b[ir][l], b[ic][l] = b[ic][l], b[ir][l] end end end xr[i], xc[i] = ir, ic; if a[ic][ic] == 0 then return -3 end -- singular matrix local pivinv = 1 / a[ic][ic]; a[ic][ic] = 1; for l = 1, n do a[ic][l] = a[ic][l] * pivinv end if b then for l = 1, n do b[ic][l] = b[ic][l] * pivinv end end for ll = 1, n do if ll ~= ic then local tmp = a[ll][ic]; a[ll][ic] = 0; local all, aic = a[ll], a[ic]; for l = 1, n do all[l] = all[l] - aic[l] * tmp end if b then local bll, bic = b[ll], b[ic]; for l = 1, m do bll[l] = bll[l] - bic[l] * tmp end end end end end for l = n, 1, -1 do if xr[l] ~= xc[l] then for k = 1, n do a[k][xr[l]], a[k][xc[l]] = a[k][xc[l]], a[k][xr[l]] end end end return 0; end
mit
gedads/Neodynamis
scripts/zones/Southern_San_dOria/npcs/Lanqueron.lua
3
1608
----------------------------------- -- Area: Southern San dOria -- NPC: Lanqueron -- Type: Item Deliverer NPC -- Involved in Quest: Lost Chick -- @zone 230 -- !pos 0.335 1.199 -28.404 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); 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
starlightknight/darkstar
scripts/globals/items/blackened_toad.lua
11
1052
----------------------------------------- -- ID: 4599 -- Item: Blackened Toad -- Food Effect: 180Min, All Races ----------------------------------------- -- Dexterity 2 -- Agility 2 -- Mind -1 -- Poison Resist 4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4599) end function onEffectGain(target,effect) target:addMod(dsp.mod.DEX, 2) target:addMod(dsp.mod.AGI, 2) target:addMod(dsp.mod.MND, -1) target:addMod(dsp.mod.POISONRES, 4) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 2) target:delMod(dsp.mod.AGI, 2) target:delMod(dsp.mod.MND, -1) target:delMod(dsp.mod.POISONRES, 4) end
gpl-3.0
gedads/Neodynamis
scripts/zones/Windurst_Waters/npcs/Aramu-Paramu.lua
3
1659
----------------------------------- -- Area: Windurst Waters -- NPC: Aramu-Paramu -- Involved In Quest: Wondering Minstrel -- !pos -63 -4 27 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL); if (wonderingstatus == QUEST_ACCEPTED) then player:startEvent(0x027e); -- WONDERING_MINSTREL: Quest Available / Quest Accepted elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x0281); -- WONDERING_MINSTREL: Quest After else player:startEvent(0x261); -- Standard Conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Abyssea-Uleguerand/npcs/qm2.lua
3
1423
----------------------------------- -- Zone: Abyssea-Uleguerand -- NPC: qm2 (???) -- Spawns Dhorme Khimaira -- !pos ? ? ? 253 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3253,1) and trade:hasItemQty(3247,1) and trade:hasItemQty(3246,1) and trade:getItemCount() == 3) then -- Player has all the required items. if (GetMobAction(17813927) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17813927):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3253 ,3247 ,3246); -- Inform player what items they need. 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
starlightknight/darkstar
scripts/zones/Upper_Jeuno/npcs/Rouliette.lua
11
1737
----------------------------------- -- Area: Upper Jeuno -- NPC: Rouliette -- Starts and Finishes Quest: Candle-making -- !pos -24 -2 11 244 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Upper_Jeuno/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.CANDLE_MAKING) == QUEST_ACCEPTED and trade:hasItemQty(531,1) == true and trade:getItemCount() == 1) then player:startEvent(37); end end; function onTrigger(player,npc) --Prerequisites for this quest : A_CANDLELIGHT_VIGIL ACCEPTED if (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.CANDLE_MAKING) ~= QUEST_COMPLETED and player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.A_CANDLELIGHT_VIGIL) == QUEST_ACCEPTED) then player:startEvent(36); -- Start Quest Candle-making else player:startEvent(30); --Standard dialog end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 36 and player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.CANDLE_MAKING) == QUEST_AVAILABLE) then player:addQuest(JEUNO,dsp.quest.id.jeuno.CANDLE_MAKING); elseif (csid == 37) then player:addTitle(dsp.title.BELIEVER_OF_ALTANA); player:addKeyItem(dsp.ki.HOLY_CANDLE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.HOLY_CANDLE); player:addFame(JEUNO,30); player:tradeComplete(trade); player:completeQuest(JEUNO,dsp.quest.id.jeuno.CANDLE_MAKING); end end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Metalworks/npcs/Grohm.lua
9
2582
----------------------------------- -- Area: Metalworks -- NPC: Grohm -- Involved In Mission: Journey Abroad -- !pos -18 -11 -27 237 ----------------------------------- require("scripts/globals/missions"); local ID = require("scripts/zones/Metalworks/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK) then if (player:getCharVar("notReceivePickaxe") == 1) then player:startEvent(425); elseif (player:getCharVar("MissionStatus") == 4) then player:startEvent(423); elseif (player:getCharVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(424); else player:startEvent(422); end elseif (player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK2) then if (player:getCharVar("MissionStatus") == 9) then player:startEvent(426); else player:startEvent(427); end elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_THREE_KINGDOMS_BASTOK) then if (player:getCharVar("notReceivePickaxe") == 1) then player:startEvent(425,1); elseif (player:getCharVar("MissionStatus") == 4) then player:startEvent(423,1); elseif (player:getCharVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(424,1); else player:startEvent(422); end elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_THREE_KINGDOMS_BASTOK2) then if (player:getCharVar("MissionStatus") == 9) then player:startEvent(426,1); else player:startEvent(427,1); end else player:startEvent(427);--422 end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 423 or csid == 425) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,605); -- Pickaxes player:setCharVar("notReceivePickaxe",1); else player:addItem(605,5); player:messageSpecial(ID.text.ITEM_OBTAINED,605); -- Pickaxes player:setCharVar("MissionStatus",5); player:setCharVar("notReceivePickaxe",0); end elseif (csid == 426) then player:setCharVar("MissionStatus",10); end end;
gpl-3.0
starlightknight/darkstar
scripts/globals/spells/bluemagic/venom_shell.lua
12
1482
----------------------------------------- -- Spell: Venom Shell -- Poisons enemies within range and gradually reduces their HP -- Spell cost: 86 MP -- Monster Type: Aquans -- Spell Type: Magical (Water) -- Blue Magic Points: 3 -- Stat Bonus: MND+2 -- Level: 42 -- Casting Time: 3 seconds -- Recast Time: 45 seconds -- Magic Bursts on: Reverberation, Distortion, and Darkness -- Combos: Clear Mind ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local typeEffect = dsp.effect.POISON local dINT = caster:getStat(dsp.mod.MND) - target:getStat(dsp.mod.MND) local params = {} params.diff = nil params.attribute = dsp.mod.INT params.skillType = dsp.skill.BLUE_MAGIC params.bonus = 0 params.effect = typeEffect local resist = applyResistanceEffect(caster, target, spell, params) local duration = 180 * resist local power = 6 if (resist > 0.5) then -- Do it! if (target:addStatusEffect(typeEffect,power,0,duration)) then spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end else spell:setMsg(dsp.msg.basic.MAGIC_RESIST) end return typeEffect end
gpl-3.0
laino/luakit
lib/lousy/signal.lua
7
3274
-------------------------------------------------------------- -- Mimic the luakit signal api functions for tables -- -- @author Fabian Streitel &lt;karottenreibe@gmail.com&gt; -- -- @author Mason Larobina &lt;mason.larobina@gmail.com&gt; -- -- @copyright 2010 Fabian Streitel, Mason Larobina -- -------------------------------------------------------------- -- Grab environment we need local assert = assert local io = io local ipairs = ipairs local setmetatable = setmetatable local string = string local table = table local tostring = tostring local type = type local unpack = unpack local verbose = luakit.verbose --- Provides a signal API similar to GTK's signals. module("lousy.signal") -- Private signal data for objects local data = setmetatable({}, { __mode = "k" }) local methods = { "add_signal", "emit_signal", "remove_signal", "remove_signals", } local function get_data(object) local d = data[object] assert(d, "object isn't setup for signals") return d end function add_signal(object, signame, func) local signals = get_data(object).signals -- Check signal name assert(type(signame) == "string", "invalid signame type: " .. type(signame)) assert(string.match(signame, "^[%w_%-:]+$"), "invalid chars in signame: " .. signame) -- Check handler function assert(type(func) == "function", "invalid handler function") -- Add to signals table if not signals[signame] then signals[signame] = { func, } else table.insert(signals[signame], func) end end function emit_signal(object, signame, ...) local d = get_data(object) local sigfuncs = d.signals[signame] or {} if verbose then io.stderr:write(string.format("D: lousy.signal: emit_signal: " .. "%q on %s\n", signame, tostring(object))) end for _, sigfunc in ipairs(sigfuncs) do local ret if d.module then ret = { sigfunc(...) } else ret = { sigfunc(object, ...) } end if ret[1] ~= nil then return unpack(ret) end end end -- Remove a signame & function pair. function remove_signal(object, signame, func) local signals = get_data(object).signals local sigfuncs = signals[signame] or {} for i, sigfunc in ipairs(sigfuncs) do if sigfunc == func then table.remove(sigfuncs, i) -- Remove empty sigfuncs table if #sigfuncs == 0 then signals[signame] = nil end return func end end end -- Remove all signal handlers with the given signame. function remove_signals(object, signame) local signals = get_data(object).signals signals[signame] = nil end function setup(object, module) assert(not data[object], "given object already setup for signals") data[object] = { signals = {}, module = module } for _, fn in ipairs(methods) do assert(not object[fn], "signal object method conflict: " .. fn) if module then local func = _M[fn] object[fn] = function (...) return func(object, ...) end else object[fn] = _M[fn] end end return object end -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
bigrpg/skynet
lualib/skynet/datasheet/dump.lua
20
6547
--[[ file format document : int32 strtbloffset int32 n int32*n index table table*n strings table: int32 array int32 dict int8*(array+dict) type (align 4) value*array kvpair*dict kvpair: string k value v value: (union) int32 integer float real int32 boolean int32 table index int32 string offset type: (enum) 0 nil 1 integer 2 real 3 boolean 4 table 5 string ]] local ctd = {} local math = math local table = table local string = string function ctd.dump(root) local doc = { table_n = 0, table = {}, strings = {}, offset = 0, } local function dump_table(t) local index = doc.table_n + 1 doc.table_n = index doc.table[index] = false -- place holder local array_n = 0 local array = {} local kvs = {} local types = {} local function encode(v) local t = type(v) if t == "table" then local index = dump_table(v) return '\4', string.pack("<i4", index-1) elseif t == "number" then if math.tointeger(v) and v <= 0x7FFFFFFF and v >= -(0x7FFFFFFF+1) then return '\1', string.pack("<i4", v) else return '\2', string.pack("<f",v) end elseif t == "boolean" then if v then return '\3', "\0\0\0\1" else return '\3', "\0\0\0\0" end elseif t == "string" then local offset = doc.strings[v] if not offset then offset = doc.offset doc.offset = offset + #v + 1 doc.strings[v] = offset table.insert(doc.strings, v) end return '\5', string.pack("<I4", offset) else error ("Unsupport value " .. tostring(v)) end end for i,v in ipairs(t) do types[i], array[i] = encode(v) array_n = i end for k,v in pairs(t) do if type(k) == "string" then local _, kv = encode(k) local tv, ev = encode(v) table.insert(types, tv) table.insert(kvs, kv .. ev) else local ik = math.tointeger(k) assert(ik and ik > 0 and ik <= array_n) end end -- encode table local typeset = table.concat(types) local align = string.rep("\0", (4 - #typeset & 3) & 3) local tmp = { string.pack("<i4i4", array_n, #kvs), typeset, align, table.concat(array), table.concat(kvs), } doc.table[index] = table.concat(tmp) return index end dump_table(root) -- encode document local index = {} local offset = 0 for i, v in ipairs(doc.table) do index[i] = string.pack("<I4", offset) offset = offset + #v end local tmp = { string.pack("<I4", 4 + 4 + 4 * doc.table_n + offset), string.pack("<I4", doc.table_n), table.concat(index), table.concat(doc.table), table.concat(doc.strings, "\0"), "\0", } return table.concat(tmp) end function ctd.undump(v) local stringtbl, n = string.unpack("<I4I4",v) local index = { string.unpack("<" .. string.rep("I4", n), v, 9) } local header = 4 + 4 + 4 * n + 1 stringtbl = stringtbl + 1 local tblidx = {} local function decode(n) local toffset = index[n+1] + header local array, dict = string.unpack("<I4I4", v, toffset) local types = { string.unpack(string.rep("B", (array+dict)), v, toffset + 8) } local offset = ((array + dict + 8 + 3) & ~3) + toffset local result = {} local function value(t) local off = offset offset = offset + 4 if t == 1 then -- integer return (string.unpack("<i4", v, off)) elseif t == 2 then -- float return (string.unpack("<f", v, off)) elseif t == 3 then -- boolean return string.unpack("<i4", v, off) ~= 0 elseif t == 4 then -- table local tindex = (string.unpack("<I4", v, off)) return decode(tindex) elseif t == 5 then -- string local sindex = string.unpack("<I4", v, off) return (string.unpack("z", v, stringtbl + sindex)) else error (string.format("Invalid data at %d (%d)", off, t)) end end for i=1,array do table.insert(result, value(types[i])) end for i=1,dict do local sindex = string.unpack("<I4", v, offset) offset = offset + 4 local key = string.unpack("z", v, stringtbl + sindex) result[key] = value(types[array + i]) end tblidx[result] = n return result end return decode(0), tblidx end local function diffmap(last, current) local lastv, lasti = ctd.undump(last) local curv, curi = ctd.undump(current) local map = {} -- new(current index):old(last index) local function comp(lastr, curr) local old = lasti[lastr] local new = curi[curr] map[new] = old for k,v in pairs(lastr) do if type(v) == "table" then local newv = curr[k] if type(newv) == "table" then comp(v, newv) end end end end comp(lastv, curv) return map end function ctd.diff(last, current) local map = diffmap(last, current) local stringtbl, n = string.unpack("<I4I4",current) local _, lastn = string.unpack("<I4I4",last) local existn = 0 for k,v in pairs(map) do existn = existn + 1 end local newn = lastn for i = 0, n-1 do if not map[i] then map[i] = newn newn = newn + 1 end end -- remap current local index = { string.unpack("<" .. string.rep("I4", n), current, 9) } local header = 4 + 4 + 4 * n + 1 local function remap(n) local toffset = index[n+1] + header local array, dict = string.unpack("<I4I4", current, toffset) local types = { string.unpack(string.rep("B", (array+dict)), current, toffset + 8) } local hlen = (array + dict + 8 + 3) & ~3 local hastable = false for _, v in ipairs(types) do if v == 4 then -- table hastable = true break end end if not hastable then return string.sub(current, toffset, toffset + hlen + (array + dict * 2) * 4 - 1) end local offset = hlen + toffset local pat = "<" .. string.rep("I4", array + dict * 2) local values = { string.unpack(pat, current, offset) } for i = 1, array do if types[i] == 4 then -- table values[i] = map[values[i]] end end for i = 1, dict do if types[i + array] == 4 then -- table values[array + i * 2] = map[values[array + i * 2]] end end return string.sub(current, toffset, toffset + hlen - 1) .. string.pack(pat, table.unpack(values)) end -- rebuild local oldindex = { string.unpack("<" .. string.rep("I4", n), current, 9) } local index = {} for i = 1, newn do index[i] = 0xffffffff end for i = 0, #map do index[map[i]+1] = oldindex[i+1] end local tmp = { string.pack("<I4I4", stringtbl + (newn - n) * 4, newn), -- expand index table string.pack("<" .. string.rep("I4", newn), table.unpack(index)), } for i = 0, n - 1 do table.insert(tmp, remap(i)) end table.insert(tmp, string.sub(current, stringtbl+1)) return table.concat(tmp) end return ctd
mit
jarzofjam/tenshi
vm/lua/tenshi-runtime/src/lua/units.lua
11
1128
-- Licensed to Pioneers in Engineering under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. Pioneers in Engineering licenses -- this file to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License local units = {} -- SI prefixes units.mega = 1e6 units.kilo = 1e3 units.mili = 1e-3 units.micro = 1e-6 units.nano = 1e-9 -- Conversion factors into standard units used in the API units.inch = 2.54 -- to cm units.pound = 453.592 -- to g units.deg = math.pi / 180.0 -- to radians return units
apache-2.0
gedads/Neodynamis
scripts/zones/Port_Bastok/Zone.lua
26
3589
----------------------------------- -- -- Zone: Port_Bastok (236) -- ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/zone"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1,-112,-3,-17,-96,3,-3);--event COP end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 0x0001; end player:setPos(132,-8.5,-13,179); player:setHomePoint(); end if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then if (prevZone == 224) then cs = 0x0049; player:setPos(-36.000, 7.000, -58.000, 194); else position = math.random(1,5) + 57; player:setPos(position,8.5,-239,192); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); end end if (player:getCurrentMission(COP) == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus") == 0) then cs = 0x0132; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local regionID =region:GetRegionID(); -- printf("regionID: %u",regionID); if (regionID == 1 and player:getCurrentMission(COP) == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0131); end end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0047); 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 == 0x0001) then player:messageSpecial(ITEM_OBTAINED,536); elseif (csid == 0x0047) then player:setPos(0,0,0,0,224); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 0x0131) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0132) then player:setVar("COP_optional_CS_chasalvigne",0); player:setVar("COP_optional_CS_Anoki",0); player:setVar("COP_optional_CS_Despachaire",0); player:setVar("PromathiaStatus",1); end end;
gpl-3.0
telergybot/zspam
plugins/media.lua
376
1679
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
Amorph/premake-stable
tests/actions/vstudio/vc2010/test_files.lua
31
1551
-- -- tests/actions/vstudio/vc2010/test_files.lua -- Validate generation of files block in Visual Studio 2010 C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.vstudio_vs2010_files = { } local suite = T.vstudio_vs2010_files local vc2010 = premake.vstudio.vc2010 -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) sln.vstudio_configs = premake.vstudio.buildconfigs(sln) vc2010.files(prj) end -- -- Test file groups -- function suite.SimpleHeaderFile() files { "include/hello.h" } prepare() test.capture [[ <ItemGroup> <ClInclude Include="include\hello.h" /> </ItemGroup> ]] end function suite.SimpleSourceFile() files { "hello.c" } prepare() test.capture [[ <ItemGroup> <ClCompile Include="hello.c"> </ClCompile> </ItemGroup> ]] end function suite.SimpleNoneFile() files { "docs/hello.txt" } prepare() test.capture [[ <ItemGroup> <None Include="docs\hello.txt" /> </ItemGroup> ]] end function suite.SimpleResourceFile() files { "resources/hello.rc" } prepare() test.capture [[ <ItemGroup> <ResourceCompile Include="resources\hello.rc" /> </ItemGroup> ]] end -- -- Test path handling -- function suite.MultipleFolderLevels() files { "src/greetings/hello.c" } prepare() test.capture [[ <ItemGroup> <ClCompile Include="src\greetings\hello.c"> </ClCompile> </ItemGroup> ]] end
bsd-3-clause
telergybot/zspam
plugins/stats.lua
33
3680
do local NUM_MSG_MAX = 6 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood local kick = chat_del_user(chat_id , user_id, ok_cb, true) vardump(kick) if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
pedro-andrade-inpe/terrame
packages/luadoc/lua/main/config.lua
3
1480
------------------------------------------------------------------------------- -- LuaDoc configuration file. This file contains the default options for -- luadoc operation. These options can be overriden by the command line tool -- @see luadoc.print_help -- @release $Id: config.lua,v 1.6 2007/04/18 14:28:39 tomas Exp $ ------------------------------------------------------------------------------- -- module "luadoc.config" ------------------------------------------------------------------------------- -- Default options -- @class table -- @name default_options -- @field output_dir default output directory for generated documentation, used -- by several doclets -- @field taglet parser used to analyze source code input -- @field doclet documentation generator -- @field template_dir directory with documentation templates, used by the html -- doclet -- @field verbose command line tool configuration to output processing -- information local s = sessionInfo().separator local luadoc_dirLocal = sessionInfo().path..s.."packages"..s.."luadoc" --[[local]] default_options = { output_dir = "", luadoc_dir = luadoc_dirLocal, taglet = luadoc_dirLocal..s.."lua"..s.."taglet"..s.."standard.lua", doclet = luadoc_dirLocal..s.."lua"..s.."doclet"..s.."html.lua", -- TODO: find a way to define doclet specific options template_dir = luadoc_dirLocal..s.."lua"..s.."doclet"..s.."html"..s, nomodules = false, nofiles = false, verbose = true, } -- return default_options
lgpl-3.0
starlightknight/darkstar
scripts/globals/items/nebimonite.lua
11
1246
----------------------------------------- -- ID: 4361 -- Item: nebimonite -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -3 -- Vitality 2 -- Defense % 13 (cap 50) ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4361) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, -3) target:addMod(dsp.mod.VIT, 2) target:addMod(dsp.mod.FOOD_DEFP, 13) target:addMod(dsp.mod.FOOD_DEF_CAP,50) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, -3) target:delMod(dsp.mod.VIT, 2) target:delMod(dsp.mod.FOOD_DEFP, 13) target:delMod(dsp.mod.FOOD_DEF_CAP,50) end
gpl-3.0
starlightknight/darkstar
scripts/zones/Beaucedine_Glacier_[S]/IDs.lua
9
1071
----------------------------------- -- Area: Beaucedine_Glacier_[S] ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.BEAUCEDINE_GLACIER_S] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. COMMON_SENSE_SURVIVAL = 8687, -- It appears that you have arrived at a new survival guide provided by the Servicemen's Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { GRANDGOULE_PH = { [17334475] = 17334482, [17334476] = 17334482, [17334477] = 17334482, }, }, npc = { }, } return zones[dsp.zone.BEAUCEDINE_GLACIER_S]
gpl-3.0
gedads/Neodynamis
scripts/globals/weaponskills/knights_of_round.lua
19
1904
----------------------------------- -- Knights Of Round -- Sword Weapon Skill -- Skill Level: N/A -- Caliburn/Excalibur: Additional Effect: Regen. -- Regen 10HP/Tick, duration varies with TP. -- Available only when equipped with the Relic Weapons Caliburn (Dynamis use only) or Excalibur. -- Also available without aftermath as a latent effect on Corbenic Sword. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:40% ; MND:40% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.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 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; 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.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5; 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, 10, 0, amDuration, 0, 3); end return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0
gedads/Neodynamis
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
hwhw/kindlevncviewer
ffi/linux_fb_h.lua
1
1493
local ffi = require("ffi") ffi.cdef[[ static const int FBIOGET_FSCREENINFO = 17922; static const int FBIOGET_VSCREENINFO = 17920; static const int FB_TYPE_PACKED_PIXELS = 0; struct fb_bitfield { unsigned int offset; unsigned int length; unsigned int msb_right; }; struct fb_fix_screeninfo { char id[16]; long unsigned int smem_start; unsigned int smem_len; unsigned int type; unsigned int type_aux; unsigned int visual; short unsigned int xpanstep; short unsigned int ypanstep; short unsigned int ywrapstep; unsigned int line_length; long unsigned int mmio_start; unsigned int mmio_len; unsigned int accel; short unsigned int capabilities; short unsigned int reserved[2]; }; struct fb_var_screeninfo { unsigned int xres; unsigned int yres; unsigned int xres_virtual; unsigned int yres_virtual; unsigned int xoffset; unsigned int yoffset; unsigned int bits_per_pixel; unsigned int grayscale; struct fb_bitfield red; struct fb_bitfield green; struct fb_bitfield blue; struct fb_bitfield transp; unsigned int nonstd; unsigned int activate; unsigned int height; unsigned int width; unsigned int accel_flags; unsigned int pixclock; unsigned int left_margin; unsigned int right_margin; unsigned int upper_margin; unsigned int lower_margin; unsigned int hsync_len; unsigned int vsync_len; unsigned int sync; unsigned int vmode; unsigned int rotate; unsigned int colorspace; unsigned int reserved[4]; }; ]]
gpl-2.0
gedads/Neodynamis
scripts/globals/spells/thunderstorm.lua
32
1193
-------------------------------------- -- Spell: Thunderstorm -- Changes the weather around target party member to "thundery." -------------------------------------- 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) target:delStatusEffectSilent(EFFECT_FIRESTORM); target:delStatusEffectSilent(EFFECT_SANDSTORM); target:delStatusEffectSilent(EFFECT_RAINSTORM); target:delStatusEffectSilent(EFFECT_WINDSTORM); target:delStatusEffectSilent(EFFECT_HAILSTORM); target:delStatusEffectSilent(EFFECT_THUNDERSTORM); target:delStatusEffectSilent(EFFECT_AURORASTORM); target:delStatusEffectSilent(EFFECT_VOIDSTORM); local merit = caster:getMerit(MERIT_STORMSURGE); local power = 0; if merit > 0 then power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2; end target:addStatusEffect(EFFECT_THUNDERSTORM,power,0,180); return EFFECT_THUNDERSTORM; end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Norg/npcs/Vishwas.lua
3
1029
----------------------------------- -- Area: Norg -- NPC: Vishwas -- Type: Standard NPC -- @zone 252 -- !pos 44.028 -7.282 13.663 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00da); 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
gedads/Neodynamis
scripts/zones/Abyssea-Attohwa/npcs/qm10.lua
3
1342
----------------------------------- -- Zone: Abyssea-Attohwa -- NPC: qm10 (???) -- Spawns Maahes -- !pos ? ? ? 215 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3081,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17658270) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17658270):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3081); -- Inform player what items they need. 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
taschemann/kq-lives
scripts/bridge2.lua
2
3727
-- bridge2 - "On Brayden river Randen and Andra, complete" -- /* -- { -- Which globals should we have for the (incomplete) bridge? -- -- P_FIGHTONBRIDGE -- (0)..(4) [Not calculated]: when this is <=4, we will not use bridge2 -- (5) Slept at the inn, bridge is pretty close to being done -- (6) [Not calculated]: when this is >= 6, we will not even enter the map -- -- P_LOSERONBRIDGE -- (0) Have not spoken to man who forgot his sword -- (1) Spoke to him after defeating the monsters -- -- P_ASLEEPONBRIDGE -- (0) Have not spoken to man sleeping on bridge -- (1) Man is asleep again -- } -- */ function autoexec() refresh() end function entity_handler(en) if (en == 0) then bubble(en, _"There have been no further threats. Thank you.") elseif (en == 1) then if (get_progress(P_LOSERONBRIDGE) == 0) then bubble(en, _"It's a good thing you helped us out with that monster!") bubble(HERO1, _"Oh, it was nothing...") bubble(en, _"No, really! I don't have a sword!") wait(50) bubble(en, _"I probably shouldn't have told you that.") set_progress(P_LOSERONBRIDGE, 1) elseif (get_progress(P_LOSERONBRIDGE) == 1) then bubble(HERO1, _"So what happened to your sword?") bubble(en, _"...") wait(50) bubble(en, _"My dog ate it.") set_progress(P_LOSERONBRIDGE, 2) elseif (get_progress(P_LOSERONBRIDGE) == 2) then bubble(en, _"Hey, look! I found a board with a nail in it!") thought(HERO1, _"Oh, good grief!") bubble(en, _"Fear my wrath! Hi-yah!") end elseif (en == 2) then bubble(en, _"Just a few more planks and this will be finished!") elseif (en == 3) then bubble(en, _"I... zzz... can't stay awak... zzz...") elseif (en == 4) then bubble(en, _"*YAWN!* That other guy's yawning is contagious!") elseif (en == 5) then bubble(en, _"My breaks are too short. I could really use another one.") elseif (en == 6) then bubble(en, _"I've planted flowers underneath the bridge.") elseif (en == 7) then bubble(en, _"I'm an architect. I'm building these pillars to reinforce the bridge.") elseif (en == 8) then if (get_progress(P_BANGTHUMB) == 0) then bubble(en, _"Yes, wha...") msg(_"WHAM!", 255, 0) bubble(en, _"Yow!! My thumb! I banged my thumb!") if (get_ent_tilex(HERO1) > get_ent_tilex(en)) then set_ent_facing(en, FACE_RIGHT) elseif (get_ent_tiley(HERO1) > get_ent_tiley(en)) then set_ent_facing(en, FACE_DOWN) end bubble(en, _"I hope that you're satisfied!") else bubble(en, _"Owww, my poor thumb...") end elseif (en == 9) then bubble(en, _"Some moron rode a wagon over here with STONE RIMS! I'd like to find the no-good, lousy...") end end function postexec() return end function refresh() showch("treasure1", 8) showch("treasure2", 90) end -- Show the status of a treasures function showch(which_marker, which_chest) -- Set tiles if -1 passed in as 'which_chest' or if chest already opened if (get_treasure(which_chest) == 1) then set_zone(which_marker, 0) end if (which_marker == "treasure1") then set_obs(which_marker, 0) end if (which_marker == "treasure2") then set_ftile(which_marker, 0) end end function zone_handler(zn) if (zn == 1) then change_map("main", "bridge", -1, 0) elseif (zn == 2) then -- // TT: This is still here incase the player didn't get it on the first -- // (incomplete) bridge. They can only get it once. chest(8, I_OSEED, 2) refresh() elseif (zn == 3) then chest(90, I_REGENERATOR, 1) refresh() elseif (zn == 4) then change_map("main", "bridge", 1, 0) end end
gpl-2.0
starlightknight/darkstar
scripts/zones/Windurst_Walls/npcs/Burute-Sorute.lua
9
5285
----------------------------------- -- Area: Windurst Walls -- NPC: Burute-Sorute -- Type: Title Change NPC -- !pos 0.080 -10.765 5.394 239 ----------------------------------- require("scripts/globals/titles") ----------------------------------- local eventId = 10004 local titleInfo = { { cost = 200, title = { dsp.title.NEW_ADVENTURER, dsp.title.CAT_BURGLAR_GROUPIE, dsp.title.CRAWLER_CULLER, dsp.title.STAR_ONION_BRIGADE_MEMBER, dsp.title.SOB_SUPER_HERO, dsp.title.EDITORS_HATCHET_MAN, dsp.title.SUPER_MODEL, dsp.title.FAST_FOOD_DELIVERER, dsp.title.CARDIAN_TUTOR, dsp.title.KISSER_MAKEUPPER, dsp.title.LOWER_THAN_THE_LOWEST_TUNNEL_WORM, dsp.title.FRESH_NORTH_WINDS_RECRUIT, dsp.title.HEAVENS_TOWER_GATEHOUSE_RECRUIT, dsp.title.NEW_BEST_OF_THE_WEST_RECRUIT, dsp.title.NEW_BUUMAS_BOOMERS_RECRUIT, dsp.title.MOGS_MASTER, dsp.title.EMERALD_EXTERMINATOR, dsp.title.DISCERNING_INDIVIDUAL, dsp.title.VERY_DISCERNING_INDIVIDUAL, dsp.title.EXTREMELY_DISCERNING_INDIVIDUAL, dsp.title.BABBANS_TRAVELING_COMPANION }, }, { cost = 300, title = { dsp.title.SAVIOR_OF_KNOWLEDGE, dsp.title.STAR_ONION_BRIGADIER, dsp.title.QUICK_FIXER, dsp.title.FAKEMOUSTACHED_INVESTIGATOR, dsp.title.CUPIDS_FLORIST, dsp.title.TARUTARU_MURDER_SUSPECT, dsp.title.HEXER_VEXER, dsp.title.GREAT_GRAPPLER_SCORPIO, dsp.title.CERTIFIED_ADVENTURER, dsp.title.BOND_FIXER, dsp.title.FOSSILIZED_SEA_FARER, dsp.title.MOGS_KIND_MASTER, }, }, { cost = 400, title = { dsp.title.HAKKURURINKURUS_BENEFACTOR, dsp.title.SPOILSPORT, dsp.title.PILGRIM_TO_MEA, dsp.title.TOTAL_LOSER, dsp.title.DOCTOR_SHANTOTTOS_FLAVOR_OF_THE_MONTH, dsp.title.THE_FANGED_ONE, dsp.title.RAINBOW_WEAVER, dsp.title.FINE_TUNER, dsp.title.DOCTOR_SHANTOTTOS_GUINEA_PIG, dsp.title.GHOSTIE_BUSTER, dsp.title.NIGHT_SKY_NAVIGATOR, dsp.title.DELIVERER_OF_TEARFUL_NEWS, dsp.title.DOWN_PIPER_PIPEUPPERER, dsp.title.DOCTOR_YORANORAN_SUPPORTER, dsp.title.DOCTOR_SHANTOTTO_SUPPORTER, dsp.title.PROFESSOR_KORUMORU_SUPPORTER, dsp.title.STARORDAINED_WARRIOR, dsp.title.SHADOW_BANISHER, dsp.title.MOGS_EXCEPTIONALLY_KIND_MASTER, dsp.title.FRIEND_OF_THE_HELMED, dsp.title.DEED_VERIFIER, }, }, { cost = 500, title = { dsp.title.PARAGON_OF_THIEF_EXCELLENCE, dsp.title.PARAGON_OF_BLACK_MAGE_EXCELLENCE, dsp.title.PARAGON_OF_RANGER_EXCELLENCE, dsp.title.PARAGON_OF_SUMMONER_EXCELLENCE, dsp.title.CERTIFIED_RHINOSTERY_VENTURER, dsp.title.DREAM_DWELLER, dsp.title.HERO_ON_BEHALF_OF_WINDURST, dsp.title.VICTOR_OF_THE_BALGA_CONTEST, dsp.title.MOGS_LOVING_MASTER, dsp.title.HEIR_OF_THE_NEW_MOON, dsp.title.SEEKER_OF_TRUTH, dsp.title.FUGITIVE_MINISTER_BOUNTY_HUNTER, dsp.title.GUIDING_STAR, dsp.title.VESTAL_CHAMBERLAIN, dsp.title.DYNAMIS_WINDURST_INTERLOPER, dsp.title.HEIR_TO_THE_REALM_OF_DREAMS, }, }, { cost = 600, title = { dsp.title.FREESWORD, dsp.title.MERCENARY, dsp.title.MERCENARY_CAPTAIN, dsp.title.COMBAT_CASTER, dsp.title.TACTICIAN_MAGICIAN, dsp.title.WISE_WIZARD, dsp.title.PATRIARCH_PROTECTOR, dsp.title.CASTER_CAPTAIN, dsp.title.MASTER_CASTER, dsp.title.MERCENARY_MAJOR, dsp.title.KNITTING_KNOWITALL, dsp.title.LOOM_LUNATIC, dsp.title.ACCOMPLISHED_WEAVER, dsp.title.BOUTIQUE_OWNER, dsp.title.BONE_BEAUTIFIER, dsp.title.SHELL_SCRIMSHANDER, dsp.title.ACCOMPLISHED_BONEWORKER, dsp.title.CURIOSITY_SHOP_OWNER, dsp.title.FASTRIVER_FISHER, dsp.title.COASTLINE_CASTER, dsp.title.ACCOMPLISHED_ANGLER, dsp.title.FISHMONGER_OWNER, dsp.title.GOURMAND_GRATIFIER, dsp.title.BANQUET_BESTOWER, dsp.title.ACCOMPLISHED_CHEF, dsp.title.RESTAURANT_OWNER, }, }, { cost = 700, title = { dsp.title.MOG_HOUSE_HANDYPERSON, dsp.title.ARRESTER_OF_THE_ASCENSION, }, }, } function onTrade(player,npc,trade) end function onTrigger(player,npc) dsp.title.changerOnTrigger(player, eventId, titleInfo) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) dsp.title.changerOnEventFinish(player, csid, option, eventId, titleInfo) end
gpl-3.0
hades2013/openwrt-mtk
package/ralink/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua
80
2561
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") -- -- SIP trunk info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Trunk Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Trunk %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "trunks") ) end return form -- -- SIP trunk config -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Trunk") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "peer", qualify = "yes", } back = peer:option(DummyValue, "_overview", "Back to trunk overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks") sipdomain = peer:option(Value, "host", "SIP Domain") sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy") outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port") register = peer:option(Flag, "register", "Register with peer") register.enabled = "yes" register.disabled = "no" regext = peer:option(Value, "registerextension", "Extension to register (optional)") regext:depends({register="1"}) didval = peer:option(ListValue, "_did", "Number of assigned DID numbers") didval:value("", "(none)") for i=1,24 do didval:value(i) end dialplan = peer:option(ListValue, "context", "Dialplan Context") dialplan:value(arg[1] .. "_inbound", "(default)") cbimap.uci:foreach("asterisk", "dialplan", function(s) dialplan:value(s['.name']) end) return cbimap end
gpl-2.0
starlightknight/darkstar
scripts/zones/Windurst_Waters/npcs/Yung_Yaam.lua
11
1123
----------------------------------- -- Area: Windurst Waters -- NPC: Yung Yaam -- Involved In Quest: Wondering Minstrel -- !pos -63 -4 27 238 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) --player:addFame(WINDURST,100) wonderingstatus = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.WONDERING_MINSTREL); fame = player:getFameLevel(WINDURST) if (wonderingstatus <= 1 and fame >= 5) then player:startEvent(637); -- WONDERING_MINSTREL: Quest Available / Quest Accepted elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(643); -- WONDERING_MINSTREL: Quest After else player:startEvent(609); -- Standard Conversation end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
pedro-andrade-inpe/terrame
packages/base/tests/functional/alternative/Agent.lua
3
18755
------------------------------------------------------------------------------------------- -- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling. -- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org -- This code is part of the TerraME framework. -- This framework is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- You should have received a copy of the GNU Lesser General Public -- License along with this library. -- The authors reassure the license terms regarding the warranties. -- They specifically disclaim any warranties, including, but not limited to, -- the implied warranties of merchantability and fitness for a particular purpose. -- The framework provided hereunder is on an "as is" basis, and the authors have no -- obligation to provide maintenance, support, updates, enhancements, or modifications. -- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct, -- indirect, special, incidental, or consequential damages arising out of the use -- of this software and its documentation. -- ------------------------------------------------------------------------------------------- return { Agent = function(unitTest) local error_func = function() Agent(2) end unitTest:assertError(error_func, tableArgumentMsg()) error_func = function() Agent{id = 123} end unitTest:assertError(error_func, incompatibleTypeMsg("id", "string", 123)) end, __call = function(unitTest) local BasicAgent = Agent{ id = "2" } local error_func = function() BasicAgent(2) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "table", 2)) error_func = function() BasicAgent{} end unitTest:assertError(error_func, "It is not possible to use an Agent that has attribute 'id' as a constructor.") end, add = function(unitTest) local ag1 = Agent{} local error_func = function() ag1:add() end unitTest:assertError(error_func, incompatibleTypeMsg(1, "State or Trajectory", nil)) error_func = function() ag1:add(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "State or Trajectory", 123)) end, addSocialNetwork = function(unitTest) local ag1 = Agent{} local error_func = function() ag1:addSocialNetwork(nil, "friends") end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() Agent{} ag1:addSocialNetwork({}, "friends") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "SocialNetwork", {})) ag1 = Agent{} local sn = SocialNetwork() error_func = function() ag1:addSocialNetwork(sn, 123) end unitTest:assertError(error_func, incompatibleTypeMsg(2, "string", 123)) end, die = function(unitTest) local ag = Agent{ on_message = function() end } ag:die() local ag2 = Agent{} local test_function = function() ag:walk() end unitTest:assertError(test_function, "Trying to use a function or an attribute of a dead Agent.") test_function = function() ag2:message{ receiver = ag } end unitTest:assertError(test_function, incompatibleTypeMsg("receiver", "Agent", ag)) end, emptyNeighbor = function(unitTest) local ag1 = Agent{mvalue = 3} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} local error_func = function() ag1:emptyNeighbor() end unitTest:assertError(error_func, "The Agent does not have a default placement. Please call Environment:createPlacement() first.") error_func = function() ag1:emptyNeighbor("mvalue") end unitTest:assertError(error_func, "Placement 'mvalue' should be a Trajectory, got number.") error_func = function() ag1:emptyNeighbor("placement2") end unitTest:assertError(error_func, "Placement 'placement2' does not exist. Please call Environment:createPlacement() first.") myEnv:createPlacement{strategy = "void"} local c1 = cs.cells[1] ag1:enter(c1) error_func = function() ag1:emptyNeighbor() end unitTest:assertError(error_func, "The CellularSpace does not have a default neighborhood. Please call 'CellularSpace:createNeighborhood' first.") error_func = function() ag1:emptyNeighbor("placement", "2") end unitTest:assertError(error_func, "Neighborhood '2' does not exist.") error_func = function() ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1) ag1:emptyNeighbor(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 123)) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1,"placement") error_func = function() ag1:emptyNeighbor("123") end unitTest:assertError(error_func, "Placement '123' does not exist. Please call Environment:createPlacement() first.") end, enter = function(unitTest) local ag1 = Agent{} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} local error_func = function() ag1:enter(nil, "placement") end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} ag1:enter({}, "placement") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Cell", {})) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} local cell = cs.cells[1] error_func = function() ag1:enter(cell, 123) end unitTest:assertError(error_func, incompatibleTypeMsg(2, "string", 123)) local predator = Agent{} local predators = Society{ instance = predator, quantity = 5 } cs = CellularSpace{xdim = 5} local e = Environment{predators, cs} e:createPlacement() local ag = predators:sample() ag:leave() local c = Cell{} error_func = function() ag:enter(c) end unitTest:assertError(error_func, "Placement 'placement' was not found in the Cell.") end, execute = function(unitTest) local ag1 = Agent{ id = "MyFirst", State{ id = "first" }, } local error_func = function() ag1:execute() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() ag1 = Agent{ id = "MyFirst", State{ id = "first" }, } ag1:execute({}) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Event", {})) end, getCell = function(unitTest) local ag1 = Agent{pl = 2} local error_func = function() ag1:getCell() end unitTest:assertError(error_func, "The Agent does not have a default placement. Please call Environment:createPlacement() first.") error_func = function() ag1:getCell("pl") end unitTest:assertError(error_func, "Placement 'pl' should be a Trajectory, got number.") end, getCells = function(unitTest) local ag1 = Agent{pl = 2} local error_func = function() ag1:getCells("pl") end unitTest:assertError(error_func, "Placement 'pl' should be a Trajectory, got number.") end, getSocialNetwork = function(unitTest) local ag1 = Agent{} local sn = SocialNetwork() ag1:addSocialNetwork(sn) local error_func = function() sn2 = ag1:getSocialNetwork{} end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", {})) end, leave = function(unitTest) local error_func = function() local ag1 = Agent{} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} local cell = cs.cells[1] ag1:enter(cell, "placement") ag1:leave({}) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", {})) error_func = function() local ag1 = Agent{} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} local cell = cs.cells[1] ag1:enter(cell, "placement") ag1:leave(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 123)) error_func = function() local ag1 = Agent{} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} ag1:leave() end unitTest:assertError(error_func, "Agent should belong to a Cell in order to leave().") local ag1 = Agent{} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} local cell = cs.cells[1] ag1:enter(cell, "placement") error_func = function() ag1:leave("notplacement") end unitTest:assertError(error_func, valueNotFoundMsg(1, "notplacement")) ag1 = Agent{pl = 2} error_func = function() ag1:leave("pl") end unitTest:assertError(error_func, "Placement 'pl' should be a Trajectory, got number.") end, message = function(unitTest) local error_func = function() local ag = Agent{} local sc = Society{instance = ag, quantity = 2} local ag1 = sc.agents[1] ag1:message() end unitTest:assertError(error_func, tableArgumentMsg()) error_func = function() local ag = Agent{} local sc = Society{instance = ag, quantity = 2} local ag1 = sc.agents[1] ag1:message(123) end unitTest:assertError(error_func, namedArgumentsMsg()) local ag = Agent{} local sc = Society{instance = ag, quantity = 2} local ag1 = sc.agents[1] error_func = function() ag1:message{} end unitTest:assertError(error_func, mandatoryArgumentMsg("receiver")) ag = Agent{} sc = Society{instance = ag, quantity = 2} ag1 = sc.agents[1] local ag2 = sc.agents[2] error_func = function() ag1:message{ receiver = ag2, delay = "not_number", content = "money" } end unitTest:assertError(error_func, incompatibleTypeMsg("delay", "number", "money")) ag = Agent{} sc = Society{instance = ag, quantity = 2} ag1 = sc.agents[1] ag2 = sc.agents[2] error_func = function() ag1:message{ receiver = ag2, delay = -1, content = "money" } end unitTest:assertError(error_func, positiveArgumentMsg("delay", -1, true)) error_func = function() ag1:message{ receiver = ag2, subject = 2 } end unitTest:assertError(error_func, incompatibleTypeMsg("subject", "string", 2)) end, move = function(unitTest) local error_func = function() local ag1 = Agent{} local cs = CellularSpace{ xdim = 3} local myEnv = Environment {cs, ag1} myEnv:createPlacement{strategy = "void", name = "renting"} local c1 = cs.cells[1] ag1:enter(c1,"renting") ag1:move() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) local ag1 = Agent{} local ag2 = Agent{} local cs = CellularSpace{ xdim = 3} local myEnv = Environment {cs, ag1} myEnv:createPlacement{strategy = "void", name = "renting"} local c1 = cs.cells[1] ag1:enter(c1, "renting") error_func = function() ag1:move(ag2, "renting") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Cell", ag2)) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void", name = "test"} c1 = cs.cells[1] error_func = function() ag1:enter(c1) end unitTest:assertError(error_func, "Placement 'placement' was not found in the Agent.") ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void", name = "renting"} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1, "renting") error_func = function() ag1:move(c1, 123) end unitTest:assertError(error_func, incompatibleTypeMsg(2, "string", 123)) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void", name = "renting"} c1 = cs.cells[1] ag1:enter(c1, "renting") c1 = cs.cells[4] error_func = function() ag1:move(c1, "not_placement") end unitTest:assertError(error_func, valueNotFoundMsg(2, "not_placement")) ag1:leave("renting") error_func = function() ag1:move(c1, "renting") end unitTest:assertError(error_func, "Agent should belong to a Cell in order to move().") end, notify = function(unitTest) local ag = Agent{x = 1, y = 1} local error_func = function() ag:notify("not_int") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "number", "not_int")) error_func = function() ag:notify(-1) end unitTest:assertError(error_func, positiveArgumentMsg(1, -1, true)) end, on_message = function(unitTest) local ag1 = Agent{} local ag2 = Agent{} local error_func = function() ag1:message{receiver = ag2} end unitTest:assertError(error_func, "Agent 'nil' cannot get a message from 'nil' because it does not implement 'on_message'.") end, reproduce = function(unitTest) local a = Agent{} local s = Society{ instance = a, quantity = 5 } local error_func = function() a:reproduce() end unitTest:assertError(error_func, "Agent should belong to a Society to be able to reproduce.") error_func = function() s:sample():reproduce(2) end unitTest:assertError(error_func, namedArgumentsMsg()) end, walk = function(unitTest) local ag1 = Agent{mvalue = 3} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} local error_func = function() ag1:walk() end unitTest:assertError(error_func, "The Agent does not have a default placement. Please call Environment:createPlacement() first.") error_func = function() ag1:walk("mvalue") end unitTest:assertError(error_func, "Placement 'mvalue' should be a Trajectory, got number.") error_func = function() ag1:walk("placement2") end unitTest:assertError(error_func, "Placement 'placement2' does not exist. Please call Environment:createPlacement() first.") myEnv:createPlacement{strategy = "void"} local c1 = cs.cells[1] ag1:enter(c1) error_func = function() ag1:walk() end unitTest:assertError(error_func, "The CellularSpace does not have a default neighborhood. Please call 'CellularSpace:createNeighborhood' first.") error_func = function() ag1:walk("placement", "2") end unitTest:assertError(error_func, "Neighborhood '2' does not exist.") error_func = function() ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1) ag1:walk(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 123)) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1,"placement") error_func = function() ag1:walk("123") end unitTest:assertError(error_func, "Placement '123' does not exist. Please call Environment:createPlacement() first.") end, walkIfEmpty = function(unitTest) local ag1 = Agent{mvalue = 3} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} local error_func = function() ag1:walkIfEmpty() end unitTest:assertError(error_func, "The Agent does not have a default placement. Please call Environment:createPlacement() first.") error_func = function() ag1:walkIfEmpty("mvalue") end unitTest:assertError(error_func, "Placement 'mvalue' should be a Trajectory, got number.") error_func = function() ag1:walkIfEmpty("placement2") end unitTest:assertError(error_func, "Placement 'placement2' does not exist. Please call Environment:createPlacement() first.") myEnv:createPlacement{strategy = "void"} local c1 = cs.cells[1] ag1:enter(c1) error_func = function() ag1:walkIfEmpty() end unitTest:assertError(error_func, "The CellularSpace does not have a default neighborhood. Please call 'CellularSpace:createNeighborhood' first.") error_func = function() ag1:walkIfEmpty("placement", "2") end unitTest:assertError(error_func, "Neighborhood '2' does not exist.") error_func = function() ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1) ag1:walkIfEmpty(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 123)) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1,"placement") error_func = function() ag1:walkIfEmpty("123") end unitTest:assertError(error_func, "Placement '123' does not exist. Please call Environment:createPlacement() first.") end, walkToEmpty = function(unitTest) local ag1 = Agent{mvalue = 3} local cs = CellularSpace{xdim = 3} local myEnv = Environment{cs, ag1} local error_func = function() ag1:walkToEmpty() end unitTest:assertError(error_func, "The Agent does not have a default placement. Please call Environment:createPlacement() first.") error_func = function() ag1:walkToEmpty("mvalue") end unitTest:assertError(error_func, "Placement 'mvalue' should be a Trajectory, got number.") error_func = function() ag1:walkToEmpty("placement2") end unitTest:assertError(error_func, "Placement 'placement2' does not exist. Please call Environment:createPlacement() first.") myEnv:createPlacement{strategy = "void"} local c1 = cs.cells[1] ag1:enter(c1) error_func = function() ag1:walkToEmpty() end unitTest:assertError(error_func, "The CellularSpace does not have a default neighborhood. Please call 'CellularSpace:createNeighborhood' first.") error_func = function() ag1:walkToEmpty("placement", "2") end unitTest:assertError(error_func, "Neighborhood '2' does not exist.") error_func = function() ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1) ag1:walkToEmpty(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 123)) ag1 = Agent{} cs = CellularSpace{xdim = 3} myEnv = Environment{cs, ag1} myEnv:createPlacement{strategy = "void"} c1 = cs.cells[1] ag1:enter(c1,"placement") error_func = function() ag1:walkToEmpty("123") end unitTest:assertError(error_func, "Placement '123' does not exist. Please call Environment:createPlacement() first.") end }
lgpl-3.0
janlou/AdvanSource
system/libs/lua-redis.lua
40
35598
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-2.0
gedads/Neodynamis
scripts/zones/Selbina/npcs/Chutarmire.lua
17
1765
----------------------------------- -- Area: Selbina -- NPC: Chutarmire -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHUTARMIRE_SHOP_DIALOG); stock = {0x12A0,5751, -- Scroll of Stone II 0x12AA,8100, -- Scroll of Water II 0x129B,11970, -- Scroll of Aero II 0x1291,16560, -- Scroll of Fire II 0x1296,21870, -- Scroll of Blizzard II 0x12A5,27900, -- Scroll of Thunder II 0x12BD,1165, -- Scroll of Stonega 0x12C7,2097, -- Scroll of Waterga 0x12B8,4147, -- Scroll of Aeroga 0x12AE,7025, -- Scroll of Firaga 0x12B3,10710, -- Scroll of Blizzaga 0x12C2,15120, -- Scroll of Thundaga 0x12DD,22680, -- Scroll of Poison II 0x12E7,12600, -- Scroll of Bio II 0x12E1,4644, -- Scroll of Poisonga 0x12FB,8100} -- Scroll of Shock Spikes showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Castle_Zvahl_Keep/mobs/Viscount_Morax.lua
3
1053
----------------------------------- -- Area: -- MOB: Viscount_Morax ----------------------------------- ----------------------------------- require("scripts/globals/titles"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(HELLSBANE); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Set Viscount_Morax's Window Open Time local wait = math.random((3600),(28800)); SetServerVariable("[POP]Viscount_Morax", os.time() + wait); -- 1-8 hours DisallowRespawn(mob:getID(), true); -- Set PH back to normal, then set to respawn spawn local PH = GetServerVariable("[PH]Viscount_Morax"); SetServerVariable("[PH]Viscount_Morax", 0); DisallowRespawn(PH, false); GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH)); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Port_Bastok/npcs/Otto.lua
3
1147
----------------------------------- -- Area: Port Bastok -- NPC: Otto -- Standard Info NPC -- Involved in Quest: The Siren's Tear -- @zone 236 -- !pos -145.929 -7.48 -13.701 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local SirensTear = player:getQuestStatus(BASTOK,THE_SIREN_S_TEAR); if (SirensTear == QUEST_ACCEPTED and player:getVar("SirensTear") == 0) then player:startEvent(0x0005); else player:startEvent(0x0014); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
gedads/Neodynamis
scripts/globals/items/plate_of_tentacle_sushi_+1.lua
12
1747
----------------------------------------- -- ID: 5216 -- Item: plate_of_tentacle_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 20 -- Dexterity 3 -- Agility 3 -- Accuracy % 20 (cap 20) -- Ranged Accuracy % 20 (cap 20) -- Double Attack 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,3600,5216); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_AGI, 3); target:addMod(MOD_FOOD_ACCP, 20); target:addMod(MOD_FOOD_ACC_CAP, 20); target:addMod(MOD_FOOD_RACCP, 20); target:addMod(MOD_FOOD_RACC_CAP, 20); target:addMod(MOD_DOUBLE_ATTACK, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_AGI, 3); target:delMod(MOD_FOOD_ACCP, 20); target:delMod(MOD_FOOD_ACC_CAP, 20); target:delMod(MOD_FOOD_RACCP, 20); target:delMod(MOD_FOOD_RACC_CAP, 20); target:delMod(MOD_DOUBLE_ATTACK, 1); end;
gpl-3.0
gedads/Neodynamis
scripts/globals/items/danceshroom.lua
12
1190
----------------------------------------- -- ID: 4375 -- Item: danceshroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -5 -- Mind 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,300,4375); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -5); target:addMod(MOD_MND, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -5); target:delMod(MOD_MND, 3); end;
gpl-3.0
starlightknight/darkstar
scripts/globals/abilities/pets/shock_absorber.lua
12
1926
--------------------------------------------- -- Shock Absorber --------------------------------------------- require("scripts/globals/automatonweaponskills") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") --------------------------------------------- function onMobSkillCheck(target, automaton, skill) return 0 end function onPetAbility(target, automaton, skill, master, action) automaton:addRecast(dsp.recast.ABILITY, skill:getID(), 180) local maneuvers = master:countEffect(dsp.effect.EARTH_MANEUVER) local pMod = math.max(automaton:getSkillLevel(dsp.skill.AUTOMATON_MELEE), automaton:getSkillLevel(dsp.skill.AUTOMATON_RANGED), automaton:getSkillLevel(dsp.skill.AUTOMATON_MAGIC)) local duration = 180 local amount = 200 local bonus = 0 if automaton:getLocalVar("shockabsorber") >= 4 then -- Shock Absorber III if maneuvers == 1 then bonus = pMod * 0.6 elseif maneuvers == 2 then bonus = pMod * 1.0 elseif maneuvers == 3 then bonus = pMod * 1.4 end elseif automaton:getLocalVar("shockabsorber") >= 2 then -- Shock Absorber II if maneuvers == 1 then bonus = pMod * 0.4 elseif maneuvers == 2 then bonus = pMod * 0.75 elseif maneuvers == 3 then bonus = pMod * 1.0 end else -- Shock Absorber if maneuvers == 1 then bonus = pMod * 0.2 elseif maneuvers == 2 then bonus = pMod * 0.4 elseif maneuvers == 3 then bonus = pMod * 0.75 end end amount = amount + math.floor(bonus) if target:addStatusEffect(dsp.effect.STONESKIN, amount, 0, duration, 0, 0, 4) then skill:setMsg(dsp.msg.basic.SKILL_GAIN_EFFECT) else skill:setMsg(dsp.msg.basic.SKILL_NO_EFFECT) end return dsp.effect.STONESKIN end
gpl-3.0
starlightknight/darkstar
scripts/globals/abilities/pets/tail_whip.lua
11
1358
--------------------------------------------------- -- Tail Whip M=5 --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/summon") --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0 end function onPetAbility(target, pet, skill) local numhits = 1 local accmod = 1 local dmgmod = 5 local totaldamage = 0 local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3) totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.PIERCING,numhits) local duration = 120 local resm = applyPlayerResistance(pet,-1,target,pet:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT),dsp.skill.ELEMENTAL_MAGIC, 5) if resm < 0.25 then resm = 0 end duration = duration * resm if (duration > 0 and AvatarPhysicalHit(skill, totaldamage) and target:hasStatusEffect(dsp.effect.WEIGHT) == false) then target:addStatusEffect(dsp.effect.WEIGHT, 50, 0, duration) end target:takeDamage(totaldamage, pet, dsp.attackType.PHYSICAL, dsp.damageType.PIERCING) target:updateEnmityFromDamage(pet,totaldamage) return totaldamage end
gpl-3.0
gedads/Neodynamis
scripts/zones/North_Gustaberg/npcs/Monument.lua
3
1484
----------------------------------- -- Area: North Gustaberg -- NPC: Monument -- Involved in Quest "Hearts of Mythril" -- !pos 300.000 -62.803 498.200 106 ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Hearts = player:getQuestStatus(BASTOK,HEARTS_OF_MYTHRIL); if (Hearts == QUEST_ACCEPTED and player:hasKeyItem(BOUQUETS_FOR_THE_PIONEERS)) then player:startEvent(0x000b); 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 == 0x000b and option == 0) then player:setVar("HeartsOfMythril",1); player:delKeyItem(BOUQUETS_FOR_THE_PIONEERS); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Davoi/npcs/_451.lua
17
1190
----------------------------------- -- Area: Davoi -- NPC: _451 (Elevator Lever) -- Notes: Used to operate Elevator @450 (actual npc script is _454) ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) npc:openDoor(3); -- lever animation RunElevator(ELEVATOR_DAVOI_LIFT); -- elevator @450 (actual npc script is _454) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Northern_San_dOria/npcs/Castilchat.lua
9
3083
----------------------------------- -- Area: Northern San d'Oria -- NPC: Castilchat -- Starts Quest: Trial Size Trial by Ice -- !pos -186 0 107 231 ----------------------------------- local ID = require("scripts/zones/Northern_San_dOria/IDs"); require("scripts/globals/teleports"); require("scripts/globals/status"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local count = trade:getItemCount(); if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and trade:hasItemQty(532,1) and count == 1) then player:messageSpecial(ID.text.FLYER_REFUSED); elseif (trade:hasItemQty(1545,1) and player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.TRIAL_SIZE_TRIAL_BY_ICE) == QUEST_ACCEPTED and player:getMainJob() == dsp.job.SMN and count == 1) then -- Trade mini fork of ice player:startEvent(734,0,1545,4,20); end end; function onTrigger(player,npc) local TrialSizeByIce = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.TRIAL_SIZE_TRIAL_BY_ICE); if (player:getMainLvl() >= 20 and player:getMainJob() == dsp.job.SMN and TrialSizeByIce == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 2) then -- Requires player to be Summoner at least lvl 20 player:startEvent(733,0,1545,4,20); --mini tuning fork of ice, zone, level elseif (TrialSizeByIce == QUEST_ACCEPTED) then local IceFork = player:hasItem(1545); if (IceFork) then player:startEvent(708); --Dialogue given to remind player to be prepared elseif (IceFork == false and tonumber(os.date("%j")) ~= player:getCharVar("TrialSizeIce_date")) then player:startEvent(737,0,1545,4,20); -- Need another mini tuning fork else player:startEvent(758); -- Standard dialog when you loose, and you don't wait 1 real day end elseif (TrialSizeByIce == QUEST_COMPLETED) then player:startEvent(736); -- Defeated Avatar else player:startEvent(711); -- Standard dialog end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 733 and option == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,1545); else player:setCharVar("TrialSizeIce_date", 0); player:addQuest(SANDORIA,dsp.quest.id.sandoria.TRIAL_SIZE_TRIAL_BY_ICE); player:addItem(1545); player:messageSpecial(ID.text.ITEM_OBTAINED,1545); end elseif (csid == 734 and option == 0 or csid == 737) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,1545); else player:addItem(1545); player:messageSpecial(ID.text.ITEM_OBTAINED,1545); end elseif (csid == 734 and option == 1) then dsp.teleport.to(player, dsp.teleport.id.CLOISTER_OF_FROST); end end;
gpl-3.0
mishin/Algorithm-Implementations
Binary_Search/Lua/Yonaba/binary_search_test.lua
53
1896
-- Tests for binary_search.lua local binary_search = require 'binary_search' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Performs a binary search', function() local t = {1, 2, 3, 4, 5} assert(binary_search(t, 1) == 1) assert(binary_search(t, 2) == 2) assert(binary_search(t, 3) == 3) assert(binary_search(t, 4) == 4) assert(binary_search(t, 5) == 5) end) run('Array values do not have to be consecutive',function() local t = {1, 3, 5, 10, 13} assert(binary_search(t, 1) == 1) assert(binary_search(t, 3) == 2) assert(binary_search(t, 5) == 3) assert(binary_search(t, 10) == 4) assert(binary_search(t, 13) == 5) end) run('But the array needs to be sorted',function() local t = {1, 15, 12, 14, 13} assert(binary_search(t, 13) == nil) assert(binary_search(t, 15) == nil) end) run('In case the value exists more than once, it returns any of them',function() local t = {1, 12, 12, 13, 15, 15, 16} assert(binary_search(t, 15) == 6) assert(binary_search(t, 12) == 2) end) run('Accepts comparison functions for reversed arrays',function() local t = {50, 33, 18, 12, 5, 1, 0} local comp = function(a, b) return a > b end assert(binary_search(t, 50, comp) == 1) assert(binary_search(t, 33, comp) == 2) assert(binary_search(t, 18, comp) == 3) assert(binary_search(t, 12, comp) == 4) assert(binary_search(t, 5, comp) == 5) assert(binary_search(t, 1, comp) == 6) assert(binary_search(t, 0, comp) == 7) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
beraldoleal/config
.config/awesome/lain/widget/fs.lua
3
5266
--[[ Licensed under GNU General Public License v2 * (c) 2018, Uli Schlacter * (c) 2018, Otto Modinos * (c) 2013, Luca CPZ --]] local helpers = require("lain.helpers") local Gio = require("lgi").Gio local focused = require("awful.screen").focused local wibox = require("wibox") local naughty = require("naughty") local math = math local string = string local tconcat = table.concat local type = type local tonumber = tonumber local query_size = Gio.FILE_ATTRIBUTE_FILESYSTEM_SIZE local query_free = Gio.FILE_ATTRIBUTE_FILESYSTEM_FREE local query_used = Gio.FILE_ATTRIBUTE_FILESYSTEM_USED local query = query_size .. "," .. query_free .. "," .. query_used -- File systems info -- lain.widget.fs local function factory(args) local fs = { widget = wibox.widget.textbox(), units = { [1] = "Kb", [2] = "Mb", [3] = "Gb", [4] = "Tb", [5] = "Pb", [6] = "Eb", [7] = "Zb", [8] = "Yb" } } function fs.hide() if not fs.notification then return end naughty.destroy(fs.notification) fs.notification = nil end function fs.show(seconds, scr) fs.hide(); fs.update() fs.notification_preset.screen = fs.followtag and focused() or scr or 1 fs.notification = naughty.notify { preset = fs.notification_preset, timeout = type(seconds) == "number" and seconds or 5 } end local args = args or {} local timeout = args.timeout or 600 local partition = args.partition local threshold = args.threshold or 99 local showpopup = args.showpopup or "on" local settings = args.settings or function() end fs.followtag = args.followtag or false fs.notification_preset = args.notification_preset if not fs.notification_preset then fs.notification_preset = { font = "Monospace 10", fg = "#FFFFFF", bg = "#000000" } end function fs.update() local notifytable = { [1] = string.format("%-10s %4s\t%6s\t%6s\t\n", "path", "used", "free", "size") } local pathlen = 10 local maxpathidx = 1 fs_now = {} for _, mount in ipairs(Gio.unix_mounts_get()) do local path = Gio.unix_mount_get_mount_path(mount) local root = Gio.File.new_for_path(path) local info = root:query_filesystem_info(query) if info then local size = info:get_attribute_uint64(query_size) local used = info:get_attribute_uint64(query_used) local free = info:get_attribute_uint64(query_free) if size > 0 then local units = math.floor(math.log(size)/math.log(1024)) fs_now[path] = { units = fs.units[units], percentage = math.floor(100 * used / size), -- used percentage size = size / math.pow(1024, math.floor(units)), used = used / math.pow(1024, math.floor(units)), free = free / math.pow(1024, math.floor(units)) } if fs_now[path].percentage > 0 then -- don't notify unused file systems notifytable[#notifytable+1] = string.format("\n%-10s %3s%%\t%6.2f\t%6.2f\t%s", path, math.floor(fs_now[path].percentage), fs_now[path].free, fs_now[path].size, fs_now[path].units) if #path > pathlen then pathlen = #path maxpathidx = #notifytable end end end end end widget = fs.widget settings() if partition and fs_now[partition] and fs_now[partition].percentage >= threshold then if not helpers.get_map(partition) then naughty.notify { preset = naughty.config.presets.critical, title = "Warning", text = string.format("%s is above %d%% (%d%%)", partition, threshold, fs_now[partition].percentage) } helpers.set_map(partition, true) else helpers.set_map(partition, false) end end if pathlen > 10 then -- if are there paths longer than 10 chars, reformat first column accordingly local pathspaces for i = 1, #notifytable do pathspaces = notifytable[i]:match("[ ]+") if i ~= maxpathidx and pathspaces then notifytable[i] = notifytable[i]:gsub(pathspaces, pathspaces .. string.rep(" ", pathlen - 10)) end end end fs.notification_preset.text = tconcat(notifytable) end if showpopup == "on" then fs.widget:connect_signal('mouse::enter', function () fs.show(0) end) fs.widget:connect_signal('mouse::leave', function () fs.hide() end) end helpers.newtimer(partition or "fs", timeout, fs.update) return fs end return factory
mit
nyaki-HUN/DESIRE
DESIRE-Modules/UI-HorusUI/project/premake5.lua
1
3165
project "UI-HorusUI" AddModuleConfig() uuid "BE777A47-193E-4B77-83E1-FAF6A383C236" pchheader "stdafx_HorusUI.h" pchsource "../src/stdafx_HorusUI.cpp" removeflags { "FatalCompileWarnings" } defines { "HORUS_STATIC", "FT2_BUILD_LIBRARY", "FT_CONFIG_OPTION_SYSTEM_ZLIB", } includedirs { "../Externals/horus_ui", "../Externals/horus_ui/include", "../Externals/horus_ui/libs/freetype/include", "../Externals/horus_ui/libs/jsoncpp/include", "../../Compression-zlib/Externals/zlib", } removefiles { "../Externals/horus_ui/libs/freetype/src/**.c", } files { "../Externals/horus_ui/libs/freetype/src/autofit/autofit.c", "../Externals/horus_ui/libs/freetype/src/base/ftbase.c", "../Externals/horus_ui/libs/freetype/src/base/ftbbox.c", "../Externals/horus_ui/libs/freetype/src/base/ftbdf.c", "../Externals/horus_ui/libs/freetype/src/base/ftbitmap.c", "../Externals/horus_ui/libs/freetype/src/base/ftcid.c", "../Externals/horus_ui/libs/freetype/src/base/ftdebug.c", "../Externals/horus_ui/libs/freetype/src/base/ftfntfmt.c", "../Externals/horus_ui/libs/freetype/src/base/ftfstype.c", "../Externals/horus_ui/libs/freetype/src/base/ftgasp.c", "../Externals/horus_ui/libs/freetype/src/base/ftglyph.c", "../Externals/horus_ui/libs/freetype/src/base/ftgxval.c", "../Externals/horus_ui/libs/freetype/src/base/ftinit.c", "../Externals/horus_ui/libs/freetype/src/base/ftlcdfil.c", "../Externals/horus_ui/libs/freetype/src/base/ftmm.c", "../Externals/horus_ui/libs/freetype/src/base/ftotval.c", "../Externals/horus_ui/libs/freetype/src/base/ftpatent.c", "../Externals/horus_ui/libs/freetype/src/base/ftpfr.c", "../Externals/horus_ui/libs/freetype/src/base/ftstroke.c", "../Externals/horus_ui/libs/freetype/src/base/ftsynth.c", "../Externals/horus_ui/libs/freetype/src/base/ftsystem.c", "../Externals/horus_ui/libs/freetype/src/base/fttype1.c", "../Externals/horus_ui/libs/freetype/src/base/ftwinfnt.c", "../Externals/horus_ui/libs/freetype/src/bdf/bdf.c", "../Externals/horus_ui/libs/freetype/src/bzip2/ftbzip2.c", "../Externals/horus_ui/libs/freetype/src/cache/ftcache.c", "../Externals/horus_ui/libs/freetype/src/cff/cff.c", "../Externals/horus_ui/libs/freetype/src/cid/type1cid.c", "../Externals/horus_ui/libs/freetype/src/gzip/ftgzip.c", "../Externals/horus_ui/libs/freetype/src/lzw/ftlzw.c", "../Externals/horus_ui/libs/freetype/src/pcf/pcf.c", "../Externals/horus_ui/libs/freetype/src/pfr/pfr.c", "../Externals/horus_ui/libs/freetype/src/psaux/psaux.c", "../Externals/horus_ui/libs/freetype/src/pshinter/pshinter.c", "../Externals/horus_ui/libs/freetype/src/psnames/psnames.c", "../Externals/horus_ui/libs/freetype/src/raster/raster.c", "../Externals/horus_ui/libs/freetype/src/sfnt/sfnt.c", "../Externals/horus_ui/libs/freetype/src/smooth/smooth.c", "../Externals/horus_ui/libs/freetype/src/smooth/ftgrays.c", "../Externals/horus_ui/libs/freetype/src/truetype/truetype.c", "../Externals/horus_ui/libs/freetype/src/type1/type1.c", "../Externals/horus_ui/libs/freetype/src/type42/type42.c", "../Externals/horus_ui/libs/freetype/src/winfonts/winfnt.c", }
bsd-2-clause
gedads/Neodynamis
scripts/zones/Nashmau/npcs/Pyopyoroon.lua
28
2129
----------------------------------- -- Area: Nashmau -- NPC: Pyopyoroon -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(TOAU) == ROYAL_PUPPETEER and player:getVar("AhtUrganStatus") == 1 and trade:hasItemQty(2307,1)) then player:startEvent(279); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(TOAU) == ROYAL_PUPPETEER and player:getVar("AhtUrganStatus") == 0) then player:startEvent(277); elseif (player:getCurrentMission(TOAU) == ROYAL_PUPPETEER and player:getVar("AhtUrganStatus") == 1) then player:startEvent(278); elseif (player:getCurrentMission(TOAU) == LOST_KINGDOM) then player:startEvent(280); else player:startEvent(275); 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 == 277) then player:setVar("AhtUrganStatus",1); elseif (csid == 279 and player:getVar("AhtUrganStatus") == 1) then player:setVar("AhtUrganStatus",0); player:tradeComplete(); player:addKeyItem(VIAL_OF_SPECTRAL_SCENT); player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SPECTRAL_SCENT); player:completeMission(TOAU,ROYAL_PUPPETEER); player:addMission(TOAU,LOST_KINGDOM); end end;
gpl-3.0
ptbrown/rexxparse-lua
src/rexxparse/template.lua
1
5270
local coroutine,yield = coroutine,coroutine.yield local sub,gsub,find = string.sub,string.gsub,string.find local tonumber = tonumber local function parse_template(template) local position, reset local matches, matchstart, matchend local function collectmatches(mstart, mend, ...) if not mstart then return nil end if not (...) then return mstart, mend, {sub(template, mstart, mend)} end return mstart, mend, {...} end local function match(pattern) matchstart, matchend, matches = collectmatches(find(template, pattern, position)) if matchstart then position = matchend + 1 return true end return false end local function check(pattern) return nil ~= find(template, pattern, position) end local function error(errorposition, message) yield("ERROR", errorposition, message) position = #template + 1 yield() -- send nil to abort iteration end local function send(match, parameter, variables) reset = yield(match, parameter, variables) if reset then position = 1 end return reset end -- Dummy yield to collect the arguments yield() while true do position = 1 reset = true -- Return matches in sequence while position <= #template do if reset then -- Blank lines are ignored -- but only at the start of a template match "^[ \t\n]+" else match "^[ \t]+" end reset = false -- Names of variables local variables = {} repeat local token -- Symbol name if match "^[%a_][%w_]*" then variables[#variables+1] = matches[1] -- or Placeholder dot elseif match "^%." then variables[#variables+1] = "." else break end if position <= #template and not (match "^[ \t]+" or check "^[,\n]") then error(position, "variable name or pattern expected") break end until not matches -- End of pattern if position > #template then send("VARS", nil, variables) break elseif match "^[,\n]" then reset = send("VARS", nil, variables) or send("EOT") or true -- Positional patterns elseif match "^([=+-]?)(%d+)" then local token, number number = tonumber(matches[2]) if matches[1] == "=" then token = "POS" else token = "POS" .. matches[1] end send(token, number, variables) -- Variable reference, position or string elseif match "^([=+-]?)%(([%a_][%w_]*)%)" then local token if matches[1] == "" then token = "VREF" elseif matches[1] == "=" then token = "POS" else token = "POS" .. matches[1] end send(token, matches[2], variables) -- or String patterns elseif match "^[\"']" then local quote = matches[1] local strstart = position local escapepattern = "[\\"..quote.."]" repeat if not match(escapepattern) then error(strstart-1, "unterminated quoted string") break end if matches[1] == "\\" then local escaped = sub(template, position, position) if escaped == quote or escaped == "\\" then -- move past character, will substitute later position = position + 1 end end until matches[1] == quote local quotedstring = gsub(sub(template, strstart, matchend - 1), "\\("..escapepattern..")", "%1") send("MATCH", quotedstring, variables) -- or Parse error else error(position, "pattern expected") end -- End of pattern (check again after pattern) if not reset then if position > #template then break elseif match "^[ \t]*[,\n]" then send("EOT") reset = true elseif not match "^[ \t]+" then error(position, "variable name or pattern expected.") break end end end yield("EOT", true) end end return function(template) local parser_thread = coroutine.wrap(parse_template) parser_thread(template) return parser_thread end
mit
gedads/Neodynamis
scripts/globals/abilities/pets/eraser.lua
5
1752
--------------------------------------------- -- Eraser --------------------------------------------- require("scripts/globals/automatonweaponskills") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg"); --------------------------------------------- function onMobSkillCheck(target, automaton, skill) return 0 end function onPetAbility(target, automaton, skill, master, action) automaton:addRecast(RECAST_ABILITY, skill:getID(), 30) local maneuvers = master:countEffect(EFFECT_LIGHT_MANEUVER) skill:setMsg(msgBasic.USES) local function removeStatus() if target:delStatusEffect(EFFECT_PETRIFICATION) then return true end if target:delStatusEffect(EFFECT_SILENCE) then return true end if target:delStatusEffect(EFFECT_BANE) then return true end if target:delStatusEffect(EFFECT_CURSE_II) then return true end if target:delStatusEffect(EFFECT_CURSE) then return true end if target:delStatusEffect(EFFECT_PARALYSIS) then return true end if target:delStatusEffect(EFFECT_PLAGUE) then return true end if target:delStatusEffect(EFFECT_POISON) then return true end if target:delStatusEffect(EFFECT_DISEASE) then return true end if target:delStatusEffect(EFFECT_BLINDNESS) then return true end if target:eraseStatusEffect() ~= 255 then return true end return false end local toremove = maneuvers local removed = 0 repeat if not removeStatus() then break end toremove = toremove - 1 removed = removed + 1 until (toremove <= 0) for i = 1, maneuvers do master:delStatusEffectSilent(EFFECT_LIGHT_MANEUVER) end return removed end
gpl-3.0
starlightknight/darkstar
scripts/zones/Bastok_Markets/npcs/Zaira.lua
12
1150
----------------------------------- -- Area: Batok Markets -- NPC: Zaira -- Standard Merchant NPC -- !pos -217.316 -2.824 49.235 235 ----------------------------------- local ID = require("scripts/zones/Bastok_Markets/IDs") require("scripts/globals/shop") function onTrigger(player,npc) local stock = { 4862, 114, 1, -- Scroll of Blind 4838, 360, 2, -- Scroll of Bio 4828, 82, 2, -- Scroll of Poison 4861, 2250, 2, -- Scroll of Sleep 4767, 61, 3, -- Scroll of Stone 4777, 140, 3, -- Scroll of Water 4762, 324, 3, -- Scroll of Aero 4752, 837, 3, -- Scroll of Fire 4757, 1584, 3, -- Scroll of Blizzard 4772, 3261, 3, -- Scroll of Thunder 4847, 1363, 3, -- Scroll of Shock 4846, 1827, 3, -- Scroll of Rasp 4845, 2250, 3, -- Scroll of Choke 4844, 3688, 3, -- Scroll of Frost 4843, 4644, 3, -- Scroll of Burn 4848, 6366, 3, -- Scroll of Drown } player:showText(npc, ID.text.ZAIRA_SHOP_DIALOG) dsp.shop.nation(player, stock, dsp.nation.BASTOK) end
gpl-3.0
starlightknight/darkstar
scripts/zones/Southern_San_dOria/npcs/Phamelise.lua
11
1471
----------------------------------- -- Area: Southern San d'Oria -- NPC: Phamelise -- Zulkheim Regional Merchant ----------------------------------- local ID = require("scripts/zones/Southern_San_dOria/IDs") require("scripts/globals/events/harvest_festivals") require("scripts/globals/conquest") require("scripts/globals/npc_util") require("scripts/globals/quests") require("scripts/globals/shop") ----------------------------------- function onTrade(player,npc,trade) if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then player:messageSpecial(ID.text.FLYER_REFUSED) else onHalloweenTrade(player, trade, npc) end end function onTrigger(player,npc) if GetRegionOwner(dsp.region.ZULKHEIM) ~= dsp.nation.SANDORIA then player:showText(npc, ID.text.PHAMELISE_CLOSED_DIALOG) else local stock = { 4372, 44, -- Giant Sheep Meat 622, 44, -- Dried Marjoram 610, 55, -- San d'Orian Flour 611, 36, -- Rye Flour 1840, 1840, -- Semolina 4366, 22, -- La Theine Cabbage 4378, 55, -- Selbina Milk } player:showText(npc, ID.text.PHAMELISE_OPEN_DIALOG) dsp.shop.general(player, stock, SANDORIA) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
gedads/Neodynamis
scripts/zones/Sealions_Den/bcnms/warriors_path.lua
3
2390
----------------------------------- -- Area: Sealion's Den -- Name: warriors_path -- bcnmID : 993 ----------------------------------- package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Sealions_Den/TextIDs"); ----------------------------------- --Tarutaru --Tenzen group 860 3875 --Makki-Chebukki (RNG) , 16908311 16908315 16908319 group 853 2492 --Kukki-Chebukki (BLM) 16908312 16908316 16908320 group 852 2293 --Cherukiki (WHM). 16908313 16908317 16908321 group 851 710 --instance 1 !pos -780 -103 -90 --instance 2 !pos -140 -23 -450 --instance 3 !pos 500 56 -810 -- 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) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:addExp(1000); if (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); player:setVar("PromathiaStatus",0); player:completeMission(COP,THE_WARRIOR_S_PATH); player:addMission(COP,GARDEN_OF_ANTIQUITY); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:setPos(-25,-1 ,-620 ,208 ,33);-- al'taieu player:addTitle(THE_CHEBUKKIS_WORST_NIGHTMARE); end end;
gpl-3.0
gedads/Neodynamis
scripts/globals/mobskills/necropurge.lua
43
1080
--------------------------------------------- -- Necropurge -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1839) then return 0; else return 1; end end if(mob:getFamily() == 91) then local mobSkin = mob:getModelId(); if (mobSkin == 1840) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 10; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 1, 0, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Castle_Oztroja_[S]/mobs/Suu_Xicu_the_Cantabile.lua
9
2324
----------------------------------- -- Area: Castle Oztroja [S] -- NM: Suu Xicu the Cantabile -- TODO: -- Summoning of pets should be tied to Soul Voice usage. -- Gains a hidden regen from Army's Paeon V. Even if it is dispelled, it will gain several HP%. ----------------------------------- mixins = {require("scripts/mixins/job_special")} ----------------------------------- function onMobRoam(mob, target) local mobId = mob:getID() local hpp = mob:getHPP() if hpp > 50 and mob:getLocalVar("petsOne") == 1 then mob:setLocalVar("petsOne", 0) for i = mobId + 5, mobId + 6 do local pet = GetMobByID(i) if pet:isSpawned() then DespawnMob(i) end end end if hpp > 25 and mob:getLocalVar("petsTwo") == 1 then mob:setLocalVar("petsTwo", 0) for i = mobId + 7, mobId + 8 do local pet = GetMobByID(i) if pet:isSpawned() then DespawnMob(i) end end end end function onMobFight(mob, target) local mobId = mob:getID() local hpp = mob:getHPP() local x = mob:getXPos() local y = mob:getYPos() local z = mob:getZPos() local r = mob:getRotPos() if hpp < 50 and mob:getLocalVar("petsOne") == 0 then mob:setLocalVar("petsOne", 1) for i = mobId + 5, mobId + 6 do local pet = GetMobByID(i) if not pet:isSpawned() then pet:setSpawn(x + math.random(-2,2), y, z + math.random(-2,2), r) pet:spawn() end end end if hpp < 25 and mob:getLocalVar("petsTwo") == 0 then mob:setLocalVar("petsTwo", 1) for i = mobId + 7, mobId + 8 do local pet = GetMobByID(i) if not pet:isSpawned() then pet:setSpawn(x + math.random(-2,2), y, z + math.random(-2,2), r) pet:spawn() end end end end function onMobDeath(mob, player, isKiller) end function onMobDespawn(mob) local mobId = mob:getID() for i = mobId + 5, mobId + 8 do local pet = GetMobByID(i) if pet:isSpawned() then DespawnMob(i) end end UpdateNMSpawnPoint(mob:getID()) mob:setRespawnTime(math.random(14400, 18000)) -- 4 to 5 hours end
gpl-3.0
focusworld/ghost-bot
bot/bot.lua
10
7114
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '0.14.6' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then print('\27[36mNot valid: Telegram message\27[39m') return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then if plugins[disabled_plugin].hidden then print('Plugin '..disabled_plugin..' is disabled on this chat') else local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) end return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "banhammer", "echo", "get", "google", "groupmanager", "help", "id", "images", "img_google", "location", "media", "plugins", "channels", "set", "stats", "time", "version", "weather", "youtube", "media_handler", "moderation"}, sudo_users = { V_for_Vendetta , 140871556 }, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
gedads/Neodynamis
scripts/globals/items/cutlet_sandwich.lua
12
1739
----------------------------------------- -- ID: 6396 -- Item: cutlet_sandwich -- Food Effect: 30Min, All Races ----------------------------------------- -- HP +40 -- STR +7 -- INT -7 -- Fire resistance +20 -- Attack +20% (cap 120) -- Ranged Attack +20% (cap 120) ----------------------------------------- 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,6396); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 40); target:addMod(MOD_STR, 7); target:addMod(MOD_INT, -7); target:addMod(MOD_FIRERES, 20); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 120); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 120); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 40); target:delMod(MOD_STR, 7); target:delMod(MOD_INT, -7); target:delMod(MOD_FIRERES, 20); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 120); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 120); end;
gpl-3.0
RememberTheAir/GroupButler
lua/groupbutler/chatmember.lua
1
2752
local log = require("groupbutler.logging") local User = require("groupbutler.user") local StorageUtil = require("groupbutler.storage.util") local ChatMember = {} local function p(self) return getmetatable(self).__private end function ChatMember:new(obj, private) assert(obj.chat, "ChatMember: Missing obj.chat") assert(obj.user, "ChatMember: Missing obj.user") assert(private.db, "ChatMember: Missing private.db") assert(private.api, "ChatMember: Missing private.api") setmetatable(obj, { __index = function(s, index) if self[index] then return self[index] end return s:getProperty(index) end, __private = private, }) return obj end function ChatMember:getProperty(index) if not StorageUtil.isChatMemberProperty[index] then log.warn("Tried to get invalid chatmember property {property}", {property=index}) return nil end local property = rawget(self, index) if property == nil then property = p(self).db:getChatMemberProperty(self, index) if property == nil then local ok = p(self).api:getChatMember(self.chat.id, self.user.id) if not ok then log.warn("ChatMember: Failed to get {property} for {chat_id}, {user_id}", { property = index, chat_id = self.chat.id, user_id = self.user.id, }) return nil end for k,v in pairs(ok) do self[k] = v if k == "user" then User:new(self.user, p(self)) end end self:cache() property = rawget(self, index) end self[index] = property end return property end function ChatMember:cache() p(self).db:cacheChatMember(self) end function ChatMember:isAdmin() if self.chat.type == "private" then -- This should never happen but... return false end return self.status == "creator" or self.status == "administrator" end function ChatMember:can(permission) if self.chat.type == "private" then -- This should never happen but... return false end if self.status == "creator" or (self.status == "administrator" and self[permission]) then return true end return false end function ChatMember:ban(until_date) local ok, err = p(self).api:kickChatMember(self.chat.id, self.user.id, until_date) if not ok then return nil, p(self).api_err:trans(err) end return ok end function ChatMember:kick() local ok, err = p(self).api:kickChatMember(self.chat.id, self.user.id) if not ok then return nil, p(self).api_err:trans(err) end p(self).api:unbanChatMember(self.chat.id, self.user.id) return ok end function ChatMember:mute(until_date) local ok, err = p(self).api:restrictChatMember({ chat_id = self.chat.id, user_id = self.user.id, until_date = until_date, can_send_messages = false, }) if not ok then return nil, p(self).api_err:trans(err) end return ok end return ChatMember
gpl-2.0
gedads/Neodynamis
scripts/globals/abilities/pets/bone_crusher.lua
4
1729
--------------------------------------------------- -- Bone Crusher --------------------------------------------------- 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 params = { numHits = 3, atkmulti = 1, weaponType = SKILL_CLB, ftp100 = 1.5, ftp200 = 1.5, ftp300 = 1.5, acc100 = 0.0, acc200 = 0.0, acc300 = 0.0, str_wsc = 0.0, dex_wsc = 0.0, vit_wsc = 0.6, agi_wsc = 0.0, int_wsc = 0.0, mnd_wsc = 0.0, chr_wsc = 0.0 } if USE_ADOULIN_WEAPON_SKILL_CHANGES then params.ftp100 = 2.66 params.ftp200 = 2.66 params.ftp300 = 2.66 if target:isUndead() then params.ftp100 = 3.66 params.ftp200 = 3.66 params.ftp300 = 3.66 end else if target:isUndead() then params.ftp100 = 2.0 params.ftp200 = 2.0 params.ftp300 = 2.0 end end local damage = doAutoPhysicalWeaponskill(automaton, target, 0, skill:getTP(), true, action, false, params, skill, action) if damage > 0 then local chance = 0.033 * skill:getTP() if not target:hasStatusEffect(EFFECT_STUN) and chance >= math.random()*100 then target:addStatusEffect(EFFECT_STUN, 1, 0, 4) end end return damage end
gpl-3.0
starlightknight/darkstar
scripts/zones/Nashmau/npcs/Yoyoroon.lua
8
1554
----------------------------------- -- Area: Nashmau -- NPC: Yoyoroon -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Nashmau/IDs") require("scripts/globals/shop") function onTrade(player,npc,trade) end function onTrigger(player,npc) local stock = { 2239, 4940, -- Tension Spring 2243, 4940, -- Loudspeaker 2246, 4940, -- Accelerator 2251, 4940, -- Armor Plate 2254, 4940, -- Stabilizer 2258, 4940, -- Mana Jammer 2262, 4940, -- Auto-Repair Kit 2266, 4940, -- Mana Tank 2240, 9925, -- Inhibitor 9229, 9925, -- Speedloader 2242, 9925, -- Mana Booster 2247, 9925, -- Scope 2250, 9925, -- Shock Absorber 2255, 9925, -- Volt Gun 2260, 9925, -- Stealth Screen 2264, 9925, -- Damage Gauge 2268, 9925, -- Mana Conserver 2238, 19890, -- Strobe 2409, 19890, -- Flame Holder 2410, 19890, -- Ice Maker 2248, 19890, -- Pattern Reader 2411, 19890, -- Replicator 2252, 19890, -- Analyzer 2256, 19890, -- Heat Seeker 2259, 19890, -- Heatsink 2263, 19890, -- Flashbulb 2267, 19890, -- Mana Converter } player:showText(npc, ID.text.YOYOROON_SHOP_DIALOG) dsp.shop.general(player, stock) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
BillardDRP/nathaniel-rp-addons
addons/billard_ents/lua/entities/billard_weed_harvested/init.lua
2
1139
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/props/cs_office/trash_can_p5.mdl") //Once again, custom models are overrated self:SetColor(Color(0, 255, 0, 255)) self:SetMaterial("models/props_c17/furniturefabric_002a") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() if phys:IsValid() then phys:Wake() end self:SetUserHealth(0) self:SetIsUsed(false) end function ENT:Think() if self:GetIsUsed() then while self:GetUserPerson():Health() > self:GetUserHealth() do self:GetUserPerson():SetHealth(self:GetUserPerson():Health() - 20) self:NextThink(CurTime() + 1) end end end function ENT:Use(activator, caller) if IsValid(caller) and caller:IsPlayer() then caller:ChatPrint("I'm so high right now, nothing could hurt me!") self:SetUserHealth(caller:Health()) self:SetUserPerson(caller) caller:SetHealth(caller:Health() * 8) self:SetIsUsed(true) DoGenericUseEffect(caller) self:Remove() end end
gpl-3.0
starlightknight/darkstar
scripts/zones/Bibiki_Bay/npcs/Toh_Zonikki.lua
9
4702
----------------------------------- -- Area: Bibiki Bay -- NPC: Toh Zonikki -- Type: Clamming NPC -- !pos -371 -1 -421 4 ----------------------------------- local ID = require("scripts/zones/Bibiki_Bay/IDs"); require("scripts/globals/keyitems"); ----------------------------------- -- Local Variables ----------------------------------- local clammingItems = { 1311, -- Oxblood 885, -- Turtle Shell 1193, -- HQ Crab Shell 1446, -- Lacquer Tree Log 4318, -- Bibiki Urchin 1586, -- Titanictus Shell 5124, -- Tropical Clam 690, -- Elm Log 887, -- Coral Fragment 703, -- Petrified Log 691, -- Maple Log 4468, -- Pamamas 3270, -- HQ Pugil Scales 888, -- Seashell 4328, -- Hobgoblin Bread 485, -- Broken Willow Rod 510, -- Goblin Armor 5187, -- Elshimo Coconut 507, -- Goblin Mail 881, -- Crab Shell 4325, -- Hobgoblin Pie 936, -- Rock Salt 4361, -- Nebimonite 864, -- Fish Scales 4484, -- Shall Shell 624, -- Pamtam Kelp 1654, -- Igneous Rock 17296, -- Pebble 5123, -- Jacknife 5122 -- Bibiki Slug }; ----------------------------------- -- Local Functions ----------------------------------- local function giveClammedItems(player) for item = 1, #clammingItems do local clammedItemQty = player:getCharVar("ClammedItem_" .. clammingItems[item]); if (clammedItemQty > 0) then if (player:addItem(clammingItems[item],clammedItemQty)) then player:messageSpecial(ID.text.YOU_OBTAIN, clammingItems[item], clammedItemQty); player:setCharVar("ClammedItem_" .. clammingItems[item], 0); else player:messageSpecial(ID.text.WHOA_HOLD_ON_NOW); break; end end end end; local function owePlayerClammedItems(player) for item = 1, #clammingItems do if (player:getCharVar("ClammedItem_" .. clammingItems[item]) > 0) then return true; end end return false; end; function onTrade(player,npc,trade) end; function onTrigger(player,npc) if ( player:hasKeyItem(dsp.ki.CLAMMING_KIT)) then -- Player has clamming kit if (player:getCharVar("ClammingKitBroken") == 1) then -- Broken bucket player:startEvent(30, 0, 0, 0, 0, 0, 0, 0, 0); else --Bucket not broken player:startEvent(29, 0, 0, 0, 0, 0, 0, 0, 0); end else -- Player does not have clamming kit if (owePlayerClammedItems(player)) then player:messageSpecial(ID.text.YOU_GIT_YER_BAG_READY); giveClammedItems(player); else player:startEvent(28, 500, 0, 0, 0, 0, 0, 0, 0); end end end; function onEventUpdate(player,csid,option) if (csid == 28) then local enoughMoney = 2; -- Not enough money if (player:getGil() >= 500) then enoughMoney = 1; --Player has enough Money end player:updateEvent(dsp.ki.CLAMMING_KIT, enoughMoney, 0, 0, 0, 500, 0, 0); elseif (csid == 29) then local clammingKitSize = player:getCharVar("ClammingKitSize"); player:updateEvent( player:getCharVar("ClammingKitWeight"), clammingKitSize, clammingKitSize, clammingKitSize + 50, 0, 0, 0, 0); end end; function onEventFinish(player,csid,option) if (csid == 28) then if (option == 1) then -- Give 50pz clamming kit player:setCharVar("ClammingKitSize", 50); player:addKeyItem(dsp.ki.CLAMMING_KIT); player:delGil(500); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.CLAMMING_KIT); end elseif (csid == 29) then if (option == 2) then -- Give player clammed items player:setCharVar("ClammingKitSize", 0); player:setCharVar("ClammingKitWeight", 0); player:delKeyItem(dsp.ki.CLAMMING_KIT); player:messageSpecial(ID.text.YOU_RETURN_THE,dsp.ki.CLAMMING_KIT); giveClammedItems(player); elseif (option == 3) then -- Get bigger kit local clammingKitSize = player:getCharVar("ClammingKitSize") + 50; player:setCharVar("ClammingKitSize", clammingKitSize); player:messageSpecial(ID.text.YOUR_CLAMMING_CAPACITY, 0, 0, clammingKitSize); end elseif ( csid == 30) then -- Broken bucket player:setCharVar("ClammingKitSize", 0); player:setCharVar("ClammingKitBroken", 0); player:setCharVar("ClammingKitWeight", 0); player:delKeyItem(dsp.ki.CLAMMING_KIT); player:messageSpecial(ID.text.YOU_RETURN_THE,dsp.ki.CLAMMING_KIT); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Upper_Jeuno/npcs/Sibila-Mobla.lua
17
1382
----------------------------------- -- Area: Upper Jeuno -- NPC: Sibila-Mobla -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Upper_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,5) == false) then player:startEvent(10083); else player:startEvent(0x0062); 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 == 10083) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",5,true); end end;
gpl-3.0
ironjade/DevStack
LanCom/DesignPattern/LUA/Simulation.lua
1
2891
#!/usr/local/bin/lua --[[ Copyright (c) 2004 by Bruno R. Preiss, P.Eng. $Author: brpreiss $ $Date: 2004/12/05 14:47:20 $ $RCSfile: Simulation.lua,v $ $Revision: 1.2 $ $Id: Simulation.lua,v 1.2 2004/12/05 14:47:20 brpreiss Exp $ --]] require "LeftistHeap" require "Association" require "ExponentialRV" --{ -- A discrete-event simulation of an M/M/1 queue. Simulation = Class.new("Simulation") -- Constructor function Simulation.methods:initialize() Simulation.super(self) self.eventList = LeftistHeap.new() self.serverBusy = false self.numberInQueue = 0 self.serviceTime = ExponentialRV.new(100.0) self.interArrivalTime = ExponentialRV.new(100.0) end -- Runs the simulation up to the specified time. -- @param timeLimit The time limit. function Simulation.methods:run(timeLimit) self.eventList:enqueue( Simulation.Event.new(Simulation.Event.ARRIVAL, 0)) while not self.eventList:is_empty() do local evt = self.eventList:dequeueMin() t = evt:get_time() if t > timeLimit then self.eventList:purge() break end --< print(evt) --> if evt:get_category() == Simulation.Event.ARRIVAL then if not self.serverBusy then self.serverBusy = true self.eventList:enqueue(Simulation.Event.new( Simulation.Event.DEPARTURE, t + self.serviceTime:next())) else self.numberInQueue = self.numberInQueue + 1 end self.eventList:enqueue( Simulation.Event.new(Simulation.Event.ARRIVAL, t + self.interArrivalTime:next())) elseif evt:get_category() == Simulation.Event.DEPARTURE then if self.numberInQueue == 0 then self.serverBusy = false else self.numberInQueue = self.numberInQueue - 1 self.eventList:enqueue( Simulation.Event.new( Simulation.Event.DEPARTURE, t + self.serviceTime:next())) end end end end --}>a --{ -- Represents an event in the M/M/1 queue simulation. Simulation.Event = Class.new("Simulation.Event", Association) -- Arrival of a customer. Simulation.Event.ARRIVAL = 1 -- Departure of a customer. Simulation.Event.DEPARTURE = 2 -- Constructs an event with the given type and time. -- @param category The type of the event. -- @param time The time of the event. function Simulation.Event.methods:initialize(category, time) Simulation.Event.super(self, time, category) end function Simulation.Event.methods:get_time() return unbox(self:get_key()) end function Simulation.Event.methods:get_category() return unbox(self:get_value()) end --}>b -- Returns a string representation of this event. function Simulation.Event.methods:toString() if self:get_category() == Simulation.Event.ARRIVAL then return "Event {" .. tostring(self:get_time()) .. ", arrival}" elseif self:get_category() == Simulation.Event.DEPARTURE then return "Event {" .. tostring(self:get_time()) .. ", departure}" end end
apache-2.0
pospanet/nodemcu-httpserver
httpserver-request.lua
1
2020
-- httpserver-request -- Part of nodemcu-httpserver, parses incoming client requests. -- Author: Marcos Kirsch local function validateMethod(method) local httpMethods = {GET=true, HEAD=true, POST=true, PUT=true, DELETE=true, TRACE=true, OPTIONS=true, CONNECT=true, PATCH=true} -- default for non-existent attributes returns nil, which evaluates to false return httpMethods[method] end local function uriToFilename(uri) return "http/" .. string.sub(uri, 2, -1) end local function parseArgs(args) local r = {}; i=1 if args == nil or args == "" then return r end for arg in string.gmatch(args, "([^&]+)") do local name, value = string.match(arg, "(.*)=(.*)") if name ~= nil then r[name] = value end i = i + 1 end return r end local function parseUri(uri) local r = {} local filename local ext local fullExt = {} if uri == nil then return r end if uri == "/" then uri = "/index.html" end questionMarkPos, b, c, d, e, f = uri:find("?") if questionMarkPos == nil then r.file = uri:sub(1, questionMarkPos) r.args = {} else r.file = uri:sub(1, questionMarkPos - 1) r.args = parseArgs(uri:sub(questionMarkPos+1, #uri)) end filename = r.file while filename:match("%.") do filename,ext = filename:match("(.+)%.(.+)") table.insert(fullExt,1,ext) end r.ext = table.concat(fullExt,".") r.isScript = r.ext == "lua" or r.ext == "lc" r.file = uriToFilename(r.file) return r end -- Parses the client's request. Returns a dictionary containing pretty much everything -- the server needs to know about the uri. return function (request) local e = request:find("\r\n", 1, true) if not e then return nil end local line = request:sub(1, e - 1) local r = {} _, i, r.method, r.request = line:find("^([A-Z]+) (.-) HTTP/[1-9]+.[0-9]+$") r.methodIsValid = validateMethod(r.method) r.uri = parseUri(r.request) return r end
gpl-2.0
starlightknight/darkstar
scripts/globals/items/istiridye.lua
11
1149
----------------------------------------- -- ID: 5456 -- Item: Istiridye -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defense +17.07% ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,5456) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, -5) target:addMod(dsp.mod.VIT, 4) target:addMod(dsp.mod.DEFP, 17.07) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, -5) target:delMod(dsp.mod.VIT, 4) target:delMod(dsp.mod.DEFP, 17.07) end
gpl-3.0
gedads/Neodynamis
scripts/zones/Southern_San_dOria/npcs/Faulpie.lua
3
2889
----------------------------------- -- Area: Southern San d'Oria -- NPC: Faulpie -- Type: Leathercraft Guild Master -- !pos -178.882 -2 9.891 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/crafting"); require("scripts/globals/missions"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_LEATHERCRAFT); if (newRank ~= 0) then player:setSkillRank(SKILL_LEATHERCRAFT,newRank); player:startEvent(0x0289,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_LEATHERCRAFT); local testItem = getTestItem(player,npc,SKILL_LEATHERCRAFT); local guildMember = isGuildMember(player,7); if (guildMember == 1) then guildMember = 150995375; end if (canGetNewRank(player,craftSkill,SKILL_LEATHERCRAFT) == 1) then getNewRank = 100; end if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD and guildMember == 150995375 and getNewRank ~= 100) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if (asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end -- The Parameters are Item IDs for the Recipe player:startEvent(0x03b0, item, 2773, 917, 917, 2776, 4103); else player:startEvent(0x0288,testItem,getNewRank,30,guildMember,44,0,0,0); end end; -- 0x0288 0x0289 0x02f8 0x02f9 0x02fa 0x02fb 0x02fc 0x02fd 0x0302 0x0303 0x0304 0x0305 0x0306 0x0307 0x03b0 0x0392 ----------------------------------- -- 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 == 0x0288 and option == 1) then local crystal = 4103; -- dark crystal if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player, guild.leathercraft); end end end;
gpl-3.0
libmoon/libmoon
lua/driver/igb.lua
3
3021
--- igb-specific code local dev = {} local dpdkc = require "dpdkc" local ffi = require "ffi" local log = require "log" -- the igb driver actually reports stats almost as expected dev.txStatsIgnoreCrc = true dev.rxStatsIgnoreCrc = true -- timestamping local TSAUXC = 0x0000B640 local TIMINCA = 0x0000B608 local TSYNCRXCTL = 0x0000B620 local TSYNCTXCTL = 0x0000B614 local TXSTMPL = 0x0000B618 local TXSTMPH = 0x0000B61C local RXSTMPL = 0x0000B624 local RXSTMPH = 0x0000B628 local RXSATRH = 0x0000B630 local ETQF_3 = 0x00005CB0 + 4 * 3 local SYSTIMEL = 0x0000B600 local SYSTIMEH = 0x0000B604 local TIMEADJL = 0x0000B60C local TIMEADJH = 0x0000B610 local SRRCTL_82580 = {} for i = 0, 7 do SRRCTL_82580[i] = 0x0000C00C + 0x40 * i end local TSYNCRXCTL_TYPE_OFFS = 1 local TSYNCRXCTL_TYPE_MASK = bit.lshift(7, TSYNCRXCTL_TYPE_OFFS) local TSYNCRXCTL_RXTT = 1 local ETQF_QUEUE_ENABLE = bit.lshift(1, 31) local SRRCTL_TIMESTAMP = bit.lshift(1, 30) -- device initializing takes unreasonably long sometimes dev.linkWaitTime = 18 dev.timeRegisters = {SYSTIMEL, SYSTIMEH, TIMEADJL, TIMEADJH} dev.crcPatch = true ffi.cdef[[ int libmoon_igb_reset_timecounters(uint32_t port_id); ]] function dev:resetTimeCounters() ffi.C.libmoon_igb_reset_timecounters(self.id) end -- just rte_eth_timesync_enable doesn't do the trick :( function dev:enableRxTimestamps(queue, udpPort) udpPort = udpPort or 319 if udpPort ~= 319 then self:unsupported("Timestamping on UDP ports other than 319") end dpdkc.rte_eth_timesync_enable(self.id) -- enable timestamping UDP packets as well local val = dpdkc.read_reg32(self.id, TSYNCRXCTL) val = bit.band(val, bit.bnot(TSYNCRXCTL_TYPE_MASK)) val = bit.bor(val, bit.lshift(2, TSYNCRXCTL_TYPE_OFFS)) dpdkc.write_reg32(self.id, TSYNCRXCTL, val) end dev.enableTxTimestamps = dev.enableRxTimestamps function dev:hasRxTimestamp() if bit.band(dpdkc.read_reg32(self.id, TSYNCRXCTL), TSYNCRXCTL_RXTT) == 0 then return nil end return bswap16(bit.rshift(dpdkc.read_reg32(self.id, RXSATRH), 16)) end function dev:filterL2Timestamps(queue) -- DPDK's init function configures ETQF3 to enable PTP L2 timestamping, so use this one local val = dpdkc.read_reg32(self.id, ETQF_3) val = bit.bor(val, ETQF_QUEUE_ENABLE, bit.lshift(queue.qid, 16)) dpdkc.write_reg32(self.id, ETQF_3, val) end function dev:filterUdpTimestamps() -- have a look at the FHFT (0x9000) registers if you want to implement this log:warn("Filtering UDP timestamps on IGB is supported by the HW but NYI") end function dev:enableRxTimestampsAllPackets(queue) dpdkc.rte_eth_timesync_enable(self.id) local val = dpdkc.read_reg32(self.id, TSYNCRXCTL) val = bit.band(val, bit.bnot(TSYNCRXCTL_TYPE_MASK)) val = bit.bor(val, bit.lshift(bit.lshift(1, 2), TSYNCRXCTL_TYPE_OFFS)) dpdkc.write_reg32(self.id, TSYNCRXCTL, val) dpdkc.write_reg32(self.id, SRRCTL_82580[queue.qid], bit.bor(dpdkc.read_reg32(self.id, SRRCTL_82580[queue.qid]), SRRCTL_TIMESTAMP)) end return dev
mit
Achain-Dev/Achain
src/Chain/libraries/glua/tests_typed/full_demo.lua
1
3862
type Person = { id: string default '123', name: string default "hi", age: int default 24, age2: number, age3 ?: int default 1, fn: (number, number) => number default function (a: number, b: number) return a + b; end } let p11: Person = Person() local as1, as2 as1, as2, as2, as1 = 1, 'abc', 'd' as3[p11] type Array2<T> = { __len: () => int, __index: (int) => T } let as3 = Array2<Person> {a=1, b="hi"} pprint('as3', as3) let as4: Array<Person> = Array<Person> { 1, 2, 3, 4 } let as5 = Person {name="glua"} pprint('as5', as5) type artT = Array2<string> let ar1: artT = artT() let ar2: string = ar1[1] let ar3 = p11[1] let ar4: Array2<string> = Array2<string>() type Contract = { id: string, name: string, storage: Person } type Contract2<S> = { id: string, name: string, storage: S, sayHi: (int) => S -- ,__call: (S) => S } type G1<T1, T2, T3> = { a: T1, b: T2, c: T3 -- message: string default '123' } type G2<T> = G1<int, T, Contract2<Person> > type G3 = G2<string> -- type G4 = string type Cat = "whiteCat" | "blackCat" | nil type Dog = "husky" | "corgi" type Pets = Cat | Dog -- The same as: type Pets = "whiteCat" | "blackCat" | "husky" | "corgi" | nil type Falsy = "" | 0 | false | nil let M: Contract2<Person> = {} local fname = 'abc' let ot1 ?: string = "123" local function testlocalfunc1(b, c, d) return true end offline function M:query(a) return tostring(1234) end function add(a: number, b: number) return a + b end function sum(a: number, b: number, ...) var s = a + b for i in ipairs(...) do s = s + tonumber(i) end return s end function test_dots(...) print('test_dots\n') local a = {} local b = 0 --[[ for k, v in ipairs(...) do a[#a+1] = v end local b if a and #a > 0 then b = a[1] else b = '0' end print('b ', b, '\n') ]]-- return tonumber(b) end let td1: number = test_dots() let td2: number = test_dots(1) let td3: number = test_dots(1, '2') function numberf1(f: (number, number) => number, a: number, b: number) return f(a, b) end function M:init() -- ÕâÀᄇ̬ÀàÐÍ·ÖÎöʱ£¬selfÈç¹ûûÓÐÌØ±ðÉùÃ÷ÀàÐÍ£¬¾ÍÓÃMµÄÀàÐÍ pprint('test3 contract demo init') -- local dd = import_contract 'not_found' -- local dd2 = import_contract('not_found') local storage = {} storage['name'] = 123 var id = self.id let tf1 = storage.id(123) local tf2: G3 = {} local tf3 = tf2.b local tf4: Array<int> = { 1, 2, 3 } local tf5: int = tf4[2] local tf6: (int, string, bool) => string local tf7 = tf6(1, '1', true) local tf8: (number, number) => number = add local tf9 = self.sayHi -- TODO local age = self.storage.age tonumber '123' local abc = "\x23\xa3\u{1234}\5\6\zabc" print(abc) local a2 = [[abcdef]] local a3 = #storage local r1: Contract2<Person> = {} local r2 = r1.storage function f1(a) if true then return 'abc' end return tonumber(a) end let f1r1 = f1(1) let f1r2 = tostring(f1r1) .. 'f1' let t2 : Person = {name="hello", age=20} t2.fn = function(a: number, b: number) return a + b end local t1: int = 1 pprint(t2.name) pprint(t2.not_found) pprint(t2['not_found2']) let t3 = add(t1, t2) local t4 = add(t1, t1, t1, t1) t3 = 100 t2.age = t2['age'] + 1 t2 = totable({}) -- tableºÍrecord¿ÉÒÔ·Ö±ð×÷Ϊ±äÁ¿ÀàÐͺÍֵʹÓ㬵«ÊÇrecordÖµ²»Äܸ³Öµ¸øÁíÒ»ÖÖrecordÀàÐ͵Ävariable t1 = 'abc' transfer_from_contract_to_address(123) local a4 = #storage.name + 1 local d = 123.45 + 2 + #storage.name + tonumber('123') + "aaa" + 1 local e = fname pprint 'hi' let t5: int | string | Person | bool | table = '123' let t6: int | string = '123' let t7: Contract2<Person> = {} let t8: Person = {} -- let t9: Person = t7(t8) let t10: Function = add let t11 = t10(123, 456, 789) end function M:start() local a = self.id end offline function M:query(a: number, b: number) return a + b end return M
mit
gedads/Neodynamis
scripts/zones/Spire_of_Dem/npcs/_0j3.lua
66
1350
----------------------------------- -- Area: Spire_of_Dem -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Dem/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Metalworks/npcs/Naji.lua
3
5236
----------------------------------- -- Area: Metalworks -- NPC: Naji -- Involved in Quests: The doorman (finish), Riding on the Clouds -- Involved in Mission: Bastok 6-2 -- !pos 64 -14 -4 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 6) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman, WAR AF1 player:startEvent(0x02ee); elseif (player:getCurrentMission(BASTOK) ~= 255) then local currentMission = player:getCurrentMission(BASTOK); if (currentMission == THE_ZERUHN_REPORT and player:hasKeyItem(ZERUHN_REPORT)) then if (player:seenKeyItem(ZERUHN_REPORT)) then player:startEvent(0x02C6,0); else player:startEvent(0x02C6,1); end elseif (currentMission == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then player:startEvent(0x02c7); elseif (currentMission == THE_EMISSARY and player:hasKeyItem(KINDRED_REPORT)) then player:startEvent(0x02ca); elseif (currentMission == THE_EMISSARY) then if (player:hasKeyItem(LETTER_TO_THE_CONSULS_BASTOK) == false and player:getVar("MissionStatus") == 0) then player:startEvent(0x02c9); else player:showText(npc,GOOD_LUCK); end elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK) and player:getVar("MissionStatus") == 0) then player:startEvent(0x02d0); elseif (currentMission == DARKNESS_RISING and player:getVar("MissionStatus") == 1) then player:startEvent(0x02d1); elseif (player:hasKeyItem(BURNT_SEAL)) then player:startEvent(0x02d2); elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 0) then player:startEvent(0x02f9); elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 3) then player:startEvent(0x02fa); else player:startEvent(0x02bc); end elseif (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman player:startEvent(0x02ee); else player:startEvent(0x02bc); end end; -- 0x02c6 0x02c7 0x02bc 0x02c9 0x02ca 0x02cb 0x02cd 0x02d0 0x02d1 0x02ee 0x03f0 0x03f1 0x02f9 -- 0x02fa 0x030e 0x0325 0x034d 0x036d 0x03aa 0x03ab 0x03ac 0x03ad 0x03ae 0x03cb 0x03c9 0x03ca ----------------------------------- -- 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 == 0x02ee) then if (player:getFreeSlotsCount(0) >= 1) then player:addItem(16678); player:messageSpecial(ITEM_OBTAINED, 16678); -- Razor Axe player:delKeyItem(YASINS_SWORD); player:setVar("theDoormanCS",0); player:addFame(BASTOK,30); player:completeQuest(BASTOK,THE_DOORMAN); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16678); -- Razor Axe end elseif (csid == 0x02C6) then player:delKeyItem(ZERUHN_REPORT); player:completeMission(BASTOK,THE_ZERUHN_REPORT); elseif (csid == 0x02c9) then player:addKeyItem(LETTER_TO_THE_CONSULS_BASTOK); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_BASTOK); player:setVar("MissionStatus",1); elseif (csid == 0x02d0 and option == 0 or csid == 0x02d1) then player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK); player:addKeyItem(NEW_FEIYIN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL); player:setVar("MissionStatus",10); elseif (csid == 0x02d0 and option == 1) then player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK); player:setVar("MissionStatus",1); elseif (csid == 0x02f9) then player:setVar("MissionStatus",1); elseif (csid == 0x02ca or csid == 0x02d2 or csid == 0x02fa) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
noname007/vanilla
vanilla/sys/vanilla.lua
2
2910
-- dep local ansicolors = require 'ansicolors' -- perf local error = error local sgmatch = string.gmatch -- vanilla local va_conf = require 'vanilla.sys.config' local ngx_handle = require 'vanilla.sys.nginx.handle' local ngx_config = require 'vanilla.sys.nginx.config' local helpers = require 'vanilla.v.libs.utils' -- settings local nginx_conf_source = 'config/nginx.conf' local Vanilla = {} function Vanilla.nginx_conf_content() -- read nginx.conf file local nginx_conf_template = helpers.read_file(nginx_conf_source) -- append notice nginx_conf_template = [[ # ===================================================================== # # THIS FILE IS AUTO GENERATED. DO NOT MODIFY. # # IF YOU CAN SEE IT, THERE PROBABLY IS A RUNNING SERVER REFERENCING IT. # # ===================================================================== # ]] .. nginx_conf_template local match = {} local tmp = 1 for v in sgmatch(nginx_conf_template , '{{(.-)}}') do match[tmp] = v tmp = tmp +1 end for _, directive in ipairs(match) do if ngx_config[directive] ~= nil then nginx_conf_template = string.gsub(nginx_conf_template, '{{' .. directive .. '}}', ngx_config[directive]) else nginx_conf_template = string.gsub(nginx_conf_template, '{{' .. directive .. '}}', '#' .. directive) end end -- pp(nginx_conf_template) -- os.exit() return nginx_conf_template end function base_launcher() return ngx_handle.new( Vanilla.nginx_conf_content(), va_conf.app_dirs.tmp .. "/" .. va_conf.env .. "-nginx.conf" ) end function Vanilla.start(env) if env == nil then env = va_conf.env end -- init base_launcher local ok, base_launcher = pcall(function() return base_launcher() end) if ok == false then print(ansicolors("%{red}ERROR:%{reset} Cannot initialize launcher: " .. base_launcher)) return end result = base_launcher:start(env) if result == 0 then if va_conf.env ~= 'test' then print(ansicolors("Vanilla app in %{cyan}" .. va_conf.env .. "%{reset} was succesfully started on port " .. ngx_config.PORT .. ".")) end else print(ansicolors("%{red}ERROR:%{reset} Could not start Vanilla app on port " .. ngx_config.PORT .. " (is it running already?).")) end end function Vanilla.stop(env) if env == nil then env = va_conf.env end -- init base_launcher local base_launcher = base_launcher() result = base_launcher:stop(env) if va_conf.env ~= 'test' then if result == 0 then print(ansicolors("Vanilla app in %{cyan}" .. va_conf.env .. "%{reset} was succesfully stopped.")) else print(ansicolors("%{red}ERROR:%{reset} Could not stop Vanilla app (are you sure it is running?).")) end end end return Vanilla
mit
gedads/Neodynamis
scripts/zones/Behemoths_Dominion/mobs/King_Behemoth.lua
3
2483
----------------------------------- -- Area: Behemoth's Dominion -- HNM: King Behemoth ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- Todo: move this to SQL after drop slots are a thing if (math.random(1,100) <= 5) then -- Hardcoded "this or this item" drop rate until implemented. SetDropRate(1936,13566,1000); -- Defending Ring SetDropRate(1936,13415,0); else SetDropRate(1936,13566,0); SetDropRate(1936,13415,1000); -- Pixie Earring end if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(17297459):setStatus(STATUS_DISAPPEAR); end end; ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_MAGIC_COOL, 60); end; ----------------------------------- -- onSpellPrecast ----------------------------------- function onSpellPrecast(mob, spell) if (spell:getID() == 218) then spell:setAoE(SPELLAOE_RADIAL); spell:setFlag(SPELLFLAG_HIT_ALL); spell:setRadius(30); spell:setAnimation(280); spell:setMPCost(1); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(BEHEMOTH_DETHRONER); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Set King_Behemoth's Window Open Time if (LandKingSystem_HQ ~= 1) then local wait = 72 * 3600; SetServerVariable("[POP]King_Behemoth", os.time() + wait); -- 3 days if (LandKingSystem_HQ == 0) then -- Is time spawn only DisallowRespawn(mob:getID(), true); end end -- Set Behemoth's spawnpoint and respawn time (21-24 hours) if (LandKingSystem_NQ ~= 1) then SetServerVariable("[PH]King_Behemoth", 0); local Behemoth = mob:getID()-1; DisallowRespawn(Behemoth, false); UpdateNMSpawnPoint(Behemoth); GetMobByID(Behemoth):setRespawnTime(math.random(75600,86400)); end if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(17297459):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Tavnazian_Safehold/npcs/Caiphimonride.lua
17
1310
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Caiphimonride -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CAIPHIMONRIDE_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 0x40b6,8478, --Longsword 0x43B7,8, --Rusty Bolt 0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet) 0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet) showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Jugner_Forest_[S]/Zone.lua
12
1694
----------------------------------- -- -- Zone: Jugner_Forest_[S] (82) -- ----------------------------------- package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Jugner_Forest_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(621.865,-6.665,300.264,149); end if (player:getQuestStatus(CRYSTAL_WAR,CLAWS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("ClawsOfGriffonProg") == 0) then cs = 0x00C8; elseif (player:getVar("roadToDivadomCS") == 1) then cs = 0x0069; end; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00C8) then player:setVar("ClawsOfGriffonProg",1); elseif (csid == 0x0069 ) then player:setVar("roadToDivadomCS", 2); end; end;
gpl-3.0
mishin/Algorithm-Implementations
Hamming_Weight/Lua/Yonaba/numberlua.lua
115
13399
--[[ LUA MODULE bit.numberlua - Bitwise operations implemented in pure Lua as numbers, with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces. SYNOPSIS local bit = require 'bit.numberlua' print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff -- Interface providing strong Lua 5.2 'bit32' compatibility local bit32 = require 'bit.numberlua'.bit32 assert(bit32.band(-1) == 0xffffffff) -- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility local bit = require 'bit.numberlua'.bit assert(bit.tobit(0xffffffff) == -1) DESCRIPTION This library implements bitwise operations entirely in Lua. This module is typically intended if for some reasons you don't want to or cannot install a popular C based bit library like BitOp 'bit' [1] (which comes pre-installed with LuaJIT) or 'bit32' (which comes pre-installed with Lua 5.2) but want a similar interface. This modules represents bit arrays as non-negative Lua numbers. [1] It can represent 32-bit bit arrays when Lua is compiled with lua_Number as double-precision IEEE 754 floating point. The module is nearly the most efficient it can be but may be a few times slower than the C based bit libraries and is orders or magnitude slower than LuaJIT bit operations, which compile to native code. Therefore, this library is inferior in performane to the other modules. The `xor` function in this module is based partly on Roberto Ierusalimschy's post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html . The included BIT.bit32 and BIT.bit sublibraries aims to provide 100% compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library. This compatbility is at the cost of some efficiency since inputted numbers are normalized and more general forms (e.g. multi-argument bitwise operators) are supported. STATUS WARNING: Not all corner cases have been tested and documented. Some attempt was made to make these similar to the Lua 5.2 [2] and LuaJit BitOp [3] libraries, but this is not fully tested and there are currently some differences. Addressing these differences may be improved in the future but it is not yet fully determined how to resolve these differences. The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua) http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp test suite (bittest.lua). However, these have not been tested on platforms with Lua compiled with 32-bit integer numbers. API BIT.tobit(x) --> z Similar to function in BitOp. BIT.tohex(x, n) Similar to function in BitOp. BIT.band(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bxor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bnot(x) --> z Similar to function in Lua 5.2 and BitOp. BIT.lshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.rshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.extract(x, field [, width]) --> z Similar to function in Lua 5.2. BIT.replace(x, v, field, width) --> z Similar to function in Lua 5.2. BIT.bswap(x) --> z Similar to function in Lua 5.2. BIT.rrotate(x, disp) --> z BIT.ror(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.lrotate(x, disp) --> z BIT.rol(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.arshift Similar to function in Lua 5.2 and BitOp. BIT.btest Similar to function in Lua 5.2 with requires two arguments. BIT.bit32 This table contains functions that aim to provide 100% compatibility with the Lua 5.2 "bit32" library. bit32.arshift (x, disp) --> z bit32.band (...) --> z bit32.bnot (x) --> z bit32.bor (...) --> z bit32.btest (...) --> true | false bit32.bxor (...) --> z bit32.extract (x, field [, width]) --> z bit32.replace (x, v, field [, width]) --> z bit32.lrotate (x, disp) --> z bit32.lshift (x, disp) --> z bit32.rrotate (x, disp) --> z bit32.rshift (x, disp) --> z BIT.bit This table contains functions that aim to provide 100% compatibility with the LuaBitOp "bit" library (from LuaJIT). bit.tobit(x) --> y bit.tohex(x [,n]) --> y bit.bnot(x) --> y bit.bor(x1 [,x2...]) --> y bit.band(x1 [,x2...]) --> y bit.bxor(x1 [,x2...]) --> y bit.lshift(x, n) --> y bit.rshift(x, n) --> y bit.arshift(x, n) --> y bit.rol(x, n) --> y bit.ror(x, n) --> y bit.bswap(x) --> y DEPENDENCIES None (other than Lua 5.1 or 5.2). DOWNLOAD/INSTALLATION If using LuaRocks: luarocks install lua-bit-numberlua Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>. Alternately, if using git: git clone git://github.com/davidm/lua-bit-numberlua.git cd lua-bit-numberlua Optionally unpack: ./util.mk or unpack and install in LuaRocks: ./util.mk install REFERENCES [1] http://lua-users.org/wiki/FloatingPoint [2] http://www.lua.org/manual/5.2/ [3] http://bitop.luajit.org/ LICENSE (c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT). 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. (end license) --]] local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'} local floor = math.floor local MOD = 2^32 local MODM = MOD-1 local function memoize(f) local mt = {} local t = setmetatable({}, mt) function mt:__index(k) local v = f(k); t[k] = v return v end return t end local function make_bitop_uncached(t, m) local function bitop(a, b) local res,p = 0,1 while a ~= 0 and b ~= 0 do local am, bm = a%m, b%m res = res + t[am][bm]*p a = (a - am) / m b = (b - bm) / m p = p*m end res = res + (a+b)*p return res end return bitop end local function make_bitop(t) local op1 = make_bitop_uncached(t,2^1) local op2 = memoize(function(a) return memoize(function(b) return op1(a, b) end) end) return make_bitop_uncached(op2, 2^(t.n or 1)) end -- ok? probably not if running on a 32-bit int Lua number type platform function M.tobit(x) return x % 2^32 end M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4} local bxor = M.bxor function M.bnot(a) return MODM - a end local bnot = M.bnot function M.band(a,b) return ((a+b) - bxor(a,b))/2 end local band = M.band function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end local bor = M.bor local lshift, rshift -- forward declare function M.rshift(a,disp) -- Lua5.2 insipred if disp < 0 then return lshift(a,-disp) end return floor(a % 2^32 / 2^disp) end rshift = M.rshift function M.lshift(a,disp) -- Lua5.2 inspired if disp < 0 then return rshift(a,-disp) end return (a * 2^disp) % 2^32 end lshift = M.lshift function M.tohex(x, n) -- BitOp style n = n or 8 local up if n <= 0 then if n == 0 then return '' end up = true n = - n end x = band(x, 16^n-1) return ('%0'..n..(up and 'X' or 'x')):format(x) end local tohex = M.tohex function M.extract(n, field, width) -- Lua5.2 inspired width = width or 1 return band(rshift(n, field), 2^width-1) end local extract = M.extract function M.replace(n, v, field, width) -- Lua5.2 inspired width = width or 1 local mask1 = 2^width-1 v = band(v, mask1) -- required by spec? local mask = bnot(lshift(mask1, field)) return band(n, mask) + lshift(v, field) end local replace = M.replace function M.bswap(x) -- BitOp style local a = band(x, 0xff); x = rshift(x, 8) local b = band(x, 0xff); x = rshift(x, 8) local c = band(x, 0xff); x = rshift(x, 8) local d = band(x, 0xff) return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d end local bswap = M.bswap function M.rrotate(x, disp) -- Lua5.2 inspired disp = disp % 32 local low = band(x, 2^disp-1) return rshift(x, disp) + lshift(low, 32-disp) end local rrotate = M.rrotate function M.lrotate(x, disp) -- Lua5.2 inspired return rrotate(x, -disp) end local lrotate = M.lrotate M.rol = M.lrotate -- LuaOp inspired M.ror = M.rrotate -- LuaOp insipred function M.arshift(x, disp) -- Lua5.2 inspired local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end local arshift = M.arshift function M.btest(x, y) -- Lua5.2 inspired return band(x, y) ~= 0 end -- -- Start Lua 5.2 "bit32" compat section. -- M.bit32 = {} -- Lua 5.2 'bit32' compatibility local function bit32_bnot(x) return (-1 - x) % MOD end M.bit32.bnot = bit32_bnot local function bit32_bxor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = bxor(a, b) if c then z = bit32_bxor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bxor = bit32_bxor local function bit32_band(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = ((a+b) - bxor(a,b)) / 2 if c then z = bit32_band(z, c, ...) end return z elseif a then return a % MOD else return MODM end end M.bit32.band = bit32_band local function bit32_bor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = MODM - band(MODM - a, MODM - b) if c then z = bit32_bor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bor = bit32_bor function M.bit32.btest(...) return bit32_band(...) ~= 0 end function M.bit32.lrotate(x, disp) return lrotate(x % MOD, disp) end function M.bit32.rrotate(x, disp) return rrotate(x % MOD, disp) end function M.bit32.lshift(x,disp) if disp > 31 or disp < -31 then return 0 end return lshift(x % MOD, disp) end function M.bit32.rshift(x,disp) if disp > 31 or disp < -31 then return 0 end return rshift(x % MOD, disp) end function M.bit32.arshift(x,disp) x = x % MOD if disp >= 0 then if disp > 31 then return (x >= 0x80000000) and MODM or 0 else local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end else return lshift(x, -disp) end end function M.bit32.extract(x, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD return extract(x, field, ...) end function M.bit32.replace(x, v, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD v = v % MOD return replace(x, v, field, ...) end -- -- Start LuaBitOp "bit" compat section. -- M.bit = {} -- LuaBitOp "bit" compatibility function M.bit.tobit(x) x = x % MOD if x >= 0x80000000 then x = x - MOD end return x end local bit_tobit = M.bit.tobit function M.bit.tohex(x, ...) return tohex(x % MOD, ...) end function M.bit.bnot(x) return bit_tobit(bnot(x % MOD)) end local function bit_bor(a, b, c, ...) if c then return bit_bor(bit_bor(a, b), c, ...) elseif b then return bit_tobit(bor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bor = bit_bor local function bit_band(a, b, c, ...) if c then return bit_band(bit_band(a, b), c, ...) elseif b then return bit_tobit(band(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.band = bit_band local function bit_bxor(a, b, c, ...) if c then return bit_bxor(bit_bxor(a, b), c, ...) elseif b then return bit_tobit(bxor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bxor = bit_bxor function M.bit.lshift(x, n) return bit_tobit(lshift(x % MOD, n % 32)) end function M.bit.rshift(x, n) return bit_tobit(rshift(x % MOD, n % 32)) end function M.bit.arshift(x, n) return bit_tobit(arshift(x % MOD, n % 32)) end function M.bit.rol(x, n) return bit_tobit(lrotate(x % MOD, n % 32)) end function M.bit.ror(x, n) return bit_tobit(rrotate(x % MOD, n % 32)) end function M.bit.bswap(x) return bit_tobit(bswap(x % MOD)) end return M
mit
raymondtfr/forgottenserver
data/lib/core/creature.lua
1
3913
function Creature.getClosestFreePosition(self, position, maxRadius, mustBeReachable) maxRadius = maxRadius or 1 -- backward compatability (extended) if maxRadius == true then maxRadius = 2 end local checkPosition = Position(position) for radius = 0, maxRadius do checkPosition.x = checkPosition.x - math.min(1, radius) checkPosition.y = checkPosition.y + math.min(1, radius) local total = math.max(1, radius * 8) for i = 1, total do if radius > 0 then local direction = math.floor((i - 1) / (radius * 2)) checkPosition:getNextPosition(direction) end local tile = Tile(checkPosition) if tile:getCreatureCount() == 0 and not tile:hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID) and (not mustBeReachable or self:getPathTo(checkPosition)) then return checkPosition end end end return Position() end function Creature.getPlayer(self) return self:isPlayer() and self or nil end function Creature.isContainer(self) return false end function Creature.isItem(self) return false end function Creature.isMonster(self) return false end function Creature.isNpc(self) return false end function Creature.isPlayer(self) return false end function Creature.isTeleport(self) return false end function Creature.isTile(self) return false end function Creature:setMonsterOutfit(monster, time) local monsterType = MonsterType(monster) if not monsterType then return false end if self:isPlayer() and not (self:hasFlag(PlayerFlag_CanIllusionAll) or monsterType:isIllusionable()) then return false end local condition = Condition(CONDITION_OUTFIT) condition:setOutfit(monsterType:getOutfit()) condition:setTicks(time) self:addCondition(condition) return true end function Creature:setItemOutfit(item, time) local itemType = ItemType(item) if not itemType then return false end local condition = Condition(CONDITION_OUTFIT) condition:setOutfit({ lookTypeEx = itemType:getId() }) condition:setTicks(time) self:addCondition(condition) return true end function Creature:addSummon(monster) local summon = Monster(monster) if not summon then return false end summon:setTarget(nil) summon:setFollowCreature(nil) summon:setDropLoot(false) summon:setSkillLoss(false) summon:setMaster(self) return true end function Creature:removeSummon(monster) local summon = Monster(monster) if not summon or summon:getMaster() ~= self then return false end summon:setTarget(nil) summon:setFollowCreature(nil) summon:setDropLoot(true) summon:setSkillLoss(true) summon:setMaster(nil) return true end function Creature:addDamageCondition(target, type, list, damage, period, rounds) if damage <= 0 or not target or target:isImmune(type) then return false end local condition = Condition(type) condition:setParameter(CONDITION_PARAM_OWNER, self:getId()) condition:setParameter(CONDITION_PARAM_DELAYED, true) if list == DAMAGELIST_EXPONENTIAL_DAMAGE then local exponent, value = -10, 0 while value < damage do value = math.floor(10 * math.pow(1.2, exponent) + 0.5) condition:addDamage(1, period or 4000, -value) if value >= damage then local permille = math.random(10, 1200) / 1000 condition:addDamage(1, period or 4000, -math.max(1, math.floor(value * permille + 0.5))) else exponent = exponent + 1 end end elseif list == DAMAGELIST_LOGARITHMIC_DAMAGE then local n, value = 0, damage while value > 0 do value = math.floor(damage * math.pow(2.718281828459, -0.05 * n) + 0.5) if value ~= 0 then condition:addDamage(1, period or 4000, -value) n = n + 1 end end elseif list == DAMAGELIST_VARYING_PERIOD then for _ = 1, rounds do condition:addDamage(1, math.random(period[1], period[2]) * 1000, -damage) end elseif list == DAMAGELIST_CONSTANT_PERIOD then condition:addDamage(rounds, period * 1000, -damage) end target:addCondition(condition) return true end
gpl-2.0