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
wingo/snabb
lib/pflua/src/pf/utils.lua
15
5364
module(...,package.seeall) local ffi = require("ffi") local C = ffi.C ffi.cdef[[ struct pflua_timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ }; int gettimeofday(struct pflua_timeval *tv, struct timezone *tz); ]] -- now() returns the current time. The first time it is called, the -- return value will be zero. This is to preserve precision, regardless -- of what the current epoch is. local zero_sec, zero_usec function now() local tv = ffi.new("struct pflua_timeval") assert(C.gettimeofday(tv, nil) == 0) if not zero_sec then zero_sec = tv.tv_sec zero_usec = tv.tv_usec end local secs = tonumber(tv.tv_sec - zero_sec) secs = secs + tonumber(tv.tv_usec - zero_usec) * 1e-6 return secs end function gmtime() local tv = ffi.new("struct pflua_timeval") assert(C.gettimeofday(tv, nil) == 0) local secs = tonumber(tv.tv_sec) secs = secs + tonumber(tv.tv_usec) * 1e-6 return secs end function set(...) local ret = {} for k, v in pairs({...}) do ret[v] = true end return ret end function concat(a, b) local ret = {} for _, v in ipairs(a) do table.insert(ret, v) end for _, v in ipairs(b) do table.insert(ret, v) end return ret end function dup(table) local ret = {} for k, v in pairs(table) do ret[k] = v end return ret end function equals(expected, actual) if type(expected) ~= type(actual) then return false end if type(expected) == 'table' then for k, v in pairs(expected) do if not equals(v, actual[k]) then return false end end for k, _ in pairs(actual) do if expected[k] == nil then return false end end return true else return expected == actual end end function is_array(x) if type(x) ~= 'table' then return false end if #x == 0 then return false end for k,v in pairs(x) do if type(k) ~= 'number' then return false end -- Restrict to unsigned 32-bit integer keys. if k < 0 or k >= 2^32 then return false end -- Array indices are integers. if k - math.floor(k) ~= 0 then return false end -- Negative zero is not a valid array index. if 1 / k < 0 then return false end end return true end function pp(expr, indent, suffix) indent = indent or '' suffix = suffix or '' if type(expr) == 'number' then print(indent..expr..suffix) elseif type(expr) == 'string' then print(indent..'"'..expr..'"'..suffix) elseif type(expr) == 'boolean' then print(indent..(expr and 'true' or 'false')..suffix) elseif is_array(expr) then assert(#expr > 0) if #expr == 1 then if type(expr[1]) == 'table' then print(indent..'{') pp(expr[1], indent..' ', ' }'..suffix) else print(indent..'{ "'..expr[1]..'" }'..suffix) end else if type(expr[1]) == 'table' then print(indent..'{') pp(expr[1], indent..' ', ',') else print(indent..'{ "'..expr[1]..'",') end indent = indent..' ' for i=2,#expr-1 do pp(expr[i], indent, ',') end pp(expr[#expr], indent, ' }'..suffix) end elseif type(expr) == 'table' then if #expr == 0 then print(indent .. '{}') else error('unimplemented') end else error("unsupported type "..type(expr)) end return expr end function assert_equals(expected, actual) if not equals(expected, actual) then pp(expected) pp(actual) error('not equal') end end -- Construct uint32 from octets a, b, c, d; a is most significant. function uint32(a, b, c, d) return a * 2^24 + b * 2^16 + c * 2^8 + d end -- Construct uint16 from octets a, b; a is most significant. function uint16(a, b) return a * 2^8 + b end function ipv4_to_int(addr) assert(addr[1] == 'ipv4', "Not an IPV4 address") return uint32(addr[2], addr[3], addr[4], addr[5]) end function ipv6_as_4x32(addr) local function c(i, j) return addr[i] * 2^16 + addr[j] end return { c(2,3), c(4,5), c(6,7), c(8,9) } end function fixpoint(f, expr) local prev repeat expr, prev = f(expr), expr until equals(expr, prev) return expr end function choose(choices) local idx = math.random(#choices) return choices[idx] end function choose_with_index(choices) local idx = math.random(#choices) return choices[idx], idx end function parse_opts(opts, defaults) local ret = {} for k, v in pairs(opts) do if defaults[k] == nil then error('unrecognized option ' .. k) end ret[k] = v end for k, v in pairs(defaults) do if ret[k] == nil then ret[k] = v end end return ret end function table_values_all_equal(t) local val for _, v in pairs(t) do if val == nil then val = v end if v ~= val then return false end end return true, val end function selftest () print("selftest: pf.utils") local tab = { 1, 2, 3 } assert(tab ~= dup(tab)) assert_equals(tab, dup(tab)) assert_equals({ 1, 2, 3, 1, 2, 3 }, concat(tab, tab)) assert_equals(set(3, 2, 1), set(1, 2, 3)) if not zero_sec then assert_equals(now(), 0) end assert(now() > 0) assert_equals(ipv4_to_int({'ipv4', 255, 0, 0, 0}), 0xff000000) local gu1 = gmtime() local gu2 = gmtime() assert(gu1, gu2) print("OK") end
apache-2.0
bmscoordinators/FFXI-Server
scripts/globals/items/stick_of_pepperoni.lua
12
1596
----------------------------------------- -- ID: 5660 -- Item: stick_of_pepperoni -- Food Effect: 30Min, All Races ----------------------------------------- -- HP % 3 (assuming 3% from testing, no known cap) -- Strength 3 -- Intelligence -1 -- Attack % 60 (assuming 60%, cap 30) ----------------------------------------- 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,5660); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 3); target:addMod(MOD_FOOD_HP_CAP, 999); target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 60); target:addMod(MOD_FOOD_ATT_CAP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 3); target:delMod(MOD_FOOD_HP_CAP, 999); target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 60); target:delMod(MOD_FOOD_ATT_CAP, 30); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Bastok_Mines/npcs/Leonie.lua
14
1058
----------------------------------- -- Area: Bastok Mines -- NPC: Leonie -- Type: Room Renters -- @zone 234 -- @pos 118.871 -0.004 -83.916 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0238); 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
bmscoordinators/FFXI-Server
scripts/zones/Spire_of_Holla/npcs/_0h3.lua
66
1356
----------------------------------- -- Area: Spire_of_Holla -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Holla/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
sajadaltaiee/telebot
plugins/settings.lua
40
41643
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -- #creategroup by @lamjavid & @Josepdal -- -- -- -------------------------------------------------- do local function create_group(msg, group_name) local group_creator = msg.from.print_name create_group_chat(group_creator, group_name, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'createGroup:1')..' "'..string.gsub(group_name, '_', ' ')..'" '..lang_text(msg.to.id, 'createGroup:2') end local function remove_message(extra, success, result) msg = backward_msg_format(result) delete_msg(msg.id, ok_cb, false) end local function set_group_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) if msg.to.type == 'channel' then channel_set_photo (receiver, file, ok_cb, false) elseif msg.to.type == 'chat' then chat_set_photo(receiver, file, ok_cb, false) end return 'ℹ️ '..lang_text(msg.to.id, 'photoSaved') else print('Error downloading: '..msg.id) return 'ℹ️ '..lang_text(msg.to.id, 'photoSaved') end end local function pre_process(msg) local hash = 'flood:max:'..msg.to.id if not redis:get(hash) then floodMax = 5 else floodMax = tonumber(redis:get(hash)) end local hash = 'flood:time:'..msg.to.id if not redis:get(hash) then floodTime = 3 else floodTime = tonumber(redis:get(hash)) end if not permissions(msg.from.id, msg.to.id, "pre_process") then --Checking flood local hashse = 'anti-flood:'..msg.to.id if not redis:get(hashse) then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then if not permissions(msg.from.id, msg.to.id, "no_flood_ban") then -- Increase the number of messages from the user on the chat local hash = 'flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > floodMax then local receiver = get_receiver(msg) local user = msg.from.id local chat = msg.to.id local channel = msg.to.id local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, lang_text(chat, 'user')..' @'..msg.from.username..' ('..msg.from.id..') '..lang_text(chat, 'isFlooding'), ok_cb, true) chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, lang_text(chat, 'user')..' @'..msg.from.username..' ('..msg.from.id..') '..lang_text(chat, 'isFlooding'), ok_cb, true) channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) end end redis:setex(hash, floodTime, msgs+1) end end end if msg.action and msg.action.type then local action = msg.action.type if action == 'chat_add_user' or action == 'chat_add_user_link' then hash = 'antibot:'..msg.to.id if redis:get(hash) then if string.sub(msg.action.user.username:lower(), -3) == 'bot' then if msg.to.type == 'chat' then chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.action.user.id, ok_cb, true) elseif msg.to.type == 'channel' then channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.action.user.id, ok_cb, true) end end end end end --Checking stickers if not msg.media then webp = 'nothing' else webp = msg.media.caption end if webp == 'sticker.webp' then hash = 'stickers:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end if not msg.media then mp4 = 'nothing' else if msg.media.type == 'document' then mp4 = msg.media.caption or 'audio' end end --Checking tgservices hash = 'tgservices:'..msg.to.id if redis:get(hash) then local action = msg.action.type if action == 'chat_add_user' or action == 'chat_add_user_link' or action == 'chat_del_user' then delete_msg(msg.id, ok_cb, false) end end --Checking GIFs and MP4 files if mp4 == 'giphy.mp4' then hash = 'gifs:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else if msg.media then if msg.media.type == 'document' then gifytpe = string.find(mp4, 'gif.mp4') or 'audio' if gifytpe == 'audio' then hash = 'audio:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else hash = 'gifs:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end end end end --Checking photos if msg.media then if msg.media.type == 'photo' then local hash = 'photo:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end end --Checking muteall local hash = 'muteall:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else if msg.media then if msg.media.type == 'photo' then local hash = 'setphoto:'..msg.to.id..':'..msg.from.id if redis:get(hash) then redis:del(hash) load_photo(msg.id, set_group_photo, msg) print('setphoto') delete_msg(msg.id, ok_cb, false) end end end end return msg end local function run(msg, matches) if matches[1] == 'settings' then if permissions(msg.from.id, msg.to.id, "settings") then if matches[2] ~= nil then if matches[2] == 'stickers' then if matches[3] == 'enable' then hash = 'stickers:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'stickersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'stickersL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'stickers:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noStickersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noStickersL'), ok_cb, false) end end return elseif matches[2] == 'tgservices' then if matches[3] == 'enable' then hash = 'tgservices:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'tgservicesT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'tgservicesL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'tgservices:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noTgservicesT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noTgservicesL'), ok_cb, false) end end return elseif matches[2] == 'gifs' then if matches[3] == 'enable' then hash = 'gifs:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'gifsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'gifsL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'gifs:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noGifsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noGifsL'), ok_cb, false) end end return elseif matches[2] == 'links' then if matches[3] == 'enable' then hash = 'links:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'LinksT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'LinksL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'links:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinksT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinksL'), ok_cb, false) end end return elseif matches[2] == 'photos' then if matches[3] == 'enable' then hash = 'photo:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'photosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'photosL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'photo:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noPhotosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noPhotosL'), ok_cb, false) end end return elseif matches[2] == 'bots' then if matches[3] == 'enable' then hash = 'antibot:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'botsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'botsL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'antibot:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noBotsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noBotsL'), ok_cb, false) end end return elseif matches[2] == 'arabic' then if matches[3] == 'enable' then hash = 'arabic:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'arabicT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'arabicL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'arabic:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noArabicT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noArabicL'), ok_cb, false) end end return elseif matches[2] == 'audios' then if matches[3] == 'enable' then hash = 'audio:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'audiosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'audiosL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'audio:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noAudiosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noAudiosL'), ok_cb, false) end end return elseif matches[2] == 'kickme' then if matches[3] == 'enable' then hash = 'kickme:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'kickmeT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'kickmeL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'kickme:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noKickmeT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noKickmeL'), ok_cb, false) end end return elseif matches[2] == 'flood' then if matches[3] == 'enable' then hash = 'anti-flood:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'anti-flood:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noFloodT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noFloodL'), ok_cb, false) end end return elseif matches[2] == 'spam' then if matches[3] == 'enable' then local hash = 'spam:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'allowedSpamT'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'allowedSpamL'), ok_cb, true) end elseif matches[3] == 'disable' then local hash = 'spam:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notAllowedSpamT'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notAllowedSpamL'), ok_cb, true) end end elseif matches[2] == 'lockmember' then hash = 'lockmember:'..msg.to.id if matches[3] == 'enable' then redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'lockMembersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'lockMembersL'), ok_cb, false) end elseif matches[3] == 'disable' then redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notLockMembersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notLockMembersT'), ok_cb, false) end end return elseif matches[2] == 'floodtime' then if not matches[3] then else hash = 'flood:time:'..msg.to.id redis:set(hash, matches[3]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodTime')..matches[3], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodTime')..matches[3], ok_cb, false) end end return elseif matches[2] == 'maxflood' then if not matches[3] then else hash = 'flood:max:'..msg.to.id redis:set(hash, matches[3]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodMax')..matches[3], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodMax')..matches[3], ok_cb, false) end end return elseif matches[2] == 'setname' then if matches[3] == 'enable' then local hash = 'name:enabled:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'chatRename'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'channelRename'), ok_cb, false) end elseif matches[3] == 'disable' then local hash = 'name:enabled:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChatRename'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChannelRename'), ok_cb, false) end end elseif matches[2] == 'setphoto' then if matches[3] == 'enable' then local hash = 'setphoto:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'chatSetphoto'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'channelSetphoto'), ok_cb, false) end elseif matches[3] == 'disable' then local hash = 'setphoto:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChatSetphoto'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChannelSetphoto'), ok_cb, false) end end end else if msg.to.type == 'chat' then text = '⚙ '..lang_text(msg.to.id, 'gSettings')..':\n' elseif msg.to.type == 'channel' then text = '⚙ '..lang_text(msg.to.id, 'sSettings')..':\n' end local allowed = lang_text(msg.to.id, 'allowed') local noAllowed = lang_text(msg.to.id, 'noAllowed') --Enable/disable Stickers local hash = 'stickers:'..msg.to.id if redis:get(hash) then sStickers = noAllowed sStickersD = '🔹' else sStickers = allowed sStickersD = '🔸' end text = text..sStickersD..' '..lang_text(msg.to.id, 'stickers')..': '..sStickers..'\n' --Enable/disable Tgservices local hash = 'tgservices:'..msg.to.id if redis:get(hash) then tTgservices = noAllowed tTgservicesD = '🔹' else tTgservices = allowed tTgservicesD = '🔸' end text = text..tTgservicesD..' '..lang_text(msg.to.id, 'tgservices')..': '..tTgservices..'\n' --Enable/disable Links local hash = 'links:'..msg.to.id if redis:get(hash) then sLink = noAllowed sLinkD = '🔹' else sLink = allowed sLinkD = '🔸' end text = text..sLinkD..' '..lang_text(msg.to.id, 'links')..': '..sLink..'\n' --Enable/disable arabic messages local hash = 'arabic:'..msg.to.id if not redis:get(hash) then sArabe = allowed sArabeD = '🔸' else sArabe = noAllowed sArabeD = '🔹' end text = text..sArabeD..' '..lang_text(msg.to.id, 'arabic')..': '..sArabe..'\n' --Enable/disable bots local hash = 'antibot:'..msg.to.id if not redis:get(hash) then sBots = allowed sBotsD = '🔸' else sBots = noAllowed sBotsD = '🔹' end text = text..sBotsD..' '..lang_text(msg.to.id, 'bots')..': '..sBots..'\n' --Enable/disable gifs local hash = 'gifs:'..msg.to.id if redis:get(hash) then sGif = noAllowed sGifD = '🔹' else sGif = allowed sGifD = '🔸' end text = text..sGifD..' '..lang_text(msg.to.id, 'gifs')..': '..sGif..'\n' --Enable/disable send photos local hash = 'photo:'..msg.to.id if redis:get(hash) then sPhoto = noAllowed sPhotoD = '🔹' else sPhoto = allowed sPhotoD = '🔸' end text = text..sPhotoD..' '..lang_text(msg.to.id, 'photos')..': '..sPhoto..'\n' --Enable/disable send audios local hash = 'audio:'..msg.to.id if redis:get(hash) then sAudio = noAllowed sAudioD = '🔹' else sAudio = allowed sAudioD = '🔸' end text = text..sAudioD..' '..lang_text(msg.to.id, 'audios')..': '..sAudio..'\n' --Enable/disable kickme local hash = 'kickme:'..msg.to.id if redis:get(hash) then sKickme = allowed sKickmeD = '🔸' else sKickme = noAllowed sKickmeD = '🔹' end text = text..sKickmeD..' '..lang_text(msg.to.id, 'kickme')..': '..sKickme..'\n' --Enable/disable spam local hash = 'spam:'..msg.to.id if redis:get(hash) then sSpam = noAllowed sSpamD = '🔹' else sSpam = allowed sSpamD = '🔸' end text = text..sSpamD..' '..lang_text(msg.to.id, 'spam')..': '..sSpam..'\n' --Enable/disable setphoto local hash = 'setphoto:'..msg.to.id if not redis:get(hash) then sSPhoto = allowed sSPhotoD = '🔸' else sSPhoto = noAllowed sSPhotoD = '🔹' end text = text..sSPhotoD..' '..lang_text(msg.to.id, 'setphoto')..': '..sSPhoto..'\n' --Enable/disable changing group name local hash = 'name:enabled:'..msg.to.id if redis:get(hash) then sName = noAllowed sNameD = '🔹' else sName = allowed sNameD = '🔸' end text = text..sNameD..' '..lang_text(msg.to.id, 'gName')..': '..sName..'\n' --Lock/unlock numbers of channel members local hash = 'lockmember:'..msg.to.id if redis:get(hash) then sLock = noAllowed sLockD = '🔹' else sLock = allowed sLockD = '🔸' end text = text..sLockD..' lockmembers: '..sLock..'\n' --Enable/disable Flood local hash = 'anti-flood:'..msg.to.id if redis:get(hash) then sFlood = allowed sFloodD = '🔸' else sFlood = noAllowed sFloodD = '🔹' end text = text..sFloodD..' '..lang_text(msg.to.id, 'flood')..': '..sFlood..'\n' local hash = 'langset:'..msg.to.id if redis:get(hash) then sLang = redis:get(hash) sLangD = '🔸' else sLang = lang_text(msg.to.id, 'noSet') sLangD = '🔹' end text = text..sLangD..' '..lang_text(msg.to.id, 'language')..': '..string.upper(sLang)..'\n' local hash = 'flood:max:'..msg.to.id if not redis:get(hash) then floodMax = 5 else floodMax = redis:get(hash) end local hash = 'flood:time:'..msg.to.id if not redis:get(hash) then floodTime = 3 else floodTime = redis:get(hash) end text = text..'🔺 '..lang_text(msg.to.id, 'mFlood')..': '..floodMax..'\n🔺 '..lang_text(msg.to.id, 'tFlood')..': '..floodTime..'\n' --Send settings to group or supergroup if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, text, ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, text, ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'rem' then if permissions(msg.from.id, msg.to.id, "settings") then if msg.reply_id then get_message(msg.reply_id, remove_message, false) get_message(msg.id, remove_message, false) end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'lang' then if permissions(msg.from.id, msg.to.id, "set_lang") then hash = 'langset:'..msg.to.id redis:set(hash, matches[2]) return lang_text(msg.to.id, 'langUpdated')..string.upper(matches[2]) else return '🚫 '..lang_text(msg.to.id, 'require_sudo') end elseif matches[1] == 'setname' then if permissions(msg.from.id, msg.to.id, "settings") then local hash = 'name:enabled:'..msg.to.id if not redis:get(hash) then if msg.to.type == 'chat' then rename_chat(msg.to.peer_id, matches[2], ok_cb, false) elseif msg.to.type == 'channel' then rename_channel(msg.to.peer_id, matches[2], ok_cb, false) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'setlink' then if permissions(msg.from.id, msg.to.id, "setlink") then hash = 'link:'..msg.to.id redis:set(hash, matches[2]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) end return else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'newlink' then if permissions(msg.from.id, msg.to.id, "setlink") then local receiver = get_receiver(msg) local hash = 'link:'..msg.to.id local function cb(extra, success, result) if result then redis:set(hash, result) end if success == 0 then return send_large_msg(receiver, 'I can\'t create a newlink.', ok_cb, true) end end if msg.to.type == 'chat' then result = export_chat_link(receiver, cb, true) elseif msg.to.type == 'channel' then result = export_channel_link(receiver, cb, true) end if result then if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) end end return else return '?? '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'link' then if permissions(msg.from.id, msg.to.id, "link") then hash = 'link:'..msg.to.id local linktext = redis:get(hash) if linktext then if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, '🌐 '..lang_text(msg.to.id, 'groupLink')..': '..linktext, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, '🌐 '..lang_text(msg.to.id, 'sGroupLink')..': '..linktext, ok_cb, true) end else if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinkSet'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinkSet'), ok_cb, true) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'setphoto' then if permissions(msg.from.id, msg.to.id, "settings") then hash = 'setphoto:'..msg.to.id if redis:get(hash) then if matches[2] == 'stop' then hash = 'setphoto:'..msg.to.id..':'..msg.from.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'setPhotoAborted'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'setPhotoAborted'), ok_cb, true) end else hash = 'setphoto:'..msg.to.id..':'..msg.from.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'sendPhoto'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'sendPhoto'), ok_cb, true) end end else return 'ℹ️ '..lang_text(msg.to.id, 'setPhotoError') end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'tosupergroup' then if msg.to.type == 'chat' then if permissions(msg.from.id, msg.to.id, "tosupergroup") then chat_upgrade('chat#id'..msg.to.id, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'chatUpgrade') else return '🚫 '..lang_text(msg.to.id, 'require_sudo') end else return 'ℹ️ '..lang_text(msg.to.id, 'notInChann') end elseif matches[1] == 'setdescription' then if permissions(msg.from.id, msg.to.id, "description") then local text = matches[2] local chat = 'channel#id'..msg.to.id if msg.to.type == 'channel' then channel_set_about(chat, text, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'desChanged') else return 'ℹ️ '..lang_text(msg.to.id, 'desOnlyChannels') end else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'muteall' and matches[2] then if permissions(msg.from.id, msg.to.id, "muteall") then print(1) local hash = 'muteall:'..msg.to.id redis:setex(hash, tonumber(matches[2]), true) print(2) return 'ℹ️ '..lang_text(msg.to.id, 'muteAllX:1')..' '..matches[2]..' '..lang_text(msg.to.id, 'muteAllX:2') else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'muteall' then if permissions(msg.from.id, msg.to.id, "muteall") then local hash = 'muteall:'..msg.to.id redis:set(hash, true) return 'ℹ️ '..lang_text(msg.to.id, 'muteAll') else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'unmuteall' then if permissions(msg.from.id, msg.to.id, "muteall") then local hash = 'muteall:'..msg.to.id redis:del(hash) return 'ℹ️ '..lang_text(msg.to.id, 'unmuteAll') else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'creategroup' and matches[2] then if permissions(msg.from.id, msg.to.id, "creategroup") then group_name = matches[2] return create_group(msg, group_name) end elseif matches[1] == 'chat_created' and msg.from.id == 0 then return '🆕 '..lang_text(msg.to.id, 'newGroupWelcome') end end return { patterns = { '^[!/#](settings)$', '^[!/#](settings) (.*) (.*)$', '^[!/#](rem)$', '^[!/#](setname) (.*)$', '^[!/#](setphoto)$', '^[!/#](setphoto) (.*)$', '^[!/#](muteall)$', '^[!/#](muteall) (.*)$', '^[!/#](unmuteall)$', '^[!/#](link)$', '^[!/#](newlink)$', '^[!/#](tosupergroup)$', '^[!/#](setdescription) (.*)$', '^[!/#](setlink) (.*)$', '^[!/#](lang) (.*)$', '^[!/#](creategroup) (.*)$', '^!!tgservice (.+)$' }, pre_process = pre_process, run = run } end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Quicksand_Caves/Zone.lua
10
6759
----------------------------------- -- -- Zone: Quicksand_Caves (208) -- ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Quicksand_Caves/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/npc_util"); require("scripts/globals/zone"); local base_id = 17629685; local anticanTagPositions = { [1] = {590.000, -6.600, -663.000}, [2] = {748.000, 2.000, -570.000}, [3] = {479.000, -14.000, -815.000}, [4] = {814.000, -14.000, -761.000} } ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Weight Door System (RegionID, X, Radius, Z) zone:registerRegion(1, -15, 5, -60, 0,0,0); -- 0x010D01EF Door zone:registerRegion(3, 15, 5,-180, 0,0,0); -- 0x010D01F1 Door zone:registerRegion(5, -580, 5,-420, 0,0,0); -- 0x010D01F3 Door zone:registerRegion(7, -700, 5,-420, 0,0,0); -- 0x010D01F5 Door zone:registerRegion(9, -700, 5,-380, 0,0,0); -- 0x010D01F7 Door zone:registerRegion(11, -780, 5,-460, 0,0,0); -- 0x010D01F9 Door zone:registerRegion(13, -820, 5,-380, 0,0,0); -- 0x010D01FB Door zone:registerRegion(15, -260, 5, 740, 0,0,0); -- 0x010D01FD Door zone:registerRegion(17, -340, 5, 660, 0,0,0); -- 0x010D01FF Door zone:registerRegion(19, -420, 5, 740, 0,0,0); -- 0x010D0201 Door zone:registerRegion(21, -340, 5, 820, 0,0,0); -- 0x010D0203 Door zone:registerRegion(23, -409, 5, 800, 0,0,0); -- 0x010D0205 Door zone:registerRegion(25, -400, 5, 670, 0,0,0); -- 0x010D0207 Door --[[ -- (Old) zone:registerRegion(1,-18,-1, -62,-13,1, -57); zone:registerRegion(3, 13,-1, -183, 18,1, -177); zone:registerRegion(5,-583,-1,-422,-577,1,-418); zone:registerRegion(7,-703,-1,-423,-697,1,-417); zone:registerRegion(9,-703,-1,-383,-697,1,-377); zone:registerRegion(11,-782,-1,-462,-777,1,-457); zone:registerRegion(13,-823,-1,-383,-817,1,-377); zone:registerRegion(15,-262,-1, 737,-257,1, 742); zone:registerRegion(17,-343,-1, 657,-337,1, 662); zone:registerRegion(19,-343,-1, 818,-337,1, 822); zone:registerRegion(21,-411,-1, 797,-406,1, 803); zone:registerRegion(23,-422,-1, 737,-417,1, 742); zone:registerRegion(25,-403,-1, 669,-397,1, 674); ]]-- -- Hole in the Sand zone:registerRegion(30,495,-9,-817,497,-7,-815); -- E-11 (Map 2) zone:registerRegion(31,815,-9,-744,817,-7,-742); -- M-9 (Map 2) zone:registerRegion(32,215,6,-17,217,8,-15); -- K-6 (Map 3) zone:registerRegion(33,-297,6,415,-295,8,417); -- E-7 (Map 6) zone:registerRegion(34,-137,6,-177,-135,8,-175); -- G-7 (Map 8) SetServerVariable("BastokFight8_1" ,0); SetServerVariable("Bastok8-1LastClear", os.time()-QM_RESET_TIME); -- Set a delay on ??? mission NM pop. UpdateTreasureSpawnPoint(17629739); npcUtil.UpdateNPCSpawnPoint(17629761, 60, 120, anticanTagPositions, "[POP]Antican_Tag"); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-980.193,14.913,-282.863,60); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local RegionID = region:GetRegionID(); if (RegionID >= 30) then switch (RegionID): caseof { [30] = function (x) player:setPos(496,-6,-816); end, [31] = function (x) player:setPos(816,-6,-743); end, [32] = function (x) player:setPos(216,9,-16); end, [33] = function (x) player:setPos(-296,9,416); end, [34] = function (x) player:setPos(-136,9,-176); end, } else -- printf("entering region %u",RegionID); local race = player:getRace(); local raceWeight; if (race == 8) then -- Galka raceWeight = 3; elseif (race == 5 or race == 6) then -- Taru male or female raceWeight = 1; else -- Hume/Elvaan/Mithra raceWeight = 2; end local varname = "[DOOR]Weight_Sensor_"..RegionID; local totalWeight = GetServerVariable(varname); totalWeight = totalWeight + raceWeight; SetServerVariable(varname,totalWeight); if (player:hasKeyItem(LOADSTONE) or totalWeight >= 3) then local door = GetNPCByID(base_id + RegionID - 1); door:openDoor(15); -- open door with a 15 second time delay. --platform = GetNPCByID(base_id + RegionID + 1); --platform:setAnimation(8); -- this is supposed to light up the platform but it's not working. Tried other values too. end end end; ----------------------------------- -- OnRegionLeave ----------------------------------- function onRegionLeave(player,region) local RegionID = region:GetRegionID(); if (RegionID < 30) then -- printf("exiting region %u",RegionID); local race = player:getRace(); local raceWeight; if (race == 8) then -- Galka raceWeight = 3; elseif (race == 5 or race == 6) then -- Taru male or female raceWeight = 1; else -- Hume/Elvaan/Mithra raceWeight = 2; end local varname = "[DOOR]Weight_Sensor_"..RegionID; local totalWeight = GetServerVariable(varname); local lastWeight = totalWeight; totalWeight = totalWeight - raceWeight; SetServerVariable(varname,totalWeight); if (lastWeight >= 3 and totalWeight < 3) then --platform = GetNPCByID(base_id + RegionID + 1); --platform:setAnimation(9); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
deepak78/luci
libs/web/luasrc/i18n.lua
11
3847
--[[ LuCI - Internationalisation Description: A very minimalistic but yet effective internationalisation module FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- --- LuCI translation library. module("luci.i18n", package.seeall) require("luci.util") require("lmo") table = {} i18ndir = luci.util.libpath() .. "/i18n/" loaded = {} context = luci.util.threadlocal() default = "en" --- Clear the translation table. function clear() table = {} end --- Load a translation and copy its data into the translation table. -- @param file Language file -- @param lang Two-letter language code -- @param force Force reload even if already loaded (optional) -- @return Success status function load(file, lang, force) lang = lang and lang:gsub("_", "-") or "" if force or not loaded[lang] or not loaded[lang][file] then local f = lmo.open(i18ndir .. file .. "." .. lang .. ".lmo") if f then if not table[lang] then table[lang] = { f } setmetatable(table[lang], { __index = function(tbl, key) for i = 1, #tbl do local s = rawget(tbl, i):lookup(key) if s then return s end end end }) else table[lang][#table[lang]+1] = f end loaded[lang] = loaded[lang] or {} loaded[lang][file] = true return true else return false end else return true end end --- Load a translation file using the default translation language. -- Alternatively load the translation of the fallback language. -- @param file Language file -- @param force Force reload even if already loaded (optional) function loadc(file, force) load(file, default, force) if context.parent then load(file, context.parent, force) end return load(file, context.lang, force) end --- Set the context default translation language. -- @param lang Two-letter language code function setlanguage(lang) context.lang = lang:gsub("_", "-") context.parent = (context.lang:match("^([a-z][a-z])_")) end --- Return the translated value for a specific translation key. -- @param key Default translation text -- @return Translated string function translate(key) return (table[context.lang] and table[context.lang][key]) or (table[context.parent] and table[context.parent][key]) or (table[default] and table[default][key]) or key end --- Return the translated value for a specific translation key and use it as sprintf pattern. -- @param key Default translation text -- @param ... Format parameters -- @return Translated and formatted string function translatef(key, ...) return tostring(translate(key)):format(...) end --- Return the translated value for a specific translation key -- and ensure that the returned value is a Lua string value. -- This is the same as calling <code>tostring(translate(...))</code> -- @param key Default translation text -- @return Translated string function string(key) return tostring(translate(key)) end --- Return the translated value for a specific translation key and use it as sprintf pattern. -- Ensure that the returned value is a Lua string value. -- This is the same as calling <code>tostring(translatef(...))</code> -- @param key Default translation text -- @param ... Format parameters -- @return Translated and formatted string function stringf(key, ...) return tostring(translate(key)):format(...) end
apache-2.0
trigrass2/gopher-lua
_lua5.1-tests/math.lua
7
5452
print("testing numbers and math lib") do local a,b,c = "2", " 3e0 ", " 10 " assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0) assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string') assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ") assert(c%a == 0 and a^b == 8) end do local a,b = math.modf(3.5) assert(a == 3 and b == 0.5) assert(math.huge > 10e30) assert(-math.huge < -10e30) end function f(...) if select('#', ...) == 1 then return (...) else return "***" end end assert(tonumber{} == nil) assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and tonumber'.01' == 0.01 and tonumber'-1.' == -1 and tonumber'+1.' == 1) assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and tonumber'1e' == nil and tonumber'1.0e+' == nil and tonumber'.' == nil) assert(tonumber('-12') == -10-2) assert(tonumber('-1.2e2') == - - -120) assert(f(tonumber('1 a')) == nil) assert(f(tonumber('e1')) == nil) assert(f(tonumber('e 1')) == nil) assert(f(tonumber(' 3.4.5 ')) == nil) assert(f(tonumber('')) == nil) assert(f(tonumber('', 8)) == nil) assert(f(tonumber(' ')) == nil) assert(f(tonumber(' ', 9)) == nil) assert(f(tonumber('99', 8)) == nil) assert(tonumber(' 1010 ', 2) == 10) assert(tonumber('10', 36) == 36) assert(tonumber('\n -10 \n', 36) == -36) assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15))))))) assert(tonumber('fFfa', 15) == nil) assert(tonumber(string.rep('1', 42), 2) + 1 == 2^42) assert(tonumber(string.rep('1', 32), 2) + 1 == 2^32) assert(tonumber('-fffffFFFFF', 16)-1 == -2^40) assert(tonumber('ffffFFFF', 16)+1 == 2^32) assert(1.1 == 1.+.1) print(100.0, 1E2, .01) assert(100.0 == 1E2 and .01 == 1e-2) assert(1111111111111111-1111111111111110== 1000.00e-03) -- 1234567890123456 assert(1.1 == '1.'+'.1') assert('1111111111111111'-'1111111111111110' == tonumber" +0.001e+3 \n\t") function eq (a,b,limit) if not limit then limit = 10E-10 end return math.abs(a-b) <= limit end assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31) assert(0.123456 > 0.123455) assert(tonumber('+1.23E30') == 1.23*10^30) -- testing order operators assert(not(1<1) and (1<2) and not(2<1)) assert(not('a'<'a') and ('a'<'b') and not('b'<'a')) assert((1<=1) and (1<=2) and not(2<=1)) assert(('a'<='a') and ('a'<='b') and not('b'<='a')) assert(not(1>1) and not(1>2) and (2>1)) assert(not('a'>'a') and not('a'>'b') and ('b'>'a')) assert((1>=1) and not(1>=2) and (2>=1)) assert(('a'>='a') and not('a'>='b') and ('b'>='a')) -- testing mod operator assert(-4%3 == 2) assert(4%-3 == -2) assert(math.pi - math.pi % 1 == 3) assert(math.pi - math.pi % 0.001 == 3.141) local function testbit(a, n) return a/2^n % 2 >= 1 end assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1)) assert(eq(math.tan(math.pi/4), 1)) assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0)) assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and eq(math.asin(1), math.pi/2)) assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2)) assert(math.abs(-10) == 10) assert(eq(math.atan2(1,0), math.pi/2)) assert(math.ceil(4.5) == 5.0) assert(math.floor(4.5) == 4.0) assert(math.mod(10,3) == 1) assert(eq(math.sqrt(10)^2, 10)) assert(eq(math.log10(2), math.log(2)/math.log(10))) assert(eq(math.exp(0), 1)) assert(eq(math.sin(10), math.sin(10%(2*math.pi)))) local v,e = math.frexp(math.pi) assert(eq(math.ldexp(v,e), math.pi)) assert(eq(math.tanh(3.5), math.sinh(3.5)/math.cosh(3.5))) assert(tonumber(' 1.3e-2 ') == 1.3e-2) assert(tonumber(' -1.00000000000001 ') == -1.00000000000001) -- testing constant limits -- 2^23 = 8388608 assert(8388609 + -8388609 == 0) assert(8388608 + -8388608 == 0) assert(8388607 + -8388607 == 0) if rawget(_G, "_soft") then return end f = io.tmpfile() assert(f) f:write("a = {") i = 1 repeat f:write("{", math.sin(i), ", ", math.cos(i), ", ", i/3, "},\n") i=i+1 until i > 1000 f:write("}") f:seek("set", 0) assert(loadstring(f:read('*a')))() assert(f:close()) assert(eq(a[300][1], math.sin(300))) assert(eq(a[600][1], math.sin(600))) assert(eq(a[500][2], math.cos(500))) assert(eq(a[800][2], math.cos(800))) assert(eq(a[200][3], 200/3)) assert(eq(a[1000][3], 1000/3, 0.001)) print('+') do -- testing NaN local NaN = 10e500 - 10e400 assert(NaN ~= NaN) assert(not (NaN < NaN)) assert(not (NaN <= NaN)) assert(not (NaN > NaN)) assert(not (NaN >= NaN)) assert(not (0 < NaN)) assert(not (NaN < 0)) local a = {} assert(not pcall(function () a[NaN] = 1 end)) assert(a[NaN] == nil) a[1] = 1 assert(not pcall(function () a[NaN] = 1 end)) assert(a[NaN] == nil) end require "checktable" stat(a) a = nil -- testing implicit convertions local a,b = '10', '20' assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20) assert(a == '10' and b == '20') math.randomseed(0) local i = 0 local Max = 0 local Min = 2 repeat local t = math.random() Max = math.max(Max, t) Min = math.min(Min, t) i=i+1 flag = eq(Max, 1, 0.001) and eq(Min, 0, 0.001) until flag or i>10000 assert(0 <= Min and Max<1) assert(flag); for i=1,10 do local t = math.random(5) assert(1 <= t and t <= 5) end i = 0 Max = -200 Min = 200 repeat local t = math.random(-10,0) Max = math.max(Max, t) Min = math.min(Min, t) i=i+1 flag = (Max == 0 and Min == -10) until flag or i>10000 assert(-10 <= Min and Max<=0) assert(flag); print('OK')
mit
bmscoordinators/FFXI-Server
scripts/zones/Windurst_Woods/npcs/Nya_Labiccio.lua
17
1516
----------------------------------- -- Area: Windurst Woods -- NPC: Nya Labiccio -- Only sells when Windurst controlls Gustaberg Region -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(GUSTABERG); if (RegionOwner ~= NATION_WINDURST) then player:showText(npc,NYALABICCIO_CLOSED_DIALOG); else player:showText(npc,NYALABICCIO_OPEN_DIALOG); stock = { 0x0454, 703, --Sulfur 0x026B, 43, --Popoto 0x0263, 36, --Rye Flour 0x1124, 40 --Eggplant } showShop(player,WINDURST,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
jochem-brouwer/VO2_Model
Run_RBIM_Resistance.lua
1
1831
local Lattice = require 'Lattice' local MyLattice = Lattice:New(); --math.randomseed(os.time()) local Model = require 'Model'; Model = Model:New(); Model.Lattice = MyLattice; MyLattice:Init(100,100,1); MyLattice:InitRandomField(10,0); MyLattice.Temperature = 1; -- If you want to calculate resistances, also init the RN; MyLattice:InitRN(); -- Measure from one side to the other. local INDEX_1 = MyLattice.Grid[math.floor(MyLattice.x/2)][1][1]; local INDEX_2 = MyLattice.Grid[math.floor(MyLattice.x/2)][MyLattice.y][1]; function Model:Measure(Lattice) -- Return a table where [ylabel] = measuredpoint. local Out = {}; Out.M = Lattice:GetM(); Out.Resistance = Lattice.RN:GetResistance(INDEX_1,INDEX_2); -- Lattice.RN:DumpSystem() print(Out.Resistance, Out.M,Lattice.ExternalField) return Out; end local function linspace(startn,num,endn) local step = (endn-startn) / (num-1); local out = {} for i = 1, num do local val = startn + (i-1)*step table.insert(out, val) end return out end ; local function tjoin(t1, t2) local out = {}; for i,v in pairs(t1) do table.insert(out,v) end for i,v in pairs(t2) do table.insert(out,v) end return out ; end local Field = linspace(-3,550,2.5); local Field2 = linspace(2.5,400,-1.5); local Field3 = linspace(-1.5,450,3); local Field4 = linspace(3,550,-2.5); local Field5 = linspace(-2.5,400,1.5); local Field6 = linspace(1.5,450,-3); local Field = tjoin(Field,Field2); local Field = tjoin(Field,Field3); local Field = tjoin(Field,Field4); local Field = tjoin(Field,Field5); local Field = tjoin(Field,Field6); --Field = {-1000,1000,-1000}; local Params = { ExternalField = Field; } Options = { Anim = false; Sweeps = MyLattice.x*MyLattice.y*MyLattice.z*100; } Model:Run(Params, 'Cycle', Options); local Plotter = require 'Plotter'
mit
bmscoordinators/FFXI-Server
scripts/zones/Monastic_Cavern/npcs/Altar.lua
6
1824
----------------------------------- -- Area: Monastic Cavern -- NPC: Altar -- Involved in Quests: The Circle of Time -- @pos 108 -2 -144 150 ----------------------------------- package.loaded["scripts/zones/Monastic_Cavern/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Monastic_Cavern/MobIDs"); require("scripts/zones/Monastic_Cavern/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME); -- CIRCLE OF TIME (Bard AF3) if (circleOfTime == QUEST_ACCEPTED and player:hasKeyItem(STAR_RING1) and player:hasKeyItem(MOON_RING)) then if (player:getVar("circleTime") == 7 and GetMobByID(BUGABOO):isDead()) then SpawnMob(BUGABOO):updateClaim(player); elseif (player:getVar("circleTime") == 8) then player:startEvent(0x03); -- Show final CS else player:messageSpecial(ALTAR); end; -- DEFAULT DIALOG else player:messageSpecial(ALTAR); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- CIRCLE OF TIME if (csid == 0x03) then player:setVar("circleTime",9); -- After bugaboo is killed, and final CS shows up player:delKeyItem(MOON_RING); player:delKeyItem(STAR_RING1); end; end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/items/bowl_of_salt_ramen_+1.lua
12
1923
----------------------------------------- -- ID: 6463 -- Item: bowl_of_salt_ramen_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- DEX +6 -- VIT +6 -- AGI +6 -- Accuracy +6% (cap 95) -- Ranged Accuracy +6% (cap 95) -- Evasion +6% (cap 95) -- Resist Slow +15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,6463); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 6); target:addMod(MOD_VIT, 6); target:addMod(MOD_AGI, 6); target:addMod(MOD_FOOD_ACCP, 6); target:addMod(MOD_FOOD_ACC_CAP, 95); target:addMod(MOD_FOOD_RACCP, 6); target:addMod(MOD_FOOD_RACC_CAP, 95); -- target:addMod(MOD_FOOD_EVAP, 6); -- target:addMod(MOD_FOOD_EVA_CAP, 95); target:addMod(MOD_SLOWRES, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 6); target:delMod(MOD_VIT, 6); target:delMod(MOD_AGI, 6); target:delMod(MOD_FOOD_ACCP, 6); target:delMod(MOD_FOOD_ACC_CAP, 95); target:delMod(MOD_FOOD_RACCP, 6); target:delMod(MOD_FOOD_RACC_CAP, 95); -- target:delMod(MOD_FOOD_EVAP, 6); -- target:delMod(MOD_FOOD_EVA_CAP, 95); target:delMod(MOD_SLOWRES, 15); end;
gpl-3.0
xomachine/textadept-spellchecker
suggestions.lua
1
3245
local backend = require("textadept-spellchecker.backend") local check = require("textadept-spellchecker.check") --------------------------- -- Indicator click handler --------------------------- local SUGGESTION_LIST = 4242 -- List id -- autocomplete handler will be placed here to avoid presence of -- many anonymous handlers in event table local current_autocomplete_handler = false -- Word beginning and length for correct substitution of suggestion local g_word_start = 0 local g_word_length = 0 -- only this autocomplete handler presents in event table local function on_answer(word, suggestion) -- Handles autocompletion answer if it is necessary -- then removes handler if current_autocomplete_handler then current_autocomplete_handler(word, suggestion or "") end -- remove handler to avoid displaying suggestion again without click current_autocomplete_handler = false end local function on_suggestion_click(list_id, selection, pos) -- Handles click on item in suggestion list and replaces mistake if list_id == SUGGESTION_LIST then if selection == _L["DICT_ADD"] then -- TODO: addition to the dictionary local checker = backend.get_checker() local word = buffer:text_range(g_word_start, g_word_start+g_word_length) checker:write("* "..word.."\n") checker:write("#\n") elseif selection == _L["IGNORE"] then local checker = backend.get_checker() local word = buffer:text_range(g_word_start, g_word_start+g_word_length) checker:write("@ "..word.."\n") else buffer:delete_range(g_word_start, g_word_length) buffer:insert_text(buffer.current_pos, selection) end check.frame() end end local function on_indicator_click(pos, mod) -- Handles click on indicator and shows suggestion menu if mod ~= 0 then return end -- no modificators should be pressed local word_start = buffer:word_start_position(pos, false) local word_end = buffer:word_end_position(pos, false) g_word_start = word_start local word = buffer:text_range(word_start, word_end) current_autocomplete_handler = function(origin_word, suggestions) g_word_length = origin_word:len() local old_separator = buffer.auto_c_separator buffer.auto_c_separator = string.byte(",") local suggestions_list = _L["DICT_ADD"].. ",".._L["IGNORE"] if suggestions and suggestions:len() > 0 then suggestions_list = suggestions_list..",".. suggestions:gsub(", ",",") end buffer:user_list_show(SUGGESTION_LIST, suggestions_list ) buffer.auto_c_separator = old_separator end local checker = backend.get_checker() checker:write(word.."\n") end local _M = {} local function shutdown() events.disconnect(events.INDICATOR_CLICK, on_indicator_click) events.disconnect(backend.ANSWER, on_answer) events.disconnect(events.USER_LIST_SELECTION, on_suggestion_click) events.disconnect(events.RESET_BEFORE, shutdown) end function _M.init() events.connect(events.INDICATOR_CLICK, on_indicator_click) events.connect(backend.ANSWER, on_answer) events.connect(events.USER_LIST_SELECTION, on_suggestion_click) events.connect(events.QUIT, shutdown) -- events.connect(events.RESET_BEFORE, shutdown) end return _M
mit
bmscoordinators/FFXI-Server
scripts/globals/items/roast_trout.lua
12
1351
----------------------------------------- -- ID: 4404 -- Item: roast_trout -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 3 -- Mind -1 -- Ranged ATT % 14 (cap 50) ----------------------------------------- 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,4404); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -1); target:addMod(MOD_RATTP, 14); target:addMod(MOD_RATT_CAP, 50); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -1); target:delMod(MOD_RATTP, 14); target:delMod(MOD_RATT_CAP, 50); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Maze_of_Shakhrami/npcs/Planar_Rift.lua
1
2306
----------------------------------- -- Area: Maze_of_Shakhrami -- NPC: Planar Rift ----------------------------------- package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Maze_of_Shakhrami/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local STRATUM = player:hasKeyItem(JADE_STRATUM_ABYSSITE_II); local mobID = 17588707; local mobNotUp = false local correctNPC = false if (GetMobAction(mobID) == ACTION_NONE or GetMobAction(mobID) == ACTION_SPAWN) then mobNotUp = true; end if (npc:getXPos(-285) and npc:getYPos(0) and npc:getZPos(-114)) then correctNPC = true; end if (STRATUM == true and mobNotUp == true and correctNPC == true) then -- NOTE: I'm only requiring 1 person (the popper) to have the voidstone+abyssite, per pop. -- I know this isn't what retail does. Retail also lets them gain more than 1 per day too. -- In the mobs onMobDeath script, we can easily make the popper 100% upgrade rate and everyone else less, if desired. if (player:getCurrency("voidstones") > 0) then player:startEvent(6000, 7); else player:startEvent(6000, 2); end else player:startEvent(6000); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- NOTE: I'm only requiring 1 person (the popper) to have the voidstone, per pop. -- I know this isn't what retail does. Retail also lets them gain more than 1 per day too. if (csid == 6000 and option == 1) then player:delCurrency("voidstones", 1); SpawnMob(17588707):updateClaim(player); end end;
gpl-3.0
Ravenlord/ddp-testing
tests/calculated_values/dependent/04_trigger-insert.lua
1
2244
--[[! - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form - or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. - - In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright - interest in the software to the public domain. We make this dedication for the benefit of the public at large and to - the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in - perpetuity of all present and future rights to this software under copyright law. - - 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 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. - - For more information, please refer to <http://unlicense.org/> --]] --[[ - Benchmark file for design problem "Calculated Values (dependent)", Trigger solution. - Insert new line item (fixed order id and product id). - - @author Markus Deutschl <deutschl.markus@gmail.com> - @copyright 2014 Markus Deutschl - @license http://unlicense.org/ Unlicense --]] -- --------------------------------------------------------------------------------------------------------------------- Includes pathtest = string.match(test, "(.*/)") or "" -- Total reusal of preparations. dofile(pathtest .. "04_trigger-select.lua") -- --------------------------------------------------------------------------------------------------------------------- Benchmark functions --- Execute the benchmark queries. -- Is called during the run command of sysbench. function benchmark() local query = [[ INSERT INTO `line_items` (`order_id`, `product_id`, `amount`) VALUES (2222, 42, 10) ]] db_query('BEGIN') rs = db_query(query) db_query('ROLLBACK') end
unlicense
abbasgh12345/creadabbas
bot/creed.lua
1
9186
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 = '1.0' -- 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) print (receiver) -- 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) _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 local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) 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 local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) 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 = { "onservice", "inrealm", "Moderator_Gp", "LockTag", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "plugins", "lock_link", "all" }, sudo_users = {179983320},--Sudo users disabled_channels = {}, realm = {105122824},--Realms Id moderation = {data = 'data/moderation.json'}, about_text = [[Creed bot 2.0 Hello my Good friends 😀🖐🏻 ‼️ this bot is made by : @creed_is_dead 〰〰〰〰〰〰〰〰 🚩 Our admins are : 🔰 @unkownhacker 〰〰〰〰〰〰〰〰 ♻️ You can send your Ideas and messages to Us By sending them into bots account by this command : !feedback (your ideas and messages) ]], help_text = [[ Creed bots Help for mods : 😈 Plugins : 🔻 1. banhammer ⭕️ Help For Banhammer👇 !Kick @UserName 😜 And You Can do It by Replay 🙈 !Ban @UserName 〽️ You Can Do It By Replay👌 !Unban @UserName You Can Do it By Replay😱 For Admins : 👇 !banall @UserName or (user_id)😺 you Can do it By Replay 👤 !unbanall 🆔User_Id🆔 〰〰〰〰〰〰〰〰〰〰 2. GroupManager :🔹 !Creategroup "GroupName" 🙈 You Can CreateGroup With this command😱 !setflood😃 Set the group flood control🈹 !settings ❌ Watch group settings !owner🚫 watch group owner !setowner user_id❗️ You can set someone to the group owner‼️ !modlist💯 watch Group mods🔆 !lock (bots-member-flood-photo-name-Arabic-english-tag-join-link)✅ lock Something🚼 !unlock (bots-member-flood-photo-name-Arabic-english-tag-join-link)✅ Unlock Something🚼 !rules 🆙 or !set rules🆗 watch group rules or set !about or !set about 🔴 !res @username🔘 See UserInfo© !who♦️ Get Ids Chat🔺 !log 🎴 get members id ♠️ !all🔴 this is like stats in a file🔸 added !clink * and !glink :) 〰〰〰〰〰〰〰〰 Admins :® !add 😎 You Can add the group to moderation.json😱 !rem😏 You Can Remove the group from mod.json⭕️ !setgpowner (Gpid) user_id ⚫️ from realm®® !addadmin 🔶 set some one to global admin🔸 !removeadmin🔘 remove somone from global admin🔹 〰〰〰〰〰〰〰〰〰〰〰 3. Stats :© !stats creedbot (sudoers)✔️ shows bt stats🔚 !stats🔘 shows group stats💲 〰〰〰〰〰〰〰〰 4. Feedback⚫️ !feedback txt🔻◼️ send maseage to admins via bot🔈 〰〰〰〰〰〰〰〰〰〰〰 5. Tagall◻️ !tagall txt🔸 will tag users© 〰〰〰〰〰〰〰〰〰 🔜 more plugins ⚠️ We are Creeds ... ⚠️ our channel : @creedantispam_channel🔋 You Can user both "!" & "/" for them🎧 ]] } 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) 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 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
paulcuth/starlight
test/lua/metamethods.lua
4
12597
-------------------------------------------------------------------------- -- Moonshine - a Lua virtual machine. -- -- Email: moonshine@gamesys.co.uk -- http://moonshinejs.org -- -- Copyright (c) 2013-2015 Gamesys Limited. All rights reserved. -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- Event metametods -- __index local o = {} local index = 'mogwai' local returnVal = {} local test local x = {} --nil setmetatable(o, {}) assertTrue (o[index] == nil, 'Getting an index of an empty table with empty metamethod should return nil.') --function setmetatable(o, { __index = function (t, i) assertTrue (t == o, '__index function in metatable should be passed the table as first argument.') assertTrue (i == index, '__index function in metatable should be passed the index as second argument.') test = true return returnVal end }) local result = o[index] assertTrue (test, '__index function in metatable should be executed when table has no property by that index.') assertTrue (result == returnVal, 'Value returned from __index function in metatable should be passed as the value') --table setmetatable(x, { __index = o }); test = false result = x[index] assertTrue (test, '__index function in metatable should be executed when table has no property by that index, even when nested.') assertTrue (result == returnVal, 'Value returned from __index function in metatable should be passed as the value when nested') --don't call if assigned x[index] = 456 test = false result = x[index] assertTrue (not test, '__index function in metatable should not be executed when table has a property by that index.') assertTrue (result == 456, '__index should be ignored when index is set.') --test diffferent types of keys setmetatable(o, { __index = function (t, i) test = true return returnVal end }) test = false result = o[123] assertTrue (test, '__index function in metatable should be executed when table has no property by numerical index') assertTrue (result == returnVal, 'Value returned from __index function in metatable should be passed as the value when index is numerical') test = false result = o[function () end] assertTrue (test, '__index function in metatable should be executed when table has no property with a function key') assertTrue (result == returnVal, 'Value returned from __index function in metatable should be passed as the value with a function key') test = false result = o[{}] assertTrue (test, '__index function in metatable should be executed when table has no property with a table key') assertTrue (result == returnVal, 'Value returned from __index function in metatable should be passed as the value with a table key') -- nil (assigned) getmetatable(o).__index = nil assertTrue (o[index] == nil, 'When __index property of metatable is nil, value returned should be nil') -- __newindex --nil o = {} setmetatable(o, {}) o[index] = 123 assertTrue (o[index] == 123, 'Setting an index of an empty table with empty metamethod should set that value.') --function local value = {} test = false o = {} setmetatable(o, { __newindex = function (t, i, v) assertTrue (t == o, '__newindex function in metatable should be passed the table as first argument.') assertTrue (i == index, '__newindex function in metatable should be passed the index as second argument.') assertTrue (v == value, '__newindex function in metatable should be passed the value as third argument.') test = true return returnVal end }) o[index] = value assertTrue (test, '__newindex function in metatable should be executed when table has no property by that index.') assertTrue (o[index] == nil, '__newindex function should not set the value unless done so explicitly,') --table does not have same effect as __index x = {} setmetatable(x, { __index = o }); test = false x[index] = value assertTrue (not test, '__newindex function in metatable should not be executed when nested.') assertTrue (x[index] == value, '__newindex function in metatable should be be ignored when nested.') --don't call if assigned test = false rawset(o, index, 111) o[index] = value assertTrue (not test, '__newindex function in metatable should not be executed when table has a property by that index.') assertTrue (o[index] == value, '__newindex should be ignored when index is set.') --test different types of keys setmetatable(o, { __newindex = function (t, i, v) test = true return returnVal end }) test = false index = 123 o[index] = value assertTrue (test, '__newindex function in metatable should be executed when table has not property for numerical key.') assertTrue (o[index] == nil, '__newindex should return the correct value when passed a numerical key.') test = false index = function () end o[index] = value assertTrue (test, '__newindex function in metatable should be executed when table has not property for function key.') assertTrue (o[index] == nil, '__newindex should return the correct value when passed a function key.') test = false index = {} o[index] = value assertTrue (test, '__newindex function in metatable should be executed when table has not property for table key.') assertTrue (o[index] == nil, '__newindex should return the correct value when passed a table key.') -- nil (assigned) rawset(o, index, nil) getmetatable(o).__index = nil assertTrue (o[index] == nil, 'When __index property of metatable is nil, value returned should be nil') -- metatable local mt = { moo = '123' } local fake = {} local fake2 = {} o = {} setmetatable(o, mt) result = getmetatable(o) assertTrue (result == mt, 'getmetatable() should return metatable when __metatable is not set') mt.__metatable = fake result = getmetatable(o) assertTrue (result ~= mt, 'getmetatable() should not return metatable when __metatable is set') assertTrue (result == fake, 'getmetatable() should return the value of __metatable, if set') local setmet = function () setmetatable(o, mt) end local s, _ = pcall(setmet) assertTrue (not s, 'setmetatable() should error when metatable has __metatable set') mt.__metatable = function () return fake2 end result = getmetatable(o) assertTrue (result ~= fake2, 'getmetatable() should not return the value returned by __metatable, if it is set to a function') assertTrue (type(result) == 'function', 'getmetatable() should return the value of __metatable, even if it is set to a function') -- Arithmetic metamethods local mt = {} local Obj = {} function Obj.new (v) local self = { ['value'] = v } setmetatable (self, mt); return self end local o = Obj.new (3); local p = Obj.new (5); local x = { value = 'moo' } -- __add mt.__add = function (a, b) return a.value..'(__add)'..b.value end assertTrue (o + p == '3(__add)5', 'Add operator should use __add metamethod, if provided [1]') assertTrue (o + x == '3(__add)moo', 'Add operator should use __add metamethod, if provided [2]') assertTrue (x + p == 'moo(__add)5', 'Add operator should use __add metamethod, if provided [3]') -- __concat mt.__concat = function (a, b) return a.value..'(__concat)'..b.value end assertTrue (o..p == '3(__concat)5', 'Concatenation operator should use __concat metamethod, if provided [1]') assertTrue (o..x == '3(__concat)moo', 'Concatenation operator should use __concat metamethod, if provided [2]') assertTrue (x..p == 'moo(__concat)5', 'Concatenation operator should use __concat metamethod, if provided [3]') -- __div mt.__div = function (a, b) return a.value..'(__div)'..b.value end assertTrue (o / p == '3(__div)5', 'Divide operator should use __div metamethod, if provided [1]') assertTrue (o / x == '3(__div)moo', 'Divide operator should use __div metamethod, if provided [2]') assertTrue (x / p == 'moo(__div)5', 'Divide operator should use __div metamethod, if provided [3]') -- __mod mt.__mod = function (a, b) return a.value..'(__mod)'..b.value end assertTrue (o % p == '3(__mod)5', 'Modulo operator should use __mod metamethod, if provided [1]') assertTrue (o % x == '3(__mod)moo', 'Modulo operator should use __mod metamethod, if provided [2]') assertTrue (x % p == 'moo(__mod)5', 'Modulo operator should use __mod metamethod, if provided [3]') -- __mul mt.__mul = function (a, b) return a.value..'(__mul)'..b.value end assertTrue (o * p == '3(__mul)5', 'Muliplication operator should use __mul metamethod, if provided [1]') assertTrue (o * x == '3(__mul)moo', 'Muliplication operator should use __mul metamethod, if provided [2]') assertTrue (x * p == 'moo(__mul)5', 'Muliplication operator should use __mul metamethod, if provided [3]') -- __pow mt.__pow = function (a, b) return a.value..'(__pow)'..b.value end assertTrue (o ^ p == '3(__pow)5', 'Exponentiation operator should use __pow metamethod, if provided [1]') assertTrue (o ^ x == '3(__pow)moo', 'Exponentiation operator should use __pow metamethod, if provided [2]') assertTrue (x ^ p == 'moo(__pow)5', 'Exponentiation operator should use __pow metamethod, if provided [3]') -- __sub mt.__sub = function (a, b) return a.value..'(__sub)'..b.value end assertTrue (o - p == '3(__sub)5', 'Subtraction operator should use __sub metamethod, if provided [1]') assertTrue (o - x == '3(__sub)moo', 'Subtraction operator should use __sub metamethod, if provided [2]') assertTrue (x - p == 'moo(__sub)5', 'Subtraction operator should use __sub metamethod, if provided [3]') -- __unm mt.__unm = function (a) return '(__unm)'..a.value end assertTrue (-o == '(__unm)3', 'Negation operator should use __unm metamethod, if provided') -- Relational metamethods -- __eq local x = 0 mt.__eq = function (a, b) x = x + 1 return true end assertTrue (o == p, 'Equality operator should use __eq metamethod, if provided [1]') assertTrue (x == 1, 'Equality operator should use __eq metamethod, if provided [2]') assertTrue (not (o == 123), 'Equality operator should not use __eq metamethod if objects are of different type [1]') assertTrue (x == 1, 'Equality operator should not use __eq metamethod if operands are of different type [2]') assertTrue (o == o, 'Equality operator should not use __eq metamethod if the operands are the same object [1]') assertTrue (x == 1, 'Equality operator should not use __eq metamethod if the operands are the same object [2]') -- __le x = 0 mt.__le = function (a, b) x = x + 1 return a.value == 3 end assertTrue (o <= p, 'Less than or equal to operator should use __le metamethod, if provided [1]') assertTrue (x == 1, 'Less than or equal to operator should use __le metamethod, if provided [2]') assertTrue (not (p <= o), 'Less than or equal to operator should use __le metamethod, if provided [3]') assertTrue (x == 2, 'Less than or equal to operator should use __le metamethod, if provided [4]') -- __lt x = 0 mt.__lt = function (a, b) x = x + 1 return a.value == 3 end assertTrue (o < p, 'Less than operator should use __le metamethod, if provided [1]') assertTrue (x == 1, 'Less than operator should use __le metamethod, if provided [2]') assertTrue (not (p < o), 'Less than operator should use __le metamethod, if provided [3]') assertTrue (x == 2, 'Less than operator should use __le metamethod, if provided [4]') -- __call x = '' mt.__concat = nil mt.__call = function (p1, p2) if p1 == o then x = 'Ron ' end x = x .. p2 return 'CEO' end y = o('Dennis') assertTrue (x == 'Ron Dennis', 'When executing a table, __call metamethod should be used, if provided') assertTrue (y == 'CEO', 'When executing a table with a __call metamethod, the return value(s) of __call function should be returned')
mit
timmerk/cardpeek
dot_cardpeek_dir/scripts/calypso.lua
16
9370
-- -- This file is part of Cardpeek, the smartcard reader utility. -- -- Copyright 2009-2013 by 'L1L1' -- -- Cardpeek is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Cardpeek is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Cardpeek. If not, see <http://www.gnu.org/licenses/>. -- -- @name Calypso -- @description Calypso tranport cards: Navigo, MOBIB, Korrigo, RavKav, ... -- @targets 0.8 -- ------------------------------------------------------------------------- -- *PLEASE NOTE* -- This work is based on: -- * public information about the calypso card specification, -- * partial information found on the web about the ticketing data -- format, as described in the French "intercode" documentation. -- * experimentation and guesses, -- This information is incomplete. If you have further data, such -- as details ofd specs, please help send them -- to L1L1@gmx.com -------------------------------------------------------------------------- CARD = 0 card.CLA=0x94 -- Class for navigo cards SEL_BY_PATH = 1 SEL_BY_LFI = 2 sel_method = SEL_BY_LFI require('lib.strict') require('lib.country_codes') function bytes.is_all(bs,byte) local i,v if #bs==0 then return false end for i,v in bs:ipairs() do if v~=byte then return false end end return true end --[[ LFI_LIST = { { "ICC", "/0002", "file" }, { "ID", "/0003", "file" }, { "Ticketing", "/2000", "folder" }, { "Environment", "/2000/2001", "file" }, { "Holder", "/2000/2002", "file" }, { "Event logs", "/2000/2010", "file" }, { "Contracts", "/2000/2020", "file" }, { "Counters", "/2000/202A", "file" }, { "Counters", "/2000/202B", "file" }, { "Counters", "/2000/202C", "file" }, { "Counters", "/2000/202D", "file" }, { "Counters", "/2000/202E", "file" }, { "Counters", "/2000/202F", "file" }, { "Counters", "/2000/2060", "file" }, { "Counters", "/2000/2061", "file" }, { "Counters", "/2000/2062", "file" }, { "Special events", "/2000/2040", "file" }, { "Contract list", "/2000/2050", "file" }, { "Counters", "/2000/2069", "file" }, { "Holder Extended", "/3F1C", "file" } } --]] LFI_LIST = { { "AID", "/3F04", "file" }, { "ICC", "/0002", "file" }, { "ID", "/0003", "file" }, { "Holder Extended", "/3F1C", "file" }, { "Display / Free", "/2F10", "file" }, { "Ticketing", "/2000", "folder" }, { "AID", "/2000/2004", "file" }, { "Environment", "/2000/2001", "file" }, { "Holder", "/2000/2002", "file" }, { "Event logs", "/2000/2010", "file" }, { "Contracts", "/2000/2020", "file" }, { "Contracts", "/2000/2030", "file" }, { "Counters", "/2000/202A", "file" }, { "Counters", "/2000/202B", "file" }, { "Counters", "/2000/202C", "file" }, { "Counters", "/2000/202D", "file" }, { "Counters", "/2000/202E", "file" }, { "Counters", "/2000/202F", "file" }, { "Counters", "/2000/2060", "file" }, { "Counters", "/2000/2061", "file" }, { "Counters", "/2000/2062", "file" }, { "Counters", "/2000/2069", "file" }, { "Counters", "/2000/206A", "file" }, { "Special events", "/2000/2040", "file" }, { "Contract list", "/2000/2050", "file" }, { "Free", "/2000/20F0", "file" }, { "MPP", "/3100", "folder" }, { "AID", "/3100/3104", "file" }, { "Public Param.", "/3100/3102", "file" }, { "Log", "/3100/3115", "file" }, { "Contracts", "/3100/3120", "file" }, { "Counters", "/3100/3113", "file" }, { "Counters", "/3100/3123", "file" }, { "Counters", "/3100/3133", "file" }, { "Counters", "/3100/3169", "file" }, { "Miscellaneous", "/3100/3150", "file" }, { "Free", "/3100/31F0", "file" }, { "RT2", "/2100", "folder" }, { "AID", "/2100/2104", "file" }, { "Environment", "/2100/2101", "file" }, { "Event logs", "/2100/2110", "file" }, { "Contract list", "/2100/2150", "file" }, { "Contracts", "/2100/2120", "file" }, { "Counters", "/2100/2169", "file" }, { "Special events", "/2100/2140", "file" }, { "Free", "/2100/21F0", "file" }, { "EP", "/1000", "folder" }, { "AID", "/1000/1004", "file" }, { "Load Log", "/1000/1014", "file" }, { "Purchase Log", "/1000/1015", "file" }, { "eTicket", "/8000", "folder" }, { "AID", "/8000/8004", "file" }, { "Preselection", "/8000/8030", "file" }, { "Event logs", "/8000/8010", "file" } } function calypso_select(ctx,desc,path,klass) local path_parsed = card.make_file_path(path) local lfi = bytes.sub(path_parsed,-2) local resp, sw local r,item local parent_node=ctx local file_node=nil if sel_method==SEL_BY_LFI then sw,resp = card.select(bytes.format(lfi,"#%D")) else sw,resp = card.select(path) end if sw==0x9000 then for r=0,(#path_parsed/2)-1 do item = bytes.format(bytes.sub(path_parsed,r*2,r*2+1),"%D") file_node = parent_node:find_first({id=item}) if file_node==nil then file_node = parent_node:append{ classname = klass, label = desc, id = item } end parent_node = file_node end if resp and #resp>0 then parent_node:append{ classname="header", label="answer to select", size=#resp, val=resp} end return file_node end return nil end function calypso_guess_network(cardenv) local env_node local record_node local data env_node = cardenv:find_first({label="Environment"}) if env_node then record_node = env_node:find_first({label="record", id="1"}) if record_node then data = record_node:get_attribute("val"):convert(1) if #data > 36 then local country_bin = data:sub(13,24) local network_bin = data:sub(25,36) local country_num = tonumber(country_bin:convert(4):format("%D")) local network_num = tonumber(network_bin:convert(4):format("%D")) if country_num==250 or country_num==56 or country_num==131 then return country_num, network_num end country_bin = data:sub(3,14) network_bin = data:sub(15,22) country_num = tonumber(country_bin:convert(4):format("%D")) network_num = tonumber(network_bin:convert(4):format("%D")) if country_num==376 then return 376,network_num end log.print(log.WARNING,"Unknown Calypso card.") else log.print(log.WARNING,"Could not find enough data in 'Environement/record#1'") end else log.print(log.WARNING,"Could not find data in 'Environement/record#1'") end else log.print(log.WARNING,"Could not find data in 'Environement'") end return false end function calypso_process(cardenv) local lfi_index local lfi_desc local lfi_node local rec_node local sw, resp local country, network local filename, file for lfi_index,lfi_desc in ipairs(LFI_LIST) do lfi_node = calypso_select(cardenv,lfi_desc[1],lfi_desc[2], lfi_desc[3]) if lfi_node and lfi_desc[3]=="file" then local record for record=1,255 do sw,resp=card.read_record(0,record,0x1D) if sw ~= 0x9000 then break end rec_node = lfi_node:append{ classname = "record", label = "record", size = #resp, id = record, val = resp } end end end country, network = calypso_guess_network(cardenv) filename = "calypso/c"..country..".lua" file = io.open(filename); if file then io.close(file) dofile(filename) else log.print(log.LOG_INFO,"Could not find "..filename) end filename = "calypso/c"..country.."n"..network..".lua" file = io.open(filename); if file then io.close(file) dofile(filename) else log.print(log.LOG_INFO,"Could not find "..filename) end end if card.connect() then CARD = card.tree_startup("CALYPSO") sw = card.select("#2000") if sw==0x9000 then sel_method = SEL_BY_LFI else sw = card.select("/2000/2010") if sw == 0x9000 then sel_method = SEL_BY_PATH else sel_method = SEL_BY_LFI ui.question("This script may not work: this card doesn't seem to react to file selection commands.",{"OK"}) end end if sw~=0x6E00 then calypso_process(CARD) end card.disconnect() else ui.question("Connection to card failed. Are you sure a card is inserted in the reader or in proximity of a contactless reader?\n\nNote: French 'navigo' cards cannot be accessed through a contactless interface.",{"OK"}); end
gpl-3.0
bnetcc/darkstar
scripts/globals/weaponskills/armor_break.lua
3
1808
----------------------------------- -- Armor Break -- Great Axe weapon skill -- Skill level: 100 -- Lowers enemy's defense. Duration of effect varies with TP. -- Lowers defense by as much as 25% if unresisted. -- Strong against: Antica, Bats, Cockatrice, Dhalmel, Lizards, Mandragora, Worms. -- Immune: Ahriman. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: Wind -- Modifiers: STR:20% ; VIT:20% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.2; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.6; params.vit_wsc = 0.6; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then local duration = (120 + (tp/1000 * 60)) * applyResistanceAddEffect(player,target,ELE_WIND,0); target:addStatusEffect(EFFECT_DEFENSE_DOWN, 25, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
awesomeWM/awesome
tests/examples/sequences/client/swap_bydirection1.lua
1
1822
--DOC_GEN_IMAGE --DOC_NO_USAGE --DOC_HIDE_START local module = ... local awful = {tag = require("awful.tag"), layout = require("awful.layout"), client = require("awful.client"), screen = require("awful.screen")} require("awful.ewmh") screen[1]._resize {x = 0, width = 640, height = 360} screen.fake_add(660, 0, 640, 360) awful.tag({ "one", "two", "three" }, screen[1], awful.layout.suit.tile) awful.tag({ "one", "two", "three" }, screen[2], awful.layout.suit.tile) function awful.spawn(name, properties) client.gen_fake{class = name, name = name, x = 10, y=10, width = 60, height =50, screen = properties.screen} end module.add_event("Spawn some apps", function() for s in screen do for i = 1, 4 do awful.spawn("c"..((s.index -1)*4 + i), {screen = s}) end end client.focus = client.get()[3] client.focus.color = "#ff777733" end) module.display_tags() module.add_event('Call `swap.bydirection` to the top', function() --DOC_HIDE_END --DOC_NEWLINE -- It will go up in the same column. awful.client.swap.bydirection("up", client.focus) --DOC_HIDE_START end) --DOC_NEWLINE module.display_tags() module.add_event('Call `swap.bydirection` to the right', function() --DOC_HIDE_END --DOC_NEWLINE -- Nothing happens because it cannot change screen. awful.client.swap.bydirection("right", client.focus) --DOC_HIDE_START end) --DOC_NEWLINE module.display_tags() module.add_event('Call `swap.bydirection` to the left', function() --DOC_HIDE_END --DOC_NEWLINE -- Moves to the first column. awful.client.swap.bydirection("left", client.focus) --DOC_HIDE_START end) module.display_tags() module.execute { display_screen = true , display_clients = true , display_label = false, display_client_name = true }
gpl-2.0
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/applications/luci-pbx/luasrc/model/cbi/pbx-advanced.lua
99
14473
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end appname = "PBX" modulename = "pbx-advanced" defaultbindport = 5060 defaultrtpstart = 19850 defaultrtpend = 19900 -- Returns all the network related settings, including a constructed RTP range function get_network_info() externhost = m.uci:get(modulename, "advanced", "externhost") ipaddr = m.uci:get("network", "lan", "ipaddr") bindport = m.uci:get(modulename, "advanced", "bindport") rtpstart = m.uci:get(modulename, "advanced", "rtpstart") rtpend = m.uci:get(modulename, "advanced", "rtpend") if bindport == nil then bindport = defaultbindport end if rtpstart == nil then rtpstart = defaultrtpstart end if rtpend == nil then rtpend = defaultrtpend end if rtpstart == nil or rtpend == nil then rtprange = nil else rtprange = rtpstart .. "-" .. rtpend end return bindport, rtprange, ipaddr, externhost end -- If not present, insert empty rules in the given config & section named PBX-SIP and PBX-RTP function insert_empty_sip_rtp_rules(config, section) -- Add rules named PBX-SIP and PBX-RTP if not existing found_sip_rule = false found_rtp_rule = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' then found_sip_rule = true elseif s1._name == 'PBX-RTP' then found_rtp_rule = true end end) if found_sip_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-SIP') end if found_rtp_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-RTP') end end -- Delete rules in the given config & section named PBX-SIP and PBX-RTP function delete_sip_rtp_rules(config, section) -- Remove rules named PBX-SIP and PBX-RTP commit = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' or s1._name == 'PBX-RTP' then m.uci:delete(config, s1['.name']) commit = true end end) -- If something changed, then we commit the config. if commit == true then m.uci:commit(config) end end -- Deletes QoS rules associated with this PBX. function delete_qos_rules() delete_sip_rtp_rules ("qos", "classify") end function insert_qos_rules() -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("qos", "classify") -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() -- Iterate through the QoS rules, and if there is no other rule with the same port -- range at the priority service level, insert this rule. commit = false m.uci:foreach("qos", "classify", function(s1) if s1._name == 'PBX-SIP' then if s1.ports ~= bindport or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", bindport) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end elseif s1._name == 'PBX-RTP' then if s1.ports ~= rtprange or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", rtprange) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end end end) -- If something changed, then we commit the qos config. if commit == true then m.uci:commit("qos") end end -- This function is a (so far) unsuccessful attempt to manipulate the firewall rules from here -- Need to do more testing and eventually move to this mode. function maintain_firewall_rules() -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() commit = false -- Only if externhost is set, do we control firewall rules. if externhost ~= nil and bindport ~= nil and rtprange ~= nil then -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("firewall", "rule") -- Iterate through the firewall rules, and if the dest_port and dest_ip setting of the\ -- SIP and RTP rule do not match what we want configured, set all the entries in the rule\ -- appropriately. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then if s1.dest_port ~= bindport then m.uci:set("firewall", s1['.name'], "dest_port", bindport) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end elseif s1._name == 'PBX-RTP' then if s1.dest_port ~= rtprange then m.uci:set("firewall", s1['.name'], "dest_port", rtprange) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end end end) else -- We delete the firewall rules if one or more of the necessary parameters are not set. sip_rule_name=nil rtp_rule_name=nil -- First discover the configuration names of the rules. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then sip_rule_name = s1['.name'] elseif s1._name == 'PBX-RTP' then rtp_rule_name = s1['.name'] end end) -- Then, using the names, actually delete the rules. if sip_rule_name ~= nil then m.uci:delete("firewall", sip_rule_name) commit = true end if rtp_rule_name ~= nil then m.uci:delete("firewall", rtp_rule_name) commit = true end end -- If something changed, then we commit the firewall config. if commit == true then m.uci:commit("firewall") end end m = Map (modulename, translate("Advanced Settings"), translate("This section contains settings that do not need to be changed under \ normal circumstances. In addition, here you can configure your system \ for use with remote SIP devices, and resolve call quality issues by enabling \ the insertion of QoS rules.")) -- Recreate the voip server config, and restart necessary services after changes are commited -- to the advanced configuration. The firewall must restart because of "Remote Usage". function m.on_after_commit(self) -- Make sure firewall rules are in place maintain_firewall_rules() -- If insertion of QoS rules is enabled if m.uci:get(modulename, "advanced", "qos_enabled") == "yes" then insert_qos_rules() else delete_qos_rules() end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/firewall restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(NamedSection, "advanced", "settings", translate("Advanced Settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("remote_usage", translate("Remote Usage"), translatef("You can use your SIP devices/softphones with this system from a remote location \ as well, as long as your Internet Service Provider gives you a public IP. \ You will be able to call other local users for free (e.g. other Analog Telephone Adapters (ATAs)) \ and use your VoIP providers to make calls as if you were local to the PBX. \ After configuring this tab, go back to where users are configured and see the new \ Server and Port setting you need to configure the remote SIP devices with. Please note that if this \ PBX is not running on your router/gateway, you will need to configure port forwarding (NAT) on your \ router/gateway. Please forward the ports below (SIP port and RTP range) to the IP address of the \ device running this PBX.")) s:tab("qos", translate("QoS Settings"), translate("If you experience jittery or high latency audio during heavy downloads, you may want \ to enable QoS. QoS prioritizes traffic to and from your network for specified ports and IP \ addresses, resulting in better latency and throughput for sound in our case. If enabled below, \ a QoS rule for this service will be configured by the PBX automatically, but you must visit the \ QoS configuration page (Network->QoS) to configure other critical QoS settings like Download \ and Upload speed.")) ringtime = s:taboption("general", Value, "ringtime", translate("Number of Seconds to Ring"), translate("Set the number of seconds to ring users upon incoming calls before hanging up \ or going to voicemail, if the voicemail is installed and enabled.")) ringtime.datatype = "port" ringtime.default = 30 ua = s:taboption("general", Value, "useragent", translate("User Agent String"), translate("This is the name that the VoIP server will use to identify itself when \ registering to VoIP (SIP) providers. Some providers require this to a specific \ string matching a hardware SIP device.")) ua.default = appname h = s:taboption("remote_usage", Value, "externhost", translate("Domain/IP Address/Dynamic Domain"), translate("You can enter your domain name, external IP address, or dynamic domain name here. \ The best thing to input is a static IP address. If your IP address is dynamic and it changes, \ your configuration will become invalid. Hence, it's recommended to set up Dynamic DNS in this case. \ and enter your Dynamic DNS hostname here. You can configure Dynamic DNS with the luci-app-ddns package.")) h.datatype = "host" p = s:taboption("remote_usage", Value, "bindport", translate("External SIP Port"), translate("Pick a random port number between 6500 and 9500 for the service to listen on. \ Do not pick the standard 5060, because it is often subject to brute-force attacks. \ When finished, (1) click \"Save and Apply\", and (2) look in the \ \"SIP Device/Softphone Accounts\" section for updated Server and Port settings \ for your SIP Devices/Softphones.")) p.datatype = "port" p = s:taboption("remote_usage", Value, "rtpstart", translate("RTP Port Range Start"), translate("RTP traffic carries actual voice packets. This is the start of the port range \ that will be used for setting up RTP communication. It's usually OK to leave this \ at the default value.")) p.datatype = "port" p.default = defaultrtpstart p = s:taboption("remote_usage", Value, "rtpend", translate("RTP Port Range End")) p.datatype = "port" p.default = defaultrtpend p = s:taboption("qos", ListValue, "qos_enabled", translate("Insert QoS Rules")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
gpl-2.0
bnetcc/darkstar
scripts/globals/items/sacred_maul.lua
5
1224
----------------------------------------- -- ID: 18392 -- Item: Sacred Maul -- Additional Effect: Light Damage -- Enchantment: "Enlight" ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(7,21); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = msgBasic.ADD_EFFECT_DMG; if (dmg < 0) then message = msgBasic.ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end; function onItemCheck(target) return 0; end; function onItemUse(target) local effect = EFFECT_ENLIGHT; doEnspell(target,target,nil,effect); end;
gpl-3.0
freeciv/freeciv
dependencies/tolua-5.2/src/bin/lua/doit.lua
1
1151
-- Generate binding code -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- Last update: Apr 2003 -- $Id: doit.lua,v 1.3 2009/11/24 16:45:13 fabraham Exp $ -- 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 doit () -- define package name, if not provided if not flags.n then if flags.f then flags.n = gsub(flags.f,"%..*","") else error("#no package name nor input file provided") end end -- proccess package local p = Package(flags.n,flags.f) if flags.p then return -- only parse end if flags.o then local st,msg = writeto(flags.o) if not st then error('#'..msg) end end p:decltype() if flags.P then p:print() else p:preamble() p:supcode() p:register() end if flags.o then writeto() end -- write header file if not flags.P then if flags.H then local st,msg = writeto(flags.H) if not st then error('#'..msg) end p:header() writeto() end end end
gpl-2.0
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/modules/niu/luasrc/model/cbi/niu/wireless/ap.lua
51
1406
local cursor = require "luci.model.uci".cursor() if not cursor:get("wireless", "ap") then cursor:section("wireless", "wifi-iface", "ap", {device = "_", doth = "1", _niu = "1", mode = "ap"}) cursor:save("wireless") end local function deviceroute(self) cursor:unload("wireless") local d = cursor:get("wireless", "ap", "device") local t = cursor:get("wireless", "ap", "_cfgtpl") if d ~= "none" then cursor:delete_all("wireless", "wifi-iface", function(s) return s.device == d and s._niu ~= "1" end) cursor:set("wireless", d, "disabled", 0) cursor:set("wireless", "ap", "network", "lan") if t and #t > 0 then cursor:delete("wireless", "ap", "_cfgtpl") cursor:set("wireless", "ap", "ssid", cursor:get("wireless", "bridge", "ssid")) cursor:set("wireless", "ap", "encryption", cursor:get("wireless", "bridge", "encryption")) cursor:set("wireless", "ap", "key", cursor:get("wireless", "bridge", "key")) cursor:set("wireless", "ap", "wds", "1") end self:set_route("ap1") else cursor:delete("wireless", "ap", "network") end cursor:save("wireless") end local d = Delegator() d.allow_finish = true d.allow_back = true d.allow_cancel = true d:add("device", "niu/wireless/apdevice") d:add("deviceroute", deviceroute) d:set("ap1", "niu/wireless/ap1") function d.on_cancel() cursor:revert("wireless") end function d.on_done() cursor:commit("wireless") end return d
gpl-2.0
sylvanaar/prat-3-0
modules/ChannelNames.lua
1
19378
--------------------------------------------------------------------------------- -- -- Prat - A framework for World of Warcraft chat mods -- -- Copyright (C) 2006-2018 Prat Development Team -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to: -- -- Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- -- ------------------------------------------------------------------------------- Prat:AddModuleToLoad(function() local PRAT_MODULE = Prat:RequestModuleName("ChannelNames") if PRAT_MODULE == nil then return end local module = Prat:NewModule(PRAT_MODULE, "AceEvent-3.0", "AceTimer-3.0", "AceHook-3.0") local PL = module.PL --@debug@ PL:AddLocale(PRAT_MODULE, "enUS", { ["ChannelNames"] = true, ["Channel name abbreviation options."] = true, ["Replace"] = true, ["Toggle replacing this channel."] = true, ["Blank"] = true, ["Dont display the channel/chat type name"] = true, ["Set"] = true, ["Channel %d"] = true, ["%s settings."] = true, ["Use a custom replacement for the chat %s text."] = true, ["channelnick_name"] = "Channel Abbreviations", ["channelnick_desc"] = "Channel Abbreviations", ["Add Channel Abbreviation"] = true, ["addnick_desc"] = "Adds an abbreviated channel name. Prefix the name with '#' to include the channel number. (e.g. '#Trade').", ["Remove Channel Abbreviation"] = true, ["Removes an an abbreviated channel name."] = true, ["Clear Channel Abbreviation"] = true, ["Clears an abbreviated channel name."] = true, ["otheropts_name"] = "Other Options", ["otheropts_desc"] = "Additional channel formating options, and channel link controls.", ["space_name"] = "Show Space", ["space_desc"] = "Toggle adding space after channel replacement.", ["colon_name"] = "Show Colon", ["colon_desc"] = "Toggle adding colon after channel replacement.", ["chanlink_name"] = "Create Channel Link", ["chanlink_desc"] = "Make the channel a clickable link which opens chat to that channel.", ["<string>"] = true, }) --@end-debug@ -- These Localizations are auto-generated. To help with localization -- please go to http://www.wowace.com/projects/prat-3-0/localization/ --[===[@non-debug@ do local L --@localization(locale="enUS", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "enUS",L) --@localization(locale="frFR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "frFR",L) --@localization(locale="deDE", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "deDE",L) --@localization(locale="koKR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "koKR",L) --@localization(locale="esMX", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "esMX",L) --@localization(locale="ruRU", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "ruRU",L) --@localization(locale="zhCN", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "zhCN",L) --@localization(locale="esES", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "esES",L) --@localization(locale="zhTW", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChannelNames")@ PL:AddLocale(PRAT_MODULE, "zhTW",L) end --@end-non-debug@]===] -- order to show channels local orderMap = { "say", "whisper", "whisperincome", "yell", "party", "partyleader", "guild", "officer", "raid", "raidleader", "raidwarning", "instance", "instanceleader", "bnwhisper", "bnwhisperincome", "bnconversation", } if not CHAT_MSG_BN_WHISPER_INFORM then CHAT_MSG_BN_WHISPER_INFORM = "Outgoing Real ID Whisper"; end if not CHAT_MSG_INSTANCE_CHAT then CHAT_MSG_INSTANCE_CHAT = INSTANCE_CHAT_MESSAGE; end if not CHAT_MSG_INSTANCE_CHAT_LEADER then CHAT_MSG_INSTANCE_CHAT_LEADER = INSTANCE_CHAT_LEADER; end -- Look Up Our Settings Key event..message.CHANNUM local eventMap = { CHAT_MSG_CHANNEL1 = "channel1", CHAT_MSG_CHANNEL2 = "channel2", CHAT_MSG_CHANNEL3 = "channel3", CHAT_MSG_CHANNEL4 = "channel4", CHAT_MSG_CHANNEL5 = "channel5", CHAT_MSG_CHANNEL6 = "channel6", CHAT_MSG_CHANNEL7 = "channel7", CHAT_MSG_CHANNEL8 = "channel8", CHAT_MSG_CHANNEL9 = "channel9", -- CHAT_MSG_CHANNEL10 = "channel10", CHAT_MSG_SAY = "say", CHAT_MSG_GUILD = "guild", CHAT_MSG_WHISPER = "whisperincome", CHAT_MSG_WHISPER_INFORM = "whisper", CHAT_MSG_BN_WHISPER = "bnwhisperincome", CHAT_MSG_BN_WHISPER_INFORM = "bnwhisper", CHAT_MSG_YELL = "yell", CHAT_MSG_PARTY = "party", CHAT_MSG_PARTY_LEADER = "partyleader", CHAT_MSG_OFFICER = "officer", CHAT_MSG_RAID = "raid", CHAT_MSG_RAID_LEADER = "raidleader", CHAT_MSG_RAID_WARNING = "raidwarning", CHAT_MSG_INSTANCE_CHAT = "instance", CHAT_MSG_INSTANCE_CHAT_LEADER = "instanceleader", CHAT_MSG_BN_CONVERSATION = "bnconversation" } local CLR = Prat.CLR Prat:SetModuleDefaults(module.name, { profile = { on = true, space = true, colon = true, chanlink = true, replace = { say = true, whisper = true, whisperincome = true, bnwhisper = true, bnwhisperincome = true, yell = true, party = true, partyleader = true, guild = true, officer = true, raid = true, raidleader = true, raidwarning = true, instance = true, instanceleader = true, channel1 = true, channel2 = true, channel3 = true, channel4 = true, channel5 = true, channel6 = true, channel7 = true, channel8 = true, channel9 = true, channel10 = true, }, chanSave = {}, shortnames = -- zhCN PratCNlocal == "zhCN" and { say = "[说]", whisper = "[密]", whisperincome = "[收]", yell = "[喊]", party = "[队]", guild = "[会]", officer = "[管]", raid = "[团]", raidleader = "[酱]", raidwarning = "[警]", instance = "[战]", instanceleader = "[蟀]", channel1 = "[1]", channel2 = "[2]", channel3 = "[3]", channel4 = "[4]", channel5 = "[5]", channel6 = "[6]", channel7 = "[7]", channel8 = "[8]", channel9 = "[9]", channel10 = "[10]", } --zhTW or PratCNlocal == "zhTW" and { say = "[說]", whisper = "[密]", whisperincome = "[聽]", yell = "[喊]", party = "[隊]", guild = "[會]", officer = "[官]", raid = "[團]", raidleader = "[團長]", raidwarning = "[警]", instance = "[戰]", instanceleader = "[戰領]", channel1 = "[1]", channel2 = "[2]", channel3 = "[3]", channel4 = "[4]", channel5 = "[5]", channel6 = "[6]", channel7 = "[7]", channel8 = "[8]", channel9 = "[9]", channel10 = "[10]", } --koKR or PratCNlocal == "koKR" and { say = "[대화]", whisper = "[귓말]", whisperincome = "[받은귓말]", yell = "[외침]", party = "[파티]", guild = "[길드]", officer = "[오피서]", raid = "[공대]", raidleader = "[공대장]", raidwarning = "[공대경보]", instance = "[전장]", instanceleader = "[전투대장]", channel1 = "[1]", channel2 = "[2]", channel3 = "[3]", channel4 = "[4]", channel5 = "[5]", channel6 = "[6]", channel7 = "[7]", channel8 = "[8]", channel9 = "[9]", channel10 = "[10]", } --Other or { say = "[S]", whisper = "[W To]", whisperincome = "[W From]", bnwhisper = "[W To]", bnwhisperincome = "[W From]", yell = "[Y]", party = "[P]", partyleader = "[PL]", guild = "[G]", officer = "[O]", raid = "[R]", raidleader = "[RL]", raidwarning = "[RW]", instance = "[I]", instanceleader = "[IL]", channel1 = "[1]", channel2 = "[2]", channel3 = "[3]", channel4 = "[4]", channel5 = "[5]", channel6 = "[6]", channel7 = "[7]", channel8 = "[8]", channel9 = "[9]", channel10 = "[10]", }, nickname = {} } }) local eventPlugins = { types = {}, channels = {} } local nickPlugins = { nicks = {} } --- module.toggleOptions = { optsep227_sep = 227, optsep_sep = 229, space = 230, colon = 240, sep241_sep = 241, chanlink = 242 } Prat:SetModuleOptions(module.name, { name = PL["ChannelNames"], desc = PL["Channel name abbreviation options."], type = "group", childGroups = "tab", args = { etypes = { name = PL["ChannelNames"], desc = PL["Channel name abbreviation options."], type = "group", -- inline = true, order = 1, plugins = eventPlugins, args = {} }, ntypes = { name = PL["channelnick_name"], desc = PL["channelnick_desc"], order = 2, -- inline = true, type = "group", plugins = nickPlugins, args = {} }, ctypes = { name = PL["otheropts_name"], desc = PL["otheropts_desc"], order = 3, type = "group", args = { -- chanlink = { -- name = PL["chanlink_name"], -- desc = PL["chanlink_desc"], -- type = "toggle", }, space = { name = PL["space_name"], desc = PL["space_desc"], type = "toggle", }, colon = { name = PL["colon_name"], desc = PL["colon_desc"], type = "toggle", }, } }, } }) --[[------------------------------------------------ Module Event Functions ------------------------------------------------]] -- function module:OnModuleEnable() self:BuildChannelOptions() self:RegisterEvent("UPDATE_CHAT_COLOR", "RefreshOptions") self:RegisterEvent("CHAT_MSG_CHANNEL_NOTICE") Prat.RegisterChatEvent(self, "Prat_FrameMessage") -- Possible fix for channel messages not getting formatted Prat.EnableProcessingForEvent("CHAT_MSG_CHANNEL_NOTICE") Prat.EnableProcessingForEvent("CHAT_MSG_CHANNEL_NOTICE_USER") Prat.EnableProcessingForEvent("CHAT_MSG_CHANNEL_LEAVE") Prat.EnableProcessingForEvent("CHAT_MSG_CHANNEL_JOIN") end function module:OnModuleDisable() self:UnregisterAllEvents() Prat.UnregisterAllChatEvents(self) end function module:GetDescription() return PL["Channel name abbreviation options."] end --[[------------------------------------------------ Core Functions ------------------------------------------------]] -- -- rebuild menu if chat colors change function module:CHAT_MSG_CHANNEL_NOTICE() self:BuildChannelOptions() self:RefreshOptions() end function module:RefreshOptions() LibStub("AceConfigRegistry-3.0"):NotifyChange("Prat") end function module:AddNickname(info, name) self.db.profile.nickname[info[#info - 1]] = name end function module:RemoveNickname(info, name) if self.db.profile.nickname[info[#info - 1]] then self.db.profile.nickname[info[#info - 1]] = nil end end function module:GetNickname(info) return self.db.profile.nickname[info[#info - 1]] end function module:NotGetNickname(info) return (self:GetNickname(info) == nil) and true or false end -- replace text using prat event implementation function module:Prat_FrameMessage(arg, message, frame, event) -- if message.TYPEPREFIX:len()>0 and message.TYPEPOSTFIX:len()>0 then if event == "CHAT_MSG_CHANNEL_JOIN" or event == "CHAT_MSG_CHANNEL_LEAVE" then message.MESSAGE = message.ORG.TYPEPOSTFIX:trim() message.ORG.TYPEPOSTFIX = " " end if event == "CHAT_MSG_CHANNEL_NOTICE" or event == "CHAT_MSG_CHANNEL_NOTICE_USER" or event == "CHAT_MSG_CHANNEL_JOIN" or event == "CHAT_MSG_CHANNEL_LEAVE" then event = "CHAT_MSG_CHANNEL" end local cfg if event == "CHAT_MSG_BN_CONVERSATION" then cfg = eventMap[event] else cfg = eventMap[event .. (message.CHANNELNUM or "")] end if self.db.profile.nickname[message.CHANNEL] then message.CHANNEL = self.db.profile.nickname[message.CHANNEL] if message.CHANNEL:sub(1, 1) == "#" then message.CHANNEL = message.CHANNEL:sub(2) else message.CHANNELNUM, message.CC = "", "" end elseif self.db.profile.replace[cfg] then message.cC, message.CHANNELNUM, message.CC, message.CHANNEL, message.Cc = "", "", "", "", "" local space = self.db.profile.space and self.db.profile.shortnames[cfg] and self.db.profile.shortnames[cfg] ~= "" and " " or "" local colon = self.db.profile.colon and (message.PLAYERLINK:len() > 0 and message.MESSAGE:len() > 0) and ":" or "" message.TYPEPREFIX = self.db.profile.shortnames[cfg] or "" if message.TYPEPREFIX:len() == 0 then message.nN, message.NN, message.Nn, message.CHANLINK = "", "", "", "" end message.TYPEPREFIX = message.TYPEPREFIX .. space if (message.PLAYERLINK:len() > 0) or (message.TYPEPREFIX:len() > 0) then message.TYPEPOSTFIX = colon .. "\32" else message.TYPEPOSTFIX = "" end end -- end end --[[------------------------------------------------ Menu Builder Functions ------------------------------------------------]] -- function module:BuildChannelOptions() for _, v in ipairs(orderMap) do self:CreateTypeOption(eventPlugins["types"], v) end for i = 1, 9 do self:CreateChannelOption(eventPlugins["channels"], "channel" .. i, i) end local t = Prat.GetChannelTable() for k, v in pairs(t) do if type(v) == "string" then self:CreateChanNickOption(nickPlugins["nicks"], v) end end end function module:CreateChanNickOption(args, keyname) local text = keyname local name = keyname args[name] = args[name] or { name = text, desc = string.format(PL["%s settings."], text), type = "group", order = 228, args = { addnick = { name = PL["Add Channel Abbreviation"], desc = PL["addnick_desc"], type = "input", order = 140, usage = "<string>", get = "GetNickname", set = "AddNickname", }, removenick = { name = PL["Remove Channel Abbreviation"], desc = PL["Removes an an abbreviated channel name."], type = "execute", order = 150, func = "RemoveNickname", disabled = "NotGetNickname"; }, } } end function module:GetChanOptValue(info, ...) return self.db.profile[info[#info]][info[#info - 1]] end function module:SetChanOptValue(info, val, ...) self.db.profile[info[#info]][info[#info - 1]] = val end do local function revLookup(keyname) for k, v in pairs(eventMap) do if keyname == v then return k end end end local function GetChatCLR(name) if name == nil then return CLR.COLOR_NONE end local type = strsub(name, 10); local info = ChatTypeInfo[type]; if not info then return CLR.COLOR_NONE end return CLR:GetHexColor(info) end local function ChatType(text, type) return CLR:Colorize(GetChatCLR(type), text) end local optionGroup = { type = "group", name = function(info) return ChatType(_G[revLookup(info[#info])], revLookup(info[#info])) end, desc = function(info) return (PL["%s settings."]):format(_G[revLookup(info[#info])]) end, get = "GetChanOptValue", set = "SetChanOptValue", args = { shortnames = { name = function(info) return ChatType(_G[revLookup(info[#info - 1])], revLookup(info[#info - 1])) end, desc = function(info) return (PL["Use a custom replacement for the chat %s text."]):format(ChatType(_G[revLookup(info[#info - 1])], revLookup(info[#info - 1]))) end, order = 1, type = "input", usage = PL["<string>"], }, replace = { name = PL["Replace"], desc = PL["Toggle replacing this channel."], type = "toggle", order = 3, }, } } local optionGroupChan = { type = "group", name = function(info) return ChatType((PL["Channel %d"]):format(info[#info]:sub(-1)), revLookup(info[#info])) end, desc = function(info) return (PL["%s settings."]):format(ChatType((PL["Channel %d"]):format(info[#info]:sub(-1)), revLookup(info[#info]))) end, get = "GetChanOptValue", set = "SetChanOptValue", order = function(info) return 200 + tonumber(info[#info]:sub(-1)) end, args = { shortnames = { name = function(info) return ChatType((PL["Channel %d"]):format(info[#info - 1]:sub(-1)), revLookup(info[#info - 1])) end, desc = function(info) return (PL["Use a custom replacement for the chat %s text."]):format(ChatType((PL["Channel %d"]):format(info[#info - 1]:sub(-1)), revLookup(info[#info - 1]))) end, order = 1, type = "input", usage = PL["<string>"], }, replace = { name = PL["Replace"], desc = PL["Toggle replacing this channel."], type = "toggle", order = 3, }, } } function module:CreateTypeOption(args, keyname) if not args[keyname] then args[keyname] = optionGroup end end function module:CreateChannelOption(args, keyname, keynum) if not args[keyname] then args[keyname] = optionGroupChan end end end return end) -- Prat:AddModuleToLoad
gpl-3.0
Oneymus/Vyzor
component/padding.lua
1
3243
--- This Component defines the Padding of a @{Frame}. -- The Padding is between the Content and the @{Border}. -- -- See http://doc.qt.nokia.com/4.7-snapshot/stylesheet-customizing.html. -- @classmod Padding local Base = require("vyzor.base") local Padding = Base("Component", "Padding") --- Padding constructor. -- @function Padding -- @param ... A list of numbers defining the size of each side of the Padding Component. -- @treturn Padding local function new (_, ...) local arg = { ... } if not arg[1] then error("Vyzor: Must pass at least one size to a new Padding.", 2) end --- @type Padding local self = {} local _top = arg[1] local _right = arg[2] or _top local _bottom = arg[3] or _top local _left = arg[4] or _right local _stylesheet local function updateStylesheet () _stylesheet = string.format("padding: %s", table.concat({ _top, _right, _bottom, _left }, " ")) end --- Properties --- @section local properties = { Top = { --- Returns the size of the top of the Padding Component. -- @function self.Top.get -- @treturn number get = function () return _top end, --- Sets the size of top of the Padding Component. -- @function self.Top.set -- @tparam number value set = function (value) _top = value end, }, Right = { --- Returns the size of the right of the Padding Component. -- @function self.Right.get -- @treturn number get = function () return _right end, --- Sets the size of right of the Padding Component. -- @function self.Right.set -- @tparam number value set = function (value) _right = value end, }, Bottom = { --- Returns the size of the bottom of the Padding Component. -- @function self.Bottom.get -- @treturn number get = function () return _bottom end, --- Sets the size of bottom of the Padding Component. -- @function self.Bottom.set -- @tparam number value set = function (value) _bottom = value end, }, Left = { --- Returns the size of the left of the Padding Component. -- @function self.Left.get -- @treturn number get = function () return _left end, --- Sets the size of left of the Padding Component. -- @function self.Left.set -- @tparam number value set = function (value) _left = value end, }, Stylesheet = { --- Updates and returns the Padding's stylesheet. -- @function self.Stylesheet.get -- @treturn string get = function () if not _stylesheet then updateStylesheet() end return _stylesheet end, }, } --- @section end setmetatable(self, { __index = function (_, key) return (properties[key] and properties[key].get()) or Padding[key] end, __newindex = function (_, key, value) if properties[key] and properties[key].set then properties[key].set(value) end end, }) return self end setmetatable(Padding, { __index = getmetatable(Padding).__index, __call = new, }) return Padding
mit
erig0/textadept-vi
test/tests/range.lua
1
1080
-- Check parsing of ex ranges local assertEq = test.assertEq local log = test.log local ts = test.tostring local vi_mode_ex = require'vi_mode_ex' -- Have a file open test.open('1_100.txt') local ranges = { -- List of address string and expected result -- result: { { start, end }, nextpos } (nextpos is in the string) { '1,4xx', { { 1, 4 }, {'xx'} } }, { '4,8xx', { { 4, 8 }, {'xx'} } }, { '4+4,10xx', { { 8, 10}, {'xx'} } }, { '.,.+4xx yy', { { 7, 11 }, {'xx', 'yy'} } }, { '1,$blah', { { 1, 101 }, {'blah'}}}, { '/10/,3xx', { { 10, 3 }, {'xx'}}}, { '4,/10/xx', { { 4, 10 }, {'xx'}}}, { '4,/33/xx', { { 4, 33 }, {'xx'}}}, { ',$xx', { { 7, 101 }, {'xx'}}}, { ',17xx', { { 7, 17 }, {'xx'}}}, { '.xx', { { 7, 7 }, {'xx'}}}, { '55xx', { { 55, 55, }, {'xx'}}}, { '/66/xx', { { 66, 66, }, {'xx'}}}, } -- Start from line 7 buffer:goto_line(6) for _, data in pairs(ranges) do local addrstring = data[1] local cmd, addr = vi_mode_ex.parse_ex_cmd(addrstring) assertEq(cmd, data[2][2]) assertEq(addr, data[2][1]) end
mit
bnetcc/darkstar
scripts/zones/Lower_Delkfutts_Tower/npcs/Planar_Rift.lua
1
1816
----------------------------------- -- Area: Lower_Delkfutts_Tower -- NPC: Planar Rift ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local STRATUM = player:hasKeyItem(WHITE_STRATUM_ABYSSITE_III); local mobID = 17531126; local mobNotUp = false local correctNPC = false if (GetMobAction(mobID) == ACTION_NONE or GetMobAction(mobID) == ACTION_SPAWN) then mobNotUp = true; end if (npc:getXPos(421) and npc:getYPos(16.399) and npc:getZPos(-20)) then correctNPC = true; end if (STRATUM == true and mobNotUp == true and correctNPC == true) then if (player:getCurrency("voidstones") > 0) then player:startEvent(6000, 7); else player:startEvent(6000, 2); end else player:startEvent(6000); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 6000 and option == 1) then player:delCurrency("voidstones", 1); SpawnMob(17531126):updateClaim(player); end end;
gpl-3.0
Wiladams/LLUI
src/v4l2_controls.lua
1
35828
local bit = require("bit") local lshift, rshift, band, bor = bit.lshift, bit.rshift, bit.band, bit.bor local C = {} -- Control classes C.V4L2_CTRL_CLASS_USER = 0x00980000 -- Old-style 'user' controls C.V4L2_CTRL_CLASS_MPEG = 0x00990000 -- MPEG-compression controls C.V4L2_CTRL_CLASS_CAMERA = 0x009a0000 -- Camera class controls C.V4L2_CTRL_CLASS_FM_TX = 0x009b0000 -- FM Modulator controls C.V4L2_CTRL_CLASS_FLASH = 0x009c0000 -- Camera flash controls C.V4L2_CTRL_CLASS_JPEG = 0x009d0000 -- JPEG-compression controls C.V4L2_CTRL_CLASS_IMAGE_SOURCE = 0x009e0000 -- Image source controls C.V4L2_CTRL_CLASS_IMAGE_PROC = 0x009f0000 -- Image processing controls C.V4L2_CTRL_CLASS_DV = 0x00a00000 -- Digital Video controls C.V4L2_CTRL_CLASS_FM_RX = 0x00a10000 -- FM Receiver controls -- User-class control IDs C.V4L2_CID_BASE = bor(C.V4L2_CTRL_CLASS_USER, 0x900) C.V4L2_CID_USER_BASE = C.V4L2_CID_BASE C.V4L2_CID_USER_CLASS = bor(C.V4L2_CTRL_CLASS_USER, 1) C.V4L2_CID_BRIGHTNESS = (C.V4L2_CID_BASE+0) C.V4L2_CID_CONTRAST = (C.V4L2_CID_BASE+1) C.V4L2_CID_SATURATION = (C.V4L2_CID_BASE+2) C.V4L2_CID_HUE = (C.V4L2_CID_BASE+3) C.V4L2_CID_AUDIO_VOLUME = (C.V4L2_CID_BASE+5) C.V4L2_CID_AUDIO_BALANCE = (C.V4L2_CID_BASE+6) C.V4L2_CID_AUDIO_BASS = (C.V4L2_CID_BASE+7) C.V4L2_CID_AUDIO_TREBLE = (C.V4L2_CID_BASE+8) C.V4L2_CID_AUDIO_MUTE = (C.V4L2_CID_BASE+9) C.V4L2_CID_AUDIO_LOUDNESS = (C.V4L2_CID_BASE+10) C.V4L2_CID_BLACK_LEVEL = (C.V4L2_CID_BASE+11) -- Deprecated C.V4L2_CID_AUTO_WHITE_BALANCE = (C.V4L2_CID_BASE+12) C.V4L2_CID_DO_WHITE_BALANCE = (C.V4L2_CID_BASE+13) C.V4L2_CID_RED_BALANCE = (C.V4L2_CID_BASE+14) C.V4L2_CID_BLUE_BALANCE = (C.V4L2_CID_BASE+15) C.V4L2_CID_GAMMA = (C.V4L2_CID_BASE+16) C.V4L2_CID_WHITENESS = (C.V4L2_CID_GAMMA) -- Deprecated C.V4L2_CID_EXPOSURE = (C.V4L2_CID_BASE+17) C.V4L2_CID_AUTOGAIN = (C.V4L2_CID_BASE+18) C.V4L2_CID_GAIN = (C.V4L2_CID_BASE+19) C.V4L2_CID_HFLIP = (C.V4L2_CID_BASE+20) C.V4L2_CID_VFLIP = (C.V4L2_CID_BASE+21) C.V4L2_CID_POWER_LINE_FREQUENCY = (C.V4L2_CID_BASE+24) C.V4L2_CID_HUE_AUTO = (C.V4L2_CID_BASE+25) C.V4L2_CID_WHITE_BALANCE_TEMPERATURE = (C.V4L2_CID_BASE+26) C.V4L2_CID_SHARPNESS = (C.V4L2_CID_BASE+27) C.V4L2_CID_BACKLIGHT_COMPENSATION = (C.V4L2_CID_BASE+28) C.V4L2_CID_CHROMA_AGC = (C.V4L2_CID_BASE+29) C.V4L2_CID_COLOR_KILLER = (C.V4L2_CID_BASE+30) C.V4L2_CID_COLORFX = (C.V4L2_CID_BASE+31) C.V4L2_CID_AUTOBRIGHTNESS = (C.V4L2_CID_BASE+32) C.V4L2_CID_BAND_STOP_FILTER = (C.V4L2_CID_BASE+33) C.V4L2_CID_ROTATE = (C.V4L2_CID_BASE+34) C.V4L2_CID_BG_COLOR = (C.V4L2_CID_BASE+35) C.V4L2_CID_CHROMA_GAIN = (C.V4L2_CID_BASE+36) C.V4L2_CID_ILLUMINATORS_1 = (C.V4L2_CID_BASE+37) C.V4L2_CID_ILLUMINATORS_2 = (C.V4L2_CID_BASE+38) C.V4L2_CID_MIN_BUFFERS_FOR_CAPTURE = (C.V4L2_CID_BASE+39) C.V4L2_CID_MIN_BUFFERS_FOR_OUTPUT = (C.V4L2_CID_BASE+40) C.V4L2_CID_ALPHA_COMPONENT = (C.V4L2_CID_BASE+41) C.V4L2_CID_COLORFX_CBCR = (C.V4L2_CID_BASE+42) -- last CID + 1 C.V4L2_CID_LASTP1 = (C.V4L2_CID_BASE+43) -- USER-class private control IDs C.V4L2_CID_USER_MEYE_BASE = (C.V4L2_CID_USER_BASE + 0x1000) C.V4L2_CID_USER_BTTV_BASE = (C.V4L2_CID_USER_BASE + 0x1010) C.V4L2_CID_USER_S2255_BASE = (C.V4L2_CID_USER_BASE + 0x1030) C.V4L2_CID_USER_SI476X_BASE = (C.V4L2_CID_USER_BASE + 0x1040) C.V4L2_CID_USER_TI_VPE_BASE = (C.V4L2_CID_USER_BASE + 0x1050) C.V4L2_CID_MPEG_BASE = bor(C.V4L2_CTRL_CLASS_MPEG, 0x900) C.V4L2_CID_MPEG_CLASS = bor(C.V4L2_CTRL_CLASS_MPEG, 1) -- MPEG streams, specific to multiplexed streams C.V4L2_CID_MPEG_STREAM_TYPE = (C.V4L2_CID_MPEG_BASE+0) C.V4L2_CID_MPEG_STREAM_PID_PMT = (C.V4L2_CID_MPEG_BASE+1) C.V4L2_CID_MPEG_STREAM_PID_AUDIO = (C.V4L2_CID_MPEG_BASE+2) C.V4L2_CID_MPEG_STREAM_PID_VIDEO = (C.V4L2_CID_MPEG_BASE+3) C.V4L2_CID_MPEG_STREAM_PID_PCR = (C.V4L2_CID_MPEG_BASE+4) C.V4L2_CID_MPEG_STREAM_PES_ID_AUDIO = (C.V4L2_CID_MPEG_BASE+5) C.V4L2_CID_MPEG_STREAM_PES_ID_VIDEO = (C.V4L2_CID_MPEG_BASE+6) C.V4L2_CID_MPEG_STREAM_VBI_FMT = (C.V4L2_CID_MPEG_BASE+7) -- MPEG audio controls specific to multiplexed streams C.V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ = (C.V4L2_CID_MPEG_BASE+100) C.V4L2_CID_MPEG_AUDIO_ENCODING = (C.V4L2_CID_MPEG_BASE+101) C.V4L2_CID_MPEG_AUDIO_L1_BITRATE = (C.V4L2_CID_MPEG_BASE+102) C.V4L2_CID_MPEG_AUDIO_L2_BITRATE = (C.V4L2_CID_MPEG_BASE+103) C.V4L2_CID_MPEG_AUDIO_L3_BITRATE = (C.V4L2_CID_MPEG_BASE+104) C.V4L2_CID_MPEG_AUDIO_MODE = (C.V4L2_CID_MPEG_BASE+105) C.V4L2_CID_MPEG_AUDIO_MODE_EXTENSION = (C.V4L2_CID_MPEG_BASE+106) C.V4L2_CID_MPEG_AUDIO_EMPHASIS = (C.V4L2_CID_MPEG_BASE+107) C.V4L2_CID_MPEG_AUDIO_CRC = (C.V4L2_CID_MPEG_BASE+108) C.V4L2_CID_MPEG_AUDIO_MUTE = (C.V4L2_CID_MPEG_BASE+109) C.V4L2_CID_MPEG_AUDIO_AAC_BITRATE = (C.V4L2_CID_MPEG_BASE+110) C.V4L2_CID_MPEG_AUDIO_AC3_BITRATE = (C.V4L2_CID_MPEG_BASE+111) C.V4L2_CID_MPEG_AUDIO_DEC_PLAYBACK = (C.V4L2_CID_MPEG_BASE+112) C.V4L2_CID_MPEG_AUDIO_DEC_MULTILINGUAL_PLAYBACK = (C.V4L2_CID_MPEG_BASE+113) -- MPEG video controls specific to multiplexed streams C.V4L2_CID_MPEG_VIDEO_ENCODING = (C.V4L2_CID_MPEG_BASE+200) C.V4L2_CID_MPEG_VIDEO_ASPECT = (C.V4L2_CID_MPEG_BASE+201) C.V4L2_CID_MPEG_VIDEO_B_FRAMES = (C.V4L2_CID_MPEG_BASE+202) C.V4L2_CID_MPEG_VIDEO_GOP_SIZE = (C.V4L2_CID_MPEG_BASE+203) C.V4L2_CID_MPEG_VIDEO_GOP_CLOSURE = (C.V4L2_CID_MPEG_BASE+204) C.V4L2_CID_MPEG_VIDEO_PULLDOWN = (C.V4L2_CID_MPEG_BASE+205) C.V4L2_CID_MPEG_VIDEO_BITRATE_MODE = (C.V4L2_CID_MPEG_BASE+206) C.V4L2_CID_MPEG_VIDEO_BITRATE = (C.V4L2_CID_MPEG_BASE+207) C.V4L2_CID_MPEG_VIDEO_BITRATE_PEAK = (C.V4L2_CID_MPEG_BASE+208) C.V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION = (C.V4L2_CID_MPEG_BASE+209) C.V4L2_CID_MPEG_VIDEO_MUTE = (C.V4L2_CID_MPEG_BASE+210) C.V4L2_CID_MPEG_VIDEO_MUTE_YUV = (C.V4L2_CID_MPEG_BASE+211) C.V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE = (C.V4L2_CID_MPEG_BASE+212) C.V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER = (C.V4L2_CID_MPEG_BASE+213) C.V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB = (C.V4L2_CID_MPEG_BASE+214) C.V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE = (C.V4L2_CID_MPEG_BASE+215) C.V4L2_CID_MPEG_VIDEO_HEADER_MODE = (C.V4L2_CID_MPEG_BASE+216) C.V4L2_CID_MPEG_VIDEO_MAX_REF_PIC = (C.V4L2_CID_MPEG_BASE+217) C.V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE = (C.V4L2_CID_MPEG_BASE+218) C.V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES = (C.V4L2_CID_MPEG_BASE+219) C.V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB = (C.V4L2_CID_MPEG_BASE+220) C.V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE = (C.V4L2_CID_MPEG_BASE+221) C.V4L2_CID_MPEG_VIDEO_VBV_SIZE = (C.V4L2_CID_MPEG_BASE+222) C.V4L2_CID_MPEG_VIDEO_DEC_PTS = (C.V4L2_CID_MPEG_BASE+223) C.V4L2_CID_MPEG_VIDEO_DEC_FRAME = (C.V4L2_CID_MPEG_BASE+224) C.V4L2_CID_MPEG_VIDEO_VBV_DELAY = (C.V4L2_CID_MPEG_BASE+225) C.V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER = (C.V4L2_CID_MPEG_BASE+226) C.V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP = (C.V4L2_CID_MPEG_BASE+300) C.V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP = (C.V4L2_CID_MPEG_BASE+301) C.V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP = (C.V4L2_CID_MPEG_BASE+302) C.V4L2_CID_MPEG_VIDEO_H263_MIN_QP = (C.V4L2_CID_MPEG_BASE+303) C.V4L2_CID_MPEG_VIDEO_H263_MAX_QP = (C.V4L2_CID_MPEG_BASE+304) C.V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP = (C.V4L2_CID_MPEG_BASE+350) C.V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP = (C.V4L2_CID_MPEG_BASE+351) C.V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP = (C.V4L2_CID_MPEG_BASE+352) C.V4L2_CID_MPEG_VIDEO_H264_MIN_QP = (C.V4L2_CID_MPEG_BASE+353) C.V4L2_CID_MPEG_VIDEO_H264_MAX_QP = (C.V4L2_CID_MPEG_BASE+354) C.V4L2_CID_MPEG_VIDEO_H264_8X8_TRANSFORM = (C.V4L2_CID_MPEG_BASE+355) C.V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE = (C.V4L2_CID_MPEG_BASE+356) C.V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE = (C.V4L2_CID_MPEG_BASE+357) C.V4L2_CID_MPEG_VIDEO_H264_I_PERIOD = (C.V4L2_CID_MPEG_BASE+358) C.V4L2_CID_MPEG_VIDEO_H264_LEVEL = (C.V4L2_CID_MPEG_BASE+359) C.V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA = (C.V4L2_CID_MPEG_BASE+360) C.V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA = (C.V4L2_CID_MPEG_BASE+361) C.V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE = (C.V4L2_CID_MPEG_BASE+362) C.V4L2_CID_MPEG_VIDEO_H264_PROFILE = (C.V4L2_CID_MPEG_BASE+363) C.V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT = (C.V4L2_CID_MPEG_BASE+364) C.V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH = (C.V4L2_CID_MPEG_BASE+365) C.V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_ENABLE = (C.V4L2_CID_MPEG_BASE+366) C.V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_IDC = (C.V4L2_CID_MPEG_BASE+367) C.V4L2_CID_MPEG_VIDEO_H264_SEI_FRAME_PACKING = (C.V4L2_CID_MPEG_BASE+368) C.V4L2_CID_MPEG_VIDEO_H264_SEI_FP_CURRENT_FRAME_0 = (C.V4L2_CID_MPEG_BASE+369) C.V4L2_CID_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE = (C.V4L2_CID_MPEG_BASE+370) C.V4L2_CID_MPEG_VIDEO_H264_FMO = (C.V4L2_CID_MPEG_BASE+371) C.V4L2_CID_MPEG_VIDEO_H264_FMO_MAP_TYPE = (C.V4L2_CID_MPEG_BASE+372) C.V4L2_CID_MPEG_VIDEO_H264_FMO_SLICE_GROUP = (C.V4L2_CID_MPEG_BASE+373) C.V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_DIRECTION = (C.V4L2_CID_MPEG_BASE+374) C.V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_RATE = (C.V4L2_CID_MPEG_BASE+375) C.V4L2_CID_MPEG_VIDEO_H264_FMO_RUN_LENGTH = (C.V4L2_CID_MPEG_BASE+376) C.V4L2_CID_MPEG_VIDEO_H264_ASO = (C.V4L2_CID_MPEG_BASE+377) C.V4L2_CID_MPEG_VIDEO_H264_ASO_SLICE_ORDER = (C.V4L2_CID_MPEG_BASE+378) C.V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING = (C.V4L2_CID_MPEG_BASE+379) C.V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_TYPE = (C.V4L2_CID_MPEG_BASE+380) C.V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER = (C.V4L2_CID_MPEG_BASE+381) C.V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER_QP = (C.V4L2_CID_MPEG_BASE+382) C.V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP = (C.V4L2_CID_MPEG_BASE+400) C.V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP = (C.V4L2_CID_MPEG_BASE+401) C.V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP = (C.V4L2_CID_MPEG_BASE+402) C.V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP = (C.V4L2_CID_MPEG_BASE+403) C.V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP = (C.V4L2_CID_MPEG_BASE+404) C.V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL = (C.V4L2_CID_MPEG_BASE+405) C.V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE = (C.V4L2_CID_MPEG_BASE+406) C.V4L2_CID_MPEG_VIDEO_MPEG4_QPEL = (C.V4L2_CID_MPEG_BASE+407) C.V4L2_CID_MPEG_VIDEO_VPX_NUM_PARTITIONS = (C.V4L2_CID_MPEG_BASE+500) C.V4L2_CID_MPEG_VIDEO_VPX_IMD_DISABLE_4X4 = (C.V4L2_CID_MPEG_BASE+501) C.V4L2_CID_MPEG_VIDEO_VPX_NUM_REF_FRAMES = (C.V4L2_CID_MPEG_BASE+502) C.V4L2_CID_MPEG_VIDEO_VPX_FILTER_LEVEL = (C.V4L2_CID_MPEG_BASE+503) C.V4L2_CID_MPEG_VIDEO_VPX_FILTER_SHARPNESS = (C.V4L2_CID_MPEG_BASE+504) C.V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_REF_PERIOD = (C.V4L2_CID_MPEG_BASE+505) C.V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_SEL = (C.V4L2_CID_MPEG_BASE+506) -- MPEG-class control IDs specific to the CX2341x driver as defined by V4L2 C.V4L2_CID_MPEG_CX2341X_BASE = bor(C.V4L2_CTRL_CLASS_MPEG, 0x1000) C.V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE = (C.V4L2_CID_MPEG_CX2341X_BASE+0) C.V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER = (C.V4L2_CID_MPEG_CX2341X_BASE+1) C.V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE = (C.V4L2_CID_MPEG_CX2341X_BASE+2) C.V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE = (C.V4L2_CID_MPEG_CX2341X_BASE+3) C.V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE = (C.V4L2_CID_MPEG_CX2341X_BASE+4) C.V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER = (C.V4L2_CID_MPEG_CX2341X_BASE+5) C.V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE = (C.V4L2_CID_MPEG_CX2341X_BASE+6) C.V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM = (C.V4L2_CID_MPEG_CX2341X_BASE+7) C.V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP = (C.V4L2_CID_MPEG_CX2341X_BASE+8) C.V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM = (C.V4L2_CID_MPEG_CX2341X_BASE+9) C.V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP = (C.V4L2_CID_MPEG_CX2341X_BASE+10) C.V4L2_CID_MPEG_CX2341X_STREAM_INSERT_NAV_PACKETS = (C.V4L2_CID_MPEG_CX2341X_BASE+11) -- MPEG-class control IDs specific to the Samsung MFC 5.1 driver as defined by V4L2 C.V4L2_CID_MPEG_MFC51_BASE = bor(C.V4L2_CTRL_CLASS_MPEG, 0x1100) C.V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY = (C.V4L2_CID_MPEG_MFC51_BASE+0) C.V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE = (C.V4L2_CID_MPEG_MFC51_BASE+1) C.V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE = (C.V4L2_CID_MPEG_MFC51_BASE+2) C.V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE = (C.V4L2_CID_MPEG_MFC51_BASE+3) C.V4L2_CID_MPEG_MFC51_VIDEO_PADDING = (C.V4L2_CID_MPEG_MFC51_BASE+4) C.V4L2_CID_MPEG_MFC51_VIDEO_PADDING_YUV = (C.V4L2_CID_MPEG_MFC51_BASE+5) C.V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT = (C.V4L2_CID_MPEG_MFC51_BASE+6) C.V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF = (C.V4L2_CID_MPEG_MFC51_BASE+7) C.V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_ACTIVITY = (C.V4L2_CID_MPEG_MFC51_BASE+50) C.V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_DARK = (C.V4L2_CID_MPEG_MFC51_BASE+51) C.V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_SMOOTH = (C.V4L2_CID_MPEG_MFC51_BASE+52) C.V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_STATIC = (C.V4L2_CID_MPEG_MFC51_BASE+53) C.V4L2_CID_MPEG_MFC51_VIDEO_H264_NUM_REF_PIC_FOR_P = (C.V4L2_CID_MPEG_MFC51_BASE+54) -- Camera class control IDs C.V4L2_CID_CAMERA_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_CAMERA, 0x900) C.V4L2_CID_CAMERA_CLASS = bor(C.V4L2_CTRL_CLASS_CAMERA, 1) C.V4L2_CID_EXPOSURE_AUTO = (C.V4L2_CID_CAMERA_CLASS_BASE+1) C.V4L2_CID_EXPOSURE_ABSOLUTE = (C.V4L2_CID_CAMERA_CLASS_BASE+2) C.V4L2_CID_EXPOSURE_AUTO_PRIORITY = (C.V4L2_CID_CAMERA_CLASS_BASE+3) C.V4L2_CID_PAN_RELATIVE = (C.V4L2_CID_CAMERA_CLASS_BASE+4) C.V4L2_CID_TILT_RELATIVE = (C.V4L2_CID_CAMERA_CLASS_BASE+5) C.V4L2_CID_PAN_RESET = (C.V4L2_CID_CAMERA_CLASS_BASE+6) C.V4L2_CID_TILT_RESET = (C.V4L2_CID_CAMERA_CLASS_BASE+7) C.V4L2_CID_PAN_ABSOLUTE = (C.V4L2_CID_CAMERA_CLASS_BASE+8) C.V4L2_CID_TILT_ABSOLUTE = (C.V4L2_CID_CAMERA_CLASS_BASE+9) C.V4L2_CID_FOCUS_ABSOLUTE = (C.V4L2_CID_CAMERA_CLASS_BASE+10) C.V4L2_CID_FOCUS_RELATIVE = (C.V4L2_CID_CAMERA_CLASS_BASE+11) C.V4L2_CID_FOCUS_AUTO = (C.V4L2_CID_CAMERA_CLASS_BASE+12) C.V4L2_CID_ZOOM_ABSOLUTE = (C.V4L2_CID_CAMERA_CLASS_BASE+13) C.V4L2_CID_ZOOM_RELATIVE = (C.V4L2_CID_CAMERA_CLASS_BASE+14) C.V4L2_CID_ZOOM_CONTINUOUS = (C.V4L2_CID_CAMERA_CLASS_BASE+15) C.V4L2_CID_PRIVACY = (C.V4L2_CID_CAMERA_CLASS_BASE+16) C.V4L2_CID_IRIS_ABSOLUTE = (C.V4L2_CID_CAMERA_CLASS_BASE+17) C.V4L2_CID_IRIS_RELATIVE = (C.V4L2_CID_CAMERA_CLASS_BASE+18) C.V4L2_CID_AUTO_EXPOSURE_BIAS = (C.V4L2_CID_CAMERA_CLASS_BASE+19) C.V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE = (C.V4L2_CID_CAMERA_CLASS_BASE+20) C.V4L2_CID_WIDE_DYNAMIC_RANGE = (C.V4L2_CID_CAMERA_CLASS_BASE+21) C.V4L2_CID_IMAGE_STABILIZATION = (C.V4L2_CID_CAMERA_CLASS_BASE+22) C.V4L2_CID_ISO_SENSITIVITY = (C.V4L2_CID_CAMERA_CLASS_BASE+23) C.V4L2_CID_ISO_SENSITIVITY_AUTO = (C.V4L2_CID_CAMERA_CLASS_BASE+24) C.V4L2_CID_EXPOSURE_METERING = (C.V4L2_CID_CAMERA_CLASS_BASE+25) C.V4L2_CID_SCENE_MODE = (C.V4L2_CID_CAMERA_CLASS_BASE+26) C.V4L2_CID_3A_LOCK = (C.V4L2_CID_CAMERA_CLASS_BASE+27) C.V4L2_LOCK_EXPOSURE = 1; C.V4L2_LOCK_WHITE_BALANCE = 2; C.V4L2_LOCK_FOCUS = 4; C.V4L2_CID_AUTO_FOCUS_START = (C.V4L2_CID_CAMERA_CLASS_BASE+28) C.V4L2_CID_AUTO_FOCUS_STOP = (C.V4L2_CID_CAMERA_CLASS_BASE+29) C.V4L2_CID_AUTO_FOCUS_STATUS = (C.V4L2_CID_CAMERA_CLASS_BASE+30) C.V4L2_AUTO_FOCUS_STATUS_IDLE = 0; C.V4L2_AUTO_FOCUS_STATUS_BUSY = 1; C.V4L2_AUTO_FOCUS_STATUS_REACHED = 2; C.V4L2_AUTO_FOCUS_STATUS_FAILED = 4; C.V4L2_CID_AUTO_FOCUS_RANGE = (C.V4L2_CID_CAMERA_CLASS_BASE+31) -- FM Modulator class control IDs C.V4L2_CID_FM_TX_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_FM_TX, 0x900) C.V4L2_CID_FM_TX_CLASS = bor(C.V4L2_CTRL_CLASS_FM_TX, 1) C.V4L2_CID_RDS_TX_DEVIATION = (C.V4L2_CID_FM_TX_CLASS_BASE + 1) C.V4L2_CID_RDS_TX_PI = (C.V4L2_CID_FM_TX_CLASS_BASE + 2) C.V4L2_CID_RDS_TX_PTY = (C.V4L2_CID_FM_TX_CLASS_BASE + 3) C.V4L2_CID_RDS_TX_PS_NAME = (C.V4L2_CID_FM_TX_CLASS_BASE + 5) C.V4L2_CID_RDS_TX_RADIO_TEXT = (C.V4L2_CID_FM_TX_CLASS_BASE + 6) C.V4L2_CID_AUDIO_LIMITER_ENABLED = (C.V4L2_CID_FM_TX_CLASS_BASE + 64) C.V4L2_CID_AUDIO_LIMITER_RELEASE_TIME = (C.V4L2_CID_FM_TX_CLASS_BASE + 65) C.V4L2_CID_AUDIO_LIMITER_DEVIATION = (C.V4L2_CID_FM_TX_CLASS_BASE + 66) C.V4L2_CID_AUDIO_COMPRESSION_ENABLED = (C.V4L2_CID_FM_TX_CLASS_BASE + 80) C.V4L2_CID_AUDIO_COMPRESSION_GAIN = (C.V4L2_CID_FM_TX_CLASS_BASE + 81) C.V4L2_CID_AUDIO_COMPRESSION_THRESHOLD = (C.V4L2_CID_FM_TX_CLASS_BASE + 82) C.V4L2_CID_AUDIO_COMPRESSION_ATTACK_TIME = (C.V4L2_CID_FM_TX_CLASS_BASE + 83) C.V4L2_CID_AUDIO_COMPRESSION_RELEASE_TIME = (C.V4L2_CID_FM_TX_CLASS_BASE + 84) C.V4L2_CID_PILOT_TONE_ENABLED = (C.V4L2_CID_FM_TX_CLASS_BASE + 96) C.V4L2_CID_PILOT_TONE_DEVIATION = (C.V4L2_CID_FM_TX_CLASS_BASE + 97) C.V4L2_CID_PILOT_TONE_FREQUENCY = (C.V4L2_CID_FM_TX_CLASS_BASE + 98) C.V4L2_CID_TUNE_PREEMPHASIS = (C.V4L2_CID_FM_TX_CLASS_BASE + 112) C.V4L2_CID_TUNE_POWER_LEVEL = (C.V4L2_CID_FM_TX_CLASS_BASE + 113) C.V4L2_CID_TUNE_ANTENNA_CAPACITOR = (C.V4L2_CID_FM_TX_CLASS_BASE + 114) -- Flash and privacy = (indicator) light controls C.V4L2_CID_FLASH_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_FLASH, 0x900) C.V4L2_CID_FLASH_CLASS = bor(C.V4L2_CTRL_CLASS_FLASH, 1) C.V4L2_CID_FLASH_LED_MODE = (C.V4L2_CID_FLASH_CLASS_BASE + 1) C.V4L2_CID_FLASH_STROBE_SOURCE = (C.V4L2_CID_FLASH_CLASS_BASE + 2) C.V4L2_CID_FLASH_STROBE = (C.V4L2_CID_FLASH_CLASS_BASE + 3) C.V4L2_CID_FLASH_STROBE_STOP = (C.V4L2_CID_FLASH_CLASS_BASE + 4) C.V4L2_CID_FLASH_STROBE_STATUS = (C.V4L2_CID_FLASH_CLASS_BASE + 5) C.V4L2_CID_FLASH_TIMEOUT = (C.V4L2_CID_FLASH_CLASS_BASE + 6) C.V4L2_CID_FLASH_INTENSITY = (C.V4L2_CID_FLASH_CLASS_BASE + 7) C.V4L2_CID_FLASH_TORCH_INTENSITY = (C.V4L2_CID_FLASH_CLASS_BASE + 8) C.V4L2_CID_FLASH_INDICATOR_INTENSITY = (C.V4L2_CID_FLASH_CLASS_BASE + 9) C.V4L2_CID_FLASH_FAULT = (C.V4L2_CID_FLASH_CLASS_BASE + 10) C.V4L2_FLASH_FAULT_OVER_VOLTAGE = 1; C.V4L2_FLASH_FAULT_TIMEOUT = 2; C.V4L2_FLASH_FAULT_OVER_TEMPERATURE = 4; C.V4L2_FLASH_FAULT_SHORT_CIRCUIT = 8; C.V4L2_FLASH_FAULT_OVER_CURRENT = 16; C.V4L2_FLASH_FAULT_INDICATOR = 32; C.V4L2_CID_FLASH_CHARGE = (C.V4L2_CID_FLASH_CLASS_BASE + 11) C.V4L2_CID_FLASH_READY = (C.V4L2_CID_FLASH_CLASS_BASE + 12) -- JPEG-class control IDs C.V4L2_CID_JPEG_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_JPEG, 0x900) C.V4L2_CID_JPEG_CLASS = bor(C.V4L2_CTRL_CLASS_JPEG, 1) C.V4L2_CID_JPEG_CHROMA_SUBSAMPLING = (C.V4L2_CID_JPEG_CLASS_BASE + 1) C.V4L2_CID_JPEG_RESTART_INTERVAL = (C.V4L2_CID_JPEG_CLASS_BASE + 2) C.V4L2_CID_JPEG_COMPRESSION_QUALITY = (C.V4L2_CID_JPEG_CLASS_BASE + 3) C.V4L2_CID_JPEG_ACTIVE_MARKER = (C.V4L2_CID_JPEG_CLASS_BASE + 4) C.V4L2_JPEG_ACTIVE_MARKER_APP0 = lshift(1, 0) C.V4L2_JPEG_ACTIVE_MARKER_APP1 = lshift(1, 1) C.V4L2_JPEG_ACTIVE_MARKER_COM = lshift(1, 16) C.V4L2_JPEG_ACTIVE_MARKER_DQT = lshift(1, 17) C.V4L2_JPEG_ACTIVE_MARKER_DHT = lshift(1, 18) -- Image source controls C.V4L2_CID_IMAGE_SOURCE_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_IMAGE_SOURCE, 0x900) C.V4L2_CID_IMAGE_SOURCE_CLASS = bor(C.V4L2_CTRL_CLASS_IMAGE_SOURCE, 1) C.V4L2_CID_VBLANK = (C.V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 1) C.V4L2_CID_HBLANK = (C.V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 2) C.V4L2_CID_ANALOGUE_GAIN = (C.V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 3) -- Image processing controls C.V4L2_CID_IMAGE_PROC_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_IMAGE_PROC, 0x900) C.V4L2_CID_IMAGE_PROC_CLASS = bor(C.V4L2_CTRL_CLASS_IMAGE_PROC, 1) C.V4L2_CID_LINK_FREQ = (C.V4L2_CID_IMAGE_PROC_CLASS_BASE + 1) C.V4L2_CID_PIXEL_RATE = (C.V4L2_CID_IMAGE_PROC_CLASS_BASE + 2) C.V4L2_CID_TEST_PATTERN = (C.V4L2_CID_IMAGE_PROC_CLASS_BASE + 3) -- DV-class control IDs defined by V4L2 C.V4L2_CID_DV_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_DV, 0x900) C.V4L2_CID_DV_CLASS = bor(C.V4L2_CTRL_CLASS_DV, 1) C.V4L2_CID_DV_TX_HOTPLUG = (C.V4L2_CID_DV_CLASS_BASE + 1) C.V4L2_CID_DV_TX_RXSENSE = (C.V4L2_CID_DV_CLASS_BASE + 2) C.V4L2_CID_DV_TX_EDID_PRESENT = (C.V4L2_CID_DV_CLASS_BASE + 3) C.V4L2_CID_DV_TX_MODE = (C.V4L2_CID_DV_CLASS_BASE + 4) C.V4L2_CID_DV_TX_RGB_RANGE = (C.V4L2_CID_DV_CLASS_BASE + 5) C.V4L2_CID_DV_RX_POWER_PRESENT = (C.V4L2_CID_DV_CLASS_BASE + 100) C.V4L2_CID_DV_RX_RGB_RANGE = (C.V4L2_CID_DV_CLASS_BASE + 101) C.V4L2_CID_FM_RX_CLASS_BASE = bor(C.V4L2_CTRL_CLASS_FM_RX, 0x900) C.V4L2_CID_FM_RX_CLASS = bor(C.V4L2_CTRL_CLASS_FM_RX, 1) C.V4L2_CID_TUNE_DEEMPHASIS = (C.V4L2_CID_FM_RX_CLASS_BASE + 1) C.V4L2_CID_RDS_RECEPTION = (C.V4L2_CID_FM_RX_CLASS_BASE + 2) local Enums = { v4l2_power_line_frequency = { V4L2_CID_POWER_LINE_FREQUENCY_DISABLED = 0, V4L2_CID_POWER_LINE_FREQUENCY_50HZ = 1, V4L2_CID_POWER_LINE_FREQUENCY_60HZ = 2, V4L2_CID_POWER_LINE_FREQUENCY_AUTO = 3, }; v4l2_colorfx = { V4L2_COLORFX_NONE = 0, V4L2_COLORFX_BW = 1, V4L2_COLORFX_SEPIA = 2, V4L2_COLORFX_NEGATIVE = 3, V4L2_COLORFX_EMBOSS = 4, V4L2_COLORFX_SKETCH = 5, V4L2_COLORFX_SKY_BLUE = 6, V4L2_COLORFX_GRASS_GREEN = 7, V4L2_COLORFX_SKIN_WHITEN = 8, V4L2_COLORFX_VIVID = 9, V4L2_COLORFX_AQUA = 10, V4L2_COLORFX_ART_FREEZE = 11, V4L2_COLORFX_SILHOUETTE = 12, V4L2_COLORFX_SOLARIZATION = 13, V4L2_COLORFX_ANTIQUE = 14, V4L2_COLORFX_SET_CBCR = 15, }; v4l2_mpeg_stream_type = { V4L2_MPEG_STREAM_TYPE_MPEG2_PS = 0, -- MPEG-2 program stream V4L2_MPEG_STREAM_TYPE_MPEG2_TS = 1, -- MPEG-2 transport stream V4L2_MPEG_STREAM_TYPE_MPEG1_SS = 2, -- MPEG-1 system stream V4L2_MPEG_STREAM_TYPE_MPEG2_DVD = 3, -- MPEG-2 DVD-compatible stream V4L2_MPEG_STREAM_TYPE_MPEG1_VCD = 4, -- MPEG-1 VCD-compatible stream V4L2_MPEG_STREAM_TYPE_MPEG2_SVCD = 5, -- MPEG-2 SVCD-compatible stream }; v4l2_mpeg_audio_mode = { V4L2_MPEG_AUDIO_MODE_STEREO = 0, V4L2_MPEG_AUDIO_MODE_JOINT_STEREO = 1, V4L2_MPEG_AUDIO_MODE_DUAL = 2, V4L2_MPEG_AUDIO_MODE_MONO = 3, }; v4l2_mpeg_audio_mode_extension = { V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_4 = 0, V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_8 = 1, V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_12 = 2, V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_16 = 3, }; v4l2_mpeg_audio_emphasis = { V4L2_MPEG_AUDIO_EMPHASIS_NONE = 0, V4L2_MPEG_AUDIO_EMPHASIS_50_DIV_15_uS = 1, V4L2_MPEG_AUDIO_EMPHASIS_CCITT_J17 = 2, }; v4l2_mpeg_audio_crc = { V4L2_MPEG_AUDIO_CRC_NONE = 0, V4L2_MPEG_AUDIO_CRC_CRC16 = 1, }; v4l2_mpeg_audio_ac3_bitrate = { V4L2_MPEG_AUDIO_AC3_BITRATE_32K = 0, V4L2_MPEG_AUDIO_AC3_BITRATE_40K = 1, V4L2_MPEG_AUDIO_AC3_BITRATE_48K = 2, V4L2_MPEG_AUDIO_AC3_BITRATE_56K = 3, V4L2_MPEG_AUDIO_AC3_BITRATE_64K = 4, V4L2_MPEG_AUDIO_AC3_BITRATE_80K = 5, V4L2_MPEG_AUDIO_AC3_BITRATE_96K = 6, V4L2_MPEG_AUDIO_AC3_BITRATE_112K = 7, V4L2_MPEG_AUDIO_AC3_BITRATE_128K = 8, V4L2_MPEG_AUDIO_AC3_BITRATE_160K = 9, V4L2_MPEG_AUDIO_AC3_BITRATE_192K = 10, V4L2_MPEG_AUDIO_AC3_BITRATE_224K = 11, V4L2_MPEG_AUDIO_AC3_BITRATE_256K = 12, V4L2_MPEG_AUDIO_AC3_BITRATE_320K = 13, V4L2_MPEG_AUDIO_AC3_BITRATE_384K = 14, V4L2_MPEG_AUDIO_AC3_BITRATE_448K = 15, V4L2_MPEG_AUDIO_AC3_BITRATE_512K = 16, V4L2_MPEG_AUDIO_AC3_BITRATE_576K = 17, V4L2_MPEG_AUDIO_AC3_BITRATE_640K = 18, }; v4l2_mpeg_stream_vbi_fmt = { V4L2_MPEG_STREAM_VBI_FMT_NONE = 0, -- No VBI in the MPEG stream V4L2_MPEG_STREAM_VBI_FMT_IVTV = 1, -- VBI in private packets, IVTV format }; v4l2_mpeg_audio_sampling_freq = { V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100 = 0, V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000 = 1, V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000 = 2, }; v4l2_mpeg_audio_encoding = { V4L2_MPEG_AUDIO_ENCODING_LAYER_1 = 0, V4L2_MPEG_AUDIO_ENCODING_LAYER_2 = 1, V4L2_MPEG_AUDIO_ENCODING_LAYER_3 = 2, V4L2_MPEG_AUDIO_ENCODING_AAC = 3, V4L2_MPEG_AUDIO_ENCODING_AC3 = 4, }; v4l2_mpeg_audio_l1_bitrate = { V4L2_MPEG_AUDIO_L1_BITRATE_32K = 0, V4L2_MPEG_AUDIO_L1_BITRATE_64K = 1, V4L2_MPEG_AUDIO_L1_BITRATE_96K = 2, V4L2_MPEG_AUDIO_L1_BITRATE_128K = 3, V4L2_MPEG_AUDIO_L1_BITRATE_160K = 4, V4L2_MPEG_AUDIO_L1_BITRATE_192K = 5, V4L2_MPEG_AUDIO_L1_BITRATE_224K = 6, V4L2_MPEG_AUDIO_L1_BITRATE_256K = 7, V4L2_MPEG_AUDIO_L1_BITRATE_288K = 8, V4L2_MPEG_AUDIO_L1_BITRATE_320K = 9, V4L2_MPEG_AUDIO_L1_BITRATE_352K = 10, V4L2_MPEG_AUDIO_L1_BITRATE_384K = 11, V4L2_MPEG_AUDIO_L1_BITRATE_416K = 12, V4L2_MPEG_AUDIO_L1_BITRATE_448K = 13, }; v4l2_mpeg_audio_l2_bitrate = { V4L2_MPEG_AUDIO_L2_BITRATE_32K = 0, V4L2_MPEG_AUDIO_L2_BITRATE_48K = 1, V4L2_MPEG_AUDIO_L2_BITRATE_56K = 2, V4L2_MPEG_AUDIO_L2_BITRATE_64K = 3, V4L2_MPEG_AUDIO_L2_BITRATE_80K = 4, V4L2_MPEG_AUDIO_L2_BITRATE_96K = 5, V4L2_MPEG_AUDIO_L2_BITRATE_112K = 6, V4L2_MPEG_AUDIO_L2_BITRATE_128K = 7, V4L2_MPEG_AUDIO_L2_BITRATE_160K = 8, V4L2_MPEG_AUDIO_L2_BITRATE_192K = 9, V4L2_MPEG_AUDIO_L2_BITRATE_224K = 10, V4L2_MPEG_AUDIO_L2_BITRATE_256K = 11, V4L2_MPEG_AUDIO_L2_BITRATE_320K = 12, V4L2_MPEG_AUDIO_L2_BITRATE_384K = 13, }; v4l2_mpeg_audio_l3_bitrate = { V4L2_MPEG_AUDIO_L3_BITRATE_32K = 0, V4L2_MPEG_AUDIO_L3_BITRATE_40K = 1, V4L2_MPEG_AUDIO_L3_BITRATE_48K = 2, V4L2_MPEG_AUDIO_L3_BITRATE_56K = 3, V4L2_MPEG_AUDIO_L3_BITRATE_64K = 4, V4L2_MPEG_AUDIO_L3_BITRATE_80K = 5, V4L2_MPEG_AUDIO_L3_BITRATE_96K = 6, V4L2_MPEG_AUDIO_L3_BITRATE_112K = 7, V4L2_MPEG_AUDIO_L3_BITRATE_128K = 8, V4L2_MPEG_AUDIO_L3_BITRATE_160K = 9, V4L2_MPEG_AUDIO_L3_BITRATE_192K = 10, V4L2_MPEG_AUDIO_L3_BITRATE_224K = 11, V4L2_MPEG_AUDIO_L3_BITRATE_256K = 12, V4L2_MPEG_AUDIO_L3_BITRATE_320K = 13, }; v4l2_mpeg_audio_dec_playback = { V4L2_MPEG_AUDIO_DEC_PLAYBACK_AUTO = 0, V4L2_MPEG_AUDIO_DEC_PLAYBACK_STEREO = 1, V4L2_MPEG_AUDIO_DEC_PLAYBACK_LEFT = 2, V4L2_MPEG_AUDIO_DEC_PLAYBACK_RIGHT = 3, V4L2_MPEG_AUDIO_DEC_PLAYBACK_MONO = 4, V4L2_MPEG_AUDIO_DEC_PLAYBACK_SWAPPED_STEREO = 5, }; v4l2_mpeg_video_encoding = { V4L2_MPEG_VIDEO_ENCODING_MPEG_1 = 0, V4L2_MPEG_VIDEO_ENCODING_MPEG_2 = 1, V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC = 2, }; v4l2_mpeg_video_aspect = { V4L2_MPEG_VIDEO_ASPECT_1x1 = 0, V4L2_MPEG_VIDEO_ASPECT_4x3 = 1, V4L2_MPEG_VIDEO_ASPECT_16x9 = 2, V4L2_MPEG_VIDEO_ASPECT_221x100 = 3, }; v4l2_mpeg_video_bitrate_mode = { V4L2_MPEG_VIDEO_BITRATE_MODE_VBR = 0, V4L2_MPEG_VIDEO_BITRATE_MODE_CBR = 1, }; v4l2_mpeg_video_header_mode = { V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE = 0, V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME = 1, }; v4l2_mpeg_video_multi_slice_mode = { V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE = 0, V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB = 1, V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES = 2, }; v4l2_mpeg_video_h264_entropy_mode = { V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC = 0, V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC = 1, }; v4l2_mpeg_video_h264_level = { V4L2_MPEG_VIDEO_H264_LEVEL_1_0 = 0, V4L2_MPEG_VIDEO_H264_LEVEL_1B = 1, V4L2_MPEG_VIDEO_H264_LEVEL_1_1 = 2, V4L2_MPEG_VIDEO_H264_LEVEL_1_2 = 3, V4L2_MPEG_VIDEO_H264_LEVEL_1_3 = 4, V4L2_MPEG_VIDEO_H264_LEVEL_2_0 = 5, V4L2_MPEG_VIDEO_H264_LEVEL_2_1 = 6, V4L2_MPEG_VIDEO_H264_LEVEL_2_2 = 7, V4L2_MPEG_VIDEO_H264_LEVEL_3_0 = 8, V4L2_MPEG_VIDEO_H264_LEVEL_3_1 = 9, V4L2_MPEG_VIDEO_H264_LEVEL_3_2 = 10, V4L2_MPEG_VIDEO_H264_LEVEL_4_0 = 11, V4L2_MPEG_VIDEO_H264_LEVEL_4_1 = 12, V4L2_MPEG_VIDEO_H264_LEVEL_4_2 = 13, V4L2_MPEG_VIDEO_H264_LEVEL_5_0 = 14, V4L2_MPEG_VIDEO_H264_LEVEL_5_1 = 15, }; v4l2_mpeg_video_h264_loop_filter_mode = { V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED = 0, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED = 1, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY = 2, }; v4l2_mpeg_video_h264_profile = { V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE = 0, V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE = 1, V4L2_MPEG_VIDEO_H264_PROFILE_MAIN = 2, V4L2_MPEG_VIDEO_H264_PROFILE_EXTENDED = 3, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH = 4, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10 = 5, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422 = 6, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_PREDICTIVE = 7, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10_INTRA = 8, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422_INTRA = 9, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_INTRA = 10, V4L2_MPEG_VIDEO_H264_PROFILE_CAVLC_444_INTRA = 11, V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_BASELINE = 12, V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH = 13, V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH_INTRA = 14, V4L2_MPEG_VIDEO_H264_PROFILE_STEREO_HIGH = 15, V4L2_MPEG_VIDEO_H264_PROFILE_MULTIVIEW_HIGH = 16, }; v4l2_mpeg_video_h264_vui_sar_idc = { V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_UNSPECIFIED = 0, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_1x1 = 1, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_12x11 = 2, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_10x11 = 3, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_16x11 = 4, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_40x33 = 5, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_24x11 = 6, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_20x11 = 7, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_32x11 = 8, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_80x33 = 9, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_18x11 = 10, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_15x11 = 11, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_64x33 = 12, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_160x99 = 13, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_4x3 = 14, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_3x2 = 15, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_2x1 = 16, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_EXTENDED = 17, }; v4l2_mpeg_video_h264_sei_fp_arrangement_type = { V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_CHECKERBOARD = 0, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_COLUMN = 1, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_ROW = 2, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_SIDE_BY_SIDE = 3, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TOP_BOTTOM = 4, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TEMPORAL = 5, }; v4l2_mpeg_video_h264_fmo_map_type = { V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_INTERLEAVED_SLICES = 0, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_SCATTERED_SLICES = 1, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_FOREGROUND_WITH_LEFT_OVER = 2, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_BOX_OUT = 3, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_RASTER_SCAN = 4, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_WIPE_SCAN = 5, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_EXPLICIT = 6, }; v4l2_mpeg_video_h264_fmo_change_dir = { V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_RIGHT = 0, V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_LEFT = 1, }; v4l2_mpeg_video_h264_hierarchical_coding_type = { V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_B = 0, V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_P = 1, }; v4l2_mpeg_video_mpeg4_level = { V4L2_MPEG_VIDEO_MPEG4_LEVEL_0 = 0, V4L2_MPEG_VIDEO_MPEG4_LEVEL_0B = 1, V4L2_MPEG_VIDEO_MPEG4_LEVEL_1 = 2, V4L2_MPEG_VIDEO_MPEG4_LEVEL_2 = 3, V4L2_MPEG_VIDEO_MPEG4_LEVEL_3 = 4, V4L2_MPEG_VIDEO_MPEG4_LEVEL_3B = 5, V4L2_MPEG_VIDEO_MPEG4_LEVEL_4 = 6, V4L2_MPEG_VIDEO_MPEG4_LEVEL_5 = 7, }; v4l2_mpeg_video_mpeg4_profile = { V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE = 0, V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE = 1, V4L2_MPEG_VIDEO_MPEG4_PROFILE_CORE = 2, V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE_SCALABLE = 3, V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY = 4, }; v4l2_vp8_num_partitions = { V4L2_CID_MPEG_VIDEO_VPX_1_PARTITION = 0, V4L2_CID_MPEG_VIDEO_VPX_2_PARTITIONS = 1, V4L2_CID_MPEG_VIDEO_VPX_4_PARTITIONS = 2, V4L2_CID_MPEG_VIDEO_VPX_8_PARTITIONS = 3, }; v4l2_vp8_num_ref_frames = { V4L2_CID_MPEG_VIDEO_VPX_1_REF_FRAME = 0, V4L2_CID_MPEG_VIDEO_VPX_2_REF_FRAME = 1, V4L2_CID_MPEG_VIDEO_VPX_3_REF_FRAME = 2, }; v4l2_vp8_golden_frame_sel = { V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_PREV = 0, V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_REF_PERIOD = 1, }; v4l2_mpeg_cx2341x_video_spatial_filter_mode = { V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_MANUAL = 0, V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_AUTO = 1, }; v4l2_mpeg_cx2341x_video_luma_spatial_filter_type = { V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_OFF = 0, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_VERT = 2, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_HV_SEPARABLE = 3, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_SYM_NON_SEPARABLE = 4, }; v4l2_mpeg_cx2341x_video_chroma_spatial_filter_type = { V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_OFF = 0, V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, }; v4l2_mpeg_cx2341x_video_temporal_filter_mode = { V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_MANUAL = 0, V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_AUTO = 1, }; v4l2_mpeg_cx2341x_video_median_filter_type = { V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_OFF = 0, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR = 1, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_VERT = 2, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR_VERT = 3, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_DIAG = 4, }; v4l2_mpeg_mfc51_video_frame_skip_mode = { V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_DISABLED = 0, V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_LEVEL_LIMIT = 1, V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_BUF_LIMIT = 2, }; v4l2_mpeg_mfc51_video_force_frame_type = { V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_DISABLED = 0, V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME = 1, V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_NOT_CODED = 2, }; v4l2_exposure_auto_type = { V4L2_EXPOSURE_AUTO = 0, V4L2_EXPOSURE_MANUAL = 1, V4L2_EXPOSURE_SHUTTER_PRIORITY = 2, V4L2_EXPOSURE_APERTURE_PRIORITY = 3 }; v4l2_auto_n_preset_white_balance = { V4L2_WHITE_BALANCE_MANUAL = 0, V4L2_WHITE_BALANCE_AUTO = 1, V4L2_WHITE_BALANCE_INCANDESCENT = 2, V4L2_WHITE_BALANCE_FLUORESCENT = 3, V4L2_WHITE_BALANCE_FLUORESCENT_H = 4, V4L2_WHITE_BALANCE_HORIZON = 5, V4L2_WHITE_BALANCE_DAYLIGHT = 6, V4L2_WHITE_BALANCE_FLASH = 7, V4L2_WHITE_BALANCE_CLOUDY = 8, V4L2_WHITE_BALANCE_SHADE = 9, }; v4l2_iso_sensitivity_auto_type = { V4L2_ISO_SENSITIVITY_MANUAL = 0, V4L2_ISO_SENSITIVITY_AUTO = 1, }; v4l2_exposure_metering = { V4L2_EXPOSURE_METERING_AVERAGE = 0, V4L2_EXPOSURE_METERING_CENTER_WEIGHTED = 1, V4L2_EXPOSURE_METERING_SPOT = 2, V4L2_EXPOSURE_METERING_MATRIX = 3, }; v4l2_scene_mode = { V4L2_SCENE_MODE_NONE = 0, V4L2_SCENE_MODE_BACKLIGHT = 1, V4L2_SCENE_MODE_BEACH_SNOW = 2, V4L2_SCENE_MODE_CANDLE_LIGHT = 3, V4L2_SCENE_MODE_DAWN_DUSK = 4, V4L2_SCENE_MODE_FALL_COLORS = 5, V4L2_SCENE_MODE_FIREWORKS = 6, V4L2_SCENE_MODE_LANDSCAPE = 7, V4L2_SCENE_MODE_NIGHT = 8, V4L2_SCENE_MODE_PARTY_INDOOR = 9, V4L2_SCENE_MODE_PORTRAIT = 10, V4L2_SCENE_MODE_SPORTS = 11, V4L2_SCENE_MODE_SUNSET = 12, V4L2_SCENE_MODE_TEXT = 13, }; v4l2_auto_focus_range = { V4L2_AUTO_FOCUS_RANGE_AUTO = 0, V4L2_AUTO_FOCUS_RANGE_NORMAL = 1, V4L2_AUTO_FOCUS_RANGE_MACRO = 2, V4L2_AUTO_FOCUS_RANGE_INFINITY = 3, }; v4l2_preemphasis = { V4L2_PREEMPHASIS_DISABLED = 0, V4L2_PREEMPHASIS_50_uS = 1, V4L2_PREEMPHASIS_75_uS = 2, }; v4l2_flash_led_mode = { V4L2_FLASH_LED_MODE_NONE, V4L2_FLASH_LED_MODE_FLASH, V4L2_FLASH_LED_MODE_TORCH, }; v4l2_flash_strobe_source = { V4L2_FLASH_STROBE_SOURCE_SOFTWARE, V4L2_FLASH_STROBE_SOURCE_EXTERNAL, }; v4l2_jpeg_chroma_subsampling = { V4L2_JPEG_CHROMA_SUBSAMPLING_444 = 0, V4L2_JPEG_CHROMA_SUBSAMPLING_422 = 1, V4L2_JPEG_CHROMA_SUBSAMPLING_420 = 2, V4L2_JPEG_CHROMA_SUBSAMPLING_411 = 3, V4L2_JPEG_CHROMA_SUBSAMPLING_410 = 4, V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY = 5, }; v4l2_dv_tx_mode = { V4L2_DV_TX_MODE_DVI_D = 0, V4L2_DV_TX_MODE_HDMI = 1, }; v4l2_dv_rgb_range = { V4L2_DV_RGB_RANGE_AUTO = 0, V4L2_DV_RGB_RANGE_LIMITED = 1, V4L2_DV_RGB_RANGE_FULL = 2, }; v4l2_deemphasis = { V4L2_DEEMPHASIS_DISABLED = 0, V4L2_DEEMPHASIS_50_uS = 1, V4L2_DEEMPHASIS_75_uS = 2, }; } local exports = { Constants = C; Enums = Enums; } return exports
mit
arashvp1/arashvp2
libs/dateparser.lua
1
6222
local difftime, time, date = os.difftime, os.time, os.date local format = string.format local tremove, tinsert = table.remove, table.insert local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable local dateparser={} --we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore. local unix_timestamp do local now = time() local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now))) unix_timestamp = function(t, offset_sec) local success, improper_time = pcall(time, t) if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end return improper_time - local_UTC_offset_sec - offset_sec end end local formats = {} -- format names local format_func = setmetatable({}, {__mode='v'}) --format functions ---register a date format parsing function function dateparser.register_format(format_name, format_function) if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end local found for i, f in ipairs(format_func) do --for ordering if f==format_function then found=true break end end if not found then tinsert(format_func, format_function) end formats[format_name] = format_function return true end ---register a date format parsing function function dateparser.unregister_format(format_name) if type(format_name)~="string" then return nil, "format name must be a string" end formats[format_name]=nil end ---return the function responsible for handling format_name date strings function dateparser.get_format_function(format_name) return formats[format_name] or nil, ("format %s not registered"):format(format_name) end ---try to parse date string --@param str date string --@param date_format optional date format name, if known --@return unix timestamp if str can be parsed; nil, error otherwise. function dateparser.parse(str, date_format) local success, res, err if date_format then if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end success, res = pcall(formats[date_format], str) else for i, func in ipairs(format_func) do success, res = pcall(func, str) if success and res then return res end end end return success and res end dateparser.register_format('W3CDTF', function(rest) local year, day_of_year, month, day, week local hour, minute, second, second_fraction, offset_hours local alt_rest year, rest = rest:match("^(%d%d%d%d)%-?(.*)$") day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$") if day_of_year then rest=alt_rest end month, rest = rest:match("^(%d%d)%-?(.*)$") day, rest = rest:match("^(%d%d)(.*)$") if #rest>0 then rest = rest:match("^T(.*)$") hour, rest = rest:match("^([0-2][0-9]):?(.*)$") minute, rest = rest:match("^([0-6][0-9]):?(.*)$") second, rest = rest:match("^([0-6][0-9])(.*)$") second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$") if second_fraction then rest=alt_rest end if rest=="Z" then rest="" offset_hours=0 else local sign, offset_h, offset_m sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$") local offset_m, alt_rest = rest:match("^(%d%d)(.*)$") if offset_m then rest=alt_rest end offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 then return nil end end year = tonumber(year) local d = { year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))), month = tonumber(month) or 1, day = tonumber(day) or 1, hour = tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } local t = unix_timestamp(d, (offset_hours or 0) * 3600) if second_fraction then return t + tonumber("0."..second_fraction) else return t end end) do local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/ A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9, K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5, S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12, Z = 0, EST = -5, EDT = -4, CST = -6, CDT = -5, MST = -7, MDT = -6, PST = -8, PDT = -7, GMT = 0, UT = 0, UTC = 0 } local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12} dateparser.register_format('RFC2822', function(rest) local year, month, day, day_of_year, week_of_year, weekday local hour, minute, second, second_fraction, offset_hours local alt_rest weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$") if weekday then rest=alt_rest end day, rest=rest:match("^(%d%d?)%s+(.*)$") month, rest=rest:match("^(%w%w%w)%s+(.*)$") month = month_val[month] year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$") hour, rest = rest:match("^(%d%d?):(.*)$") minute, rest = rest:match("^(%d%d?)(.*)$") second, alt_rest = rest:match("^:(%d%d)(.*)$") if second then rest = alt_rest end local tz, offset_sign, offset_h, offset_m tz, alt_rest = rest:match("^%s+(%u+)(.*)$") if tz then rest = alt_rest offset_hours = tz_table[tz] else offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$") offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 or not (year and day and month and hour and minute) then return nil end year = tonumber(year) local d = { year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))), month = month, day = tonumber(day), hour= tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } return unix_timestamp(d, offset_hours * 3600) end) end dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF return dateparser --@avbat
gpl-3.0
norefle/facil
src/facil/create.lua
1
1925
--[[---------------------------------------------------------------------------- --- @file create.lua --- @brief fácil's create command. ----------------------------------------------------------------------------]]-- local Core = require "facil.core" local _M = {} --- Creates new card -- @param name Short descriptive name of card. -- @retval true, string - on success, where string is the uuid of new card. -- @retval nil, string - on error, where string contains detailed description. function _M.create(name) if not name or "string" ~= type(name) then return nil, "Invalid argument." end if not Core.getRootPath() then return nil, "Can't get fácil's root directory." end local card = {} card.name = name card.id = Core.uuid.new() if not card.id then return nil, "Can't generate uuid for card." end local templateErr, template = Core.getTemplate("md.lua") if not templateErr then return nil, "Can't read none of template files for task." end template.value = template.value:gsub("${NAME}", name) card.time = os.time() local prefix, body = Core.splitId(card.id) local markdown, markdownErr = Core.createCardFile("cards", prefix, body, ".md", template.value) if not markdown then return nil, markdownErr end --- @warning Platform (linux specific) dependent code. --- @todo Either replace with something more cross platform --- or check OS before. os.execute("$EDITOR " .. markdown.name) local meta, metaErr = Core.createCardFile("meta", prefix, body, nil, Core.serializeMeta(card)) if not meta then return nil, metaErr end local marker, markerErr = Core.createCardFile("boards", "backlog", card.id, nil, tostring(card.time)) if not marker then return nil, markerErr end return true, card.id end return _M
mit
bnetcc/darkstar
scripts/zones/Lower_Jeuno/npcs/Panta-Putta.lua
5
3837
----------------------------------- -- Area: Lower Jeuno -- NPC: Panta-Putta -- Starts and Finishes Quest: The Wonder Magic Set, The kind cardian -- Involved in Quests: The Lost Cardian -- @zone 245 -- !pos -61 0 -140 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) TheWonderMagicSet = player:getQuestStatus(JEUNO,THE_WONDER_MAGIC_SET); WonderMagicSetKI = player:hasKeyItem(WONDER_MAGIC_SET); TheLostCardianCS = player:getVar("theLostCardianVar"); TheKindCardian = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); if (player:getFameLevel(JEUNO) >= 4 and TheWonderMagicSet == QUEST_AVAILABLE) then player:startEvent(77); -- Start quest "The wonder magic set" elseif (TheWonderMagicSet == QUEST_ACCEPTED and WonderMagicSetKI == false) then player:startEvent(55); -- During quest "The wonder magic set" elseif (WonderMagicSetKI == true) then player:startEvent(33); -- Finish quest "The wonder magic set" elseif (TheWonderMagicSet == QUEST_COMPLETED and player:getQuestStatus(JEUNO,COOK_S_PRIDE) ~= QUEST_COMPLETED) then player:startEvent(40); -- Standard dialog elseif (TheWonderMagicSet == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_LOST_CARDIAN) == QUEST_AVAILABLE) then if (TheLostCardianCS >= 1) then player:startEvent(30); -- Second dialog for "The lost cardien" quest else player:startEvent(40); -- Standard dialog end elseif (TheKindCardian == QUEST_ACCEPTED and player:getVar("theKindCardianVar") == 2) then player:startEvent(35); -- Finish quest "The kind cardien" elseif (TheKindCardian == QUEST_COMPLETED) then player:startEvent(76); -- New standard dialog after "The kind cardien" else player:startEvent(78); -- Base standard dialog end end; -- 78 oh zut j'ai besoin de cette marmite -- 30 j'ai été trop dur avec two... et percé la marmite -- 40 du moment que j'ai cette boite et la marmite je vais enfin battre ce gars function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 77 and option == 1) then player:addQuest(JEUNO,THE_WONDER_MAGIC_SET); elseif (csid == 33) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13328); else player:addTitle(FOOLS_ERRAND_RUNNER); player:delKeyItem(WONDER_MAGIC_SET); player:addItem(13328); player:messageSpecial(ITEM_OBTAINED,13328); player:addFame(JEUNO, 30); player:needToZone(true); player:completeQuest(JEUNO,THE_WONDER_MAGIC_SET); end elseif (csid == 30) then player:setVar("theLostCardianVar",2); elseif (csid == 35) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13596); else player:addTitle(BRINGER_OF_BLISS); player:delKeyItem(TWO_OF_SWORDS); player:setVar("theKindCardianVar",0); player:addItem(13596); player:messageSpecial(ITEM_OBTAINED,13596); -- Green Cape player:addFame(JEUNO, 30); player:completeQuest(JEUNO,THE_KIND_CARDIAN); end end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Pashhow_Marshlands_[S]/mobs/Croque-mitaine.lua
1
1356
----------------------------------- -- Zone: Pashhow Marshlands (S) -- NM: Croque-mitaine ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/utils"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); mob:setMobMod(MOBMOD_MAIN_2HOUR, 1); -- addMod mob:addMod(MOD_TRIPLE_ATTACK, 15) mob:addMod(MOD_ATT, 100); end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGEN, 40); mob:setMod(MOD_REGAIN, 10); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) if (target:hasStatusEffect(EFFECT_POISON)) then target:delStatusEffect(EFFECT_POISON); end duration = 30 * applyResistanceAddEffect(mob, target, ELE_WATER, EFFECT_POISON) utils.clamp(duration,1,30); target:addStatusEffect(EFFECT_POISON, 100, 3, duration); return SUBEFFECT_POISON, 160, EFFECT_POISON; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Norg/npcs/Gilgamesh.lua
1
3014
----------------------------------- -- Area: Norg -- NPC: Gilgamesh -- !pos 122.452 -9.009 -12.052 252 ----------------------------------- require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(BASTOK) == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 2) then if (trade:hasItemQty(1160,1) and trade:getItemCount() == 1) then -- Frag Rock player:startEvent(99); -- Bastok Mission 6-2 end end end; function onTrigger(player,npc) local ZilartMission = player:getCurrentMission(ZILART); --[[ if (ZilartMission == KAZAMS_CHIEFTAINESS) then player:startEvent(7); ]] -------------------------------------- -- Begin VW stuff if (player:getQuestStatus(OUTLANDS, VOIDWATCH_OPS_BORDER_CROSSING) == QUEST_COMPLETED and player:getQuestStatus(OUTLANDS, VW_OP_115_LI_TELOR_VARIANT) == QUEST_AVAILABLE) then if (player:getVar("NORG_VW_STATUS") == 0) then player:startEvent(256); else player:startEvent(257); end -- elseif -- 262 Return from sky, part 2, get sent to Aht Urgan. -- 263 repeat Gilgamesh dialog -- End VW stuff -------------------------------------- elseif (ZilartMission == KAZAMS_CHIEFTAINESS) then player:startEvent(0x0007); elseif (ZilartMission == THE_TEMPLE_OF_UGGALEPIH) then player:startEvent(8); elseif (ZilartMission == HEADSTONE_PILGRIMAGE) then player:startEvent(9); elseif (ZilartMission == RETURN_TO_DELKFUTTS_TOWER) then player:startEvent(13); elseif (ZilartMission == ROMAEVE) then player:startEvent(11); elseif (ZilartMission == THE_MITHRA_AND_THE_CRYSTAL) then player:startEvent(170); elseif (ZilartMission == ARK_ANGELS) then player:startEvent(171); elseif (ZilartMission == THE_CELESTIAL_NEXUS) then player:startEvent(173); elseif (ZilartMission == AWAKENING) then player:startEvent(177); end end; --0x00af 0x0000 0x0002 0x0003 0x0004 7 8 9 0x000a 0x0062 99 0x001d 0x000c --13 0x0092 0x009e 0x00a4 0x00a9 170 171 0x00ac 173 0x00b0 177 0x00e8 0x00e9 --0x00ea -- 0x0062 99 mission bastok -- 0x000c parle de kuzotz ? parle de bijoux aussi -- 0x000a parle de zitah function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 99) then player:tradeComplete(); player:setVar("MissionStatus",3); -------------------------------------- -- Begin VW stuff elseif (csid == 256) then player:setVar("NORG_VW_STATUS", 1); else -- 262 Return from sky, part 2, get sent to Aht Urgan. -- 263 repeat Gilgamesh dialog -- End VW stuff -------------------------------------- end end;
gpl-3.0
notcake/vfs
lua/vfs/protocol/protocol.lua
1
2307
VFS.Protocol.ResponseTable = {} VFS.Protocol.StringTable = VFS.StringTable () function VFS.Protocol.Register (packetType, class) VFS.Protocol.StringTable:Add (packetType) class.Type = packetType class.TypeId = VFS.Protocol.StringTable:HashFromString (packetType) end function VFS.Protocol.RegisterNotification (packetType, ctor) VFS.Protocol.StringTable:Add (packetType) VFS.Protocol.ResponseTable [packetType] = ctor local class = VFS.GetMetaTable (ctor) class.Type = packetType class.TypeId = VFS.Protocol.StringTable:HashFromString (packetType) end function VFS.Protocol.RegisterResponse (packetType, ctor) VFS.Protocol.StringTable:Add (packetType) VFS.Protocol.ResponseTable [packetType] = ctor local class = VFS.GetMetaTable (ctor) class.Type = packetType class.TypeId = VFS.Protocol.StringTable:HashFromString (packetType) end VFS.Net.RegisterChannel ("vfs_new_session", function (remoteId, inBuffer) local remoteEndPoint = VFS.EndPointManager:GetEndPoint (remoteId) local requestId = inBuffer:UInt32 () local typeId = inBuffer:UInt32 () local packetType = VFS.Protocol.StringTable:StringFromHash (typeId) local ctor = VFS.Protocol.ResponseTable [packetType] if not ctor then ErrorNoHalt ("vfs_new_session : No handler for " .. tostring (packetType) .. " is registered!") return end local response = ctor () response:SetRemoteEndPoint (remoteEndPoint) response:SetId (requestId) remoteEndPoint:HandleIncomingSession (response, inBuffer) end ) VFS.Net.RegisterChannel ("vfs_session_data", function (remoteId, inBuffer) local remoteEndPoint = VFS.EndPointManager:GetEndPoint (remoteId) remoteEndPoint:HandleIncomingPacket (inBuffer:UInt32 (), inBuffer) end ) VFS.Net.RegisterChannel ("vfs_notification", function (remoteId, inBuffer) local remoteEndPoint = VFS.EndPointManager:GetEndPoint (remoteId) local typeId = inBuffer:UInt32 () local packetType = VFS.Protocol.StringTable:StringFromHash (typeId) local ctor = VFS.Protocol.ResponseTable [packetType] if not ctor then ErrorNoHalt ("vfs_notification : No handler for " .. tostring (packetType) .. " is registered!\n") return end local session = ctor () session:SetRemoteEndPoint (remoteEndPoint) remoteEndPoint:HandleIncomingNotification (session, inBuffer) end )
gpl-3.0
bnetcc/darkstar
scripts/globals/effects/voidstorm.lua
35
1337
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR,math.floor(effect:getPower()/2)); target:addMod(MOD_DEX,math.floor(effect:getPower()/2)); target:addMod(MOD_VIT,math.floor(effect:getPower()/2)); target:addMod(MOD_AGI,math.floor(effect:getPower()/2)); target:addMod(MOD_INT,math.floor(effect:getPower()/2)); target:addMod(MOD_MND,math.floor(effect:getPower()/2)); target:addMod(MOD_CHR,math.floor(effect:getPower()/2)); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR,math.floor(effect:getPower()/2)); target:delMod(MOD_DEX,math.floor(effect:getPower()/2)); target:delMod(MOD_VIT,math.floor(effect:getPower()/2)); target:delMod(MOD_AGI,math.floor(effect:getPower()/2)); target:delMod(MOD_INT,math.floor(effect:getPower()/2)); target:delMod(MOD_MND,math.floor(effect:getPower()/2)); target:delMod(MOD_CHR,math.floor(effect:getPower()/2)); end;
gpl-3.0
jpcy/bgfx
3rdparty/spirv-headers/include/spirv/1.1/spirv.lua
59
26704
-- Copyright (c) 2014-2018 The Khronos Group Inc. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and/or associated documentation files (the "Materials"), -- to deal in the Materials without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Materials, and to permit persons to whom the -- Materials are 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 Materials. -- -- MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS -- STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND -- HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ -- -- THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS -- IN THE MATERIALS. -- This header is automatically generated by the same tool that creates -- the Binary Section of the SPIR-V specification. -- Enumeration tokens for SPIR-V, in various styles: -- C, C++, C++11, JSON, Lua, Python -- -- - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL -- - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL -- - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL -- - Lua will use tables, e.g.: spv.SourceLanguage.GLSL -- - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] -- -- Some tokens act like mask values, which can be OR'd together, -- while others are mutually exclusive. The mask-like ones have -- "Mask" in their name, and a parallel enum that has the shift -- amount (1 << x) for each corresponding enumerant. spv = { MagicNumber = 0x07230203, Version = 0x00010100, Revision = 8, OpCodeMask = 0xffff, WordCountShift = 16, SourceLanguage = { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, }, ExecutionModel = { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, }, AddressingModel = { Logical = 0, Physical32 = 1, Physical64 = 2, }, MemoryModel = { Simple = 0, GLSL450 = 1, OpenCL = 2, }, ExecutionMode = { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, }, StorageClass = { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, }, Dim = { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, }, SamplerAddressingMode = { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, }, SamplerFilterMode = { Nearest = 0, Linear = 1, }, ImageFormat = { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, }, ImageChannelOrder = { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, }, ImageChannelDataType = { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, }, ImageOperandsShift = { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, }, ImageOperandsMask = { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, }, FPFastMathModeShift = { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, }, FPFastMathModeMask = { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, }, FPRoundingMode = { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, }, LinkageType = { Export = 0, Import = 1, }, AccessQualifier = { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, }, FunctionParameterAttribute = { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, }, Decoration = { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, }, BuiltIn = { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, }, SelectionControlShift = { Flatten = 0, DontFlatten = 1, }, SelectionControlMask = { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, }, LoopControlShift = { Unroll = 0, DontUnroll = 1, DependencyInfinite = 2, DependencyLength = 3, }, LoopControlMask = { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, DependencyInfinite = 0x00000004, DependencyLength = 0x00000008, }, FunctionControlShift = { Inline = 0, DontInline = 1, Pure = 2, Const = 3, }, FunctionControlMask = { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, }, MemorySemanticsShift = { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, }, MemorySemanticsMask = { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, }, MemoryAccessShift = { Volatile = 0, Aligned = 1, Nontemporal = 2, }, MemoryAccessMask = { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, }, Scope = { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, }, GroupOperation = { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, }, KernelEnqueueFlags = { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, }, KernelProfilingInfoShift = { CmdExecTime = 0, }, KernelProfilingInfoMask = { MaskNone = 0, CmdExecTime = 0x00000001, }, Capability = { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, }, Op = { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, }, }
bsd-2-clause
sylvanaar/prat-3-0
modules/Substitutions.lua
1
20473
--------------------------------------------------------------------------------- -- -- Prat - A framework for World of Warcraft chat mods -- -- Copyright (C) 2006-2018 Prat Development Team -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to: -- -- Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- -- ------------------------------------------------------------------------------- Prat:AddModuleToLoad(function() local PRAT_MODULE = Prat:RequestModuleName("Substitutions") if PRAT_MODULE == nil then return end local module = Prat:NewModule(PRAT_MODULE) -- define localized strings local PL = module.PL --@debug@ PL:AddLocale(PRAT_MODULE, "enUS", { ["Substitutions"] = true, ["A module to provide basic chat substitutions."] = true, ['User defined substitutions'] = true, ['Options for setting and removing user defined substitutions. (NB: users may define custom values for existing substitutions, but they will revert to the default value if the user definition is deleted.)'] = true, ['Set substitution'] = true, ['Set the value of a user defined substitution (NB: this may be the same as an existing default substitution; to reset it to the default, just remove the user created definition).'] = true, ['subname = text after expansion -- NOTE: sub name without the prefix "%"'] = true, ['List substitutions'] = true, ['Lists all current subtitutions in the default chat frame'] = true, ['Delete substitution'] = true, ['Deletes a user defined substitution'] = true, ['subname -- NOTE: sub name without the prefix \'%\''] = true, ['Are you sure?'] = true, ['Delete all'] = true, ['Deletes all user defined substitutions'] = true, ['Are you sure - this will delete all user defined substitutions and reset defaults?'] = true, ['List of available substitutions'] = true, ['List of available substitutions defined by this module. (NB: users may define custom values for existing substitutions, but they will revert to the default value if the user definition is deleted.)'] = true, ["NO MATCHFUNC FOUND"] = true, ["current-prompt"] = "Current value: '%s'\nClick to paste into the chat.", ['no substitution name given'] = true, ['no value given for subtitution "%s"'] = true, ['|cffff0000warning:|r subtitution "%s" already defined as "%s", overwriting'] = true, ['defined %s: expands to => %s'] = true, ['no substitution name suPLied for deletion'] = true, ['no user defined subs found'] = true, ['user defined substition "%s" not found'] = true, ["user substitutions index (usersubs_idx) doesn't exist! oh dear."] = true, ["can't find substitution index for a substitution named '%s'"] = true, ['removing user defined substitution "%s"; previously expanded to => "%s"'] = true, ['substitution: %s defined as => %s'] = true, ['%d total user defined substitutions'] = true, ['module:buildUserSubsIndex(): warning: module patterns not defined!'] = true, ["<notarget>"] = true, ["male"] = true, ["female"] = true, ["unknown sex"] = true, ["<noguild>"] = true, ["his"] = true, ["hers"] = true, ["its"] = true, ["him"] = true, ["her"] = true, ["it"] = true, ['usersub_'] = true, ["TargetHealthDeficit"] = true, ["TargetPercentHP"] = true, ["TargetPronoun"] = true, ["PlayerHP"] = true, ["PlayerName"] = true, ["PlayerMaxHP"] = true, ["PlayerHealthDeficit"] = true, ["PlayerPercentHP"] = true, ["PlayerCurrentMana"] = true, ["PlayerMaxMana"] = true, ["PlayerPercentMana"] = true, ["PlayerManaDeficit"] = true, ["TargetName"] = true, ["TargetTargetName"] = true, ["MouseoverTargetName"] = true, ["TargetClass"] = true, ["TargetHealth"] = true, ["TargetRace"] = true, ["TargetGender"] = true, ["TargetLevel"] = true, ["TargetPossesive"] = true, ["TargetManaDeficit"] = true, ["TargetGuild"] = true, ["TargetIcon"] = true, ["MapZone"] = true, ["MapLoc"] = true, ["MapPos"] = true, ["MapYPos"] = true, ["MapXPos"] = true, ["RandNum"] = true, ["PlayerAverageItemLevel"] = true, }) --@end-debug@ -- These Localizations are auto-generated. To help with localization -- please go to http://www.wowace.com/projects/prat-3-0/localization/ --[===[@non-debug@ do local L --@localization(locale="enUS", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "enUS", L) --@localization(locale="itIT", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "itIT", L) --@localization(locale="ptBR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "ptBR", L) --@localization(locale="frFR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "frFR", L) --@localization(locale="deDE", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "deDE", L) --@localization(locale="koKR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "koKR", L) --@localization(locale="esMX", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "esMX", L) --@localization(locale="ruRU", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "ruRU", L) --@localization(locale="zhCN", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "zhCN", L) --@localization(locale="esES", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "esES", L) --@localization(locale="zhTW", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="Substitutions")@ PL:AddLocale(PRAT_MODULE, "zhTW", L) end --@end-non-debug@]===] Prat:SetModuleDefaults(module.name, { profile = { on = false, } }) local patternPlugins = { patterns = {} } Prat:SetModuleOptions(module.name, { name = PL["Substitutions"], desc = PL["A module to provide basic chat substitutions."], type = 'group', plugins = patternPlugins, args = {} }) local function subDesc(info) return info.handler:GetSubstDescription(info) end --[[------------------------------------------------ Core Functions ------------------------------------------------]] -- function module:OnModuleEnable() self:BuildModuleOptions(patternPlugins.patterns) end function module:BuildModuleOptions(args) local modulePatterns = Prat.GetModulePatterns(self) self.buildingMenu = true for _, v in pairs(modulePatterns) do if v then local name = v.optname local pat = v.pattern:gsub("%%%%", "%%") args[name] = args[name] or {} local d = args[name] d.name = name .. " " .. pat d.desc = subDesc d.type = "execute" d.func = "DoPat" end end self.buildingMenu = false end function module:GetDescription() return PL["A module to provide basic chat substitutions."] end function module:GetSubstDescription(info) local val = self:InfoToPattern(info) self.buildingMenu = true val = val and val.matchfunc and val.matchfunc() or PL["NO MATCHFUNC FOUND"] val = PL["current-prompt"]:format("|cff80ff80" .. tostring(val) .. "|r"):gsub("%%%%", "%%") self.buildingMenu = false return val end function module:InfoToPattern(info) local modulePatterns = Prat.GetModulePatterns(self) local name = info[#info] or "" if modulePatterns then for _, v in pairs(modulePatterns) do if v and v.optname == name then return v end end end end function module:DoPat(info) local pat = self:InfoToPattern(info) pat = pat and pat.pattern or "" local e = ChatEdit_GetActiveWindow() if not e or not e:IsVisible() then return end e:SetText((e:GetText() or "") .. pat:gsub("[%(%)]", ""):gsub("%%%%", "%%")) end do local function prat_match(text) local text = text or "" if module.buildingMenu then return text end return Prat:RegisterMatch(text, "OUTBOUND") end local function Zone(...) return prat_match(GetRealZoneText()) end local function Loc(...) return prat_match(GetMinimapZoneText()) end local function GetPlayerMapPosition(unit) return C_Map.GetPlayerMapPosition(C_Map.GetBestMapForUnit(unit), unit):GetXY() end local function Pos() local x, y = GetPlayerMapPosition("player") local str = "(" .. math.floor((x * 100) + 0.5) .. "," .. math.floor((y * 100) + 0.5) .. ")" return prat_match(str) end local function Ypos() local x, y = GetPlayerMapPosition("player") local y = tostring(math.floor((y * 100) + 0.5)) return prat_match(y) end local function Xpos() local x, y = GetPlayerMapPosition("player") local x = tostring(math.floor((x * 100) + 0.5)) return prat_match(x) end local function PlayerHP(...) return prat_match(UnitHealth("player")) end local function PlayerMaxHP(...) return prat_match(UnitHealthMax("player")) end local function PlayerPercentHP() return prat_match(floor(100 * (UnitHealth("player") / UnitHealthMax("player")))) end local function PlayerHealthDeficit() return prat_match(UnitHealthMax("player") - UnitHealth("player")) end local function PlayerCurrentMana() return prat_match(UnitPower("player")) end local function PlayerMaxMana() return prat_match(UnitPowerMax("player")) end local function PlayerPercentMana() return prat_match(string.format("%.0f%%%%", floor(100 * (UnitPower("player") / UnitPowerMax("player"))))) end local function PlayerManaDeficit() return prat_match(UnitPowerMax("player") - UnitPower("player")) end local function TargetPercentHP() local str = PL["<notarget>"] if UnitExists("target") then str = string.format("%.0f%%%%", floor(100 * (UnitHealth("target") / UnitHealthMax("target")))) end return prat_match(str) end local function TargetHealth() local str = PL["<notarget>"] if UnitExists("target") then str = UnitHealth("target") end return prat_match(str) end local function TargetHealthDeficit() local str = PL["<notarget>"] if UnitExists("target") then str = UnitHealthMax("target") - UnitHealth("target") end return prat_match(str) end local function TargetManaDeficit() local str = PL["<notarget>"] if UnitExists("target") then str = UnitPowerMax("target") - UnitPower("target") end return prat_match(str) end local function TargetClass() local class = PL["<notarget>"] if UnitExists("target") then class = UnitClass("target") end return prat_match(class) end local raidiconpfx = ICON_TAG_RAID_TARGET_STAR1:sub(1, -2) or "rt" local function TargetIcon() local icon = "" if UnitExists("target") then local iconnum = GetRaidTargetIndex("target") if type(iconnum) ~= "nil" then icon = ("{%s%d}"):format(raidiconpfx, tostring(iconnum)) end end return prat_match(icon) end local function TargetRace() local race = PL["<notarget>"] if UnitExists("target") then if UnitIsPlayer("target") then race = UnitRace("target") else race = UnitCreatureFamily("target") if not race then race = UnitCreatureType("target") end end end return prat_match(race) end local function TargetGender() local sex = PL["<notarget>"] if UnitExists("target") then local s = UnitSex("target") if (s == 2) then sex = PL["male"] elseif (s == 3) then sex = PL["female"] else sex = PL["unknown sex"] end end return prat_match(sex) end local function TargetLevel() local level = PL["<notarget>"] if UnitExists("target") then level = UnitLevel("target") end return prat_match(level) end local function TargetGuild() local guild = PL["<notarget>"] if UnitExists("target") then guild = PL["<noguild>"] if IsInGuild("target") then guild = GetGuildInfo("target") or "" end end return prat_match(guild) end -- %tps (possesive) local function TargetPossesive() local p = PL["<notarget>"] if UnitExists("target") then local s = UnitSex("target") if (s == 2) then p = PL["his"] elseif (s == 3) then p = PL["hers"] else p = PL["its"] end end return prat_match(p) end -- %tpn (pronoun) local function TargetPronoun() local p = PL["<notarget>"] if UnitExists("target") then local s = UnitSex("target") if (s == 2) then p = PL["him"] elseif (s == 3) then p = PL["her"] else p = PL["it"] end end return prat_match(p) end -- %tn (target) local function TargetName() local t = PL['<notarget>'] if UnitExists("target") then t = UnitName("target") end return prat_match(t) end -- %tt (target) local function TargetTargetName() local t = PL['<notarget>'] if UnitExists("targettarget") then t = UnitName("targettarget") end return prat_match(t) end -- %mn (mouseover) local function MouseoverName() local t = PL['<notarget>'] if UnitExists("mouseover") then t = UnitName("mouseover") end return prat_match(t) end -- %pn (player) local function PlayerName() local p = GetUnitName("player") or "" return prat_match(p) end local function PlayerAverageItemLevel() local avgItemLevel = GetAverageItemLevel(); avgItemLevel = floor(avgItemLevel); return prat_match(avgItemLevel) end local function Rand() return prat_match(math.random(1, 100)) end --[[ * %tn = current target * %pn = player name * %hc = your current health * %hm = your max health * %hp = your percentage health * %hd = your current health deficit * %mc = your current mana * %mm = your max mana * %mp = your percentage mana * %md = your current mana deficit * %thp = target's percentage health * %th = target's current health * %td = target's health deficit * %tc = class of target * %tr = race of target * %ts = sex of target * %tl = level of target * %ti = raid icon of target * %tps = possesive for target (his/hers/its) * %tpn = pronoun for target (him/her/it) * %fhp = focus's percentage health * %fc = class of focus * %fr = race of focus * %fs = sex of focus * %fl = level of focus * %fps = possesive for focus (his/hers/its) * %fpn = pronoun for focus (him/her/it) * %tt = target of target * %zon = your current zone (Dun Morogh, Hellfire Peninsula, etc.) * %loc = your current subzone (as shown on the minimap) * %pos = your current coordinates (x,y) * %ypos = your current y coordinate * %xpos = your current x coordinate * %rnd = a random number between 1 and 100 * %ail = your average item level --]] Prat:SetModulePatterns(module, { { pattern = "(%%thd)", matchfunc = TargetHealthDeficit, optname = PL["TargetHealthDeficit"], type = "OUTBOUND" }, { pattern = "(%%thp)", matchfunc = TargetPercentHP, priority = 51, optname = PL["TargetPercentHP"], type = "OUTBOUND" }, { pattern = "(%%tpn)", matchfunc = TargetPronoun, optname = PL["TargetPronoun"], type = "OUTBOUND" }, { pattern = "(%%hc)", matchfunc = PlayerHP, optname = PL["PlayerHP"], type = "OUTBOUND" }, { pattern = "(%%pn)", matchfunc = PlayerName, optname = PL["PlayerName"], type = "OUTBOUND" }, { pattern = "(%%hm)", matchfunc = PlayerMaxHP, optname = PL["PlayerMaxHP"], type = "OUTBOUND" }, { pattern = "(%%hd)", matchfunc = PlayerHealthDeficit, optname = PL["PlayerHealthDeficit"], type = "OUTBOUND" }, { pattern = "(%%hp)", matchfunc = PlayerPercentHP, optname = PL["PlayerPercentHP"], type = "OUTBOUND" }, { pattern = "(%%mc)", matchfunc = PlayerCurrentMana, optname = PL["PlayerCurrentMana"], type = "OUTBOUND" }, { pattern = "(%%mm)", matchfunc = PlayerMaxMana, optname = PL["PlayerMaxMana"], type = "OUTBOUND" }, { pattern = "(%%mp)", matchfunc = PlayerPercentMana, optname = PL["PlayerPercentMana"], type = "OUTBOUND" }, { pattern = "(%%pmd)", matchfunc = PlayerManaDeficit, optname = PL["PlayerManaDeficit"], type = "OUTBOUND" }, GetAverageItemLevel and { pattern = "(%%ail)", matchfunc = PlayerAverageItemLevel, optname = PL["PlayerAverageItemLevel"], type = "OUTBOUND" }, { pattern = "(%%tn)", matchfunc = TargetName, optname = PL["TargetName"], type = "OUTBOUND" }, { pattern = "(%%tt)", matchfunc = TargetTargetName, optname = PL["TargetTargetName"], type = "OUTBOUND" }, { pattern = "(%%tc)", matchfunc = TargetClass, optname = PL["TargetClass"], type = "OUTBOUND" }, { pattern = "(%%th)", matchfunc = TargetHealth, optname = PL["TargetHealth"], type = "OUTBOUND" }, { pattern = "(%%tr)", matchfunc = TargetRace, optname = PL["TargetRace"], type = "OUTBOUND" }, { pattern = "(%%ts)", matchfunc = TargetGender, optname = PL["TargetGender"], type = "OUTBOUND" }, { pattern = "(%%ti)", matchfunc = TargetIcon, optname = PL["TargetIcon"], type = "OUTBOUND" }, { pattern = "(%%tl)", matchfunc = TargetLevel, optname = PL["TargetLevel"], type = "OUTBOUND" }, { pattern = "(%%tps)", matchfunc = TargetPossesive, optname = PL["TargetPossesive"], type = "OUTBOUND" }, { pattern = "(%%tmd)", matchfunc = TargetManaDeficit, optname = PL["TargetManaDeficit"], type = "OUTBOUND" }, { pattern = "(%%tg)", matchfunc = TargetGuild, optname = PL["TargetGuild"], type = "OUTBOUND" }, { pattern = "(%%mn)", matchfunc = MouseoverName, optname = PL["MouseoverTargetName"], type = "OUTBOUND" }, { pattern = "(%%zon)", matchfunc = Zone, optname = PL["MapZone"], type = "OUTBOUND" }, { pattern = "(%%loc)", matchfunc = Loc, optname = PL["MapLoc"], type = "OUTBOUND" }, { pattern = "(%%pos)", matchfunc = Pos, optname = PL["MapPos"], type = "OUTBOUND" }, { pattern = "(%%ypos)", matchfunc = Ypos, optname = PL["MapYPos"], type = "OUTBOUND" }, { pattern = "(%%xpos)", matchfunc = Xpos, optname = PL["MapXPos"], type = "OUTBOUND" }, { pattern = "(%%rnd)", matchfunc = Rand, optname = PL["RandNum"], type = "OUTBOUND" }, } --[[ TODO: %%fhp - focus health %%fr %%fc %%fs %%fl %%fvr %%fvn ]]) end return end) -- Prat:AddModuleToLoad
gpl-3.0
bnetcc/darkstar
scripts/globals/items/slice_of_marinara_pizza_+1.lua
1
1231
----------------------------------------- -- ID: 6212 -- Item: slice of marinara pizza +1 -- Food Effect: 60 minutes, all Races ----------------------------------------- -- HP +25 -- Accuracy+11% (Max. 58) -- Attack+21% (Max. 55) -- "Undead Killer"+5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,6212); end; function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_FOOD_ACCP, 11); target:addMod(MOD_FOOD_ACC_CAP, 58); target:addMod(MOD_FOOD_ATTP, 21); target:addMod(MOD_FOOD_ATT_CAP, 55); target:addMod(MOD_UNDEAD_KILLER, 5); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 25); target:delMod(MOD_FOOD_ACCP, 111); target:delMod(MOD_FOOD_ACC_CAP, 58); target:delMod(MOD_FOOD_ATTP, 21); target:delMod(MOD_FOOD_ATT_CAP, 55); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
luc-tielen/lua-quickcheck
lqc/generators/table.lua
2
6241
--- Module for generating tables of varying sizes and types -- @module lqc.generators.table -- @alias new_table local Gen = require 'lqc.generator' local random = require 'lqc.random' local bool = require 'lqc.generators.bool' local int = require 'lqc.generators.int' local float = require 'lqc.generators.float' local string = require 'lqc.generators.string' local lqc = require 'lqc.quickcheck' local lqc_gen = require 'lqc.lqc_gen' local oneof = lqc_gen.oneof local frequency = lqc_gen.frequency local deep_equals = require 'lqc.helpers.deep_equals' local deep_copy = require 'lqc.helpers.deep_copy' --- Checks if an object is equal to another (shallow equals) -- @param a first value -- @param b second value -- @return true if a equals b; otherwise false local function normal_equals(a, b) return a == b end --- Determines if the shrink mechanism should try to reduce the table in size. -- @param size size of the table to shrink down -- @return true if size should be reduced; otherwise false local function should_shrink_smaller(size) if size == 0 then return false end return random.between(1, 5) == 1 end --- Determines how many items in the table should be shrunk down -- @param size size of the table -- @return amount of values in the table that should be shrunk down local function shrink_how_many(size) -- 20% chance between 1 and size, 80% 1 element. if random.between(1, 5) == 1 then return random.between(1, size) end return 1 end --- Creates a generator for a table of arbitrary or specific size -- @param table_size size of the table to be generated -- @return generator that can generate tables local function new_table(table_size) -- Keep a list of generators used in this new table -- This variable is needed to share state (which generators) between -- the pick and shrink function local generators = {} --- Shrinks the table by 1 randomly chosen element -- @param tbl previously generated table value -- @param size size of the table -- @return shrunk down table local function shrink_smaller(tbl, size) local idx = random.between(1, size) table.remove(tbl, idx) table.remove(generators, idx) -- also update the generators for this table!! return tbl end --- Shrink a value in the table. -- @param tbl table to shrink down -- @param size size of the table -- @param iterations_count remaining amount of times the shrinking should be retried -- @return shrunk down table local function do_shrink_values(tbl, size, iterations_count) local idx = random.between(1, size) local old_value = tbl[idx] local new_value = generators[idx]:shrink(old_value) -- Check if we should retry shrinking: if iterations_count ~= 0 then local check_equality = (type(new_value) == 'table') and deep_equals or normal_equals if check_equality(new_value, old_value) then -- Shrink introduced no simpler result, retry at other index. return do_shrink_values(tbl, size, iterations_count - 1) end end tbl[idx] = new_value return tbl end --- Shrinks an amount of values in the table -- @param tbl table to shrink down -- @param size size of the table -- @param how_many amount of values to shrink down -- @return shrunk down table local function shrink_values(tbl, size, how_many) if how_many ~= 0 then local new_tbl = do_shrink_values(tbl, size, lqc.numshrinks) return shrink_values(new_tbl, size, how_many - 1) end return tbl end --- Generates a random table with a certain size -- @param size size of the table to generate -- @return tableof a specific size with random values local function do_generic_pick(size) local result = {} for idx = 1, size do -- TODO: Figure out a better way to decrease table size rapidly, maybe use -- math.log (e.g. ln(size + 1) ? local subtable_size = math.floor(size * 0.01) local generator = frequency { { 10, new_table(subtable_size) }, { 90, oneof { bool(), int(size), float(), string(size) } } } generators[idx] = generator result[idx] = generator:pick(size) end return result end -- Now actually generate a table: if table_size then -- Specific size --- Helper function for generating a table of a specific size -- @param size size of the table to generate -- @return function that can generate a table of a specific size local function specific_size_pick(size) local function do_pick() return do_generic_pick(size) end return do_pick end --- Shrinks a table without removing any elements. -- @param prev previously generated table value -- @return shrunk down table local function specific_size_shrink(prev) local size = #prev if size == 0 then return prev end -- handle empty tables return shrink_values(prev, size, shrink_how_many(size)) end return Gen.new(specific_size_pick(table_size), specific_size_shrink) end -- Arbitrary size --- Generate a (nested / empty) table of an arbitrary size. -- @param numtests Amount of times the property calls this generator; used to -- guide the optimatization process. -- @return table of an arbitrary size local function arbitrary_size_pick(numtests) local size = random.between(0, numtests) return do_generic_pick(size) end --- Shrinks a table by removing elements or shrinking values in the table. -- @param prev previously generated value -- @return shrunk down table value local function arbitrary_size_shrink(prev) local size = #prev if size == 0 then return prev end -- handle empty tables if should_shrink_smaller(size) then return shrink_smaller(prev, size) end local tbl_copy = deep_copy(prev) local new_tbl = shrink_values(tbl_copy, size, shrink_how_many(size)) if deep_equals(prev, new_tbl) then -- shrinking didn't help, remove an element return shrink_smaller(prev, size) end -- table shrunk successfully! return new_tbl end return Gen.new(arbitrary_size_pick, arbitrary_size_shrink) end return new_table
mit
gamebytes/pioneer
data/models/buildings/city3k/combo/combos.lua
1
2036
--[[ --A bunch of differently coloured combos --metallic blue define_model('combo', { info = { bounding_radius = 10, materials={'default'}, tags = {'city_building'}, }, static = function(lod) set_material('default', .43,.5,.63,1,1.26,1.4,1.66,30) use_material('default') call_model('combo0', v(0,0,0),v(1,0,0),v(0,1,0),1) end }) --darker blue define_model('combo_1', { info = { bounding_radius = 10, materials={'default'}, tags = {'city_building'}, }, static = function(lod) set_material('default', .45,.55,.6,1,.3,.3,.4,30) use_material('default') call_model('combo0', v(0,-1,0),v(1,0,0),v(0,1,0),1) end }) --pea soup define_model('combo_2', { info = { bounding_radius = 10, materials={'default'}, tags = {'city_building'}, }, static = function(lod) set_material('default', .65,.6,.3,1,.4,.3,.3,30) use_material('default') call_model('combo0', v(0,-1,0),v(1,0,0),v(0,1,0),1) end }) --green define_model('combo_3', { info = { bounding_radius = 10, materials={'default'}, tags = {'city_building'}, }, static = function(lod) set_material('default', .45,.65,.4,1,.4,.4,.3,30) use_material('default') call_model('combo0', v(0,-1,0),v(1,0,0),v(0,1,0),1) end }) --doublecombo define_model('combo_1_1', { info = { bounding_radius = 20, materials={'default'}, tags = {'city_building'}, }, static = function(lod) call_model('combo_1', v(-14,-1,0),v(1,0,0),v(0,1,0),1) call_model('combo_2', v(0,-1,0),v(1,0,0),v(0,1,0),1) end }) --triplecombo define_model('combo_1_2', { info = { bounding_radius = 30, materials={'default', 'concrete'}, tags = {'city_building'}, }, static = function(lod) set_material('concrete',.6,.6,.5,1,.3,.3,.3,5) call_model('combo_1', v(-14,2,0),v(1,0,0),v(0,1,0),1) call_model('combo_2', v(0,2,0),v(1,0,0),v(0,1,0),1) call_model('combo_3', v(-24,2,10),v(1,0,0),v(0,1,0),1) zbias(1,v(-14,2.01,15),v(0,1,0)) use_material('concrete') call_model('bld_base_1', v(-14,1.01,15),v(1,0,0),v(0,1,0),1) zbias(0) end }) --]]
gpl-3.0
norefle/facil
src/facil/init.lua
1
1546
--[[---------------------------------------------------------------------------- --- @file init.lua --- @brief fácil's init command. ----------------------------------------------------------------------------]]-- local Core = require "facil.core" local Template = { config = require "facil.template.default_config", task = require "facil.template.md" } local _M = {} --- Initialized fácil's file system layout inside selected directory. -- @param root Path to the root directory, where to initialize fl. -- @retval true - on success -- @retval nil, string - on error, where string contains detailed description. function _M.init(root) if not root or "string" ~= type(root) then return nil, "Invalid argument." end local directories = { root .. "/.fl", root .. "/.fl/boards", root .. "/.fl/boards/backlog", root .. "/.fl/boards/progress", root .. "/.fl/boards/done", root .. "/.fl/cards", root .. "/.fl/meta", root .. "/.fl/template" } for _, path in pairs(directories) do if not Core.createDir(path) then return nil, "Can't create directory: " .. path end end local success, errorCode = Core.createFile(root, Template.config.value, "config") if not success then return nil, errorCode end success, errorCode = Core.createFile(root, Template.task.value, Core.path("template", "md.lua")) if not success then return nil, errorCode end return true end return _M
mit
mwoz123/koreader
frontend/apps/reader/modules/readerpagemap.lua
1
18673
local BD = require("ui/bidi") local Blitbuffer = require("ffi/blitbuffer") local CenterContainer = require("ui/widget/container/centercontainer") local Device = require("device") local Font = require("ui/font") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local InputContainer = require("ui/widget/container/inputcontainer") local Menu = require("ui/widget/menu") local MultiConfirmBox = require("ui/widget/multiconfirmbox") local OverlapGroup = require("ui/widget/overlapgroup") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local Screen = Device.screen local T = require("ffi/util").template local _ = require("gettext") local ReaderPageMap = InputContainer:new{ label_font_face = "ffont", label_default_font_size = 14, -- Black so it's readable (and non-gray-flashing on GloHD) label_color = Blitbuffer.COLOR_BLACK, show_page_labels = nil, use_page_labels = nil, _mirroredUI = BD.mirroredUILayout(), } function ReaderPageMap:init() self.has_pagemap = false self.container = nil self.max_left_label_width = 0 self.max_right_label_width = 0 self.label_font_size = G_reader_settings:readSetting("pagemap_label_font_size") or self.label_default_font_size self.use_textbox_widget = nil self.initialized = false self.ui:registerPostInitCallback(function() self:_postInit() end) end function ReaderPageMap:_postInit() self.initialized = true if self.ui.document.info.has_pages then return end if not self.ui.document:hasPageMap() then return end self.has_pagemap = true self:resetLayout() self.ui.menu:registerToMainMenu(self) self.view:registerViewModule("pagemap", self) end function ReaderPageMap:resetLayout() if not self.initialized then return end if self[1] then self[1]:free() self[1] = nil end if not self.show_page_labels then return end self.container = OverlapGroup:new{ dimen = Screen:getSize(), -- Pages in 2-page mode are not mirrored, so we'll -- have to handle any mirroring tweak ourselves allow_mirroring = false, } self[1] = self.container -- Get some metric for label min width self.label_face = Font:getFace(self.label_font_face, self.label_font_size) local textw = TextWidget:new{ text = " ", face = self.label_face, } self.space_width = textw:getWidth() textw:setText("8") self.number_width = textw:getWidth() textw:free() self.min_label_width = self.space_width * 2 + self.number_width end function ReaderPageMap:onReadSettings(config) local h_margins = config:readSetting("copt_h_page_margins") or G_reader_settings:readSetting("copt_h_page_margins") or DCREREADER_CONFIG_H_MARGIN_SIZES_MEDIUM self.max_left_label_width = Screen:scaleBySize(h_margins[1]) self.max_right_label_width = Screen:scaleBySize(h_margins[2]) if config:has("pagemap_show_page_labels") then self.show_page_labels = config:isTrue("pagemap_show_page_labels") else self.show_page_labels = G_reader_settings:nilOrTrue("pagemap_show_page_labels") end if config:has("pagemap_use_page_labels") then self.use_page_labels = config:isTrue("pagemap_use_page_labels") else self.use_page_labels = G_reader_settings:isTrue("pagemap_use_page_labels") end end function ReaderPageMap:onSetPageMargins(margins) if not self.has_pagemap then return end self.max_left_label_width = Screen:scaleBySize(margins[1]) self.max_right_label_width = Screen:scaleBySize(margins[3]) self:resetLayout() end function ReaderPageMap:cleanPageLabel(label) -- Cleanup page label, that may contain some noise (as they -- were meant to be shown in a list, like a TOC) label = label:gsub("[Pp][Aa][Gg][Ee]%s*", "") -- remove leading "Page " from "Page 123" return label end function ReaderPageMap:updateVisibleLabels() -- This might be triggered before PostInitCallback is if not self.initialized then return end if not self.has_pagemap then return end if not self.show_page_labels then return end self.container:clear() local page_labels = self.ui.document:getPageMapVisiblePageLabels() local footer_height = ((self.view.footer_visible and not self.view.footer.settings.reclaim_height) and 1 or 0) * self.view.footer:getHeight() local max_y = Screen:getHeight() - footer_height local last_label_bottom_y = 0 for _, page in ipairs(page_labels) do local in_left_margin = self._mirroredUI if self.ui.document:getVisiblePageCount() > 1 then -- Pages in 2-page mode are not mirrored, so we'll -- have to handle any mirroring tweak ourselves in_left_margin = page.screen_page == 1 end local max_label_width = in_left_margin and self.max_left_label_width or self.max_right_label_width if max_label_width < self.min_label_width then max_label_width = self.min_label_width end local label_width = max_label_width - 2 * self.space_width -- one space to screen edge, one to content local text = self:cleanPageLabel(page.label) local label_widget = TextBoxWidget:new{ text = text, width = label_width, face = self.label_face, line_height = 0, -- no additional line height fgcolor = self.label_color, alignment = not in_left_margin and "right", alignment_strict = true, } local label_height = label_widget:getTextHeight() local frame = FrameContainer:new{ bordersize = 0, padding = 0, padding_left = in_left_margin and self.space_width, padding_right = not in_left_margin and self.space_width, label_widget, allow_mirroring = false, } local offset_x = in_left_margin and 0 or Screen:getWidth() - frame:getSize().w local offset_y = page.screen_y if offset_y < last_label_bottom_y then -- Avoid consecutive labels to overwrite themselbes offset_y = last_label_bottom_y end if offset_y + label_height > max_y then -- Push label up so it's fully above footer offset_y = max_y - label_height end last_label_bottom_y = offset_y + label_height frame.overlap_offset = {offset_x, offset_y} table.insert(self.container, frame) end end -- Events that may change page draw offset, and might need visible labels -- to be updated to get their correct screen y ReaderPageMap.onPageUpdate = ReaderPageMap.updateVisibleLabels ReaderPageMap.onPosUpdate = ReaderPageMap.updateVisibleLabels ReaderPageMap.onChangeViewMode = ReaderPageMap.updateVisibleLabels ReaderPageMap.onSetStatusLine = ReaderPageMap.updateVisibleLabels function ReaderPageMap:onShowPageList() -- build up item_table local cur_page = self.ui.document:getCurrentPage() local cur_page_idx = 0 local page_list = self.ui.document:getPageMap() for k, v in ipairs(page_list) do v.text = v.label v.mandatory = v.page if v.page <= cur_page then cur_page_idx = k end end if cur_page_idx > 0 then -- Have Menu jump to the current page and show it in bold page_list.current = cur_page_idx end -- We use the per-page and font-size settings set for the ToC local items_per_page = G_reader_settings:readSetting("toc_items_per_page") or 14 local items_font_size = G_reader_settings:readSetting("toc_items_font_size") or Menu.getItemFontSize(items_per_page) local items_with_dots = G_reader_settings:nilOrTrue("toc_items_with_dots") local pl_menu = Menu:new{ title = _("Reference page numbers list"), item_table = page_list, is_borderless = true, is_popout = false, width = Screen:getWidth(), height = Screen:getHeight(), cface = Font:getFace("x_smallinfofont"), items_per_page = items_per_page, items_font_size = items_font_size, line_color = require("ffi/blitbuffer").COLOR_WHITE, single_line = true, align_baselines = true, with_dots = items_with_dots, on_close_ges = { GestureRange:new{ ges = "two_finger_swipe", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), }, direction = BD.flipDirectionIfMirroredUILayout("east") } } } self.pagelist_menu = CenterContainer:new{ dimen = Screen:getSize(), covers_fullscreen = true, -- hint for UIManager:_repaint() pl_menu, } -- buid up menu widget method as closure local pagemap = self function pl_menu:onMenuChoice(item) pagemap.ui.link:addCurrentLocationToStack() pagemap.ui.rolling:onGotoXPointer(item.xpointer) end pl_menu.close_callback = function() UIManager:close(self.pagelist_menu) end pl_menu.show_parent = self.pagelist_menu self.refresh = function() pl_menu:updateItems() end UIManager:show(self.pagelist_menu) return true end function ReaderPageMap:wantsPageLabels() return self.has_pagemap and self.use_page_labels end function ReaderPageMap:getCurrentPageLabel(clean_label) -- Note: in scroll mode with PDF, when multiple pages are shown on -- the screen, the advertized page number is the greatest page number -- among the pages shown (so, the page number of the partial page -- shown at bottom of screen). -- For consistency, getPageMapCurrentPageLabel() returns the last page -- label shown in the view if there are more than one (or the previous -- one if there is none). local label = self.ui.document:getPageMapCurrentPageLabel() return clean_label and self:cleanPageLabel(label) or label end function ReaderPageMap:getFirstPageLabel(clean_label) local label = self.ui.document:getPageMapFirstPageLabel() return clean_label and self:cleanPageLabel(label) or label end function ReaderPageMap:getLastPageLabel(clean_label) local label = self.ui.document:getPageMapLastPageLabel() return clean_label and self:cleanPageLabel(label) or label end function ReaderPageMap:getXPointerPageLabel(xp, clean_label) local label = self.ui.document:getPageMapXPointerPageLabel(xp) return clean_label and self:cleanPageLabel(label) or label end function ReaderPageMap:getRenderedPageNumber(page_label, cleaned) -- Only used from ReaderGoTo. As page_label is a string, no -- way to use a binary search: do a full scan of the PageMap -- here in Lua, even if it's not cheap. local page_list = self.ui.document:getPageMap() for k, v in ipairs(page_list) do local label = cleaned and self:cleanPageLabel(v.label) or v.label if label == page_label then return v.page end end end function ReaderPageMap:addToMainMenu(menu_items) menu_items.page_map = { -- @translators This and the other related ones refer to alternate page numbers provided in some EPUB books, that usually reference page numbers in a specific hardcopy edition of the book. text = _("Reference pages"), sub_item_table ={ { -- @translators This shows the <dc:source> in the EPUB that usually tells which hardcopy edition the reference page numbers refers to. text = _("Reference source info"), enabled_func = function() return self.ui.document:getPageMapSource() ~= nil end, callback = function() local text = T(_("Source (book hardcopy edition) of reference page numbers:\n\n%1"), self.ui.document:getPageMapSource()) local InfoMessage = require("ui/widget/infomessage") local infomsg = InfoMessage:new{ text = text, } UIManager:show(infomsg) end, keep_menu_open = true, }, { text = _("Reference page numbers list"), callback = function() self:onShowPageList() end, }, { text = _("Use reference page numbers"), checked_func = function() return self.use_page_labels end, callback = function() self.use_page_labels = not self.use_page_labels self.ui.doc_settings:saveSetting("pagemap_use_page_labels", self.use_page_labels) -- Reset a few stuff that may use page labels self.ui.toc:resetToc() self.ui.view.footer:onUpdateFooter() UIManager:setDirty(self.view.dialog, "partial") end, hold_callback = function(touchmenu_instance) local use_page_labels = G_reader_settings:isTrue("pagemap_use_page_labels") UIManager:show(MultiConfirmBox:new{ text = use_page_labels and _("The default (★) for newly opened books that have a reference page numbers map is to use these reference page numbers instead of the renderer page numbers.\n\nWould you like to change it?") or _("The default (★) for newly opened books that have a reference page numbers map is to not use these reference page numbers and keep using the renderer page numbers.\n\nWould you like to change it?"), choice1_text_func = function() return use_page_labels and _("Renderer") or _("Renderer (★)") end, choice1_callback = function() G_reader_settings:makeFalse("pagemap_use_page_labels") if touchmenu_instance then touchmenu_instance:updateItems() end end, choice2_text_func = function() return use_page_labels and _("Reference (★)") or _("Reference") end, choice2_callback = function() G_reader_settings:makeTrue("pagemap_use_page_labels") if touchmenu_instance then touchmenu_instance:updateItems() end end, }) end, separator = true, }, { text = _("Show reference page labels in margin"), checked_func = function() return self.show_page_labels end, callback = function() self.show_page_labels = not self.show_page_labels self.ui.doc_settings:saveSetting("pagemap_show_page_labels", self.show_page_labels) self:resetLayout() self:updateVisibleLabels() UIManager:setDirty(self.view.dialog, "partial") end, hold_callback = function(touchmenu_instance) local show_page_labels = G_reader_settings:nilOrTrue("pagemap_show_page_labels") UIManager:show(MultiConfirmBox:new{ text = show_page_labels and _("The default (★) for newly opened books that have a reference page numbers map is to show reference page number labels in the margin.\n\nWould you like to change it?") or _("The default (★) for newly opened books that have a reference page numbers map is to not show reference page number labels in the margin.\n\nWould you like to change it?"), choice1_text_func = function() return show_page_labels and _("Hide") or _("Hide (★)") end, choice1_callback = function() G_reader_settings:makeFalse("pagemap_show_page_labels") if touchmenu_instance then touchmenu_instance:updateItems() end end, choice2_text_func = function() return show_page_labels and _("Show (★)") or _("Show") end, choice2_callback = function() G_reader_settings:makeTrue("pagemap_show_page_labels") if touchmenu_instance then touchmenu_instance:updateItems() end end, }) end, }, { text_func = function() return T(_("Page labels font size (%1)"), self.label_font_size) end, enabled_func = function() return self.show_page_labels end, callback = function(touchmenu_instance) local SpinWidget = require("ui/widget/spinwidget") local spin_w = SpinWidget:new{ width = math.floor(Screen:getWidth() * 0.6), value = self.label_font_size, value_min = 8, value_max = 20, default_value = self.label_default_font_size, title_text = _("Page labels font size"), keep_shown_on_apply = true, callback = function(spin) self.label_font_size = spin.value G_reader_settings:saveSetting("pagemap_label_font_size", self.label_font_size) if touchmenu_instance then touchmenu_instance:updateItems() end self:resetLayout() self:updateVisibleLabels() UIManager:setDirty(self.view.dialog, "partial") end, } UIManager:show(spin_w) end, keep_menu_open = true, }, }, } end return ReaderPageMap
agpl-3.0
nsimplex/Tallbrood
scripts/tallbrood/wicker/utils/string.lua
2
1130
--[[ Copyright (C) 2013 simplex This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- --@@ENVIRONMENT BOOTUP local _modname = assert( (assert(..., 'This file should be loaded through require.')):match('^[%a_][%w_%s]*') , 'Invalid path.' ) module( ..., require(_modname .. '.booter') ) --@@END ENVIRONMENT BOOTUP function Capitalize(s) -- The extra parentheses are to trim the return list to 1 return value. return (s:lower():gsub( '^(%w)', string.upper ):gsub( '(%s%w)', string.upper )) end capitalize = Capitalize BindModule 'string' return _M
gpl-2.0
Evsdd/domoticz
dzVents/runtime/device-adapters/Adapters.lua
4
4226
local genericAdapter = require('generic_device') local deviceAdapters = { 'airquality_device', 'alert_device', 'ampere_1_phase_device', 'ampere_3_phase_device', 'barometer_device', 'counter_device', 'custom_sensor_device', 'distance_device', 'electric_usage_device', 'evohome_device', 'gas_device', 'group_device', 'humidity_device', 'kwh_device', 'leafwetness_device', 'logitech_media_server_device', 'lux_device', 'onkyo_device', 'opentherm_gateway_device', 'p1_smartmeter_device', 'percentage_device', 'pressure_device', 'rain_device', 'rgbw_device', 'scaleweight_device', 'scene_device', 'security_device', 'solar_radiation_device', 'soilmoisture_device', 'soundlevel_device', 'switch_device', 'thermostat_setpoint_device', 'temperature_device', 'temperature_barometer_device', 'temperature_humidity_device', 'temperature_humidity_barometer_device', 'text_device', 'uv_device', 'visibility_device', 'voltage_device', 'youless_device', 'waterflow_device', 'wind_device', 'zone_heating_device', 'zwave_thermostat_mode_device', 'kodi_device' } local utils = require('Utils') function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields + 1] = c end) return fields end local function DeviceAdapters(dummyLogger) local self = {} self.name = 'Adapter manager' function self.getDeviceAdapters(device) -- find a matching adapters local adapters = {} for i, adapterName in pairs(deviceAdapters) do -- do a safe call and catch possible errors ok, adapter = pcall(require, adapterName) if (not ok) then utils.log(adapter, utils.LOG_ERROR) else if (adapter.baseType == device.baseType) then local matches = adapter.matches(device, self) if (matches) then table.insert(adapters, adapter) end end end end return adapters end self.genericAdapter = genericAdapter self.deviceAdapters = deviceAdapters function self.parseFormatted (sValue, radixSeparator) local splitted = string.split(sValue, ' ') local sV = splitted[1] local unit = splitted[2] -- normalize radix to . if (sV ~= nil) then sV = string.gsub(sV, '%' .. radixSeparator, '.') end local value = sV ~= nil and tonumber(sV) or 0 return { ['value'] = value, ['unit'] = unit ~= nil and unit or '' } end function self.getDummyMethod(device, name) if (dummyLogger ~= nil) then dummyLogger(device, name) end return function() utils.log('Method ' .. name .. ' is not available for device "' .. device.name .. '" (deviceType=' .. device.deviceType .. ', deviceSubType=' .. device.deviceSubType .. '). ' .. 'If you believe this is not correct, please report.', utils.LOG_ERROR) end end function self.addDummyMethod(device, name) if (device[name] == nil) then device[name] = self.getDummyMethod(device, name) end end function self.round(num, numDecimalPlaces) if (num == nil) then --print(debug.traceback()) num = 0 end local mult = 10 ^ (numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end self.states = { on = { b = true, inv = 'Off' }, open = { b = true, inv = 'Off' }, ['group on'] = { b = true }, panic = { b = true, inv = 'Off' }, normal = { b = true, inv = 'Alarm' }, alarm = { b = true, inv = 'Normal' }, chime = { b = true }, video = { b = true }, audio = { b = true }, photo = { b = true }, playing = { b = true, inv = 'Pause' }, motion = { b = true }, off = { b = false, inv = 'On' }, closed = { b = false, inv = 'On' }, unlocked = { b = false, inv = 'On' }, locked = { b = true, inv = 'Off' }, ['group off'] = { b = false }, ['panic end'] = { b = false }, ['no motion'] = { b = false, inv = 'Off' }, stop = { b = false, inv = 'Open' }, stopped = { b = false }, paused = { b = false, inv = 'Play' }, ['all on'] = { b = true, inv = 'All Off' }, ['all off'] = { b = false, inv = 'All On' }, ['nightmode'] = { b = true, inv = 'Off' }, ['set to white'] = { b = true, inv = 'Off' }, ['set kelvin level'] = { b = true, inv = 'Off' }, } return self end return DeviceAdapters
gpl-3.0
bnetcc/darkstar
scripts/zones/Gusgen_Mines/npcs/qm4.lua
5
1112
----------------------------------- -- Area: Gusgen Mines -- NPC: qm4 (???) -- Involved In Quest: Ghosts of the Past -- !pos -174 0 369 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST) == QUEST_ACCEPTED and player:hasItem(13122) == false) then if (trade:hasItemQty(605,1) and trade:getItemCount() == 1) then -- Trade Pickaxe player:tradeComplete(); SpawnMob(17580337,300):updateClaim(player); end end end; function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/mobskills/pyric_bulwark.lua
5
1129
--------------------------------------------- -- Pyric Bulwark -- -- Description: Grants a Physical Shield effect for a time. -- Type: Enhancing -- -- Range: Self --------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1796) then return 0; else return 1; end end -- TODO: Used only when second/left head is alive (animationsub 0 or 1) if (mob:AnimationSub() <= 1) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) -- addEx to pervent dispel mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD,0,1,0,45) skill:setMsg(msgBasic.SKILL_GAIN_EFFECT) if (mob:getFamily() == 313) then -- Tinnin follows this up immediately with Nerve Gas mob:useMobAbility(1580); end return EFFECT_PHYSICAL_SHIELD; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Bastok_Markets/npcs/Harmodios.lua
5
1892
----------------------------------- -- Area: Bastok Markets -- NPC: Harmodios -- Standard Merchant NPC -- !pos -79.928 -4.824 -135.114 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/shop"); function onTrigger(player,npc) local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,10) == false) then player:startEvent(430); elseif (player:getVar("comebackQueenCS") == 1) then player:startEvent(490); else player:showText(npc,HARMODIOS_SHOP_DIALOG); local stock = { 17347, 990, 1, -- Piccolo 17344, 219, 2, -- Cornette 17353, 43, 2, -- Maple Harp 5041 , 69120, 2, -- Scroll of Vital Etude 5042 , 66240, 2, -- Scroll of Swift Etude 5043 , 63360, 2, -- Scroll of Sage Etude 5044 , 56700, 2, -- Scroll of Logical Etude 5039 , 79560, 2, -- Scroll of Herculean Etude 5040 , 76500, 2, -- Scroll of Uncanny Etude 17351, 4644, 3, -- Gemshorn 17345, 43, 3, -- Flute 5045 , 54000, 3, -- Scroll of Bewitching Etude } showNationShop(player, NATION_BASTOK, stock); end; end; function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if (csid == 430) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",10,true); elseif (csid == 490) then player:startEvent(491); elseif (csid == 491) then player:setVar("comebackQueenCS", 2); end; end;
gpl-3.0
samdmarshall/necromancy
src/necromancy/models/color.lua
1
1294
local struct = require("struct") local color = {} Color = struct { normal = "", bold = "", underline = "", } color.DefaultDefault = Color { normal = "default", bold = "bold", underline = "underline", } color.DefaultBlack = Color { normal = "black", bold = "bold", underline = "underline", } color.DefaultRed = Color { normal = "red", bold = "bold", underline = "underline", } color.DefaultGreen = Color { normal = "green", bold = "bold", underline = "underline", } color.DefaultYellow = Color { normal = "yellow", bold = "bold", underline = "underline", } color.DefaultBlue = Color { normal = "blue", bold = "bold", underline = "underline", } color.DefaultMagenta = Color { normal = "magenta", bold = "bold", underline = "underline", } color.DefaultCyan = Color { normal = "cyan", bold = "bold", underline = "underline", } color.DefaultWhite = Color { normal = "white", bold = "bold", underline = "underline", } color.name = {"default", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"} color.defaults = {color.DefaultDefault, color.DefaultBlack, color.DefaultRed, color.DefaultGreen, color.DefaultYellow, color.DefaultBlue, color.DefaultMagenta, color.DefaultCyan, color.DefaultWhite} return color
bsd-3-clause
lcf258/openwrtcn
applications/luci-app-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua
68
2351
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. 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
apache-2.0
bnetcc/darkstar
scripts/zones/Cloister_of_Storms/Zone.lua
5
1078
----------------------------------- -- -- Zone: Cloister_of_Storms (202) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Storms/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(517.957,-18.013,540.045,0); end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
BHH-team/BHH-team
plugins/inpm.lua
1
3114
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end --Copyright; @Xx_minister_salib_xX --Persian Translate; @Xx_minister_salib_xX --ch : @Xx_etehad_salib_xX
gpl-2.0
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/applications/luci-radvd/luasrc/model/cbi/radvd/interface.lua
78
7996
--[[ LuCI - Lua Configuration Interface Copyright 2010 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 sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - Interface %q", "?"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "interface" then luci.http.redirect(m.redirect) return end m.uci:foreach("radvd", "interface", function(s) if s['.name'] == sid and s.interface then m.title = translatef("Radvd - Interface %q", s.interface) return false end end) s = m:section(NamedSection, sid, "interface", translate("Interface Configuration")) s.addremove = false s:tab("general", translate("General")) s:tab("timing", translate("Timing")) s:tab("mobile", translate("Mobile IPv6")) -- -- General -- o = s:taboption("general", Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:taboption("general", Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:taboption("general", DynamicList, "client", translate("Clients"), translate("Restrict communication to specified clients, leave empty to use multicast")) o.rmempty = true o.datatype = "ip6addr" o.placeholder = "any" function o.cfgvalue(...) local v = Value.cfgvalue(...) local l = { } for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:taboption("general", Flag, "AdvSendAdvert", translate("Enable advertisements"), translate("Enables router advertisements and solicitations")) o.rmempty = false function o.write(self, section, value) if value == "1" then m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "IgnoreIfMissing", 1) end m.uci:set("radvd", section, "AdvSendAdvert", value) end o = s:taboption("general", Flag, "UnicastOnly", translate("Unicast only"), translate("Indicates that the underlying link is not broadcast capable, prevents unsolicited advertisements from being sent")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvManagedFlag", translate("Managed flag"), translate("Enables the additional stateful administered autoconfiguration protocol (RFC2462)")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvOtherConfigFlag", translate("Configuration flag"), translate("Enables the autoconfiguration of additional, non address information (RFC2462)")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvSourceLLAddress", translate("Source link-layer address"), translate("Includes the link-layer address of the outgoing interface in the RA")) o.rmempty = false o.default = "1" o:depends("AdvSendAdvert", "1") o = s:taboption("general", Value, "AdvLinkMTU", translate("Link MTU"), translate("Advertises the given link MTU in the RA if specified. 0 disables MTU advertisements")) o.datatype = "uinteger" o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("general", Value, "AdvCurHopLimit", translate("Current hop limit"), translate("Advertises the default Hop Count value for outgoing unicast packets in the RA. 0 disables hopcount advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 64 o:depends("AdvSendAdvert", "1") o = s:taboption("general", ListValue, "AdvDefaultPreference", translate("Default preference"), translate("Advertises the default router preference")) o.optional = false o.default = "medium" o:value("low", translate("low")) o:value("medium", translate("medium")) o:value("high", translate("high")) o:depends("AdvSendAdvert", "1") -- -- Timing -- o = s:taboption("timing", Value, "MinRtrAdvInterval", translate("Minimum advertisement interval"), translate("The minimum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 198 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "MaxRtrAdvInterval", translate("Maximum advertisement interval"), translate("The maximum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 600 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "MinDelayBetweenRAs", translate("Minimum advertisement delay"), translate("The minimum time allowed between sending multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 3 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvReachableTime", translate("Reachable time"), translate("Advertises assumed reachability time in milliseconds of neighbours in the RA if specified. 0 disables reachability advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvRetransTimer", translate("Retransmit timer"), translate("Advertises wait time in milliseconds between Neighbor Solicitation messages in the RA if specified. 0 disables retransmit advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvDefaultLifetime", translate("Default lifetime"), translate("Advertises the lifetime of the default router in seconds. 0 indicates that the node is no default router")) o.datatype = "uinteger" o.optional = false o.placeholder = 1800 o:depends("AdvSendAdvert", "1") -- -- Mobile -- o = s:taboption("mobile", Flag, "AdvHomeAgentFlag", translate("Advertise Home Agent flag"), translate("Advertises Mobile IPv6 Home Agent capability (RFC3775)")) o:depends("AdvSendAdvert", "1") o = s:taboption("mobile", Flag, "AdvIntervalOpt", translate("Mobile IPv6 interval option"), translate("Include Mobile IPv6 Advertisement Interval option to RA")) o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Flag, "AdvHomeAgentInfo", translate("Home Agent information"), translate("Include Home Agent Information in the RA")) o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Flag, "AdvMobRtrSupportFlag", translate("Mobile IPv6 router registration"), translate("Advertises Mobile Router registration capability (NEMO Basic)")) o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Value, "HomeAgentLifetime", translate("Home Agent lifetime"), translate("Advertises the time in seconds the router is offering Mobile IPv6 Home Agent services")) o.datatype = "uinteger" o.optional = false o.placeholder = 1800 o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Value, "HomeAgentPreference", translate("Home Agent preference"), translate("The preference for the Home Agent sending this RA")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) return m
gpl-2.0
bnetcc/darkstar
scripts/zones/Port_San_dOria/npcs/Answald.lua
5
1305
----------------------------------- -- Area: Port San d'Oria -- NPC: Answald -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeAnswald") == 0) then player:messageSpecial(ANSWALD_DIALOG); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeAnswald",1); player:messageSpecial(FLYERS_HANDED, 17 - player:getVar("FFR")); elseif (player:getVar("tradeAnswald") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; function onTrigger(player,npc) player:startEvent(584); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Hall_of_Transference/npcs/_0e8.lua
5
1366
----------------------------------- -- Area: Hall of Transference -- NPC: Large Apparatus (Right) - Mea -- !pos 290.253 -81.849 -42.381 14 ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("MeaChipRegistration") == 0 and player:getVar("skyShortcut") == 1 and trade:hasItemQty(478,1) and trade:getItemCount() == 1) then player:tradeComplete(); player:startEvent(164); end end; function onTrigger(player,npc) if (player:getVar("MeaChipRegistration") == 1) then player:messageSpecial(NO_RESPONSE_OFFSET+6); -- Device seems to be functioning correctly. else player:startEvent(163); -- Hexagonal Cones end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 164) then player:messageSpecial(NO_RESPONSE_OFFSET+4,478); -- You fit.. player:messageSpecial(NO_RESPONSE_OFFSET+5); -- Device has been repaired player:setVar("MeaChipRegistration",1); end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/sage_etude.lua
5
1579
----------------------------------------- -- Spell: Sage Etude -- Static INT Boost, BRD 66 ----------------------------------------- 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 sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 416) then power = 12; elseif ((sLvl+iLvl >= 417) and (sLvl+iLvl <= 445)) then power = 13; elseif ((sLvl+iLvl >= 446) and (sLvl+iLvl <= 474)) then power = 14; elseif (sLvl+iLvl >= 475) then power = 15; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,10,duration,caster:getID(), MOD_INT, 2)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_ETUDE; end;
gpl-3.0
timmerk/cardpeek
dot_cardpeek_dir/scripts/vitale_2.lua
17
5057
-- -- This file is part of Cardpeek, the smartcard reader utility. -- -- Copyright 2009-2013 by 'L1L1' -- -- Cardpeek is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Cardpeek is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Cardpeek. If not, see <http://www.gnu.org/licenses/>. -- -- @description The French health card (Version 2) -- @targets 0.8 require('lib.tlv') function ui_parse_asciidate(node,data) local d = bytes.format(data,"%P") local t = os.time( { ['year'] = string.sub(d,1,4), ['month'] = string.sub(d,5,6), ['day'] = string.sub(d,7,8) } ) nodes.set_attribute(node,"val",data) nodes.set_attribute(node,"alt",os.date("%x",t)) return true end VITALE_IDO = { ['65'] = { "Bénéficiaire" }, ['65/90'] = { "Nationalité", ui_parse_printable }, ['65/93'] = { "Numéro de sécurité sociale", ui_parse_printable }, ['65/80'] = { "Nom", ui_parse_printable }, ['65/81'] = { "Prénom", ui_parse_printable }, ['65/82'] = { "Date de naissance", ui_parse_asciidate }, ['66'] = { "Carte vitale" }, ['66/80'] = { "Date de début de validité", ui_parse_asciidate }, ['7F21'] = { "Certificat" }, ['5F37'] = { "Signature de l'AC" }, ['5F38'] = { "Résidu de la clé publique" }, } function read_bin() local total, sw, resp, r total = bytes.new(8) r = 0 repeat sw, resp = card.read_binary(".",r) total = bytes.concat(total,resp) r = r + 256 until #resp~=256 or sw~=0x9000 if #total>0 then return 0x9000, total end return sw, total end AID_VITALE = "#D250000002564954414C45" AID_VITALE_MF = "#D2500000024D465F564954414C45" function create_card_map() local resp, sw local map = {} local tag,val,rest local tag2,val2,rest2 local entry, aid, file, name sw,resp = card.select(AID_VITALE) if sw~=0x9000 then return nil end sw,resp = card.select(".2001") if sw~=0x9000 then return nil end sw,resp = read_bin() if sw~=0x9000 then return nil end tag,val = asn1.split(resp) -- E0,DATA,nil tag,rest2,rest = asn1.split(val) -- A0,DATA,DATA repeat tag2,val2,rest2 = asn1.split(rest2) if tag2==0x82 then entry = tostring(bytes.sub(val2,0,1)) aid = "#"..tostring(bytes.sub(val2,4,-1)) map[entry]={ ['aid'] = aid, ['files'] = {} } end until rest2==nil or tag==0 repeat tag,val,rest = asn1.split(rest) if tag==0x80 then entry = tostring(bytes.sub(val,8,9)) file = "."..tostring(bytes.sub(val,10,11)) name = bytes.format(bytes.sub(val,0,7),"%P") table.insert(map[entry]['files'],{ ['name']=name, ['ef']=file }) end until rest==nil or tag==0 for entry in pairs(map) do if map[entry]['aid']==AID_VITALE_MF then table.insert(map[entry]['files'],{ ['name']="DIR", ['ef']=".2F00" }) table.insert(map[entry]['files'],{ ['name']="PAN", ['ef']=".2F02" }) elseif map[entry]['aid']==AID_VITALE then table.insert(map[entry]['files'],{ ['name']="POINTERS", ['ef']=".2001" }) end end return map end --[[ AID = { "D2500000024D465F564954414C45", "E828BD080FD2500000044164E86C65", "D2500000044164E86C650101" } --]] local header if card.connect() then CARD = card.tree_startup("VITALE 2") map = create_card_map() if map then for app in pairs(map) do sw,resp = card.select(map[app]['aid']) if sw==0x9000 then APP = CARD:append({ classname="application", label="Application", id=map[app]['aid'] }) header = APP:append({ classname="header", label="answer to select", size=#resp }) tlv_parse(header,resp) end for i in pairs(map[app]['files']) do EF = APP:append({ classname="file", label=map[app]['files'][i]['name'], id=map[app]['files'][i]['ef'] }) sw,resp = card.select(map[app]['files'][i]['ef']) header = EF:append({ classname="header", label="answer to select", size=#resp }) tlv_parse(header,resp) if sw==0x9000 then sw,resp = read_bin() CONTENT = EF:append({ classname="body", label="content", size=#resp }) if sw==0x9000 then if resp:get(0)==0 or (resp:get(0)==0x04 and resp:get(1)==0x00) then nodes.set_attribute(CONTENT,"val",resp) else tlv_parse(CONTENT,resp,VITALE_IDO) end else nodes.set_attribute(CONTENT,"alt",string.format("data not accessible (code %04X)",sw)) end end end end end card.disconnect() else ui.question("No card detected",{"OK"}) end
gpl-3.0
leonardoaxe/OpenRA
mods/ra/maps/soviet-06a/soviet06a-AI.lua
19
3128
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function() local lazyUnits = enemy.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) Trigger.OnDamaged(unit, function() Trigger.ClearAll(unit) Trigger.AfterDelay(0, function() IdleHunt(unit) end) end) end) end BaseApwr = { type = "apwr", pos = CVec.New(-13, 7), cost = 500, exists = true } BaseTent = { type = "tent", pos = CVec.New(-2, 12), cost = 400, exists = true } BaseProc = { type = "proc", pos = CVec.New(-7, 5), cost = 1400, exists = true } BaseWeap = { type = "weap", pos = CVec.New(-9, 11), cost = 2000, exists = true } BaseApwr2 = { type = "apwr", pos = CVec.New(-4, 1), cost = 500, exists = true } BaseBuildings = { BaseApwr, BaseTent, BaseProc, BaseWeap, BaseApwr2 } BuildBase = function() for i,v in ipairs(BaseBuildings) do if not v.exists then BuildBuilding(v) return end end Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end BuildBuilding = function(building) Trigger.AfterDelay(Actor.BuildTime(building.type), function() if CYard.IsDead or CYard.Owner ~= enemy then return elseif Harvester.IsDead and enemy.Resources <= 299 then return end local actor = Actor.Create(building.type, true, { Owner = enemy, Location = CYardLocation.Location + building.pos }) enemy.Cash = enemy.Cash - building.cost building.exists = true Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end) end ProduceInfantry = function() if not BaseTent.exists then return elseif Harvester.IsDead and enemy.Resources <= 299 then return end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(AlliedInfantryTypes) } local Path = Utils.Random(AttackPaths) enemy.Build(toBuild, function(unit) InfAttack[#InfAttack + 1] = unit[1] if #InfAttack >= 10 then SendUnits(InfAttack, Path) InfAttack = { } Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry) else Trigger.AfterDelay(delay, ProduceInfantry) end end) end ProduceArmor = function() if not BaseWeap.exists then return elseif Harvester.IsDead and enemy.Resources <= 599 then return end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(AlliedArmorTypes) } local Path = Utils.Random(AttackPaths) enemy.Build(toBuild, function(unit) ArmorAttack[#ArmorAttack + 1] = unit[1] if #ArmorAttack >= 6 then SendUnits(ArmorAttack, Path) ArmorAttack = { } Trigger.AfterDelay(DateTime.Minutes(3), ProduceArmor) else Trigger.AfterDelay(delay, ProduceArmor) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end) end
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/barbed_crescent.lua
1
1428
----------------------------------------- -- Spell: Barbed Crescent ----------------------------------------- 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 params = {}; params.effect = EFFECT_ACCURACY_DOWN; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_DISTORTION; params.numhits = 1; params.multiplier = 1.925; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 90; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.30; params.int_wsc = 0.10; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; local damage =BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 4) then target:delStatusEffect(params.effect); target:addStatusEffect(params.effect,4,0,getBlueEffectDuration(caster,resist,params.effect)); end return damage; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Bastok_Mines/npcs/Rashid.lua
5
3349
----------------------------------- -- Area: Bastok Mines -- NPC: Rashid -- Type: Mission Giver -- !pos -8.444 -2 -123.575 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) local CurrentMission = player:getCurrentMission(BASTOK); local Count = trade:getItemCount(); if (CurrentMission ~= 255) then if (CurrentMission == FETICHISM and player:hasCompletedMission(BASTOK,FETICHISM) == false and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(1008); -- Finish Mission "Fetichism" (First Time) elseif (CurrentMission == FETICHISM and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(1005); -- Finish Mission "Fetichism" (Repeat) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and player:hasCompletedMission(BASTOK,TO_THE_FORSAKEN_MINES) == false and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(1010); -- Finish Mission "To the forsaken mines" (First Time) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(1006); -- Finish Mission "To the forsaken mines" (Repeat) end end end; function onTrigger(player,npc) if (player:getNation() ~= NATION_BASTOK) then player:startEvent(1003); -- For non-Bastokian else local CurrentMission = player:getCurrentMission(BASTOK); local cs, p, offset = getMissionOffset(player,1,CurrentMission,player:getVar("MissionStatus")); if (cs ~= 0 or offset ~= 0 or ((CurrentMission == 0 or CurrentMission == 16) and offset == 0)) then if (CurrentMission <= 15 and cs == 0) then player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 1~5) elseif (CurrentMission > 15 and cs == 0) then player:showText(npc,EXTENDED_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 6~10) else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (player:getRank() == 1 and player:hasCompletedMission(BASTOK,THE_ZERUHN_REPORT) == false) then player:startEvent(1000); -- Start First Mission "The Zeruhn Report" elseif (CurrentMission ~= 255) then player:startEvent(1002); -- Have mission already activated else local flagMission, repeatMission = getMissionMask(player); player:startEvent(1001,flagMission,0,0,0,0,repeatMission); -- Mission List end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishMissionTimeline(player,1,csid,option); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Nashmau/npcs/Kakkaroon.lua
5
1923
----------------------------------- -- Area: Nashmau -- NPC: Kakkaroon -- Standard Info NPC -- !pos 13.245 0.000 -25.307 53 ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local ratrace = player:getQuestStatus(AHT_URHGAN,RAT_RACE); local ratRaceProg = player:getVar("ratraceCS"); if (ratrace == QUEST_AVAILABLE) then player:startEvent(308); elseif (ratRaceProg == 6) then player:startEvent(312); elseif (ratrace == QUEST_ACCEPTED) then player:startEvent(313); elseif (ratrace == QUEST_COMPLETED) then player:startEvent(314); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 308) then player:setVar("ratraceCS",1); player:addQuest(AHT_URHGAN,RAT_RACE); elseif (csid == 312) then if (player:getFreeSlotsCount() <= 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2187,2); player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2186,2); player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2185,3); else player:setVar("ratraceCS",0); player:addItem(2187,2); player:addItem(2186,2); player:addItem(2185,3); player:messageSpecial(ITEM_OBTAINEDX,2187,2); player:messageSpecial(ITEM_OBTAINEDX,2186,2); player:messageSpecial(ITEM_OBTAINEDX,2185,3); player:completeQuest(AHT_URHGAN,RAT_RACE); end end end;
gpl-3.0
best98ir/SASAN
plugins/tools.lua
1
72759
--Begin Tools.lua :) local SUDO = 157059515 -- put Your ID here! <=== function exi_files(cpath) local files = {} local pth = cpath for k, v in pairs(scandir(pth)) do table.insert(files, v) end return files end local function file_exi(name, cpath) for k,v in pairs(exi_files(cpath)) do if name == v then return true end end return false end local function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end local function index_function(user_id) for k,v in pairs(_config.admins) do if user_id == v[1] then print(k) return k end end -- If not found return false end local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end local function already_sudo(user_id) for k,v in pairs(_config.sudo_users) do if user_id == v then return k end end -- If not found return false end local function reload_plugins( ) plugins = {} load_plugins() end local function exi_file() local files = {} local pth = tcpath..'/data/document' for k, v in pairs(scandir(pth)) do if (v:match('.lua$')) then table.insert(files, v) end end return files end local function pl_exi(name) for k,v in pairs(exi_file()) do if name == v then return true end end return false end local function sudolist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = "*List of sudo users :*\n" else text = "_لیست سودو های ربات :_\n" end for i=1,#sudo_users do text = text..i.." - "..sudo_users[i].."\n" end return text end local function adminlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = '*List of bot admins :*\n' else text = "_لیست ادمین های ربات :_\n" end local compare = text local i = 1 for v,user in pairs(_config.admins) do text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n' i = i +1 end if compare == text then if not lang then text = '_No_ *admins* _available_' else text = '_ادمینی برای ربات تعیین نشده_' end end return text end local function chat_list(msg) i = 1 local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use #join (ID) to join*\n\n' for k,v in pairsByKeys(data[tostring(groups)]) do local group_id = v if data[tostring(group_id)] then settings = data[tostring(group_id)]['settings'] end for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n:gsub("", "") chat_name = name:gsub("‮", "") group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n' if name:match("[\216-\219][\128-\191]") then group_info = i..' - \n'..group_name_id else group_info = i..' - '..group_name_id end i = i + 1 end end message = message..group_info end return message end local function botrem(msg) local data = load_data(_config.moderation.data) data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) if redis:get('CheckExpire::'..msg.to.id) then redis:del('CheckExpire::'..msg.to.id) end if redis:get('ExpireDate:'..msg.to.id) then redis:del('ExpireDate:'..msg.to.id) end tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil) end local function warning(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local expiretime = redis:ttl('ExpireDate:'..msg.to.id) if expiretime == -1 then return else local d = math.floor(expiretime / 86400) + 1 if tonumber(d) == 1 and not is_sudo(msg) and is_mod(msg) then if lang then tdcli.sendMessage(msg.to.id, 0, 1, 'از شارژ گروه 1 روز باقی مانده، برای شارژ مجدد با سودو ربات تماس بگیرید وگرنه با اتمام زمان شارژ، گروه از لیست ربات حذف وربات گروه را ترک خواهد کرد.', 1, 'md') else tdcli.sendMessage(msg.to.id, 0, 1, '_Group 1 day remaining charge, to recharge the robot contact with the sudo. With the completion of charging time, the group removed from the robot list and the robot will leave the group._', 1, 'md') end end end end local function action_by_reply(arg, data) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "adminprom" then local function adminprom_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "admindem" then local function admindem_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local nameid = index_function(tonumber(data.id_)) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "visudo" then local function visudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "desudo" then local function desudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(arg.user_id) then return false end if data.id_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function pre_process(msg) if msg.to.type ~= 'pv' then local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local gpst = data[tostring(msg.to.id)] local chex = redis:get('CheckExpire::'..msg.to.id) local exd = redis:get('ExpireDate:'..msg.to.id) if gpst and not chex and msg.from.id ~= SUDO and not is_sudo(msg) then redis:set('CheckExpire::'..msg.to.id,true) redis:set('ExpireDate:'..msg.to.id,true) redis:setex('ExpireDate:'..msg.to.id, 86400, true) if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 1 روز شارژ شد. لطفا با سودو برای شارژ بیشتر تماس بگیرید. در غیر اینصورت گروه شما از لیست ربات حذف و ربات گروه را ترک خواهد کرد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 1 day. to recharge the robot contact with the sudo. With the completion of charging time, the group removed from the robot list and the robot will leave the group._', 1, 'md') end end if chex and not exd and msg.from.id ~= SUDO and not is_sudo(msg) then local text1 = 'شارژ این گروه به اتمام رسید \n\nID: <code>'..msg.to.id..'</code>\n\nدر صورتی که میخواهید ربات این گروه را ترک کند از دستور زیر استفاده کنید\n\n/leave '..msg.to.id..'\nبرای جوین دادن توی این گروه میتونی از دستور زیر استفاده کنی:\n/jointo '..msg.to.id..'\n_________________\nدر صورتی که میخواهید گروه رو دوباره شارژ کنید میتوانید از کد های زیر استفاده کنید...\n\n<b>برای شارژ 1 ماهه:</b>\n/plan 1 '..msg.to.id..'\n\n<b>برای شارژ 3 ماهه:</b>\n/plan 2 '..msg.to.id..'\n\n<b>برای شارژ نامحدود:</b>\n/plan 3 '..msg.to.id local text2 = '_شارژ این گروه به پایان رسید. به دلیل عدم شارژ مجدد، گروه از لیست ربات حذف و ربات از گروه خارج میشود._' local text3 = '_Charging finished._\n\n*Group ID:*\n\n*ID:* `'..msg.to.id..'`\n\n*If you want the robot to leave this group use the following command:*\n\n`/Leave '..msg.to.id..'`\n\n*For Join to this group, you can use the following command:*\n\n`/Jointo '..msg.to.id..'`\n\n_________________\n\n_If you want to recharge the group can use the following code:_\n\n*To charge 1 month:*\n\n`/Plan 1 '..msg.to.id..'`\n\n*To charge 3 months:*\n\n`/Plan 2 '..msg.to.id..'`\n\n*For unlimited charge:*\n\n`/Plan 3 '..msg.to.id..'`' local text4 = '_Charging finished. Due to lack of recharge remove the group from the robot list and the robot leave the group._' if lang then tdcli.sendMessage(SUDO, 0, 1, text1, 1, 'html') tdcli.sendMessage(msg.to.id, 0, 1, text2, 1, 'md') else tdcli.sendMessage(SUDO, 0, 1, text3, 1, 'md') tdcli.sendMessage(msg.to.id, 0, 1, text4, 1, 'md') end botrem(msg) else local expiretime = redis:ttl('ExpireDate:'..msg.to.id) local day = (expiretime / 86400) if tonumber(day) > 0.208 and not is_sudo(msg) and is_mod(msg) then warning(msg) end end end end local function run(msg, matches) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local Chash = "cmd_lang:"..msg.to.id local Clang = redis:get(Chash) if tonumber(msg.from.id) == SUDO then if ((matches[1] == "clear cache" and not Clang) or (matches[1] == "پاک کردن حافظه" and Clang)) then run_bash("rm -rf ~/.telegram-cli/data/sticker/*") run_bash("rm -rf ~/.telegram-cli/data/photo/*") run_bash("rm -rf ~/.telegram-cli/data/animation/*") run_bash("rm -rf ~/.telegram-cli/data/video/*") run_bash("rm -rf ~/.telegram-cli/data/audio/*") run_bash("rm -rf ~/.telegram-cli/data/voice/*") run_bash("rm -rf ~/.telegram-cli/data/temp/*") run_bash("rm -rf ~/.telegram-cli/data/thumb/*") run_bash("rm -rf ~/.telegram-cli/data/document/*") run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*") run_bash("rm -rf ~/.telegram-cli/data/encrypted/*") run_bash("rm -rf ./data/photos/*") return "*All Cache Has Been Cleared*" end if ((matches[1] == "visudo" and not Clang) or (matches[1] == "سودو" and Clang)) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="visudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="visudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="visudo"}) end end if ((matches[1] == "desudo" and not Clang) or (matches[1] == "حذف سودو" and Clang)) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="desudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="desudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="desudo"}) end end end if ((matches[1] == "config" and not Clang) or (matches[1] == "پیکربندی" and Clang)) and is_admin(msg) then return set_config(msg) end if is_sudo(msg) then if ((matches[1]:lower() == 'add' and not Clang) or (matches[1] == "افزودن" and Clang)) and not redis:get('ExpireDate:'..msg.to.id) then redis:set('ExpireDate:'..msg.to.id,true) redis:setex('ExpireDate:'..msg.to.id, 180, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 3 دقیقه برای اجرای تنظیمات شارژ میباشد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 3 minutes for settings._', 1, 'md') end end if ((matches[1] == 'rem' and not Clang) or (matches[1] == "حذف گروه" and Clang)) then if redis:get('CheckExpire::'..msg.to.id) then redis:del('CheckExpire::'..msg.to.id) end redis:del('ExpireDate:'..msg.to.id) end if ((matches[1]:lower() == 'gid' and not Clang) or (matches[1] == "اطلاعات" and Clang)) then tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..msg.to.id..'`', 1,'md') end if ((matches[1] == 'leave' and not Clang) or (matches[1] == "خروج" and Clang)) and matches[2] then if lang then tdcli.sendMessage(matches[2], 0, 1, 'ربات با دستور سودو از گروه خارج شد.\nبرای اطلاعات بیشتر با سودو تماس بگیرید.', 1, 'md') tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil) tdcli.sendMessage(SUDO, msg.id_, 1, 'ربات با موفقیت از گروه '..matches[2]..' خارج شد.', 1,'md') else tdcli.sendMessage(matches[2], 0, 1, '_Robot left the group._\n*For more information contact The SUDO.*', 1, 'md') tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil) tdcli.sendMessage(SUDO, msg.id_, 1, '*Robot left from under group successfully:*\n\n`'..matches[2]..'`', 1,'md') end end if ((matches[1]:lower() == 'charge' and not Clang) or (matches[1] == "شارژ" and Clang)) and matches[2] and matches[3] then if string.match(matches[2], '^-%d+$') then if tonumber(matches[3]) > 0 and tonumber(matches[3]) < 1001 then local extime = (tonumber(matches[3]) * 86400) redis:setex('ExpireDate:'..matches[2], extime, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت '..matches[3]..' روز تمدید گردید.', 1, 'md') tdcli.sendMessage(matches[2], 0, 1, 'ربات توسط ادمین به مدت `'..matches[3]..'` روز شارژ شد\nبرای مشاهده زمان شارژ گروه دستور /check استفاده کنید...',1 , 'md') else tdcli.sendMessage(SUDO, 0, 1, '*Recharged successfully in the group:* `'..matches[2]..'`\n_Expire Date:_ `'..matches[3]..'` *Day(s)*', 1, 'md') tdcli.sendMessage(matches[2], 0, 1, '*Robot recharged* `'..matches[3]..'` *day(s)*\n*For checking expire date, send* `/check`',1 , 'md') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md') end end end end if ((matches[1]:lower() == 'plan' and not Clang) or (matches[1] == "پلن" and Clang)) then if matches[2] == '1' and matches[3] then if string.match(matches[3], '^-%d+$') then local timeplan1 = 2592000 redis:setex('ExpireDate:'..matches[3], timeplan1, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 1 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 30 روز دیگر اعتبار دارد! ( 1 ماه )', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '_ربات با موفقیت فعال شد و تا 30 روز دیگر اعتبار دارد!_', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 1 Successfully Activated!\nThis group recharged with plan 1 for 30 days (1 Month)*', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `30` *Days (1 Month)*', 1, 'md') end end end if matches[2] == '2' and matches[3] then if string.match(matches[3], '^-%d+$') then local timeplan2 = 7776000 redis:setex('ExpireDate:'..matches[3],timeplan2,true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, 0, 1, 'پلن 2 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, 'ربات با موفقیت فعال شد و تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 2 Successfully Activated!\nThis group recharged with plan 2 for 90 days (3 Month)*', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `90` *Days (3 Months)*', 1, 'md') end end end if matches[2] == '3' and matches[3] then if string.match(matches[3], '^-%d+$') then redis:set('ExpireDate:'..matches[3],true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 3 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه به صورت نامحدود شارژ شد!', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, 'ربات بدون محدودیت فعال شد ! ( نامحدود )', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 3 Successfully Activated!\nThis group recharged with plan 3 for unlimited*', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `Unlimited`', 1, 'md') end end end end if ((matches[1]:lower() == 'jointo' and not Clang) or (matches[1] == "ورود به" and Clang)) and matches[2] then if string.match(matches[2], '^-%d+$') then if lang then tdcli.sendMessage(SUDO, msg.id_, 1, 'با موفقیت تورو به گروه '..matches[2]..' اضافه کردم.', 1, 'md') tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil) tdcli.sendMessage(matches[2], 0, 1, '_سودو به گروه اضافه شد._', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*I added you to this group:*\n\n`'..matches[2]..'`', 1, 'md') tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil) tdcli.sendMessage(matches[2], 0, 1, 'Admin Joined!', 1, 'md') end end end end if ((matches[1]:lower() == 'savefile' and not Clang) or (matches[1] == "ذخیره فایل" and Clang)) and matches[2] and is_sudo(msg) then if msg.reply_id then local folder = matches[2] function get_filemsg(arg, data) function get_fileinfo(arg,data) if data.content_.ID == 'MessageDocument' or data.content_.ID == 'MessagePhoto' or data.content_.ID == 'MessageSticker' or data.content_.ID == 'MessageAudio' or data.content_.ID == 'MessageVoice' or data.content_.ID == 'MessageVideo' or data.content_.ID == 'MessageAnimation' then if data.content_.ID == 'MessageDocument' then local doc_id = data.content_.document_.document_.id_ local filename = data.content_.document_.file_name_ local pathf = tcpath..'/data/document/'..filename local cpath = tcpath..'/data/document' if file_exi(filename, cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(doc_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>فایل</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>File</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessagePhoto' then local photo_id = data.content_.photo_.sizes_[2].photo_.id_ local file = data.content_.photo_.id_ local pathf = tcpath..'/data/photo/'..file..'_(1).jpg' local cpath = tcpath..'/data/photo' if file_exi(file..'_(1).jpg', cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(photo_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>عکس</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Photo</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageSticker' then local stpath = data.content_.sticker_.sticker_.path_ local sticker_id = data.content_.sticker_.sticker_.id_ local secp = tostring(tcpath)..'/data/sticker/' local ffile = string.gsub(stpath, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') if file_exi(name, secp) then local pfile = folder os.rename(stpath, pfile) file_dl(sticker_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>استیکر</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Sticker</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageAudio' then local audio_id = data.content_.audio_.audio_.id_ local audio_name = data.content_.audio_.file_name_ local pathf = tcpath..'/data/audio/'..audio_name local cpath = tcpath..'/data/audio' if file_exi(audio_name, cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(audio_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صدای</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Audio</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageVoice' then local voice_id = data.content_.voice_.voice_.id_ local file = data.content_.voice_.voice_.path_ local secp = tostring(tcpath)..'/data/voice/' local ffile = string.gsub(file, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') if file_exi(name, secp) then local pfile = folder os.rename(file, pfile) file_dl(voice_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صوت</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Voice</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageVideo' then local video_id = data.content_.video_.video_.id_ local file = data.content_.video_.video_.path_ local secp = tostring(tcpath)..'/data/video/' local ffile = string.gsub(file, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') if file_exi(name, secp) then local pfile = folder os.rename(file, pfile) file_dl(video_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>ویديو</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Video</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageAnimation' then local anim_id = data.content_.animation_.animation_.id_ local anim_name = data.content_.animation_.file_name_ local pathf = tcpath..'/data/animation/'..anim_name local cpath = tcpath..'/data/animation' if file_exi(anim_name, cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(anim_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>تصویر متحرک</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Gif</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end else return end end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil) end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil) end end if msg.to.type == 'channel' or msg.to.type == 'chat' then if ((matches[1] == 'charge' and not Clang) or (matches[1] == "شارژ" and Clang)) and matches[2] and not matches[3] and is_sudo(msg) then if tonumber(matches[2]) > 0 and tonumber(matches[2]) < 1001 then local extime = (tonumber(matches[2]) * 86400) redis:setex('ExpireDate:'..msg.to.id, extime, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id) end if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md') tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md') tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md') end end end if ((matches[1]:lower() == 'check' and not Clang) or (matches[1] == "اعتبار" and Clang)) and is_mod(msg) and not matches[2] then local check_time = redis:ttl('ExpireDate:'..msg.to.id) year = math.floor(check_time / 31536000) byear = check_time % 31536000 month = math.floor(byear / 2592000) bmonth = byear % 2592000 day = math.floor(bmonth / 86400) bday = bmonth % 86400 hours = math.floor( bday / 3600) bhours = bday % 3600 min = math.floor(bhours / 60) sec = math.floor(bhours % 60) if not lang then if check_time == -1 then remained_expire = '_Unlimited Charging!_' elseif tonumber(check_time) > 1 and check_time < 60 then remained_expire = '_Expire until_ *'..sec..'* _sec_' elseif tonumber(check_time) > 60 and check_time < 3600 then remained_expire = '_Expire until_ '..min..' _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then remained_expire = '_Expire until_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 86400 and tonumber(check_time) < 2592000 then remained_expire = '_Expire until_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 2592000 and tonumber(check_time) < 31536000 then remained_expire = '_Expire until_ *'..month..'* _month_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 31536000 then remained_expire = '_Expire until_ *'..year..'* _year_ *'..month..'* _month_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' end tdcli.sendMessage(msg.to.id, msg.id_, 1, remained_expire, 1, 'md') else if check_time == -1 then remained_expire = '_گروه به صورت نامحدود شارژ میباشد!_' elseif tonumber(check_time) > 1 and check_time < 60 then remained_expire = '_گروه به مدت_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 60 and check_time < 3600 then remained_expire = '_گروه به مدت_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then remained_expire = '_گروه به مدت_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 86400 and tonumber(check_time) < 2592000 then remained_expire = '_گروه به مدت_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 2592000 and tonumber(check_time) < 31536000 then remained_expire = '_گروه به مدت_ *'..month..'* _ماه_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 31536000 then remained_expire = '_گروه به مدت_ *'..year..'* _سال_ *'..month..'* _ماه_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' end tdcli.sendMessage(msg.to.id, msg.id_, 1, remained_expire, 1, 'md') end end end if ((matches[1] == 'check' and not Clang) or (matches[1] == "اعتبار" and Clang)) and is_mod(msg) and matches[2] then if string.match(matches[2], '^-%d+$') then local check_time = redis:ttl('ExpireDate:'..matches[2]) year = math.floor(check_time / 31536000) byear = check_time % 31536000 month = math.floor(byear / 2592000) bmonth = byear % 2592000 day = math.floor(bmonth / 86400) bday = bmonth % 86400 hours = math.floor( bday / 3600) bhours = bday % 3600 min = math.floor(bhours / 60) sec = math.floor(bhours % 60) if not lang then if check_time == -1 then remained_expire = '_Unlimited Charging!_' elseif tonumber(check_time) > 1 and check_time < 60 then remained_expire = '_Expire until_ *'..sec..'* _sec_' elseif tonumber(check_time) > 60 and check_time < 3600 then remained_expire = '_Expire until_ '..min..' _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then remained_expire = '_Expire until_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 86400 and tonumber(check_time) < 2592000 then remained_expire = '_Expire until_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 2592000 and tonumber(check_time) < 31536000 then remained_expire = '_Expire until_ *'..month..'* _month_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 31536000 then remained_expire = '_Expire until_ *'..year..'* _year_ *'..month..'* _month_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' end tdcli.sendMessage(msg.to.id, msg.id_, 1, remained_expire, 1, 'md') else if check_time == -1 then remained_expire = '_گروه به صورت نامحدود شارژ میباشد!_' elseif tonumber(check_time) > 1 and check_time < 60 then remained_expire = '_گروه به مدت_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 60 and check_time < 3600 then remained_expire = '_گروه به مدت_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then remained_expire = '_گروه به مدت_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 86400 and tonumber(check_time) < 2592000 then remained_expire = '_گروه به مدت_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 2592000 and tonumber(check_time) < 31536000 then remained_expire = '_گروه به مدت_ *'..month..'* _ماه_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' elseif tonumber(check_time) > 31536000 then remained_expire = '_گروه به مدت_ *'..year..'* _سال_ *'..month..'* _ماه_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه شارژ میباشد_' end tdcli.sendMessage(msg.to.id, msg.id_, 1, remained_expire, 1, 'md') end end end if ((matches[1] == "adminprom" and not Clang) or (matches[1] == "ادمین" and Clang)) and is_sudo(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="adminprom"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="adminprom"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="adminprom"}) end end if ((matches[1] == "admindem" and not Clang) or (matches[1] == "حذف ادمین" and Clang)) and is_sudo(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.to.id,cmd="admindem"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="admindem"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="admindem"}) end end if ((matches[1] == 'creategroup' and not Clang) or (matches[1] == "ساخت گروه" and Clang)) and is_admin(msg) then local text = matches[2] tdcli.createNewGroupChat({[0] = msg.from.id}, text, dl_cb, nil) if not lang then return '_Group Has Been Created!_' else return '_گروه ساخته شد!_' end end if ((matches[1] == 'createsuper' and not Clang) or (matches[1] == "ساخت سوپرگروه" and Clang)) and is_admin(msg) then local text = matches[2] tdcli.createNewChannelChat(text, 1, '@sasan8u', (function(b, d) tdcli.addChatMember(d.id_, msg.from.id, 0, dl_cb, nil) end), nil) if not lang then return '_SuperGroup Has Been Created and_ [`'..msg.from.id..'`] _Joined To This SuperGroup._' else return '_سوپرگروه ساخته شد و_ [`'..msg.from.id..'`] _به گروه اضافه شد._' end end if ((matches[1] == 'tosuper' and not Clang) or (matches[1] == "تبدیل به سوپرگروه" and Clang)) and is_admin(msg) then local id = msg.to.id tdcli.migrateGroupChatToChannelChat(id, dl_cb, nil) if not lang then return '_Group Has Been Changed To SuperGroup!_' else return '_گروه به سوپر گروه تبدیل شد!_' end end if ((matches[1] == 'import' and not Clang) or (matches[1] == "ورود لینک" and Clang)) and is_admin(msg) then if matches[2]:match("^([https?://w]*.?telegram.me/joinchat/.*)$") or matches[2]:match("^([https?://w]*.?t.me/joinchat/.*)$") then local link = matches[2] if link:match('t.me') then link = string.gsub(link, 't.me', 'telegram.me') end tdcli.importChatInviteLink(link, dl_cb, nil) if not lang then return '*Done!*' else return '*انجام شد!*' end end end if ((matches[1] == 'setbotname' and not Clang) or (matches[1] == "تغییر نام ربات" and Clang)) and is_sudo(msg) then tdcli.changeName(matches[2]) if not lang then return '_Bot Name Changed To:_ *'..matches[2]..'*' else return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*' end end if ((matches[1] == 'setbotusername' and not Clang) or (matches[1] == "تغییر یوزرنیم ربات" and Clang)) and is_sudo(msg) then tdcli.changeUsername(matches[2]) if not lang then return '_Bot Username Changed To:_ @'..matches[2] else return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..'' end end if ((matches[1] == 'delbotusername' and not Clang) or (matches[1] == "حذف یوزرنیم ربات" and Clang)) and is_sudo(msg) then tdcli.changeUsername('') if not lang then return '*Done!*' else return '*انجام شد!*' end end if ((matches[1] == 'markread' and not Clang) or (matches[1] == "" and Clang)) and is_sudo(msg) then if ((matches[2] == 'on' and not Clang) or (matches[2] == "فعال" and Clang)) then redis:set('markread','on') if not lang then return '_Markread >_ *ON*' else return '_تیک دوم >_ *روشن*' end end if ((matches[2] == 'off' and not Clang) or (matches[2] == "غیرفعال" and Clang)) then redis:set('markread','off') if not lang then return '_Markread >_ *OFF*' else return '_تیک دوم >_ *خاموش*' end end end if ((matches[1] == 'bc' and not Clang) or (matches[1] == "ارسال" and Clang)) and is_admin(msg) then local text = matches[2] tdcli.sendMessage(matches[3], 0, 0, text, 0) end if ((matches[1] == 'broadcast' and not Clang) or (matches[1] == "ارسال به همه" and Clang)) and is_sudo(msg) then local data = load_data(_config.moderation.data) local bc = matches[2] for k,v in pairs(data) do tdcli.sendMessage(k, 0, 0, bc, 0) end end if is_sudo(msg) then if ((matches[1]:lower() == "sendfile" and not Clang) or (matches[1] == "ارسال فایل" and Clang)) and matches[2] and matches[3] then local send_file = "./"..matches[2].."/"..matches[3] tdcli.sendDocument(msg.chat_id_, msg.id_,0, 1, nil, send_file, msg_caption, dl_cb, nil) end if ((matches[1]:lower() == "sendplug" and not Clang) or (matches[1] == "ارسال پلاگین" and Clang)) and matches[2] then local plug = "./plugins/"..matches[2]..".lua" tdcli.sendDocument(msg.chat_id_, msg.id_,0, 1, nil, plug, msg_caption, dl_cb, nil) end end if ((matches[1]:lower() == 'save' and not Clang) or (matches[1] == "ذخیره پلاگین" and Clang)) and matches[2] and is_sudo(msg) then if tonumber(msg.reply_to_message_id_) ~= 0 then function get_filemsg(arg, data) function get_fileinfo(arg,data) if data.content_.ID == 'MessageDocument' then fileid = data.content_.document_.document_.id_ filename = data.content_.document_.file_name_ file_dl(document_id) sleep(1) if (filename:lower():match('.lua$')) then local pathf = tcpath..'/data/document/'..filename if pl_exi(filename) then local pfile = 'plugins/'..matches[2]..'.lua' os.rename(pathf, pfile) tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Plugin</b> <code>'..matches[2]..'</code> <b>Has Been Saved.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file is not Plugin File._', 1, 'md') end else return end end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil) end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil) end end if ((matches[1] == 'sudolist' and not Clang) or (matches[1] == "لیست سودو" and Clang)) and is_sudo(msg) then return sudolist(msg) end if ((matches[1] == 'chats' and not Clang) or (matches[1] == "لیست گروه ها" and Clang)) and is_admin(msg) then return chat_list(msg) end if ((matches[1]:lower() == 'join' and not Clang) or (matches[1] == "افزودن" and Clang)) and is_admin(msg) and matches[2] then tdcli.sendMessage(msg.to.id, msg.id, 1, 'I Invite you in '..matches[2]..'', 1, 'html') tdcli.sendMessage(matches[2], 0, 1, "Admin Joined!🌚", 1, 'html') tdcli.addChatMember(matches[2], msg.from.id, 0, dl_cb, nil) end if ((matches[1] == 'rem' and not Clang) or (matches[1] == "حذف گروه" and Clang)) and matches[2] and is_admin(msg) then local data = load_data(_config.moderation.data) -- Group configuration removal data[tostring(matches[2])] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(matches[2])] = nil save_data(_config.moderation.data, data) tdcli.sendMessage(matches[2], 0, 1, "Group has been removed by admin command", 1, 'html') return '_Group_ *'..matches[2]..'* _removed_' end if ((matches[1] == 'beyond' and not Clang) or (matches[1] == "بیوند" and Clang)) then return tdcli.sendMessage(msg.to.id, msg.id, 1, _config.info_text, 1, 'html') end if ((matches[1] == 'adminlist' and not Clang) or (matches[1] == "لیست ادمین" and Clang)) and is_admin(msg) then return adminlist(msg) end if ((matches[1] == 'leave' and not Clang) or (matches[1] == "خروج" and Clang)) and is_admin(msg) then tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil) end if ((matches[1] == 'autoleave' and not Clang) or (matches[1] == "خروج خودکار" and Clang)) and is_admin(msg) then local hash = 'auto_leave_bot' --Enable Auto Leave if ((matches[2] == 'enable' and not Clang) or (matches[2] == "فعال" and Clang)) then redis:del(hash) return 'Auto leave has been enabled' --Disable Auto Leave elseif ((matches[2] == 'disable' and not Clang) or (matches[2] == "غیرفعال" and Clang)) then redis:set(hash, true) return 'Auto leave has been disabled' --Auto Leave Status elseif ((matches[2] == 'status' and not Clang) or (matches[2] == "موقعیت" and Clang)) then if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end end if matches[1] == "helptools" and not Clang and is_mod(msg) then if not lang then text = [[ _👥 Sudoer And Admins Bot Help :_ *🔰 /visudo* `[username|id|reply]` _🔹 Add Sudo_ *🔰 /desudo* `[username|id|reply]` _🔹 Demote Sudo_ *🔰 /sudolist * _🔹 Sudo(s) list_ *🔰 /adminprom* `[username|id|reply]` _🔹 Add admin for bot_ *🔰 /admindem* `[username|id|reply]` _🔹 Demote bot admin_ *🔰 /adminlist * _🔹 Admin(s) list_ *🔰 /leave * _🔹 Leave current group_ *🔰 /autoleave* `[disable/enable]` _🔹 Automatically leaves group_ *🔰 /creategroup* `[text]` _🔹 Create normal group_ *🔰 /createsuper* `[text]` _🔹 Create supergroup_ *🔰 /tosuper * _🔹 Convert to supergroup_ *🔰 /chats* _🔹 List of added groups_ *🔰 /join* `[id]` _🔹 Adds you to the group_ *🔰 /rem* `[id]` _🔹 Remove a group from Database_ *🔰 /import* `[link]` _🔹 Bot joins via link_ *🔰 /setbotname* `[text]` _🔹 Change bot's name_ *🔰 /setbotusername* `[text]` _🔹 Change bot's username_ *🔰 /delbotusername * _🔹 Delete bot's username_ *🔰 /markread* `[off/on]` _🔹 Second mark_ *🔰 /broadcast* `[text]` _🔹 Send message to all added groups_ *🔰 /bc* `[text] [GroupID]` _🔹 Send message to a specific group_ *🔰 /sendfile* `[folder] [file]` _🔹 Send file from folder_ *🔰 /sendplug* `[plug]` _🔹 Send plugin_ *🔰 /save* `[plugin name] [reply]` _🔹 Save plugin by reply_ *🔰 /savefile* `[address/filename] [reply]` _🔹 Save File by reply to specific folder_ *🔰 /config* _🔹 Set Owner and Admin Group_ *🔰 /clear cache* _🔹 Clear All Cache Of .telegram-cli/data_ *🔰 /check* _🔹 Stated Expiration Date_ *🔰 /check* `[GroupID]` _🔹 Stated Expiration Date Of Specific Group_ *🔰 /charge* `[GroupID]` `[Number Of Days]` _🔹 Set Expire Time For Specific Group_ *🔰 /charge* `[Number Of Days]` _🔹 Set Expire Time For Group_ *🔰 /jointo* `[GroupID]` _🔹 Invite You To Specific Group_ *🔰 /leave* `[GroupID]` _🔹 Leave Bot From Specific Group_ _✅ You can use_ *[!/#]* _at the beginning of commands._ `⚠ ️This help is only for sudoers/bot admins.` *⚠️ This means only the sudoers and its bot admins can use mentioned commands.* *Good luck ;)*]]..msg_caption tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md') else text = [[ _👥 راهنمای ادمین و سودو های ربات:_ *🔰 /visudo* `[username|id|reply]` _🔹 اضافه کردن سودو_ *🔰 /desudo* `[username|id|reply]` _🔹 حذف کردن سودو_ *🔰 /sudolist * _🔹 لیست سودو‌های ربات_ *🔰 /adminprom* `[username|id|reply]` _🔹 اضافه کردن ادمین به ربات_ *🔰 /admindem* `[username|id|reply]` _🔹 حذف فرد از ادمینی ربات_ *🔰 /adminlist * _🔹 لیست ادمین ها_ *🔰 /leave * _🔹 خارج شدن ربات از گروه_ *🔰 /autoleave* `[disable/enable/status]` _🔹 خروج خودکار_ *🔰 /creategroup* `[text]` _🔹 ساخت گروه ریلم_ *🔰 /createsuper* `[text]` _🔹 ساخت سوپر گروه_ *🔰 /tosuper * _🔹 تبدیل به سوپر گروه_ *🔰 /chats* _🔹 لیست گروه های مدیریتی ربات_ *🔰 /join* `[ID]` _🔹 جوین شدن توسط ربات_ *🔰 /rem* `[GroupID]` _🔹 حذف گروه ازطریق پنل مدیریتی_ *🔰 /import* `[link]` _🔹 جوین شدن ربات توسط لینک_ *🔰 /setbotname* `[text]` _🔹 تغییر اسم ربات_ *🔰 /setbotusername* `[text]` _🔹 تغییر یوزرنیم ربات_ *🔰 /delbotusername* _🔹 پاک کردن یوزرنیم ربات_ *🔰 /markread* `[on/off]` _🔹 تیک دوم_ *🔰 /broadcast* `[text]` _🔹 فرستادن پیام به تمام گروه های مدیریتی ربات_ *🔰 /bc* `[text]` `[GroupID]` _🔹 ارسال پیام مورد نظر به گروه خاص_ *🔰 /sendfile* `[cd]` `[file]` _🔹 ارسال فایل موردنظر از پوشه خاص_ *🔰 /sendplug* `[plugname]` _🔹 ارسال پلاگ مورد نظر_ *🔰 /save* `[plugname] [reply]` _🔹 ذخیره کردن پلاگین_ *🔰 /savefile* `[address/filename] [reply]` _🔹 ذخیره کردن فایل در پوشه مورد نظر_ *🔰 /config* _🔹 اضافه کردن سازنده و مدیران گروه به مدیریت ربات_ *🔰 /clear cache* _🔹 پاک کردن کش مسیر .telegram-cli/data_ *🔰 /check* _🔹 اعلام تاریخ انقضای گروه_ *🔰 /check* `[GroupID]` _🔹 اعلام تاریخ انقضای گروه مورد نظر_ *🔰 /charge* `[GroupID]` `[days]` _🔹 تنظیم تاریخ انقضای گروه مورد نظر_ *🔰 /charge* `[days]` _🔹 تنظیم تاریخ انقضای گروه_ *🔰 /jointo* `[GroupID]` _🔹 دعوت شدن شما توسط ربات به گروه مورد نظر_ *🔰 /leave* `[GroupID]` _🔹 خارج شدن ربات از گروه مورد نظر_ *✅ شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید* _⚠️ این راهنما فقط برای سودو ها/ادمین های ربات میباشد!_ `⚠️ این به این معناست که فقط سودو ها/ادمین های ربات میتوانند از دستورات بالا استفاده کنند!` *موفق باشید ;)*]]..msg_caption tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md') end end if matches[1] == "راهنمای ابزار" and Clang and is_mod(msg) then if not lang then text = [[ _👥 Sudoer And Admins Bot Help :_ *🔰 سودو* `[username|id|reply]` _🔹 Add Sudo_ *🔰 حذف سودو* `[username|id|reply]` _🔹 Demote Sudo_ *🔰 لیست سودو * _🔹 Sudo(s) list_ *🔰 ادمین* `[username|id|reply]` _🔹 Add admin for bot_ *🔰 حذف ادمین* `[username|id|reply]` _🔹 Demote bot admin_ *🔰 لیست ادمین * _🔹 Admin(s) list_ *🔰 خروج * _🔹 Leave current group_ *🔰 خروج خودکار* `[فعال/غیرفعال]` _🔹 Automatically leaves group_ *🔰 ساخت گروه* `[متن]` _🔹 Create normal group_ *🔰 ساخت سوپرگروه* `[متن]` _🔹 Create supergroup_ *🔰 تبدیل به سوپرگروه * _🔹 Convert to supergroup_ *🔰 لیست گروه ها* _🔹 List of added groups_ *🔰 افزودن* `[id]` _🔹 Adds you to the group_ *🔰 حذف گروه* `[id]` _🔹 Remove a group from Database_ *🔰 ورود لینک* `[لینک]` _🔹 Bot joins via link_ *🔰 تغییر نام ربات* `[متن]` _🔹 Change bot's name_ *🔰 تغییر یوزرنیم ربات* `[متن]` _🔹 Change bot's username_ *🔰 حذف یوزرنیم ربات * _🔹 Delete bot's username_ *🔰 تیک دوم* `[فعال/غیرفعال]` _🔹 Second mark_ *🔰 ارسال به همه* `[متن]` _🔹 Send message to all added groups_ *🔰 ارسال* `[متن] [GroupID]` _🔹 Send message to a specific group_ *🔰 ارسال فایل* `[مسیر] [اسم فایل]` _🔹 Send file from folder_ *🔰 ارسال پلاگین* `[اسم پلاگین]` _🔹 Send plugin_ *🔰 ذخیره پلاگین* `[اسم پلاگین] [reply]` _🔹 Save plugin by reply_ *🔰 ذخیره فایل* `[مسیر/اسم فایل] [reply]` _🔹 Save File by reply to specific folder_ *🔰 پیکربندی* _🔹 Set Owner and Admin Group as Moderator_ *🔰 پاک کردن حافظه* _🔹 Clear All Cache Of .telegram-cli/data_ *🔰 اعتبار* _🔹 Stated Expiration Date_ *🔰 اعتبار* `[GroupID]` _🔹 Stated Expiration Date Of Specific Group_ *🔰 شارژ* `[GroupID]` `[تعداد روز]` _🔹 Set Expire Time For Specific Group_ *🔰 شارژ* `[تعداد روز]` _🔹 Set Expire Time For Group_ *🔰 ورود به* `[GroupID]` _🔹 Invite You To Specific Group_ *🔰 خروج* `[GroupID]` _🔹 Leave Bot From Specific Group_ `⚠️ This help is only for sudoers/bot admins.` *⚠️ This means only the sudoers and its bot admins can use mentioned commands.* *Good luck ;)*]] tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md') else text = [[ _👥 راهنمای ادمین و سودو های ربات:_ *🔰 سودو* `[username|id|reply]` _🔹 اضافه کردن سودو_ *🔰 حذف سودو* `[username|id|reply]` _🔹 حذف کردن سودو_ *🔰 لیست سودو* _🔹 لیست سودو‌های ربات_ *🔰 ادمین* `[username|id|reply]` _🔹 اضافه کردن ادمین به ربات_ *🔰 حذف ادمین* `[username|id|reply]` _🔹 حذف فرد از ادمینی ربات_ *🔰 لیست ادمین* _🔹 لیست ادمین ها_ *🔰 خروج* _🔹 خارج شدن ربات از گروه_ *🔰 خروج خودکار* `[غیرفعال/فعال | موقعیت]` _🔹 خروج خودکار_ *🔰 ساخت گروه* `[اسم انتخابی]` _🔹 ساخت گروه ریلم_ *🔰 ساخت سوپرگروه* `[اسم انتخابی]` _🔹 ساخت سوپر گروه_ *🔰 تبدیل به سوپرگروه* _🔹 تبدیل به سوپر گروه_ *🔰 لیست گروه ها* _🔹 لیست گروه های مدیریتی ربات_ *🔰 افزودن* `[ایدی گروه]` _🔹 جوین شدن توسط ربات_ *🔰 حذف گروه* `[ایدی گروه]` _🔹 حذف گروه ازطریق پنل مدیریتی_ *🔰 ورود لینک* `[لینک_]` _🔹 جوین شدن ربات توسط لینک_ *🔰 تغییر نام ربات* `[text]` _🔹 تغییر اسم ربات_ *🔰 تغییر یوزرنیم ربات* `[text]` _🔹 تغییر یوزرنیم ربات_ *🔰 حذف یوزرنیم ربات* _🔹 پاک کردن یوزرنیم ربات_ *🔰 تیک دوم* `[فعال/غیرفعال]` _🔹 تیک دوم_ *🔰 ارسال به همه* `[متن]` _🔹 فرستادن پیام به تمام گروه های مدیریتی ربات_ *🔰 ارسال* `[متن]` `[ایدی گروه]` _🔹 ارسال پیام مورد نظر به گروه خاص_ *🔰 ارسال فایل* `[cd]` `[file]` _🔹 ارسال فایل موردنظر از پوشه خاص_ *🔰 ارسال پلاگین* `[اسم پلاگین]` _🔹 ارسال پلاگ مورد نظر_ *🔰 ذخیره پلاگین* `[اسم پلاگین] [reply]` _🔹 ذخیره کردن پلاگین_ *🔰 ذخیره فایل* `[address/filename] [reply]` _🔹 ذخیره کردن فایل در پوشه مورد نظر_ *🔰 پیکربندی* _🔹 اضافه کردن سازنده و مدیران گروه به مدیریت ربات_ *🔰 پاک کردن حافظه* _🔹 پاک کردن کش مسیر .telegram-cli/data_ *🔰 اعتبار* _🔹 اعلام تاریخ انقضای گروه_ *🔰 اعتبار* `[ایدی گروه]` _🔹 اعلام تاریخ انقضای گروه مورد نظر_ *🔰 شارژ* `[ایدی گروه]` `[تعداد روز]` _🔹 تنظیم تاریخ انقضای گروه مورد نظر_ *🔰 شارژ* `[تعداد روز]` _🔹 تنظیم تاریخ انقضای گروه_ *🔰 ورود به* `[ایدی گروه]` _🔹 دعوت شدن شما توسط ربات به گروه مورد نظر_ *🔰 خروج* `[ایدی گروه]` _🔹 خارج شدن ربات از گروه مورد نظر_ *✅ شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید* _⚠️ این راهنما فقط برای سودو ها/ادمین های ربات میباشد!_ `⚠️ این به این معناست که فقط سودو ها/ادمین های ربات میتوانند از دستورات بالا استفاده کنند!` *موفق باشید ;)*]] tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md') end end end return { patterns = { "^[!/#](helptools)$", "^[!/#](config)$", "^[!/#](visudo)$", "^[!/#](desudo)$", "^[!/#](sudolist)$", "^[!/#](visudo) (.*)$", "^[!/#](desudo) (.*)$", "^[!/#](adminprom)$", "^[!/#](admindem)$", "^[!/#](adminlist)$", "^[!/#](adminprom) (.*)$", "^[!/#](admindem) (.*)$", "^[!/#](leave)$", "^[!/#](autoleave) (.*)$", "^[!/#](beyond)$", "^[!/#](creategroup) (.*)$", "^[!/#](createsuper) (.*)$", "^[!/#](tosuper)$", "^[!/#](chats)$", "^[!/#](clear cache)$", "^[!/#](join) (-%d+)$", "^[!/#](rem) (-%d+)$", "^[!/#](import) (.*)$", "^[!/#](setbotname) (.*)$", "^[!/#](setbotusername) (.*)$", "^[!/#](delbotusername) (.*)$", "^[!/#](markread) (.*)$", "^[!/#](bc) +(.*) (-%d+)$", "^[!/#](broadcast) (.*)$", "^[!/#](sendfile) (.*) (.*)$", "^[!/#](save) (.*)$", "^[!/#](sendplug) (.*)$", "^[!/#](savefile) (.*)$", "^[!/#]([Aa]dd)$", "^[!/#]([Gg]id)$", "^[!/#]([Cc]heck)$", "^[!/#]([Cc]heck) (-%d+)$", "^[!/#]([Cc]harge) (-%d+) (%d+)$", "^[!/#]([Cc]harge) (%d+)$", "^[!/#]([Jj]ointo) (-%d+)$", "^[!/#]([Ll]eave) (-%d+)$", "^[!/#]([Pp]lan) ([123]) (-%d+)$", "^[!/#]([Rr]em)$", "^(پیکربندی)$", "^(افزودن)$", "^(حذف گروه)$", "^(حذف گروه) (-%d+)$", "^(راهنمای ابزار)$", "^(لیست سودو)$", "^(اطلاعات)$", "^(ساخت گروه) (.*)$", "^(ورود به) (-%d+)$", "^(ساخت گروه) (.*)$", "^(ساخت سوپرگروه) (.*)$", "^(ذخیره فایل) (.*)$", "^(سودو)$", "^(سودو) (.*)$", "^(حذف سودو)$", "^(حذف سودو) (.*)$", "^(ادمین)$", "^(حذف ادمین)$", "^(حذف ادمین) (.*)$", "^(ارسال فایل) (.*)$", "^(حذف یوزرنیم ربات) (.*)$", "^(تغییر یوزرنیم ربات) (.*)$", "^(تغییر نام ربات) (.*)$", "^(تبدیل به سوپرگروه)$", "^(ارسال به همه) (.*)$", "^(لیست گروه ها)$", "^(خروج)$", "^(خروج) (-%d+)$", "^(ارسال پلاگین) (.*)$", "^(لیست ادمین)$", "^(خروج خودکار) (.*)$", "^(شارژ) (-%d+) (%d+)$", "^(شارژ) (%d+)$", "^(پلن) ([123]) (-%d+)$", "^(اعتبار)$", "^(اعتبار) (-%d+)$", "^(ذخیره پلاگین) (.*)$", "^(تیک دوم) (.*)$", "^(ارسال) +(.*) (-%d+)$", "^(افزودن) (-%d+)$", "^(پاک کردن حافظه)$", "^(بیوند)$", }, run = run, pre_process = pre_process } -- #End By @BeyondTeam
gpl-3.0
casperkaae/nn
Criterion.lua
17
1247
local Criterion = torch.class('nn.Criterion') function Criterion:__init() self.gradInput = torch.Tensor() self.output = 0 end function Criterion:updateOutput(input, target) end function Criterion:forward(input, target) return self:updateOutput(input, target) end function Criterion:backward(input, target) return self:updateGradInput(input, target) end function Criterion:updateGradInput(input, target) end function Criterion:clone() local f = torch.MemoryFile("rw"):binary() f:writeObject(self) f:seek(1) local clone = f:readObject() f:close() return clone end function Criterion:type(type) assert(type, 'Criterion: must provide a type to convert to') -- find all tensors and convert them for key,param in pairs(self) do self[key] = nn.utils.recursiveType(param, type) end return self end function Criterion:float() return self:type('torch.FloatTensor') end function Criterion:double() return self:type('torch.DoubleTensor') end function Criterion:cuda() return self:type('torch.CudaTensor') end function Criterion:__call__(input, target) self.output = self:forward(input, target) self.gradInput = self:backward(input, target) return self.output, self.gradInput end
bsd-3-clause
bnetcc/darkstar
scripts/zones/QuBia_Arena/bcnms/those_who_lurk_in_shadows.lua
5
2390
----------------------------------- -- Area: Qu'Bia Arena -- NPC: Those Who Lurk in Shadows -- !pos -221 -24 19 206 ----------------------------------- package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (player:hasKeyItem(MARK_OF_SEED)) then player:delKeyItem(MARK_OF_SEED); end if (leavecode == 2) then -- Play end CS. Need time and battle id for record keeping + storage player:addExp(700); if (player:getCurrentMission(ACP) == THOSE_WHO_LURK_IN_SHADOWS_III) then player:startEvent(32001,1,1,1,instance:getTimeInside(),1,20,0); else -- Gives skip dialog if previously completed player:startEvent(32001,1,1,1,instance:getTimeInside(),1,20,1); end elseif (leavecode == 4) then player:startEvent(32002); 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 == 32001) then if (player:getCurrentMission(ACP) == THOSE_WHO_LURK_IN_SHADOWS_III) then player:completeMission(ACP,THOSE_WHO_LURK_IN_SHADOWS_III); player:addMission(ACP,REMEMBER_ME_IN_YOUR_DREAMS); end if (player:hasKeyItem(IVORY_KEY) == false and player:getCurrentMission(ACP) >= THOSE_WHO_LURK_IN_SHADOWS_III) then player:addKeyItem(IVORY_KEY); player:setVar("LastIvoryKey", os.date("%j")); player:messageSpecial(KEYITEM_OBTAINED,IVORY_KEY); end end end;
gpl-3.0
awesomeWM/awesome
lib/wibox/widget/progressbar.lua
1
20398
--------------------------------------------------------------------------- --- A progressbar widget. -- -- ![Components](../images/progressbar.svg) -- -- Common usage examples -- ===================== -- -- To add text on top of the progressbar, a `wibox.layout.stack` can be used: -- --@DOC_wibox_widget_progressbar_text_EXAMPLE@ -- -- To display the progressbar vertically, use a `wibox.container.rotate` widget: -- --@DOC_wibox_widget_progressbar_vertical_EXAMPLE@ -- -- By default, this widget will take all the available size. To prevent this, -- a `wibox.container.constraint` widget or the `forced_width`/`forced_height` -- properties have to be used. -- -- To have a gradient between 2 colors when the bar reaches a threshold, use -- the `gears.color` gradients: -- --@DOC_wibox_widget_progressbar_grad1_EXAMPLE@ -- -- The same goes for multiple solid colors: -- --@DOC_wibox_widget_progressbar_grad2_EXAMPLE@ -- --@DOC_wibox_widget_defaults_progressbar_EXAMPLE@ -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @copyright 2009 Julien Danjou -- @widgetmod wibox.widget.progressbar -- @supermodule wibox.widget.base --------------------------------------------------------------------------- local setmetatable = setmetatable local ipairs = ipairs local math = math local gdebug = require("gears.debug") local base = require("wibox.widget.base") local color = require("gears.color") local beautiful = require("beautiful") local shape = require("gears.shape") local gtable = require("gears.table") local progressbar = { mt = {} } --- The progressbar border color. -- -- If the value is nil, no border will be drawn. -- -- @DOC_wibox_widget_progressbar_border_color_EXAMPLE@ -- -- @property border_color -- @tparam color|nil border_color The border color to set. -- @propemits true false -- @propbeautiful -- @see gears.color --- The progressbar border width. -- -- @DOC_wibox_widget_progressbar_border_width_EXAMPLE@ -- -- @property border_width -- @tparam number|nil border_width -- @propertytype nil Defaults to `beautiful.progressbar_border_width`. -- @propertytype number The number of pixels -- @propertyunit pixel -- @negativeallowed false -- @propbeautiful -- @propemits true false -- @propbeautiful --- The progressbar inner border color. -- -- If the value is nil, no border will be drawn. -- -- @DOC_wibox_widget_progressbar_bar_border_color_EXAMPLE@ -- -- @property bar_border_color -- @tparam color|nil bar_border_color The border color to set. -- @propemits true false -- @propbeautiful -- @see gears.color --- The progressbar inner border width. -- -- @DOC_wibox_widget_progressbar_bar_border_width_EXAMPLE@ -- -- @property bar_border_width -- @tparam number|nil bar_border_width -- @propertyunit pixel -- @negativeallowed false -- @propbeautiful -- @usebeautiful beautiful.progressbar_border_width Fallback when -- `beautiful.progressbar_bar_border_width` isn't set. -- @propemits true false --- The progressbar foreground color. -- -- @DOC_wibox_widget_progressbar_color_EXAMPLE@ -- -- @property color -- @tparam color|nil color The progressbar color. -- @propertytype nil Fallback to the current value of `beautiful.progressbar_fg`. -- @propemits true false -- @usebeautiful beautiful.progressbar_fg -- @see gears.color --- The progressbar background color. -- -- @DOC_wibox_widget_progressbar_background_color_EXAMPLE@ -- -- @property background_color -- @tparam color|nil background_color The progressbar background color. -- @propertytype nil Fallback to the current value of `beautiful.progressbar_bg`. -- @propemits true false -- @usebeautiful beautiful.progressbar_bg -- @see gears.color --- The progressbar inner shape. -- --@DOC_wibox_widget_progressbar_bar_shape_EXAMPLE@ -- -- @property bar_shape -- @tparam shape|nil bar_shape -- @propemits true false -- @propbeautiful -- @see gears.shape --- The progressbar shape. -- --@DOC_wibox_widget_progressbar_shape_EXAMPLE@ -- -- @property shape -- @tparam shape|nil shape -- @propemits true false -- @propbeautiful -- @see gears.shape --- Set the progressbar to draw vertically. -- -- This doesn't do anything anymore, use a `wibox.container.rotate` widget. -- -- @deprecated set_vertical -- @tparam boolean vertical -- @deprecatedin 4.0 --- Force the inner part (the bar) to fit in the background shape. -- --@DOC_wibox_widget_progressbar_clip_EXAMPLE@ -- -- @property clip -- @tparam[opt=true] boolean clip -- @propemits true false --- The progressbar to draw ticks. -- -- The add a little bar in between the values. -- -- @DOC_wibox_widget_progressbar_ticks_EXAMPLE@ -- -- @property ticks -- @tparam[opt=false] boolean ticks -- @propemits true false -- @see ticks_gap -- @see ticks_size --- The progressbar ticks gap. -- -- @DOC_wibox_widget_progressbar_ticks_gap_EXAMPLE@ -- -- @property ticks_gap -- @tparam[opt=1] number ticks_gap -- @propertyunit pixel -- @negativeallowed false -- @propemits true false -- @see ticks_size -- @see ticks --- The progressbar ticks size. -- -- @DOC_wibox_widget_progressbar_ticks_size_EXAMPLE@ -- -- It is also possible to mix this feature with the `bar_shape` property: -- -- @DOC_wibox_widget_progressbar_ticks_size2_EXAMPLE@ -- -- @property ticks_size -- @tparam[opt=4] number ticks_size -- @propertyunit pixel -- @negativeallowed false -- @propemits true false -- @see ticks_gap -- @see ticks --- The maximum value the progressbar should handle. -- -- By default, the value is 1. So the content of `value` is -- a percentage. -- -- @DOC_wibox_widget_progressbar_max_value_EXAMPLE@ -- -- @property max_value -- @tparam[opt=1] number max_value -- @negativeallowed true -- @propemits true false -- @see value --- The progressbar background color. -- -- @beautiful beautiful.progressbar_bg -- @param color --- The progressbar foreground color. -- -- @beautiful beautiful.progressbar_fg -- @param color --- The progressbar shape. -- -- @beautiful beautiful.progressbar_shape -- @tparam[opt=gears.shape.rectangle] shape shape -- @see gears.shape --- The progressbar border color. -- -- @beautiful beautiful.progressbar_border_color -- @param color --- The progressbar outer border width. -- -- @beautiful beautiful.progressbar_border_width -- @param number --- The progressbar inner shape. -- -- @beautiful beautiful.progressbar_bar_shape -- @tparam[opt=gears.shape.rectangle] gears.shape shape -- @see gears.shape --- The progressbar bar border width. -- -- @beautiful beautiful.progressbar_bar_border_width -- @param number --- The progressbar bar border color. -- -- @beautiful beautiful.progressbar_bar_border_color -- @param color --- The progressbar margins. -- -- The margins are around the progressbar. If you want to add space between the -- bar and the border, use `paddings`. -- -- @DOC_wibox_widget_progressbar_margins2_EXAMPLE@ -- -- Note that if the `clip` is disabled, this allows the background to be smaller -- than the bar. -- -- It is also possible to specify a single number instead of a border for each -- direction; -- -- @DOC_wibox_widget_progressbar_margins1_EXAMPLE@ -- -- @property margins -- @tparam[opt=0] table|number|nil margins A table for each side or a number -- @tparam[opt=0] number margins.top -- @tparam[opt=0] number margins.bottom -- @tparam[opt=0] number margins.left -- @tparam[opt=0] number margins.right -- @propertyunit pixel -- @negativeallowed true -- @propertytype number Use the same value for each side. -- @propertytype table Use a different value for each side: -- @propemits false false -- @propbeautiful -- @see clip -- @see paddings -- @see wibox.container.margin --- The progressbar padding. -- -- This is the space between the inner bar and the progressbar outer border. -- -- Note that if the `clip` is disabled, this allows the bar to be taller -- than the background. -- -- @DOC_wibox_widget_progressbar_paddings2_EXAMPLE@ -- -- The paddings can also be a single numeric value: -- -- @DOC_wibox_widget_progressbar_paddings1_EXAMPLE@ -- -- @property paddings -- @tparam[opt=0] table|number|nil paddings A table for each side or a number -- @tparam[opt=0] number paddings.top -- @tparam[opt=0] number paddings.bottom -- @tparam[opt=0] number paddings.left -- @tparam[opt=0] number paddings.right -- @propertyunit pixel -- @negativeallowed true -- @propertytype number Use the same value for each side. -- @propertytype table Use a different value for each side: -- @propemits false false -- @propbeautiful -- @see clip -- @see margins --- The progressbar margins. -- -- Note that if the `clip` is disabled, this allows the background to be smaller -- than the bar. -- @beautiful beautiful.progressbar_margins -- @tparam[opt=0] (table|number|nil) margins A table for each side or a number -- @tparam[opt=0] number margins.top -- @tparam[opt=0] number margins.bottom -- @tparam[opt=0] number margins.left -- @tparam[opt=0] number margins.right -- @see clip -- @see beautiful.progressbar_paddings -- @see wibox.container.margin --- The progressbar padding. -- -- Note that if the `clip` is disabled, this allows the bar to be taller -- than the background. -- @beautiful beautiful.progressbar_paddings -- @tparam[opt=0] (table|number|nil) padding A table for each side or a number -- @tparam[opt=0] number paddings.top -- @tparam[opt=0] number paddings.bottom -- @tparam[opt=0] number paddings.left -- @tparam[opt=0] number paddings.right -- @see clip -- @see beautiful.progressbar_margins local properties = { "border_color", "color" , "background_color", "value" , "max_value" , "ticks", "ticks_gap" , "ticks_size", "border_width", "shape" , "bar_shape" , "bar_border_width", "clip" , "margins" , "bar_border_color", "paddings", } function progressbar.draw(pbar, _, cr, width, height) local ticks_gap = pbar._private.ticks_gap or 1 local ticks_size = pbar._private.ticks_size or 4 -- We want one pixel wide lines cr:set_line_width(1) local max_value = pbar._private.max_value local value = math.min(max_value, math.max(0, pbar._private.value)) if value >= 0 then value = value / max_value end local border_width = pbar._private.border_width or beautiful.progressbar_border_width or 0 local bcol = pbar._private.border_color or beautiful.progressbar_border_color border_width = bcol and border_width or 0 local bg = pbar._private.background_color or beautiful.progressbar_bg or "#ff0000aa" local bg_width, bg_height = width, height local clip = pbar._private.clip ~= false and beautiful.progressbar_clip ~= false -- Apply the margins local margin = pbar._private.margins or beautiful.progressbar_margins if margin then if type(margin) == "number" then cr:translate(margin, margin) bg_width, bg_height = bg_width - 2*margin, bg_height - 2*margin else cr:translate(margin.left or 0, margin.top or 0) bg_height = bg_height - (margin.top or 0) - (margin.bottom or 0) bg_width = bg_width - (margin.left or 0) - (margin.right or 0) end end -- Draw the background shape if border_width > 0 then -- Cairo draw half of the border outside of the path area cr:translate(border_width/2, border_width/2) bg_width, bg_height = bg_width - border_width, bg_height - border_width cr:set_line_width(border_width) end local background_shape = pbar._private.shape or beautiful.progressbar_shape or shape.rectangle background_shape(cr, bg_width, bg_height) cr:set_source(color(bg)) local over_drawn_width = bg_width + border_width local over_drawn_height = bg_height + border_width if border_width > 0 then cr:fill_preserve() -- Draw the border cr:set_source(color(bcol)) cr:stroke() over_drawn_width = over_drawn_width - 2*border_width over_drawn_height = over_drawn_height - 2*border_width else cr:fill() end -- Undo the translation cr:translate(-border_width/2, -border_width/2) -- Make sure the bar stay in the shape if clip then background_shape(cr, bg_width, bg_height) cr:clip() cr:translate(border_width, border_width) else -- Assume the background size is irrelevant to the bar itself if type(margin) == "number" then cr:translate(-margin, -margin) else cr:translate(-(margin.left or 0), -(margin.top or 0)) end over_drawn_height = height over_drawn_width = width end -- Apply the padding local padding = pbar._private.paddings or beautiful.progressbar_paddings if padding then if type(padding) == "number" then cr:translate(padding, padding) over_drawn_height = over_drawn_height - 2*padding over_drawn_width = over_drawn_width - 2*padding else cr:translate(padding.left or 0, padding.top or 0) over_drawn_height = over_drawn_height - (padding.top or 0) - (padding.bottom or 0) over_drawn_width = over_drawn_width - (padding.left or 0) - (padding.right or 0) end end over_drawn_width = math.max(over_drawn_width , 0) over_drawn_height = math.max(over_drawn_height, 0) local rel_x = over_drawn_width * value -- Draw the progressbar shape local explicit_bar_shape = pbar._private.bar_shape or beautiful.progressbar_bar_shape local bar_shape = explicit_bar_shape or shape.rectangle local bar_border_width = pbar._private.bar_border_width or beautiful.progressbar_bar_border_width or pbar._private.border_width or beautiful.progressbar_border_width or 0 local bar_border_color = pbar._private.bar_border_color or beautiful.progressbar_bar_border_color bar_border_width = bar_border_color and bar_border_width or 0 over_drawn_width = over_drawn_width - bar_border_width over_drawn_height = over_drawn_height - bar_border_width cr:translate(bar_border_width/2, bar_border_width/2) if pbar._private.ticks and explicit_bar_shape then local tr_off = 0 -- Make all the shape and fill later in case the `color` is a gradient. for _=0, width / (ticks_size+ticks_gap)-border_width do bar_shape(cr, ticks_size - (bar_border_width/2), over_drawn_height) cr:translate(ticks_size+ticks_gap, 0) tr_off = tr_off + ticks_size+ticks_gap end -- Re-align the (potential) color gradients to 0,0. cr:translate(-tr_off, 0) if bar_border_width > 0 then cr:set_source(color(bar_border_color)) cr:set_line_width(bar_border_width) cr:stroke_preserve() end cr:set_source(color(pbar._private.color or beautiful.progressbar_fg or "#ff0000")) cr:fill() else bar_shape(cr, rel_x, over_drawn_height) cr:set_source(color(pbar._private.color or beautiful.progressbar_fg or "#ff0000")) if bar_border_width > 0 then cr:fill_preserve() cr:set_source(color(bar_border_color)) cr:set_line_width(bar_border_width) cr:stroke() else cr:fill() end end -- Legacy "ticks" bars. It looks horrible, but to avoid breaking the -- behavior, so be it. if pbar._private.ticks and not explicit_bar_shape then for i=0, width / (ticks_size+ticks_gap)-border_width do local rel_offset = over_drawn_width / 1 - (ticks_size+ticks_gap) * i if rel_offset <= rel_x then cr:rectangle(rel_offset, border_width, ticks_gap, over_drawn_height) end end cr:set_source(color(pbar._private.background_color or "#000000aa")) cr:fill() end end function progressbar:fit(_, width, height) return width, height end --- Set the progressbar value. -- -- By default, unless `max_value` is set, it is number between -- zero and one. -- -- @DOC_wibox_widget_progressbar_value_EXAMPLE@ -- -- @property value -- @tparam[opt=0] number value -- @negativeallowed true -- @propemits true false -- @see max_value function progressbar:set_value(value) value = value or 0 self._private.value = value self:emit_signal("widget::redraw_needed") return self end function progressbar:set_max_value(max_value) self._private.max_value = max_value self:emit_signal("widget::redraw_needed") end --- Set the progressbar height. -- -- This method is deprecated. Use a `wibox.container.constraint` widget or -- `forced_height`. -- -- @tparam number height The height to set. -- @deprecated set_height -- @renamedin 4.0 function progressbar:set_height(height) gdebug.deprecate("Use a `wibox.container.constraint` widget or `forced_height`", {deprecated_in=4}) self:set_forced_height(height) end --- Set the progressbar width. -- -- This method is deprecated. Use a `wibox.container.constraint` widget or -- `forced_width`. -- -- @tparam number width The width to set. -- @deprecated set_width -- @renamedin 4.0 function progressbar:set_width(width) gdebug.deprecate("Use a `wibox.container.constraint` widget or `forced_width`", {deprecated_in=4}) self:set_forced_width(width) end -- Build properties function for _, prop in ipairs(properties) do if not progressbar["set_" .. prop] then progressbar["set_" .. prop] = function(pbar, value) pbar._private[prop] = value pbar:emit_signal("widget::redraw_needed") pbar:emit_signal("property::"..prop, value) return pbar end end if not progressbar["get_"..prop] then progressbar["get_" .. prop] = function(pbar) return pbar._private[prop] end end end function progressbar:set_vertical(value) --luacheck: no unused_args gdebug.deprecate("Use a `wibox.container.rotate` widget", {deprecated_in=4}) end --- Create a progressbar widget. -- -- @tparam table args Standard widget() arguments. You should add width and -- height constructor parameters to set progressbar geometry. -- @tparam[opt] number args.width The width. -- @tparam[opt] number args.height The height. -- @tparam[opt] gears.color args.border_color The progressbar border color. -- @tparam[opt] number args.border_width The progressbar border width. -- @tparam[opt] gears.color args.bar_border_color The progressbar inner border color. -- @tparam[opt] number args.bar_border_width The progressbar inner border width. -- @tparam[opt] gears.color args.color The progressbar foreground color. -- @tparam[opt] gears.color args.background_color The progressbar background color. -- @tparam[opt] gears.shape args.bar_shape The progressbar inner shape. -- @tparam[opt] gears.shape args.shape The progressbar shape. -- @tparam[opt] boolean args.clip Force the inner part (the bar) to fit in the background shape. -- @tparam[opt] boolean args.ticks The progressbar to draw ticks. -- @tparam[opt] number args.ticks_gap The progressbar ticks gap. -- @tparam[opt] number args.ticks_size The progressbar ticks size. -- @tparam[opt] number args.max_value The maximum value the progressbar should handle. -- @tparam[opt] table|number args.margins The progressbar margins. -- @tparam[opt] table|number args.paddings The progressbar padding. -- @tparam[opt] number args.value Set the progressbar value. -- @treturn wibox.widget.progressbar A progressbar widget. -- @constructorfct wibox.widget.progressbar function progressbar.new(args) args = args or {} local pbar = base.make_widget(nil, nil, { enable_properties = true, }) pbar._private.width = args.width or 100 pbar._private.height = args.height or 20 pbar._private.value = 0 pbar._private.max_value = 1 gtable.crush(pbar, progressbar, true) return pbar end function progressbar.mt:__call(...) return progressbar.new(...) end return setmetatable(progressbar, progressbar.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
BHH-team/BHH-team
plugins/all.lua
1
4767
do data = load_data(_config.moderation.data) 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) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_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 table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end --Copyright; @Xx_minister_salib_xX --Persian Translate; @Xx_minister_salib_xX --ch : @Xx_etehad_salib_xX
gpl-2.0
fengshao0907/Atlas
lib/proxy/balance.lua
41
2807
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] module("proxy.balance", package.seeall) function idle_failsafe_rw() local backend_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] if conns.cur_idle_connections > 0 and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.type == proxy.BACKEND_TYPE_RW then backend_ndx = i break end end return backend_ndx end function idle_ro() local max_conns = -1 local max_conns_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] -- pick a slave which has some idling connections if s.type == proxy.BACKEND_TYPE_RO and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and conns.cur_idle_connections > 0 then if max_conns == -1 or s.connected_clients < max_conns then max_conns = s.connected_clients max_conns_ndx = i end end end return max_conns_ndx end function cycle_read_ro() local backends = proxy.global.backends local rwsplit = proxy.global.config.rwsplit local max_weight = rwsplit.max_weight local cur_weight = rwsplit.cur_weight local next_ndx = rwsplit.next_ndx local ndx_num = rwsplit.ndx_num local ndx = 0 for i = 1, ndx_num do --ÿ¸öquery×î¶àÂÖѯndx_num´Î local s = backends[next_ndx] if s.type == proxy.BACKEND_TYPE_RO and s.weight >= cur_weight and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.pool.users[proxy.connection.client.username].cur_idle_connections > 0 then ndx = next_ndx end if next_ndx == ndx_num then --ÂÖѯÍêÁË×îºóÒ»¸öndx£¬È¨Öµ¼õÒ» cur_weight = cur_weight - 1 if cur_weight == 0 then cur_weight = max_weight end next_ndx = 1 else --·ñÔòÖ¸Ïòϸöndx next_ndx = next_ndx + 1 end if ndx ~= 0 then break end end rwsplit.cur_weight = cur_weight rwsplit.next_ndx = next_ndx return ndx end
gpl-2.0
knewron-technologies/1btn
firmware/release v2/setup.lua
3
1136
-- gpio pin mapping RED = 1; GREEN = 2; YELLOW = 3; BLUE = 4; MAGENTA = 5; CYAN = 6 WHITE = 7; redLED = 7; greenLED = 6; blueLED = 5; node.setcpufreq(node.CPU160MHZ); -- set LED pins as output gpio.mode(redLED, gpio.OUTPUT); gpio.mode(greenLED, gpio.OUTPUT); gpio.mode(blueLED, gpio.OUTPUT); function setLED(ledColor) if bit.isset(ledColor, 0) then gpio.write(redLED, gpio.HIGH); else gpio.write(redLED, gpio.LOW); end if bit.isset(ledColor, 1) then gpio.write(greenLED, gpio.HIGH); else gpio.write(greenLED, gpio.LOW); end if bit.isset(ledColor, 2) then gpio.write(blueLED, gpio.HIGH); else gpio.write(blueLED, gpio.LOW); end end function blinkLED(ledColor, blinkTimes) for j = 1, blinkTimes do setLED(ledColor); tmr.delay(250000); setLED(0); tmr.delay(250000); end end -- setup uart at 9600bps by default with no echo uart.setup(0, 9600, 8, 0, 1, 0); -- configure wifi wifi.setmode(wifi.STATIONAP); setLED(0); dofile('btn.lc'); -- clean up collectgarbage("collect");
mit
Kaixhin/FGMachine
examples/Recurrent-Attention-Model/dataset.lua
1
1485
local mnist = require 'mnist' -- Load data local dataset = {} dataset.train = mnist.traindataset() dataset.test = mnist.testdataset() -- Save dataset constants dataset.height = 28 dataset.width = 28 dataset.channels = 1 dataset.classes = 10 -- Assign tensors local trainSet = { X = torch.zeros(dataset.train.size, dataset.channels, dataset.height, dataset.width), Y = torch.zeros(dataset.train.size), size = dataset.train.size } local testSet = { X = torch.zeros(dataset.test.size, dataset.channels, dataset.height, dataset.width), Y = torch.zeros(dataset.test.size), size = dataset.test.size } -- Form training data for i = 1, dataset.train.size do trainSet.X[{{i}, {1}, {}, {}}] = dataset.train[i].x trainSet.Y[{{i}}] = dataset.train[i].y -- 1-index labels if dataset.train[i].y == 0 then trainSet.Y[{{i}}] = 10 end end -- Form testing data for i = 1, dataset.test.size do testSet.X[{{i}, {1}, {}, {}}] = dataset.test[i].x testSet.Y[{{i}}] = dataset.test[i].y -- 1-index labels if dataset.test[i].y == 0 then testSet.Y[{{i}}] = 10 end end -- Put into dataset object dataset.train = trainSet dataset.test = testSet -- Retrieves a batch dataset.getBatch = function(setType, dataType, batchIndex, batchSize) if dataType == 'X' then return dataset[setType][dataType][{{batchIndex, batchIndex + batchSize - 1}, {}, {}, {}}] else return dataset[setType][dataType][{{batchIndex, batchIndex + batchSize - 1}}] end end return dataset
mit
awesomeWM/awesome
lib/wibox/layout/flex.lua
1
7853
--------------------------------------------------------------------------- -- Split the space equally between multiple widgets. -- -- -- A `flex` layout may be initialized with any number of child widgets, and -- during runtime widgets may be added and removed dynamically. -- -- On the main axis, the layout will divide the available space evenly between -- all child widgets, without any regard to how much space these widgets might -- be asking for. -- -- Just like @{wibox.layout.fixed}, `flex` allows adding spacing between the -- widgets, either as an ofset via @{spacing} or with a -- @{spacing_widget}. -- -- On its secondary axis, the layout's size is determined by the largest child -- widget. Smaller child widgets are then placed with the same size. -- Therefore, child widgets may ignore their `forced_width` or `forced_height` -- properties for vertical and horizontal layouts respectively. -- --@DOC_wibox_layout_defaults_flex_EXAMPLE@ -- @author Uli Schlachter -- @copyright 2010 Uli Schlachter -- @layoutmod wibox.layout.flex -- @supermodule wibox.layout.fixed --------------------------------------------------------------------------- local base = require("wibox.widget.base") local fixed = require("wibox.layout.fixed") local table = table local pairs = pairs local gmath = require("gears.math") local gtable = require("gears.table") local flex = {} -- {{{ Override inherited properties we want to hide --- From `wibox.layout.fixed`. -- @property fill_space -- @tparam[opt=true] boolean fill_space -- @propemits true false -- @hidden -- }}} --- Add some widgets to the given fixed layout. -- -- @tparam widget ... Widgets that should be added (must at least be one). -- @method add -- @noreturn -- @interface layout --- Remove a widget from the layout. -- -- @tparam number index The widget index to remove. -- @treturn boolean index If the operation is successful. -- @method remove -- @interface layout --- Remove one or more widgets from the layout. -- -- The last parameter can be a boolean, forcing a recursive seach of the -- widget(s) to remove. -- -- @tparam widget ... Widgets that should be removed (must at least be one). -- @treturn boolean If the operation is successful. -- @method remove_widgets -- @interface layout --- Insert a new widget in the layout at position `index`. -- -- @tparam number index The position -- @tparam widget widget The widget -- @treturn boolean If the operation is successful -- @method insert -- @emits widget::inserted -- @emitstparam widget::inserted widget self The layout. -- @emitstparam widget::inserted widget widget The inserted widget. -- @emitstparam widget::inserted number count The widget count. -- @interface layout --- A widget to insert as a separator between child widgets. -- -- If this property is a valid widget and @{spacing} is greater than `0`, a -- copy of this widget is inserted between each child widget, with its size in -- the layout's main direction determined by @{spacing}. -- -- By default no widget is used and any @{spacing} is applied as an empty offset. -- --@DOC_wibox_layout_flex_spacing_widget_EXAMPLE@ -- -- @property spacing_widget -- @tparam[opt=nil] widget|nil spacing_widget -- @propemits true false -- @interface layout --- The amount of space inserted between the child widgets. -- -- If a @{spacing_widget} is defined, this value is used for its size. -- --@DOC_wibox_layout_flex_spacing_EXAMPLE@ -- -- @property spacing -- @tparam[opt=0] number spacing Spacing between widgets. -- @propertyunit pixel -- @negativeallowed true -- @propemits true false -- @interface layout function flex:layout(_, width, height) local result = {} local spacing = self._private.spacing local num = #self._private.widgets local total_spacing = (spacing*(num-1)) local spacing_widget = self._private.spacing_widget local abspace = math.abs(spacing) local spoffset = spacing < 0 and 0 or spacing local is_y = self._private.dir == "y" local is_x = not is_y local space_per_item if is_y then space_per_item = height / num - total_spacing/num else space_per_item = width / num - total_spacing/num end if self._private.max_widget_size then space_per_item = math.min(space_per_item, self._private.max_widget_size) end local pos, pos_rounded = 0, 0 for k, v in pairs(self._private.widgets) do local x, y, w, h local next_pos = pos + space_per_item local next_pos_rounded = gmath.round(next_pos) if is_y then x, y = 0, pos_rounded w, h = width, next_pos_rounded - pos_rounded else x, y = pos_rounded, 0 w, h = next_pos_rounded - pos_rounded, height end pos = next_pos + spacing pos_rounded = next_pos_rounded + spacing table.insert(result, base.place_widget_at(v, x, y, w, h)) if k > 1 and spacing ~= 0 and spacing_widget then table.insert(result, base.place_widget_at( spacing_widget, is_x and (x - spoffset) or x, is_y and (y - spoffset) or y, is_x and abspace or w, is_y and abspace or h )) end end return result end -- Fit the flex layout into the given space. -- @param context The context in which we are fit. -- @param orig_width The available width. -- @param orig_height The available height. function flex:fit(context, orig_width, orig_height) local used_in_dir = 0 local used_in_other = 0 -- Figure out the maximum size we can give out to sub-widgets local sub_height = self._private.dir == "x" and orig_height or orig_height / #self._private.widgets local sub_width = self._private.dir == "y" and orig_width or orig_width / #self._private.widgets for _, v in pairs(self._private.widgets) do local w, h = base.fit_widget(self, context, v, sub_width, sub_height) local max = self._private.dir == "y" and w or h if max > used_in_other then used_in_other = max end used_in_dir = used_in_dir + (self._private.dir == "y" and h or w) end if self._private.max_widget_size then used_in_dir = math.min(used_in_dir, #self._private.widgets * self._private.max_widget_size) end local spacing = self._private.spacing * (#self._private.widgets-1) if self._private.dir == "y" then return used_in_other, used_in_dir + spacing end return used_in_dir + spacing, used_in_other end --- Set the maximum size the widgets in this layout will take. -- --That is, maximum width for horizontal and maximum height for vertical. -- -- @property max_widget_size -- @tparam[opt=nil] number|nil max_widget_size -- @propertytype nil No size limit. -- @negativeallowed false -- @propemits true false function flex:set_max_widget_size(val) if self._private.max_widget_size ~= val then self._private.max_widget_size = val self:emit_signal("widget::layout_changed") self:emit_signal("property::max_widget_size", val) end end local function get_layout(dir, widget1, ...) local ret = fixed[dir](widget1, ...) gtable.crush(ret, flex, true) ret._private.fill_space = nil return ret end --- Creates and returns a new horizontal flex layout. -- -- @tparam widget ... Widgets that should be added to the layout. -- @constructorfct wibox.layout.flex.horizontal function flex.horizontal(...) return get_layout("horizontal", ...) end --- Creates and returns a new vertical flex layout. -- -- @tparam widget ... Widgets that should be added to the layout. -- @constructorfct wibox.layout.flex.vertical function flex.vertical(...) return get_layout("vertical", ...) end --@DOC_fixed_COMMON@ return flex -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
cfromknecht/N-Body
third_party/glsdk/glload/codegen/_MakeCoreHeaderFile.lua
5
2261
--[[ The function MakeCoreHeaderFile will generate the core source file. This file will contain all of the core function pointers (including core extensions) in a big struct. It also exposes a function that will set these function pointers from the default version of OpenGL. The function is called "void [funcPrefix]eIntCoreInit();" This exists to fix the "core function" problem. Windows, for examples, defines all of the 1.1 entrypoints as regular functions. Thus, calling wglGetProcAddress will not retrieve those functions. We must instead get pointers to those functions manually. They get put into this struct. The above function will fill in the pointers that standard GL provides, while NULL-ing out things that aren't statically defined. You MUST include a file that has all of the typedefs before including this file. ]] require "_makeHelpers" require "_util" function MakeCoreHeaderFile(outFilename, specData, funcPrefix) local hFile = io.open(GetSourcePath() .. outFilename .. ".h", "w"); if(not hFile) then print("Could not open the output file\"" .. GetSourcePath() .. outFilename .. "\".\n"); return; end local defineName = string.upper(outFilename) .. "_H"; hFile:write(GetFileIncludeGuardStart(defineName)); hFile:write("\n"); hFile:write(GetExternCStart()); hFile:write("\n"); hFile:write("\n"); --Collect all of the appropriate functions. local funcList = Make.FetchAllCoreFunctions(specData); hFile:write(string.format("typedef struct %s_s\n", Make.GetCoreStructType(funcPrefix))); hFile:write("{\n"); --Write out the struct values. for i, func in ipairs(funcList) do hFile:write(string.format("\tvoid *%s;\n", Make.GetCoreStructMemberName(func, funcPrefix) )); end WriteForm(hFile, "}%s;\n", Make.GetCoreStructType(funcPrefix)); hFile:write("\n"); --Write the extern of the struct definition. hFile:write(string.format("extern %s %s;\n", Make.GetCoreStructType(funcPrefix), Make.GetCoreStructVarName(funcPrefix))); hFile:write("\n"); WriteFormatted(hFile, "void %s();\n", Make.GetCoreInitFuncName(funcPrefix)); hFile:write("\n"); hFile:write(GetExternCEnd()); hFile:write("\n"); hFile:write(GetFileIncludeGuardEnd(defineName)); hFile:write("\n"); hFile:close(); end
mit
TeleDALAD/test
bot/bot.lua
1
6651
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") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- 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 local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) 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 = { "9gag", "eur", "echo", "btc", "get", "giphy", "google", "gps", "help", "id", "images", "img_google", "location", "media", "plugins", "channels", "set", "stats", "time", "version", "weather", "xkcd", "youtube" }, sudo_users = {175623013}, disabled_channels = {} } 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 -- 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
bnetcc/darkstar
scripts/zones/West_Ronfaure/npcs/qm3.lua
5
1157
----------------------------------- -- Area: West Ronfaure -- NPC: qm3 (???) -- Involved in Quest: The Dismayed Customer -- !pos -399 -10 -438 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 3) then player:addKeyItem(GULEMONTS_DOCUMENT); player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT); player:setVar("theDismayedCustomer", 0); else player:messageSpecial(DISMAYED_CUSTOMER); end; end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
vowstar/nodemcu-firmware
app/cjson/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
mit
awesomeWM/awesome
tests/examples/awful/popup/wiboxtypes.lua
1
7591
--DOC_GEN_IMAGE --DOC_HIDE_ALL --DOC_NO_USAGE --DOC_NO_DASH require("_date") local awful = require("awful") local gears = require("gears") local naughty = require("naughty") local wibox = require("wibox") local beautiful = require("beautiful") --DOC_HIDE local assets = require("beautiful.theme_assets") local look = require("_default_look") local color = require("gears.color") screen[1]._resize {width = 640, height = 480} -- This example is used to show the various type of wibox awesome provides -- and mimic the default config look local c = client.gen_fake {hide_first=true} -- Don't use `awful.wallpaper` to avoid rasterizing the background. local wallpaper = wibox { below = true, shape = gears.shape.octogon, visible = true, bg = "#00000000", } awful.placement.maximize(wallpaper) wallpaper.widget = wibox.widget { fit = function(_, _, width, height) return width, height end, draw = function(_, _, cr, width, height) cr:translate(width - 80, 60) assets.gen_awesome_name( cr, height - 40, "#ffffff", beautiful.bg_normal, beautiful.bg_normal ) end, widget = wibox.widget.base.make_widget() } local p = awful.popup { widget = wibox.widget { { text = "Item", widget = wibox.widget.textbox }, { { text = "Selected", widget = wibox.widget.textbox }, bg = beautiful.bg_highlight, widget = wibox.container.background }, { text = "Item", widget = wibox.widget.textbox }, forced_width = 100, widget = wibox.layout.fixed.vertical }, border_color = beautiful.border_color, border_width = 1, x = 50, y = 200, } p:_apply_size_now() require("gears.timer").run_delayed_calls_now() p._drawable._do_redraw() require("gears.timer").delayed_call(function() -- Get the 4th textbox local list = p:find_widgets(30, 40) mouse.coords {x= 120, y=225} mouse.push_history() local textboxinstance = list[#list] local p2 = awful.popup { widget = wibox.widget { text = "Submenu", forced_height = 20, forced_width = 70, widget = wibox.widget.textbox }, border_color = beautiful.border_color, preferred_positions = "right", border_width = 1, } p2:move_next_to(textboxinstance, "right") end) c:geometry { x = 50, y = 350, height = 100, width = 150, } c._old_geo = {c:geometry()} c:set_label("A client") -- The popup awful.popup { widget = wibox.widget { awful.widget.layoutlist { filter = awful.widget.layoutlist.source.for_screen, screen = 1, base_layout = wibox.widget { spacing = 5, forced_num_cols = 5, layout = wibox.layout.grid.vertical, }, widget_template = { { { id = 'icon_role', forced_height = 22, forced_width = 22, widget = wibox.widget.imagebox, }, margins = 4, widget = wibox.container.margin, }, id = 'background_role', forced_width = 24, forced_height = 24, shape = gears.shape.rounded_rect, widget = wibox.container.background, }, }, margins = 4, widget = wibox.container.margin, }, border_color = beautiful.border_color, border_width = beautiful.border_width, placement = awful.placement.centered, ontop = true, shape = gears.shape.rounded_rect } -- poor copy of awful.widget.calendar_widget until I fix its API to be less -- insane. local p10 = awful.popup { widget = { wibox.widget.calendar.month(os.date('*t')), top = 30, margins = 10, layout = wibox.container.margin }, preferred_anchors = "middle", border_width = 2, border_color = beautiful.border_color, hide_on_right_click = true, placement = function(d) return awful.placement.top_right(d, { honor_workarea = true, }) end, shape = gears.shape.infobubble, } require("gears.timer").run_delayed_calls_now() p10:bind_to_widget(look.mytextclock) -- The titlebar c:emit_signal("request::titlebars", "rules", {})--DOC_HIDE -- Normal wiboxes wibox { width = 50, height = 50, shape = gears.shape.octogon, visible = true, color = "#0000ff", x = 570, y = 410, border_width = 2, border_color = beautiful.border_color, } -- The tooltip mouse.coords{x=50, y= 100} mouse.push_history() local tt = awful.tooltip { text = "A tooltip!", visible = true, } tt.bg = beautiful.bg_normal -- Extra information overlay local overlay_w = wibox { bg = "#00000000", visible = true, ontop = true, } awful.placement.maximize(overlay_w) local canvas = wibox.layout.manual() canvas.forced_height = 480 canvas.forced_width = 640 overlay_w:set_widget(canvas) local function create_info(text, x, y, width, height) canvas:add_at(wibox.widget { { { text = text, halign = "center", ellipsize = "none", wrap = "word", widget = wibox.widget.textbox }, margins = 10, widget = wibox.container.margin }, forced_width = width, forced_height = height, shape = gears.shape.rectangle, border_width = 1, border_color = beautiful.border_color, bg = "#ffff0055", widget = wibox.container.background }, {x = x, y = y}) end local function create_line(x1, y1, x2, y2) return canvas:add_at(wibox.widget { fit = function() return x2-x1+6, y2-y1+6 end, draw = function(_, _, cr) cr:set_source(color(beautiful.fg_normal)) cr:set_line_width(1) cr:arc(1.5, 1.5, 1.5, 0, math.pi*2) cr:arc(x2-x1+1.5, y2-y1+1.5, 1.5, 0, math.pi*2) cr:fill() cr:move_to(1.5,1.5) cr:line_to(x2-x1+1.5, y2-y1+1.5) cr:stroke() end, layout = wibox.widget.base.make_widget, }, {x=x1, y=y1}) end naughty.connect_signal("request::display", function(n) naughty.layout.box {notification = n} end) naughty.notification { title = "A notification", message = "With a message! ....", position = "top_middle", } create_info("awful.wibar", 100, 50, 100, 30) create_info("awful.titlebar", 250, 350, 100, 30) create_info("awful.tooltip", 30, 130, 100, 30) create_info("awful.popup", 450, 240, 100, 30) create_info("naughty.layout.box", 255, 110, 130, 30) create_info("Standard `wibox`", 420, 420, 130, 30) create_info("awful.wallpaper", 420, 330, 110, 30) create_info("awful.menu", 60, 270, 80, 30) create_line(150, 10, 150, 55) create_line(75, 100, 75, 135) create_line(545, 432, 575, 432) create_line(500, 165, 500, 245) create_line(380, 250, 450, 250) create_line(190, 365, 255, 365) create_line(320, 60, 320, 110) create_line(525, 345, 570, 345) create_line(100, 240, 100, 270) --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
TurkeyMan/premake-core
modules/gmake2/tests/test_gmake2_pch.lua
11
4768
-- -- test_gmake2_pch.lua -- Validate the setup for precompiled headers in makefiles. -- (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local p = premake local suite = test.declare("gmake2_pch") local p = premake local gmake2 = p.modules.gmake2 local project = p.project -- -- Setup and teardown -- local wks, prj function suite.setup() os.chdir(_TESTS_DIR) gmake2.cpp.initialize() wks, prj = test.createWorkspace() end local function prepareVars() local cfg = test.getconfig(prj, "Debug") gmake2.cpp.pch(cfg) end local function prepareRules() local cfg = test.getconfig(prj, "Debug") gmake2.cpp.pchRules(cfg.project) end local function prepareFlags() local project = test.getproject(wks, 1) gmake2.cpp.createRuleTable(project) gmake2.cpp.createFileTable(project) gmake2.cpp.outputFileRuleSection(project) end -- -- If no header has been set, nothing should be output. -- function suite.noConfig_onNoHeaderSet() prepareVars() test.isemptycapture() end -- -- If a header is set, but the NoPCH flag is also set, then -- nothing should be output. -- function suite.noConfig_onHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags "NoPCH" files { 'a.cpp', 'b.cpp' } prepareFlags() test.capture [[ # File Rules # ############################################# $(OBJDIR)/a.o: a.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/b.o: b.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end -- -- If a header is specified and the NoPCH flag is not set, then -- the header can be used. -- function suite.config_onPchEnabled() pchheader "include/myproject.h" prepareVars() test.capture [[ PCH = include/myproject.h PCH_PLACEHOLDER = $(OBJDIR)/$(notdir $(PCH)) GCH = $(PCH_PLACEHOLDER).gch ]] end -- -- The PCH can be specified relative the an includes search path. -- function suite.pch_searchesIncludeDirs() pchheader "premake.h" includedirs { "../../../src/host" } prepareVars() test.capture [[ PCH = ../../../src/host/premake.h ]] end -- -- Verify the format of the PCH rules block for a C++ file. -- function suite.buildRules_onCpp() pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) $(OBJECTS): $(GCH) | $(PCH_PLACEHOLDER) $(GCH): $(PCH) | prebuild @echo $(notdir $<) $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" $(PCH_PLACEHOLDER): $(GCH) | $(OBJDIR) ifeq (posix,$(SHELLTYPE)) $(SILENT) touch "$@" else $(SILENT) echo $null >> "$@" endif else $(OBJECTS): | prebuild endif ]] end -- -- Verify the format of the PCH rules block for a C file. -- function suite.buildRules_onC() language "C" pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) $(OBJECTS): $(GCH) | $(PCH_PLACEHOLDER) $(GCH): $(PCH) | prebuild @echo $(notdir $<) $(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" $(PCH_PLACEHOLDER): $(GCH) | $(OBJDIR) ifeq (posix,$(SHELLTYPE)) $(SILENT) touch "$@" else $(SILENT) echo $null >> "$@" endif else $(OBJECTS): | prebuild endif ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.findsPCH_onIncludeDirs() location "MyProject" pchheader "premake.h" includedirs { "../../../src/host" } prepareVars() test.capture [[ PCH = ../../../../src/host/premake.h ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.PCHFlag() pchheader "include/myproject.h" files { 'a.cpp', 'b.cpp' } prepareFlags() test.capture [[ # File Rules # ############################################# $(OBJDIR)/a.o: a.cpp @echo $(notdir $<) $(SILENT) $(CXX) -include $(PCH_PLACEHOLDER) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/b.o: b.cpp @echo $(notdir $<) $(SILENT) $(CXX) -include $(PCH_PLACEHOLDER) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end function suite.PCHFlag_PerFile() pchheader "include/myproject.h" files { 'a.cpp', 'b.cpp' } filter { "files:a.cpp" } flags "NoPCH" prepareFlags() test.capture [[ # File Rules # ############################################# $(OBJDIR)/a.o: a.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/b.o: b.cpp @echo $(notdir $<) $(SILENT) $(CXX) -include $(PCH_PLACEHOLDER) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end
bsd-3-clause
leonardoaxe/OpenRA
mods/cnc/maps/nod07a/nod07a-AI.lua
5
5825
AttackPaths = { { AttackPath1 }, { AttackPath2 } } GDIBase = { GDICYard, GDIPyle, GDIWeap, GDIHQ, GDIProc, GDINuke1, GDINuke2, GDINuke3, GDIBuilding1, GDIBuilding2, GDIBuilding3, GDIBuilding4, GDIBuilding5, GDIBuilding6, GDIBuilding7, GDIBuilding8 } InfantryAttackGroup = { } InfantryGroupSize = 4 InfantryProductionCooldown = DateTime.Minutes(3) InfantryProductionTypes = { "e1", "e1", "e2" } HarvesterProductionType = { "harv" } VehicleAttackGroup = { } VehicleGroupSize = 4 VehicleProductionCooldown = DateTime.Minutes(4) VehicleProductionTypes = { "jeep", "jeep", "mtnk", "mtnk", "mtnk" } StartingCash = 4000 BaseProc = { type = "proc", pos = CPos.New(22, 51), cost = 1500, exists = true } BaseNuke1 = { type = "nuke", pos = CPos.New(16, 56), cost = 500, exists = true } BaseNuke2 = { type = "nuke", pos = CPos.New(18, 57), cost = 500, exists = true } BaseNuke3 = { type = "nuke", pos = CPos.New(27, 51), cost = 500, exists = true } InfantryProduction = { type = "pyle", pos = CPos.New(18, 54), cost = 500, exists = true } VehicleProduction = { type = "weap", pos = CPos.New(27, 55), cost = 2000, exists = true } BaseBuildings = { BaseProc, BaseNuke1, BaseNuke2, BaseNuke3, InfantryProduction, VehicleProduction } BuildBase = function(cyard) Utils.Do(BaseBuildings, function(building) if not building.exists and not cyardIsBuilding then BuildBuilding(building, cyard) return end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end BuildBuilding = function(building, cyard) cyardIsBuilding = true Trigger.AfterDelay(Actor.BuildTime(building.type), function() cyardIsBuilding = false if cyard.IsDead or cyard.Owner ~= enemy then return end local actor = Actor.Create(building.type, true, { Owner = enemy, Location = building.pos }) enemy.Cash = enemy.Cash - building.cost building.exists = true if actor.Type == 'pyle' or actor.Type == 'hand' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(actor) end) elseif actor.Type == 'weap' or actor.Type == 'afld' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(actor) end) end Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end) end CheckForHarvester = function() local harv = enemy.GetActorsByType("harv") return #harv > 0 end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function(enemy) local lazyUnits = enemy.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) IdleHunt(unit) end) end ProduceHarvester = function(building) if not buildingHarvester then buildingHarvester = true building.Build(HarvesterProductionType, function() buildingHarvester = false end) end end ProduceInfantry = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(InfantryProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) InfantryAttackGroup[#InfantryAttackGroup + 1] = unit[1] if #InfantryAttackGroup >= InfantryGroupSize then SendUnits(InfantryAttackGroup, Path) InfantryAttackGroup = { } Trigger.AfterDelay(InfantryProductionCooldown, function() ProduceInfantry(building) end) else Trigger.AfterDelay(delay, function() ProduceInfantry(building) end) end end) end ProduceVehicle = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then ProduceHarvester(building) Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(VehicleProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) VehicleAttackGroup[#VehicleAttackGroup + 1] = unit[1] if #VehicleAttackGroup >= VehicleGroupSize then SendUnits(VehicleAttackGroup, Path) VehicleAttackGroup = { } Trigger.AfterDelay(VehicleProductionCooldown, function() ProduceVehicle(building) end) else Trigger.AfterDelay(delay, function() ProduceVehicle(building) end) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end) end StartAI = function(cyard) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) enemy.Cash = StartingCash BuildBase(cyard) end Trigger.OnAllKilledOrCaptured(GDIBase, function() IdlingUnits(enemy) end) Trigger.OnKilled(GDIProc, function(building) BaseProc.exists = false end) Trigger.OnKilled(GDINuke1, function(building) BaseNuke1.exists = false end) Trigger.OnKilled(GDINuke2, function(building) BaseNuke2.exists = false end) Trigger.OnKilled(GDINuke3, function(building) BaseNuke3.exists = false end) Trigger.OnKilled(GDIPyle, function(building) InfantryProduction.exists = false end) Trigger.OnKilled(GDIWeap, function(building) VehicleProduction.exists = false end)
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/regen_iv.lua
5
1338
----------------------------------------- -- Spell: Regen IV -- Gradually restores target's HP. ----------------------------------------- -- Scale down duration based on level -- Composure increases duration 3x ----------------------------------------- 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 hp = math.ceil(30 * (1 + 0.01 * caster:getMod(MOD_REGEN_MULTIPLIER))); -- spell base times gear multipliers hp = hp + caster:getMerit(MERIT_REGEN_EFFECT); -- bonus hp from merits hp = hp + caster:getMod(MOD_LIGHT_ARTS_REGEN); -- bonus hp from light arts local duration = 60; duration = duration + caster:getMod(MOD_REGEN_DURATION); duration = calculateDurationForLvl(duration, 86, target:getMainLvl()); if (target:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then target:delStatusEffect(EFFECT_REGEN); end if (target:addStatusEffect(EFFECT_REGEN,hp,3,duration,0,0,0)) then spell:setMsg(msgBasic.MAGIC_GAIN_EFFECT); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect end return EFFECT_REGEN; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Southern_San_dOria/npcs/Anniversary_Mog.lua
1
9649
----------------------------------- -- Southern Sandy Anniversary Moogle -- anniversary band every day if not in inventory and free slot -- Random effect applied once an hour when player talks to moogle ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/events/LegionDarkAnniversary"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1) then if (player:getFreeSlotsCount() == 0) then player:PrintToPlayer("Hey, you don't have inventory space, kupo! ", chatType.SAY, underscore2space(npc:getName())); else -- Note: most complete trade first because item is rare flagged! if (trade:hasItemQty(13216, 1)) then -- Gold Mog Belt player:tradeComplete(trade); player:addItem(13216, 1, 551, 2, 37, 1); -- STR+3, VIT+3, Mag.Evasion+2 player:PrintToPlayer("A Gold Mog belt!!! Here, let me unlock its latent powers.. ", chatType.SAY, underscore2space(npc:getName())); player:injectActionPacket(6, 207, 0, 0, 0); player:messageSpecial(ITEM_OBTAINED, 13216); elseif (trade:hasItemQty(13217, 1)) then -- Silver Mog Belt player:tradeComplete(trade); player:addItem(13217, 1, 554, 2, 1806, 1); -- INT+3, MND+3, Pet: STR+2 DEX+2 VIT+2 player:PrintToPlayer("A Silver Mog belt!!! Here, let me unlock its latent powers.. ", chatType.SAY, underscore2space(npc:getName())); player:injectActionPacket(6, 207, 0, 0, 0); player:messageSpecial(ITEM_OBTAINED, 13217); elseif (trade:hasItemQty(13218, 1)) then -- Bronze Mog Belt player:tradeComplete(trade); player:addItem(13218, 1, 553, 2, 332, 1); -- DEX+3, AGI+3, Sklchn.dmg.+2% player:PrintToPlayer("A Bronze Mog belt!!! Here, let me unlock its latent powers.. ", chatType.SAY, underscore2space(npc:getName())); player:injectActionPacket(6, 207, 0, 0, 0); player:messageSpecial(ITEM_OBTAINED, 13218); else player:PrintToPlayer("Have you ever heard of the legendary mog belts? In ages past we moogles had amazing girdled of magnificent kupower! ", chatType.SAY, underscore2space(npc:getName())); end end else player:PrintToPlayer("Hey, one item at a time, don't kupo'ing confuse me. ", chatType.SAY, underscore2space(npc:getName())); end end; function onTrigger(player,npc) local month = tonumber(os.date("%m")); local day = tonumber(os.date("%d")); if ((month == 12 and day >= 1 and day <= 10)) then --[[ old code -- Anniversary ring if (player:getFreeSlotsCount() >= 1) then if (player:getVar("AnniversaryLootGet") < os.time()) then player:messageSpecial(ITEM_OBTAINED, 15793); player:addItem(15793, 1); player:setVar("AnniversaryLootGet", os.time()+86400); else player:PrintToPlayer("Check back later. Rings are issued once a day. ", chatType.SAY, npc:getName()); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 15793); end ]] -- Convert old varname.. if (player:getVar("ANNIRING_TIMER") ~=0) then player:setVar("AnniversaryLootGet", player:getVar("ANNIRING_TIMER")); player:setVar("ANNIRING_TIMER", 0); end if (player:getVar("AnniversaryBuff_TIMER") ~=0) then player:setVar("AnniversaryBuffGet", player:getVar("AnniversaryBuff_TIMER")); player:setVar("AnniversaryBuff_TIMER", 0); end -- One per day random reward -- Todo: make this into random past event rewards, after we have more working events if (player:getVar("AnniversaryLootGet") < os.time()) then local itemID = getAnniversaryEventItem(player); if (itemID ~= nil) then if (player:addItem(itemID, 1)) then player:setVar("AnniversaryLootGet", os.time()+86400); player:messageSpecial(ITEM_OBTAINED, itemID); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, itemID); end else player:PrintToPlayer("An error occurred, could not find the item ID. Please bug report."); end else player:PrintToPlayer("Anniversary event prizes are awarded once per earth day. ", chatType.SAY, underscore2space(npc:getName())); end local AnniversaryBuff = math.random(1,10); if (player:getVar("AnniversaryBuffGet") < os.time()) then if (AnniversaryBuff == 1) then player:addStatusEffect(EFFECT_FLEE,50,0,1800); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); player:addStatusEffect(EFFECT_COSTUME,2744,0,1800); elseif (AnniversaryBuff == 2) then player:addStatusEffect(EFFECT_REGEN, 10,1,1800); player:addStatusEffect(EFFECT_REFRESH, 10,1,1800); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); elseif (AnniversaryBuff == 3) then player:addStatusEffect(EFFECT_REGAIN, 10,1,1800); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); elseif (AnniversaryBuff == 4) then player:addStatusEffect(EFFECT_MAX_HP_BOOST,40,0,1800); player:addStatusEffect(EFFECT_MAX_MP_BOOST,40,0,1800); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); elseif (AnniversaryBuff == 5) then player:addStatusEffect(EFFECT_STR_BOOST,50,0,1800); player:addStatusEffect(EFFECT_DEX_BOOST,50,0,1800); player:addStatusEffect(EFFECT_VIT_BOOST,50,0,1800); player:addStatusEffect(EFFECT_AGI_BOOST,50,0,1800); player:addStatusEffect(EFFECT_INT_BOOST,50,0,1800); player:addStatusEffect(EFFECT_MND_BOOST,50,0,1800); player:addStatusEffect(EFFECT_CHR_BOOST,50,0,1800); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); elseif (AnniversaryBuff == 6) then player:addStatusEffect(EFFECT_CHAINSPELL, 1,0,900); player:setVar("AnniversaryBuffGet", os.time()+3600); elseif (AnniversaryBuff == 7) then player:addStatusEffect(EFFECT_HUNDRED_FISTS,1,0,900); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); elseif (AnniversaryBuff == 8) then player:addStatusEffect(EFFECT_MIGHTY_STRIKES,1,0,900); player:setVar("AnniversaryBuffGet", os.time()+3600); elseif (AnniversaryBuff == 9) then player:addStatusEffect(EFFECT_MANAFONT,1,0,900); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); elseif (AnniversaryBuff == 10) then player:addStatusEffect(EFFECT_MAX_HP_BOOST,1000,0,900); player:addStatusEffect(EFFECT_MAX_MP_BOOST,1000,0,900); player:addStatusEffect(EFFECT_MIGHTY_STRIKES,1,0,900); player:addStatusEffect(EFFECT_HUNDRED_FISTS,1,0,900); player:addStatusEffect(EFFECT_CHAINSPELL,1,0,900); player:addStatusEffect(EFFECT_PERFECT_DODGE,1,0,900); player:addStatusEffect(EFFECT_INVINCIBLE,1,0,900); player:addStatusEffect(EFFECT_ELEMENTAL_SFORZO,1,0,900); player:addStatusEffect(EFFECT_MANAFONT,1,0,900); player:addStatusEffect(EFFECT_REGAIN,150,0,900); player:addStatusEffect(EFFECT_REFRESH,99,0,900); player:addStatusEffect(EFFECT_REGEN,99,0,900); player:setVar("AnniversaryBuffGet", os.time()+3600); player:injectActionPacket(6, 207, 0, 0, 0); end else player:PrintToPlayer("Anniversary power-up buffs are issued once an hour. ", chatType.SAY, underscore2space(npc:getName())); end player:PrintToPlayer("Have you ever heard of the legendary mog belts? In ages past we moogles had amazing girdled of magnificent kupower! ", chatType.SAY, underscore2space(npc:getName())); else player:PrintToPlayer("The Anniversary Event begins December 1st and lasts to December 10th. ", chatType.SAY, underscore2space(npc:getName())); player:PrintToPlayer("Have you ever heard of the legendary mog belts? In ages past we moogles had amazing girdled of magnificent kupower! ", chatType.SAY, underscore2space(npc:getName())); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("updateRESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("finishRESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/mobskills/erratic_flutter.lua
3
1440
--------------------------------------------- -- Erratic Flutter -- -- Description: Deals Fire damage around the caster. Grants the effect of Haste. -- Family: Wamoura -- Monipulators: Wamoura (MON), Coral Wamoura (MON) -- Level (Monstrosity): 60 -- TP Cost (Monstrosity): 1500 TP -- Type: Enhancing -- Element: Fire -- Can be dispelled: Yes -- Notes: -- Blue magic version is 307/1024 haste for 5 minutes. Wamaora haste is presumed identical. -- Wamoura version also deals Fire damage to targets around the wamoura. -- While it does not overwrite most forms of Slowga, Slow II, Slow II TP moves, -- Erratic Flutter does overwrite Hojo: Ni, Hojo: Ichi, and Slow. -- Player Blue magic version is wind element instead of fire. --------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*1.5,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS); MobBuffMove(mob, EFFECT_HASTE, 307, 0, 300); -- There is no message for the self buff aspect, only dmg. target:delHP(dmg); return dmg; end;
gpl-3.0
javaliker/google-diff-match-patch
lua/diff_match_patch.lua
265
73869
--[[ * Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Based on the JavaScript implementation by Neil Fraser. * Ported to Lua by Duncan Cross. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. --]] --[[ -- Lua 5.1 and earlier requires the external BitOp library. -- This library is built-in from Lua 5.2 and later as 'bit32'. require 'bit' -- <http://bitop.luajit.org/> local band, bor, lshift = bit.band, bit.bor, bit.lshift --]] local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local type, setmetatable, ipairs, select = type, setmetatable, ipairs, select local unpack, tonumber, error = unpack, tonumber, error local strsub, strbyte, strchar, gmatch, gsub = string.sub, string.byte, string.char, string.gmatch, string.gsub local strmatch, strfind, strformat = string.match, string.find, string.format local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local max, min, floor, ceil, abs = math.max, math.min, math.floor, math.ceil, math.abs local clock = os.clock -- Utility functions. local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]' local function percentEncode_replace(v) return strformat('%%%02X', strbyte(v)) end local function tsplice(t, idx, deletions, ...) local insertions = select('#', ...) for i = 1, deletions do tremove(t, idx) end for i = insertions, 1, -1 do -- do not remove parentheses around select tinsert(t, idx, (select(i, ...))) end end local function strelement(str, i) return strsub(str, i, i) end local function indexOf(a, b, start) if (#b == 0) then return nil end return strfind(a, b, start, true) end local htmlEncode_pattern = '[&<>\n]' local htmlEncode_replace = { ['&'] = '&amp;', ['<'] = '&lt;', ['>'] = '&gt;', ['\n'] = '&para;<br>' } -- Public API Functions -- (Exported at the end of the script) local diff_main, diff_cleanupSemantic, diff_cleanupEfficiency, diff_levenshtein, diff_prettyHtml local match_main local patch_make, patch_toText, patch_fromText, patch_apply --[[ * The data structure representing a diff is an array of tuples: * {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}} * which means: delete 'Hello', add 'Goodbye' and keep ' world.' --]] local DIFF_DELETE = -1 local DIFF_INSERT = 1 local DIFF_EQUAL = 0 -- Number of seconds to map a diff before giving up (0 for infinity). local Diff_Timeout = 1.0 -- Cost of an empty edit operation in terms of edit characters. local Diff_EditCost = 4 -- At what point is no match declared (0.0 = perfection, 1.0 = very loose). local Match_Threshold = 0.5 -- How far to search for a match (0 = exact location, 1000+ = broad match). -- A match this many characters away from the expected location will add -- 1.0 to the score (0.0 is a perfect match). local Match_Distance = 1000 -- When deleting a large block of text (over ~64 characters), how close do -- the contents have to be to match the expected contents. (0.0 = perfection, -- 1.0 = very loose). Note that Match_Threshold controls how closely the -- end points of a delete need to match. local Patch_DeleteThreshold = 0.5 -- Chunk size for context length. local Patch_Margin = 4 -- The number of bits in an int. local Match_MaxBits = 32 function settings(new) if new then Diff_Timeout = new.Diff_Timeout or Diff_Timeout Diff_EditCost = new.Diff_EditCost or Diff_EditCost Match_Threshold = new.Match_Threshold or Match_Threshold Match_Distance = new.Match_Distance or Match_Distance Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold Patch_Margin = new.Patch_Margin or Patch_Margin Match_MaxBits = new.Match_MaxBits or Match_MaxBits else return { Diff_Timeout = Diff_Timeout; Diff_EditCost = Diff_EditCost; Match_Threshold = Match_Threshold; Match_Distance = Match_Distance; Patch_DeleteThreshold = Patch_DeleteThreshold; Patch_Margin = Patch_Margin; Match_MaxBits = Match_MaxBits; } end end -- --------------------------------------------------------------------------- -- DIFF API -- --------------------------------------------------------------------------- -- The private diff functions local _diff_compute, _diff_bisect, _diff_halfMatchI, _diff_halfMatch, _diff_cleanupSemanticScore, _diff_cleanupSemanticLossless, _diff_cleanupMerge, _diff_commonPrefix, _diff_commonSuffix, _diff_commonOverlap, _diff_xIndex, _diff_text1, _diff_text2, _diff_toDelta, _diff_fromDelta --[[ * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} opt_checklines Has no effect in Lua. * @param {number} opt_deadline Optional time when the diff should be complete * by. Used internally for recursive calls. Users should set DiffTimeout * instead. * @return {Array.<Array.<number|string>>} Array of diff tuples. --]] function diff_main(text1, text2, opt_checklines, opt_deadline) -- Set a deadline by which time the diff must be complete. if opt_deadline == nil then if Diff_Timeout <= 0 then opt_deadline = 2 ^ 31 else opt_deadline = clock() + Diff_Timeout end end local deadline = opt_deadline -- Check for null inputs. if text1 == nil or text1 == nil then error('Null inputs. (diff_main)') end -- Check for equality (speedup). if text1 == text2 then if #text1 > 0 then return {{DIFF_EQUAL, text1}} end return {} end -- LUANOTE: Due to the lack of Unicode support, Lua is incapable of -- implementing the line-mode speedup. local checklines = false -- Trim off common prefix (speedup). local commonlength = _diff_commonPrefix(text1, text2) local commonprefix if commonlength > 0 then commonprefix = strsub(text1, 1, commonlength) text1 = strsub(text1, commonlength + 1) text2 = strsub(text2, commonlength + 1) end -- Trim off common suffix (speedup). commonlength = _diff_commonSuffix(text1, text2) local commonsuffix if commonlength > 0 then commonsuffix = strsub(text1, -commonlength) text1 = strsub(text1, 1, -commonlength - 1) text2 = strsub(text2, 1, -commonlength - 1) end -- Compute the diff on the middle block. local diffs = _diff_compute(text1, text2, checklines, deadline) -- Restore the prefix and suffix. if commonprefix then tinsert(diffs, 1, {DIFF_EQUAL, commonprefix}) end if commonsuffix then diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix} end _diff_cleanupMerge(diffs) return diffs end --[[ * Reduce the number of edits by eliminating semantically trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupSemantic(diffs) local changes = false local equalities = {} -- Stack of indices where equalities are found. local equalitiesLength = 0 -- Keeping our own length var is faster. local lastequality = nil -- Always equal to diffs[equalities[equalitiesLength]][2] local pointer = 1 -- Index of current position. -- Number of characters that changed prior to the equality. local length_insertions1 = 0 local length_deletions1 = 0 -- Number of characters that changed after the equality. local length_insertions2 = 0 local length_deletions2 = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer length_insertions1 = length_insertions2 length_deletions1 = length_deletions2 length_insertions2 = 0 length_deletions2 = 0 lastequality = diffs[pointer][2] else -- An insertion or deletion. if diffs[pointer][1] == DIFF_INSERT then length_insertions2 = length_insertions2 + #(diffs[pointer][2]) else length_deletions2 = length_deletions2 + #(diffs[pointer][2]) end -- Eliminate an equality that is smaller or equal to the edits on both -- sides of it. if lastequality and (#lastequality <= max(length_insertions1, length_deletions1)) and (#lastequality <= max(length_insertions2, length_deletions2)) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 -- Throw away the previous equality (it needs to be reevaluated). equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 length_insertions1, length_deletions1 = 0, 0 -- Reset the counters. length_insertions2, length_deletions2 = 0, 0 lastequality = nil changes = true end end pointer = pointer + 1 end -- Normalize the diff. if changes then _diff_cleanupMerge(diffs) end _diff_cleanupSemanticLossless(diffs) -- Find any overlaps between deletions and insertions. -- e.g: <del>abcxxx</del><ins>xxxdef</ins> -- -> <del>abc</del>xxx<ins>def</ins> -- e.g: <del>xxxabc</del><ins>defxxx</ins> -- -> <ins>def</ins>xxx<del>abc</del> -- Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 2 while diffs[pointer] do if (diffs[pointer - 1][1] == DIFF_DELETE and diffs[pointer][1] == DIFF_INSERT) then local deletion = diffs[pointer - 1][2] local insertion = diffs[pointer][2] local overlap_length1 = _diff_commonOverlap(deletion, insertion) local overlap_length2 = _diff_commonOverlap(insertion, deletion) if (overlap_length1 >= overlap_length2) then if (overlap_length1 >= #deletion / 2 or overlap_length1 >= #insertion / 2) then -- Overlap found. Insert an equality and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(insertion, 1, overlap_length1)}) diffs[pointer - 1][2] = strsub(deletion, 1, #deletion - overlap_length1) diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1) pointer = pointer + 1 end else if (overlap_length2 >= #deletion / 2 or overlap_length2 >= #insertion / 2) then -- Reverse overlap found. -- Insert an equality and swap and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(deletion, 1, overlap_length2)}) diffs[pointer - 1] = {DIFF_INSERT, strsub(insertion, 1, #insertion - overlap_length2)} diffs[pointer + 1] = {DIFF_DELETE, strsub(deletion, overlap_length2 + 1)} pointer = pointer + 1 end end pointer = pointer + 1 end pointer = pointer + 1 end end --[[ * Reduce the number of edits by eliminating operationally trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupEfficiency(diffs) local changes = false -- Stack of indices where equalities are found. local equalities = {} -- Keeping our own length var is faster. local equalitiesLength = 0 -- Always equal to diffs[equalities[equalitiesLength]][2] local lastequality = nil -- Index of current position. local pointer = 1 -- The following four are really booleans but are stored as numbers because -- they are used at one point like this: -- -- (pre_ins + pre_del + post_ins + post_del) == 3 -- -- ...i.e. checking that 3 of them are true and 1 of them is false. -- Is there an insertion operation before the last equality. local pre_ins = 0 -- Is there a deletion operation before the last equality. local pre_del = 0 -- Is there an insertion operation after the last equality. local post_ins = 0 -- Is there a deletion operation after the last equality. local post_del = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. local diffText = diffs[pointer][2] if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then -- Candidate found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer pre_ins, pre_del = post_ins, post_del lastequality = diffText else -- Not a candidate, and can never become one. equalitiesLength = 0 lastequality = nil end post_ins, post_del = 0, 0 else -- An insertion or deletion. if diffs[pointer][1] == DIFF_DELETE then post_del = 1 else post_ins = 1 end --[[ * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> --]] if lastequality and ( (pre_ins+pre_del+post_ins+post_del == 4) or ( (#lastequality < Diff_EditCost / 2) and (pre_ins+pre_del+post_ins+post_del == 3) )) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 lastequality = nil if (pre_ins == 1) and (pre_del == 1) then -- No changes made which could affect previous entry, keep going. post_ins, post_del = 1, 1 equalitiesLength = 0 else -- Throw away the previous equality. equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 post_ins, post_del = 0, 0 end changes = true end end pointer = pointer + 1 end if changes then _diff_cleanupMerge(diffs) end end --[[ * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {number} Number of changes. --]] function diff_levenshtein(diffs) local levenshtein = 0 local insertions, deletions = 0, 0 for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if (op == DIFF_INSERT) then insertions = insertions + #data elseif (op == DIFF_DELETE) then deletions = deletions + #data elseif (op == DIFF_EQUAL) then -- A deletion and an insertion is one substitution. levenshtein = levenshtein + max(insertions, deletions) insertions = 0 deletions = 0 end end levenshtein = levenshtein + max(insertions, deletions) return levenshtein end --[[ * Convert a diff array into a pretty HTML report. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} HTML representation. --]] function diff_prettyHtml(diffs) local html = {} for x, diff in ipairs(diffs) do local op = diff[1] -- Operation (insert, delete, equal) local data = diff[2] -- Text of change. local text = gsub(data, htmlEncode_pattern, htmlEncode_replace) if op == DIFF_INSERT then html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>' elseif op == DIFF_DELETE then html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>' elseif op == DIFF_EQUAL then html[x] = '<span>' .. text .. '</span>' end end return tconcat(html) end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE DIFF FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} checklines Has no effect in Lua. * @param {number} deadline Time when the diff should be complete by. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_compute(text1, text2, checklines, deadline) if #text1 == 0 then -- Just add some text (speedup). return {{DIFF_INSERT, text2}} end if #text2 == 0 then -- Just delete some text (speedup). return {{DIFF_DELETE, text1}} end local diffs local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 local i = indexOf(longtext, shorttext) if i ~= nil then -- Shorter text is inside the longer text (speedup). diffs = { {DIFF_INSERT, strsub(longtext, 1, i - 1)}, {DIFF_EQUAL, shorttext}, {DIFF_INSERT, strsub(longtext, i + #shorttext)} } -- Swap insertions for deletions if diff is reversed. if #text1 > #text2 then diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE end return diffs end if #shorttext == 1 then -- Single character string. -- After the previous speedup, the character can't be an equality. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end -- Check to see if the problem can be split in two. do local text1_a, text1_b, text2_a, text2_b, mid_common = _diff_halfMatch(text1, text2) if text1_a then -- A half-match was found, sort out the return data. -- Send both pairs off for separate processing. local diffs_a = diff_main(text1_a, text2_a, checklines, deadline) local diffs_b = diff_main(text1_b, text2_b, checklines, deadline) -- Merge the results. local diffs_a_len = #diffs_a diffs = diffs_a diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common} for i, b_diff in ipairs(diffs_b) do diffs[diffs_a_len + 1 + i] = b_diff end return diffs end end return _diff_bisect(text1, text2, deadline) end --[[ * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisect(text1, text2, deadline) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 local _sub, _element local max_d = ceil((text1_length + text2_length) / 2) local v_offset = max_d local v_length = 2 * max_d local v1 = {} local v2 = {} -- Setting all elements to -1 is faster in Lua than mixing integers and nil. for x = 0, v_length - 1 do v1[x] = -1 v2[x] = -1 end v1[v_offset + 1] = 0 v2[v_offset + 1] = 0 local delta = text1_length - text2_length -- If the total number of characters is odd, then -- the front path will collide with the reverse path. local front = (delta % 2 ~= 0) -- Offsets for start and end of k loop. -- Prevents mapping of space beyond the grid. local k1start = 0 local k1end = 0 local k2start = 0 local k2end = 0 for d = 0, max_d - 1 do -- Bail out if deadline is reached. if clock() > deadline then break end -- Walk the front path one step. for k1 = -d + k1start, d - k1end, 2 do local k1_offset = v_offset + k1 local x1 if (k1 == -d) or ((k1 ~= d) and (v1[k1_offset - 1] < v1[k1_offset + 1])) then x1 = v1[k1_offset + 1] else x1 = v1[k1_offset - 1] + 1 end local y1 = x1 - k1 while (x1 <= text1_length) and (y1 <= text2_length) and (strelement(text1, x1) == strelement(text2, y1)) do x1 = x1 + 1 y1 = y1 + 1 end v1[k1_offset] = x1 if x1 > text1_length + 1 then -- Ran off the right of the graph. k1end = k1end + 2 elseif y1 > text2_length + 1 then -- Ran off the bottom of the graph. k1start = k1start + 2 elseif front then local k2_offset = v_offset + delta - k1 if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then -- Mirror x2 onto top-left coordinate system. local x2 = text1_length - v2[k2_offset] + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end -- Walk the reverse path one step. for k2 = -d + k2start, d - k2end, 2 do local k2_offset = v_offset + k2 local x2 if (k2 == -d) or ((k2 ~= d) and (v2[k2_offset - 1] < v2[k2_offset + 1])) then x2 = v2[k2_offset + 1] else x2 = v2[k2_offset - 1] + 1 end local y2 = x2 - k2 while (x2 <= text1_length) and (y2 <= text2_length) and (strelement(text1, -x2) == strelement(text2, -y2)) do x2 = x2 + 1 y2 = y2 + 1 end v2[k2_offset] = x2 if x2 > text1_length + 1 then -- Ran off the left of the graph. k2end = k2end + 2 elseif y2 > text2_length + 1 then -- Ran off the top of the graph. k2start = k2start + 2 elseif not front then local k1_offset = v_offset + delta - k2 if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then local x1 = v1[k1_offset] local y1 = v_offset + x1 - k1_offset -- Mirror x2 onto top-left coordinate system. x2 = text1_length - x2 + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end end -- Diff took too long and hit the deadline or -- number of diffs equals number of characters, no commonality at all. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end --[[ * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisectSplit(text1, text2, x, y, deadline) local text1a = strsub(text1, 1, x - 1) local text2a = strsub(text2, 1, y - 1) local text1b = strsub(text1, x) local text2b = strsub(text2, y) -- Compute both diffs serially. local diffs = diff_main(text1a, text2a, false, deadline) local diffsb = diff_main(text1b, text2b, false, deadline) local diffs_len = #diffs for i, v in ipairs(diffsb) do diffs[diffs_len + i] = v end return diffs end --[[ * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. --]] function _diff_commonPrefix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerstart = 1 while (pointermin < pointermid) do if (strsub(text1, pointerstart, pointermid) == strsub(text2, pointerstart, pointermid)) then pointermin = pointermid pointerstart = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. --]] function _diff_commonSuffix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, -1) ~= strbyte(text2, -1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerend = 1 while (pointermin < pointermid) do if (strsub(text1, -pointermid, -pointerend) == strsub(text2, -pointermid, -pointerend)) then pointermin = pointermid pointerend = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private --]] function _diff_commonOverlap(text1, text2) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 -- Eliminate the null case. if text1_length == 0 or text2_length == 0 then return 0 end -- Truncate the longer string. if text1_length > text2_length then text1 = strsub(text1, text1_length - text2_length + 1) elseif text1_length < text2_length then text2 = strsub(text2, 1, text1_length) end local text_length = min(text1_length, text2_length) -- Quick check for the worst case. if text1 == text2 then return text_length end -- Start by looking for a single character match -- and increase length until no match is found. -- Performance analysis: http://neil.fraser.name/news/2010/11/04/ local best = 0 local length = 1 while true do local pattern = strsub(text1, text_length - length + 1) local found = strfind(text2, pattern, 1, true) if found == nil then return best end length = length + found - 1 if found == 1 or strsub(text1, text_length - length + 1) == strsub(text2, 1, length) then best = length length = length + 1 end end end --[[ * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * This speedup can produce non-minimal diffs. * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {?Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatchI(longtext, shorttext, i) -- Start with a 1/4 length substring at position i as a seed. local seed = strsub(longtext, i, i + floor(#longtext / 4)) local j = 0 -- LUANOTE: do not change to 1, was originally -1 local best_common = '' local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b while true do j = indexOf(shorttext, seed, j + 1) if (j == nil) then break end local prefixLength = _diff_commonPrefix(strsub(longtext, i), strsub(shorttext, j)) local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1), strsub(shorttext, 1, j - 1)) if #best_common < suffixLength + prefixLength then best_common = strsub(shorttext, j - suffixLength, j - 1) .. strsub(shorttext, j, j + prefixLength - 1) best_longtext_a = strsub(longtext, 1, i - suffixLength - 1) best_longtext_b = strsub(longtext, i + prefixLength) best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1) best_shorttext_b = strsub(shorttext, j + prefixLength) end end if #best_common * 2 >= #longtext then return {best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common} else return nil end end --[[ * Do the two texts share a substring which is at least half the length of the * longer text? * @param {string} text1 First string. * @param {string} text2 Second string. * @return {?Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatch(text1, text2) if Diff_Timeout <= 0 then -- Don't risk returning a non-optimal diff if we have unlimited time. return nil end local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 if (#longtext < 4) or (#shorttext * 2 < #longtext) then return nil -- Pointless. end -- First check if the second quarter is the seed for a half-match. local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4)) -- Check again based on the third quarter. local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2)) local hm if not hm1 and not hm2 then return nil elseif not hm2 then hm = hm1 elseif not hm1 then hm = hm2 else -- Both matched. Select the longest. hm = (#hm1[5] > #hm2[5]) and hm1 or hm2 end -- A half-match was found, sort out the return data. local text1_a, text1_b, text2_a, text2_b if (#text1 > #text2) then text1_a, text1_b = hm[1], hm[2] text2_a, text2_b = hm[3], hm[4] else text2_a, text2_b = hm[1], hm[2] text1_a, text1_b = hm[3], hm[4] end local mid_common = hm[5] return text1_a, text1_b, text2_a, text2_b, mid_common end --[[ * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private --]] function _diff_cleanupSemanticScore(one, two) if (#one == 0) or (#two == 0) then -- Edges are the best. return 6 end -- Each port of this function behaves slightly differently due to -- subtle differences in each language's definition of things like -- 'whitespace'. Since this function's purpose is largely cosmetic, -- the choice has been made to use each language's native features -- rather than force total conformity. local char1 = strsub(one, -1) local char2 = strsub(two, 1, 1) local nonAlphaNumeric1 = strmatch(char1, '%W') local nonAlphaNumeric2 = strmatch(char2, '%W') local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s') local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s') local lineBreak1 = whitespace1 and strmatch(char1, '%c') local lineBreak2 = whitespace2 and strmatch(char2, '%c') local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$') local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n') if blankLine1 or blankLine2 then -- Five points for blank lines. return 5 elseif lineBreak1 or lineBreak2 then -- Four points for line breaks. return 4 elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then -- Three points for end of sentences. return 3 elseif whitespace1 or whitespace2 then -- Two points for whitespace. return 2 elseif nonAlphaNumeric1 or nonAlphaNumeric2 then -- One point for non-alphanumeric. return 1 end return 0 end --[[ * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupSemanticLossless(diffs) local pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while diffs[pointer + 1] do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local equality1 = prevDiff[2] local edit = diff[2] local equality2 = nextDiff[2] -- First, shift the edit as far left as possible. local commonOffset = _diff_commonSuffix(equality1, edit) if commonOffset > 0 then local commonString = strsub(edit, -commonOffset) equality1 = strsub(equality1, 1, -commonOffset - 1) edit = commonString .. strsub(edit, 1, -commonOffset - 1) equality2 = commonString .. equality2 end -- Second, step character by character right, looking for the best fit. local bestEquality1 = equality1 local bestEdit = edit local bestEquality2 = equality2 local bestScore = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) while strbyte(edit, 1) == strbyte(equality2, 1) do equality1 = equality1 .. strsub(edit, 1, 1) edit = strsub(edit, 2) .. strsub(equality2, 1, 1) equality2 = strsub(equality2, 2) local score = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) -- The >= encourages trailing rather than leading whitespace on edits. if score >= bestScore then bestScore = score bestEquality1 = equality1 bestEdit = edit bestEquality2 = equality2 end end if prevDiff[2] ~= bestEquality1 then -- We have an improvement, save it back to the diff. if #bestEquality1 > 0 then diffs[pointer - 1][2] = bestEquality1 else tremove(diffs, pointer - 1) pointer = pointer - 1 end diffs[pointer][2] = bestEdit if #bestEquality2 > 0 then diffs[pointer + 1][2] = bestEquality2 else tremove(diffs, pointer + 1, 1) pointer = pointer - 1 end end end pointer = pointer + 1 end end --[[ * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupMerge(diffs) diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end. local pointer = 1 local count_delete, count_insert = 0, 0 local text_delete, text_insert = '', '' local commonlength while diffs[pointer] do local diff_type = diffs[pointer][1] if diff_type == DIFF_INSERT then count_insert = count_insert + 1 text_insert = text_insert .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_DELETE then count_delete = count_delete + 1 text_delete = text_delete .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_EQUAL then -- Upon reaching an equality, check for prior redundancies. if count_delete + count_insert > 1 then if (count_delete > 0) and (count_insert > 0) then -- Factor out any common prefixies. commonlength = _diff_commonPrefix(text_insert, text_delete) if commonlength > 0 then local back_pointer = pointer - count_delete - count_insert if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL) then diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2] .. strsub(text_insert, 1, commonlength) else tinsert(diffs, 1, {DIFF_EQUAL, strsub(text_insert, 1, commonlength)}) pointer = pointer + 1 end text_insert = strsub(text_insert, commonlength + 1) text_delete = strsub(text_delete, commonlength + 1) end -- Factor out any common suffixies. commonlength = _diff_commonSuffix(text_insert, text_delete) if commonlength ~= 0 then diffs[pointer][2] = strsub(text_insert, -commonlength) .. diffs[pointer][2] text_insert = strsub(text_insert, 1, -commonlength - 1) text_delete = strsub(text_delete, 1, -commonlength - 1) end end -- Delete the offending records and add the merged ones. if count_delete == 0 then tsplice(diffs, pointer - count_insert, count_insert, {DIFF_INSERT, text_insert}) elseif count_insert == 0 then tsplice(diffs, pointer - count_delete, count_delete, {DIFF_DELETE, text_delete}) else tsplice(diffs, pointer - count_delete - count_insert, count_delete + count_insert, {DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert}) end pointer = pointer - count_delete - count_insert + (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1 elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then -- Merge this equality with the previous one. diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2] tremove(diffs, pointer) else pointer = pointer + 1 end count_insert, count_delete = 0, 0 text_delete, text_insert = '', '' end end if diffs[#diffs][2] == '' then diffs[#diffs] = nil -- Remove the dummy entry at the end. end -- Second pass: look for single edits surrounded on both sides by equalities -- which can be shifted sideways to eliminate an equality. -- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC local changes = false pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while pointer < #diffs do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local currentText = diff[2] local prevText = prevDiff[2] local nextText = nextDiff[2] if strsub(currentText, -#prevText) == prevText then -- Shift the edit over the previous equality. diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1) nextDiff[2] = prevText .. nextDiff[2] tremove(diffs, pointer - 1) changes = true elseif strsub(currentText, 1, #nextText) == nextText then -- Shift the edit over the next equality. prevDiff[2] = prevText .. nextText diff[2] = strsub(currentText, #nextText + 1) .. nextText tremove(diffs, pointer + 1) changes = true end end pointer = pointer + 1 end -- If shifts were made, the diff needs reordering and another shift sweep. if changes then -- LUANOTE: no return value, but necessary to use 'return' to get -- tail calls. return _diff_cleanupMerge(diffs) end end --[[ * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @param {number} loc Location within text1. * @return {number} Location within text2. --]] function _diff_xIndex(diffs, loc) local chars1 = 1 local chars2 = 1 local last_chars1 = 1 local last_chars2 = 1 local x for _x, diff in ipairs(diffs) do x = _x if diff[1] ~= DIFF_INSERT then -- Equality or deletion. chars1 = chars1 + #diff[2] end if diff[1] ~= DIFF_DELETE then -- Equality or insertion. chars2 = chars2 + #diff[2] end if chars1 > loc then -- Overshot the location. break end last_chars1 = chars1 last_chars2 = chars2 end -- Was the location deleted? if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then return last_chars2 end -- Add the remaining character length. return last_chars2 + (loc - last_chars1) end --[[ * Compute and return the source text (all equalities and deletions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Source text. --]] function _diff_text1(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_INSERT then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Compute and return the destination text (all equalities and insertions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Destination text. --]] function _diff_text2(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_DELETE then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Crush the diff into an encoded string which describes the operations * required to transform text1 into text2. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. * Operations are tab-separated. Inserted text is escaped using %xx notation. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Delta text. --]] function _diff_toDelta(diffs) local text = {} for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if op == DIFF_INSERT then text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace) elseif op == DIFF_DELETE then text[x] = '-' .. #data elseif op == DIFF_EQUAL then text[x] = '=' .. #data end end return tconcat(text, '\t') end --[[ * Given the original text1, and an encoded string which describes the * operations required to transform text1 into text2, compute the full diff. * @param {string} text1 Source string for the diff. * @param {string} delta Delta text. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @throws {Errorend If invalid input. --]] function _diff_fromDelta(text1, delta) local diffs = {} local diffsLength = 0 -- Keeping our own length var is faster local pointer = 1 -- Cursor in text1 for token in gmatch(delta, '[^\t]+') do -- Each token begins with a one character parameter which specifies the -- operation of this token (delete, insert, equality). local tokenchar, param = strsub(token, 1, 1), strsub(token, 2) if (tokenchar == '+') then local invalidDecode = false local decoded = gsub(param, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in _diff_fromDelta: ' .. param) end diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_INSERT, decoded} elseif (tokenchar == '-') or (tokenchar == '=') then local n = tonumber(param) if (n == nil) or (n < 0) then error('Invalid number in _diff_fromDelta: ' .. param) end local text = strsub(text1, pointer, pointer + n - 1) pointer = pointer + n if (tokenchar == '=') then diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_EQUAL, text} else diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_DELETE, text} end else error('Invalid diff operation in _diff_fromDelta: ' .. token) end end if (pointer ~= #text1 + 1) then error('Delta length (' .. (pointer - 1) .. ') does not equal source text length (' .. #text1 .. ').') end return diffs end -- --------------------------------------------------------------------------- -- MATCH API -- --------------------------------------------------------------------------- local _match_bitap, _match_alphabet --[[ * Locate the best instance of 'pattern' in 'text' near 'loc'. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. --]] function match_main(text, pattern, loc) -- Check for null inputs. if text == nil or pattern == nil or loc == nil then error('Null inputs. (match_main)') end if text == pattern then -- Shortcut (potentially not guaranteed by the algorithm) return 1 elseif #text == 0 then -- Nothing to match. return -1 end loc = max(1, min(loc, #text)) if strsub(text, loc, loc + #pattern - 1) == pattern then -- Perfect match at the perfect spot! (Includes case of null pattern) return loc else -- Do a fuzzy compare. return _match_bitap(text, pattern, loc) end end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE MATCH FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Initialise the alphabet for the Bitap algorithm. * @param {string} pattern The text to encode. * @return {Object} Hash of character locations. * @private --]] function _match_alphabet(pattern) local s = {} local i = 0 for c in gmatch(pattern, '.') do s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1)) i = i + 1 end return s end --[[ * Locate the best instance of 'pattern' in 'text' near 'loc' using the * Bitap algorithm. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. * @private --]] function _match_bitap(text, pattern, loc) if #pattern > Match_MaxBits then error('Pattern too long.') end -- Initialise the alphabet. local s = _match_alphabet(pattern) --[[ * Compute and return the score for a match with e errors and x location. * Accesses loc and pattern through being a closure. * @param {number} e Number of errors in match. * @param {number} x Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private --]] local function _match_bitapScore(e, x) local accuracy = e / #pattern local proximity = abs(loc - x) if (Match_Distance == 0) then -- Dodge divide by zero error. return (proximity == 0) and 1 or accuracy end return accuracy + (proximity / Match_Distance) end -- Highest score beyond which we give up. local score_threshold = Match_Threshold -- Is there a nearby exact match? (speedup) local best_loc = indexOf(text, pattern, loc) if best_loc then score_threshold = min(_match_bitapScore(0, best_loc), score_threshold) -- LUANOTE: Ideally we'd also check from the other direction, but Lua -- doesn't have an efficent lastIndexOf function. end -- Initialise the bit arrays. local matchmask = lshift(1, #pattern - 1) best_loc = -1 local bin_min, bin_mid local bin_max = #pattern + #text local last_rd for d = 0, #pattern - 1, 1 do -- Scan for the best match; each iteration allows for one more error. -- Run a binary search to determine how far from 'loc' we can stray at this -- error level. bin_min = 0 bin_mid = bin_max while (bin_min < bin_mid) do if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then bin_min = bin_mid else bin_max = bin_mid end bin_mid = floor(bin_min + (bin_max - bin_min) / 2) end -- Use the result from this iteration as the maximum for the next. bin_max = bin_mid local start = max(1, loc - bin_mid + 1) local finish = min(loc + bin_mid, #text) + #pattern local rd = {} for j = start, finish do rd[j] = 0 end rd[finish + 1] = lshift(1, d) - 1 for j = finish, start, -1 do local charMatch = s[strsub(text, j - 1, j - 1)] or 0 if (d == 0) then -- First pass: exact match. rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch) else -- Subsequent passes: fuzzy match. -- Functions instead of operators make this hella messy. rd[j] = bor( band( bor( lshift(rd[j + 1], 1), 1 ), charMatch ), bor( bor( lshift(bor(last_rd[j + 1], last_rd[j]), 1), 1 ), last_rd[j + 1] ) ) end if (band(rd[j], matchmask) ~= 0) then local score = _match_bitapScore(d, j - 1) -- This match will almost certainly be better than any existing match. -- But check anyway. if (score <= score_threshold) then -- Told you so. score_threshold = score best_loc = j - 1 if (best_loc > loc) then -- When passing loc, don't exceed our current distance from loc. start = max(1, loc * 2 - best_loc) else -- Already passed loc, downhill from here on in. break end end end end -- No hope for a (better) match at greater error levels. if (_match_bitapScore(d + 1, loc) > score_threshold) then break end last_rd = rd end return best_loc end -- ----------------------------------------------------------------------------- -- PATCH API -- ----------------------------------------------------------------------------- local _patch_addContext, _patch_deepCopy, _patch_addPadding, _patch_splitMax, _patch_appendText, _new_patch_obj --[[ * Compute a list of patches to turn text1 into text2. * Use diffs if provided, otherwise compute it ourselves. * There are four ways to call this function, depending on what data is * available to the caller: * Method 1: * a = text1, b = text2 * Method 2: * a = diffs * Method 3 (optimal): * a = text1, b = diffs * Method 4 (deprecated, use method 3): * a = text1, b = text2, c = diffs * * @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or * Array of diff tuples for text1 to text2 (method 2). * @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). * @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for * text1 to text2 (method 4) or undefined (methods 1,2,3). * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function patch_make(a, opt_b, opt_c) local text1, diffs local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c) if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then -- Method 1: text1, text2 -- Compute diffs from text1 and text2. text1 = a diffs = diff_main(text1, opt_b, true) if (#diffs > 2) then diff_cleanupSemantic(diffs) diff_cleanupEfficiency(diffs) end elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then -- Method 2: diffs -- Compute text1 from diffs. diffs = a text1 = _diff_text1(diffs) elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then -- Method 3: text1, diffs text1 = a diffs = opt_b elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table') then -- Method 4: text1, text2, diffs -- text2 is not used. text1 = a diffs = opt_c else error('Unknown call format to patch_make.') end if (diffs[1] == nil) then return {} -- Get rid of the null case. end local patches = {} local patch = _new_patch_obj() local patchDiffLength = 0 -- Keeping our own length var is faster. local char_count1 = 0 -- Number of characters into the text1 string. local char_count2 = 0 -- Number of characters into the text2 string. -- Start with text1 (prepatch_text) and apply the diffs until we arrive at -- text2 (postpatch_text). We recreate the patches one by one to determine -- context info. local prepatch_text, postpatch_text = text1, text1 for x, diff in ipairs(diffs) do local diff_type, diff_text = diff[1], diff[2] if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then -- A new patch starts here. patch.start1 = char_count1 + 1 patch.start2 = char_count2 + 1 end if (diff_type == DIFF_INSERT) then patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length2 = patch.length2 + #diff_text postpatch_text = strsub(postpatch_text, 1, char_count2) .. diff_text .. strsub(postpatch_text, char_count2 + 1) elseif (diff_type == DIFF_DELETE) then patch.length1 = patch.length1 + #diff_text patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff postpatch_text = strsub(postpatch_text, 1, char_count2) .. strsub(postpatch_text, char_count2 + #diff_text + 1) elseif (diff_type == DIFF_EQUAL) then if (#diff_text <= Patch_Margin * 2) and (patchDiffLength ~= 0) and (#diffs ~= x) then -- Small equality inside a patch. patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length1 = patch.length1 + #diff_text patch.length2 = patch.length2 + #diff_text elseif (#diff_text >= Patch_Margin * 2) then -- Time for a new patch. if (patchDiffLength ~= 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch patch = _new_patch_obj() patchDiffLength = 0 -- Unlike Unidiff, our patch lists have a rolling context. -- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff -- Update prepatch text & pos to reflect the application of the -- just completed patch. prepatch_text = postpatch_text char_count1 = char_count2 end end end -- Update the current character count. if (diff_type ~= DIFF_INSERT) then char_count1 = char_count1 + #diff_text end if (diff_type ~= DIFF_DELETE) then char_count2 = char_count2 + #diff_text end end -- Pick up the leftover patch if not empty. if (patchDiffLength > 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch end return patches end --[[ * Merge a set of patches onto the text. Return a patched text, as well * as a list of true/false values indicating which patches were applied. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @param {string} text Old text. * @return {Array.<string|Array.<boolean>>} Two return values, the * new text and an array of boolean values. --]] function patch_apply(patches, text) if patches[1] == nil then return text, {} end -- Deep copy the patches so that no changes are made to originals. patches = _patch_deepCopy(patches) local nullPadding = _patch_addPadding(patches) text = nullPadding .. text .. nullPadding _patch_splitMax(patches) -- delta keeps track of the offset between the expected and actual location -- of the previous patch. If there are patches expected at positions 10 and -- 20, but the first patch was found at 12, delta is 2 and the second patch -- has an effective expected position of 22. local delta = 0 local results = {} for x, patch in ipairs(patches) do local expected_loc = patch.start2 + delta local text1 = _diff_text1(patch.diffs) local start_loc local end_loc = -1 if #text1 > Match_MaxBits then -- _patch_splitMax will only provide an oversized pattern in -- the case of a monster delete. start_loc = match_main(text, strsub(text1, 1, Match_MaxBits), expected_loc) if start_loc ~= -1 then end_loc = match_main(text, strsub(text1, -Match_MaxBits), expected_loc + #text1 - Match_MaxBits) if end_loc == -1 or start_loc >= end_loc then -- Can't find valid trailing context. Drop this patch. start_loc = -1 end end else start_loc = match_main(text, text1, expected_loc) end if start_loc == -1 then -- No match found. :( results[x] = false -- Subtract the delta for this failed patch from subsequent patches. delta = delta - patch.length2 - patch.length1 else -- Found a match. :) results[x] = true delta = start_loc - expected_loc local text2 if end_loc == -1 then text2 = strsub(text, start_loc, start_loc + #text1 - 1) else text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1) end if text1 == text2 then -- Perfect match, just shove the replacement text in. text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs) .. strsub(text, start_loc + #text1) else -- Imperfect match. Run a diff to get a framework of equivalent -- indices. local diffs = diff_main(text1, text2, false) if (#text1 > Match_MaxBits) and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then -- The end points match, but the content is unacceptably bad. results[x] = false else _diff_cleanupSemanticLossless(diffs) local index1 = 1 local index2 for y, mod in ipairs(patch.diffs) do if mod[1] ~= DIFF_EQUAL then index2 = _diff_xIndex(diffs, index1) end if mod[1] == DIFF_INSERT then text = strsub(text, 1, start_loc + index2 - 2) .. mod[2] .. strsub(text, start_loc + index2 - 1) elseif mod[1] == DIFF_DELETE then text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text, start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1)) end if mod[1] ~= DIFF_DELETE then index1 = index1 + #mod[2] end end end end end end -- Strip the padding off. text = strsub(text, #nullPadding + 1, -#nullPadding - 1) return text, results end --[[ * Take a list of patches and return a textual representation. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} Text representation of patches. --]] function patch_toText(patches) local text = {} for x, patch in ipairs(patches) do _patch_appendText(patch, text) end return tconcat(text) end --[[ * Parse a textual representation of patches and return a list of patch objects. * @param {string} textline Text representation of patches. * @return {Array.<_new_patch_obj>} Array of patch objects. * @throws {Error} If invalid input. --]] function patch_fromText(textline) local patches = {} if (#textline == 0) then return patches end local text = {} for line in gmatch(textline, '([^\n]*)') do text[#text + 1] = line end local textPointer = 1 while (textPointer <= #text) do local start1, length1, start2, length2 = strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$') if (start1 == nil) then error('Invalid patch string: "' .. text[textPointer] .. '"') end local patch = _new_patch_obj() patches[#patches + 1] = patch start1 = tonumber(start1) length1 = tonumber(length1) or 1 if (length1 == 0) then start1 = start1 + 1 end patch.start1 = start1 patch.length1 = length1 start2 = tonumber(start2) length2 = tonumber(length2) or 1 if (length2 == 0) then start2 = start2 + 1 end patch.start2 = start2 patch.length2 = length2 textPointer = textPointer + 1 while true do local line = text[textPointer] if (line == nil) then break end local sign; sign, line = strsub(line, 1, 1), strsub(line, 2) local invalidDecode = false local decoded = gsub(line, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in patch_fromText: ' .. line) end line = decoded if (sign == '-') then -- Deletion. patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line} elseif (sign == '+') then -- Insertion. patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line} elseif (sign == ' ') then -- Minor equality. patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line} elseif (sign == '@') then -- Start of next patch. break elseif (sign == '') then -- Blank line? Whatever. else -- WTF? error('Invalid patch mode "' .. sign .. '" in: ' .. line) end textPointer = textPointer + 1 end end return patches end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE PATCH FUNCTIONS -- --------------------------------------------------------------------------- local patch_meta = { __tostring = function(patch) local buf = {} _patch_appendText(patch, buf) return tconcat(buf) end } --[[ * Class representing one patch operation. * @constructor --]] function _new_patch_obj() return setmetatable({ --[[ @type {Array.<Array.<number|string>>} ]] diffs = {}; --[[ @type {?number} ]] start1 = 1; -- nil; --[[ @type {?number} ]] start2 = 1; -- nil; --[[ @type {number} ]] length1 = 0; --[[ @type {number} ]] length2 = 0; }, patch_meta) end --[[ * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. * @param {_new_patch_obj} patch The patch to grow. * @param {string} text Source text. * @private --]] function _patch_addContext(patch, text) if (#text == 0) then return end local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1) local padding = 0 -- LUANOTE: Lua's lack of a lastIndexOf function results in slightly -- different logic here than in other language ports. -- Look for the first two matches of pattern in text. If two are found, -- increase the pattern length. local firstMatch = indexOf(text, pattern) local secondMatch = nil if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) end while (#pattern == 0 or secondMatch ~= nil) and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do padding = padding + Patch_Margin pattern = strsub(text, max(1, patch.start2 - padding), patch.start2 + patch.length1 - 1 + padding) firstMatch = indexOf(text, pattern) if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) else secondMatch = nil end end -- Add one chunk for good luck. padding = padding + Patch_Margin -- Add the prefix. local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1) if (#prefix > 0) then tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix}) end -- Add the suffix. local suffix = strsub(text, patch.start2 + patch.length1, patch.start2 + patch.length1 - 1 + padding) if (#suffix > 0) then patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix} end -- Roll back the start points. patch.start1 = patch.start1 - #prefix patch.start2 = patch.start2 - #prefix -- Extend the lengths. patch.length1 = patch.length1 + #prefix + #suffix patch.length2 = patch.length2 + #prefix + #suffix end --[[ * Given an array of patches, return another array that is identical. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function _patch_deepCopy(patches) local patchesCopy = {} for x, patch in ipairs(patches) do local patchCopy = _new_patch_obj() local diffsCopy = {} for i, diff in ipairs(patch.diffs) do diffsCopy[i] = {diff[1], diff[2]} end patchCopy.diffs = diffsCopy patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length1 = patch.length1 patchCopy.length2 = patch.length2 patchesCopy[x] = patchCopy end return patchesCopy end --[[ * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} The padding string added to each side. --]] function _patch_addPadding(patches) local paddingLength = Patch_Margin local nullPadding = '' for x = 1, paddingLength do nullPadding = nullPadding .. strchar(x) end -- Bump all the patches forward. for x, patch in ipairs(patches) do patch.start1 = patch.start1 + paddingLength patch.start2 = patch.start2 + paddingLength end -- Add some padding on start of first diff. local patch = patches[1] local diffs = patch.diffs local firstDiff = diffs[1] if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. tinsert(diffs, 1, {DIFF_EQUAL, nullPadding}) patch.start1 = patch.start1 - paddingLength -- Should be 0. patch.start2 = patch.start2 - paddingLength -- Should be 0. patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #firstDiff[2]) then -- Grow first equality. local extraLength = paddingLength - #firstDiff[2] firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2] patch.start1 = patch.start1 - extraLength patch.start2 = patch.start2 - extraLength patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end -- Add some padding on end of last diff. patch = patches[#patches] diffs = patch.diffs local lastDiff = diffs[#diffs] if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding} patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #lastDiff[2]) then -- Grow last equality. local extraLength = paddingLength - #lastDiff[2] lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength) patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end return nullPadding end --[[ * Look through the patches and break up any which are longer than the maximum * limit of the match algorithm. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. --]] function _patch_splitMax(patches) local patch_size = Match_MaxBits local x = 1 while true do local patch = patches[x] if patch == nil then return end if patch.length1 > patch_size then local bigpatch = patch -- Remove the big old patch. tremove(patches, x) x = x - 1 local start1 = bigpatch.start1 local start2 = bigpatch.start2 local precontext = '' while bigpatch.diffs[1] do -- Create one of several smaller patches. local patch = _new_patch_obj() local empty = true patch.start1 = start1 - #precontext patch.start2 = start2 - #precontext if precontext ~= '' then patch.length1, patch.length2 = #precontext, #precontext patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext} end while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do local diff_type = bigpatch.diffs[1][1] local diff_text = bigpatch.diffs[1][2] if (diff_type == DIFF_INSERT) then -- Insertions are harmless. patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1] tremove(bigpatch.diffs, 1) empty = false elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1) and (patch.diffs[1][1] == DIFF_EQUAL) and (#diff_text > 2 * patch_size) then -- This is a large deletion. Let it pass in one chunk. patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text empty = false patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} tremove(bigpatch.diffs, 1) else -- Deletion or equality. -- Only take as much as we can stomach. diff_text = strsub(diff_text, 1, patch_size - patch.length1 - Patch_Margin) patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text if (diff_type == DIFF_EQUAL) then patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text else empty = false end patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} if (diff_text == bigpatch.diffs[1][2]) then tremove(bigpatch.diffs, 1) else bigpatch.diffs[1][2] = strsub(bigpatch.diffs[1][2], #diff_text + 1) end end end -- Compute the head context for the next patch. precontext = _diff_text2(patch.diffs) precontext = strsub(precontext, -Patch_Margin) -- Append the end context for this patch. local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin) if postcontext ~= '' then patch.length1 = patch.length1 + #postcontext patch.length2 = patch.length2 + #postcontext if patch.diffs[1] and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2] .. postcontext else patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext} end end if not empty then x = x + 1 tinsert(patches, x, patch) end end end x = x + 1 end end --[[ * Emulate GNU diff's format. * Header: @@ -382,8 +481,9 @@ * @return {string} The GNU diff string. --]] function _patch_appendText(patch, text) local coords1, coords2 local length1, length2 = patch.length1, patch.length2 local start1, start2 = patch.start1, patch.start2 local diffs = patch.diffs if length1 == 1 then coords1 = start1 else coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1 end if length2 == 1 then coords2 = start2 else coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2 end text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n' local op -- Escape the body of the patch with %xx notation. for x, diff in ipairs(patch.diffs) do local diff_type = diff[1] if diff_type == DIFF_INSERT then op = '+' elseif diff_type == DIFF_DELETE then op = '-' elseif diff_type == DIFF_EQUAL then op = ' ' end text[#text + 1] = op .. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace) .. '\n' end return text end -- Expose the API local _M = {} _M.DIFF_DELETE = DIFF_DELETE _M.DIFF_INSERT = DIFF_INSERT _M.DIFF_EQUAL = DIFF_EQUAL _M.diff_main = diff_main _M.diff_cleanupSemantic = diff_cleanupSemantic _M.diff_cleanupEfficiency = diff_cleanupEfficiency _M.diff_levenshtein = diff_levenshtein _M.diff_prettyHtml = diff_prettyHtml _M.match_main = match_main _M.patch_make = patch_make _M.patch_toText = patch_toText _M.patch_fromText = patch_fromText _M.patch_apply = patch_apply -- Expose some non-API functions as well, for testing purposes etc. _M.diff_commonPrefix = _diff_commonPrefix _M.diff_commonSuffix = _diff_commonSuffix _M.diff_commonOverlap = _diff_commonOverlap _M.diff_halfMatch = _diff_halfMatch _M.diff_bisect = _diff_bisect _M.diff_cleanupMerge = _diff_cleanupMerge _M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless _M.diff_text1 = _diff_text1 _M.diff_text2 = _diff_text2 _M.diff_toDelta = _diff_toDelta _M.diff_fromDelta = _diff_fromDelta _M.diff_xIndex = _diff_xIndex _M.match_alphabet = _match_alphabet _M.match_bitap = _match_bitap _M.new_patch_obj = _new_patch_obj _M.patch_addContext = _patch_addContext _M.patch_splitMax = _patch_splitMax _M.patch_addPadding = _patch_addPadding _M.settings = settings return _M
apache-2.0
bnetcc/darkstar
scripts/zones/Castle_Oztroja/npcs/_m75.lua
5
1990
----------------------------------- -- Area: Castle Oztroja -- NPC: _m75 (Torch Stand) -- Notes: Opens door _477 when _m72 to _m75 are lit -- !pos -139.643 -72.113 -62.682 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- function onTrigger(player,npc) DoorID = npc:getID() - 5; Torch1 = npc:getID() - 3; Torch2 = npc:getID() - 2; Torch3 = npc:getID() - 1; Torch4 = npc:getID(); DoorA = GetNPCByID(DoorID):getAnimation(); TorchStand1A = GetNPCByID(Torch1):getAnimation(); TorchStand2A = GetNPCByID(Torch2):getAnimation(); TorchStand3A = GetNPCByID(Torch3):getAnimation(); TorchStand4A = npc:getAnimation(); if (DoorA == 9 and TorchStand4A == 9) then player:startEvent(10); else player:messageSpecial(TORCH_LIT); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (option == 1) then GetNPCByID(Torch4):openDoor(55); if ((DoorA == 9)) then GetNPCByID(DoorID):openDoor(35); -- The lamps shouldn't go off here, but I couldn't get the torches to update animation times without turning them off first -- They need to be reset to the door open time(35s) + 4s (39 seconds) GetNPCByID(Torch1):setAnimation(9); GetNPCByID(Torch2):setAnimation(9); GetNPCByID(Torch3):setAnimation(9); GetNPCByID(Torch4):setAnimation(9); GetNPCByID(Torch1):openDoor(39); GetNPCByID(Torch2):openDoor(39); GetNPCByID(Torch3):openDoor(39); GetNPCByID(Torch4):openDoor(39); end end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Western_Adoulin/npcs/Bilp.lua
7
1605
----------------------------------- -- Area: Western Adoulin -- NPC: Bilp -- Type: Standard NPC and Quest NPC -- Starts and Involved with Quest: 'Scaredy-Cats' -- @zone 256 -- !pos -91 3 0 256 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local Scaredycats = player:getQuestStatus(ADOULIN, SCAREDYCATS); local Scaredycats_Status = player:getVar("Scaredycats_Status"); if ((Scaredycats_Status < 1) and (Scaredycats == QUEST_AVAILABLE)) then -- Dialogue before seeing the initial walk-in CS with Bilp, Eamonn, and Lhe. player:startEvent(5031); elseif (Scaredycats_Status == 1) then if (Scaredycats == QUEST_ACCEPTED) then -- Reminder for Quest: 'Scaredy-Cats', go to Ceizak Battlegrounds player:startEvent(5025); else -- Starts Quest: 'Scaredy-Cats', after first refusal. player:startEvent(5024); end elseif (Scaredycats_Status == 2) then -- Reminder for Quest: 'Scaredy-Cats', go to Sih Gates. player:startEvent(5026); else -- Dialogue after completeing Quest: 'Scaredy-Cats' player:startEvent(5029); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if ((csid == 5024) and (option == 1)) then -- Starts Quest: 'Scaredy-Cats', after first refusal. player:setVar("Scaredycats_Status", 2); player:addQuest(ADOULIN, SCAREDYCATS); end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Port_Windurst/npcs/Explorer_Moogle.lua
5
1376
----------------------------------- -- Area: Port Windurst -- NPC: Explorer Moogle -- Working 100% ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) accept = 0; event = 854; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = 300; if (csid == 854) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/weaponskills/double_thrust.lua
26
1348
----------------------------------- -- Double Thrust -- Polearm weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget. -- Aligned with the Light Belt. -- Element: None -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.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 = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Abyssea-Tahrongi/mobs/Iratham.lua
1
2137
----------------------------------- -- Area: Abyssea - Tahrongi (45) -- Mob: Iratham ----------------------------------- package.loaded["scripts/zones/Abyssea-Tahrongi/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Abyssea-Tahrongi/TextIDs"); require("scripts/globals/abyssea"); require("scripts/globals/keyitems"); require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- function onMobInitialize(mob) end; function onMobSpawn(mob) mob:addMod(MOD_ATT,90); mob:addMod(MOD_ACC,100); mob:addMod(MOD_MACC,300); mob:addMod(MOD_REGEN,90); mob:addMod(MOD_REGAIN,20); end; function onMobEngaged(mob,target) end; function onMobFight(mob,target) if (mob:getHPP() < 20) then mob:setMobMod(MOBMOD_SPELL_LIST, 155); elseif (mob:getHPP() < 50) then mob:setMobMod(MOBMOD_SPELL_LIST, 154); else -- I'm assuming that if it heals up, it goes back to the its original spell list. mob:setMobMod(MOBMOD_SPELL_LIST, 153); -- This 'else' can be removed if that isn't the case, and a localVar added so it only execs once. end end; function onMobDeath(mob, player, isKiller) player:addTitle(IRATHAM_CAPTURER); if (isKiller == true) then local itemRate = math.random(1,100); local lootTable = { [1] = 20546, -- Ninzas +1 [2] = 20634, -- Leisilonu +1 [3] = 20961, -- Qatsunoci +1 [4] = 21051, -- Shichishito +1 [5] = 21286 -- Hgafircian +1 } if (itemRate >= 50) then -- First drop is 50 in 100. player:addTreasure(lootTable[math.random(1,5)], mob); end if (itemRate >= 90) then -- You lucky high roller, 2nd drop is only 10 in 100 player:addTreasure(lootTable[math.random(1,5)], mob); end end local CHANCE = 15; if (math.random(0,99) < CHANCE and player:hasKeyItem(ATMA_OF_THE_COSMOS) == false) then player:addKeyItem(ATMA_OF_THE_COSMOS); player:messageSpecial(KEYITEM_OBTAINED, ATMA_OF_THE_COSMOS); end end;
gpl-3.0
TurkeyMan/premake-core
tests/project/test_location.lua
32
1123
-- -- tests/project/test_location.lua -- Test handling of the projects's location field. -- Copyright (c) 2013 Jason Perkins and the Premake project -- local suite = test.declare("project_location") -- -- Setup and teardown -- local wks, prj function suite.setup() wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks, 1) end -- -- If no explicit location is set, the location should be set to the -- directory containing the script which defined the project. -- function suite.usesScriptLocation_onNoLocation() prepare() test.isequal(os.getcwd(), prj.location) end -- -- If an explicit location has been set, use it. -- function suite.usesLocation_onLocationSet() location "build" prepare() test.isequal(path.join(os.getcwd(), "build"), prj.location) end -- -- If the workspace sets a location, and the project does not, it should -- inherit the value from the workspace. -- function suite.inheritsWorkspaceLocation_onNoProjectLocation() workspace () location "build" prepare() test.isequal(path.join(os.getcwd(), "build"), prj.location) end
bsd-3-clause
bnetcc/darkstar
scripts/globals/weaponskills/tachi_kasha.lua
3
1971
----------------------------------- -- Tachi Kasha -- Great Katana weapon skill -- Skill Level: 250 -- Paralyzes target. Damage varies with TP. -- Paralyze effect duration is 60 seconds when unresisted. -- In order to obtain Tachi: Kasha, the quest The Potential Within must be completed. -- Will stack with Sneak Attack. -- Tachi: Kasha appears to have a moderate attack bonus of +50%. [1] -- Aligned with the Flame Gorget, Light Gorget & Shadow Gorget. -- Aligned with the Flame Belt, Light Belt & Shadow Belt. -- Element: None -- Modifiers: STR:75% -- 100%TP 200%TP 300%TP -- 1.5625 2.6875 4.125 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1.56; params.ftp200 = 1.88; params.ftp300 = 2.5; params.str_wsc = 0.75; 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.5; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.5625; params.ftp200 = 2.6875; params.ftp300 = 4.125; params.str_wsc = 0.75; params.atkmulti = 1.65 end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_PARALYSIS) == false) then local duration = 60 * applyResistanceAddEffect(player,target,ELE_ICE,0); target:addStatusEffect(EFFECT_PARALYSIS, 25, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Qulun_Dome/mobs/Diamond_Quadav.lua
5
1741
----------------------------------- -- Area: Qulun_Dome -- NM: Diamond_Quadav -- Note: PH for Za Dha Adamantking PH ----------------------------------- package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil; ----------------------------------- mixins = {require("scripts/mixins/job_special")}; require("scripts/zones/Qulun_Dome/TextIDs"); require("scripts/zones/Qulun_Dome/MobIDs"); require("scripts/globals/status"); ----------------------------------- function onMobInitialize(mob) -- the quest version of this NM doesn't drop gil if (mob:getID() >= AFFABLE_ADAMANTKING_OFFSET) then mob:setMobMod(MOBMOD_GIL_MAX, -1); end end; function onMobSpawn(mob) end; function onMobEngaged(mob,target) mob:showText(mob,DIAMOND_QUADAV_ENGAGE); end; function onMobDeath(mob, player, isKiller) if (isKiller) then mob:showText(mob,DIAMOND_QUADAV_DEATH); end end; function onMobDespawn(mob) local nqId = mob:getID(); -- the quest version of this NM doesn't respawn or count toward hq nm if (nqId == DIAMOND_QUADAV) then local hqId = mob:getID() + 1; local ToD = GetServerVariable("[POP]Za_Dha_Adamantking"); local kills = GetServerVariable("[PH]Za_Dha_Adamantking"); local popNow = (math.random(1,5) == 3 or kills > 6); if (os.time() > ToD and popNow) then DisallowRespawn(nqId, true); DisallowRespawn(hqId, false); UpdateNMSpawnPoint(hqId); GetMobByID(hqId):setRespawnTime(math.random(75600,86400)); else UpdateNMSpawnPoint(nqId); mob:setRespawnTime(math.random(75600,86400)); SetServerVariable("[PH]Za_Dha_Adamantking", kills + 1); end end end;
gpl-3.0
mwoz123/koreader
frontend/document/documentregistry.lua
1
7904
--[[-- This is a registry for document providers ]]-- local logger = require("logger") local lfs = require("libs/libkoreader-lfs") local util = require("util") local DocumentRegistry = { registry = {}, providers = {}, filetype_provider = {}, mimetype_ext = {}, } function DocumentRegistry:addProvider(extension, mimetype, provider, weight) extension = string.lower(extension) table.insert(self.providers, { extension = extension, mimetype = mimetype, provider = provider, weight = weight or 100, }) self.filetype_provider[extension] = true -- We regard the first extension registered for a mimetype as canonical. -- Provided we order the calls to addProvider() correctly, that means -- epub instead of epub3, etc. self.mimetype_ext[mimetype] = self.mimetype_ext[mimetype] or extension end function DocumentRegistry:getRandomFile(dir, opened, extension) local DocSettings = require("docsettings") if string.sub(dir, string.len(dir)) ~= "/" then dir = dir .. "/" end local files = {} local i = 0 local ok, iter, dir_obj = pcall(lfs.dir, dir) if ok then for entry in iter, dir_obj do if lfs.attributes(dir .. entry, "mode") == "file" and self:hasProvider(dir .. entry) and (opened == nil or DocSettings:hasSidecarFile(dir .. entry) == opened) and (extension == nil or extension[util.getFileNameSuffix(entry)]) then i = i + 1 files[i] = entry end end if i == 0 then return nil end else return nil end math.randomseed(os.time()) return dir .. files[math.random(i)] end --- Returns true if file has provider. -- @string file -- @treturn boolean function DocumentRegistry:hasProvider(file, mimetype) if mimetype and self.mimetype_ext[mimetype] then return true end if not file then return false end local filename_suffix = string.lower(util.getFileNameSuffix(file)) local filetype_provider = G_reader_settings:readSetting("provider") or {} if self.filetype_provider[filename_suffix] or filetype_provider[filename_suffix] then return true end local DocSettings = require("docsettings") if DocSettings:hasSidecarFile(file) then return DocSettings:open(file):has("provider") end return false end --- Returns the preferred registered document handler. -- @string file -- @treturn table provider, or nil function DocumentRegistry:getProvider(file) local providers = self:getProviders(file) if providers then -- provider for document local DocSettings = require("docsettings") if DocSettings:hasSidecarFile(file) then local doc_settings_provider = DocSettings:open(file):readSetting("provider") if doc_settings_provider then for _, provider in ipairs(providers) do if provider.provider.provider == doc_settings_provider then return provider.provider end end end end -- global provider for filetype local filename_suffix = util.getFileNameSuffix(file) local g_settings_provider = G_reader_settings:readSetting("provider") if g_settings_provider and g_settings_provider[filename_suffix] then for _, provider in ipairs(providers) do if provider.provider.provider == g_settings_provider[filename_suffix] then return provider.provider end end end -- highest weighted provider return providers[1].provider else for _, provider in ipairs(self.providers) do if provider.extension == "txt" then return provider.provider end end end end --- Returns the registered document handlers. -- @string file -- @treturn table providers, or nil function DocumentRegistry:getProviders(file) local providers = {} --- @todo some implementation based on mime types? for _, provider in ipairs(self.providers) do local added = false local suffix = string.sub(file, -string.len(provider.extension) - 1) if string.lower(suffix) == "."..provider.extension then for i = #providers, 1, -1 do local prov_prev = providers[i] if prov_prev.provider == provider.provider then if prov_prev.weight >= provider.weight then added = true else table.remove(providers, i) end end end -- if extension == provider.extension then -- stick highest weighted provider at the front if not added and #providers >= 1 and provider.weight > providers[1].weight then table.insert(providers, 1, provider) elseif not added then table.insert(providers, provider) end end end if #providers >= 1 then return providers end end --- Get mapping of file extensions to providers -- @treturn table mapping file extensions to a list of providers function DocumentRegistry:getExtensions() local t = {} for _, provider in ipairs(self.providers) do local ext = provider.extension t[ext] = t[ext] or {} table.insert(t[ext], provider) end return t end --- Sets the preferred registered document handler. -- @string file -- @bool all function DocumentRegistry:setProvider(file, provider, all) local _, filename_suffix = util.splitFileNameSuffix(file) -- per-document if not all then local DocSettings = require("docsettings"):open(file) DocSettings:saveSetting("provider", provider.provider) DocSettings:flush() -- global else local filetype_provider = G_reader_settings:readSetting("provider") or {} filetype_provider[filename_suffix] = provider.provider G_reader_settings:saveSetting("provider", filetype_provider) end end function DocumentRegistry:mimeToExt(mimetype) return self.mimetype_ext[mimetype] end function DocumentRegistry:openDocument(file, provider) -- force a GC, so that any previous document used memory can be reused -- immediately by this new document without having to wait for the -- next regular gc. The second call may help reclaming more memory. collectgarbage() collectgarbage() if not self.registry[file] then provider = provider or self:getProvider(file) if provider ~= nil then local ok, doc = pcall(provider.new, provider, {file = file}) if ok then self.registry[file] = { doc = doc, refs = 1, } else logger.warn("cannot open document", file, doc) end end else self.registry[file].refs = self.registry[file].refs + 1 end if self.registry[file] then return self.registry[file].doc end end function DocumentRegistry:closeDocument(file) if self.registry[file] then self.registry[file].refs = self.registry[file].refs - 1 if self.registry[file].refs == 0 then self.registry[file] = nil return 0 else return self.registry[file].refs end else error("Try to close unregistered file.") end end -- load implementations: require("document/credocument"):register(DocumentRegistry) require("document/pdfdocument"):register(DocumentRegistry) require("document/djvudocument"):register(DocumentRegistry) require("document/picdocument"):register(DocumentRegistry) return DocumentRegistry
agpl-3.0
bnetcc/darkstar
scripts/zones/Aht_Urhgan_Whitegate/Shared.lua
5
5550
----------------------------------- -- Tables and Functions Used at Multiple Places within Aht Urgan Whitegate ----------------------------------- require("scripts/globals/settings"); -- Lua Set Initializer http://www.lua.org/pil/11.5.html function Set (list) local set = {} for _, l in ipairs(list) do set[l] = true end return set end -- Set of Royal Palace Approved Armor ROYAL_PALACE_ALLOWED_BODY_ARMORS = Set{ 12548, -- Adaman Cuirass Lv. 73 WAR / PLD 13746, -- Gem Cuirass Lv. 73 WAR / PLD 13742, -- Aketon Lv. 60 MNK / WHM / RDM / THF / PLD / BST / BRD / DRG / SMN / BLU / COR / PUP / DNC 13743, -- Aketon +1 Lv. 60 MNK / WHM / RDM / THF / PLD / BST / BRD / DRG / SMN / BLU / COR / PUP / DNC 14525, -- Amir Korazin Lv. 72 WAR / PLD / DRK / SAM /DRG 13795, -- Arhat's Gi Lv. 64 MNK / SAM / NIN 13802, -- Arhat's Gi +1 Lv. 64 MNK / SAM / NIN 14416, -- Barone Corazza Lv. 70 WAR / DRG 14417, -- Conte Corazza Lv. 70 WAR / DRG 13779, -- Black Cloak Lv. 68 BLM 13780, -- Demon's Cloak Lv. 68 BLM 13754, -- Black Cotehardie Lv. 59 MNK / WHM / BLM / RDM / THF / BST / BRD / RNG / NIN / SMN / BLU / PUP / DNC / SCH 13755, -- Flora Cotehardie Lv. 59 MNK / WHM / BLM / RDM / THF / BST / BRD / RNG / NIN / SMN / BLU / PUP / DNC / SCH 14436, -- Blessed Briault Lv. 70 WHM 14438, -- Blessed Briault +1 Lv. 70 WHM 13775, -- Blue Cotehardie Lv. 69 RDM / THF / RNG / NIN / COR / DNC 13776, -- Blue Cotehardie +1 Lv. 69 RDM / THF / RNG / NIN / COR / DNC 13740, -- Byrnie Lv. 60 WAR / PLD / DRK / BST / SAM / NIN 13741, -- Byrnie +1 Lv. 60 WAR / PLD / DRK / BST / SAM / NIN 13703, -- Brigandine Lv. 45 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 13710, -- Brigandine +1 Lv. 45 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14372, -- Cardinal Vest Lv. 73 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14373, -- Bachelor Vest Lv. 73 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14440, -- Chasuble Lv. 72 RDM 14441, -- Chasuble +1 Lv. 72 RDM 12573, -- Dusk Jerkin Lv. 72 WAR / RDM / THF / PLD / DRK / BST /BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14391, -- Dusk Jerkin +1 Lv. 72 WAR / RDM / THF / PLD / DRK / BST /BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14389, -- Dragon Harness Lv. 73 THF 14390, -- Dragon Harness +1 Lv. 73 THF 14380, -- Errant Houppelande Lv. 72 WHM / BLM / RDM / BRD / SMN / BLU / PUP / SCH 14381, -- Mahatma Houppelande Lv. 72 WHM / BLM / RDM / BRD / SMN / BLU / PUP / SCH 14437, -- Hachiman Domaru Lv. 70 SAM 14439, -- Hachiman Domaru +1 Lv. 70 SAM 12555, -- Haubergeon Lv. 59 WAR / PLD / DRK / BST / SAM /NIN 13735, -- Haubergeon Lv. 59 WAR / PLD / DRK / BST / SAM /NIN 12556, -- Hauberk Lv. 69 WAR / DRK / BST 13793, -- Hauberk +1 Lv. 69 WAR / DRK / BST 13812, -- Holy Breastplate Lv. 40 WHM 13813, -- Divine Breastplate Lv. 40 WHM 14488, -- Homam Corazza Lv. 75 THF / PLD / DRK / DRG / BLU 14420, -- Igqira Weskit Lv. 73 BLM 14421, -- Genie Weskit Lv. 73 BLM 14526, -- Jaridah Peti Lv. 55 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14529, -- Akinji Peti Lv. 55 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 13744, -- Justaucorps Lv. 58 MNK / WHM / BLM / RDM / THF / DRK / BRD / RNG / SMN / BLU / COR / PUP / DNC / SCH 13745, -- Justaucorps +1 Lv. 58 MNK / WHM / BLM / RDM / THF / DRK / BRD / RNG / SMN / BLU / COR / PUP / DNC / SCH 14489, -- Nashira Manteel Lv. 75 WHM / BLM / RDM / SMN / BLU 12605, -- Noble's Tunic Lv. 68 WHM 13774, -- Aristocrat's Coat Lv. 68 WHM 14530, -- Pahluwan Khazagand Lv. 72 MNK / RDM / THF / BST / RNG / NIN / DRG / COR / PUP / DNC 14382, -- Plastron Lv. 71 DRK 14383, -- Plastron +1 Lv. 71 DRK 14376, -- Rasetsu Samue Lv. 72 MNK / SAM / NIN 14377, -- Rasetsu Samue +1 Lv. 72 MNK / SAM / NIN 13748, -- Vermillion Cloak Lv. 59 MNK / WHM / BLM / RDM / PLD / BRD / RNG / SMN / BLU / PUP / SCH 13749, -- Royal Cloak Lv. 59 MNK / WHM / BLM / RDM / PLD / BRD / RNG / SMN / BLU / PUP / SCH 12579, -- Scorpion Harness Lv. 57 WAR / MNK / RDM / THF / PLD / DRK / BST / BRD / SAM / NIN / DRG / BLU / COR / DNC 13734, -- Scorpion Harness +1 Lv. 57 WAR / MNK / RDM / THF / PLD / DRK / BST / BRD / SAM / NIN / DRG / BLU / COR / DNC 14524, -- Sipahi Jawshan Lv. 59 WAR / PLD / DRK / BST / SAM 14528, -- Abtal Jawshan Lv. 59 WAR / PLD / DRK / BST / SAM 14414, -- Sha'ir Manteel Lv. 72 BRD 14415 -- Sheikh Manteel Lv. 72 BRD } -- Function to check if the player is wearing armor that is appropriate for the royal palace. function doRoyalPalaceArmorCheck(player) local bodyArmor = player:getEquipID(SLOT_BODY); local check = (ROYAL_PALACE_ALLOWED_BODY_ARMORS[bodyArmor] ~= nil); local hasHandArmor = player:getEquipID(SLOT_HANDS); local hasLegArmor = player:getEquipID(SLOT_LEGS); local hasFeetArmor = player:getEquipID(SLOT_FEET); if (hasHandArmor == 0 or hasLegArmor == 0 or hasFeetArmor == 0) then check = false; -- printf("Royal Palace Armor Check for Player <%s> -> Missing Required Hand/Leg/Feet Armor", player:getName()); end -- printf("Royal Palace Armor Check for Player <%s> with Body Armor <%u>, allowed = %s", player:getName(), bodyArmor, check); return check; end
gpl-3.0
TAJaroszewski/lma_contrail_monitoring
deployment_scripts/puppet/modules/lma_collector/files/plugins/filters/afd_workers.lua
1
3493
-- Copyright 2015 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. require 'string' local afd = require 'afd' local consts = require 'gse_constants' local worker_states = {} -- emit AFD event metrics based on openstack_nova_services, openstack_cinder_services and openstack_neutron_agents metrics function process_message() local metric_name = read_message('Fields[name]') local service = string.format('%s-%s', string.match(metric_name, 'openstack_([^_]+)'), read_message('Fields[service]')) local worker_key = string.format('%s.%s', metric_name, service) if not worker_states[worker_key] then worker_states[worker_key] = {} end local worker = worker_states[worker_key] worker[read_message('Fields[state]')] = read_message('Fields[value]') local state = consts.OKAY if not(worker.up and worker.down) then -- not enough data for now return 0 end if worker.up == 0 then state = consts.DOWN afd.add_to_alarms(consts.DOWN, 'last', metric_name, {{name='service',value=service},{name='state',value='up'}}, {}, '==', worker.up, 0, nil, nil, string.format("All instances for the service %s are down or disabled", service)) elseif worker.down >= worker.up then state = consts.CRIT afd.add_to_alarms(consts.CRIT, 'last', metric_name, {{name='service',value=service},{name='state',value='down'}}, {}, '>=', worker.down, worker.up, nil, nil, string.format("More instances of %s are down than up", service)) elseif worker.down > 0 then state = consts.WARN afd.add_to_alarms(consts.WARN, 'last', metric_name, {{name='service',value=service},{name='state',value='down'}}, {}, '>', worker.down, 0, nil, nil, string.format("At least one %s instance is down", service)) end afd.inject_afd_service_metric(service, state, read_message('Fields[hostname]'), 0, 'workers') -- reset the cache for this worker worker_states[worker_key] = {} return 0 end
apache-2.0
bnetcc/darkstar
scripts/commands/mp.lua
22
1359
--------------------------------------------------------------------------------------------------- -- func: mp <amount> <player> -- desc: Sets the GM or target players mana. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "is" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!mp <amount> {player}"); end; function onTrigger(player, mp, target) -- validate amount if (mp == nil or tonumber(mp) == nil) then error(player, "You must provide an amount."); return; elseif (mp < 0) then error(player, "Invalid amount."); return; end -- validate target local targ; if (target == nil) then targ = player; else targ = GetPlayerByName(target); if (targ == nil) then error(player, string.format( "Player named '%s' not found!", target ) ); return; end end -- set mp if (targ:getHP() > 0) then targ:setMP(mp); if(targ:getID() ~= player:getID()) then player:PrintToPlayer(string.format("Set %s's MP to %i.", targ:getName(), targ:getMP())); end else player:PrintToPlayer(string.format("%s is currently dead.", targ:getName())); end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/bowl_of_nashmau_stew.lua
3
1718
----------------------------------------- -- ID: 5595 -- Item: Bowl of Nashmau Stew -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- MP -100 -- Vitality -10 -- Agility -10 -- Intelligence -10 -- Mind -10 -- Charisma -10 -- Accuracy +15% Cap 25 -- Attack +18% Cap 60 -- Defense -100 -- Evasion -100 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5595); end; function onEffectGain(target, effect) target:addMod(MOD_MP, -100); target:addMod(MOD_VIT, -10); target:addMod(MOD_AGI, -10); target:addMod(MOD_INT, -10); target:addMod(MOD_MND, -10); target:addMod(MOD_CHR, -10); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 25); target:addMod(MOD_FOOD_ATTP, 18); target:addMod(MOD_FOOD_ATT_CAP, 60); target:addMod(MOD_DEF, -100); target:addMod(MOD_EVA, -100); end; function onEffectLose(target, effect) target:delMod(MOD_MP, -100); target:delMod(MOD_VIT, -10); target:delMod(MOD_AGI, -10); target:delMod(MOD_INT, -10); target:delMod(MOD_MND, -10); target:delMod(MOD_CHR, -10); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 25); target:delMod(MOD_FOOD_ATTP, 18); target:delMod(MOD_FOOD_ATT_CAP, 60); target:delMod(MOD_DEF, -100); target:delMod(MOD_EVA, -100); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Bastok_Markets/npcs/Ardea.lua
5
1733
----------------------------------- -- Area: Bastok Markets -- NPC: Ardea -- !pos -198 -6 -69 235 -- Involved in quests: Chasing Quotas, Rock Racketeer -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local RockRacketeer = player:getQuestStatus(WINDURST,ROCK_RACKETTER); local Quotas_Status = player:getVar("ChasingQuotas_Progress"); -- Rock Racketeer if (RockRacketeer == QUEST_ACCEPTED and player:hasKeyItem(SHARP_GRAY_STONE)) then player:startEvent(261); elseif (Quotas_Status == 3) then player:startEvent(264); -- Someone was just asking about that earring. elseif (Quotas_Status == 4) then player:startEvent(265); -- They'll be happy if you return it. -- Standard dialog else player:startEvent(260); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- Rock Racketeer if (csid == 261 and option ~= 1) then player:delKeyItem(SHARP_GRAY_STONE); player:addGil(GIL_RATE*10); player:setVar("rockracketeer_sold",1); elseif (csid == 261 and option ~= 2) then player:setVar("rockracketeer_sold",2); elseif (csid == 264) then player:setVar("ChasingQuotas_Progress",4); end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/uppercut.lua
35
1828
----------------------------------------- -- Spell: Uppercut -- Damage varies with TP -- Spell cost: 31 MP -- Monster Type: Plantoids -- Spell Type: Physical (Blunt) -- Blue Magic Points: 3 -- Stat Bonus: STR+2, DEX+1 -- Level: 38 -- Casting Time: 0.5 seconds -- Recast Time: 17.75 seconds -- Skillchain Element(s): Fire (Primary) and Lightning (Secondary) - (can open Scission, Detonation, Liquefaction, or Fusion; can close Liquefaction, Impaction, or Fusion) -- Combos: Attack Bonus ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_LIQUEFACTION; params.scattr2 = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.5; params.tp150 = 1.5; params.tp300 = 1.5; params.azuretp = 1.5; params.duppercap = 39; params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); -- Missing Knockback return damage; end;
gpl-3.0
bnetcc/darkstar
scripts/globals/mobskills/spirits_within_custom.lua
1
1724
--------------------------------------------- -- Spirits Within -- -- Description: Delivers an unavoidable attack. Damage varies with HP and TP. -- Type: Magical/Breath -- Ignores shadows and most damage reduction. -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/utils"); require("scripts/globals/monstertpmoves"); require("scripts/zones/Throne_Room/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:getFamily() == 482) then target:showText(mob,YOUR_ANSWER); return 0; else return 0; end; function onMobWeaponSkill(target, mob, skill) if (mob:getFamily() == 482) then target:showText(mob,RETURN_TO_THE_DARKNESS); else mob:messageBasic(43, 0, 686+256); end local tp = skill:getTP(); local hp = mob:getHP(); local dmg = 0; -- Should produce 1000 - 3750 @ full HP using the player formula, assuming 8k HP for AA EV. -- dmg * 2.5, as wiki claims ~2500 at 100% HP, until a better formula comes along. if tp <= 200 then -- 100 - 200 dmg = math.floor(hp * (math.floor(0.16 * tp) + 16) / 256); else -- 201 - 300 dmg = math.floor(hp * (math.floor(0.72 * tp) - 96) / 256); end dmg = dmg * 2.5; -- Believe it or not, it's been proven to be breath damage. dmg = target:breathDmgTaken(dmg); --handling phalanx dmg = dmg - target:getMod(MOD_PHALANX); if (dmg < 0) then return 0; end dmg = utils.stoneskin(target, dmg); if (dmg > 0) then target:wakeUp(); target:updateEnmityFromDamage(mob,dmg); end target:delHP(dmg); return dmg; end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/armys_paeon_ii.lua
5
1339
----------------------------------------- -- Spell: Army's Paeon II -- Gradually restores target's HP. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 2; if (sLvl+iLvl > 150) then power = power + 1; end local iBoost = caster:getMod(MOD_PAEON_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_PAEON,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_PAEON; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Mog_Garden/npcs/GreenThumbMo.lua
5
2025
package.loaded["scripts/zones/Mog_Garden/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mog_Garden/TextIDs"); require("scripts/globals/moghouse") require("scripts/globals/shop"); ----------------------------------- local BRONZE_PIECE_ITEMID = 2184; function onTrade(player, npc, trade) moogleTrade(player, npc, trade) end; function onTrigger(player, npc) player:startEvent(1016); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player, csid, option) if (csid == 1016 and option == 0xFFF00FF) then -- Show the Mog House menu.. -- Print the expire time for mog locker if exists.. local lockerLease = getMogLockerExpiryTimestamp(player); if (lockerLease ~= nil) then if (lockerLease == -1) then -- Lease expired.. player:messageSpecial(MOGLOCKER_MESSAGE_OFFSET + 2, BRONZE_PIECE_ITEMID); else player:messageSpecial(MOGLOCKER_MESSAGE_OFFSET + 1, lockerLease); end end -- Show the mog house menu.. player:sendMenu(1); elseif (csid == 1016 and option == 0xFFE00FF) then -- Buy/Sell Things local stock = { 573, 280, -- Vegetable Seeds 574, 320, -- Fruit Seeds 575, 280, -- Grain Seeds 572, 280, -- Herb Seeds 1236, 1685, -- Cactus Stems 2235, 320, -- Wildgrass Seeds 3986, 1111, -- Chestnut Tree Sap (11th Anniversary Campaign) 3985, 1111, -- Monarch Beetle Saliva (11th Anniversary Campaign) 3984, 1111, -- Golden Seed Pouch (11th Anniversary Campaign) }; showShop( player, STATIC, stock ); elseif (csid == 1016 and option == 0xFFB00FF) then -- Leave this Mog Garden -> Whence I Came player:warp(); -- Ghetto for now, the last zone seems to get messed up due to mog house issues. end end;
gpl-3.0