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
nasomi/darkstar
scripts/globals/items/galkan_sausage_-1.lua
35
1586
----------------------------------------- -- ID: 5862 -- Item: galkan_sausage_-1 -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Dexterity -3 -- Vitality -3 -- Agility -3 -- Mind -3 -- Intelligence -3 -- Charisma -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5862); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -3); target:addMod(MOD_DEX, -3); target:addMod(MOD_VIT, -3); target:addMod(MOD_AGI, -3); target:addMod(MOD_MND, -3); target:addMod(MOD_INT, -3); target:addMod(MOD_CHR, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -3); target:delMod(MOD_DEX, -3); target:delMod(MOD_VIT, -3); target:delMod(MOD_AGI, -3); target:delMod(MOD_MND, -3); target:delMod(MOD_INT, -3); target:delMod(MOD_CHR, -3); end;
gpl-3.0
actboy168/YDWE
Development/Component/plugin/w3x2lni/script/gui/new/page/index.lua
3
1295
local gui = require 'yue.gui' local timer = require 'gui.timer' local lang = require 'share.lang' local ui = require 'gui.new.template' local template = ui.container { style = { FlexGrow = 1, FlexDirection = 'row', AlignItems = 'center', JustifyContent = 'center' }, ui.label { text = lang.ui.DRAG_MAP, style = { Height = 50, Width = 200 }, font = { size = 16 }, bind = { text_color = 'color', } }, ui.button { title = lang.ui.VERSION .. (require 'share.changelog')[1].version, color = '#333743', style = { Position = 'absolute', Bottom = 20, Right = 0, Width = 140 }, on = { click = function() window:show_page('about') end } } } local view, data = ui.create(template, { color = '#222' }) local hover = false local ani = nil function view:onmouseenter() hover = true timer.wait(1000, function() if hover then local n = 2 ani = timer.count(100, 6, function() n = n + 1 data.color = '#' .. n .. n .. n end) end end) end function view:onmouseleave() hover = false data.color = '#222' if ani then ani:remove() end end return view
gpl-3.0
nasomi/darkstar
scripts/globals/spells/plenilune_embrace.lua
18
1964
----------------------------------------- -- Spell: Plenilune Embrace -- Restores target party member's HP and enhances attack and magic attack.. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 90; local attBoost = 1; local magAttBoost = 1; local moonPhase = VanadielMoonPhase(); if (moonPhase <= 5) then magAttBoost = 15; attBoost = 1; elseif (moonPhase <= 25) then magAttBoost = 12; attBoost = 3; elseif (moonPhase <= 40) then magAttBoost = 10; attBoost = 5; elseif (moonPhase <= 60) then magAttBoost = 7; attBoost = 7; elseif (moonPhase <= 75) then magAttBoost = 5; attBoost = 10; elseif (moonPhase <= 90) then magAttBoost = 3; attBoost = 12; elseif (moonPhase <= 100) then magAttBoost = 1; attBoost = 15; end caster:addStatusEffect(EFFECT_ATTACK_BOOST,attBoost,0,duration); caster:addStatusEffect(EFFECT_MAGIC_ATK_BOOST,magAttBoost,0,duration); local minCure = 350; local divisor = 0.6666; local constant = 230; local power = getCurePowerOld(caster); if (power > 559) then divisor = 2.8333; constant = 491.2 elseif (power > 319) then divisor = 1; constant = 310; end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); caster:updateEnmityFromCure(target,final); return final; end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/blowfish.lua
18
1257
----------------------------------------- -- ID: 5812 -- Item: Blowfish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 1 -- Mind -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5812); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); end;
gpl-3.0
haka-security/haka
sample/stats/stats_utils.lua
5
2760
local function group_by(tab, field) local ret = {} for _, entry in ipairs(tab) do local value = entry[field] assert(value, string.format("stats are not available on field %s", field)) if not ret[value] then ret[value] = {} end table.insert(ret[value], entry) end return ret end local function order_by(tab, order) local ret = {} for k, v in pairs(tab) do table.insert(ret, {k, v}) end table.sort(ret, order) return ret end local function max_length_field(tab, nb) local max = {} if nb > #tab then nb = #tab end for iter = 1, nb do for k, v in sorted_pairs(tab[iter]) do local size = #v if size > 99 then -- Lua formating limits width to 99 size = 99 end if not max[k] then max[k] = #k end if size > max[k] then max[k] = size end end end return max end local function print_columns(tab, nb) local max = max_length_field(tab, nb) if #tab > 0 then local columns = {} for k, _ in sorted_pairs(tab[1]) do table.insert(columns, string.format("%-" .. tostring(max[k]) .. "s", k)) end print("| " .. table.concat(columns, " | ") .. " |") end return max end -- Metatable for storing 'sql-like' table and methods. Intended to be used to -- store 'stats' data and to provide methods to request them local table_mt = {} table_mt.__index = table_mt function table_mt:select_table(elements, where) local ret = {} for _, entry in ipairs(self) do local selected_entry = {} if not where or where(entry) then for _, field in ipairs(elements) do selected_entry[field] = entry[field] end table.insert(ret, selected_entry) end end setmetatable(ret, table_mt) return ret end function table_mt:top(field, nb) nb = nb or 10 assert(field, "missing field parameter") local grouped = group_by(self, field) local sorted = order_by(grouped, function(p, q) return #p[2] > #q[2] or (#p[2] == #q[2] and p[1] > q[1]) end) for _, entry in ipairs(sorted) do if nb <= 0 then break end print(entry[1], ":", #entry[2]) nb = nb - 1 end end function table_mt:dump(nb) nb = nb or #self assert(nb > 0, "illegal negative value") local max = print_columns(self, nb) local iter = nb for _, entry in ipairs(self) do if iter <= 0 then break end local content = {} for k, v in sorted_pairs(entry) do table.insert(content, string.format("%-" .. tostring(max[k]) .. "s", v)) end print("| " .. table.concat(content, " | ") .. " |") iter = iter -1 end if #self > nb then print("... " .. tostring(#self - nb) .. " remaining entries") end end function table_mt:list() if #stats > 1 then for k, _ in sorted_pairs(self[1]) do print(k) end end end return { new = function () local ret = {} setmetatable(ret, table_mt) return ret end }
mpl-2.0
nasomi/darkstar
scripts/zones/Southern_San_dOria/npcs/Vaquelage.lua
34
1528
----------------------------------- -- Area: Southern San dOria -- NPC: Vaquelage -- Type: Item Deliverer NPC -- @pos 17.396 1.699 -29.357 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
RhenaudTheLukark/CreateYourFrisk
Assets/Mods/RTLGeno/Lua/Monsters/Lukark.lua
1
3267
-- A basic monster script skeleton you can copy and modify for your own creations. comments = { "Lukark is vengeful.", "Lukark prepares his next move.", "Lukark frowns at you.", "Lukark brushes his hair as dust gets into it.", "Lukark gazes at you with intensity.", "The dust staining your clothes only fuels Lukark's rage." } commands = { "Pardon" } randomdialogue = { "[effect:none][func:SetFace,angry]Come back here!", "[effect:none][func:SetFace,angry]You can't escape me now!", "[effect:none][func:SetFace,angry]I'll get you no matter what.", "[effect:none][func:SetFace,angry]Take this!" } sprite = "Lukark/full" --Always PNG. Extension is added automatically. name = "Lukark" hp = 1000 atk = 5 def = 1 gold = math.random(35, 105) xp = math.random(125, 375) check = "The Overworld Creator.[w:15]\rDestroy him if you dare." dialogbubble = "rightwideminus" -- See documentation for what bubbles you have available. cancheck = true canspare = false pardonCount = 0 attackprogression = 0 anim = "normal" SetActive(false) effect = "none" -- Happens after the slash animation but before function HandleAttack(attackstatus) if attackstatus > 0 then SetFace("hurt") end end -- This handles the commands; all-caps versions of the commands list you have above. function HandleCustomCommand(command) if command == "PARDON" then if pardonCount == 0 then BattleDialog({ "You tell Lukark you'll stop your killing frenzy.", "It doesn't seem to calm him down one bit." }) currentdialogue = { "[effect:none][func:SetFace,angry]Hah! As if someone like you could feel remorse!", "[next]" } elseif pardonCount == 1 then BattleDialog({ "Your voice crackles as you mutter an apology to Lukark." }) currentdialogue = {"[effect:none]...[w:20][noskip][func:SetFace,smiling][noskip:off]I still don't believe you, you killer.", "[next]" } elseif pardonCount == 2 then BattleDialog({ "A tear roll down your cheek as you bow in front of Lukark, pleading him to stop this nonsense." }) currentdialogue = { "[effect:none]......[noskip][w:20][func:SetFace,happy][noskip:off]Please stop. We both know this has gone too far by now.", "[next]" } else BattleDialog({ "You ask for Lukark's forgiveness once more...", "But he ignores you." }) end pardonCount = pardonCount + 1 end end function OnDeath() hp = 1 Audio.Pause() currentdialogue = { "[noskip][effect:none]Gah, [w:20]I knew it...[w:20][next]", "[noskip][effect:none]I should have been more careful...[w:20][next]", "[noskip][effect:none][func:SetFace,happy]What a joke...[w:20][func:FadeKill][func:Kill][next]" } end -- Starts the death fade anim function FadeKill() Encounter.Call("LukarkHideAnimation", true) end -- Changes Lukark's animation function SetFace(anim) Encounter.Call("SetLukarkFace", anim) end function Pause() Audio.Pause() end function Unpause() Audio.Unpause() end -- Plays a given sound function PlaySE(filename) Audio.PlaySound(filename) end -- Enables this enemy function Activate() SetActive(true) end
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c2700061.lua
1
1190
--P-042 Great Ape Prince Vegeta local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddPlayProcedure(c,COLOR_YELLOW,2,2) ds.AddSetcode(c,CHARACTER_VEGETA,SPECIAL_TRAIT_SAIYAN,SPECIAL_TRAIT_GREAT_APE) --critical ds.EnableCritical(c) --blocker ds.EnableCritical(c) --to hand ds.AddSingleAutoPlay(c,0,nil,scard.thtg,scard.thop,DS_EFFECT_FLAG_CARD_CHOOSE) ds.AddSingleAutoCombo(c,0,nil,scard.thtg,scard.thop,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=1 scard.thtg=ds.ChooseDecktopTarget(Card.IsSpecialTrait,3,0,1,DS_HINTMSG_TOHAND,nil,SPECIAL_TRAIT_GREAT_APE) function scard.thop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToSkill(e) then if Duel.SendtoHand(tc,PLAYER_OWNER,DS_REASON_SKILL)==0 then return Duel.ShuffleDeck(tp) end Duel.ConfirmCards(1-tc:GetControler(),tc) Duel.ShuffleHand(tp) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TODROP) local g=Duel.SelectMatchingCard(tp,nil,tp,LOCATION_HAND,0,1,1,nil) if g:GetCount()==0 then return end Duel.SendtoDrop(g,DS_REASON_SKILL) else Duel.ShuffleDeck(tp) end end
gpl-3.0
nasomi/darkstar
scripts/zones/Bastok_Mines/npcs/Rodellieux.lua
36
1462
----------------------------------- -- Area: Bastok_Mines -- NPC: Rodellieux -- Only sells when Bastok controlls Fauregandi Region ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); 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) RegionOwner = GetRegionOwner(FAUREGANDI); if (RegionOwner ~= BASTOK) then player:showText(npc,RODELLIEUX_CLOSED_DIALOG); else player:showText(npc,RODELLIEUX_OPEN_DIALOG); stock = { 0x11db, 90, --Beaugreens 0x110b, 39, --Faerie Apple 0x02b3, 54 --Maple Log } showShop(player,BASTOK,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
thesabbir/luci
applications/luci-app-shadowsocks-libev/luasrc/model/cbi/shadowsocks-libev.lua
39
3926
-- Copyright 2015 Jian Chang <aa65535@live.com> -- Licensed to the public under the Apache License 2.0. local m, s, o, e, a if luci.sys.call("pidof ss-redir >/dev/null") == 0 then m = Map("shadowsocks-libev", translate("ShadowSocks-libev"), translate("ShadowSocks-libev is running")) else m = Map("shadowsocks-libev", translate("ShadowSocks-libev"), translate("ShadowSocks-libev is not running")) end e = { "table", "rc4", "rc4-md5", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "bf-cfb", "camellia-128-cfb", "camellia-192-cfb", "camellia-256-cfb", "cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "seed-cfb", "salsa20", "chacha20", } -- Global Setting s = m:section(TypedSection, "shadowsocks-libev", translate("Global Setting")) s.anonymous = true o = s:option(Flag, "enable", translate("Enable")) o.default = 1 o.rmempty = false o = s:option(Value, "server", translate("Server Address")) o.datatype = "ipaddr" o.rmempty = false o = s:option(Value, "server_port", translate("Server Port")) o.datatype = "port" o.rmempty = false o = s:option(Value, "local_port", translate("Local Port")) o.datatype = "port" o.default = 1080 o.rmempty = false o = s:option(Value, "timeout", translate("Connection Timeout")) o.datatype = "uinteger" o.default = 60 o.rmempty = false o = s:option(Value, "password", translate("Password")) o.password = true o.rmempty = false o = s:option(ListValue, "encrypt_method", translate("Encrypt Method")) for i,v in ipairs(e) do o:value(v) end o.rmempty = false o = s:option(Value, "ignore_list", translate("Ignore List")) o:value("/dev/null", translate("Disabled")) o.default = "/dev/null" o.rmempty = false -- UDP Relay s = m:section(TypedSection, "shadowsocks-libev", translate("UDP Relay")) s.anonymous = true o = s:option(ListValue, "udp_mode", translate("Relay Mode")) o:value("0", translate("Disabled")) o:value("1", translate("Enabled")) o:value("2", translate("Custom")) o.default = 0 o.rmempty = false o = s:option(Value, "udp_server", translate("Server Address")) o.datatype = "ipaddr" o:depends("udp_mode", 2) o = s:option(Value, "udp_server_port", translate("Server Port")) o.datatype = "port" o:depends("udp_mode", 2) o = s:option(Value, "udp_local_port", translate("Local Port")) o.datatype = "port" o.default = 1081 o:depends("udp_mode", 2) o = s:option(Value, "udp_timeout", translate("Connection Timeout")) o.datatype = "uinteger" o.default = 60 o:depends("udp_mode", 2) o = s:option(Value, "udp_password", translate("Password")) o.password = true o:depends("udp_mode", 2) o = s:option(ListValue, "udp_encrypt_method", translate("Encrypt Method")) for i,v in ipairs(e) do o:value(v) end o:depends("udp_mode", 2) -- UDP Forward s = m:section(TypedSection, "shadowsocks-libev", translate("UDP Forward")) s.anonymous = true o = s:option(Flag, "tunnel_enable", translate("Enable")) o.default = 1 o.rmempty = false o = s:option(Value, "tunnel_port", translate("UDP Local Port")) o.datatype = "port" o.default = 5300 o = s:option(Value, "tunnel_forward", translate("Forwarding Tunnel")) o.default = "8.8.4.4:53" -- Access Control s = m:section(TypedSection, "shadowsocks-libev", translate("Access Control")) s.anonymous = true s:tab("lan_ac", translate("LAN")) o = s:taboption("lan_ac", ListValue, "lan_ac_mode", translate("Access Control")) o:value("0", translate("Disabled")) o:value("1", translate("Allow listed only")) o:value("2", translate("Allow all except listed")) o.default = 0 o.rmempty = false a = luci.sys.net.arptable() or {} o = s:taboption("lan_ac", DynamicList, "lan_ac_ip", translate("LAN IP List")) o.datatype = "ipaddr" for i,v in ipairs(a) do o:value(v["IP address"]) end s:tab("wan_ac", translate("WAN")) o = s:taboption("wan_ac", DynamicList, "wan_bp_ip", translate("Bypassed IP")) o.datatype = "ip4addr" o = s:taboption("wan_ac", DynamicList, "wan_fw_ip", translate("Forwarded IP")) o.datatype = "ip4addr" return m
apache-2.0
mlem/wesnoth
data/ai/micro_ais/cas/ca_recruit_random.lua
26
4781
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require("ai/lua/ai_helper.lua") local LS = wesnoth.dofile "lua/location_set.lua" local recruit_type local ca_recruit_random = {} function ca_recruit_random:evaluation(ai, cfg) -- Random recruiting from all the units the side has -- Check if leader is on keep local leader = wesnoth.get_units { side = wesnoth.current.side, canrecruit = 'yes' }[1] if (not leader) or (not wesnoth.get_terrain_info(wesnoth.get_terrain(leader.x, leader.y)).keep) then return 0 end -- Find all connected castle hexes local castle_map = LS.of_pairs({ { leader.x, leader.y } }) local width, height, border = wesnoth.get_map_size() local new_castle_hex_found = true while new_castle_hex_found do new_castle_hex_found = false local new_hexes = {} castle_map:iter(function(x, y) for xa,ya in H.adjacent_tiles(x, y) do if (not castle_map:get(xa, ya)) and (xa >= 1) and (xa <= width) and (ya >= 1) and (ya <= height) then local is_castle = wesnoth.get_terrain_info(wesnoth.get_terrain(xa, ya)).castle if is_castle then table.insert(new_hexes, { xa, ya }) new_castle_hex_found = true end end end end) for _,hex in ipairs(new_hexes) do castle_map:insert(hex[1], hex[2]) end end -- Check if there is space left for recruiting local no_space = true castle_map:iter(function(x, y) local unit = wesnoth.get_unit(x, y) if (not unit) then no_space = false end end) if no_space then return 0 end -- Set up the probability array local probabilities, probability_sum = {}, 0 -- Go through all the types listed in [probability] tags (which can be comma-separated lists) -- Types and probabilities are put into cfg.type and cfg.prob arrays by micro_ai_wml_tag.lua for ind,types in ipairs(cfg.type) do types = AH.split(types, ",") for _,typ in ipairs(types) do -- 'type' is a reserved keyword in Lua -- If this type is in the recruit list, add it for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do if (recruit == typ) then probabilities[typ] = { value = cfg.prob[ind] } probability_sum = probability_sum + cfg.prob[ind] break end end end end -- Now we add in all the unit types not listed in [probability] tags for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do if (not probabilities[recruit]) then probabilities[recruit] = { value = 1 } probability_sum = probability_sum + 1 end end -- Now eliminate all those that are too expensive (unless cfg.skip_low_gold_recruiting is set) if cfg.skip_low_gold_recruiting then for typ,probability in pairs(probabilities) do -- 'type' is a reserved keyword in Lua if (wesnoth.unit_types[typ].cost > wesnoth.sides[wesnoth.current.side].gold) then probability_sum = probability_sum - probability.value probabilities[typ] = nil end end end -- Now set up the cumulative probability values for each type -- Both min and max need to be set as the order of pairs() is not guaranteed local cum_prob = 0 for typ,probability in pairs(probabilities) do probabilities[typ].p_i = cum_prob cum_prob = cum_prob + probability.value probabilities[typ].p_f = cum_prob end -- We always call the exec function, no matter if the selected unit is affordable -- The point is that this will blacklist the CA if an unaffordable recruit was -- chosen -> no cheaper recruits will be selected in subsequent calls if (cum_prob > 0) then local rand_prob = math.random(cum_prob) for typ,probability in pairs(probabilities) do if (probability.p_i < rand_prob) and (rand_prob <= probability.p_f) then recruit_type = typ break end end else recruit_type = wesnoth.sides[wesnoth.current.side].recruit[1] end return cfg.ca_score end function ca_recruit_random:execution(ai, cfg) -- Let this function blacklist itself if the chosen recruit is too expensive if wesnoth.unit_types[recruit_type].cost <= wesnoth.sides[wesnoth.current.side].gold then AH.checked_recruit(ai, recruit_type) end end return ca_recruit_random
gpl-2.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Belgidiveau.lua
17
2240
----------------------------------- -- Area: Northern San d'Oria -- NPC: Belgidiveau -- Starts and Finishes Quest: Trouble at the Sluice -- @zone 231 -- @pos -98 0 69 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) troubleAtTheSluice = player:getQuestStatus(SANDORIA,TROUBLE_AT_THE_SLUICE); NeutralizerKI = player:hasKeyItem(NEUTRALIZER); if (troubleAtTheSluice == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then player:startEvent(0x0039); elseif (troubleAtTheSluice == QUEST_ACCEPTED and NeutralizerKI == false) then player:startEvent(0x0037); elseif (NeutralizerKI) then player:startEvent(0x0038); else player:startEvent(0x0249); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0039 and option == 0) then player:addQuest(SANDORIA,TROUBLE_AT_THE_SLUICE); player:setVar("troubleAtTheSluiceVar",1); elseif (csid == 0x0038) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16706); -- Heavy Axe else player:tradeComplete(); player:delKeyItem(NEUTRALIZER); player:addItem(16706); player:messageSpecial(ITEM_OBTAINED,16706); -- Heavy Axe player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,TROUBLE_AT_THE_SLUICE); end end end;
gpl-3.0
raburton/nodemcu-firmware
lua_modules/ds18b20/ds18b20.lua
18
3492
-------------------------------------------------------------------------------- -- DS18B20 one wire module for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Vowstar <vowstar@nodemcu.com> -- 2015/02/14 sza2 <sza2trash@gmail.com> Fix for negative values -------------------------------------------------------------------------------- -- Set module name as parameter of require local modname = ... local M = {} _G[modname] = M -------------------------------------------------------------------------------- -- Local used variables -------------------------------------------------------------------------------- -- DS18B20 dq pin local pin = nil -- DS18B20 default pin local defaultPin = 9 -------------------------------------------------------------------------------- -- Local used modules -------------------------------------------------------------------------------- -- Table module local table = table -- String module local string = string -- One wire module local ow = ow -- Timer module local tmr = tmr -- Limited to local environment setfenv(1,M) -------------------------------------------------------------------------------- -- Implementation -------------------------------------------------------------------------------- C = 'C' F = 'F' K = 'K' function setup(dq) pin = dq if(pin == nil) then pin = defaultPin end ow.setup(pin) end function addrs() setup(pin) tbl = {} ow.reset_search(pin) repeat addr = ow.search(pin) if(addr ~= nil) then table.insert(tbl, addr) end tmr.wdclr() until (addr == nil) ow.reset_search(pin) return tbl end function readNumber(addr, unit) result = nil setup(pin) flag = false if(addr == nil) then ow.reset_search(pin) count = 0 repeat count = count + 1 addr = ow.search(pin) tmr.wdclr() until((addr ~= nil) or (count > 100)) ow.reset_search(pin) end if(addr == nil) then return result end crc = ow.crc8(string.sub(addr,1,7)) if (crc == addr:byte(8)) then if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then -- print("Device is a DS18S20 family device.") ow.reset(pin) ow.select(pin, addr) ow.write(pin, 0x44, 1) -- tmr.delay(1000000) present = ow.reset(pin) ow.select(pin, addr) ow.write(pin,0xBE,1) -- print("P="..present) data = nil data = string.char(ow.read(pin)) for i = 1, 8 do data = data .. string.char(ow.read(pin)) end -- print(data:byte(1,9)) crc = ow.crc8(string.sub(data,1,8)) -- print("CRC="..crc) if (crc == data:byte(9)) then t = (data:byte(1) + data:byte(2) * 256) if (t > 32767) then t = t - 65536 end if (addr:byte(1) == 0x28) then t = t * 625 -- DS18B20, 4 fractional bits else t = t * 5000 -- DS18S20, 1 fractional bit end if(unit == nil or unit == 'C') then -- do nothing elseif(unit == 'F') then t = t * 1.8 + 320000 elseif(unit == 'K') then t = t + 2731500 else return nil end t = t / 10000 return t end tmr.wdclr() else -- print("Device family is not recognized.") end else -- print("CRC is not valid!") end return result end function read(addr, unit) t = readNumber(addr, unit) if (t == nil) then return nil else return t end end -- Return module table return M
mit
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/resistance_torso_bare_walk_shot_3.meta.lua
2
2737
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.40000000596046448, amplification = 100, light_colors = { "223 113 38 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -12, y = -1 }, rotation = 2.5 }, head = { pos = { x = -2, y = 2 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 13, y = 19 }, rotation = 0 }, secondary_hand = { pos = { x = 16, y = -20 }, rotation = 0 }, secondary_shoulder = { pos = { x = 7, y = 20 }, rotation = 183 }, shoulder = { pos = { x = 10, y = -19 }, rotation = 177 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
thesabbir/luci
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdiface6.lua
68
5949
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd6", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd6") if not arg[1] or m.uci:get("olsrd6", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
apache-2.0
saucisson/layeredata
src/layeredata/init.lua
3
30238
local C3 = require "c3" local Coromake = require "coroutine.make" local Uuid = require "uuid" Uuid.seed () local Layer = setmetatable ({}, { __tostring = function () return "Layer" end }) local Proxy = setmetatable ({}, { __tostring = function () return "Proxy" end }) local Reference = setmetatable ({}, { __tostring = function () return "Reference" end }) local Key = setmetatable ({ __tostring = function (self) return "-" .. self.name .. "-" end }, { __tostring = function () return "Key" end }) local IgnoreNone = {} local IgnoreKeys = { __mode = "k" } local IgnoreValues = { __mode = "v" } --local IgnoreAll = { __mode = "kv" } local Read_Only = { __index = function () assert (false) end, __newindex = function () assert (false) end, } -- ---------------------------------------------------------------------- -- ## Layers -- ---------------------------------------------------------------------- Layer.key = setmetatable ({ checks = setmetatable ({ name = "checks" }, Key), defaults = setmetatable ({ name = "defaults" }, Key), deleted = setmetatable ({ name = "deleted" }, Key), labels = setmetatable ({ name = "labels" }, Key), meta = setmetatable ({ name = "meta" }, Key), refines = setmetatable ({ name = "refines" }, Key), }, Read_Only) Layer.tag = setmetatable ({ null = setmetatable ({ name = "null" }, Key), computing = setmetatable ({ name = "computing" }, Key), }, Read_Only) Layer.coroutine = Coromake () Layer.hidden = setmetatable ({}, IgnoreKeys ) Layer.loaded = setmetatable ({}, IgnoreValues) Layer.children = setmetatable ({}, IgnoreKeys ) Layer.references = setmetatable ({}, IgnoreKeys ) function Layer.new (t) assert (t == nil or type (t) == "table") t = t or {} assert (t.temporary == nil or type (t.temporary) == "boolean") assert (t.write_to == nil or getmetatable (t.write_to) == Proxy) local layer = setmetatable ({}, Layer) Layer.hidden [layer] = { name = t.name or Uuid (), temporary = t.temporary or nil, data = t.data or {}, write_to = t.write_to or nil, observers = {}, } local hidden = Layer.hidden [layer] local ref local proxy = Proxy.new (layer) if not t.temporary then ref = Reference.new (proxy) end hidden.proxy = proxy hidden.ref = ref Layer.loaded [hidden.name] = proxy return proxy, ref end function Layer.__tostring (layer) assert (getmetatable (layer) == Layer) return "layer:" .. tostring (Layer.hidden [layer].name) end function Layer.require (name) local loaded = Layer.loaded [name] if loaded then local layer = Layer.hidden [loaded].layer local info = Layer.hidden [layer] return info.proxy, info.ref else local layer, ref = Layer.new { name = name, } require (name) (Layer, layer, ref) Layer.loaded [name] = layer return layer, ref end end function Layer.clear () local Metatable = IgnoreNone Layer.caches = { index = setmetatable ({}, Metatable), pairs = setmetatable ({}, Metatable), ipairs = setmetatable ({}, Metatable), len = setmetatable ({}, Metatable), check = setmetatable ({}, Metatable), exists = setmetatable ({}, Metatable), dependencies = setmetatable ({}, Metatable), resolve = setmetatable ({}, Metatable), lt = setmetatable ({}, Metatable), } Layer.statistics = { index = setmetatable ({}, Metatable), pairs = setmetatable ({}, Metatable), ipairs = setmetatable ({}, Metatable), len = setmetatable ({}, Metatable), check = setmetatable ({}, Metatable), exists = setmetatable ({}, Metatable), dependencies = setmetatable ({}, Metatable), } Layer.messages = setmetatable ({}, IgnoreKeys) end function Layer.is_empty (proxy) assert (getmetatable (proxy) == Proxy and #Layer.hidden [proxy].keys == 0) local layer = Layer.hidden [proxy].layer local data = Layer.hidden [layer].data return not not next (data) end function Layer.write_to (proxy, to) assert (getmetatable (proxy) == Proxy and #Layer.hidden [proxy].keys == 0) assert (not to or getmetatable (to) == Proxy) local layer = Layer.hidden [proxy].layer local info = Layer.hidden [layer] local previous = info.write_to info.write_to = to return previous end function Layer.dump (proxy) assert (getmetatable (proxy) == Proxy and #Layer.hidden [proxy].keys == 0) local layer = Layer.hidden [proxy].layer local labels = {} if Layer.hidden [layer].data [Layer.key.labels] then for label, _ in pairs (Layer.hidden [layer].data [Layer.key.labels]) do labels [label] = true end end local layers_n = 1 local seen_layers = {} local seen_keys = {} local function convert (x) if type (x) == "string" then return string.format ("%q", x) elseif type (x) == "number" or type (x) == "boolean" then return tostring (x) elseif getmetatable (x) == Key then seen_keys [x] = true return x.name elseif getmetatable (x) == Proxy then local p = Layer.hidden [x] local l = Layer.hidden [p.layer] local result = "Layer.require " .. string.format ("%q", l.name) for _, v in ipairs (p.keys) do local s if type (v) == "string" then s = v:match "^[_%a][_%w]*$" and "." .. v or "[" .. convert (v) .. "]" else s = "[" .. convert (v) .. "]" end result = result .. s end return result elseif getmetatable (x) == Reference then local reference = Layer.hidden [x] local result if labels [reference.from] then result = "ref" else for name, p in pairs (Layer.loaded) do local l = Layer.hidden [p].layer local ref = Layer.hidden [l].ref if ref and Layer.hidden [ref].from == reference.from then seen_layers [name] = layers_n result = "r" .. tostring (layers_n) layers_n = layers_n+1 break end end if not result then result = "Layer.reference (" .. string.format ("%q", reference.from) .. ")" end end for _, v in ipairs (reference.keys) do local s if type (v) == "string" then s = v:match "^[_%a][_%w]*$" and "." .. v or "[" .. convert (v) .. "]" else s = "[" .. convert (v) .. "]" end result = result .. s end return result elseif type (x) == "table" then local result = {} for k, v in pairs (x) do if k == Layer.key.labels then local ls = {} for kl, vl in pairs (v) do if not labels [kl] then ls [convert (kl)] = convert (vl) end end if next (ls) then result [convert (k)] = ls end else result [convert (k)] = convert (v) end end return result elseif type (x) == "function" then return nil, "cannot dump functions" else assert (false) end end local function indent (x, level) local indentation = "" for _ = 1, level do indentation = indentation .. " " end if type (x) == "string" then return x elseif type (x) == "table" then local lines = {} for k, v in pairs (x) do local match = k:match [[^"([_%a][_%w]*)"$]] local key if match then key = match else key = "[" .. k .. "]" end lines [#lines+1] = { key = key, value = indent (v, level+1), } end table.sort (lines, function (l, r) return l.key < r.key end) for i, line in ipairs (lines) do lines [i] = indentation .. " " .. line.key .. " = " .. line.value .. "," end return "{\n" .. table.concat (lines, "\n") .. "\n" .. indentation .. "}" else assert (false) end end local result = { [[return function (Layer, layer, ref)]], [[end]], } local locals = {} local imports = {} local contents = {} local keys = {} -- body local body = convert (Layer.hidden [layer].data) local lines = {} for k, v in pairs (body) do local match = k:match [[^"([_%a][_%w]*)"$]] local key if match then key = "." .. match else key = " [" .. k .. "]" end lines [#lines+1] = { key = key, value = indent (v, 1), } end table.sort (lines, function (l, r) return l.key < r.key end) for _, line in ipairs (lines) do contents [#contents+1] = " layer" .. line.key .. " = " .. line.value end -- locals for x in pairs (seen_keys) do keys [#keys+1] = x end table.sort (keys, function (l, r) return l.name < r.name end) for _, t in ipairs (keys) do locals [#locals+1] = " local " .. t.name .. " = Layer.key." .. t.name end -- imports for x, n in pairs (seen_layers) do local key = "local l" .. tostring (n) .. ", r" .. tostring (n) local value = "Layer.require " .. string.format ("%q", x) imports [#imports+1] = { key = key, value = value, } end table.sort (imports, function (l, r) return l.key < r.key end) for i, t in ipairs (imports) do imports [i] = " " .. t.key .. " = " .. t.value end -- output if #locals ~= 0 then table.insert (result, #result, table.concat (locals, "\n")) end if #imports ~= 0 then table.insert (result, #result, table.concat (imports, "\n")) end if #contents ~= 0 then table.insert (result, #result, table.concat (contents, "\n")) end return table.concat (result, "\n") end function Layer.merge (source, target) assert (getmetatable (source) == Proxy and #Layer.hidden [source].keys == 0) assert (getmetatable (target) == Proxy and #Layer.hidden [target].keys == 0) local function iterate (s, t) assert (type (s) == "table") assert (getmetatable (t) == Proxy) for k, v in pairs (s) do if k == Layer.key.checks or k == Layer.key.defaults or k == Layer.key.labels or v == Layer.key.deleted or k == Layer.key.refines or getmetatable (v) == Reference or getmetatable (v) == Proxy or type (v) ~= "table" then t [k] = v elseif type (t [k]) == "table" then iterate (v, t [k]) else t [k] = {} iterate (v, t [k]) end end end source = Layer.hidden [source].layer iterate (Layer.hidden [source].data, target) end -- ---------------------------------------------------------------------- -- ## Observers -- ---------------------------------------------------------------------- local Observer = {} Observer.__index = Observer function Layer.observe (proxy, f) assert (getmetatable (proxy) == Proxy) assert (type (f) == "function" or (getmetatable (f) and getmetatable (f).__call)) local layer = Layer.hidden [proxy].layer local observer = setmetatable ({}, Observer) Layer.hidden [observer] = { layer = layer, handler = f, } return observer:enable () end function Observer.enable (observer) assert (getmetatable (observer) == Observer) local layer = Layer.hidden [observer].layer local info = Layer.hidden [layer] info.observers [observer] = true return observer end function Observer.disable (observer) assert (getmetatable (observer) == Observer) local layer = Layer.hidden [observer].layer local info = Layer.hidden [layer] info.observers [observer] = nil return observer end -- ---------------------------------------------------------------------- -- ## Proxies -- ---------------------------------------------------------------------- function Proxy.new (layer) assert (getmetatable (layer) == Layer) local proxy = setmetatable ({}, Proxy) Layer.hidden [proxy] = { layer = layer, keys = {}, parent = false, } return proxy end function Proxy.__tostring (proxy) assert (getmetatable (proxy) == Proxy) local result = {} local hidden = Layer.hidden [proxy] local keys = hidden.keys result [1] = tostring (hidden.layer) for i = 1, #keys do result [i+1] = "[" .. tostring (keys [i]) .. "]" end return table.concat (result, " ") end function Proxy.messages (proxy) assert (getmetatable (proxy) == Proxy) return Layer.messages [proxy] end function Proxy.child (proxy, key) assert (getmetatable (proxy) == Proxy) assert (key ~= nil) local found = Layer.children [proxy] and Layer.children [proxy] [key] if found then return found end local result = setmetatable ({}, Proxy) local hidden = Layer.hidden [proxy] local keys = {} for i, k in ipairs (hidden.keys) do keys [i] = k end keys [#keys+1] = key Layer.hidden [result] = { layer = hidden.layer, keys = keys, parent = proxy, } Layer.children [proxy] = Layer.children [proxy] or setmetatable ({}, IgnoreValues) Layer.children [proxy] [key] = result return result end function Proxy.check (proxy) assert (getmetatable (proxy) == Proxy) local cache = Layer.caches.check if cache [proxy] then return end cache [proxy] = true local hidden = Layer.hidden [proxy] for _, key in ipairs (hidden.keys) do if getmetatable (key) == Key then return end end local checks = proxy [Layer.key.checks] if not checks then return end local messages = Layer.messages [proxy] or {} for _, f in Proxy.__pairs (checks) do assert (type (f) == "function") local co = Layer.coroutine.wrap (function () return f (proxy) end) for id, data in co do messages [id] = data or {} end end if next (messages) then Layer.messages [proxy] = messages else Layer.messages [proxy] = nil end end function Proxy.check_all (proxy) assert (getmetatable (proxy) == Proxy) local seen = {} local function iterate (x) assert (getmetatable (x) == Proxy) seen [x] = true Proxy.check (x) for _, child in Layer.pairs (x) do if getmetatable (child) == Proxy and not seen [child] then iterate (child) end end end iterate (proxy) end function Proxy.__index (proxy, key) assert (getmetatable (proxy) == Proxy) local child = Proxy.child (proxy, key) local cached = Layer.caches.index [child] if cached == Layer.tag.null or cached == Layer.tag.computing then return nil elseif cached ~= nil then return cached end local result Layer.statistics.index [child] = (Layer.statistics.index [child] or 0) + 1 Layer.caches .index [child] = Layer.tag.computing if Proxy.exists (child) then for _, value in Proxy.dependencies (child) do if value ~= nil then if getmetatable (value) == Reference then result = Reference.resolve (value, child) elseif getmetatable (value) == Proxy then result = value elseif value == Layer.key.deleted then result = nil elseif type (value) == "table" then result = child else result = value end break end end end if result == nil then Layer.caches.index [child] = Layer.tag.null else Layer.caches.index [child] = result end if Layer.check and getmetatable (result) == Proxy then Proxy.check (result) end return result end function Proxy.raw (proxy) assert (getmetatable (proxy) == Proxy) local hidden = Layer.hidden [proxy] local layer = Layer.hidden [hidden.layer] local current = layer.data local keys = hidden.keys for _, key in ipairs (keys) do if type (current) == "table" and getmetatable (current) ~= Proxy and getmetatable (current) ~= Reference then current = current [key] else current = nil end end return current end function Proxy.__newindex (proxy, key, value) assert (getmetatable (proxy) == Proxy) assert ( type (key) ~= "table" or getmetatable (key) == Proxy or getmetatable (key) == Reference or getmetatable (key) == Key) local layer = Layer.hidden [proxy].layer local info = Layer.hidden [layer] local keys = Layer.hidden [proxy].keys local coroutine = Coromake () local observers = {} for observer in pairs (info.observers) do observers [observer] = assert (coroutine.create (Layer.hidden [observer].handler)) end local old_value = proxy [key] for _, co in pairs (observers) do assert (coroutine.resume (co, coroutine, proxy, key, old_value)) end if info.write_to then assert (info.write_to ~= false) local newp = info.write_to for _, k in ipairs (keys) do newp = Proxy.child (newp, k) end newp [key] = value else local current = info.data for _, k in ipairs (keys) do if current [k] == nil then current [k] = {} end current = current [k] end if value == nil then current [key] = Layer.key.deleted else current [key] = value end end local new_value = proxy [key] for _, co in pairs (observers) do coroutine.resume (co, new_value) end Layer.clear () if Layer.check then Proxy.check (proxy) end end function Proxy.keys (proxy) assert (getmetatable (proxy) == Proxy) local hidden = Layer.hidden [proxy] local coroutine = Coromake () return coroutine.wrap (function () for i, key in ipairs (hidden.keys) do coroutine.yield (i, key) end end) end function Proxy.exists (proxy) assert (getmetatable (proxy) == Proxy) if Layer.caches.exists [proxy] ~= nil then return Layer.caches.exists [proxy] end Layer.statistics.exists [proxy] = (Layer.statistics.exists [proxy] or 0) + 1 local result = false local hidden = Layer.hidden [proxy] if hidden.parent then for _, raw in Proxy.dependencies (hidden.parent) do if type (raw) == "table" and getmetatable (raw) ~= Proxy and getmetatable (raw) ~= Reference and raw [hidden.keys [#hidden.keys]] ~= nil then local value = raw [hidden.keys [#hidden.keys]] if getmetatable (value) == Reference then result = true else result = true end break end end else result = Proxy.raw (proxy) ~= nil and Proxy.raw (proxy) ~= Layer.key.deleted end Layer.caches.exists [proxy] = result return result end local function reverse (t) for i = 1, math.floor (#t / 2) do t [i], t [#t-i+1] = t [#t-i+1], t [i] end return t end function Proxy.dependencies (proxy) assert (getmetatable (proxy) == Proxy) local cache = Layer.caches.dependencies local result = cache [proxy] local dependencies_cache = setmetatable ({}, IgnoreKeys) local refines_cache = setmetatable ({}, IgnoreKeys) if result == nil then Layer.statistics.dependencies [proxy] = (Layer.statistics.dependencies [proxy] or 0) + 1 if Proxy.exists (proxy) then local refines, dependencies local c3 = C3 { superclass = function (p) return p and refines (p) or {} end, } dependencies = function (x) assert (getmetatable (x) == Proxy) local found = dependencies_cache [x] if found == Layer.tag.null then return nil elseif found ~= nil then assert (found ~= Layer.tag.computing) return found end dependencies_cache [x] = Layer.tag.computing local all = c3 (x) reverse (all) dependencies_cache [x] = all ~= nil and all or Layer.tag.null return all end refines = function (x) assert (getmetatable (x) == Proxy) local found = refines_cache [x] if found == Layer.tag.null then return nil elseif found ~= nil then assert (found ~= Layer.tag.computing) return found end refines_cache [x] = Layer.tag.computing local hidden = Layer.hidden [x] local raw = Proxy.raw (x) local all = {} local refinments = { refines = {}, parents = {}, } for _, key in ipairs (hidden.keys) do if key == Layer.key.defaults or key == Layer.key.refines then refines_cache [proxy] = all ~= nil and all or Layer.tag.null return all end end local in_special = getmetatable (hidden.keys [#hidden.keys]) == Key repeat if getmetatable (raw) == Proxy then raw = Proxy.raw (raw) elseif getmetatable (raw) == Reference then raw = Reference.resolve (raw, proxy) end until getmetatable (raw) ~= Proxy and getmetatable (raw) ~= Reference if type (raw) == "table" then for _, refine in ipairs (raw [Layer.key.refines] or {}) do refinments.refines [#refinments.refines+1] = refine end end if hidden.parent then local exists = Proxy.exists (x) local key = hidden.keys [#hidden.keys] local parents = {} for parent in Proxy.dependencies (hidden.parent) do parents [#parents+1] = parent end reverse (parents) for _, parent in ipairs (parents) do local child = Proxy.child (parent, key) if parent ~= hidden.parent and Proxy.exists (child) then refinments.parents [#refinments.parents+1] = child end local raw_parent = Proxy.raw (parent) if not in_special and exists and raw_parent then repeat if getmetatable (raw_parent) == Proxy then raw_parent = Proxy.raw (raw_parent) elseif getmetatable (raw_parent) == Reference then raw_parent = Reference.resolve (raw_parent, proxy) end until getmetatable (raw_parent) ~= Proxy and getmetatable (raw_parent) ~= Reference for _, default in ipairs (raw_parent and raw_parent [Layer.key.defaults] or {}) do refinments.parents [#refinments.parents+1] = default end end end end local parent = Layer.hidden [proxy].parent local flattened = {} local seen = { [x] = true, } for _, container in ipairs { refinments.parents, refinments.refines, } do for _, refine in ipairs (container) do while refine and getmetatable (refine) == Reference do refine = Reference.resolve (refine, parent) end if getmetatable (refine) == Proxy then flattened [#flattened+1] = refine end end end for i = #flattened, 1, -1 do local element = flattened [i] if not seen [element] then seen [element] = true all [#all+1 ] = element end end reverse (all) refines_cache [proxy] = all ~= nil and all or Layer.tag.null return all end result = dependencies (proxy) else result = {} end cache [proxy] = result end return coroutine.wrap (function () for _, x in ipairs (result) do coroutine.yield (x, Proxy.raw (x)) end end) end function Proxy.__lt (lhs, rhs) assert (getmetatable (lhs) == Proxy) assert (getmetatable (rhs) == Proxy) if not Layer.caches.lt [lhs] then Layer.caches.lt [lhs] = setmetatable ({}, IgnoreNone) end if Layer.caches.lt [lhs] [rhs] ~= nil then return Layer.caches.lt [lhs] [rhs] end for p in Proxy.dependencies (rhs, { all = true }) do if getmetatable (p) == Proxy and p == lhs then Layer.caches.lt [lhs] [rhs] = true return true end end Layer.caches.lt [lhs] [rhs] = false return false end function Proxy.__le (lhs, rhs) if lhs == rhs then return true else return Proxy.__lt (lhs, rhs) end end function Proxy.project (proxy, what) assert (getmetatable (proxy) == Proxy) assert (getmetatable (what ) == Proxy) local lhs_proxy = Layer.hidden [proxy] local rhs_proxy = Layer.hidden [what] local rhs_layer = Layer.hidden [rhs_proxy.layer] local result = rhs_layer.proxy for _, key in ipairs (lhs_proxy.keys) do result = type (result) == "table" and result [key] or nil end return result end function Proxy.parent (proxy) assert (getmetatable (proxy) == Proxy) local hidden = Layer.hidden [proxy] return hidden.parent end function Proxy.__len (proxy) assert (getmetatable (proxy) == Proxy) local cache = Layer.caches.len if cache [proxy] then return cache [proxy] end cache [proxy] = false for i = 1, math.huge do if proxy [i] == nil then cache [proxy] = i-1 return i-1 end end end function Proxy.__ipairs (proxy) assert (getmetatable (proxy) == Proxy) local cache = Layer.caches.ipairs if cache [proxy] then return coroutine.wrap (function () for i, v in ipairs (cache [proxy]) do coroutine.yield (i, v) end end) end Layer.statistics.ipairs [proxy] = (Layer.statistics.ipairs [proxy] or 0) + 1 cache [proxy] = {} local coroutine = Coromake () local cached = {} for i = 1, math.huge do local result = proxy [i] if result == nil then break end result = proxy [i] cached [i] = result end cache [proxy] = cached return coroutine.wrap (function () for i, result in ipairs (cache [proxy]) do coroutine.yield (i, result) end end) end function Proxy.__pairs (proxy) assert (getmetatable (proxy) == Proxy) local cache = Layer.caches.pairs if cache [proxy] then return coroutine.wrap (function () for k, v in pairs (cache [proxy]) do coroutine.yield (k, v) end end) end Layer.statistics.pairs [proxy] = (Layer.statistics.pairs [proxy] or 0) + 1 cache [proxy] = {} local coroutine = Coromake () local result = {} for _, current in Proxy.dependencies (proxy) do while getmetatable (current) == Reference do current = Reference.resolve (current, proxy) end local iter if getmetatable (current) == Proxy then iter = Proxy.__pairs elseif type (current) == "table" then iter = pairs end if iter then for k in iter (current) do if result [k] == nil and getmetatable (k) ~= Layer.Key then result [k] = proxy [k] end end end end cache [proxy] = result return coroutine.wrap (function () for k, v in pairs (result) do coroutine.yield (k, v) end end) end function Reference.new (target) local found = Layer.references [target] if found then return found end if type (target) == "string" then local result = setmetatable ({}, Reference) Layer.hidden [result] = { from = target, keys = {}, } Layer.references [target] = result return result elseif getmetatable (target) == Proxy then local label = Uuid () if not target [Layer.key.labels] then target [Layer.key.labels] = {} end target [Layer.key.labels] [label] = true local result = setmetatable ({}, Reference) Layer.hidden [result] = { from = label, keys = {}, } Layer.references [target] = result return result else assert (false) end end function Reference.__tostring (reference) assert (getmetatable (reference) == Reference) local hidden = Layer.hidden [reference] local result = {} result [1] = tostring (hidden.from) result [2] = "->" for i, key in ipairs (hidden.keys) do result [i+2] = "[" .. tostring (key) .. "]" end return table.concat (result, " ") end function Reference.__index (reference, key) if type (key) == "number" then assert (key < 10) end assert (getmetatable (reference) == Reference) local found = Layer.children [reference] and Layer.children [reference] [key] if found then return found end local hidden = Layer.hidden [reference] local keys = {} for i, k in ipairs (hidden.keys) do keys [i] = k end keys [#keys+1] = key local result = setmetatable ({}, Reference) Layer.hidden [result] = { parent = reference, from = hidden.from, keys = keys, } Layer.children [reference] = Layer.children [reference] or setmetatable ({}, IgnoreValues) Layer.children [reference] [key] = result return result end function Reference.resolve (reference, proxy) assert (getmetatable (reference) == Reference) if getmetatable (proxy) ~= Proxy then return nil end local cache = Layer.caches.resolve local cached = cache [proxy] and cache [proxy] [reference] if cached == Layer.tag.null or cached == Layer.tag.computing then return nil elseif cached then return cached end cache [proxy] = cache [proxy] or setmetatable ({}, IgnoreNone) local ref_hidden = Layer.hidden [reference] local current = proxy do while current do if current and current [Layer.key.labels] and current [Layer.key.labels] [ref_hidden.from] then break end current = Layer.hidden [current].parent end if not current then cache [proxy] [reference] = Layer.tag.null return nil end end for _, key in ipairs (ref_hidden.keys) do while getmetatable (current) == Reference do current = Reference.resolve (current, proxy) end if getmetatable (current) ~= Proxy then cache [proxy] [reference] = Layer.tag.null return nil end current = current [key] end cache [proxy] [reference] = current return current end Layer.Proxy = Proxy Layer.Reference = Reference Layer.Key = Key Layer.reference = Reference.new -- Lua 5.1 compatibility: Layer.len = Proxy.__len Layer.pairs = Proxy.__pairs Layer.ipairs = Proxy.__ipairs Layer.clear () return Layer
mit
nasomi/darkstar
scripts/zones/Castle_Zvahl_Baileys/Zone.lua
28
3517
----------------------------------- -- -- Zone: Castle_Zvahl_Baileys (161) -- ----------------------------------- package.loaded["scripts/zones/Castle_Zvahl_Baileys/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Castle_Zvahl_Baileys/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -90,17,45, -84,19,51); -- map 4 NW porter zone:registerRegion(1, 17,-90,45, -85,18,51); -- map 4 NW porter zone:registerRegion(2, -90,17,-10, -85,18,-5); -- map 4 SW porter zone:registerRegion(3, -34,17,-10, -30,18,-5); -- map 4 SE porter zone:registerRegion(4, -34,17,45, -30,18,51); -- map 4 NE porter -- Marquis Allocen SetRespawnTime(17436913, 900, 10800); -- Marquis Amon SetRespawnTime(17436918, 900, 10800); -- Duke Haborym SetRespawnTime(17436923, 900, 10800); -- Grand Duke Batym SetRespawnTime(17436927, 900, 10800); UpdateTreasureSpawnPoint(17436993); UpdateTreasureSpawnPoint(17436994); 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(-181.969,-35.542,19.995,254); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { --------------------------------- [1] = function (x) -- --------------------------------- player:startEvent(0x0003); -- ports player to NW room of map 3 end, --------------------------------- [2] = function (x) -- --------------------------------- player:startEvent(0x0002); -- ports player to SW room of map 3 end, --------------------------------- [3] = function (x) -- --------------------------------- player:startEvent(0x0001); -- ports player to SE room of map 3 end, --------------------------------- [4] = function (x) -- --------------------------------- player:startEvent(0x0000); -- ports player to NE room of map 3 end, default = function (x) --print("default"); end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/globals/mobskills/Havoc_Spiral.lua
25
1095
--------------------------------------------- -- Havoc Spiral -- -- Description: Deals damage to players in an area of effect. Additional effect: Sleep -- Type: Physical -- 2-3 Shadows -- Range: Unknown -- Special weaponskill unique to Ark Angel MR. Deals ~100-300 damage. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) -- TODO: Can skillchain? Unknown property. local numhits = 1; local accmod = 1; local dmgmod = 3; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_2_SHADOW); -- Witnessed 280 to a melee, 400 to a BRD, and 500 to a wyvern, so... target:delHP(dmg); MobStatusEffectMove(mob, target, EFFECT_SLEEP_I, 1, 0, math.random(30, 60)); return dmg; end;
gpl-3.0
nasomi/darkstar
scripts/globals/mobskills/Stun_Cannon.lua
17
1144
--------------------------------------------------- -- Stun_Cannon.lua -- -- Description: 20'(?) AoE ~300 magic damage and Paralysis, ignores Utsusemi -- Type: Magical -- -- Range: 20 yalms --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobID = mob:getID(); --(16908294 ,16908301 ,16908308 =omega ,16933124=proto-omega) local mobhp = mob:getHPP(); if (mobID == 16933124 and mobhp < 70 and mobhp > 30 ) then -- proto-omega bipedform return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = 1.5; local typeEffect = EFFECT_PARALYSIS; MobStatusEffectMove(mob, target, typeEffect, 20, 0, 120); local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_DARK,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end
gpl-3.0
nasomi/darkstar
scripts/zones/Apollyon/mobs/Carnagechief_Jackbodokk.lua
16
2435
----------------------------------- -- Area: Apollyon CS -- NPC: Carnagechief_Jackbodokk ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobID = mob:getID(); local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); SpawnMob(16933130):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933131):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933132):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local mobID = mob:getID(); local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100); local instancetime = target:getSpecialBattlefieldLeftTime(5); if (lifepourcent < 50 and GetNPCByID(16933245):getAnimation() == 8) then SpawnMob(16933134):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933135):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933133):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933136):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetNPCByID(16933245):setAnimation(9); end if (instancetime < 13) then if (IsMobDead(16933144)==false) then --link dee wapa GetMobByID(16933144):updateEnmity(target); elseif (IsMobDead(16933137)==false) then --link na qba GetMobByID(16933137):updateEnmity(target); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if ((IsMobDead(16933144)==false or IsMobDead(16933137)==false) and alreadyReceived(killer,1,GetInstanceRegion(1294)) == false) then killer:addTimeToSpecialBattlefield(5,5); addLimbusList(killer,1,GetInstanceRegion(1294)); end end;
gpl-3.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/statcollection/schema_examples/enfos.lua
5
5097
customSchema = class({}) function customSchema:init() -- Check the schema_examples folder for different implementations -- Flags statCollection:setFlags({ version = CEnfosGameMode:GetVersion() }) -- Listen for changes in the current state ListenToGameEvent('game_rules_state_change', function(keys) local state = GameRules:State_Get() -- Send custom stats when the game ends if state == DOTA_GAMERULES_STATE_POST_GAME then -- Build game array local game = BuildGameArray() -- Build players array local players = BuildPlayersArray() -- Print the schema data to the console if statCollection.TESTING then PrintSchema(game, players) end -- Send custom stats if statCollection.HAS_SCHEMA then statCollection:sendCustom({ game = game, players = players }) end end end, nil) end ------------------------------------- -- In the statcollection/lib/utilities.lua, you'll find many useful functions to build your schema. -- You are also encouraged to call your custom mod-specific functions -- Returns a table with our custom game tracking. function BuildGameArray() local game = {} -- Add game values here as game.someValue = GetSomeGameValue() game.r = Enfos.curRound return game end -- Returns a table containing data for every player in the game function BuildPlayersArray() local players = {} for playerID = 0, DOTA_MAX_PLAYERS do if PlayerResource:IsValidPlayerID(playerID) then if not PlayerResource:IsBroadcaster(playerID) then local hero = PlayerResource:GetSelectedHeroEntity(playerID) table.insert(players, { -- steamID32 required in here steamID32 = PlayerResource:GetSteamAccountID(playerID), -- Example functions for generic stats are defined in statcollection/lib/utilities.lua -- Add player values here as someValue = GetSomePlayerValue(), hn = GetHeroName(playerID), -- name hl = hero:GetLevel(), -- level hnw = GetNetworth(PlayerResource:GetSelectedHeroEntity(playerID)), -- Networth pt = GetPlayerTeam(PlayerResource:GetSelectedHeroEntity(playerID)), -- Hero's team pk = hero:GetKills(), -- Kills pa = hero:GetAssists(), -- Assists pd = hero:GetDeaths(), -- Deaths plh = PlayerResource:GetLastHits(hero:GetPlayerOwnerID()), -- Last hits ph = PlayerResource:GetHealing(hero:GetPlayerOwnerID()), -- Healing pgpm = math.floor(PlayerResource:GetGoldPerMin(hero:GetPlayerOwnerID())), -- GPM il = GetItemList(hero) -- Item list }) end end end return players end -- Prints the custom schema, required to get an schemaID function PrintSchema(gameArray, playerArray) print("-------- GAME DATA --------") DeepPrintTable(gameArray) print("\n-------- PLAYER DATA --------") DeepPrintTable(playerArray) print("-------------------------------------") end -- Write 'test_schema' on the console to test your current functions instead of having to end the game if Convars:GetBool('developer') then Convars:RegisterCommand("test_schema", function() PrintSchema(BuildGameArray(), BuildPlayersArray()) end, "Test the custom schema arrays", 0) end ------------------------------------- -- If your gamemode is round-based, you can use statCollection:submitRound(bLastRound) at any point of your main game logic code to send a round -- If you intend to send rounds, make sure your settings.kv has the 'HAS_ROUNDS' set to true. Each round will send the game and player arrays defined earlier -- The round number is incremented internally, lastRound can be marked to notify that the game ended properly function customSchema:submitRound(isLastRound) local winners = BuildRoundWinnerArray() local game = BuildGameArray() local players = BuildPlayersArray() statCollection:sendCustom({ game = game, players = players }) isLastRound = isLastRound or false --If the function is passed with no parameter, default to false. return { winners = winners, lastRound = isLastRound } end -- A list of players marking who won this round function BuildRoundWinnerArray() local winners = {} local current_winner_team = GameRules.Winner or 0 --You'll need to provide your own way of determining which team won the round for playerID = 0, DOTA_MAX_PLAYERS do if PlayerResource:IsValidPlayerID(playerID) then if not PlayerResource:IsBroadcaster(playerID) then winners[PlayerResource:GetSteamAccountID(playerID)] = (PlayerResource:GetTeam(playerID) == current_winner_team) and 1 or 0 end end end return winners end -------------------------------------
mit
nasomi/darkstar
scripts/zones/Lower_Jeuno/npcs/_l00.lua
36
1563
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -109.065 0 -158.032 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 11) then player:setVar("cService",12); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 24) then player:setVar("cService",25); end end end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
srush/OpenNMT
onmt/utils/Cuda.lua
4
1893
require('nn') require('nngraph') local Cuda = { activated = false } function Cuda.init(opt, gpuIdx) Cuda.activated = opt.gpuid > 0 if Cuda.activated then local _, err = pcall(function() require('cutorch') require('cunn') if gpuIdx == nil then -- allow memory access between devices cutorch.getKernelPeerToPeerAccess(true) if opt.seed then cutorch.manualSeedAll(opt.seed) end cutorch.setDevice(opt.gpuid) else cutorch.setDevice(gpuIdx) end if opt.seed then cutorch.manualSeed(opt.seed) end end) if err then error(err) end end end --[[ Recursively move all supported objects in `obj` on the GPU. When using CPU only, converts to float instead of the default double. ]] function Cuda.convert(obj) if torch.typename(obj) then if Cuda.activated and obj.cuda ~= nil then return obj:cuda() elseif not Cuda.activated and obj.float ~= nil then -- Defaults to float instead of double. return obj:float() end end if torch.typename(obj) or type(obj) == 'table' then for k, v in pairs(obj) do obj[k] = Cuda.convert(v) end end return obj end function Cuda.getGPUs(ngpu) local gpus = {} if Cuda.activated then if ngpu > cutorch.getDeviceCount() then error("not enough available GPU - " .. ngpu .. " requested, " .. cutorch.getDeviceCount() .. " available") end gpus[1] = Cuda.gpuid local i = 1 while #gpus ~= ngpu do if i ~= gpus[1] then table.insert(gpus, i) end i = i + 1 end else for _ = 1, ngpu do table.insert(gpus, 0) end end return gpus end function Cuda.freeMemory() if Cuda.activated then local freeMemory = cutorch.getMemoryUsage(cutorch.getDevice()) return freeMemory end return 0 end return Cuda
mit
nasomi/darkstar
scripts/zones/Norg/npcs/HomePoint#2.lua
19
1167
----------------------------------- -- Area: Norg -- NPC: HomePoint#2 -- @pos -65 -5 54 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Norg/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 104); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
luanorlandi/SwiftSpaceBattle
src/interface/game/borderHp.lua
2
1113
local borderHpDeck = MOAIGfxQuad2D.new() borderHpDeck:setTexture("texture/effect/borderhp.png") borderHpDeck:setRect(-window.width/2, -window.height/2, window.width/2, window.height/2) BorderHp = {} BorderHp.__index = BorderHp function BorderHp:new() local B = {} setmetatable(B, BorderHp) B.active = true B.sprite = MOAIProp2D.new() changePriority(B.sprite, "interface") B.sprite:setDeck(borderHpDeck) B.sprite:setLoc(0, 0) window.layer:insertProp(B.sprite) B.thread = coroutine.create(function() B:showBorderHp() end) coroutine.resume(B.thread) return B end function BorderHp:showBorderHp() self.sprite:setBlendMode(MOAIProp.GL_SRC_ALPHA, MOAIProp.GL_ONE_MINUS_SRC_ALPHA) -- start invisible self.sprite:setColor(1, 1, 1, 0) while self.active do coroutine.yield() local hpPercentage = player.hp / player.maxHp if hpPercentage > 1 then hpPercentage = 1 end if hpPercentage < 0 then hpPercentage = 0 end hpPercentage = 1 - hpPercentage self.sprite:setColor(1, 1, 1, hpPercentage) end end function BorderHp:clear() window.layer:removeProp(self.sprite) end
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/water_surface_33.meta.lua
66
1953
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "122 171 252 255", "118 168 252 255", "103 159 251 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/water_surface_26.meta.lua
66
1953
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "122 171 252 255", "118 168 252 255", "103 159 251 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/water_surface_5.meta.lua
66
1953
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "122 171 252 255", "118 168 252 255", "103 159 251 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/water_surface_28.meta.lua
66
1953
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "122 171 252 255", "118 168 252 255", "103 159 251 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
ngeiswei/ardour
share/scripts/s_vamp_plugin_index.lua
6
1336
ardour { ["type"] = "Snippet", name = "Vamp Plugin List" } function factory () return function () local plugins = ARDOUR.LuaAPI.Vamp.list_plugins (); for id in plugins:iter () do local vamp = ARDOUR.LuaAPI.Vamp(id, Session:nominal_sample_rate()) local vp = vamp:plugin () print (" --- VAMP Plugin ---") print ("Id:", vp:getIdentifier ()) print ("Name:", vp:getName ()) print ("Description:", vp:getDescription ()) local progs = vp:getPrograms(); if not progs:empty () then print ("Preset(s):") for p in progs:iter () do print (" *", p) end end local params = vp:getParameterDescriptors () if not params:empty () then print ("Parameters(s):") for p in params:iter () do -- http://manual.ardour.org/lua-scripting/class_reference/#Vamp:PluginBase:ParameterDescriptor print (" * Id:", p.identifier, "Name:", p.name, "Desc:", p.description) local i = 0; for vn in p.valueNames:iter() do print (" ^^ ", i, " -> ", vn) i = i + 1 end end end local feats = vp:getOutputDescriptors () if not feats:empty () then print ("Output(s):") for p in feats:iter () do -- http://manual.ardour.org/lua-scripting/class_reference/#Vamp:Plugin:OutputDescriptor print (" * Id:", p.identifier, "Name:", p.name, "Desc:", p.description) end end end end end
gpl-2.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/statcollection/schema.lua
1
4744
customSchema = class({}) function customSchema:init() -- Check the schema_examples folder for different implementations --Flag Example -- Doing this in OnGameInProgress because this doesnt work here --statCollection:setFlags(GameMode.flags) --[[ Data GameMode.flags = { version = SMASHVERSION, HeroSelection = CustomNetTables:GetTableValue("settings","HeroSelection").value, Format = CustomNetTables:GetTableValue("settings","Format").value, } ]] -- Listen for changes in the current state ListenToGameEvent('game_rules_state_change', function(keys) local state = GameRules:State_Get() -- Send custom stats when the game ends if state == DOTA_GAMERULES_STATE_POST_GAME then -- Build game array local game = BuildGameArray() -- Build players array local players = BuildPlayersArray() -- Print the schema data to the console if statCollection.TESTING then PrintSchema(game, players) end -- Send custom stats if statCollection.HAS_SCHEMA then statCollection:sendCustom({ game = game, players = players }) end end end, nil) -- Write 'test_schema' on the console to test your current functions instead of having to end the game if Convars:GetBool('developer') then Convars:RegisterCommand("test_schema", function() PrintSchema(BuildGameArray(), BuildPlayersArray()) end, "Test the custom schema arrays", 0) Convars:RegisterCommand("test_end_game", function() GameRules:SetGameWinner(DOTA_TEAM_GOODGUYS) end, "Test the end game", 0) end end ------------------------------------- -- In the statcollection/lib/utilities.lua, you'll find many useful functions to build your schema. -- You are also encouraged to call your custom mod-specific functions -- Returns a table with our custom game tracking. function BuildGameArray() local game = {} -- Add game values here as game.someValue = GetSomeGameValue() game.Lifes = CustomNetTables:GetTableValue("settings","nStartingLifes").value game.map = CustomNetTables:GetTableValue("settings","map").value return game end -- Returns a table containing data for every player in the game function BuildPlayersArray() local players = {} for playerID = 0, DOTA_MAX_PLAYERS do if PlayerResource:IsValidPlayerID(playerID) then if not PlayerResource:IsBroadcaster(playerID) then local hero = PlayerResource:GetSelectedHeroEntity(playerID) table.insert(players, { -- steamID32 required in here steamID32 = PlayerResource:GetSteamAccountID(playerID), -- Example functions for generic stats are defined in statcollection/lib/utilities.lua -- Add player values here as someValue = GetSomePlayerValue(), hn = GetHeroName(playerID) }) end end end return players end -- Prints the custom schema, required to get an schemaID function PrintSchema(gameArray, playerArray) print("-------- GAME DATA --------") DeepPrintTable(gameArray) print("\n-------- PLAYER DATA --------") DeepPrintTable(playerArray) print("-------------------------------------") end ------------------------------------- -- If your gamemode is round-based, you can use statCollection:submitRound(bLastRound) at any point of your main game logic code to send a round -- If you intend to send rounds, make sure your settings.kv has the 'HAS_ROUNDS' set to true. Each round will send the game and player arrays defined earlier -- The round number is incremented internally, lastRound can be marked to notify that the game ended properly function customSchema:submitRound() local winners = BuildRoundWinnerArray() local game = BuildGameArray() local players = BuildPlayersArray() statCollection:sendCustom({ game = game, players = players }) end -- A list of players marking who won this round function BuildRoundWinnerArray() local winners = {} local current_winner_team = GameRules.Winner or 0 --You'll need to provide your own way of determining which team won the round for playerID = 0, DOTA_MAX_PLAYERS do if PlayerResource:IsValidPlayerID(playerID) then if not PlayerResource:IsBroadcaster(playerID) then winners[PlayerResource:GetSteamAccountID(playerID)] = (PlayerResource:GetTeam(playerID) == current_winner_team) and 1 or 0 end end end return winners end -------------------------------------
mit
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/metropolis_torso_rifle_gtm_2.meta.lua
2
2804
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.43000000715255737, amplification = 140, light_colors = { "89 31 168 255", "48 42 88 255", "61 16 123 0" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -13, y = -12 }, rotation = 41 }, head = { pos = { x = -2, y = 2 }, rotation = 19.133642196655273 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 3, y = 20 }, rotation = -10 }, secondary_hand = { pos = { x = 41, y = 14 }, rotation = 0 }, secondary_shoulder = { pos = { x = -11, y = 20 }, rotation = -140 }, shoulder = { pos = { x = 12, y = -15 }, rotation = -139 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/steel_shell.meta.lua
2
1951
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "255 255 255 255", "193 177 85 255", "202 185 89 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/zones/Palborough_Mines/npcs/Treasure_Chest.lua
19
2656
----------------------------------- -- Area: Palborough Mines -- NPC: Treasure Chest -- @zone 143 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Palborough_Mines/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1025,1); -- Treasure Key --trade:hasItemQty(1115,1); -- Skeleton Key --trade:hasItemQty(1023,1); -- Living Key --trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1025,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1025); 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
nasomi/darkstar
scripts/globals/abilities/tabula_rasa.lua
28
1290
----------------------------------- -- Ability: Tabula Rasa -- Optimizes both white and black magic capabilities while allowing charge-free stratagem use. -- Obtained: Scholar Level 1 -- Recast Time: 1:00:00 -- Duration: 0:03:00 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local regenbonus = 0; if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then regenbonus = 3 * math.floor((player:getMainLvl() - 10) / 10); end local helixbonus = 0; if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then helixbonus = math.floor(player:getMainLvl() / 4); end player:resetRecast(RECAST_ABILITY, 228); player:resetRecast(RECAST_ABILITY, 231); player:resetRecast(RECAST_ABILITY, 232); player:addStatusEffect(EFFECT_TABULA_RASA,math.floor(helixbonus*1.5),0,180,0,math.floor(regenbonus*1.5)); return EFFECT_TABULA_RASA; end;
gpl-3.0
appaquet/torch-android
src/pkg/torch/FFI.lua
2
5232
local ok, ffi = pcall(require, 'ffi') if ok then local Real2real = { Byte='unsigned char', Char='char', Short='short', Int='int', Long='long', Float='float', Double='double' } -- Allocator ffi.cdef[[ typedef struct THAllocator { void* (*malloc)(void*, long); void* (*realloc)(void*, void*, long); void (*free)(void*, void*); } THAllocator; ]] -- Storage for Real, real in pairs(Real2real) do local cdefs = [[ typedef struct THRealStorage { real *data; long size; int refcount; char flag; THAllocator *allocator; void *allocatorContext; } THRealStorage; ]] cdefs = cdefs:gsub('Real', Real):gsub('real', real) ffi.cdef(cdefs) local Storage = torch.getmetatable(string.format('torch.%sStorage', Real)) local Storage_tt = ffi.typeof('TH' .. Real .. 'Storage**') rawset(Storage, "cdata", function(self) return Storage_tt(self)[0] end) rawset(Storage, "data", function(self) return Storage_tt(self)[0].data end) end -- Tensor for Real, real in pairs(Real2real) do local cdefs = [[ typedef struct THRealTensor { long *size; long *stride; int nDimension; THRealStorage *storage; long storageOffset; int refcount; char flag; } THRealTensor; ]] cdefs = cdefs:gsub('Real', Real):gsub('real', real) ffi.cdef(cdefs) local Tensor = torch.getmetatable(string.format('torch.%sTensor', Real)) local Tensor_tt = ffi.typeof('TH' .. Real .. 'Tensor**') rawset(Tensor, "cdata", function(self) if not self then return nil; end return Tensor_tt(self)[0] end) rawset(Tensor, "data", function(self) if not self then return nil; end self = Tensor_tt(self)[0] return self.storage ~= nil and self.storage.data + self.storageOffset or nil end) -- faster apply (contiguous case) local apply = Tensor.apply rawset(Tensor, "apply", function(self, func) if self:isContiguous() and self.data then local self_d = self:data() for i=0,self:nElement()-1 do local res = func(tonumber(self_d[i])) -- tonumber() required for long... if res then self_d[i] = res end end return self else return apply(self, func) end end) -- faster map (contiguous case) local map = Tensor.map rawset(Tensor, "map", function(self, src, func) if self:isContiguous() and src:isContiguous() and self.data and src.data then local self_d = self:data() local src_d = src:data() assert(src:nElement() == self:nElement(), 'size mismatch') for i=0,self:nElement()-1 do local res = func(tonumber(self_d[i]), tonumber(src_d[i])) -- tonumber() required for long... if res then self_d[i] = res end end return self else return map(self, src, func) end end) -- faster map2 (contiguous case) local map2 = Tensor.map2 rawset(Tensor, "map2", function(self, src1, src2, func) if self:isContiguous() and src1:isContiguous() and src2:isContiguous() and self.data and src1.data and src2.data then local self_d = self:data() local src1_d = src1:data() local src2_d = src2:data() assert(src1:nElement() == self:nElement(), 'size mismatch') assert(src2:nElement() == self:nElement(), 'size mismatch') for i=0,self:nElement()-1 do local res = func(tonumber(self_d[i]), tonumber(src1_d[i]), tonumber(src2_d[i])) -- tonumber() required for long... if res then self_d[i] = res end end return self else return map2(self, src1, src2, func) end end) end -- torch.data -- will fail if :data() is not defined function torch.data(self, asnumber) if not self then return nil; end local data = self:data() if asnumber then return ffi.cast('intptr_t', data) else return data end end -- torch.cdata -- will fail if :cdata() is not defined function torch.cdata(self, asnumber) if not self then return nil; end local cdata = self:cdata() if asnumber then return ffi.cast('intptr_t', cdata) else return cdata end end end
bsd-3-clause
ngeiswei/ardour
share/scripts/send_to_bus.lua
2
1466
ardour { ["type"] = "EditorAction", name = "Send Tracks to Bus", license = "MIT", author = "Ardour Team", description = [[Create a Bus and add aux-sends from all selected tracks]] } function factory () return function () -- find number of channels to use for the new bus, follow master-bus' inputs local chn = 2 local mst = Session:master_out (); if not mst:isnil () then chn = mst:n_inputs ():n_audio () end mst = nil -- explicitly drop reference if chn == 0 then chn = 2; end local sel = Editor:get_selection () -- get selection local tracks = ARDOUR.RouteListPtr () -- create a new list -- find selected *tracks*, add to tracks list for r in sel.tracks:routelist ():iter () do if not r:to_track ():isnil () then tracks:push_back (r) end end if tracks:size () > 0 then local bus = Session:new_audio_route (chn, chn, nil, 1, "", ARDOUR.PresentationInfo.Flag.AudioBus, ARDOUR.PresentationInfo.max_order) if bus:size () > 0 then Session:add_internal_sends (bus:front (), ARDOUR.Placement.PostFader, tracks); end end end end function icon (params) return function (ctx, width, height, fg) local txt = Cairo.PangoLayout (ctx, "ArdourMono ".. math.ceil (math.min (width, height) * .5) .. "px") txt:set_text ("\u{2192}B") -- "->B" local tw, th = txt:get_pixel_size () ctx:move_to (.5 * (width - tw), .5 * (height - th)) ctx:set_source_rgba (ARDOUR.LuaAPI.color_to_rgba (fg)) txt:show_in_cairo_context (ctx) end end
gpl-2.0
nasomi/darkstar
scripts/globals/items/crawler_egg.lua
35
1201
----------------------------------------- -- ID: 4357 -- Item: crawler_egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 10 -- Magic 10 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4357); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); end;
gpl-3.0
thesabbir/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/ping.lua
69
1137
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
apache-2.0
coolflyreg/gs
3rd/skynet-mingw/examples/share.lua
66
1702
local skynet = require "skynet" local sharedata = require "sharedata" local mode = ... if mode == "host" then skynet.start(function() skynet.error("new foobar") sharedata.new("foobar", { a=1, b= { "hello", "world" } }) skynet.fork(function() skynet.sleep(200) -- sleep 2s skynet.error("update foobar a = 2") sharedata.update("foobar", { a =2 }) skynet.sleep(200) -- sleep 2s skynet.error("update foobar a = 3") sharedata.update("foobar", { a = 3, b = { "change" } }) skynet.sleep(100) skynet.error("delete foobar") sharedata.delete "foobar" end) end) else skynet.start(function() skynet.newservice(SERVICE_NAME, "host") local obj = sharedata.query "foobar" local b = obj.b skynet.error(string.format("a=%d", obj.a)) for k,v in ipairs(b) do skynet.error(string.format("b[%d]=%s", k,v)) end -- test lua serialization local s = skynet.packstring(obj) local nobj = skynet.unpack(s) for k,v in pairs(nobj) do skynet.error(string.format("nobj[%s]=%s", k,v)) end for k,v in ipairs(nobj.b) do skynet.error(string.format("nobj.b[%d]=%s", k,v)) end for i = 1, 5 do skynet.sleep(100) skynet.error("second " ..i) for k,v in pairs(obj) do skynet.error(string.format("%s = %s", k , tostring(v))) end end local ok, err = pcall(function() local tmp = { b[1], b[2] } -- b is invalid , so pcall should failed end) if not ok then skynet.error(err) end -- obj. b is not the same with local b for k,v in ipairs(obj.b) do skynet.error(string.format("b[%d] = %s", k , tostring(v))) end collectgarbage() skynet.error("sleep") skynet.sleep(100) b = nil collectgarbage() skynet.error("sleep") skynet.sleep(100) skynet.exit() end) end
gpl-2.0
nasomi/darkstar
scripts/globals/spells/bluemagic/yawn.lua
17
1611
----------------------------------------- -- Spell: Yawn -- Puts all enemies within range to sleep -- Spell cost: 55 MP -- Monster Type: Birds -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: CHR+1, HP+5 -- Level: 64 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Duration: 90 seconds -- Magic Bursts on: Transfixion, Fusion, Light -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_SLEEP_II; local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,typeEffect); local duration = 90 * resist; if (resist > 0.5) then -- Do it! if ((target:isFacing(caster))) then -- TODO: Apparently this check shouldn't exist for enemies using this spell? Need more info. if (target:addStatusEffect(typeEffect,2,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end; else spell:setMsg(75); end; else spell:setMsg(85); end; return typeEffect; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Duke_Gomory.lua
16
1252
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Duke Gomory ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if (mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 2; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if (Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if (Animate_Trigger == 32767) then killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
exitunlimited/Exit-Unlimited
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
m13790115/eset
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
nasomi/darkstar
scripts/globals/spells/ionohelix.lua
9
1732
-------------------------------------- -- Spell: Ionohelix -- Deals lightning damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); -- calculate raw damage local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); -- get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3); -- get the resisted damage dmg = dmg*resist; -- add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); -- add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); local dot = dmg; -- add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); -- calculate Damage over time dot = target:magicDmgTaken(dot); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); if (dot > 0) then target:addStatusEffect(EFFECT_HELIX,dot,3,duration); end; return dmg; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Upper_Jeuno/npcs/Zekobi-Morokobi.lua
38
1038
----------------------------------- -- Area: Upper Jeuno -- NPC: Zekobi-Morokobi -- Type: Standard NPC -- @zone: 244 -- @pos 41.258 -5.999 -74.105 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0057); 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
nasomi/darkstar
scripts/zones/Dangruf_Wadi/npcs/Grounds_Tome.lua
34
1133
----------------------------------- -- Area: Dangruf Wadi -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_DANGRUF_WADI,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,639,640,641,642,643,644,645,646,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,639,640,641,642,643,644,645,646,0,0,GOV_MSG_DANGRUF_WADI); end;
gpl-3.0
thesabbir/luci
libs/luci-lib-nixio/docsrc/nixio.TLSSocket.lua
173
2926
--- TLS Socket Object. -- TLS Sockets contain the underlying socket and context in the fields -- "socket" and "context". -- @cstyle instance module "nixio.TLSSocket" --- Initiate the TLS handshake as client with the server. -- @class function -- @name TLSSocket.connect -- @usage This function calls SSL_connect(). -- @usage You have to call either connect or accept before transmitting data. -- @see TLSSocket.accept -- @return true --- Wait for a TLS handshake from a client. -- @class function -- @name TLSSocket.accept -- @usage This function calls SSL_accept(). -- @usage You have to call either connect or accept before transmitting data. -- @see TLSSocket.connect -- @return true --- Send a message to the socket. -- @class function -- @name TLSSocket.send -- @usage This function calls SSL_write(). -- @usage <strong>Warning:</strong> It is not guaranteed that all data -- in the buffer is written at once. -- You have to check the return value - the number of bytes actually written - -- or use the safe IO functions in the high-level IO utility module. -- @usage Unlike standard Lua indexing the lowest offset and default is 0. -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @return number of bytes written --- Send a message on the socket (This is an alias for send). -- See the send description for a detailed description. -- @class function -- @name TLSSocket.write -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @see TLSSocket.send -- @return number of bytes written --- Receive a message on the socket. -- @class function -- @name TLSSocket.recv -- @usage This function calls SSL_read(). -- @usage <strong>Warning:</strong> It is not guaranteed that all requested data -- is read at once. -- You have to check the return value - the length of the buffer actually read - -- or use the safe IO functions in the high-level IO utility module. -- @usage The length of the return buffer is limited by the (compile time) -- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default). -- Any read request greater than that will be safely truncated to this value. -- @param length Amount of data to read (in Bytes). -- @return buffer containing data successfully read --- Receive a message on the socket (This is an alias for recv). -- See the recv description for more details. -- @class function -- @name TLSSocket.read -- @param length Amount of data to read (in Bytes). -- @see TLSSocket.recv -- @return buffer containing data successfully read --- Shut down the TLS connection. -- @class function -- @name TLSSocket.shutdown -- @usage This function calls SSL_shutdown(). -- @return true
apache-2.0
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/Liloune.lua
36
1373
----------------------------------- -- Area: Port San d'Oria -- NPC: Liloune -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x252); 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
nasomi/darkstar
scripts/zones/Castle_Oztroja/npcs/_m75.lua
16
2231
----------------------------------- -- 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"); ----------------------------------- -- onTrigger Action ----------------------------------- 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(0x000a); else player:messageSpecial(TORCH_LIT); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (option == 1) then GetNPCByID(Torch4):openDoor(55); if ((DoorA == 9) and (TorchStand1A == 8) and (TorchStand2A == 8) and (TorchStand3A == 8)) 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
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Pepigort.lua
38
1027
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pepigort -- Type: Standard Dialogue NPC -- @zone: 231 -- @pos -126.739 11.999 262.757 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PEPIGORT_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/statcollection/schema_examples/pmp.lua
5
4723
customSchema = class({}) function customSchema:init(options) -- Flags statCollection:setFlags({ version = GetVersion() }) -- Listen for changes in the current state ListenToGameEvent('game_rules_state_change', function(keys) -- Grab the current state local state = GameRules:State_Get() if state == DOTA_GAMERULES_STATE_POST_GAME then -- Build game array local game = BuildGameArray() -- Build players array local players = BuildPlayersArray() -- Send custom stats statCollection:sendCustom({ game = game, players = players }) end end, nil) end function customSchema:submitRound(args) winners = BuildRoundWinnerArray() game = BuildGameArray() players = BuildPlayersArray() statCollection:sendCustom({ game = game, players = players }) return { winners = winners, lastRound = false } end ------------------------------------- function BuildRoundWinnerArray() local winners = {} local current_winner_team = GameRules.Winner or 0 for playerID = 0, DOTA_MAX_PLAYERS do if PlayerResource:IsValidPlayerID(playerID) then if not PlayerResource:IsBroadcaster(playerID) then winners[PlayerResource:GetSteamAccountID(playerID)] = (PlayerResource:GetTeam(playerID) == current_winner_team) and 1 or 0 end end end return winners end function BuildGameArray() local game = {} game.bk = GetBossKilled() --boss_killed game.tt = GetTimesTraded() --times_traded return game end function BuildPlayersArray() players = {} for playerID = 0, DOTA_MAX_PLAYERS do if PlayerResource:IsValidPlayerID(playerID) then if not PlayerResource:IsBroadcaster(playerID) then local player_upgrades = PMP:GetUpgradeList(playerID) table.insert(players, { --steamID32 required in here steamID32 = PlayerResource:GetSteamAccountID(playerID), ph = GetPlayerRace(playerID), --player_hero pk = PlayerResource:GetKills(playerID), --player_kills pd = PlayerResource:GetDeaths(playerID), --player_deaths pl = GetHeroLevel(playerID), --player_level -- Resources tge = GetTotalEarnedGold(playerID), --total_gold_earned tle = GetTotalEarnedLumber(playerID), --total_lumber_earned txe = GetTotalEarnedXP(playerID), --total_xp_earned pf = GetFoodLimit(playerID), --player_food psr = GetSpawnRate(playerID), --player_spawn_rate -- Defensive abilities spu = GetSuperPeonsUsed(playerID), --super_peons_used bu = GetBarricadesUsed(playerID), --barricades_used ru = GetRepairsUsed(playerID), --repairs_used -- Upgrades uw = GetPlayerWeaponLevel(playerID), --upgrade_weapon uh = player_upgrades["helm"] or 0, --upgrade_helm ua = player_upgrades["armor"] or 0, --upgrade_armor uw = player_upgrades["wings"] or 0, --upgrade_wings uhp = player_upgrades["health"] or 0, --upgrade_health -- Passive ability upgrades acs = player_upgrades["critical_strike"] or 0, --ability_critical_strike ash = player_upgrades["stun_hit"] or 0, --ability_stun_hit apw = player_upgrades["poisoned_weapons"] or 0, --ability_poisoned_weapons ar = player_upgrades["racial"] or 0, --ability_racial ad = player_upgrades["dodge"] or 0, --ability_dodge asa = player_upgrades["spiked_armor"] or 0, --ability_spiked_armor -- Hero global upgrades pdmg = player_upgrades["pimp_damage"] or 0, --pimp_damage parm = player_upgrades["pimp_armor"] or 0, --pimp_armor pspd = player_upgrades["pimp_speed"] or 0, --pimp_speed preg = player_upgrades["pimp_regen"] or 0, --pimp_regen }) end end end return players end function GetPlayerWeaponLevel(playerID) local player_upgrades = PMP:GetUpgradeList(playerID) local race = GetPlayerRace(playerID) local weapon_level = 0 if race == "night_elf" then weapon_level = player_upgrades["bow"] + player_upgrades["quiver"] else weapon_level = player_upgrades["weapon"] end return weapon_level end
mit
nasomi/darkstar
scripts/globals/items/goblin_pie.lua
35
1579
----------------------------------------- -- ID: 4539 -- Item: goblin_pie -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 12 -- Magic 12 -- Dexterity -1 -- Agility 3 -- Vitality -1 -- Charisma -5 -- Defense % 9 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4539); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 12); target:addMod(MOD_MP, 12); target:addMod(MOD_DEX, -1); target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -1); target:addMod(MOD_CHR, -5); target:addMod(MOD_DEFP, 9); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 12); target:delMod(MOD_MP, 12); target:delMod(MOD_DEX, -1); target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -1); target:delMod(MOD_CHR, -5); target:delMod(MOD_DEFP, 9); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Maze_of_Shakhrami/npcs/Ahko_Mhalijikhari.lua
20
1928
----------------------------------- -- Area: Maze of Shakhrami -- NPC: Ahko Mhalijikhari -- Type: Quest NPC -- @pos -344.617 -12.226 -166.233 198 -- 0x003d 0x003e 0x003f 0x0040 0x0041 ----------------------------------- package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Maze_of_Shakhrami/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:startEvent(0x0040); if (player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN) ~= QUEST_AVAILABLE and player:getVar("ECO_WARRIOR_ACTIVE") == 238) then if (player:hasKeyItem(INDIGESTED_MEAT)) then player:startEvent(0x0041); -- After NM's dead elseif (player:hasStatusEffect(EFFECT_LEVEL_RESTRICTION) == false) then player:startEvent(0x003e); -- else player:startEvent(0x0040); end else player:startEvent(0x003d); -- default end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x003e and option == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,20,0,0); elseif (csid == 0x0041) then player:setVar("ECOR_WAR_WIN-NMs_killed",0); player:delStatusEffect(EFFECT_LEVEL_RESTRICTION); elseif (csid == 0x0040) then player:delStatusEffect(EFFECT_LEVEL_RESTRICTION); end end;
gpl-3.0
akornatskyy/lucid
spec/routing/routes/plain_spec.lua
1
2751
local plain = require 'routing.routes.plain' local assert, describe, it = assert, describe, it local new = plain.new describe('plain route', function() describe('builder', function() it('supports alphanumeric characters', function() assert(new('abc123')) end) it('supports dash, slash and dot characters', function() assert(new('/hello/world')) assert(new('hello-world')) assert(new('hello.world')) end) it('does not support some characters', function() assert.is_nil(new('~hello')) assert.is_nil(new('#hello')) end) end) describe('finishing strategy', function() local r = new('/', true) it('supports empty pattern', function() assert.has_nil(new('').match) end) describe('exact matches', function() it('fallback to empty table if args is nil', function() assert.same({['/'] = {}}, r.exact_matches) end) it('supports extra args', function() r = new('/', true, {event_type='task'}) assert.same({['/'] = {event_type='task'}}, r.exact_matches) end) end) describe('match', function() it('not supported since replaced by exact matches', function() assert.has_nil(r.match) end) end) end) describe('starts with strategy', function() local r = new('/welcome', false) describe('exact matches', function() it('fallback to empty table if args is nil', function() assert.same({['/welcome'] = {}}, r.exact_matches) end) it('supports extra args', function() r = new('/welcome', false, {event_type='task'}) assert.same({['/welcome'] = {event_type='task'}}, r.exact_matches) end) end) describe('match', function() it('returns a number of characters matched and args', function() r = new('/hello', false, {lang='en'}) local matched, args = r:match('/hello/world') assert.equals(6, matched) assert.same({lang='en'}, args) end) it('ignores route name', function() r = new('/hello', false, nil, 'hello') local matched, args = r:match('/hello/world') assert(matched) assert.same({}, args) end) it('returns nil if no match found', function() local matched = r:match('/') assert.is_nil(matched) end) end) end) end)
mit
nasomi/darkstar
scripts/zones/Abyssea-Altepa/Zone.lua
32
1531
----------------------------------- -- -- Zone: Abyssea - Altepa -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Altepa/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(435 ,0 ,320 ,136) end if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED and player:getVar("1stTimeAyssea") == 0) then player:setVar("1stTimeAyssea",1); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/bowl_of_nashmau_stew.lua
36
1975
----------------------------------------- -- 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"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5595); end; ----------------------------------- -- onEffectGain Action ----------------------------------- 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, 18); target:addMod(MOD_FOOD_ACC_CAP, 25); target:addMod(MOD_FOOD_ATTP, 15); target:addMod(MOD_FOOD_ATT_CAP, 60); target:addMod(MOD_DEF, -100); target:addMod(MOD_EVA, -100); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- 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, 18); target:delMod(MOD_FOOD_ACC_CAP, 25); target:delMod(MOD_FOOD_ATTP, 15); target:delMod(MOD_FOOD_ATT_CAP, 60); target:delMod(MOD_DEF, -100); target:delMod(MOD_EVA, -100); end;
gpl-3.0
actboy168/YDWE
Development/Component/script/common/ffi/unicode.lua
2
1695
local ffi = require 'ffi' ffi.cdef[[ int MultiByteToWideChar(unsigned int CodePage, unsigned long dwFlags, const char* lpMultiByteStr, int cbMultiByte, wchar_t* lpWideCharStr, int cchWideChar); int WideCharToMultiByte(unsigned int CodePage, unsigned long dwFlags, const wchar_t* lpWideCharStr, int cchWideChar, char* lpMultiByteStr, int cchMultiByte, const char* lpDefaultChar, int* pfUsedDefaultChar); ]] local CP_UTF8 = 65001 local CP_ACP = 0 local function u2w(input) local wlen = ffi.C.MultiByteToWideChar(CP_UTF8, 0, input, #input, nil, 0) local wstr = ffi.new('wchar_t[?]', wlen+1) ffi.C.MultiByteToWideChar(CP_UTF8, 0, input, #input, wstr, wlen) return wstr, wlen end local function a2w(input) local wlen = ffi.C.MultiByteToWideChar(CP_ACP, 0, input, #input, nil, 0) local wstr = ffi.new('wchar_t[?]', wlen+1) ffi.C.MultiByteToWideChar(CP_ACP, 0, input, #input, wstr, wlen) return wstr, wlen end local function w2u(wstr, wlen) local len = ffi.C.WideCharToMultiByte(CP_UTF8, 0, wstr, wlen or -1, nil, 0, nil, nil) local str = ffi.new('char[?]', len+1) ffi.C.WideCharToMultiByte(CP_UTF8, 0, wstr, wlen or -1, str, len, nil, nil) return ffi.string(str) end local function w2a(wstr, wlen) local len = ffi.C.WideCharToMultiByte(CP_ACP, 0, wstr, wlen or -1, nil, 0, nil, nil) local str = ffi.new('char[?]', len) ffi.C.WideCharToMultiByte(CP_ACP, 0, wstr, wlen or -1, str, len, nil, nil) return ffi.string(str) end return { u2w = u2w, a2w = a2w, w2u = w2u, w2a = w2a, u2a = function (input) return w2a(u2w(input)) end, a2u = function (input) return w2u(a2w(input)) end, }
gpl-3.0
nasomi/darkstar
scripts/globals/mobskills/Gate_of_Tartarus.lua
19
1070
--------------------------------------------- -- Gate of Tartarus -- -- Description: Lowers target's attack. Additional effect: Refresh -- Type: Physical -- Shadow per hit -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20; if (mob:getTP() == 300) then duration = 60; elseif (mob:getTP() >= 200) then duration = 40; end MobBuffMove(mob, EFFECT_REFRESH, 8, 3, duration); MobStatusEffectMove(mob, target, EFFECT_ATTACK_DOWN, 20, 0, duration); target:delHP(dmg); return dmg; end;
gpl-3.0
nasomi/darkstar
scripts/zones/East_Ronfaure/npcs/Logging_Point.lua
29
1101
----------------------------------- -- Area: East Ronfaure -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x0385); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); 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
nasomi/darkstar
scripts/zones/Port_Bastok/npcs/Dulsie.lua
17
1327
----------------------------------- -- Area: Port Bastok -- NPC: Dulsie -- Adventurer's Assistant -- Working 100% ------------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(0x218,1) and trade:getItemCount() == 1) then player:startEvent(0x0008); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0007); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0008) then player:tradeComplete(); player:addGil(GIL_RATE*50); player:messageSpecial(GIL_OBTAINED,GIL_RATE*50); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Heavens_Tower/npcs/_6q1.lua
17
1377
----------------------------------- -- Area: Heaven's Tower -- NPC: Starway Stairway -- @pos -10 0.1 30 242 ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Heavens_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == 2) then if (player:hasKeyItem(STARWAY_STAIRWAY_BAUBLE)) then if (player:getXPos() < -14) then player:startEvent(0x006A); else player:startEvent(0x0069); end; else player:messageSpecial(STAIRWAY_LOCKED); end; else player:messageSpecial(STAIRWAY_ONLY_CITIZENS); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Waters/Zone.lua
28
3433
----------------------------------- -- -- Zone: Windurst_Waters (238) -- ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/zone"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Check if we are on Windurst Mission 1-3 zone:registerRegion(1, 23,-12,-208, 31,-8,-197); applyHalloweenNpcCostumes(zone:getID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 0x213; end player:setPos(-40,-5,80,64); player:setHomePoint(); end -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then position = math.random(1,5) + 157; player:setPos(position,-5,-62,192); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); end if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status") == 1) then -- COP MEMORIES_OF_A_MAIDEN--3-3B: Windurst Route player:setVar("MEMORIES_OF_A_MAIDEN_Status",2); cs = 0x0367; end return cs; 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; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Windurst Mission 1-3, final cutscene with Leepe-Hoppe -- If we're on Windurst Mission 1-3 if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE and player:getVar("MissionStatus") == 2) then player:startEvent(0x0092); end end, } end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x213) then player:messageSpecial(ITEM_OBTAINED,0x218); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 0x0092) then -- Returned from Giddeus, Windurst 1-3 player:setVar("MissionStatus",3); player:setVar("ghoo_talk",0); player:setVar("laa_talk",0); end end;
gpl-3.0
raziel057/FrameworkBenchmarks
frameworks/Lua/octopus/config.lua
12
1032
return { extensions = { {octopusExtensionsDir, "core"}, {octopusExtensionsDir, "baseline"}, {octopusExtensionsDir, "orm"}, {octopusExtensionsDir, "app"}, }, octopusExtensionsDir = octopusExtensionsDir, octopusHostDir = octopusHostDir, port = 8080, securePort = 38080, luaCodeCache = "on", serverName = "localhost", errorLog = "error_log logs/error.log;", accessLog = "access_log logs/access.log;", includeDrop = [[#include drop.conf;]], maxBodySize = "50k", minifyJavaScript = false, minifyCommand = [[java -jar ../yuicompressor-2.4.8.jar %s -o %s]], databaseConnection = { rdbms = "mysql", host = "DBHOSTNAME", port = 3306, database = "hello_world", user = "benchmarkdbuser", password = "benchmarkdbpass", compact = false }, globalParameters = { octopusHostDir = octopusHostDir, sourceCtxPath = "", requireSecurity = false, sessionTimeout = 3600, usePreparedStatement = false, }, }
bsd-3-clause
nasomi/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Gavrie.lua
34
1475
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Gavrie -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,GAVRIE_SHOP_DIALOG); stock = {0x1036,2595, -- Eye Drops 0x1034,316, -- Antidote 0x1037,800, -- Echo Drops 0x1010,910, -- Potion 0x1020,4832, -- Ether 0x103B,3360, -- Remedy 0x119D,12, -- Distilled Water 0x492B,50, -- Automaton Oil 0x492C,250, -- Automaton Oil +1 0x492D,500, -- Automaton Oil +2 0x4AF1,1000} -- Automaton Oil +3 showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
C60Project/C60-PRODUCT
plugins/mediasettings.lua
4
3530
local function get_group_name(text) local name = text:match('.*%((.+)%)$') if not name then return '' end name = '\n('..name..')' return name:mEscape() end local function doKeyboard_media(chat_id) local keyboard = {} keyboard.inline_keyboard = {} for i,media in pairs(config.media_list) do local status = (db:hget('chat:'..chat_id..':media', media)) or 'allowed' if status == 'allowed' then status = '✅' else status = '🔐 '..status end local line = { {text = media, callback_data = 'mediallert'}, {text = status, callback_data = 'media:'..media..':'..chat_id} } table.insert(keyboard.inline_keyboard, line) end --media warn local max = (db:hget('chat:'..chat_id..':warnsettings', 'mediamax')) or 2 table.insert(keyboard.inline_keyboard, {{text = 'Warns (media) 📍 '..max, callback_data = 'mediallert'}}) local warn = { {text = '➖', callback_data = 'mediawarn:dim:'..chat_id}, {text = '➕', callback_data = 'mediawarn:raise:'..chat_id}, } table.insert(keyboard.inline_keyboard, warn) return keyboard end local action = function(msg, blocks, ln) if not msg.cb and msg.chat.type ~= 'private' then if not is_mod(msg) then return end if blocks[1] == 'media list' then local media_sett = db:hgetall('chat:'..msg.chat.id..':media') local text = lang[ln].mediasettings.settings_header for k,v in pairs(media_sett) do text = text..'`'..k..'`'..' ≡ '..v..'\n' end api.sendReply(msg, text, true) end if blocks[1] == 'media' then keyboard = doKeyboard_media(msg.chat.id) local res = api.sendKeyboard(msg.from.id, lang[ln].all.media_first..'\n('..msg.chat.title:mEscape()..')', keyboard, true) if res then api.sendMessage(msg.chat.id, lang[ln].bonus.general_pm, true) else cross.sendStartMe(msg, ln) end end end if msg.cb then if blocks[1] == 'mediallert' then api.answerCallbackQuery(msg.cb_id, '⚠️ '..lang[ln].bonus.menu_cb_media) return end local cb_text local group_name = get_group_name(msg.old_text) local chat_id = msg.target_id if blocks[1] == 'mediawarn' then local current = tonumber(db:hget('chat:'..chat_id..':warnsettings', 'mediamax')) or 2 if blocks[2] == 'dim' then if current < 2 then cb_text = lang[ln].warn.inline_low else local new = db:hincrby('chat:'..chat_id..':warnsettings', 'mediamax', -1) cb_text = make_text(lang[ln].floodmanager.changed_cross, current, new) end elseif blocks[2] == 'raise' then if current > 11 then cb_text = lang[ln].warn.inline_high else local new = db:hincrby('chat:'..chat_id..':warnsettings', 'mediamax', 1) cb_text = make_text(lang[ln].floodmanager.changed_cross, current, new) end end cb_text = '⚙ '..cb_text end if blocks[1] == 'media' then local media = blocks[2] cb_text = '⚡️ '..cross.changeMediaStatus(chat_id, media, 'next', ln) end keyboard = doKeyboard_media(chat_id) api.editMessageText(msg.chat.id, msg.message_id, lang[ln].all.media_first..group_name, keyboard, true) api.answerCallbackQuery(msg.cb_id, cb_text) end end return { action = action, triggers = { '^/(media list)$', '^/(media)$', '^###cb:(media):(%a+):(-%d+)', '^###cb:(mediawarn):(%a+):(-%d+)', '^###cb:(mediallert)', } }
gpl-2.0
nasomi/darkstar
scripts/zones/Metalworks/npcs/_6le.lua
34
1035
----------------------------------- -- Area: Metalworks -- Door: _6le (Presidential Suite) -- @pos 113 -20 8 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(ITS_LOCKED); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
EnjoyHacking/nn
Concat.lua
40
3881
local Concat, parent = torch.class('nn.Concat', 'nn.Container') function Concat:__init(dimension) parent.__init(self) self.size = torch.LongStorage() self.dimension = dimension end function Concat:updateOutput(input) local outs = {} for i=1,#self.modules do local currentOutput = self.modules[i]:updateOutput(input) outs[i] = currentOutput if i == 1 then self.size:resize(currentOutput:dim()):copy(currentOutput:size()) else self.size[self.dimension] = self.size[self.dimension] + currentOutput:size(self.dimension) end end self.output:resize(self.size) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = outs[i] self.output:narrow(self.dimension, offset, currentOutput:size(self.dimension)):copy(currentOutput) offset = offset + currentOutput:size(self.dimension) end return self.output end function Concat:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local currentGradInput = module:updateGradInput(input, gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension))) if currentGradInput then -- if the module does not produce a gradInput (for example first layer), then ignore it and move on. if i==1 then self.gradInput:copy(currentGradInput) else self.gradInput:add(currentGradInput) end end offset = offset + currentOutput:size(self.dimension) end return self.gradInput end function Concat:accGradParameters(input, gradOutput, scale) scale = scale or 1 local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output module:accGradParameters( input, gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)), scale) offset = offset + currentOutput:size(self.dimension) end end function Concat:backward(input, gradOutput, scale) self.gradInput:resizeAs(input) scale = scale or 1 local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local currentGradInput = module:backward(input, gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)), scale) if currentGradInput then -- if the module does not produce a gradInput (for example first layer), then ignore it and move on. if i==1 then self.gradInput:copy(currentGradInput) else self.gradInput:add(currentGradInput) end end offset = offset + currentOutput:size(self.dimension) end return self.gradInput end function Concat:accUpdateGradParameters(input, gradOutput, lr) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output module:accUpdateGradParameters( input, gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)), lr) offset = offset + currentOutput:size(self.dimension) end end function Concat:__tostring__() local tab = ' ' local line = '\n' local next = ' |`-> ' local ext = ' | ' local extlast = ' ' local last = ' ... -> ' local str = torch.type(self) str = str .. ' {' .. line .. tab .. 'input' for i=1,#self.modules do if i == self.modules then str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast) else str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext) end end str = str .. line .. tab .. last .. 'output' str = str .. line .. '}' return str end
bsd-3-clause
Hello23-Ygopro/ygopro-ds
expansions/script/c27004274.lua
1
1560
--TB2-069 Son Goku & Uub, Seeds of the Future local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,CHARACTER_SON_GOKU,SPECIAL_TRAIT_SAIYAN,CHARACTER_INCLUDES_SON_GOKU,SPECIAL_TRAIT_WORLD_TOURNAMENT,CHARACTER_UUB,SPECIAL_TRAIT_EARTHLING) ds.AddPlayProcedure(c,COLOR_BLUE,3,5) --ultimate ds.EnableUltimate(c) --double strike ds.EnableDoubleStrike(c) --dual attack ds.EnableDualAttack(c) --energy cost down ds.AddPermanentUpdateEnergyCost(c,-2,scard.eccon,LOCATION_HAND) --to deck ds.AddSingleAutoAttack(c,0,nil,scard.tdtg,scard.tdop,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=1 --energy cost down function scard.eccon(e,tp,eg,ep,ev,re,r,rp) local ct1=Duel.GetMatchingGroupCount(ds.EnergyAreaFilter(),e:GetHandlerPlayer(),DS_LOCATION_ENERGY,0,nil) local ct2=Duel.GetMatchingGroupCount(ds.EnergyAreaFilter(),e:GetHandlerPlayer(),0,DS_LOCATION_ENERGY,nil) return ds.ldscon(aux.FilterBoolFunction(Card.IsSpecialTrait,SPECIAL_TRAIT_WORLD_TOURNAMENT))(e,tp,eg,ep,ev,re,r,rp) and ct1>=6 and ct2>=6 end --to deck function scard.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return true end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.SelectLifeTarget(tp,nil,1-tp,0,1,nil,e) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TODECK) Duel.SelectTarget(tp,ds.EnergyAreaFilter(),tp,0,DS_LOCATION_ENERGY,0,1,nil) end scard.tdop=ds.ChooseSendtoDeckOperation(DECK_SEQUENCE_BOTTOM)
gpl-3.0
nasomi/darkstar
scripts/zones/Lufaise_Meadows/npcs/qm4.lua
17
1350
----------------------------------- -- Area: Lufaise Meadows -- NPC: ??? - spawns Splinterspine Grukjuk for quest "A Hard Day's Knight" -- @pos -38.605 -9.022 -290.700 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Lufaise_Meadows/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- NOTE: uncertain of retailness of messages. Had expected but did not find any csid. if (GetMobAction(16875774) == 0 and player:getQuestStatus(OTHER_AREAS,A_HARD_DAY_S_KNIGHT) == QUEST_ACCEPTED and player:getVar("SPLINTERSPINE_GRUKJUK") <= 1) then player:messageSpecial(SURVEY_THE_SURROUNDINGS); player:messageSpecial(MURDEROUS_PRESENCE); player:setVar("SPLINTERSPINE_GRUKJUK",1); SpawnMob(16875774,120):updateClaim(player); -- Splinterspine Grukjuk else player:messageSpecial(YOU_CAN_SEE_FOR_MALMS); player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/abilities/pets/pet_lightning_breath.lua
25
1262
--------------------------------------------------- -- Lightning Breath --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill, master) ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 1; if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25; pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST); end local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_LIGHTNING); -- Works out to (hp/6) + 15, as desired dmgmod = (dmgmod * (1+gear))*deep; local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end
gpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
30
3470
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Copyright 2013 Manuel Munz <freifunk at somakoma dot de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- require("luci.tools.webadmin") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with " .. "a fixed hostname while having a dynamically changing " .. "IP address.")) s = m:section(TypedSection, "service", "") s.addremove = true s.anonymous = false s:option(Flag, "enabled", translate("Enable")) svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = false svc.default = "dyndns.org" local services = { } local fd = io.open("/usr/lib/ddns/services", "r") if fd then local ln repeat ln = fd:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services[#services+1] = s end until not ln fd:close() end local v for _, v in luci.util.vspairs(services) do svc:value(v) end function svc.cfgvalue(...) local v = Value.cfgvalue(...) if not v or #v == 0 then return "-" else return v end end function svc.write(self, section, value) if value == "-" then m.uci:delete("ddns", section, self.option) else Value.write(self, section, value) end end svc:value("-", "-- "..translate("custom").." --") local url = s:option(Value, "update_url", translate("Custom update-URL")) url:depends("service_name", "-") url.rmempty = true local hostname = s:option(Value, "domain", translate("Hostname")) hostname.rmempty = true hostname.default = "mypersonaldomain.dyndns.org" hostname.datatype = "host" local username = s:option(Value, "username", translate("Username")) username.rmempty = true local pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true require("luci.tools.webadmin") local src = s:option(ListValue, "ip_source", translate("Source of IP address")) src.default = "network" src:value("network", translate("network")) src:value("interface", translate("interface")) src:value("web", translate("URL")) local iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true iface.default = "wan" luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end local web = s:option(Value, "ip_url", translate("URL")) web:depends("ip_source", "web") web.default = "http://checkip.dyndns.com/" web.rmempty = true local ci = s:option(Value, "check_interval", translate("Check for changed IP every")) ci.datatype = "and(uinteger,min(1))" ci.default = 10 local unit = s:option(ListValue, "check_unit", translate("Check-time unit")) unit.default = "minutes" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) fi = s:option(Value, "force_interval", translate("Force update every")) fi.datatype = "and(uinteger,min(1))" fi.default = 72 local unit = s:option(ListValue, "force_unit", translate("Force-time unit")) unit.default = "hours" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) return m
gpl-2.0
dani-sj/soheyl
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
jeffreyling/seq2seq-hard
model_utils.lua
1
3094
function clone_many_times(net, T) local clones = {} local params, gradParams if net.parameters then params, gradParams = net:parameters() if params == nil then params = {} end end local paramsNoGrad if net.parametersNoGrad then paramsNoGrad = net:parametersNoGrad() end local mem = torch.MemoryFile("w"):binary() mem:writeObject(net) for t = 1, T do -- We need to use a new reader for each clone. -- We don't want to use the pointers to already read objects. local reader = torch.MemoryFile(mem:storage(), "r"):binary() local clone = reader:readObject() reader:close() if net.parameters then local cloneParams, cloneGradParams = clone:parameters() local cloneParamsNoGrad for i = 1, #params do cloneParams[i]:set(params[i]) cloneGradParams[i]:set(gradParams[i]) end if paramsNoGrad then cloneParamsNoGrad = clone:parametersNoGrad() for i =1,#paramsNoGrad do cloneParamsNoGrad[i]:set(paramsNoGrad[i]) end end end clones[t] = clone collectgarbage() end mem:close() return clones end function adagradStep(x, dfdx, eta, state) if not state.var then state.var = torch.Tensor():typeAs(x):resizeAs(x):zero() state.std = torch.Tensor():typeAs(x):resizeAs(x) end state.var:addcmul(1, dfdx, dfdx) state.std:sqrt(state.var) x:addcdiv(-eta, dfdx, state.std:add(1e-10)) end function adamStep(x, dfdx, lr, state) local beta1 = state.beta1 or 0.9 local beta2 = state.beta2 or 0.999 local eps = state.eps or 1e-8 state.t = state.t or 0 state.m = state.m or dfdx.new(dfdx:size()):zero() state.v = state.v or dfdx.new(dfdx:size()):zero() state.denom = state.denom or dfdx.new(dfdx:size()):zero() state.t = state.t + 1 state.m:mul(beta1):add(1-beta1, dfdx) state.v:mul(beta2):addcmul(1-beta2, dfdx, dfdx) state.denom:copy(state.v):sqrt():add(eps) local bias1 = 1-beta1^state.t local bias2 = 1-beta2^state.t local stepSize = lr * math.sqrt(bias2)/bias1 dfdx:copy(state.m):cdiv(state.denom):mul(-stepSize) x:add(dfdx) end function adadeltaStep(x, dfdx, state) local rho = state.rho or 0.9 local eps = state.eps or 1e-6 state.var = state.var or dfdx.new(dfdx:size()):zero() state.std = state.std or dfdx.new(dfdx:size()):zero() state.delta = state.delta or dfdx.new(dfdx:size()):zero() state.accDelta = state.accDelta or dfdx.new(dfdx:size()):zero() state.var:mul(rho):addcmul(1-rho, dfdx, dfdx) state.std:copy(state.var):add(eps):sqrt() state.delta:copy(state.accDelta):add(eps):sqrt():cdiv(state.std):cmul(dfdx) dfdx:copy(state.delta):mul(-1) state.accDelta:mul(rho):addcmul(1-rho, state.delta, state.delta) x:add(dfdx) end function get_indices(t, source_char_l) local t1 = math.floor((t-1)/source_char_l) + 1 local t2 = ((t-1) % source_char_l) + 1 return t1, t2 end
mit
nasomi/darkstar
scripts/zones/Crawlers_Nest/npcs/qm9.lua
17
1819
----------------------------------- -- Area: Crawlers Nest -- NPC: ??? -- Used In Quest: A Boy's Dream -- @pos -18 -8 124 197 ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Crawlers_Nest/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DreadbugTimer = player:getVar("DreadbugNM_Timer"); local DreadbugDay = player:getVar("DreadbugNM_Day"); local MyDay = VanadielDayOfTheYear(); local aBoysDream = player:getQuestStatus(SANDORIA, A_BOY_S_DREAM); if (MyDay ~= DreadbugDay and aBoysDream == QUEST_ACCEPTED) then local canSpawn = (os.time() - DreadbugTimer) > 30; if (canSpawn) then SpawnMob(17584425,168):updateClaim(player); -- Despawn after 3 minutes (-12 seconds for despawn delay). player:setVar("DreadbugNM_Timer",os.time()+180); player:setVar("DreadbugNM_Day",VanadielDayOfTheYear()); player:messageSpecial(SENSE_OF_FOREBODING); else player:messageSpecial(NOTHING_SEEMS_TO_HAPPEN); end else player:messageSpecial(NOTHING_WILL_HAPPEN_YET); 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
nasomi/darkstar
scripts/globals/items/nexus_cape.lua
29
1354
----------------------------------------- -- ID: 11538 -- Item: Nexus Cape -- Enchantment: "Teleport" (Party Leader) ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/teleports"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local leader = target:getPartyLeader(); local leaderZone = GetPlayerByName(target:getPartyLeader()):getZoneID(); local validZoneList = { 005,007,100,101,102,103,104,105,106,107,108,110,111,112,113,114, 115,116,117,118,119,120,123,124,126,127,128,230,231,232,234,235, 236,238,239,240,241,243,244,245,246,247,248,249,250,252,257 } if (leader == nil) then return 56; -- Not in a party, fail. elseif (target:getID() == GetPlayerByName(leader):getID()) then return 56; -- User is leader, fail. end for _, validZone in ipairs( validZoneList ) do if (validZone == leaderZone) then return 0; -- All good, teleporting! end end return 56; -- Leader wasn't in a valid zone, fail. end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_TO_LEADER,0,1); end;
gpl-3.0
shangjiyu/luci-with-extra
applications/luci-app-aria2/luasrc/controller/aria2.lua
17
1090
--[[ LuCI - Lua Configuration Interface - aria2 support Copyright 2014-2015 nanpuyue <nanpuyue@gmail.com> Modified by kuoruan <kuoruan@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.controller.aria2", package.seeall) function index() if not nixio.fs.access("/etc/config/aria2") then return end local page = entry({"admin", "services", "aria2"}, cbi("aria2"), _("Aria2 Settings")) page.dependent = true entry({"admin", "services", "aria2", "status"}, call("status")).leaf = true end function status() local sys = require "luci.sys" local ipkg = require "luci.model.ipkg" local http = require "luci.http" local uci = require "luci.model.uci".cursor() local status = { running = (sys.call("pidof aria2c > /dev/null") == 0), yaaw = ipkg.installed("yaaw"), webui = ipkg.installed("webui-aria2") } http.prepare_content("application/json") http.write_json(status) end
apache-2.0
droogmic/droogmic-domoticz-lua
packages/socket/mime.lua
149
2487
----------------------------------------------------------------------------- -- MIME support for the Lua language. -- Author: Diego Nehab -- Conforming to RFCs 2045-2049 ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local ltn12 = require("ltn12") local mime = require("mime.core") local io = require("io") local string = require("string") local _M = mime -- encode, decode and wrap algorithm tables local encodet, decodet, wrapt = {},{},{} _M.encodet = encodet _M.decodet = decodet _M.wrapt = wrapt -- creates a function that chooses a filter by name from a given table local function choose(table) return function(name, opt1, opt2) if base.type(name) ~= "string" then name, opt1, opt2 = "default", name, opt1 end local f = table[name or "nil"] if not f then base.error("unknown key (" .. base.tostring(name) .. ")", 3) else return f(opt1, opt2) end end end -- define the encoding filters encodet['base64'] = function() return ltn12.filter.cycle(_M.b64, "") end encodet['quoted-printable'] = function(mode) return ltn12.filter.cycle(_M.qp, "", (mode == "binary") and "=0D=0A" or "\r\n") end -- define the decoding filters decodet['base64'] = function() return ltn12.filter.cycle(_M.unb64, "") end decodet['quoted-printable'] = function() return ltn12.filter.cycle(_M.unqp, "") end local function format(chunk) if chunk then if chunk == "" then return "''" else return string.len(chunk) end else return "nil" end end -- define the line-wrap filters wrapt['text'] = function(length) length = length or 76 return ltn12.filter.cycle(_M.wrp, length, length) end wrapt['base64'] = wrapt['text'] wrapt['default'] = wrapt['text'] wrapt['quoted-printable'] = function() return ltn12.filter.cycle(_M.qpwrp, 76, 76) end -- function that choose the encoding, decoding or wrap algorithm _M.encode = choose(encodet) _M.decode = choose(decodet) _M.wrap = choose(wrapt) -- define the end-of-line normalization filter function _M.normalize(marker) return ltn12.filter.cycle(_M.eol, 0, marker) end -- high level stuffing filter function _M.stuff() return ltn12.filter.cycle(_M.dot, 2) end return _M
mit
chergert/libpeas
loaders/lua5.1/resources/peas-lua-internal.lua
4
4552
-- -- Copyright (C) 2015 - Garrett Regier -- -- libpeas is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- libpeas 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. local debug = require 'debug' local package = require 'package' local lgi = require 'lgi' local GObject = lgi.GObject local Peas = lgi.Peas local Hooks = {} Hooks.__index = Hooks function Hooks.new() local self = { priv = {} } setmetatable(self, Hooks) self.priv.module_cache = {} self.priv.extension_cache = {} return self end function Hooks:failed(msg) -- This is implemented by the plugin loader error('Hooks:failed() was not implemented!') end local function add_package_path(package_path) local paths = (';%s/?.lua;%s/?/init.lua'):format(package_path, package_path) if not package.path:find(paths, 1, true) then package.path = package.path .. paths end end local function format_plugin_exception(err) -- Format the error even if given a userdata local formatted = debug.traceback(tostring(err), 2) if type(formatted) ~= 'string' then return formatted end -- Remove all mentions of this file local lines = {} for line in formatted:gmatch('([^\n]+\n?)') do if line:find('peas-lua-internal.lua', 1, true) then break end table.insert(lines, line) end return table.concat(lines, '') end function Hooks:load(filename, module_dir, module_name) local module = self.priv.module_cache[filename] if module ~= nil then return module ~= false end if package.loaded[module_name] ~= nil then local msg = ("Error loading plugin '%s': " .. "module name '%s' has already been used") self:failed(msg:format(filename, module_name)) end add_package_path(module_dir) local success, result = xpcall(function() return require(module_name) end, format_plugin_exception) if not success then local msg = "Error loading plugin '%s':\n%s" self:failed(msg:format(module_name, tostring(result))) end if type(result) ~= 'table' then self.priv.module_cache[filename] = false local msg = "Error loading plugin '%s': expected table, got: %s (%s)" self:failed(msg:format(module_name, type(result), tostring(result))) end self.priv.module_cache[filename] = result self.priv.extension_cache[filename] = {} return true end function Hooks:find_extension_type(filename, gtype) local module_gtypes = self.priv.extension_cache[filename] local extension_type = module_gtypes[gtype] if extension_type ~= nil then if extension_type == false then return nil end return extension_type end for _, value in pairs(self.priv.module_cache[filename]) do local value_gtype = value._gtype if value_gtype ~= nil then if GObject.type_is_a(value_gtype, gtype) then module_gtypes[gtype] = value_gtype return value_gtype end end end module_gtypes[gtype] = false return nil end local function check_native(native, wrapped, typename) local msg = ('Invalid wrapper for %s: %s'):format(typename, tostring(wrapped)) -- Cannot compare userdata directly! assert(wrapped ~= nil, msg) assert(tostring(native) == tostring(wrapped._native), msg) end function Hooks:setup_extension(exten, info) local wrapped_exten = GObject.Object(exten, false) check_native(exten, wrapped_exten, 'extension') local wrapped_info = Peas.PluginInfo(info, false) check_native(info, wrapped_info, 'PeasPluginInfo') wrapped_exten.priv.plugin_info = wrapped_info end function Hooks:garbage_collect() collectgarbage() end return Hooks.new() -- ex:ts=4:et:
lgpl-2.1
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/bulwark_shot_2.meta.lua
8
2731
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 90, light_colors = { "255 0 0 255", "255 252 252 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = -6 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = -16, y = 4 }, rotation = 0 }, shell_spawn = { pos = { x = 8, y = -8 }, rotation = -90 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = -15, y = 3 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-firewall/luasrc/model/cbi/firewall/zones.lua
84
2233
--[[ LuCI - Lua Configuration Interface 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 $Id$ ]]-- local ds = require "luci.dispatcher" local fw = require "luci.model.firewall" local m, s, o, p, i, v m = Map("firewall", translate("Firewall - Zone Settings"), translate("The firewall creates zones over your network interfaces to control network traffic flow.")) fw.init(m.uci) s = m:section(TypedSection, "defaults", translate("General Settings")) s.anonymous = true s.addremove = false s:option(Flag, "syn_flood", translate("Enable SYN-flood protection")) o = s:option(Flag, "drop_invalid", translate("Drop invalid packets")) o.default = o.disabled p = { s:option(ListValue, "input", translate("Input")), s:option(ListValue, "output", translate("Output")), s:option(ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s = m:section(TypedSection, "zone", translate("Zones")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true s.extedit = ds.build_url("admin", "network", "firewall", "zones", "%s") function s.create(self) local z = fw:new_zone() if z then luci.http.redirect( ds.build_url("admin", "network", "firewall", "zones", z.sid) ) end end function s.remove(self, section) return fw:del_zone(section) end o = s:option(DummyValue, "_info", translate("Zone ⇒ Forwardings")) o.template = "cbi/firewall_zoneforwards" o.cfgvalue = function(self, section) return self.map:get(section, "name") end p = { s:option(ListValue, "input", translate("Input")), s:option(ListValue, "output", translate("Output")), s:option(ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s:option(Flag, "masq", translate("Masquerading")) s:option(Flag, "mtu_fix", translate("MSS clamping")) return m
gpl-2.0
nasomi/darkstar
scripts/zones/Qufim_Island/npcs/Tsonga-Hoponga_WW.lua
30
3060
----------------------------------- -- Area: Qufim Island -- NPC: Tsonga-Hoponga, W.W. -- Type: Outpost Conquest Guards -- @pos -245.366 -20.344 299.502 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
nasomi/darkstar
scripts/globals/pathfind.lua
18
2553
-- Util methods for pathfinding pathfind = {}; PATHFLAG_NONE = 0 PATHFLAG_RUN = 1 PATHFLAG_WALLHACK = 2 PATHFLAG_REVERSE = 4 -- returns the point at the given index function pathfind.get(points, index) local pos = {}; if (index < 0) then index = (#points + index - 2) / 3; end pos[1] = points[index*3-2]; pos[2] = points[index*3-1]; pos[3] = points[index*3]; return pos; end; function pathfind.length(points) return #points / 3; end function pathfind.first(points) return pathfind.get(points, 1); end; function pathfind.equal(point1, point2) return point1[1] == point2[1] and point1[2] == point2[2] and point1[3] == point2[3]; end; -- returns the last point function pathfind.last(points) local length = #points; return pathfind.get(points, length/3); end; -- returns a random point from given point array function pathfind.random(points) local length = #points; return pathfind.get(points, math.random(1, length)); end; -- returns the start path without the first element function pathfind.fromStart(points, start) start = start or 1; local t2 = {} local maxLength = 50; local length = pathfind.length(points); local count = 1; local pos = start + 1; local index = 1; while pos <= length and count <= maxLength do local pt = pathfind.get(points, pos); t2[index] = pt[1]; t2[index+1] = pt[2]; t2[index+2] = pt[3]; pos = pos + 1; count = count + 1; index = index + 3; end return t2 end; -- reverses the array and removes the first element function pathfind.fromEnd(points, start) start = start or 1 local t2 = {} -- do not add the last element local length = #points / 3; start = length - start; local index = 1; for i=start,1,-1 do local pt = pathfind.get(points, i); t2[index] = pt[1] t2[index+1] = pt[2] t2[index+2] = pt[3] index = index + 3 if (i > 50) then break; end end return t2 end; -- continusly runs the path function pathfind.patrol(npc, points, flags) if (npc:atPoint(pathfind.first(points)) or npc:atPoint(pathfind.last(points))) then npc:pathThrough(pathfind.fromStart(points), flags); else local length = #points / 3; local currentLength = 0; local i = 51; -- i'm some where inbetween while(i <= length) do if (npc:atPoint(pathfind.get(points, i))) then npc:pathThrough(pathfind.fromStart(points, i), flags); break; end i = i + 50; end end end;
gpl-3.0
nicholas-leonard/nn
CosineEmbeddingCriterion.lua
22
3690
local CosineEmbeddingCriterion, parent = torch.class('nn.CosineEmbeddingCriterion', 'nn.Criterion') function CosineEmbeddingCriterion:__init(margin) parent.__init(self) margin = margin or 0 self.margin = margin self.gradInput = {torch.Tensor(), torch.Tensor()} self.sizeAverage = true end function CosineEmbeddingCriterion:updateOutput(input,y) local input1, input2 = input[1], input[2] -- keep backward compatibility if type(y) == 'number' then self._y = self._y or input1.new(1) self._y[1] = y y = self._y end if input1:dim() == 1 then input1 = input1:view(1,-1) input2 = input2:view(1,-1) end if not self.buffer then self.buffer = input1.new() self.w1 = input1.new() self.w22 = input1.new() self.w = input1.new() self.w32 = input1.new() self._outputs = input1.new() -- comparison operators behave differently from cuda/c implementations if input1:type() == 'torch.CudaTensor' then self._idx = input1.new() else self._idx = torch.ByteTensor() end end self.buffer:cmul(input1,input2) self.w1:sum(self.buffer,2) local epsilon = 1e-12 self.buffer:cmul(input1,input1) self.w22:sum(self.buffer,2):add(epsilon) -- self._outputs is also used as a temporary buffer self._outputs:resizeAs(self.w22):fill(1) self.w22:cdiv(self._outputs, self.w22) self.w:resizeAs(self.w22):copy(self.w22) self.buffer:cmul(input2,input2) self.w32:sum(self.buffer,2):add(epsilon) self.w32:cdiv(self._outputs, self.w32) self.w:cmul(self.w32) self.w:sqrt() self._outputs:cmul(self.w1,self.w) self._outputs = self._outputs:select(2,1) y.eq(self._idx,y,-1) self._outputs[self._idx] = self._outputs[self._idx]:add(-self.margin):cmax(0) y.eq(self._idx,y,1) self._outputs[self._idx] = self._outputs[self._idx]:mul(-1):add(1) self.output = self._outputs:sum() if self.sizeAverage then self.output = self.output/y:size(1) end return self.output end function CosineEmbeddingCriterion:updateGradInput(input, y) local v1 = input[1] local v2 = input[2] local not_batch = false -- keep backward compatibility if type(y) == 'number' then self._y = self._y or input1.new(1) self._y[1] = y y = self._y end if v1:dim() == 1 then v1 = v1:view(1,-1) v2 = v2:view(1,-1) not_batch = true end local gw1 = self.gradInput[1] local gw2 = self.gradInput[2] gw1:resizeAs(v1):copy(v2) gw2:resizeAs(v1):copy(v1) self.buffer:cmul(self.w1,self.w22) gw1:addcmul(-1,self.buffer:expandAs(v1),v1) gw1:cmul(self.w:expandAs(v1)) self.buffer:cmul(self.w1,self.w32) gw2:addcmul(-1,self.buffer:expandAs(v1),v2) gw2:cmul(self.w:expandAs(v1)) -- self._idx = self._outputs <= 0 y.le(self._idx,self._outputs,0) self._idx = self._idx:view(-1,1):expand(gw1:size()) gw1[self._idx] = 0 gw2[self._idx] = 0 y.eq(self._idx,y,1) self._idx = self._idx:view(-1,1):expand(gw2:size()) gw1[self._idx] = gw1[self._idx]:mul(-1) gw2[self._idx] = gw2[self._idx]:mul(-1) if self.sizeAverage then gw1:div(y:size(1)) gw2:div(y:size(1)) end if not_batch then self.gradInput[1]:resize(gw1:size(2)) self.gradInput[2]:resize(gw2:size(2)) end return self.gradInput end function CosineEmbeddingCriterion:type(type) self._idx = nil parent.type(self,type) -- comparison operators behave differently from cuda/c implementations if type == 'torch.CudaTensor' then self._idx = torch.CudaTensor() else self._idx = torch.ByteTensor() end return self end
bsd-3-clause
irboy/000LOGIN000
plugins/info.lua
1
8329
--Begin info.lua By @SoLiD local Solid = 157059515 local function setrank(msg, user_id, value,chat_id) local hash = nil hash = 'rank:'..msg.to.id..':variables' if hash then redis:hset(hash, user_id, value) return tdcli.sendMessage(chat_id, '', 0, '_set_ *Rank* _for_ *[ '..user_id..' ]* _To :_ *'..value..'*', 0, "md") end end local function info_by_reply(arg, data) if tonumber(data.sender_user_id_) then local function info_cb(arg, data) if data.username_ then username = "@"..check_markdown(data.username_) else username = "" end if data.first_name_ then firstname = check_markdown(data.first_name_) else firstname = "" end if data.last_name_ then lastname = check_markdown(data.last_name_) else lastname = "" end local hash = 'rank:'..arg.chat_id..':variables' local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n\n" if data.id_ == tonumber(Solid) then text = text..'_Rank :_ *Executive Admin*\n\n' elseif is_sudo1(data.id_) then text = text..'_Rank :_ *Full Access Admin*\n\n' elseif is_admin1(data.id_) then text = text..'_Rank :_ *Bot Admin*\n\n' elseif is_owner1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Owner*\n\n' elseif is_mod1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Moderator*\n\n' else text = text..'_Rank :_ *Group Member*\n\n' end local user_info = {} local uhash = 'user:'..data.id_ local user = redis:hgetall(uhash) local um_hash = 'msgs:'..data.id_..':'..arg.chat_id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'Total messages : '..user_info_msgs..'\n\n' text = text..'@Y0BINARI' tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md") end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, info_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_,msgid=data.id_}) else tdcli.sendMessage(data.chat_id_, "", 0, "*User not found*", 0, "md") end end local function info_by_username(arg, data) if tonumber(data.id_) then if data.type_.user_.username_ then username = "@"..check_markdown(data.type_.user_.username_) else username = "" end if data.type_.user_.first_name_ then firstname = check_markdown(data.type_.user_.first_name_) else firstname = "" end if data.type_.user_.last_name_ then lastname = check_markdown(data.type_.user_.last_name_) else lastname = "" end local hash = 'rank:'..arg.chat_id..':variables' local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n\n" if data.id_ == tonumber(Solid) then text = text..'_Rank :_ *Executive Admin*\n\n' elseif is_sudo1(data.id_) then text = text..'_Rank :_ *Full Access Admin*\n\n' elseif is_admin1(data.id_) then text = text..'_Rank :_ *Bot Admin*\n\n' elseif is_owner1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Owner*\n\n' elseif is_mod1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Moderator*\n\n' else text = text..'_Rank :_ *Group Member*\n\n' end local user_info = {} local uhash = 'user:'..data.id_ local user = redis:hgetall(uhash) local um_hash = 'msgs:'..data.id_..':'..arg.chat_id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'Total messages : '..user_info_msgs..'\n\n' text = text..'@Y0BINARI' tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md") else tdcli.sendMessage(arg.chat_id, "", 0, "*User not found*", 0, "md") end end local function info_by_id(arg, data) if tonumber(data.id_) then if data.username_ then username = "@"..check_markdown(data.username_) else username = "" end if data.first_name_ then firstname = check_markdown(data.first_name_) else firstname = "" end if data.last_name_ then lastname = check_markdown(data.last_name_) else lastname = "" end local hash = 'rank:'..arg.chat_id..':variables' local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n\n" if data.id_ == tonumber(Solid) then text = text..'_Rank :_ *Executive Admin*\n\n' elseif is_sudo1(data.id_) then text = text..'_Rank :_ *Full Access Admin*\n\n' elseif is_admin1(data.id_) then text = text..'_Rank :_ *Bot Admin*\n\n' elseif is_owner1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Owner*\n\n' elseif is_mod1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Moderator*\n\n' else text = text..'_Rank :_ *Group Member*\n\n' end local user_info = {} local uhash = 'user:'..data.id_ local user = redis:hgetall(uhash) local um_hash = 'msgs:'..data.id_..':'..arg.chat_id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'Total messages : '..user_info_msgs..'\n\n' text = text..'@Y0BINARI' tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md") else tdcli.sendMessage(arg.chat_id, "", 0, "*User not found*", 0, "md") end end local function setrank_by_reply(arg, data) end local function run(msg, matches) local Chash = "cmd_lang:"..msg.to.id local Clang = redis:get(Chash) if (matches[1]:lower() == 'info' and not Clang) or (matches[1]:lower() == 'اطلاعات فرد' and Clang) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, info_by_reply, {chat_id=msg.chat_id_}) end if matches[2] and string.match(matches[2], '^%d+$') and tonumber(msg.reply_to_message_id_) == 0 then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, info_by_id, {chat_id=msg.chat_id_,user_id=matches[2],msgid=msg.id_}) end if matches[2] and not string.match(matches[2], '^%d+$') and tonumber(msg.reply_to_message_id_) == 0 then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, info_by_username, {chat_id=msg.chat_id_,username=matches[2],msgid=msg.id_}) end if not matches[2] and tonumber(msg.reply_to_message_id_) == 0 then local function info2_cb(arg, data) if tonumber(data.id_) then if data.username_ then username = "@"..check_markdown(data.username_) else username = "" end if data.first_name_ then firstname = check_markdown(data.first_name_) else firstname = "" end if data.last_name_ then lastname = check_markdown(data.last_name_) else lastname = "" end local hash = 'rank:'..arg.chat_id..':variables' local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n\n" if data.id_ == tonumber(Solid) then text = text..'_Rank :_ *Executive Admin*\n\n' elseif is_sudo1(data.id_) then text = text..'_Rank :_ *Full Access Admin*\n\n' elseif is_admin1(data.id_) then text = text..'_Rank :_ *Bot Admin*\n\n' elseif is_owner1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Owner*\n\n' elseif is_mod1(arg.chat_id, data.id_) then text = text..'_Rank :_ *Group Moderator*\n\n' else text = text..'_Rank :_ *Group Member*\n\n' end local user_info = {} local uhash = 'user:'..data.id_ local user = redis:hgetall(uhash) local um_hash = 'msgs:'..data.id_..':'..arg.chat_id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'Total messages : '..user_info_msgs..'\n\n' text = text..'@Y0BINARI' tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = msg.from.id, }, info_by_id, {chat_id=msg.chat_id_,user_id=msg.from.id,msgid=msg.id_}) end end end return { patterns = { "^[!/#](info)$", "^[!/#](info) (.*)$", "^(اطلاعات فرد)$", "^(اطلاعات فرد) (.*)$", }, run = run } --This Is info.lua for BDReborn Source :)
gpl-3.0
DevTeam-Co/maximus
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-3.0
ioiasff/pqrw
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
mahdi1378/FBI
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
silver-des/silverbot
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
Etehadmarg/margbot
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
m13790115/eset
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
mikelewis0/easyccg
training/train.lua
2
6149
require 'torch' require 'nn' require 'features' require 'SGD' local Train = torch.class('nn.Train') -- read input files function Train:loadDataset(path, features, windowBackward, windowForward, includeRareCategories) file = io.open(path) local lineNum = 1; local size = 0; for line in file:lines() do if lineNum > 3 or (line ~= '' and string.sub(line, 1, 1) ~= '#') then for instance in string.gmatch(line, "[^ ]+") do size = size + 1 end end lineNum = lineNum + 1 end -- Get length of input file = io.open(path) local index = 0 local window = windowBackward + windowForward + 1 local inputData = torch.Tensor(size, window * (3 + features:getNumberOfSparseFeatures())) local targetData = torch.IntStorage(size) local lineNum = 1; for line in file:lines() do if lineNum > 3 or (line ~= '' and string.sub(line, 1, 1) ~= '#') then local numWords = 0 local words = {} local cats = {} local posTags = {} for instance in string.gmatch(line, "[^ ]+") do numWords = numWords + 1 local delim1 = string.find(instance, '|', 1, true) if (delim1) then local delim2 = string.find(instance, '|', delim1 + 1, true) words[numWords] = string.sub(instance, 1, delim1 - 1) if (delim2) then posTags[numWords] = string.sub(instance, delim1 + 1, delim2 - 1) cats[numWords] = string.sub(instance, delim2 + 1, string.len(instance)) else posTags[numWords] = string.sub(instance, delim1 + 1, string.len(instance)) end else -- No training example provided cats[numWords] = "*NO_CATEGORY*" words[numWords] = instance end end for i = 1,numWords do local input = features:getFeatures(words, posTags, i, windowBackward, windowForward); local label = features:getCategoryIndex(cats[i]) if label > 0 or (includeRareCategories) then --Label 0 is rare categories. These are used for evaluation, but not for training. index = index + 1 for j=1,input:size()[1] do value = input[j] inputData[index][j] = value end targetData[index] = label end end else end lineNum = lineNum + 1 end local dataset = {inputData, targetData}; function dataset:size() return (index) end return dataset end function Train:loadEmbeddings(path) local file = io.open(path) local firstLine = file:read("*line"); local embeddingsSize = 0 for instance in firstLine.gmatch(firstLine, "[^ ]+") do embeddingsSize = embeddingsSize + 1 end embeddingsFile = torch.DiskFile(path); wordTable = nn.LookupTable(features.numWords, embeddingsSize) embedding = torch.DoubleStorage(embeddingsSize) print("Loading embeddings") for i=1,features.numWords-1-features.extraWords do embeddingsFile:readDouble(embedding); local emb = torch.Tensor(embeddingsSize) for j=1,embeddingsSize do emb[j] = embedding[j] end --First two entries are padding if i==1 then for j=1,features.extraWords do wordTable.weight[j] = emb:clone(); end end wordTable.weight[i + features.extraWords] = emb; end print("Loaded embeddings") return wordTable, embeddingsSize end function Train:trainModel(trainFile, validationAutoFile, validationGoldFile, embeddingsFolder, features, windowBackward, windowForward, hiddenSize, name) wordTable, embeddingsSize = self:loadEmbeddings(embeddingsFolder .. '/embeddings.vectors') k = 5 window = windowBackward + windowForward + 1 tableSize = (embeddingsSize + k + k + features:getNumberOfSparseFeatures()) * window print ("Window Size = " .. window) print ("Embeddings Size = " .. embeddingsSize) print ("Lookup Table Size = " .. tableSize) print ("Categories Size = " .. features.numCats) print ("Suffixes Size = " .. features.numSuffixes) print ("Vocabulary Size = " .. features.numWords) print ("Sparse Features Size = " .. features:getNumberOfSparseFeatures()) capsTable = nn.LookupTable(window, k) capsTable:reset(0.1) suffixTable = nn.LookupTable(features.numSuffixes, k) suffixTable:reset(0.1) pt = nn.ParallelTable() pt:add(wordTable) pt:add(suffixTable) pt:add(capsTable) -- Assume we always have 3 lookup-table features (word embeddings, suffixes and capitalization), -- but allow additional features (such as word, POS and Brown clusters) as one-hot vectors. if features:getNumberOfSparseFeatures() > 0 then pt:add(nn.Identity()) end jt = nn.JoinTable(2) rs2 = nn.Reshape(tableSize) mlp = nn.Sequential() mlp:add(pt) mlp:add(jt) mlp:add(rs2) if hiddenSize > 0 then ll1 = nn.Linear(tableSize, hiddenSize) hth = nn.HardTanh() ll2 = nn.Linear(hiddenSize, features.numCats) lsm = nn.LogSoftMax() mlp:add(ll1) mlp:add(hth) mlp:add(ll2) mlp:add(lsm) else hth = nn.HardTanh() ll1 = nn.Linear(tableSize, features.numCats) lsm = nn.LogSoftMax() mlp:add(ll1) mlp:add(lsm) end folder = embeddingsFolder .. '/train.' .. name --.. hiddenSize .. '.' .. windowBackward .. '.' .. windowForward os.execute("mkdir " .. folder) print ("Loading dev set") -- Hacky way of merging automatic POS tags with Gold supertags local validationAuto = self:loadDataset(validationAutoFile, features, windowBackward, windowForward, true) local validationGold = self:loadDataset(validationGoldFile, features, windowBackward, windowForward, true) local validation = {validationAuto[1], validationGold[2]} function validation:size() return (validationAuto:size()) end print ("Dev examples: " .. validation:size()) print ("Loading train set") dataset = self:loadDataset(trainFile, features, windowBackward, windowForward, false) print ("Done") criterion = nn.ClassNLLCriterion() trainer = nn.SGD(mlp, criterion, folder, 3, window) trainer.learningRate = 0.01 trainer.maxIteration = 25 trainer:train(dataset, validation) return mlp end
mit
Hello23-Ygopro/ygopro-ds
expansions/script/c27002125.lua
1
2272
--BT2-110 Cooler, Blood of the Tyrant Clan local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZA_CLAN,CHARACTER_COOLER) ds.AddPlayProcedure(c,COLOR_YELLOW,3,4) --double strike ds.EnableDoubleStrike(c) --switch position ds.AddActivateMainSkill(c,0,DS_LOCATION_BATTLE,scard.posop,scard.poscost,scard.postg,DS_EFFECT_FLAG_CARD_CHOOSE,nil,1) end scard.dragon_ball_super_card=true scard.combo_cost=1 function scard.poscost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(ds.BattleAreaFilter(),tp,DS_LOCATION_BATTLE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,ds.BattleAreaFilter(),tp,DS_LOCATION_BATTLE,0,1,1,nil) Duel.DSRemove(e,g,REASON_COST) end function scard.plfilter1(c,e,tp) return (c:IsSpecialTrait(SPECIAL_TRAIT_COOLERS_ARMORED_SQUADRON) or c:IsSpecialTrait(SPECIAL_TRAIT_FRIEZA_CLAN)) and not c:IsCharacter(CHARACTER_COOLER) and c:IsCanBePlayed(e,0,tp,false,false) end function scard.postg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingTarget(ds.BattleAreaFilter(Card.IsActive),tp,0,DS_LOCATION_BATTLE,1,nil) or Duel.IsExistingTarget(ds.DropAreaFilter(scard.plfilter1),tp,DS_LOCATION_DROP,0,1,nil,e,tp) end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) end function scard.posfilter(c,e) return c:IsActive() and c:IsCanBeSkillTarget(e) end function scard.plfilter2(c,e) return (c:IsSpecialTrait(SPECIAL_TRAIT_COOLERS_ARMORED_SQUADRON) or c:IsSpecialTrait(SPECIAL_TRAIT_FRIEZA_CLAN)) and not c:IsCharacter(CHARACTER_COOLER) and c:IsCanBeSkillTarget(e) end function scard.posop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOREST) local g1=Duel.SelectMatchingCard(tp,ds.BattleAreaFilter(scard.posfilter),tp,0,DS_LOCATION_BATTLE,0,2,nil,e) if g1:GetCount()>0 then Duel.SetTargetCard(g1) Duel.SwitchPosition(g1,DS_POS_FACEUP_REST) end Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_PLAY) local g2=Duel.SelectMatchingCard(tp,ds.DropAreaFilter(scard.plfilter2),tp,DS_LOCATION_DROP,0,1,1,nil,e) if g2:GetCount()==0 then return end Duel.SetTargetCard(g2) Duel.Play(g2,0,tp,tp,false,false,DS_POS_FACEUP_ACTIVE) end
gpl-3.0
MatthewDwyer/botman
mudlet/profiles/newbot/custom/customIRC.lua
1
1112
--[[ Botman - A collection of scripts for managing 7 Days to Die servers Copyright (C) 2019 Matthew Dwyer This copyright applies to the Lua source code in this Mudlet profile. Email smegzor@gmail.com URL http://botman.nz Source https://bitbucket.org/mhdwyer/botman --]] -- Coded something awesome? Consider sharing it :D -- function customIRC(name, words, wordsOld, msgLower, ircID) local status, row, cursor, errorString if (words[1] == "debug" and words[2] == "on") then server.enableWindowMessages = true irc_chat(name, "Debugging ON") return true end if (words[1] == "debug" and words[2] == "all") then server.enableWindowMessages = true botman.debugAll = true irc_chat(name, "Debugging ON") return true end if (words[1] == "debug" and words[2] == "off") then server.enableWindowMessages = false botman.debugAll = false irc_chat(name, "Debugging OFF") return true end if words[1] == "test" and words[2] == "command" then irc_chat(name, "Test Start") irc_chat(name, "Test End") return true end return false end
gpl-3.0
nasomi/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Loillie.lua
17
1608
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Loillie -- @zone 80 -- @pos 78 -8 -23 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then local mask = player:getVar("GiftsOfGriffonPlumes"); if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,6)) then player:startEvent(0x01D) -- Gifts of Griffon Trade end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0265); -- Default Dialogue end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x01D) then -- Gifts Of Griffon Trade player:tradeComplete(); local mask = player:getVar("GiftsOfGriffonPlumes"); player:setMaskBit(mask,"GiftsOfGriffonPlumes",6,true); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/effects/perfect_defense.lua
35
3155
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) print(target:getMod(MOD_UDMGMAGIC)); print(target:getMod(MOD_UDMGPHYS)); effect:setSubPower(effect:getPower()*(256/100)); target:addMod(MOD_UDMGPHYS, -effect:getPower()); target:addMod(MOD_UDMGBREATH, -effect:getPower()); target:addMod(MOD_UDMGMAGIC, -effect:getSubPower()); target:addMod(MOD_UDMGRANGE, -effect:getPower()); target:addMod(MOD_SLEEPRES, effect:getPower()); target:addMod(MOD_POISONRES, effect:getPower()); target:addMod(MOD_PARALYZERES, effect:getPower()); target:addMod(MOD_BLINDRES, effect:getPower()); target:addMod(MOD_SILENCERES, effect:getPower()); target:addMod(MOD_BINDRES, effect:getPower()); target:addMod(MOD_CURSERES, effect:getPower()); target:addMod(MOD_SLOWRES, effect:getPower()); target:addMod(MOD_STUNRES, effect:getPower()); target:addMod(MOD_CHARMRES, effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) if (effect:getTickCount() > ((effect:getDuration() / effect:getTick())/2)) then if (effect:getPower() > 2) then effect:setPower(effect:getPower() - 2); effect:setSubPower(effect:getSubPower() - 3); target:delMod(MOD_UDMGPHYS, -2); target:delMod(MOD_UDMGBREATH, -2); target:delMod(MOD_UDMGMAGIC, -3); target:delMod(MOD_UDMGRANGE, -2); target:delMod(MOD_SLEEPRES, 2); target:delMod(MOD_POISONRES, 2); target:delMod(MOD_PARALYZERES, 2); target:delMod(MOD_BLINDRES, 2); target:delMod(MOD_SILENCERES, 2); target:delMod(MOD_BINDRES, 2); target:delMod(MOD_CURSERES, 2); target:delMod(MOD_SLOWRES, 2); target:delMod(MOD_STUNRES, 2); target:delMod(MOD_CHARMRES, 2); end end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_UDMGPHYS, -effect:getPower()); target:delMod(MOD_UDMGBREATH, -effect:getPower()); target:delMod(MOD_UDMGMAGIC, -effect:getSubPower()); target:delMod(MOD_UDMGRANGE, -effect:getPower()); target:delMod(MOD_SLEEPRES, effect:getPower()); target:delMod(MOD_POISONRES, effect:getPower()); target:delMod(MOD_PARALYZERES, effect:getPower()); target:delMod(MOD_BLINDRES, effect:getPower()); target:delMod(MOD_SILENCERES, effect:getPower()); target:delMod(MOD_BINDRES, effect:getPower()); target:delMod(MOD_CURSERES, effect:getPower()); target:delMod(MOD_SLOWRES, effect:getPower()); target:delMod(MOD_STUNRES, effect:getPower()); target:delMod(MOD_CHARMRES, effect:getPower()); print(target:getMod(MOD_UDMGMAGIC)); print(target:getMod(MOD_UDMGPHYS)); end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27001100.lua
1
1248
--BT1-086 Golden Frieza, Resurrected Terror local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZAS_ARMY,CHARACTER_FRIEZA,SPECIAL_TRAIT_FRIEZA_CLAN) ds.AddPlayProcedure(c,COLOR_YELLOW,3,4) --evolve ds.EnableEvolve(c,aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_FRIEZA),COLOR_YELLOW,2,4) --triple strike ds.EnableTripleStrike(c) --to drop ds.AddSingleAutoPlay(c,0,nil,ds.hinttg,scard.tgop,DS_EFFECT_FLAG_CARD_CHOOSE,ds.evoplcon) end scard.dragon_ball_super_card=true scard.combo_cost=1 function scard.posfilter(c,e) return c:IsActive() and c:IsCanBeSkillTarget(e) end function scard.tgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local g1=Duel.GetMatchingGroup(ds.BattleAreaFilter(Card.IsRest),tp,DS_LOCATION_BATTLE,DS_LOCATION_BATTLE,c) Duel.SendtoDrop(g1,DS_REASON_SKILL) local g2=Duel.GetMatchingGroup(ds.BattleAreaFilter(scard.posfilter),tp,DS_LOCATION_BATTLE,DS_LOCATION_BATTLE,c,e) local ct=g2:GetCount() if ct==0 then return end Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOREST) local sg=g2:Select(tp,ct,ct,nil) Duel.SetTargetCard(sg) Duel.SwitchPosition(sg,DS_POS_FACEUP_REST) end
gpl-3.0
appaquet/torch-android
src/3rdparty/nnx/SpatialReSampling.lua
2
1789
local SpatialReSampling, parent = torch.class('nn.SpatialReSampling', 'nn.Module') local help_desc = [[Applies a 2D re-sampling over an input image composed of several input planes. The input tensor in forward(input) is expected to be a 3D or 4D tensor ([batchSize x nInputPlane x width x height). The number of output planes will be the same as the nb of input planes. The re-sampling is done using bilinear interpolation. For a simple nearest-neihbor upsampling, use nn.SpatialUpSampling(), and for a simple average-based down-sampling, use nn.SpatialDownSampling(). If the input image is a 3D tensor nInputPlane x height x width, the output image size will be nInputPlane x oheight x owidth where owidth and oheight are given to the constructor. Instead of owidth & oheight, one can provide rwidth & rheight, such that owidth = iwidth*rwidth & oheight = iheight*rheight. ]] function SpatialReSampling:__init(...) parent.__init(self) xlua.unpack_class( self, {...}, 'nn.SpatialReSampling', help_desc, {arg='rwidth', type='number', help='ratio: owidth/iwidth'}, {arg='rheight', type='number', help='ratio: oheight/iheight'}, {arg='owidth', type='number', help='output width'}, {arg='oheight', type='number', help='output height'} ) end function SpatialReSampling:updateOutput(input) local hDim, wDim = 2, 3 if input:dim() == 4 then hDim, wDim = 3, 4 end self.oheight = self.oheight or self.rheight*input:size(hDim) self.owidth = self.owidth or self.rwidth*input:size(wDim) input.nn.SpatialReSampling_updateOutput(self, input) return self.output end function SpatialReSampling:updateGradInput(input, gradOutput) input.nn.SpatialReSampling_updateGradInput(self, input, gradOutput) return self.gradInput end
bsd-3-clause
thesabbir/luci
applications/luci-app-asterisk/luasrc/asterisk.lua
68
17804
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.asterisk", package.seeall) require("luci.asterisk.cc_idd") local _io = require("io") local uci = require("luci.model.uci").cursor() local sys = require("luci.sys") local util = require("luci.util") AST_BIN = "/usr/sbin/asterisk" AST_FLAGS = "-r -x" --- LuCI Asterisk - Resync uci context function uci_resync() uci = luci.model.uci.cursor() end --- LuCI Asterisk io interface -- Handles low level io. -- @type module io = luci.util.class() --- Execute command and return output -- @param command String containing the command to execute -- @return String containing the command output function io.exec(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") local buffer = fh:read("*a") fh:close() return buffer end --- Execute command and invoke given callback for each readed line -- @param command String containing the command to execute -- @param callback Function to call back for each line -- @return Always true function io.execl(command, callback) local ln local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") repeat ln = fh:read("*l") callback(ln) until not ln fh:close() return true end --- Execute command and return an iterator that returns one line per invokation -- @param command String containing the command to execute -- @return Iterator function function io.execi(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") return function() local ln = fh:read("*l") if not ln then fh:close() end return ln end end --- LuCI Asterisk - core status core = luci.util.class() --- Retrive version string. -- @return String containing the reported asterisk version function core.version(self) local version = io.exec("core show version") return version:gsub(" *\n", "") end --- LuCI Asterisk - SIP information. -- @type module sip = luci.util.class() --- Get a list of known SIP peers -- @return Table containing each SIP peer function sip.peers(self) local head = false local peers = { } for line in io.execi("sip show peers") do if not head then head = true elseif not line:match(" sip peers ") then local online, delay, id, uid local name, host, dyn, nat, acl, port, status = line:match("(.-) +(.-) +([D ]) ([N ]) (.) (%d+) +(.+)") if host == '(Unspecified)' then host = nil end if port == '0' then port = nil else port = tonumber(port) end dyn = ( dyn == 'D' and true or false ) nat = ( nat == 'N' and true or false ) acl = ( acl ~= ' ' and true or false ) online, delay = status:match("(OK) %((%d+) ms%)") if online == 'OK' then online = true delay = tonumber(delay) elseif status ~= 'Unmonitored' then online = false delay = 0 else online = nil delay = 0 end id, uid = name:match("(.+)/(.+)") if not ( id and uid ) then id = name .. "..." uid = nil end peers[#peers+1] = { online = online, delay = delay, name = id, user = uid, dynamic = dyn, nat = nat, acl = acl, host = host, port = port } end end return peers end --- Get informations of given SIP peer -- @param peer String containing the name of the SIP peer function sip.peer(peer) local info = { } local keys = { } for line in io.execi("sip show peer " .. peer) do if #line > 0 then local key, val = line:match("(.-) *: +(.*)") if key and val then key = key:gsub("^ +",""):gsub(" +$", "") val = val:gsub("^ +",""):gsub(" +$", "") if key == "* Name" then key = "Name" elseif key == "Addr->IP" then info.address, info.port = val:match("(.+) Port (.+)") info.port = tonumber(info.port) elseif key == "Status" then info.online, info.delay = val:match("(OK) %((%d+) ms%)") if info.online == 'OK' then info.online = true info.delay = tonumber(info.delay) elseif status ~= 'Unmonitored' then info.online = false info.delay = 0 else info.online = nil info.delay = 0 end end if val == 'Yes' or val == 'yes' or val == '<Set>' then val = true elseif val == 'No' or val == 'no' then val = false elseif val == '<Not set>' or val == '(none)' then val = nil end keys[#keys+1] = key info[key] = val end end end return info, keys end --- LuCI Asterisk - Internal helpers -- @type module tools = luci.util.class() --- Convert given value to a list of tokens. Split by white space. -- @param val String or table value -- @return Table containing tokens function tools.parse_list(v) local tokens = { } v = type(v) == "table" and v or { v } for _, v in ipairs(v) do if type(v) == "string" then for v in v:gmatch("(%S+)") do tokens[#tokens+1] = v end end end return tokens end --- Convert given list to a collection of hyperlinks -- @param list Table of tokens -- @param url String pattern or callback function to construct urls (optional) -- @param sep String containing the seperator (optional, default is ", ") -- @return String containing the html fragment function tools.hyperlinks(list, url, sep) local html local function mkurl(p, t) if type(p) == "string" then return p:format(t) elseif type(p) == "function" then return p(t) else return '#' end end list = list or { } url = url or "%s" sep = sep or ", " for _, token in ipairs(list) do html = ( html and html .. sep or '' ) .. '<a href="%s">%s</a>' %{ mkurl(url, token), token } end return html or '' end --- LuCI Asterisk - International Direct Dialing Prefixes -- @type module idd = luci.util.class() --- Lookup the country name for the given IDD code. -- @param country String containing IDD code -- @return String containing the country name function idd.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return v[1] end end elseif v[3] == tostring(c) then return v[1] end end end --- Lookup the country code for the given IDD code. -- @param country String containing IDD code -- @return Table containing the country code(s) function idd.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end elseif v[3] == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Lookup the IDD code(s) for the given country. -- @param idd String containing the country name -- @return Table containing the IDD code(s) function idd.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Populate given CBI field with IDD codes. -- @param field CBI option object -- @return (nothing) function idd.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][3]) == "table" and cc_idd.CC_IDD[val][3] or { cc_idd.CC_IDD[val][3] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then if v[3][1] == val[1] then return "_%i" % i end else if v[3] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Country Code Prefixes -- @type module cc = luci.util.class() --- Lookup the country name for the given CC code. -- @param country String containing CC code -- @return String containing the country name function cc.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return v[1] end end elseif v[2] == tostring(c) then return v[1] end end end --- Lookup the international dialing code for the given CC code. -- @param cc String containing CC code -- @return String containing IDD code function cc.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end elseif v[2] == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Lookup the CC code(s) for the given country. -- @param country String containing the country name -- @return Table containing the CC code(s) function cc.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Populate given CBI field with CC codes. -- @param field CBI option object -- @return (nothing) function cc.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][2]) == "table" and cc_idd.CC_IDD[val][2] or { cc_idd.CC_IDD[val][2] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then if v[2][1] == val[1] then return "_%i" % i end else if v[2] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Dialzone -- @type module dialzone = luci.util.class() --- Parse a dialzone section -- @param zone Table containing the zone info -- @return Table with parsed information function dialzone.parse(z) if z['.name'] then return { trunks = tools.parse_list(z.uses), name = z['.name'], description = z.description or z['.name'], addprefix = z.addprefix, matches = tools.parse_list(z.match), intlmatches = tools.parse_list(z.international), countrycode = z.countrycode, localzone = z.localzone, localprefix = z.localprefix } end end --- Get a list of known dial zones -- @return Associative table of zones and table of zone names function dialzone.zones() local zones = { } local znames = { } uci:foreach("asterisk", "dialzone", function(z) zones[z['.name']] = dialzone.parse(z) znames[#znames+1] = z['.name'] end) return zones, znames end --- Get a specific dial zone -- @param name Name of the dial zone -- @return Table containing zone information function dialzone.zone(n) local zone uci:foreach("asterisk", "dialzone", function(z) if z['.name'] == n then zone = dialzone.parse(z) end end) return zone end --- Find uci section hash for given zone number -- @param idx Zone number -- @return String containing the uci hash pointing to the section function dialzone.ucisection(i) local hash local index = 1 i = tonumber(i) uci:foreach("asterisk", "dialzone", function(z) if not hash and index == i then hash = z['.name'] end index = index + 1 end) return hash end --- LuCI Asterisk - Voicemailbox -- @type module voicemail = luci.util.class() --- Parse a voicemail section -- @param zone Table containing the mailbox info -- @return Table with parsed information function voicemail.parse(z) if z.number and #z.number > 0 then local v = { id = '%s@%s' %{ z.number, z.context or 'default' }, number = z.number, context = z.context or 'default', name = z.name or z['.name'] or 'OpenWrt', zone = z.zone or 'homeloc', password = z.password or '0000', email = z.email or '', page = z.page or '', dialplans = { } } uci:foreach("asterisk", "dialplanvoice", function(s) if s.dialplan and #s.dialplan > 0 and s.voicebox == v.number then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known voicemail boxes -- @return Associative table of boxes and table of box numbers function voicemail.boxes() local vboxes = { } local vnames = { } uci:foreach("asterisk", "voicemail", function(z) local v = voicemail.parse(z) if v then local n = '%s@%s' %{ v.number, v.context } vboxes[n] = v vnames[#vnames+1] = n end end) return vboxes, vnames end --- Get a specific voicemailbox -- @param number Number of the voicemailbox -- @return Table containing mailbox information function voicemail.box(n) local box n = n:gsub("@.+$","") uci:foreach("asterisk", "voicemail", function(z) if z.number == tostring(n) then box = voicemail.parse(z) end end) return box end --- Find all voicemailboxes within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to mailbox info function voicemail.in_dialplan(p) local plan = type(p) == "string" and p or p.name local boxes = { } uci:foreach("asterisk", "dialplanvoice", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local box = voicemail.box(s.voicebox) if box then boxes[s.extension] = box end end end) return boxes end --- Remove voicemailbox and associated extensions from config -- @param box Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function voicemail.remove(v, ctx) ctx = ctx or uci local box = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "voicemail", {number=box}) local ok2 = ctx:delete_all("asterisk", "dialplanvoice", {voicebox=box}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - MeetMe Conferences -- @type module meetme = luci.util.class() --- Parse a meetme section -- @param room Table containing the room info -- @return Table with parsed information function meetme.parse(r) if r.room and #r.room > 0 then local v = { room = r.room, pin = r.pin or '', adminpin = r.adminpin or '', description = r._description or '', dialplans = { } } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.dialplan and #s.dialplan > 0 and s.room == v.room then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known meetme rooms -- @return Associative table of rooms and table of room numbers function meetme.rooms() local mrooms = { } local mnames = { } uci:foreach("asterisk", "meetme", function(r) local v = meetme.parse(r) if v then mrooms[v.room] = v mnames[#mnames+1] = v.room end end) return mrooms, mnames end --- Get a specific meetme room -- @param number Number of the room -- @return Table containing room information function meetme.room(n) local room uci:foreach("asterisk", "meetme", function(r) if r.room == tostring(n) then room = meetme.parse(r) end end) return room end --- Find all meetme rooms within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to room info function meetme.in_dialplan(p) local plan = type(p) == "string" and p or p.name local rooms = { } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local room = meetme.room(s.room) if room then rooms[s.extension] = room end end end) return rooms end --- Remove meetme room and associated extensions from config -- @param room Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function meetme.remove(v, ctx) ctx = ctx or uci local room = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "meetme", {room=room}) local ok2 = ctx:delete_all("asterisk", "dialplanmeetme", {room=room}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - Dialplan -- @type module dialplan = luci.util.class() --- Parse a dialplan section -- @param plan Table containing the plan info -- @return Table with parsed information function dialplan.parse(z) if z['.name'] then local plan = { zones = { }, name = z['.name'], description = z.description or z['.name'] } -- dialzones for _, name in ipairs(tools.parse_list(z.include)) do local zone = dialzone.zone(name) if zone then plan.zones[#plan.zones+1] = zone end end -- voicemailboxes plan.voicemailboxes = voicemail.in_dialplan(plan) -- meetme conferences plan.meetmerooms = meetme.in_dialplan(plan) return plan end end --- Get a list of known dial plans -- @return Associative table of plans and table of plan names function dialplan.plans() local plans = { } local pnames = { } uci:foreach("asterisk", "dialplan", function(p) plans[p['.name']] = dialplan.parse(p) pnames[#pnames+1] = p['.name'] end) return plans, pnames end --- Get a specific dial plan -- @param name Name of the dial plan -- @return Table containing plan information function dialplan.plan(n) local plan uci:foreach("asterisk", "dialplan", function(p) if p['.name'] == n then plan = dialplan.parse(p) end end) return plan end
apache-2.0
nasomi/darkstar
scripts/zones/Middle_Delkfutts_Tower/TextIDs.lua
9
1147
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6542; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6547; -- Obtained: <item>. GIL_OBTAINED = 6548; -- Obtained <number> gil. KEYITEM_OBTAINED = 6550; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7206; -- You can't fish here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7308; -- You unlock the chest! CHEST_FAIL = 7309; -- Fails to open the chest. CHEST_TRAP = 7310; -- The chest was trapped! CHEST_WEAK = 7311; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7312; -- The chest was a mimic! CHEST_MOOGLE = 7313; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7314; -- The chest was but an illusion... CHEST_LOCKED = 7315; -- The chest appears to be locked. -- Quest dialog NOTHING_OUT_OF_ORDINARY = 6561; -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6562; -- You are suddenly overcome with a sense of foreboding... -- conquest Base CONQUEST_BASE = 4;
gpl-3.0